add stb_ds.h and tests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sean Barrett · committed by Sean Barrett · parent aeec66c · Browse files · 3 files·+2063 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+2063 added−0 removed
- tests:+437 added−0 removed
- other:+1626 added−0 removed
Provenance
- Commit
477471d- Tree
e3f6fff- Author
Sean Barrett <sean@nothings.org>- Committer
Sean Barrett <sean@nothings.org>- Parent
aeec66c
3 files changed+2063 added−0 removed
added:tests/test_ds.c+416 added
1+#include <stdio.h>2+3+#ifdef DS_TEST4+#define STBDS_UNIT_TESTS5+#endif6+7+#ifdef DS_STATS8+#define STBDS_STATISTICS9+#endif10+11+#ifndef DS_PERF12+#define STBDS_ASSERT assert13+#include <assert.h>14+#endif15+16+//#define STBDS_SIPHASH_2_417+#define STB_DS_IMPLEMENTATION18+#include "../stb_ds.h"19+20+size_t churn_inserts, churn_deletes;21+22+void churn(int a, int b, int count)23+{24+ struct { int key,value; } *map=NULL;25+ int i,j,n,k;26+ for (i=0; i < a; ++i)27+ hmput(map,i,i+1);28+ for (n=0; n < count; ++n) {29+ for (j=a; j < b; ++j,++i) {30+ hmput(map,i,i+1);31+ }32+ assert(hmlen(map) == b);33+ for (j=a; j < b; ++j) {34+ k=i-j-1;35+ k = hmdel(map,k);36+ assert(k != 0);37+ }38+ assert(hmlen(map) == a);39+ }40+ hmfree(map);41+ churn_inserts = i;42+ churn_deletes = (b-a) * n;43+}44+45+#ifdef DS_TEST46+int main(int argc, char **argv)47+{48+ stbds_unit_tests();49+ churn(0,100,1);50+ churn(3,7,50000);51+ churn(3,15,50000);52+ churn(16, 48, 25000);53+ churn(10, 15, 25000);54+ churn(200,500, 5000);55+ churn(2000,5000, 500);56+ churn(20000,50000, 50);57+ return 0;58+}59+#endif60+61+#ifdef DS_STATS62+#define MAX(a,b) ((a) > (b) ? (a) : (b))63+size_t max_hit_probes, max_miss_probes, total_put_probes, total_miss_probes, churn_misses;64+void churn_stats(int a, int b, int count)65+{66+ struct { int key,value; } *map=NULL;67+ int i,j,n,k;68+ churn_misses = 0;69+ for (i=0; i < a; ++i) {70+ hmput(map,i,i+1);71+ max_hit_probes = MAX(max_hit_probes, stbds_hash_probes);72+ total_put_probes += stbds_hash_probes;73+ stbds_hash_probes = 0;74+ }75+ 76+ for (n=0; n < count; ++n) {77+ for (j=a; j < b; ++j,++i) {78+ hmput(map,i,i+1);79+ max_hit_probes = MAX(max_hit_probes, stbds_hash_probes);80+ total_put_probes += stbds_hash_probes;81+ stbds_hash_probes = 0;82+ }83+ for (j=0; j < (b-a)*10; ++j) {84+ k=i+j;85+ (void) hmgeti(map,k); // miss86+ max_miss_probes = MAX(max_miss_probes, stbds_hash_probes);87+ total_miss_probes += stbds_hash_probes;88+ stbds_hash_probes = 0;89+ ++churn_misses;90+ }91+ assert(hmlen(map) == b);92+ for (j=a; j < b; ++j) {93+ k=i-j-1;94+ k = hmdel(map,k);95+ stbds_hash_probes = 0;96+ assert(k);97+ }98+ assert(hmlen(map) == a);99+ }100+ hmfree(map);101+ churn_inserts = i;102+ churn_deletes = (b-a) * n;103+}104+105+void reset_stats(void)106+{107+ stbds_array_grow=0, 108+ stbds_hash_grow=0;109+ stbds_hash_shrink=0;110+ stbds_hash_rebuild=0;111+ stbds_hash_probes=0;112+ stbds_hash_alloc=0;113+ stbds_rehash_probes=0;114+ stbds_rehash_items=0;115+ max_hit_probes = 0;116+ max_miss_probes = 0;117+ total_put_probes = 0;118+ total_miss_probes = 0;119+}120+121+void print_churn_probe_stats(char *str)122+{123+ printf("Probes: %3d max hit, %3d max miss, %4.2f avg hit, %4.2f avg miss: %s\n",124+ (int) max_hit_probes, (int) max_miss_probes, (float) total_put_probes / churn_inserts, (float) total_miss_probes / churn_misses, str);125+ reset_stats();126+}127+128+int main(int arg, char **argv)129+{130+ churn_stats(0,500000,1); print_churn_probe_stats("Inserting 500000 items");131+ churn_stats(0,500000,1); print_churn_probe_stats("Inserting 500000 items");132+ churn_stats(0,500000,1); print_churn_probe_stats("Inserting 500000 items");133+ churn_stats(0,500000,1); print_churn_probe_stats("Inserting 500000 items");134+ churn_stats(49000,50000,500); print_churn_probe_stats("Deleting/Inserting 500000 items");135+ churn_stats(49000,50000,500); print_churn_probe_stats("Deleting/Inserting 500000 items");136+ churn_stats(49000,50000,500); print_churn_probe_stats("Deleting/Inserting 500000 items");137+ churn_stats(49000,50000,500); print_churn_probe_stats("Deleting/Inserting 500000 items");138+ return 0;139+}140+#endif141+142+#ifdef DS_PERF143+#define WIN32_LEAN_AND_MEAN144+#include <windows.h>145+#define STB_DEFINE146+#define STB_NO_REGISTRY147+//#include "../stb.h"148+149+150+size_t t0, sum, mn,mx,count;151+void begin(void)152+{153+ size_t t0;154+ LARGE_INTEGER m;155+ QueryPerformanceCounter(&m);156+ t0 = m.QuadPart;157+ sum = 0;158+ count = 0;159+ mx = 0;160+ mn = ~(size_t) 0;161+}162+163+void measure(void)164+{165+ size_t t1, t;166+ LARGE_INTEGER m;167+ QueryPerformanceCounter(&m);168+ t1 = m.QuadPart;169+ t = t1-t0;170+ if (t1 < t0)171+ printf("ALERT: QueryPerformanceCounter was unordered!\n");172+ if (t < mn) mn = t;173+ if (t > mx) mx = t;174+ sum += t;175+ ++count;176+ t0 = t1;177+}178+179+void dont_measure(void)180+{181+ size_t t1, t;182+ LARGE_INTEGER m;183+ QueryPerformanceCounter(&m);184+ t0 = m.QuadPart;185+}186+187+double timer;188+void end(void)189+{190+ LARGE_INTEGER m;191+ QueryPerformanceFrequency(&m);192+193+ if (count > 3) {194+ // discard the highest and lowest195+ sum -= mn;196+ sum -= mx;197+ count -= 2;198+ }199+ timer = (double) (sum) / count / m.QuadPart * 1000;200+}201+202+void build(int a, int b, int count, int step)203+{204+ struct { int key,value; } *map=NULL;205+ int i,j,n,k;206+ for (i=0; i < a; ++i)207+ hmput(map,i*step,i+1);208+ measure();209+ churn_inserts = i;210+ hmfree(map);211+ dont_measure();212+}213+214+#ifdef STB__INCLUDE_STB_H215+void build_stb(int a, int b, int count, int step)216+{217+ stb_idict *d = stb_idict_new_size(8);218+ struct { int key,value; } *map=NULL;219+ int i,j,n,k;220+ for (i=0; i < a; ++i)221+ stb_idict_add(d, i*step, i+1);222+ measure();223+ churn_inserts = i;224+ stb_idict_destroy(d);225+ dont_measure();226+}227+#endif228+229+void churn_skip(unsigned int a, unsigned int b, int count)230+{231+ struct { unsigned int key,value; } *map=NULL;232+ unsigned int i,j,n,k;233+ for (i=0; i < a; ++i)234+ hmput(map,i,i+1);235+ dont_measure();236+ for (n=0; n < count; ++n) {237+ for (j=a; j < b; ++j,++i) {238+ hmput(map,i,i+1);239+ }240+ assert(hmlen(map) == b);241+ for (j=a; j < b; ++j) {242+ k=i-j-1;243+ k = hmdel(map,k);244+ assert(k != 0);245+ }246+ assert(hmlen(map) == a);247+ }248+ measure();249+ churn_inserts = i;250+ churn_deletes = (b-a) * n;251+ hmfree(map);252+ dont_measure();253+}254+255+typedef struct { int n[8]; } str32;256+void churn32(int a, int b, int count, int include_startup)257+{258+ struct { str32 key; int value; } *map=NULL;259+ int i,j,n;260+ str32 key = { 0 };261+ for (i=0; i < a; ++i) {262+ key.n[0] = i;263+ hmput(map,key,i+1);264+ }265+ if (!include_startup)266+ dont_measure();267+ for (n=0; n < count; ++n) {268+ for (j=a; j < b; ++j,++i) {269+ key.n[0] = i;270+ hmput(map,key,i+1);271+ }272+ assert(hmlen(map) == b);273+ for (j=a; j < b; ++j) {274+ key.n[0] = i-j-1;275+ hmdel(map,key);276+ }277+ assert(hmlen(map) == a);278+ }279+ measure();280+ hmfree(map);281+ churn_inserts = i;282+ churn_deletes = (b-a) * n;283+ dont_measure();284+}285+286+typedef struct { int n[32]; } str256;287+void churn256(int a, int b, int count, int include_startup)288+{289+ struct { str256 key; int value; } *map=NULL;290+ int i,j,n;291+ str256 key = { 0 };292+ for (i=0; i < a; ++i) {293+ key.n[0] = i;294+ hmput(map,key,i+1);295+ }296+ if (!include_startup)297+ dont_measure();298+ for (n=0; n < count; ++n) {299+ for (j=a; j < b; ++j,++i) {300+ key.n[0] = i;301+ hmput(map,key,i+1);302+ }303+ assert(hmlen(map) == b);304+ for (j=a; j < b; ++j) {305+ key.n[0] = i-j-1;306+ hmdel(map,key);307+ }308+ assert(hmlen(map) == a);309+ }310+ measure();311+ hmfree(map);312+ churn_inserts = i;313+ churn_deletes = (b-a) * n;314+ dont_measure();315+}316+317+void churn8(int a, int b, int count, int include_startup)318+{319+ struct { size_t key,value; } *map=NULL;320+ int i,j,n,k;321+ for (i=0; i < a; ++i)322+ hmput(map,i,i+1);323+ if (!include_startup)324+ dont_measure();325+ for (n=0; n < count; ++n) {326+ for (j=a; j < b; ++j,++i) {327+ hmput(map,i,i+1);328+ }329+ assert(hmlen(map) == b);330+ for (j=a; j < b; ++j) {331+ k=i-j-1;332+ k = hmdel(map,k);333+ assert(k != 0);334+ }335+ assert(hmlen(map) == a);336+ }337+ measure();338+ hmfree(map);339+ churn_inserts = i;340+ churn_deletes = (b-a) * n;341+ dont_measure();342+}343+344+345+int main(int arg, char **argv)346+{347+ int n,s,w;348+ double worst = 0;349+350+#if 0351+ begin(); for (n=0; n < 2000; ++n) { build_stb(2000,0,0,1); } end(); printf(" // %7.2fms : 2,000 inserts creating 2K table\n", timer);352+ begin(); for (n=0; n < 500; ++n) { build_stb(20000,0,0,1); } end(); printf(" // %7.2fms : 20,000 inserts creating 20K table\n", timer);353+ begin(); for (n=0; n < 100; ++n) { build_stb(200000,0,0,1); } end(); printf(" // %7.2fms : 200,000 inserts creating 200K table\n", timer);354+ begin(); for (n=0; n < 10; ++n) { build_stb(2000000,0,0,1); } end(); printf(" // %7.2fms : 2,000,000 inserts creating 2M table\n", timer);355+ begin(); for (n=0; n < 5; ++n) { build_stb(20000000,0,0,1); } end(); printf(" // %7.2fms : 20,000,000 inserts creating 20M table\n", timer);356+#endif357+358+ begin(); for (n=0; n < 2000; ++n) { churn8(2000,0,0,1); } end(); printf(" // %7.2fms : 2,000 inserts creating 2K table w/ 8-byte key\n", timer);359+ begin(); for (n=0; n < 500; ++n) { churn8(20000,0,0,1); } end(); printf(" // %7.2fms : 20,000 inserts creating 20K table w/ 8-byte key\n", timer);360+ begin(); for (n=0; n < 100; ++n) { churn8(200000,0,0,1); } end(); printf(" // %7.2fms : 200,000 inserts creating 200K table w/ 8-byte key\n", timer);361+ begin(); for (n=0; n < 10; ++n) { churn8(2000000,0,0,1); } end(); printf(" // %7.2fms : 2,000,000 inserts creating 2M table w/ 8-byte key\n", timer);362+ begin(); for (n=0; n < 5; ++n) { churn8(20000000,0,0,1); } end(); printf(" // %7.2fms : 20,000,000 inserts creating 20M table w/ 8-byte key\n", timer);363+364+#if 0365+ begin(); for (n=0; n < 2000; ++n) { churn32(2000,0,0,1); } end(); printf(" // %7.2fms : 2,000 inserts creating 2K table w/ 32-byte key\n", timer);366+ begin(); for (n=0; n < 500; ++n) { churn32(20000,0,0,1); } end(); printf(" // %7.2fms : 20,000 inserts creating 20K table w/ 32-byte key\n", timer);367+ begin(); for (n=0; n < 100; ++n) { churn32(200000,0,0,1); } end(); printf(" // %7.2fms : 200,000 inserts creating 200K table w/ 32-byte key\n", timer);368+ begin(); for (n=0; n < 10; ++n) { churn32(2000000,0,0,1); } end(); printf(" // %7.2fms : 2,000,000 inserts creating 2M table w/ 32-byte key\n", timer);369+ begin(); for (n=0; n < 5; ++n) { churn32(20000000,0,0,1); } end(); printf(" // %7.2fms : 20,000,000 inserts creating 20M table w/ 32-byte key\n", timer);370+371+ begin(); for (n=0; n < 2000; ++n) { churn256(2000,0,0,1); } end(); printf(" // %7.2fms : 2,000 inserts creating 2K table w/ 256-byte key\n", timer);372+ begin(); for (n=0; n < 500; ++n) { churn256(20000,0,0,1); } end(); printf(" // %7.2fms : 20,000 inserts creating 20K table w/ 256-byte key\n", timer);373+ begin(); for (n=0; n < 100; ++n) { churn256(200000,0,0,1); } end(); printf(" // %7.2fms : 200,000 inserts creating 200K table w/ 256-byte key\n", timer);374+ begin(); for (n=0; n < 10; ++n) { churn256(2000000,0,0,1); } end(); printf(" // %7.2fms : 2,000,000 inserts creating 2M table w/ 256-byte key\n", timer);375+ begin(); for (n=0; n < 5; ++n) { churn256(20000000,0,0,1); } end(); printf(" // %7.2fms : 20,000,000 inserts creating 20M table w/ 256-byte key\n", timer);376+#endif377+378+ begin(); for (n=0; n < 2000; ++n) { build(2000,0,0,1); } end(); printf(" // %7.2fms : 2,000 inserts creating 2K table w/ 4-byte key\n", timer);379+ begin(); for (n=0; n < 500; ++n) { build(20000,0,0,1); } end(); printf(" // %7.2fms : 20,000 inserts creating 20K table w/ 4-byte key\n", timer);380+ begin(); for (n=0; n < 100; ++n) { build(200000,0,0,1); } end(); printf(" // %7.2fms : 200,000 inserts creating 200K table w/ 4-byte key\n", timer);381+ begin(); for (n=0; n < 10; ++n) { build(2000000,0,0,1); } end(); printf(" // %7.2fms : 2,000,000 inserts creating 2M table w/ 4-byte key\n", timer);382+ begin(); for (n=0; n < 5; ++n) { build(20000000,0,0,1); } end(); printf(" // %7.2fms : 20,000,000 inserts creating 20M table w/ 4-byte key\n", timer);383+384+ begin(); for (n=0; n < 60; ++n) { churn_skip(2000,2100,5000); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 2K table\n", timer);385+ begin(); for (n=0; n < 30; ++n) { churn_skip(20000,21000,500); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 20K table\n", timer);386+ begin(); for (n=0; n < 15; ++n) { churn_skip(200000,201000,500); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 200K table\n", timer);387+ begin(); for (n=0; n < 8; ++n) { churn_skip(2000000,2001000,500); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 2M table\n", timer);388+ begin(); for (n=0; n < 5; ++n) { churn_skip(20000000,20001000,500); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 20M table\n", timer);389+ begin(); for (n=0; n < 1; ++n) { churn_skip(200000000u,200001000u,500); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 200M table\n", timer);390+ // even though the above measures a roughly fixed amount of work, we still have to build the table n times, hence the fewer measurements each time391+392+ begin(); for (n=0; n < 60; ++n) { churn_skip(1000,3000,250); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 2K table\n", timer);393+ begin(); for (n=0; n < 15; ++n) { churn_skip(10000,30000,25); } end(); printf(" // %7.2fms : 500,000 inserts & deletes in 20K table\n", timer);394+ begin(); for (n=0; n < 7; ++n) { churn_skip(100000,300000,10); } end(); printf(" // %7.2fms : 2,000,000 inserts & deletes in 200K table\n", timer);395+ begin(); for (n=0; n < 2; ++n) { churn_skip(1000000,3000000,10); } end(); printf(" // %7.2fms : 20,000,000 inserts & deletes in 2M table\n", timer);396+397+ // search for bad intervals.. in practice this just seems to measure execution variance398+ for (s = 2; s < 64; ++s) {399+ begin(); for (n=0; n < 50; ++n) { build(200000,0,0,s); } end();400+ if (timer > worst) {401+ worst = timer;402+ w = s;403+ }404+ }405+ for (; s <= 1024; s *= 2) {406+ begin(); for (n=0; n < 50; ++n) { build(200000,0,0,s); } end();407+ if (timer > worst) {408+ worst = timer;409+ w = s;410+ }411+ }412+ printf(" // %7.2fms(%d) : Worst time from inserting 200,000 items with spacing %d.\n", worst, w, w);413+414+ return 0;415+}416+#endifadded:tests/test_siphash.c+21 added
1+#include <stdio.h>2+3+#define STB_DS_IMPLEMENTATION4+#define STBDS_SIPHASH_2_45+#define STBDS_TEST_SIPHASH_2_46+#include "../stb_ds.h"7+8+int main(int argc, char **argv)9+{10+ unsigned char mem[64];11+ int i,j;12+ for (i=0; i < 64; ++i) mem[i] = i;13+ for (i=0; i < 64; ++i) {14+ size_t hash = stbds_hash_bytes(mem, i, 0);15+ printf(" { ");16+ for (j=0; j < 8; ++j)17+ printf("0x%02x, ", (unsigned char) ((hash >> (j*8)) & 255));18+ printf(" },\n");19+ }20+ return 0;21+}added:stb_ds.h+1626 added
1+/* stb_ds.h - v0.2 - public domain data structures - Sean Barrett 20192+ 3+ This is a single-header-file library that provides easy-to-use4+ dynamic arrays and hash tables for C (also works in C++).5+6+ For a gentle introduction:7+ http://nothings.org/stb_ds8+9+ To use this library, do this in *one* C or C++ file:10+ #define STB_DS_IMPLEMENTATION11+ #include "stb_ds.h"12+13+TABLE OF CONTENTS14+15+ Table of Contents16+ Compile-time options17+ License18+ Documentation19+ Notes20+ Notes - Dynamic arrays21+ Notes - Hash maps22+ Credits23+24+COMPILE-TIME OPTIONS25+26+ #define STBDS_NO_SHORT_NAMES27+28+ This flag needs to be set globally.29+ 30+ By default stb_ds exposes shorter function names that are not qualified31+ with the "stbds_" prefix. If these names conflict with the names in your32+ code, define this flag.33+34+ #define STBDS_SIPHASH_2_435+36+ This flag only needs to be set in the file containing #define STB_DS_IMPLEMENTATION.37+38+ By default stb_ds.h hashes using a weaker variant of SipHash and a custom hash for39+ 4- and 8-byte keys. On 64-bit platforms, you can define the above flag to force40+ stb_ds.h to use specification-compliant SipHash-2-4 for all keys. Doing so makes41+ hash table insertion about 20% slower on 4- and 8-byte keys, 5% slower on42+ 64-byte keys, and 10% slower on 256-byte keys on my test computer.43+44+LICENSE45+46+ Placed in the public domain and also MIT licensed.47+ See end of file for detailed license information.48+49+DOCUMENTATION50+51+ Dynamic Arrays52+53+ Non-function interface:54+55+ Declare an empty dynamic array of type T56+ T* foo = NULL; 57+58+ Access the i'th item of a dynamic array 'foo' of type T, T* foo:59+ foo[i]60+61+ Functions (actually macros)62+63+ arrfree:64+ void arrfree(T*);65+ Frees the array.66+67+ arrlen:68+ ptrdiff_t arrlen(T*);69+ Returns the number of elements in the array.70+71+ arrlenu:72+ size_t arrlenu(T*);73+ Returns the number of elements in the array as an unsigned type.74+75+ arrput:76+ T arrput(T* a, T b);77+ Appends the item b to the end of array a. Returns b.78+79+ arrins:80+ T arrins(T* a, int p, T b);81+ Inserts the item b into the middle of array a, into a[p],82+ moving the rest of the array over. Returns b.83+84+ arrinsn:85+ void arrins(T* a, int p, int n);86+ Inserts n uninitialized items into array a starting at a[p],87+ moving the rest of the array over.88+89+ arrdel:90+ void arrdel(T* a, int p);91+ Deletes the element at a[p], moving the rest of the array over.92+93+ arrdeln:94+ void arrdel(T* a, int p, int n);95+ Deletes n elements starting at a[p], moving the rest of the array over.96+97+ arrdelswap:98+ void arrdelswap(T* a, int p);99+ Deletes the element at a[p], replacing it with the element from100+ the end of the array. O(1) performance.101+102+ arrsetlen:103+ void arrsetlen(T* a, int n);104+ Changes the length of the array to n. Allocates uninitialized105+ slots at the end if necessary.106+107+ arrsetcap:108+ size_t arrsetcap(T* a, int n);109+ Sets the length of allocated storage to at least n. It will not110+ change the length of the array.111+112+ arrcap:113+ size_t arrcap(T* a);114+ Returns the number of total elements the array can contain without115+ needing to be reallocated.116+117+ Hash maps & String hash maps118+119+ Given T is a structure type: struct { TK key; TV value; }. Note that some120+ functions do not require TV value and can have other fields. For string121+ hash maps, TK must be 'char *'.122+123+ Special interface:124+125+ stbds_rand_seed:126+ void stbds_rand_seed(size_t seed);127+ For security against adversarially chosen data, you should seed the128+ library with a strong random number. Or at least seed it with time().129+130+ stbds_hash_string:131+ size_t stbds_hash_string(char *str, size_t seed);132+ Returns a hash value for a string.133+134+ stbds_hash_bytes:135+ size_t stbds_hash_bytes(void *p, size_t len, size_t seed);136+ These functions hash an arbitrary number of bytes. The function137+ uses a custom hash for 4- and 8-byte data, and a weakened version138+ of SipHash for everything else. On 64-bit platforms you can get139+ specification-compliant SipHash-2-4 on all data by defining140+ STBDS_SIPHASH_2_4, at a significant cost in speed.141+142+ Non-function interface:143+144+ Declare an empty hash map of type T145+ T* foo = NULL;146+147+ Access the i'th entry in a hash table T* foo:148+ foo[i]149+150+ Function interface (actually macros):151+152+ hmfree153+ shfree154+ void hmfree(T*);155+ void shfree(T*);156+ Frees the hashmap and sets the pointer to NULL.157+158+ hmlen159+ shlen160+ ptrdiff_t hmlen(T*)161+ ptrdiff_t shlen(T*)162+ Returns the number of elements in the hashmap.163+164+ hmlenu165+ shlenu166+ size_t hmlenu(T*)167+ size_t shlenu(T*)168+ Returns the number of elements in the hashmap.169+170+ hmgeti171+ shgeti172+ ptrdiff_t hmgeti(T*, TK key)173+ ptrdiff_t shgeti(T*, char* key)174+ Returns the index in the hashmap which has the key 'key', or -1175+ if the key is not present.176+177+ hmget178+ shget179+ TV hmget(T*, TK key)180+ TV shget(T*, char* key)181+ Returns the value corresponding to 'key' in the hashmap.182+ The structure must have a 'value' field183+184+ hmgets185+ shgets186+ T hmgets(T*, TK key)187+ T shgets(T*, char* key)188+ Returns the structure corresponding to 'key' in the hashmap.189+190+ hmdefault191+ shdefault192+ TV hmdefault(T*, TV value)193+ TV shdefault(T*, TV value)194+ Sets the default value for the hashmap, the value which will be195+ returned by hmget/shget if the key is not present.196+197+ hmdefaults198+ shdefaults199+ TV hmdefaults(T*, T item)200+ TV shdefaults(T*, T item)201+ Sets the default struct for the hashmap, the contents which will be202+ returned by hmgets/shgets if the key is not present.203+204+ hmput205+ shput206+ TV hmput(T*, TK key, TV value)207+ TV shput(T*, char* key, TV value)208+ Inserts a <key,value> pair into the hashmap. If the key is already209+ present in the hashmap, updates its value.210+211+ hmputs212+ shputs213+ T hmputs(T*, T item)214+ T shputs(T*, T item)215+ Returns the structure corresponding to 'key' in the hashmap.216+217+ hmdel218+ shdel219+ int hmdel(T*, TK key)220+ int shdel(T*, char* key)221+ If 'key' is in the hashmap, deletes its entry and returns 1.222+ Otherwise returns 0.223+224+ Function interface (actually macros) for strings only:225+226+ sh_new_strdup227+ void sh_new_strdup(T*);228+ Overwrites the existing pointer with a newly allocated229+ string hashmap which will automatically allocate and free230+ each string key using malloc/free231+232+ sh_new_arena233+ void sh_new_arena(T*);234+ Overwrites the existing pointer with a newly allocated235+ string hashmap which will automatically allocate each string236+ key to a string arena. Every string key ever used by this237+ hash table remains in the arena until the arena is freed.238+ Additionally, any key which is deleted and reinserted will239+ be allocated multiple times in the string arena.240+241+NOTES242+243+ * These data structures are realloc'd when they grow, and the macro "functions"244+ write to the provided pointer. This means: (a) the pointer must be an lvalue,245+ and (b) the pointer to the data structure is not stable, and you must maintain246+ it the same as you would a realloc'd pointer. For example, if you pass a pointer247+ to a dynamic array to a function which updates it, the function must return248+ back the new pointer to the caller. This is the price of trying to do this in C.249+250+ * You iterate over the contents of a dynamic array and a hashmap in exactly251+ the same way, using arrlen/hmlen/shlen:252+253+ for (i=0; i < arrlen(foo); ++i)254+ ... foo[i] ...255+256+ * All operations except arrins/arrdel are O(1) amortized, but individual257+ operations can be slow, so these data structures may not be suitable258+ for real time use. Dynamic arrays double in capacity as needed, so259+ elements are copied an average of once. Hash tables double/halve260+ their size as needed, with appropriate hysteresis to maintain O(1)261+ performance.262+263+NOTES - DYNAMIC ARRAY264+265+ * If you know how long a dynamic array is going to be in advance, you can avoid266+ extra memory allocations by using arrsetlen to allocate it to that length in267+ advance and use foo[n] while filling it out, or arrsetcap to allocate the memory268+ for that length and use arrput/arrpush as normal.269+270+ * Unlike some other versions of the dynamic array, this version should271+ be safe to use with strict-aliasing optimizations.272+273+NOTES - HASH MAP274+275+ * For compilers other than GCC and clang (e.g. Visual Studio), for hmput/hmget/hmdel276+ and variants, the key must be an lvalue (so the macro can take the address of it).277+ For GCC and clang, extensions are used that eliminate this requirement if you're278+ using C99 and later or using C++.279+280+ * To test for presence of a key in a hashmap, just do 'hmget(foo,key) >= 0'.281+282+ * The iteration order of your data in the hashmap is determined solely by the283+ order of insertions and deletions. In particular, if you never delete, new284+ keys are always added at the end of the array. This will be consistent285+ across all platforms and versions of the library. However, you should not286+ attempt to serialize the internal hash table, as the hash is not consistent287+ between different platforms, and may change with future versions of the library.288+289+ * Use sh_new_arena() for string hashmaps that you never delete from. Initialize290+ with NULL if you're managing the memory for your strings, or your strings are291+ never freed (at least until the hashmap is freed). Otherwise, use sh_new_strdup().292+ @TODO: make an arena variant that garbage collects the strings with a trivial293+ copy collector into a new arena whenever the table shrinks / rebuilds. Since294+ current arena recommendation is to only use arena if it never deletes, then295+ this can just replace current arena implementation.296+297+ * If adversarial input is a serious concern and you're on a 64-bit platform,298+ enable STBDS_SIPHASH_2_4 (see the 'Compile-time options' section), and pass299+ a strong random number to stbds_rand_seed.300+ 301+ * The default value for the hash table is stored in foo[-1], so if you302+ use code like 'hmget(T,k)->value = 5' you can overwrite the value303+ stored by hmdefault if 'k' is not present.304+305+CREDITS306+307+ Sean Barrett -- library, idea for dynamic array API/implementation308+ Per Vognsen -- idea for hash table API/implementation309+*/310+311+#ifndef INCLUDE_STB_DS_H312+#define INCLUDE_STB_DS_H313+314+#include <stdlib.h>315+#include <stddef.h>316+#include <string.h>317+318+#ifndef STBDS_NO_SHORT_NAMES319+#define arrlen stbds_arrlen320+#define arrlenu stbds_arrlenu321+#define arrput stbds_arrput322+#define arrpush stbds_arrput323+#define arrfree stbds_arrfree324+#define arraddn stbds_arraddn325+#define arrsetlen stbds_arrsetlen326+#define arrlast stbds_arrlast327+#define arrins stbds_arrins328+#define arrinsn stbds_arrinsn329+#define arrdel stbds_arrdel330+#define arrdeln stbds_arrdeln331+#define arrdelswap stbds_arrdelswap332+#define arrcap stbds_arrcap333+#define arrsetcap stbds_arrsetcap334+335+#define hmput stbds_hmput336+#define hmputs stbds_hmputs337+#define hmget stbds_hmget338+#define hmgets stbds_hmgets339+#define hmgetp stbds_hmgetp340+#define hmgeti stbds_hmgeti341+#define hmdel stbds_hmdel342+#define hmlen stbds_hmlen343+#define hmlenu stbds_hmlenu344+#define hmfree stbds_hmfree345+#define hmdefault stbds_hmdefault346+#define hmdefaults stbds_hmdefaults347+348+#define shput stbds_shput349+#define shputs stbds_shputs350+#define shget stbds_shget351+#define shgets stbds_shgets352+#define shgetp stbds_shgetp353+#define shgeti stbds_shgeti354+#define shdel stbds_shdel355+#define shlen stbds_shlen356+#define shlenu stbds_shlenu357+#define shfree stbds_shfree358+#define shdefault stbds_shdefault359+#define shdefaults stbds_shdefaults360+#define sh_new_arena stbds_sh_new_arena361+#define sh_new_strdup stbds_sh_new_strdup362+363+#define stralloc stbds_stralloc364+#define strreset stbds_strreset365+#endif 366+#ifdef __cplusplus367+extern "C" {368+#endif369+370+// for security against attackers, seed the library with a random number, at least time() but stronger is better371+extern void stbds_rand_seed(size_t seed);372+373+// these are the hash functions used internally if you want to test them or use them for other purposes374+extern size_t stbds_hash_bytes(void *p, size_t len, size_t seed);375+extern size_t stbds_hash_string(char *str, size_t seed);376+377+// this is a simple string arena allocator, initialize with e.g. 'stbds_string_arena my_arena={0}'.378+typedef struct stbds_string_arena stbds_string_arena;379+extern char * stbds_stralloc(stbds_string_arena *a, char *str);380+extern void stbds_strreset(stbds_string_arena *a);381+382+// have to #define STBDS_UNIT_TESTS to call this383+extern void stbds_unit_tests(void);384+385+///////////////386+//387+// Everything below here is implementation details388+//389+390+extern void * stbds_arrgrowf(void *a, size_t elemsize, size_t addlen, size_t min_cap);391+extern void stbds_hmfree_func(void *p, size_t elemsize, size_t keyoff);392+extern void * stbds_hmget_key(void *a, size_t elemsize, void *key, size_t keysize, int mode);393+extern void * stbds_hmput_default(void *a, size_t elemsize);394+extern void * stbds_hmput_key(void *a, size_t elemsize, void *key, size_t keysize, int mode);395+extern void * stbds_hmdel_key(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode);396+extern void * stbds_shmode_func(size_t elemsize, int mode);397+398+#ifdef __cplusplus399+}400+#endif401+402+#if defined(__GNUC__) || defined(__clang__)403+#define STBDS_HAS_TYPEOF404+#ifdef __cplusplus405+#define STBDS_HAS_LITERAL_ARRAY406+#endif407+#endif408+409+#if !defined(__cplusplus)410+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L411+#define STBDS_HAS_LITERAL_ARRAY412+#endif413+#endif414+415+// this macro takes the address of the argument, but on gcc/clang can accept rvalues416+#if defined(STBDS_HAS_LITERAL_ARRAY) && defined(STBDS_HAS_TYPEOF)417+#define STBDS_ADDRESSOF(typevar, value) ((typeof(typevar)[1]){value}) // literal array decays to pointer to value418+#else419+#define STBDS_ADDRESSOF(typevar, value) &(value)420+#endif421+422+#define STBDS_OFFSETOF(var,field) ((char *) &(var)->field - (char *) (var))423+424+#define stbds_header(t) ((stbds_array_header *) (t) - 1)425+#define stbds_temp(t) stbds_header(t)->temp426+427+#define stbds_arrsetcap(a,n) (stbds_arrgrow(a,0,n))428+#define stbds_arrsetlen(a,n) ((stbds_arrcap(a) < n ? stbds_arrsetcap(a,n),0 : 0), (a) ? stbds_header(a)->length = (n) : 0)429+#define stbds_arrcap(a) ((a) ? stbds_header(a)->capacity : 0)430+#define stbds_arrlen(a) ((a) ? (ptrdiff_t) stbds_header(a)->length : 0)431+#define stbds_arrlenu(a) ((a) ? stbds_header(a)->length : 0)432+#define stbds_arrput(a,v) (stbds_arrmaybegrow(a,1), (a)[stbds_header(a)->length++] = (v))433+#define stbds_arrpush stbds_arrput // synonym434+#define stbds_arraddn(a,n) (stbds_arrmaybegrow(a,n), stbds_header(a)->length += (n))435+#define stbds_arrlast(a) ((a)[stbds_header(a)->length-1])436+#define stbds_arrfree(a) ((void) ((a) ? realloc(stbds_header(a),0) : 0), (a)=NULL)437+#define stbds_arrdel(a,i) stbds_arrdeln(a,i,1)438+#define stbds_arrdeln(a,i,n) (memmove(&(a)[i], &(a)[(i)+(n)], sizeof *(a) * (stbds_header(a)->length-(n)-(i))), stbds_header(a)->length -= (n))439+#define stbds_arrdelswap(a,i) ((a)[i] = stbds_arrlast(a), stbds_header(a)->length -= 1)440+#define stbds_arrinsn(a,i,n) (stbds_arraddn((a),(n)), memmove(&(a)[(i)+(n)], &(a)[i], sizeof *(a) * (stbds_header(a)->length-(n)-(i))))441+#define stbds_arrins(a,i,v) (stbds_arrinsn((a),(i),1), (a)[i]=(v))442+443+#define stbds_arrmaybegrow(a,n) ((!(a) || stbds_header(a)->length + (n) > stbds_header(a)->capacity) \444+ ? (stbds_arrgrow(a,n,0),0) : 0)445+446+#define stbds_arrgrow(a,b,c) ((a) = stbds_arrgrowf((a), sizeof *(a), (b), (c)))447+448+#define stbds_hmput(t, k, v) \449+ ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, 0), \450+ (t)[stbds_temp((t)-1)].key = (k), \451+ (t)[stbds_temp((t)-1)].value = (v))452+453+#define stbds_hmputs(t, s) \454+ ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), &(s).key, sizeof (s).key, STBDS_HM_BINARY), \455+ (t)[stbds_temp((t)-1)] = (s))456+457+#define stbds_hmgeti(t,k) \458+ ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, STBDS_HM_BINARY), \459+ stbds_temp((t)-1))460+461+#define stbds_hmgetp(t, k) \462+ ((void) stbds_hmgeti(t,k), &(t)[stbds_temp((t)-1)])463+464+#define stbds_hmdel(t,k) \465+ (((t) = stbds_hmdel_key_wrapper((t),sizeof *(t), STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, STBDS_OFFSETOF((t),key), STBDS_HM_BINARY)),(t)?stbds_temp((t)-1):0)466+467+#define stbds_hmdefault(t, v) \468+ ((t) = stbds_hmput_default_wrapper((t), sizeof *(t)), (t)[-1].value = (v))469+470+#define stbds_hmdefaults(t, s) \471+ ((t) = stbds_hmput_default_wrapper((t), sizeof *(t)), (t)[-1] = (s))472+473+#define stbds_hmfree(p) \474+ ((void) ((p) != NULL ? stbds_hmfree_func((p)-1,sizeof*(p),STBDS_OFFSETOF((p),key)),0 : 0),(p)=NULL)475+476+#define stbds_hmgets(t, k) (*stbds_hmgetp(t,k))477+#define stbds_hmget(t, k) (stbds_hmgetp(t,k)->value)478+#define stbds_hmlen(t) (stbds_arrlen((t)-1)-1)479+#define stbds_hmlenu(t) (stbds_arrlenu((t)-1)-1)480+481+#define stbds_shput(t, k, v) \482+ ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (k), sizeof (t)->key, STBDS_HM_STRING), \483+ (t)[stbds_temp(t-1)].value = (v))484+485+#define stbds_shputs(t, s) \486+ ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (s).key, sizeof (s).key, STBDS_HM_STRING), \487+ (t)[stbds_temp(t-1)] = (s))488+489+#define stbds_shgeti(t,k) \490+ ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), (k), sizeof (t)->key, STBDS_HM_STRING), \491+ stbds_temp(t))492+493+#define stbds_shgetp(t, k) \494+ ((void) stbds_shgeti(t,k), &(t)[stbds_temp(t-1)])495+496+#define stbds_shdel(t,k) \497+ (((t) = stbds_hmdel_key((t),sizeof *(t), (k), sizeof (t)->key, STBDS_OFFSETOF((t),key), STBDS_HM_STRING)),(t)?stbds_temp((t)-1):0)498+499+#define stbds_sh_new_arena(t) \500+ ((t) = stbds_shmode_func_wrapper(t, sizeof *(t), STBDS_SH_ARENA))501+#define stbds_sh_new_strdup(t) \502+ ((t) = stbds_shmode_func_wrapper(t, sizeof *(t), STBDS_SH_STRDUP))503+504+#define stbds_shdefault(t, v) stbds_hmdefault(t,v)505+#define stbds_shdefaults(t, s) stbds_hmdefaults(t,s)506+507+#define stbds_shfree stbds_hmfree508+#define stbds_shlenu stbds_hmlenu509+510+#define stbds_shgets(t, k) (*stbds_shgetp(t,k))511+#define stbds_shget(t, k) (stbds_shgetp(t,k)->value)512+#define stbds_shlen stbds_hmlen513+514+typedef struct515+{516+ size_t length;517+ size_t capacity;518+ void * hash_table;519+ ptrdiff_t temp;520+} stbds_array_header;521+522+typedef struct stbds_string_block523+{524+ struct stbds_string_block *next;525+ char storage[8];526+} stbds_string_block;527+528+struct stbds_string_arena529+{530+ stbds_string_block *storage;531+ size_t remaining;532+ unsigned char block;533+ unsigned char mode; // this isn't used by the string arena itself534+};535+536+enum537+{538+ STBDS_HM_BINARY,539+ STBDS_HM_STRING,540+};541+542+enum543+{544+ STBDS_SH_NONE,545+ STBDS_SH_STRDUP,546+ STBDS_SH_ARENA547+};548+549+#ifdef __cplusplus550+// in C we use implicit assignment from these void*-returning functions to T*.551+// in C++ these templates make the same code work552+template<class T> static T * stbds_arrgrowf_wrapper(T *a, size_t elemsize, size_t addlen, size_t min_cap) {553+ return (T*)stbds_arrgrowf((void *)a, elemsize, addlen, min_cap);554+}555+template<class T> static T * stbds_hmget_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, int mode) {556+ return (T*)stbds_hmget_key((void*)a, elemsize, key, keysize, mode);557+}558+template<class T> static T * stbds_hmput_default_wrapper(T *a, size_t elemsize) {559+ return (T*)stbds_hmput_default((void *)a, elemsize);560+}561+template<class T> static T * stbds_hmput_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, int mode) {562+ return (T*)stbds_hmput_key((void*)a, elemsize, key, keysize, mode);563+}564+template<class T> static T * stbds_hmdel_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode){565+ return (T*)stbds_hmdel_key((void*)a, elemsize, key, keysize, keyoffset, mode);566+}567+template<class T> static T * stbds_shmode_func_wrapper(T *, size_t elemsize, int mode) {568+ return stbds_shmode_func(elemsize, mode);569+}570+#else571+#define stbds_arrgrowf_wrapper stbds_arrgrowf572+#define stbds_hmget_key_wrapper stbds_hmget_key573+#define stbds_hmput_default_wrapper stbds_hmput_default574+#define stbds_hmput_key_wrapper stbds_hmput_key575+#define stbds_hmdel_key_wrapper stbds_hmdel_key576+#define stbds_shmode_func_wrapper(t,e,m) stbds_shmode_func(e,m)577+#endif578+579+#endif // INCLUDE_STB_DS_H580+581+582+//////////////////////////////////////////////////////////////////////////////583+//584+// IMPLEMENTATION585+//586+587+#ifdef STB_DS_IMPLEMENTATION588+#include <assert.h>589+#include <string.h>590+591+#ifndef STBDS_ASSERT592+#define STBDS_ASSERT(x) ((void) 0)593+#endif594+595+#ifdef STBDS_STATISTICS596+#define STBDS_STATS(x) x597+size_t stbds_array_grow;598+size_t stbds_hash_grow;599+size_t stbds_hash_shrink;600+size_t stbds_hash_rebuild;601+size_t stbds_hash_probes;602+size_t stbds_hash_alloc;603+size_t stbds_rehash_probes;604+size_t stbds_rehash_items;605+#else606+#define STBDS_STATS(x)607+#endif608+609+//610+// stbds_arr implementation611+//612+613+void *stbds_arrgrowf(void *a, size_t elemsize, size_t addlen, size_t min_cap)614+{615+ void *b;616+ size_t min_len = stbds_arrlen(a) + addlen;617+618+ // compute the minimum capacity needed619+ if (min_len > min_cap)620+ min_cap = min_len;621+622+ if (min_cap <= stbds_arrcap(a))623+ return a;624+625+ // increase needed capacity to guarantee O(1) amortized626+ if (min_cap < 2 * stbds_arrcap(a))627+ min_cap = 2 * stbds_arrcap(a);628+ else if (min_cap < 4)629+ min_cap = 4;630+631+ b = realloc((a) ? stbds_header(a) : 0, elemsize * min_cap + sizeof(stbds_array_header));632+ b = (char *) b + sizeof(stbds_array_header);633+ if (a == NULL) {634+ stbds_header(b)->length = 0;635+ stbds_header(b)->hash_table = 0;636+ } else {637+ STBDS_STATS(++stbds_array_grow);638+ }639+ stbds_header(b)->capacity = min_cap;640+ return b;641+}642+643+//644+// stbds_hm hash table implementation645+//646+647+#define STBDS_CACHE_LINE_SIZE 64648+#define STBDS_BUCKET_LENGTH 8649+#define STBDS_BUCKET_SHIFT 3650+#define STBDS_BUCKET_MASK (STBDS_BUCKET_LENGTH-1)651+652+#define STBDS_ALIGN_FWD(n,a) (((n) + (a) - 1) & ~((a)-1))653+654+typedef struct655+{656+ size_t hash [STBDS_BUCKET_LENGTH];657+ ptrdiff_t index[STBDS_BUCKET_LENGTH];658+} stbds_hash_bucket; // in 32-bit, this is one 64-byte cache line; in 64-bit, each array is one 64-byte cache line659+660+typedef struct661+{662+ size_t slot_count;663+ size_t used_count;664+ size_t used_count_threshold;665+ size_t used_count_shrink_threshold;666+ size_t tombstone_count;667+ size_t tombstone_count_threshold;668+ size_t seed;669+ size_t slot_count_log2;670+ stbds_string_arena string;671+ stbds_hash_bucket *storage; // not a separate allocation, just 64-byte aligned storage after this struct672+} stbds_hash_index;673+674+#define STBDS_INDEX_EMPTY -1675+#define STBDS_INDEX_DELETED -2676+#define STBDS_INDEX_IN_USE(x) ((x) >= 0)677+678+#define STBDS_HASH_EMPTY 0679+#define STBDS_HASH_DELETED 1680+681+static size_t stbds_hash_seed=0x31415926;682+683+void stbds_rand_seed(size_t seed)684+{685+ stbds_hash_seed = seed;686+}687+688+#define stbds_load_32_or_64(var, temp, v32, v64_hi, v64_lo) \689+ temp = v64_lo ^ v32, temp <<= 16, temp <<= 16, temp >>= 16, temp >>= 16, /* discard if 32-bit */ \690+ var = v64_hi, var <<= 16, var <<= 16, /* discard if 32-bit */ \691+ var ^= temp ^ v32692+693+#define STBDS_SIZE_T_BITS ((sizeof (size_t)) * 8)694+695+static size_t stbds_probe_position(size_t hash, size_t slot_count, size_t slot_log2)696+{697+ #if 1698+ size_t pos = (hash >> (STBDS_SIZE_T_BITS-slot_log2));699+ STBDS_ASSERT(pos < slot_count);700+ return pos;701+ #else702+ return hash & (slot_count-1);703+ #endif704+}705+706+static size_t stbds_log2(size_t slot_count)707+{708+ size_t n=0;709+ while (slot_count > 1) {710+ slot_count >>= 1;711+ ++n;712+ }713+ return n;714+}715+716+static stbds_hash_index *stbds_make_hash_index(size_t slot_count, stbds_hash_index *ot)717+{718+ stbds_hash_index *t;719+ t = (stbds_hash_index *) realloc(0,(slot_count >> STBDS_BUCKET_SHIFT) * sizeof(stbds_hash_bucket) + sizeof(stbds_hash_index) + STBDS_CACHE_LINE_SIZE-1);720+ t->storage = (stbds_hash_bucket *) STBDS_ALIGN_FWD((size_t) (t+1), STBDS_CACHE_LINE_SIZE);721+ t->slot_count = slot_count;722+ t->slot_count_log2 = stbds_log2(slot_count);723+ t->tombstone_count = 0;724+ t->used_count = 0;725+726+ #if 0 // A1727+ t->used_count_threshold = slot_count*12/16; // if 12/16th of table is occupied, grow728+ t->tombstone_count_threshold = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild729+ t->used_count_shrink_threshold = slot_count* 4/16; // if table is only 4/16th full, shrink730+ #elif 1 // A2731+ //t->used_count_threshold = slot_count*12/16; // if 12/16th of table is occupied, grow732+ //t->tombstone_count_threshold = slot_count* 3/16; // if tombstones are 3/16th of table, rebuild733+ //t->used_count_shrink_threshold = slot_count* 4/16; // if table is only 4/16th full, shrink734+735+ // compute without overflowing736+ t->used_count_threshold = slot_count - (slot_count>>2);737+ t->tombstone_count_threshold = (slot_count>>3) + (slot_count>>4);738+ t->used_count_shrink_threshold = slot_count >> 2;739+740+ #elif 0 // B1741+ t->used_count_threshold = slot_count*13/16; // if 13/16th of table is occupied, grow742+ t->tombstone_count_threshold = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild743+ t->used_count_shrink_threshold = slot_count* 5/16; // if table is only 5/16th full, shrink744+ #else // C1745+ t->used_count_threshold = slot_count*14/16; // if 14/16th of table is occupied, grow746+ t->tombstone_count_threshold = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild747+ t->used_count_shrink_threshold = slot_count* 6/16; // if table is only 6/16th full, shrink748+ #endif749+ // Following statistics were measured on a Core i7-6700 @ 4.00Ghz, compiled with clang 7.0.1 -O2750+ // Note that the larger tables have high variance as they were run fewer times751+ // A1 A2 B1 C1752+ // 0.10ms : 0.10ms : 0.10ms : 0.11ms : 2,000 inserts creating 2K table 753+ // 0.96ms : 0.95ms : 0.97ms : 1.04ms : 20,000 inserts creating 20K table 754+ // 14.48ms : 14.46ms : 10.63ms : 11.00ms : 200,000 inserts creating 200K table 755+ // 195.74ms : 196.35ms : 203.69ms : 214.92ms : 2,000,000 inserts creating 2M table 756+ // 2193.88ms : 2209.22ms : 2285.54ms : 2437.17ms : 20,000,000 inserts creating 20M table 757+ // 65.27ms : 53.77ms : 65.33ms : 65.47ms : 500,000 inserts & deletes in 2K table 758+ // 72.78ms : 62.45ms : 71.95ms : 72.85ms : 500,000 inserts & deletes in 20K table 759+ // 89.47ms : 77.72ms : 96.49ms : 96.75ms : 500,000 inserts & deletes in 200K table760+ // 97.58ms : 98.14ms : 97.18ms : 97.53ms : 500,000 inserts & deletes in 2M table 761+ // 118.61ms : 119.62ms : 120.16ms : 118.86ms : 500,000 inserts & deletes in 20M table 762+ // 192.11ms : 194.39ms : 196.38ms : 195.73ms : 500,000 inserts & deletes in 200M table763+764+ if (slot_count <= STBDS_BUCKET_LENGTH)765+ t->used_count_shrink_threshold = 0;766+ // to avoid infinite loop, we need to guarantee that at least one slot is empty and will terminate probes767+ STBDS_ASSERT(t->used_count_threshold + t->tombstone_count_threshold < t->slot_count);768+ STBDS_STATS(++stbds_hash_alloc);769+ if (ot) {770+ t->string = ot->string;771+ // reuse old seed so we can reuse old hashes so below "copy out old data" doesn't do any hashing772+ t->seed = ot->seed;773+ } else {774+ size_t a,b,temp;775+ memset(&t->string, 0, sizeof(t->string));776+ t->seed = stbds_hash_seed;777+ // LCG778+ // in 32-bit, a = 2147001325 b = 715136305779+ // in 64-bit, a = 2862933555777941757 b = 3037000493780+ stbds_load_32_or_64(a,temp, 2147001325, 0x27bb2ee6, 0x87b0b0fd);781+ stbds_load_32_or_64(b,temp, 715136305, 0, 0xb504f32d);782+ stbds_hash_seed = stbds_hash_seed * a + b;783+ }784+785+ {786+ size_t i,j;787+ for (i=0; i < slot_count >> STBDS_BUCKET_SHIFT; ++i) {788+ stbds_hash_bucket *b = &t->storage[i];789+ for (j=0; j < STBDS_BUCKET_LENGTH; ++j)790+ b->hash[j] = STBDS_HASH_EMPTY;791+ for (j=0; j < STBDS_BUCKET_LENGTH; ++j)792+ b->index[j] = STBDS_INDEX_EMPTY;793+ }794+ }795+796+ // copy out the old data, if any797+ if (ot) {798+ size_t i,j;799+ t->used_count = ot->used_count;800+ for (i=0; i < ot->slot_count >> STBDS_BUCKET_SHIFT; ++i) {801+ stbds_hash_bucket *ob = &ot->storage[i];802+ for (j=0; j < STBDS_BUCKET_LENGTH; ++j) {803+ if (STBDS_INDEX_IN_USE(ob->index[j])) {804+ size_t hash = ob->hash[j];805+ size_t pos = stbds_probe_position(hash, t->slot_count, t->slot_count_log2);806+ size_t step = STBDS_BUCKET_LENGTH;807+ STBDS_STATS(++stbds_rehash_items);808+ for (;;) {809+ size_t limit,z;810+ stbds_hash_bucket *bucket;811+ pos &= (t->slot_count-1);812+ bucket = &t->storage[pos >> STBDS_BUCKET_SHIFT];813+ STBDS_STATS(++stbds_rehash_probes);814+815+ for (z=pos & STBDS_BUCKET_MASK; z < STBDS_BUCKET_LENGTH; ++z) {816+ if (bucket->hash[z] == 0) {817+ bucket->hash[z] = hash;818+ bucket->index[z] = ob->index[j];819+ goto done;820+ }821+ }822+823+ limit = pos & STBDS_BUCKET_MASK;824+ for (z = 0; z < limit; ++z) {825+ if (bucket->hash[z] == 0) {826+ bucket->hash[z] = hash;827+ bucket->index[z] = ob->index[j];828+ goto done;829+ }830+ }831+832+ pos += step; // quadratic probing833+ step += STBDS_BUCKET_LENGTH;834+ }835+ }836+ done:837+ ;838+ }839+ }840+ }841+842+ return t;843+}844+845+#define STBDS_ROTATE_LEFT(val, n) (((val) << (n)) | ((val) >> (STBDS_SIZE_T_BITS - (n))))846+#define STBDS_ROTATE_RIGHT(val, n) (((val) >> (n)) | ((val) << (STBDS_SIZE_T_BITS - (n))))847+848+size_t stbds_hash_string(char *str, size_t seed)849+{850+ size_t hash = seed;851+ while (*str)852+ hash = STBDS_ROTATE_LEFT(hash, 9) + (unsigned char) *str++;853+854+ // Thomas Wang 64-to-32 bit mix function, hopefully also works in 32 bits855+ hash ^= seed;856+ hash = (~hash) + (hash << 18);857+ hash ^= hash ^ STBDS_ROTATE_RIGHT(hash,31);858+ hash = hash * 21;859+ hash ^= hash ^ STBDS_ROTATE_RIGHT(hash,11);860+ hash += (hash << 6);861+ hash ^= STBDS_ROTATE_RIGHT(hash,22);862+ return hash+seed;863+}864+865+#ifdef STBDS_SIPHASH_2_4866+#define STBDS_SIPHASH_C_ROUNDS 2867+#define STBDS_SIPHASH_D_ROUNDS 4868+typedef int STBDS_SIPHASH_2_4_can_only_be_used_in_64_bit_builds[sizeof(size_t) == 8 ? 1 : -1];869+#endif870+871+#ifndef STBDS_SIPHASH_C_ROUNDS872+#define STBDS_SIPHASH_C_ROUNDS 1873+#endif874+#ifndef STBDS_SIPHASH_D_ROUNDS875+#define STBDS_SIPHASH_D_ROUNDS 1876+#endif877+878+static size_t stbds_siphash_bytes(void *p, size_t len, size_t seed)879+{880+ unsigned char *d = (unsigned char *) p;881+ size_t i,j;882+ size_t v0,v1,v2,v3, data;883+884+ // hash that works on 32- or 64-bit registers without knowing which we have885+ // (computes different results on 32-bit and 64-bit platform)886+ // derived from siphash, but on 32-bit platforms very different as it uses 4 32-bit state not 4 64-bit887+ v0 = ((((size_t) 0x736f6d65 << 16) << 16) + 0x70736575) ^ seed;888+ v1 = ((((size_t) 0x646f7261 << 16) << 16) + 0x6e646f6d) ^ ~seed;889+ v2 = ((((size_t) 0x6c796765 << 16) << 16) + 0x6e657261) ^ seed; 890+ v3 = ((((size_t) 0x74656462 << 16) << 16) + 0x79746573) ^ ~seed;891+892+ #ifdef STBDS_TEST_SIPHASH_2_4893+ // hardcoded with key material in the siphash test vectors894+ v0 ^= 0x0706050403020100ull ^ seed;895+ v1 ^= 0x0f0e0d0c0b0a0908ull ^ ~seed;896+ v2 ^= 0x0706050403020100ull ^ seed;897+ v3 ^= 0x0f0e0d0c0b0a0908ull ^ ~seed;898+ #endif899+900+ #define STBDS_SIPROUND() \901+ do { \902+ v0 += v1; v1 = STBDS_ROTATE_LEFT(v1, 13); v1 ^= v0; v0 = STBDS_ROTATE_LEFT(v0,STBDS_SIZE_T_BITS/2); \903+ v2 += v3; v3 = STBDS_ROTATE_LEFT(v3, 16); v3 ^= v2; \904+ v2 += v1; v1 = STBDS_ROTATE_LEFT(v1, 17); v1 ^= v2; v2 = STBDS_ROTATE_LEFT(v2,STBDS_SIZE_T_BITS/2); \905+ v0 += v3; v3 = STBDS_ROTATE_LEFT(v3, 21); v3 ^= v0; \906+ } while (0)907+908+ for (i=0; i+sizeof(size_t) <= len; i += sizeof(size_t), d += sizeof(size_t)) {909+ data = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);910+ data |= (size_t) (d[4] | (d[5] << 8) | (d[6] << 16) | (d[7] << 24)) << 16 << 16; // discarded if size_t == 4911+912+ v3 ^= data;913+ for (j=0; j < STBDS_SIPHASH_C_ROUNDS; ++j)914+ STBDS_SIPROUND();915+ v0 ^= data;916+ }917+ data = len << (STBDS_SIZE_T_BITS-8);918+ switch (len - i) {919+ case 7: data |= ((size_t) d[6] << 48);920+ case 6: data |= ((size_t) d[5] << 40);921+ case 5: data |= ((size_t) d[4] << 32);922+ case 4: data |= (d[3] << 24);923+ case 3: data |= (d[2] << 16);924+ case 2: data |= (d[1] << 8);925+ case 1: data |= d[0];926+ case 0: break;927+ }928+ v3 ^= data;929+ for (j=0; j < STBDS_SIPHASH_C_ROUNDS; ++j)930+ STBDS_SIPROUND();931+ v0 ^= data;932+ v2 ^= 0xff;933+ for (j=0; j < STBDS_SIPHASH_D_ROUNDS; ++j)934+ STBDS_SIPROUND();935+#ifdef STBDS_SIPHASH_2_4936+ return v0^v1^v2^v3;937+#else938+ return v1^v2^v3; // slightly stronger since v0^v3 in above cancels out final round operation939+#endif940+}941+942+size_t stbds_hash_bytes(void *p, size_t len, size_t seed)943+{944+#ifdef STBDS_SIPHASH_2_4945+ return stbds_siphash_bytes(p,len,seed);946+#else947+ unsigned char *d = (unsigned char *) p;948+949+ if (len == 4) {950+ unsigned int hash = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);951+ #if 0952+ // HASH32-A Bob Jenkin's hash function w/o large constants953+ hash ^= seed ^ len;954+ hash -= (hash<<6);955+ hash ^= (hash>>17);956+ hash -= (hash<<9);957+ hash ^= (hash<<4);958+ hash -= (hash<<3);959+ hash ^= (hash<<10);960+ hash ^= (hash>>15);961+ #elif 1962+ // HASH32-BB Bob Jenkin's presumably-accidental version of Thomas Wang hash with rotates turned into shifts.963+ // Note that converting these back to rotates makes it run a lot slower, presumably due to collisions, so I'm964+ // not really sure what's going on.965+ hash ^= seed ^ len;966+ hash = (hash ^ 61) ^ (hash >> 16);967+ hash = hash + (hash << 3);968+ hash = hash ^ (hash >> 4);969+ hash = hash * 0x27d4eb2d;970+ hash = hash ^ (hash >> 15);971+ #else // HASH32-C - Murmur3972+ hash *= 0xcc9e2d51;973+ hash = (hash << 17) | (hash >> 15);974+ hash *= 0x1b873593;975+ hash ^= seed;976+ hash = (hash << 19) | (hash >> 13);977+ hash = hash*5 + 0xe6546b64;978+ hash ^= len;979+ hash ^= hash >> 16;980+ hash *= 0x85ebca6b;981+ hash ^= hash >> 13;982+ hash *= 0xc2b2ae35;983+ hash ^= hash >> 16;984+ #endif985+ // Following statistics were measured on a Core i7-6700 @ 4.00Ghz, compiled with clang 7.0.1 -O2986+ // Note that the larger tables have high variance as they were run fewer times987+ // HASH32-A // HASH32-BB // HASH32-C988+ // 0.10ms // 0.10ms // 0.10ms : 2,000 inserts creating 2K table 989+ // 0.96ms // 0.95ms // 0.99ms : 20,000 inserts creating 20K table 990+ // 14.69ms // 14.43ms // 14.97ms : 200,000 inserts creating 200K table 991+ // 199.99ms // 195.36ms // 202.05ms : 2,000,000 inserts creating 2M table 992+ // 2234.84ms // 2187.74ms // 2240.38ms : 20,000,000 inserts creating 20M table 993+ // 55.68ms // 53.72ms // 57.31ms : 500,000 inserts & deletes in 2K table 994+ // 63.43ms // 61.99ms // 65.73ms : 500,000 inserts & deletes in 20K table 995+ // 80.04ms // 77.96ms // 81.83ms : 500,000 inserts & deletes in 200K table996+ // 100.42ms // 97.40ms // 102.39ms : 500,000 inserts & deletes in 2M table 997+ // 119.71ms // 120.59ms // 121.63ms : 500,000 inserts & deletes in 20M table 998+ // 185.28ms // 195.15ms // 187.74ms : 500,000 inserts & deletes in 200M table999+ // 15.58ms // 14.79ms // 15.52ms : 200,000 inserts creating 200K table with varying key spacing1000+1001+ return (((size_t) hash << 16 << 16) | hash) ^ seed;1002+ } else if (len == 8 && sizeof(size_t) == 8) {1003+ size_t hash = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24) | ((size_t)d[4] << 32) | ((size_t)d[5] << 40) | ((size_t)d[6] << 48) | ((size_t)d[7] << 56);1004+ hash ^= seed ^ len;1005+ hash = (~hash) + (hash << 21);1006+ hash ^= STBDS_ROTATE_RIGHT(hash,24);1007+ hash *= 265;1008+ hash ^= STBDS_ROTATE_RIGHT(hash,14);1009+ hash *= 21;1010+ hash ^= STBDS_ROTATE_RIGHT(hash,28);1011+ hash += (hash << 31);1012+ hash = (~hash) + (hash << 18);1013+ return hash^seed;1014+ } else {1015+ return stbds_siphash_bytes(p,len,seed);1016+ }1017+#endif1018+}1019+1020+static int stbds_is_key_equal(void *a, size_t elemsize, void *key, size_t keysize, int mode, size_t i)1021+{1022+ if (mode >= STBDS_HM_STRING)1023+ return 0==strcmp((char *) key, * (char **) ((char *) a + elemsize*i));1024+ else1025+ return 0==memcmp(key, (char *) a + elemsize*i, keysize);1026+}1027+1028+#define STBDS_HASH_TO_ARR(x,elemsize) ((char*) (x) - (elemsize))1029+#define STBDS_ARR_TO_HASH(x,elemsize) ((char*) (x) + (elemsize))1030+#define STBDS_FREE(x) realloc(x,0)1031+1032+#define stbds_hash_table(a) ((stbds_hash_index *) stbds_header(a)->hash_table)1033+ 1034+void stbds_hmfree_func(void *a, size_t elemsize, size_t keyoff)1035+{1036+ if (a == NULL) return;1037+ if (stbds_hash_table(a) != NULL) {1038+ if (stbds_hash_table(a)->string.mode == STBDS_SH_STRDUP) {1039+ size_t i;1040+ // skip 0th element, which is default1041+ for (i=1; i < stbds_header(a)->length; ++i)1042+ STBDS_FREE(*(char**) ((char *) a + elemsize*i));1043+ }1044+ stbds_strreset(&stbds_hash_table(a)->string);1045+ }1046+ STBDS_FREE(stbds_header(a)->hash_table);1047+ STBDS_FREE(stbds_header(a));1048+}1049+1050+static ptrdiff_t stbds_hm_find_slot(void *a, size_t elemsize, void *key, size_t keysize, int mode)1051+{1052+ void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);1053+ stbds_hash_index *table = stbds_hash_table(raw_a);1054+ size_t hash = mode >= STBDS_HM_STRING ? stbds_hash_string((char*)key,table->seed) : stbds_hash_bytes(key, keysize,table->seed);1055+ size_t step = STBDS_BUCKET_LENGTH;1056+ size_t limit,i;1057+ size_t pos;1058+ stbds_hash_bucket *bucket;1059+1060+ if (hash < 2) hash += 2; // stored hash values are forbidden from being 0, so we can detect empty slots1061+1062+ pos = stbds_probe_position(hash, table->slot_count, table->slot_count_log2);1063+1064+ for (;;) {1065+ STBDS_STATS(++stbds_hash_probes);1066+ bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];1067+1068+ // start searching from pos to end of bucket, this should help performance on small hash tables that fit in cache1069+ for (i=pos & STBDS_BUCKET_MASK; i < STBDS_BUCKET_LENGTH; ++i) {1070+ if (bucket->hash[i] == hash) {1071+ if (stbds_is_key_equal(a, elemsize, key, keysize, mode, bucket->index[i])) {1072+ return (pos & ~STBDS_BUCKET_MASK)+i;1073+ }1074+ } else if (bucket->hash[i] == STBDS_HASH_EMPTY) {1075+ return -1;1076+ }1077+ }1078+1079+ // search from beginning of bucket to pos1080+ limit = pos & STBDS_BUCKET_MASK;1081+ for (i = 0; i < limit; ++i) {1082+ if (bucket->hash[i] == hash) {1083+ if (stbds_is_key_equal(a, elemsize, key, keysize, mode, bucket->index[i])) {1084+ return (pos & ~STBDS_BUCKET_MASK)+i;1085+ }1086+ } else if (bucket->hash[i] == STBDS_HASH_EMPTY) {1087+ return -1;1088+ }1089+ }1090+1091+ // quadratic probing1092+ pos += step;1093+ step += STBDS_BUCKET_LENGTH;1094+ pos &= (table->slot_count-1);1095+ }1096+ /* NOTREACHED */1097+ return -1;1098+}1099+1100+void * stbds_hmget_key(void *a, size_t elemsize, void *key, size_t keysize, int mode)1101+{1102+ if (a == NULL) {1103+ // make it non-empty so we can return a temp1104+ a = stbds_arrgrowf(0, elemsize, 0, 1);1105+ stbds_header(a)->length += 1;1106+ memset(a, 0, elemsize);1107+ stbds_temp(a) = STBDS_INDEX_EMPTY;1108+ // adjust a to point after the default element1109+ return STBDS_ARR_TO_HASH(a,elemsize);1110+ } else {1111+ stbds_hash_index *table;1112+ void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);1113+ // adjust a to point to the default element1114+ table = (stbds_hash_index *) stbds_header(raw_a)->hash_table;1115+ if (table == 0) {1116+ stbds_temp(raw_a) = -1;1117+ } else {1118+ ptrdiff_t slot = stbds_hm_find_slot(a, elemsize, key, keysize, mode);1119+ if (slot < 0) {1120+ stbds_temp(raw_a) = STBDS_INDEX_EMPTY;1121+ } else {1122+ stbds_hash_bucket *b = &table->storage[slot >> STBDS_BUCKET_SHIFT];1123+ stbds_temp(raw_a) = b->index[slot & STBDS_BUCKET_MASK];1124+ }1125+ }1126+ return a;1127+ }1128+}1129+1130+void * stbds_hmput_default(void *a, size_t elemsize)1131+{1132+ // three cases:1133+ // a is NULL <- allocate1134+ // a has a hash table but no entries, because of shmode <- grow1135+ // a has entries <- do nothing1136+ if (a == NULL || stbds_header(STBDS_HASH_TO_ARR(a,elemsize))->length == 0) {1137+ a = stbds_arrgrowf(a ? STBDS_HASH_TO_ARR(a,elemsize) : NULL, elemsize, 0, 1);1138+ stbds_header(a)->length += 1;1139+ memset(a, 0, elemsize);1140+ a=STBDS_ARR_TO_HASH(a,elemsize);1141+ }1142+ return a;1143+}1144+1145+static char *stbds_strdup(char *str);1146+1147+void *stbds_hmput_key(void *a, size_t elemsize, void *key, size_t keysize, int mode)1148+{1149+ void *raw_a;1150+ stbds_hash_index *table;1151+1152+ if (a == NULL) {1153+ a = stbds_arrgrowf(0, elemsize, 0, 1);1154+ memset(a, 0, elemsize);1155+ stbds_header(a)->length += 1;1156+ // adjust a to point AFTER the default element1157+ a = STBDS_ARR_TO_HASH(a,elemsize);1158+ }1159+1160+ // adjust a to point to the default element1161+ raw_a = a;1162+ a = STBDS_HASH_TO_ARR(a,elemsize);1163+1164+ table = (stbds_hash_index *) stbds_header(a)->hash_table;1165+1166+ if (table == NULL || table->used_count >= table->used_count_threshold) {1167+ stbds_hash_index *nt;1168+ size_t slot_count;1169+1170+ slot_count = (table == NULL) ? STBDS_BUCKET_LENGTH : table->slot_count*2;1171+ nt = stbds_make_hash_index(slot_count, table);1172+ if (table) {1173+ STBDS_FREE(table);1174+ }1175+ stbds_header(a)->hash_table = table = nt;1176+ STBDS_STATS(++stbds_hash_grow);1177+ }1178+1179+ // we iterate hash table explicitly because we want to track if we saw a tombstone1180+ {1181+ size_t hash = mode >= STBDS_HM_STRING ? stbds_hash_string((char*)key,table->seed) : stbds_hash_bytes(key, keysize,table->seed);1182+ size_t step = STBDS_BUCKET_LENGTH;1183+ size_t limit,i;1184+ size_t pos;1185+ ptrdiff_t tombstone = -1;1186+ stbds_hash_bucket *bucket;1187+1188+ // stored hash values are forbidden from being 0, so we can detect empty slots to early out quickly1189+ if (hash < 2) hash += 2;1190+1191+ pos = stbds_probe_position(hash, table->slot_count, table->slot_count_log2);1192+1193+ for (;;) {1194+ STBDS_STATS(++stbds_hash_probes);1195+ bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];1196+1197+ // start searching from pos to end of bucket1198+ for (i=pos & STBDS_BUCKET_MASK; i < STBDS_BUCKET_LENGTH; ++i) {1199+ if (bucket->hash[i] == hash) {1200+ if (stbds_is_key_equal(raw_a, elemsize, key, keysize, mode, bucket->index[i])) {1201+ stbds_temp(a) = bucket->index[i];1202+ return STBDS_ARR_TO_HASH(a,elemsize);1203+ }1204+ } else if (bucket->hash[i] == 0) {1205+ pos = (pos & ~STBDS_BUCKET_MASK) + i;1206+ goto found_empty_slot;1207+ } else if (tombstone < 0) {1208+ if (bucket->index[i] == STBDS_INDEX_DELETED)1209+ tombstone = (ptrdiff_t) ((pos & ~STBDS_BUCKET_MASK) + i);1210+ }1211+ }1212+1213+ // search from beginning of bucket to pos1214+ limit = pos & STBDS_BUCKET_MASK;1215+ for (i = 0; i < limit; ++i) {1216+ if (bucket->hash[i] == hash) {1217+ if (stbds_is_key_equal(raw_a, elemsize, key, keysize, mode, bucket->index[i])) {1218+ stbds_temp(a) = bucket->index[i];1219+ return STBDS_ARR_TO_HASH(a,elemsize);1220+ }1221+ } else if (bucket->hash[i] == 0) {1222+ pos = (pos & ~STBDS_BUCKET_MASK) + i;1223+ goto found_empty_slot;1224+ } else if (tombstone < 0) {1225+ if (bucket->index[i] == STBDS_INDEX_DELETED)1226+ tombstone = (ptrdiff_t) ((pos & ~STBDS_BUCKET_MASK) + i);1227+ }1228+ }1229+1230+ // quadratic probing1231+ pos += step;1232+ step += STBDS_BUCKET_LENGTH;1233+ pos &= (table->slot_count-1);1234+ }1235+ found_empty_slot:1236+ if (tombstone >= 0) {1237+ pos = tombstone;1238+ --table->tombstone_count;1239+ }1240+ ++table->used_count;1241+1242+ {1243+ ptrdiff_t i = (ptrdiff_t) stbds_arrlen(a);1244+ // we want to do stbds_arraddn(1), but we can't use the macros since we don't have something of the right type1245+ if ((size_t) i+1 > stbds_arrcap(a))1246+ *(void **) &a = stbds_arrgrowf(a, elemsize, 1, 0);1247+ raw_a = STBDS_ARR_TO_HASH(a,elemsize);1248+1249+ STBDS_ASSERT((size_t) i+1 <= stbds_arrcap(a));1250+ stbds_header(a)->length = i+1;1251+ bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];1252+ bucket->hash[pos & STBDS_BUCKET_MASK] = hash;1253+ bucket->index[pos & STBDS_BUCKET_MASK] = i-1;1254+ stbds_temp(a) = i-1;1255+1256+ switch (table->string.mode) {1257+ case STBDS_SH_STRDUP: *(char **) ((char *) a + elemsize*i) = stbds_strdup((char*) key); break;1258+ case STBDS_SH_ARENA: *(char **) ((char *) a + elemsize*i) = stbds_stralloc(&table->string, (char*)key); break;1259+ default: *(char **) ((char *) a + elemsize*i) = (char *) key; break;1260+ }1261+ }1262+ return STBDS_ARR_TO_HASH(a,elemsize);1263+ }1264+}1265+1266+void * stbds_shmode_func(size_t elemsize, int mode)1267+{1268+ void *a = stbds_arrgrowf(0, elemsize, 0, 1);1269+ stbds_hash_index *h;1270+ stbds_header(a)->hash_table = h = (stbds_hash_index *) stbds_make_hash_index(STBDS_BUCKET_LENGTH, NULL);1271+ h->string.mode = mode;1272+ return STBDS_ARR_TO_HASH(a,elemsize);1273+}1274+1275+void * stbds_hmdel_key(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode)1276+{1277+ if (a == NULL) {1278+ return 0;1279+ } else {1280+ stbds_hash_index *table;1281+ void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);1282+ table = (stbds_hash_index *) stbds_header(raw_a)->hash_table;1283+ stbds_temp(raw_a) = 0;1284+ if (table == 0) {1285+ return a;1286+ } else {1287+ ptrdiff_t slot;1288+ slot = stbds_hm_find_slot(a, elemsize, key, keysize, mode);1289+ if (slot < 0)1290+ return a;1291+ else {1292+ stbds_hash_bucket *b = &table->storage[slot >> STBDS_BUCKET_SHIFT];1293+ int i = slot & STBDS_BUCKET_MASK;1294+ ptrdiff_t old_index = b->index[i];1295+ ptrdiff_t final_index = (ptrdiff_t) stbds_arrlen(raw_a)-1-1; // minus one for the raw_a vs a, and minus one for 'last'1296+ STBDS_ASSERT(slot < (ptrdiff_t) table->slot_count);1297+ --table->used_count;1298+ ++table->tombstone_count;1299+ stbds_temp(raw_a) = 1;1300+ STBDS_ASSERT(table->used_count >= 0);1301+ //STBDS_ASSERT(table->tombstone_count < table->slot_count/4);1302+ b->hash[i] = STBDS_HASH_DELETED;1303+ b->index[i] = STBDS_INDEX_DELETED;1304+1305+ if (mode == STBDS_HM_STRING && table->string.mode == STBDS_SH_STRDUP)1306+ STBDS_FREE(*(char**) ((char *) a+elemsize*old_index));1307+1308+ // if indices are the same, memcpy is a no-op, but back-pointer-fixup will fail, so skip1309+ if (old_index != final_index) {1310+ // swap delete 1311+ memmove((char*) a + elemsize*old_index, (char*) a + elemsize*final_index, elemsize);1312+1313+ // now find the slot for the last element1314+ if (mode == STBDS_HM_STRING)1315+ slot = stbds_hm_find_slot(a, elemsize, *(char**) ((char *) a+elemsize*old_index + keyoffset), keysize, mode);1316+ else1317+ slot = stbds_hm_find_slot(a, elemsize, (char* ) a+elemsize*old_index + keyoffset, keysize, mode);1318+ STBDS_ASSERT(slot >= 0);1319+ b = &table->storage[slot >> STBDS_BUCKET_SHIFT];1320+ i = slot & STBDS_BUCKET_MASK;1321+ STBDS_ASSERT(b->index[i] == final_index);1322+ b->index[i] = old_index;1323+ }1324+ stbds_header(raw_a)->length -= 1;1325+1326+ if (table->used_count < table->used_count_shrink_threshold && table->slot_count > STBDS_BUCKET_LENGTH) {1327+ stbds_header(raw_a)->hash_table = stbds_make_hash_index(table->slot_count>>1, table);1328+ STBDS_FREE(table);1329+ STBDS_STATS(++stbds_hash_shrink);1330+ } else if (table->tombstone_count > table->tombstone_count_threshold) {1331+ stbds_header(raw_a)->hash_table = stbds_make_hash_index(table->slot_count , table);1332+ STBDS_FREE(table);1333+ STBDS_STATS(++stbds_hash_rebuild);1334+ }1335+1336+ return a;1337+ }1338+ }1339+ }1340+ /* NOTREACHED */1341+ return 0;1342+}1343+1344+static char *stbds_strdup(char *str)1345+{1346+ // to keep replaceable allocator simple, we don't want to use strdup.1347+ // rolling our own also avoids problem of strdup vs _strdup1348+ size_t len = strlen(str)+1;1349+ char *p = (char*) realloc(0, len);1350+ memmove(p, str, len);1351+ return p;1352+}1353+1354+#ifndef STBDS_STRING_ARENA_BLOCKSIZE_MIN1355+#define STBDS_STRING_ARENA_BLOCKSIZE_MIN 5121356+#endif1357+#ifndef STBDS_STRING_ARENA_BLOCKSIZE_MAX1358+#define STBDS_STRING_ARENA_BLOCKSIZE_MAX 1<<201359+#endif1360+1361+char *stbds_stralloc(stbds_string_arena *a, char *str)1362+{1363+ char *p;1364+ size_t len = strlen(str)+1;1365+ if (len > a->remaining) {1366+ // compute the next blocksize1367+ size_t blocksize = a->block;1368+1369+ // size is 512, 512, 1024, 1024, 2048, 2048, 4096, 4096, etc., so that1370+ // there are log(SIZE) allocations to free when we destroy the table1371+ blocksize = (size_t) (STBDS_STRING_ARENA_BLOCKSIZE_MIN) << (blocksize>>1);1372+1373+ // if size is under 1M, advance to next blocktype1374+ if (blocksize < (size_t)(STBDS_STRING_ARENA_BLOCKSIZE_MAX))1375+ ++a->block;1376+1377+ if (len > blocksize) {1378+ // if string is larger than blocksize, then just allocate the full size.1379+ // note that we still advance string_block so block size will continue1380+ // increasing, so e.g. if somebody only calls this with 1000-long strings,1381+ // eventually the arena will start doubling and handling those as well1382+ stbds_string_block *sb = (stbds_string_block *) realloc(0, sizeof(*sb)-8 + len);1383+ memmove(sb->storage, str, len);1384+ if (a->storage) {1385+ // insert it after the first element, so that we don't waste the space there1386+ sb->next = a->storage->next;1387+ a->storage->next = sb;1388+ } else {1389+ sb->next = 0;1390+ a->storage = sb;1391+ a->remaining = 0; // this is redundant, but good for clarity1392+ }1393+ return sb->storage;1394+ } else {1395+ stbds_string_block *sb = (stbds_string_block *) realloc(0, sizeof(*sb)-8 + blocksize);1396+ sb->next = a->storage;1397+ a->storage = sb;1398+ a->remaining = blocksize;1399+ }1400+ }1401+1402+ STBDS_ASSERT(len <= a->remaining);1403+ p = a->storage->storage + a->remaining - len;1404+ a->remaining -= len;1405+ memmove(p, str, len);1406+ return p;1407+}1408+1409+void stbds_strreset(stbds_string_arena *a)1410+{1411+ stbds_string_block *x,*y;1412+ x = a->storage;1413+ while (x) {1414+ y = x->next;1415+ realloc(x,0);1416+ x = y;1417+ }1418+ memset(a, 0, sizeof(*a));1419+}1420+1421+#endif1422+1423+//////////////////////////////////////////////////////////////////////////////1424+//1425+// UNIT TESTS1426+//1427+1428+#ifdef STBDS_UNIT_TESTS1429+#include <stdio.h>1430+#ifndef STBDS_ASSERT1431+#define STBDS_ASSERT assert1432+#include <assert.h>1433+#endif1434+1435+typedef struct { int key,b,c,d; } stbds_struct;1436+1437+static char buffer[256];1438+char *strkey(int n)1439+{1440+ sprintf(buffer, "test_%d", n);1441+ return buffer;1442+}1443+1444+void stbds_unit_tests(void)1445+{1446+ const int testsize = 100000;1447+ int *arr=NULL;1448+ struct { int key; int value; } *intmap = NULL;1449+ struct { char *key; int value; } *strmap = NULL;1450+ struct { stbds_struct key; int value; } *map = NULL;1451+ stbds_struct *map2 = NULL;1452+ stbds_string_arena sa = { 0 };1453+1454+ int i,j;1455+1456+ for (i=0; i < 20000; i += 50) {1457+ for (j=0; j < i; ++j)1458+ arrpush(arr,j);1459+ arrfree(arr);1460+ }1461+1462+ for (i=0; i < 4; ++i) {1463+ arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);1464+ arrdel(arr,i);1465+ arrfree(arr);1466+ arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);1467+ arrdelswap(arr,i);1468+ arrfree(arr);1469+ }1470+1471+ for (i=0; i < 5; ++i) {1472+ arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);1473+ stbds_arrins(arr,i,5);1474+ assert(arr[i] == 5);1475+ if (i < 4)1476+ assert(arr[4] == 4);1477+ arrfree(arr);1478+ }1479+1480+ hmdefault(intmap, -1);1481+ i=1; assert(hmget(intmap, i) == -1);1482+ for (i=0; i < testsize; i+=2)1483+ hmput(intmap, i, i*5);1484+ for (i=0; i < testsize; i+=1)1485+ if (i & 1) assert(hmget(intmap, i) == -1 );1486+ else assert(hmget(intmap, i) == i*5);1487+ for (i=0; i < testsize; i+=2)1488+ hmput(intmap, i, i*3);1489+ for (i=0; i < testsize; i+=1)1490+ if (i & 1) assert(hmget(intmap, i) == -1 );1491+ else assert(hmget(intmap, i) == i*3);1492+ for (i=2; i < testsize; i+=4)1493+ hmdel(intmap, i); // delete half the entries1494+ for (i=0; i < testsize; i+=1)1495+ if (i & 3) assert(hmget(intmap, i) == -1 );1496+ else assert(hmget(intmap, i) == i*3);1497+ for (i=0; i < testsize; i+=1)1498+ hmdel(intmap, i); // delete the rest of the entries 1499+ for (i=0; i < testsize; i+=1)1500+ assert(hmget(intmap, i) == -1 );1501+ hmfree(intmap);1502+ for (i=0; i < testsize; i+=2)1503+ hmput(intmap, i, i*3);1504+ hmfree(intmap);1505+1506+ #ifdef __clang__1507+ intmap = NULL;1508+ hmput(intmap, 15, 7);1509+ hmput(intmap, 11, 3);1510+ hmput(intmap, 9, 5);1511+ assert(hmget(intmap, 9) == 5);1512+ assert(hmget(intmap, 11) == 3);1513+ assert(hmget(intmap, 15) == 7);1514+ #endif1515+1516+ for (i=0; i < testsize; ++i)1517+ stralloc(&sa, strkey(i));1518+ strreset(&sa);1519+1520+ for (j=0; j < 2; ++j) {1521+ if (j == 0)1522+ sh_new_strdup(strmap);1523+ else1524+ sh_new_arena(strmap);1525+ shdefault(strmap, -1);1526+ for (i=0; i < testsize; i+=2)1527+ shput(strmap, strkey(i), i*3);1528+ for (i=0; i < testsize; i+=1)1529+ if (i & 1) assert(shget(strmap, strkey(i)) == -1 );1530+ else assert(shget(strmap, strkey(i)) == i*3);1531+ for (i=2; i < testsize; i+=4)1532+ shdel(strmap, strkey(i)); // delete half the entries1533+ for (i=0; i < testsize; i+=1)1534+ if (i & 3) assert(shget(strmap, strkey(i)) == -1 );1535+ else assert(shget(strmap, strkey(i)) == i*3);1536+ for (i=0; i < testsize; i+=1)1537+ shdel(strmap, strkey(i)); // delete the rest of the entries 1538+ for (i=0; i < testsize; i+=1)1539+ assert(shget(strmap, strkey(i)) == -1 );1540+ shfree(strmap);1541+ }1542+1543+ {1544+ struct { char *key; char value; } *hash = NULL;1545+ char name[4] = "jen";1546+ shput(hash, "bob" , 'h');1547+ shput(hash, "sally" , 'e');1548+ shput(hash, "fred" , 'l');1549+ shput(hash, "jen" , 'x');1550+ shput(hash, "doug" , 'o');1551+1552+ shput(hash, name , 'l');1553+ shfree(hash);1554+ }1555+1556+ for (i=0; i < testsize; i += 2) {1557+ stbds_struct s = { i,i*2,i*3,i*4 };1558+ hmput(map, s, i*5);1559+ }1560+1561+ for (i=0; i < testsize; i += 1) {1562+ stbds_struct s = { i,i*2,i*3 ,i*4 };1563+ stbds_struct t = { i,i*2,i*3+1,i*4 };1564+ if (i & 1) assert(hmget(map, s) == 0);1565+ else assert(hmget(map, s) == i*5);1566+ assert(hmget(map, t) == 0);1567+ }1568+1569+ for (i=0; i < testsize; i += 2) {1570+ stbds_struct s = { i,i*2,i*3,i*4 };1571+ hmputs(map2, s);1572+ }1573+ hmfree(map);1574+1575+ for (i=0; i < testsize; i += 1) {1576+ stbds_struct s = { i,i*2,i*3,i*4 };1577+ stbds_struct t = { i,i*2,i*3,i*4 };1578+ if (i & 1) assert(hmgets(map2, s.key).d == 0);1579+ else assert(hmgets(map2, s.key).d == i*4);1580+ }1581+ hmfree(map2);1582+}1583+#endif1584+1585+1586+/*1587+------------------------------------------------------------------------------1588+This software is available under 2 licenses -- choose whichever you prefer.1589+------------------------------------------------------------------------------1590+ALTERNATIVE A - MIT License1591+Copyright (c) 2019 Sean Barrett1592+Permission is hereby granted, free of charge, to any person obtaining a copy of1593+this software and associated documentation files (the "Software"), to deal in1594+the Software without restriction, including without limitation the rights to1595+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies1596+of the Software, and to permit persons to whom the Software is furnished to do1597+so, subject to the following conditions:1598+The above copyright notice and this permission notice shall be included in all1599+copies or substantial portions of the Software.1600+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR1601+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,1602+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE1603+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER1604+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,1605+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE1606+SOFTWARE.1607+------------------------------------------------------------------------------1608+ALTERNATIVE B - Public Domain (www.unlicense.org)1609+This is free and unencumbered software released into the public domain.1610+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this1611+software, either in source code form or as a compiled binary, for any purpose,1612+commercial or non-commercial, and by any means.1613+In jurisdictions that recognize copyright laws, the author or authors of this1614+software dedicate any and all copyright interest in the software to the public1615+domain. We make this dedication for the benefit of the public at large and to1616+the detriment of our heirs and successors. We intend this dedication to be an1617+overt act of relinquishment in perpetuity of all present and future rights to1618+this software under copyright law.1619+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR1620+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,1621+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE1622+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN1623+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION1624+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.1625+------------------------------------------------------------------------------1626+*/