stb_ds.h 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  1. /* stb_ds.h - v0.67 - public domain data structures - Sean Barrett 2019
  2. This is a single-header-file library that provides easy-to-use
  3. dynamic arrays and hash tables for C (also works in C++).
  4. For a gentle introduction:
  5. http://nothings.org/stb_ds
  6. To use this library, do this in *one* C or C++ file:
  7. #define STB_DS_IMPLEMENTATION
  8. #include "stb_ds.h"
  9. TABLE OF CONTENTS
  10. Table of Contents
  11. Compile-time options
  12. License
  13. Documentation
  14. Notes
  15. Notes - Dynamic arrays
  16. Notes - Hash maps
  17. Credits
  18. COMPILE-TIME OPTIONS
  19. #define STBDS_NO_SHORT_NAMES
  20. This flag needs to be set globally.
  21. By default stb_ds exposes shorter function names that are not qualified
  22. with the "stbds_" prefix. If these names conflict with the names in your
  23. code, define this flag.
  24. #define STBDS_SIPHASH_2_4
  25. This flag only needs to be set in the file containing #define STB_DS_IMPLEMENTATION.
  26. By default stb_ds.h hashes using a weaker variant of SipHash and a custom hash for
  27. 4- and 8-byte keys. On 64-bit platforms, you can define the above flag to force
  28. stb_ds.h to use specification-compliant SipHash-2-4 for all keys. Doing so makes
  29. hash table insertion about 20% slower on 4- and 8-byte keys, 5% slower on
  30. 64-byte keys, and 10% slower on 256-byte keys on my test computer.
  31. #define STBDS_REALLOC(context,ptr,size) better_realloc
  32. #define STBDS_FREE(context,ptr) better_free
  33. These defines only need to be set in the file containing #define STB_DS_IMPLEMENTATION.
  34. By default stb_ds uses stdlib realloc() and free() for memory management. You can
  35. substitute your own functions instead by defining these symbols. You must either
  36. define both, or neither. Note that at the moment, 'context' will always be NULL.
  37. @TODO add an array/hash initialization function that takes a memory context pointer.
  38. #define STBDS_UNIT_TESTS
  39. Defines a function stbds_unit_tests() that checks the functioning of the data structures.
  40. Note that on older versions of gcc (e.g. 5.x.x) you may need to build with '-std=c++0x'
  41. (or equivalentally '-std=c++11') when using anonymous structures as seen on the web
  42. page or in STBDS_UNIT_TESTS.
  43. LICENSE
  44. Placed in the public domain and also MIT licensed.
  45. See end of file for detailed license information.
  46. DOCUMENTATION
  47. Dynamic Arrays
  48. Non-function interface:
  49. Declare an empty dynamic array of type T
  50. T* foo = NULL;
  51. Access the i'th item of a dynamic array 'foo' of type T, T* foo:
  52. foo[i]
  53. Functions (actually macros)
  54. arrfree:
  55. void arrfree(T*);
  56. Frees the array.
  57. arrlen:
  58. ptrdiff_t arrlen(T*);
  59. Returns the number of elements in the array.
  60. arrlenu:
  61. size_t arrlenu(T*);
  62. Returns the number of elements in the array as an unsigned type.
  63. arrpop:
  64. T arrpop(T* a)
  65. Removes the final element of the array and returns it.
  66. arrput:
  67. T arrput(T* a, T b);
  68. Appends the item b to the end of array a. Returns b.
  69. arrins:
  70. T arrins(T* a, int p, T b);
  71. Inserts the item b into the middle of array a, into a[p],
  72. moving the rest of the array over. Returns b.
  73. arrinsn:
  74. void arrinsn(T* a, int p, int n);
  75. Inserts n uninitialized items into array a starting at a[p],
  76. moving the rest of the array over.
  77. arraddnptr:
  78. T* arraddnptr(T* a, int n)
  79. Appends n uninitialized items onto array at the end.
  80. Returns a pointer to the first uninitialized item added.
  81. arraddnindex:
  82. size_t arraddnindex(T* a, int n)
  83. Appends n uninitialized items onto array at the end.
  84. Returns the index of the first uninitialized item added.
  85. arrdel:
  86. void arrdel(T* a, int p);
  87. Deletes the element at a[p], moving the rest of the array over.
  88. arrdeln:
  89. void arrdeln(T* a, int p, int n);
  90. Deletes n elements starting at a[p], moving the rest of the array over.
  91. arrdelswap:
  92. void arrdelswap(T* a, int p);
  93. Deletes the element at a[p], replacing it with the element from
  94. the end of the array. O(1) performance.
  95. arrsetlen:
  96. void arrsetlen(T* a, int n);
  97. Changes the length of the array to n. Allocates uninitialized
  98. slots at the end if necessary.
  99. arrsetcap:
  100. size_t arrsetcap(T* a, int n);
  101. Sets the length of allocated storage to at least n. It will not
  102. change the length of the array.
  103. arrcap:
  104. size_t arrcap(T* a);
  105. Returns the number of total elements the array can contain without
  106. needing to be reallocated.
  107. Hash maps & String hash maps
  108. Given T is a structure type: struct { TK key; TV value; }. Note that some
  109. functions do not require TV value and can have other fields. For string
  110. hash maps, TK must be 'char *'.
  111. Special interface:
  112. stbds_rand_seed:
  113. void stbds_rand_seed(size_t seed);
  114. For security against adversarially chosen data, you should seed the
  115. library with a strong random number. Or at least seed it with time().
  116. stbds_hash_string:
  117. size_t stbds_hash_string(char *str, size_t seed);
  118. Returns a hash value for a string.
  119. stbds_hash_bytes:
  120. size_t stbds_hash_bytes(void *p, size_t len, size_t seed);
  121. These functions hash an arbitrary number of bytes. The function
  122. uses a custom hash for 4- and 8-byte data, and a weakened version
  123. of SipHash for everything else. On 64-bit platforms you can get
  124. specification-compliant SipHash-2-4 on all data by defining
  125. STBDS_SIPHASH_2_4, at a significant cost in speed.
  126. Non-function interface:
  127. Declare an empty hash map of type T
  128. T* foo = NULL;
  129. Access the i'th entry in a hash table T* foo:
  130. foo[i]
  131. Function interface (actually macros):
  132. hmfree
  133. shfree
  134. void hmfree(T*);
  135. void shfree(T*);
  136. Frees the hashmap and sets the pointer to NULL.
  137. hmlen
  138. shlen
  139. ptrdiff_t hmlen(T*)
  140. ptrdiff_t shlen(T*)
  141. Returns the number of elements in the hashmap.
  142. hmlenu
  143. shlenu
  144. size_t hmlenu(T*)
  145. size_t shlenu(T*)
  146. Returns the number of elements in the hashmap.
  147. hmgeti
  148. shgeti
  149. hmgeti_ts
  150. ptrdiff_t hmgeti(T*, TK key)
  151. ptrdiff_t shgeti(T*, char* key)
  152. ptrdiff_t hmgeti_ts(T*, TK key, ptrdiff_t tempvar)
  153. Returns the index in the hashmap which has the key 'key', or -1
  154. if the key is not present.
  155. hmget
  156. hmget_ts
  157. shget
  158. TV hmget(T*, TK key)
  159. TV shget(T*, char* key)
  160. TV hmget_ts(T*, TK key, ptrdiff_t tempvar)
  161. Returns the value corresponding to 'key' in the hashmap.
  162. The structure must have a 'value' field
  163. hmgets
  164. shgets
  165. T hmgets(T*, TK key)
  166. T shgets(T*, char* key)
  167. Returns the structure corresponding to 'key' in the hashmap.
  168. hmgetp
  169. shgetp
  170. hmgetp_ts
  171. hmgetp_null
  172. shgetp_null
  173. T* hmgetp(T*, TK key)
  174. T* shgetp(T*, char* key)
  175. T* hmgetp_ts(T*, TK key, ptrdiff_t tempvar)
  176. T* hmgetp_null(T*, TK key)
  177. T* shgetp_null(T*, char *key)
  178. Returns a pointer to the structure corresponding to 'key' in
  179. the hashmap. Functions ending in "_null" return NULL if the key
  180. is not present in the hashmap; the others return a pointer to a
  181. structure holding the default value (but not the searched-for key).
  182. hmdefault
  183. shdefault
  184. TV hmdefault(T*, TV value)
  185. TV shdefault(T*, TV value)
  186. Sets the default value for the hashmap, the value which will be
  187. returned by hmget/shget if the key is not present.
  188. hmdefaults
  189. shdefaults
  190. TV hmdefaults(T*, T item)
  191. TV shdefaults(T*, T item)
  192. Sets the default struct for the hashmap, the contents which will be
  193. returned by hmgets/shgets if the key is not present.
  194. hmput
  195. shput
  196. TV hmput(T*, TK key, TV value)
  197. TV shput(T*, char* key, TV value)
  198. Inserts a <key,value> pair into the hashmap. If the key is already
  199. present in the hashmap, updates its value.
  200. hmputs
  201. shputs
  202. T hmputs(T*, T item)
  203. T shputs(T*, T item)
  204. Inserts a struct with T.key into the hashmap. If the struct is already
  205. present in the hashmap, updates it.
  206. hmdel
  207. shdel
  208. int hmdel(T*, TK key)
  209. int shdel(T*, char* key)
  210. If 'key' is in the hashmap, deletes its entry and returns 1.
  211. Otherwise returns 0.
  212. Function interface (actually macros) for strings only:
  213. sh_new_strdup
  214. void sh_new_strdup(T*);
  215. Overwrites the existing pointer with a newly allocated
  216. string hashmap which will automatically allocate and free
  217. each string key using realloc/free
  218. sh_new_arena
  219. void sh_new_arena(T*);
  220. Overwrites the existing pointer with a newly allocated
  221. string hashmap which will automatically allocate each string
  222. key to a string arena. Every string key ever used by this
  223. hash table remains in the arena until the arena is freed.
  224. Additionally, any key which is deleted and reinserted will
  225. be allocated multiple times in the string arena.
  226. NOTES
  227. * These data structures are realloc'd when they grow, and the macro
  228. "functions" write to the provided pointer. This means: (a) the pointer
  229. must be an lvalue, and (b) the pointer to the data structure is not
  230. stable, and you must maintain it the same as you would a realloc'd
  231. pointer. For example, if you pass a pointer to a dynamic array to a
  232. function which updates it, the function must return back the new
  233. pointer to the caller. This is the price of trying to do this in C.
  234. * The following are the only functions that are thread-safe on a single data
  235. structure, i.e. can be run in multiple threads simultaneously on the same
  236. data structure
  237. hmlen shlen
  238. hmlenu shlenu
  239. hmget_ts shget_ts
  240. hmgeti_ts shgeti_ts
  241. hmgets_ts shgets_ts
  242. * You iterate over the contents of a dynamic array and a hashmap in exactly
  243. the same way, using arrlen/hmlen/shlen:
  244. for (i=0; i < arrlen(foo); ++i)
  245. ... foo[i] ...
  246. * All operations except arrins/arrdel are O(1) amortized, but individual
  247. operations can be slow, so these data structures may not be suitable
  248. for real time use. Dynamic arrays double in capacity as needed, so
  249. elements are copied an average of once. Hash tables double/halve
  250. their size as needed, with appropriate hysteresis to maintain O(1)
  251. performance.
  252. NOTES - DYNAMIC ARRAY
  253. * If you know how long a dynamic array is going to be in advance, you can avoid
  254. extra memory allocations by using arrsetlen to allocate it to that length in
  255. advance and use foo[n] while filling it out, or arrsetcap to allocate the memory
  256. for that length and use arrput/arrpush as normal.
  257. * Unlike some other versions of the dynamic array, this version should
  258. be safe to use with strict-aliasing optimizations.
  259. NOTES - HASH MAP
  260. * For compilers other than GCC and clang (e.g. Visual Studio), for hmput/hmget/hmdel
  261. and variants, the key must be an lvalue (so the macro can take the address of it).
  262. Extensions are used that eliminate this requirement if you're using C99 and later
  263. in GCC or clang, or if you're using C++ in GCC. But note that this can make your
  264. code less portable.
  265. * To test for presence of a key in a hashmap, just do 'hmgeti(foo,key) >= 0'.
  266. * The iteration order of your data in the hashmap is determined solely by the
  267. order of insertions and deletions. In particular, if you never delete, new
  268. keys are always added at the end of the array. This will be consistent
  269. across all platforms and versions of the library. However, you should not
  270. attempt to serialize the internal hash table, as the hash is not consistent
  271. between different platforms, and may change with future versions of the library.
  272. * Use sh_new_arena() for string hashmaps that you never delete from. Initialize
  273. with NULL if you're managing the memory for your strings, or your strings are
  274. never freed (at least until the hashmap is freed). Otherwise, use sh_new_strdup().
  275. @TODO: make an arena variant that garbage collects the strings with a trivial
  276. copy collector into a new arena whenever the table shrinks / rebuilds. Since
  277. current arena recommendation is to only use arena if it never deletes, then
  278. this can just replace current arena implementation.
  279. * If adversarial input is a serious concern and you're on a 64-bit platform,
  280. enable STBDS_SIPHASH_2_4 (see the 'Compile-time options' section), and pass
  281. a strong random number to stbds_rand_seed.
  282. * The default value for the hash table is stored in foo[-1], so if you
  283. use code like 'hmget(T,k)->value = 5' you can accidentally overwrite
  284. the value stored by hmdefault if 'k' is not present.
  285. CREDITS
  286. Sean Barrett -- library, idea for dynamic array API/implementation
  287. Per Vognsen -- idea for hash table API/implementation
  288. Rafael Sachetto -- arrpop()
  289. github:HeroicKatora -- arraddn() reworking
  290. Bugfixes:
  291. Andy Durdin
  292. Shane Liesegang
  293. Vinh Truong
  294. Andreas Molzer
  295. github:hashitaku
  296. github:srdjanstipic
  297. Macoy Madson
  298. Andreas Vennstrom
  299. Tobias Mansfield-Williams
  300. */
  301. #ifdef STBDS_UNIT_TESTS
  302. #define _CRT_SECURE_NO_WARNINGS
  303. #endif
  304. #ifndef INCLUDE_STB_DS_H
  305. #define INCLUDE_STB_DS_H
  306. #include <stddef.h>
  307. #include <string.h>
  308. #ifndef STBDS_NO_SHORT_NAMES
  309. #define arrlen stbds_arrlen
  310. #define arrlenu stbds_arrlenu
  311. #define arrput stbds_arrput
  312. #define arrpush stbds_arrput
  313. #define arrpop stbds_arrpop
  314. #define arrfree stbds_arrfree
  315. #define arraddn stbds_arraddn // deprecated, use one of the following instead:
  316. #define arraddnptr stbds_arraddnptr
  317. #define arraddnindex stbds_arraddnindex
  318. #define arrsetlen stbds_arrsetlen
  319. #define arrlast stbds_arrlast
  320. #define arrins stbds_arrins
  321. #define arrinsn stbds_arrinsn
  322. #define arrdel stbds_arrdel
  323. #define arrdeln stbds_arrdeln
  324. #define arrdelswap stbds_arrdelswap
  325. #define arrcap stbds_arrcap
  326. #define arrsetcap stbds_arrsetcap
  327. #define hmput stbds_hmput
  328. #define hmputs stbds_hmputs
  329. #define hmget stbds_hmget
  330. #define hmget_ts stbds_hmget_ts
  331. #define hmgets stbds_hmgets
  332. #define hmgetp stbds_hmgetp
  333. #define hmgetp_ts stbds_hmgetp_ts
  334. #define hmgetp_null stbds_hmgetp_null
  335. #define hmgeti stbds_hmgeti
  336. #define hmgeti_ts stbds_hmgeti_ts
  337. #define hmdel stbds_hmdel
  338. #define hmlen stbds_hmlen
  339. #define hmlenu stbds_hmlenu
  340. #define hmfree stbds_hmfree
  341. #define hmdefault stbds_hmdefault
  342. #define hmdefaults stbds_hmdefaults
  343. #define shput stbds_shput
  344. #define shputi stbds_shputi
  345. #define shputs stbds_shputs
  346. #define shget stbds_shget
  347. #define shgeti stbds_shgeti
  348. #define shgets stbds_shgets
  349. #define shgetp stbds_shgetp
  350. #define shgetp_null stbds_shgetp_null
  351. #define shdel stbds_shdel
  352. #define shlen stbds_shlen
  353. #define shlenu stbds_shlenu
  354. #define shfree stbds_shfree
  355. #define shdefault stbds_shdefault
  356. #define shdefaults stbds_shdefaults
  357. #define sh_new_arena stbds_sh_new_arena
  358. #define sh_new_strdup stbds_sh_new_strdup
  359. #define stralloc stbds_stralloc
  360. #define strreset stbds_strreset
  361. #endif
  362. #if defined(STBDS_REALLOC) && !defined(STBDS_FREE) || !defined(STBDS_REALLOC) && defined(STBDS_FREE)
  363. #error "You must define both STBDS_REALLOC and STBDS_FREE, or neither."
  364. #endif
  365. #if !defined(STBDS_REALLOC) && !defined(STBDS_FREE)
  366. #include <stdlib.h>
  367. #define STBDS_REALLOC(c,p,s) realloc(p,s)
  368. #define STBDS_FREE(c,p) free(p)
  369. #endif
  370. #ifdef _MSC_VER
  371. #define STBDS_NOTUSED(v) (void)(v)
  372. #else
  373. #define STBDS_NOTUSED(v) (void)sizeof(v)
  374. #endif
  375. #ifdef __cplusplus
  376. extern "C" {
  377. #endif
  378. // for security against attackers, seed the library with a random number, at least time() but stronger is better
  379. extern void stbds_rand_seed(size_t seed);
  380. // these are the hash functions used internally if you want to test them or use them for other purposes
  381. extern size_t stbds_hash_bytes(void *p, size_t len, size_t seed);
  382. extern size_t stbds_hash_string(char *str, size_t seed);
  383. // this is a simple string arena allocator, initialize with e.g. 'stbds_string_arena my_arena={0}'.
  384. typedef struct stbds_string_arena stbds_string_arena;
  385. extern char * stbds_stralloc(stbds_string_arena *a, char *str);
  386. extern void stbds_strreset(stbds_string_arena *a);
  387. // have to #define STBDS_UNIT_TESTS to call this
  388. extern void stbds_unit_tests(void);
  389. ///////////////
  390. //
  391. // Everything below here is implementation details
  392. //
  393. extern void * stbds_arrgrowf(void *a, size_t elemsize, size_t addlen, size_t min_cap);
  394. extern void stbds_arrfreef(void *a);
  395. extern void stbds_hmfree_func(void *p, size_t elemsize);
  396. extern void * stbds_hmget_key(void *a, size_t elemsize, void *key, size_t keysize, int mode);
  397. extern void * stbds_hmget_key_ts(void *a, size_t elemsize, void *key, size_t keysize, ptrdiff_t *temp, int mode);
  398. extern void * stbds_hmput_default(void *a, size_t elemsize);
  399. extern void * stbds_hmput_key(void *a, size_t elemsize, void *key, size_t keysize, int mode);
  400. extern void * stbds_hmdel_key(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode);
  401. extern void * stbds_shmode_func(size_t elemsize, int mode);
  402. #ifdef __cplusplus
  403. }
  404. #endif
  405. #if defined(__GNUC__) || defined(__clang__)
  406. #define STBDS_HAS_TYPEOF
  407. #ifdef __cplusplus
  408. //#define STBDS_HAS_LITERAL_ARRAY // this is currently broken for clang
  409. #endif
  410. #endif
  411. #if !defined(__cplusplus)
  412. #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
  413. #define STBDS_HAS_LITERAL_ARRAY
  414. #endif
  415. #endif
  416. // this macro takes the address of the argument, but on gcc/clang can accept rvalues
  417. #if defined(STBDS_HAS_LITERAL_ARRAY) && defined(STBDS_HAS_TYPEOF)
  418. #if __clang__
  419. #define STBDS_ADDRESSOF(typevar, value) ((__typeof__(typevar)[1]){value}) // literal array decays to pointer to value
  420. #else
  421. #define STBDS_ADDRESSOF(typevar, value) ((typeof(typevar)[1]){value}) // literal array decays to pointer to value
  422. #endif
  423. #else
  424. #define STBDS_ADDRESSOF(typevar, value) &(value)
  425. #endif
  426. #define STBDS_OFFSETOF(var,field) ((char *) &(var)->field - (char *) (var))
  427. #define stbds_header(t) ((stbds_array_header *) (t) - 1)
  428. #define stbds_temp(t) stbds_header(t)->temp
  429. #define stbds_temp_key(t) (*(char **) stbds_header(t)->hash_table)
  430. #define stbds_arrsetcap(a,n) (stbds_arrgrow(a,0,n))
  431. #define stbds_arrsetlen(a,n) ((stbds_arrcap(a) < (size_t) (n) ? stbds_arrsetcap((a),(size_t)(n)),0 : 0), (a) ? stbds_header(a)->length = (size_t) (n) : 0)
  432. #define stbds_arrcap(a) ((a) ? stbds_header(a)->capacity : 0)
  433. #define stbds_arrlen(a) ((a) ? (ptrdiff_t) stbds_header(a)->length : 0)
  434. #define stbds_arrlenu(a) ((a) ? stbds_header(a)->length : 0)
  435. #define stbds_arrput(a,v) (stbds_arrmaybegrow(a,1), (a)[stbds_header(a)->length++] = (v))
  436. #define stbds_arrpush stbds_arrput // synonym
  437. #define stbds_arrpop(a) (stbds_header(a)->length--, (a)[stbds_header(a)->length])
  438. #define stbds_arraddn(a,n) ((void)(stbds_arraddnindex(a, n))) // deprecated, use one of the following instead:
  439. #define stbds_arraddnptr(a,n) (stbds_arrmaybegrow(a,n), (n) ? (stbds_header(a)->length += (n), &(a)[stbds_header(a)->length-(n)]) : (a))
  440. #define stbds_arraddnindex(a,n)(stbds_arrmaybegrow(a,n), (n) ? (stbds_header(a)->length += (n), stbds_header(a)->length-(n)) : stbds_arrlen(a))
  441. #define stbds_arraddnoff stbds_arraddnindex
  442. #define stbds_arrlast(a) ((a)[stbds_header(a)->length-1])
  443. #define stbds_arrfree(a) ((void) ((a) ? STBDS_FREE(NULL,stbds_header(a)) : (void)0), (a)=NULL)
  444. #define stbds_arrdel(a,i) stbds_arrdeln(a,i,1)
  445. #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))
  446. #define stbds_arrdelswap(a,i) ((a)[i] = stbds_arrlast(a), stbds_header(a)->length -= 1)
  447. #define stbds_arrinsn(a,i,n) (stbds_arraddn((a),(n)), memmove(&(a)[(i)+(n)], &(a)[i], sizeof *(a) * (stbds_header(a)->length-(n)-(i))))
  448. #define stbds_arrins(a,i,v) (stbds_arrinsn((a),(i),1), (a)[i]=(v))
  449. #define stbds_arrmaybegrow(a,n) ((!(a) || stbds_header(a)->length + (n) > stbds_header(a)->capacity) \
  450. ? (stbds_arrgrow(a,n,0),0) : 0)
  451. #define stbds_arrgrow(a,b,c) ((a) = stbds_arrgrowf_wrapper((a), sizeof *(a), (b), (c)))
  452. #define stbds_hmput(t, k, v) \
  453. ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, 0), \
  454. (t)[stbds_temp((t)-1)].key = (k), \
  455. (t)[stbds_temp((t)-1)].value = (v))
  456. #define stbds_hmputs(t, s) \
  457. ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), &(s).key, sizeof (s).key, STBDS_HM_BINARY), \
  458. (t)[stbds_temp((t)-1)] = (s))
  459. #define stbds_hmgeti(t,k) \
  460. ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, STBDS_HM_BINARY), \
  461. stbds_temp((t)-1))
  462. #define stbds_hmgeti_ts(t,k,temp) \
  463. ((t) = stbds_hmget_key_ts_wrapper((t), sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, &(temp), STBDS_HM_BINARY), \
  464. (temp))
  465. #define stbds_hmgetp(t, k) \
  466. ((void) stbds_hmgeti(t,k), &(t)[stbds_temp((t)-1)])
  467. #define stbds_hmgetp_ts(t, k, temp) \
  468. ((void) stbds_hmgeti_ts(t,k,temp), &(t)[temp])
  469. #define stbds_hmdel(t,k) \
  470. (((t) = stbds_hmdel_key_wrapper((t),sizeof *(t), (void*) STBDS_ADDRESSOF((t)->key, (k)), sizeof (t)->key, STBDS_OFFSETOF((t),key), STBDS_HM_BINARY)),(t)?stbds_temp((t)-1):0)
  471. #define stbds_hmdefault(t, v) \
  472. ((t) = stbds_hmput_default_wrapper((t), sizeof *(t)), (t)[-1].value = (v))
  473. #define stbds_hmdefaults(t, s) \
  474. ((t) = stbds_hmput_default_wrapper((t), sizeof *(t)), (t)[-1] = (s))
  475. #define stbds_hmfree(p) \
  476. ((void) ((p) != NULL ? stbds_hmfree_func((p)-1,sizeof*(p)),0 : 0),(p)=NULL)
  477. #define stbds_hmgets(t, k) (*stbds_hmgetp(t,k))
  478. #define stbds_hmget(t, k) (stbds_hmgetp(t,k)->value)
  479. #define stbds_hmget_ts(t, k, temp) (stbds_hmgetp_ts(t,k,temp)->value)
  480. #define stbds_hmlen(t) ((t) ? (ptrdiff_t) stbds_header((t)-1)->length-1 : 0)
  481. #define stbds_hmlenu(t) ((t) ? stbds_header((t)-1)->length-1 : 0)
  482. #define stbds_hmgetp_null(t,k) (stbds_hmgeti(t,k) == -1 ? NULL : &(t)[stbds_temp((t)-1)])
  483. #define stbds_shput(t, k, v) \
  484. ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_HM_STRING), \
  485. (t)[stbds_temp((t)-1)].value = (v))
  486. #define stbds_shputi(t, k, v) \
  487. ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_HM_STRING), \
  488. (t)[stbds_temp((t)-1)].value = (v), stbds_temp((t)-1))
  489. #define stbds_shputs(t, s) \
  490. ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (s).key, sizeof (s).key, STBDS_HM_STRING), \
  491. (t)[stbds_temp((t)-1)] = (s), \
  492. (t)[stbds_temp((t)-1)].key = stbds_temp_key((t)-1)) // above line overwrites whole structure, so must rewrite key here if it was allocated internally
  493. #define stbds_pshput(t, p) \
  494. ((t) = stbds_hmput_key_wrapper((t), sizeof *(t), (void*) (p)->key, sizeof (p)->key, STBDS_HM_PTR_TO_STRING), \
  495. (t)[stbds_temp((t)-1)] = (p))
  496. #define stbds_shgeti(t,k) \
  497. ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_HM_STRING), \
  498. stbds_temp((t)-1))
  499. #define stbds_pshgeti(t,k) \
  500. ((t) = stbds_hmget_key_wrapper((t), sizeof *(t), (void*) (k), sizeof (*(t))->key, STBDS_HM_PTR_TO_STRING), \
  501. stbds_temp((t)-1))
  502. #define stbds_shgetp(t, k) \
  503. ((void) stbds_shgeti(t,k), &(t)[stbds_temp((t)-1)])
  504. #define stbds_pshget(t, k) \
  505. ((void) stbds_pshgeti(t,k), (t)[stbds_temp((t)-1)])
  506. #define stbds_shdel(t,k) \
  507. (((t) = stbds_hmdel_key_wrapper((t),sizeof *(t), (void*) (k), sizeof (t)->key, STBDS_OFFSETOF((t),key), STBDS_HM_STRING)),(t)?stbds_temp((t)-1):0)
  508. #define stbds_pshdel(t,k) \
  509. (((t) = stbds_hmdel_key_wrapper((t),sizeof *(t), (void*) (k), sizeof (*(t))->key, STBDS_OFFSETOF(*(t),key), STBDS_HM_PTR_TO_STRING)),(t)?stbds_temp((t)-1):0)
  510. #define stbds_sh_new_arena(t) \
  511. ((t) = stbds_shmode_func_wrapper(t, sizeof *(t), STBDS_SH_ARENA))
  512. #define stbds_sh_new_strdup(t) \
  513. ((t) = stbds_shmode_func_wrapper(t, sizeof *(t), STBDS_SH_STRDUP))
  514. #define stbds_shdefault(t, v) stbds_hmdefault(t,v)
  515. #define stbds_shdefaults(t, s) stbds_hmdefaults(t,s)
  516. #define stbds_shfree stbds_hmfree
  517. #define stbds_shlenu stbds_hmlenu
  518. #define stbds_shgets(t, k) (*stbds_shgetp(t,k))
  519. #define stbds_shget(t, k) (stbds_shgetp(t,k)->value)
  520. #define stbds_shgetp_null(t,k) (stbds_shgeti(t,k) == -1 ? NULL : &(t)[stbds_temp((t)-1)])
  521. #define stbds_shlen stbds_hmlen
  522. typedef struct
  523. {
  524. size_t length;
  525. size_t capacity;
  526. void * hash_table;
  527. ptrdiff_t temp;
  528. } stbds_array_header;
  529. typedef struct stbds_string_block
  530. {
  531. struct stbds_string_block *next;
  532. char storage[8];
  533. } stbds_string_block;
  534. struct stbds_string_arena
  535. {
  536. stbds_string_block *storage;
  537. size_t remaining;
  538. unsigned char block;
  539. unsigned char mode; // this isn't used by the string arena itself
  540. };
  541. #define STBDS_HM_BINARY 0
  542. #define STBDS_HM_STRING 1
  543. enum
  544. {
  545. STBDS_SH_NONE,
  546. STBDS_SH_DEFAULT,
  547. STBDS_SH_STRDUP,
  548. STBDS_SH_ARENA
  549. };
  550. #ifdef __cplusplus
  551. // in C we use implicit assignment from these void*-returning functions to T*.
  552. // in C++ these templates make the same code work
  553. template<class T> static T * stbds_arrgrowf_wrapper(T *a, size_t elemsize, size_t addlen, size_t min_cap) {
  554. return (T*)stbds_arrgrowf((void *)a, elemsize, addlen, min_cap);
  555. }
  556. template<class T> static T * stbds_hmget_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, int mode) {
  557. return (T*)stbds_hmget_key((void*)a, elemsize, key, keysize, mode);
  558. }
  559. template<class T> static T * stbds_hmget_key_ts_wrapper(T *a, size_t elemsize, void *key, size_t keysize, ptrdiff_t *temp, int mode) {
  560. return (T*)stbds_hmget_key_ts((void*)a, elemsize, key, keysize, temp, mode);
  561. }
  562. template<class T> static T * stbds_hmput_default_wrapper(T *a, size_t elemsize) {
  563. return (T*)stbds_hmput_default((void *)a, elemsize);
  564. }
  565. template<class T> static T * stbds_hmput_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, int mode) {
  566. return (T*)stbds_hmput_key((void*)a, elemsize, key, keysize, mode);
  567. }
  568. template<class T> static T * stbds_hmdel_key_wrapper(T *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode){
  569. return (T*)stbds_hmdel_key((void*)a, elemsize, key, keysize, keyoffset, mode);
  570. }
  571. template<class T> static T * stbds_shmode_func_wrapper(T *, size_t elemsize, int mode) {
  572. return (T*)stbds_shmode_func(elemsize, mode);
  573. }
  574. #else
  575. #define stbds_arrgrowf_wrapper stbds_arrgrowf
  576. #define stbds_hmget_key_wrapper stbds_hmget_key
  577. #define stbds_hmget_key_ts_wrapper stbds_hmget_key_ts
  578. #define stbds_hmput_default_wrapper stbds_hmput_default
  579. #define stbds_hmput_key_wrapper stbds_hmput_key
  580. #define stbds_hmdel_key_wrapper stbds_hmdel_key
  581. #define stbds_shmode_func_wrapper(t,e,m) stbds_shmode_func(e,m)
  582. #endif
  583. #endif // INCLUDE_STB_DS_H
  584. //////////////////////////////////////////////////////////////////////////////
  585. //
  586. // IMPLEMENTATION
  587. //
  588. #ifdef STB_DS_IMPLEMENTATION
  589. #include <assert.h>
  590. #include <string.h>
  591. #ifndef STBDS_ASSERT
  592. #define STBDS_ASSERT_WAS_UNDEFINED
  593. #define STBDS_ASSERT(x) ((void) 0)
  594. #endif
  595. #ifdef STBDS_STATISTICS
  596. #define STBDS_STATS(x) x
  597. 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. #else
  606. #define STBDS_STATS(x)
  607. #endif
  608. //
  609. // stbds_arr implementation
  610. //
  611. //int *prev_allocs[65536];
  612. //int num_prev;
  613. void *stbds_arrgrowf(void *a, size_t elemsize, size_t addlen, size_t min_cap)
  614. {
  615. stbds_array_header temp={0}; // force debugging
  616. void *b;
  617. size_t min_len = stbds_arrlen(a) + addlen;
  618. (void) sizeof(temp);
  619. // compute the minimum capacity needed
  620. if (min_len > min_cap)
  621. min_cap = min_len;
  622. if (min_cap <= stbds_arrcap(a))
  623. return a;
  624. // increase needed capacity to guarantee O(1) amortized
  625. if (min_cap < 2 * stbds_arrcap(a))
  626. min_cap = 2 * stbds_arrcap(a);
  627. else if (min_cap < 4)
  628. min_cap = 4;
  629. //if (num_prev < 65536) if (a) prev_allocs[num_prev++] = (int *) ((char *) a+1);
  630. //if (num_prev == 2201)
  631. // num_prev = num_prev;
  632. b = STBDS_REALLOC(NULL, (a) ? stbds_header(a) : 0, elemsize * min_cap + sizeof(stbds_array_header));
  633. //if (num_prev < 65536) prev_allocs[num_prev++] = (int *) (char *) b;
  634. b = (char *) b + sizeof(stbds_array_header);
  635. if (a == NULL) {
  636. stbds_header(b)->length = 0;
  637. stbds_header(b)->hash_table = 0;
  638. stbds_header(b)->temp = 0;
  639. } else {
  640. STBDS_STATS(++stbds_array_grow);
  641. }
  642. stbds_header(b)->capacity = min_cap;
  643. return b;
  644. }
  645. void stbds_arrfreef(void *a)
  646. {
  647. STBDS_FREE(NULL, stbds_header(a));
  648. }
  649. //
  650. // stbds_hm hash table implementation
  651. //
  652. #ifdef STBDS_INTERNAL_SMALL_BUCKET
  653. #define STBDS_BUCKET_LENGTH 4
  654. #else
  655. #define STBDS_BUCKET_LENGTH 8
  656. #endif
  657. #define STBDS_BUCKET_SHIFT (STBDS_BUCKET_LENGTH == 8 ? 3 : 2)
  658. #define STBDS_BUCKET_MASK (STBDS_BUCKET_LENGTH-1)
  659. #define STBDS_CACHE_LINE_SIZE 64
  660. #define STBDS_ALIGN_FWD(n,a) (((n) + (a) - 1) & ~((a)-1))
  661. typedef struct
  662. {
  663. size_t hash [STBDS_BUCKET_LENGTH];
  664. ptrdiff_t index[STBDS_BUCKET_LENGTH];
  665. } stbds_hash_bucket; // in 32-bit, this is one 64-byte cache line; in 64-bit, each array is one 64-byte cache line
  666. typedef struct
  667. {
  668. char * temp_key; // this MUST be the first field of the hash table
  669. size_t slot_count;
  670. size_t used_count;
  671. size_t used_count_threshold;
  672. size_t used_count_shrink_threshold;
  673. size_t tombstone_count;
  674. size_t tombstone_count_threshold;
  675. size_t seed;
  676. size_t slot_count_log2;
  677. stbds_string_arena string;
  678. stbds_hash_bucket *storage; // not a separate allocation, just 64-byte aligned storage after this struct
  679. } stbds_hash_index;
  680. #define STBDS_INDEX_EMPTY -1
  681. #define STBDS_INDEX_DELETED -2
  682. #define STBDS_INDEX_IN_USE(x) ((x) >= 0)
  683. #define STBDS_HASH_EMPTY 0
  684. #define STBDS_HASH_DELETED 1
  685. static size_t stbds_hash_seed=0x31415926;
  686. void stbds_rand_seed(size_t seed)
  687. {
  688. stbds_hash_seed = seed;
  689. }
  690. #define stbds_load_32_or_64(var, temp, v32, v64_hi, v64_lo) \
  691. temp = v64_lo ^ v32, temp <<= 16, temp <<= 16, temp >>= 16, temp >>= 16, /* discard if 32-bit */ \
  692. var = v64_hi, var <<= 16, var <<= 16, /* discard if 32-bit */ \
  693. var ^= temp ^ v32
  694. #define STBDS_SIZE_T_BITS ((sizeof (size_t)) * 8)
  695. static size_t stbds_probe_position(size_t hash, size_t slot_count, size_t slot_log2)
  696. {
  697. size_t pos;
  698. STBDS_NOTUSED(slot_log2);
  699. pos = hash & (slot_count-1);
  700. #ifdef STBDS_INTERNAL_BUCKET_START
  701. pos &= ~STBDS_BUCKET_MASK;
  702. #endif
  703. return pos;
  704. }
  705. static size_t stbds_log2(size_t slot_count)
  706. {
  707. size_t n=0;
  708. while (slot_count > 1) {
  709. slot_count >>= 1;
  710. ++n;
  711. }
  712. return n;
  713. }
  714. static stbds_hash_index *stbds_make_hash_index(size_t slot_count, stbds_hash_index *ot)
  715. {
  716. stbds_hash_index *t;
  717. t = (stbds_hash_index *) STBDS_REALLOC(NULL,0,(slot_count >> STBDS_BUCKET_SHIFT) * sizeof(stbds_hash_bucket) + sizeof(stbds_hash_index) + STBDS_CACHE_LINE_SIZE-1);
  718. t->storage = (stbds_hash_bucket *) STBDS_ALIGN_FWD((size_t) (t+1), STBDS_CACHE_LINE_SIZE);
  719. t->slot_count = slot_count;
  720. t->slot_count_log2 = stbds_log2(slot_count);
  721. t->tombstone_count = 0;
  722. t->used_count = 0;
  723. #if 0 // A1
  724. t->used_count_threshold = slot_count*12/16; // if 12/16th of table is occupied, grow
  725. t->tombstone_count_threshold = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild
  726. t->used_count_shrink_threshold = slot_count* 4/16; // if table is only 4/16th full, shrink
  727. #elif 1 // A2
  728. //t->used_count_threshold = slot_count*12/16; // if 12/16th of table is occupied, grow
  729. //t->tombstone_count_threshold = slot_count* 3/16; // if tombstones are 3/16th of table, rebuild
  730. //t->used_count_shrink_threshold = slot_count* 4/16; // if table is only 4/16th full, shrink
  731. // compute without overflowing
  732. t->used_count_threshold = slot_count - (slot_count>>2);
  733. t->tombstone_count_threshold = (slot_count>>3) + (slot_count>>4);
  734. t->used_count_shrink_threshold = slot_count >> 2;
  735. #elif 0 // B1
  736. t->used_count_threshold = slot_count*13/16; // if 13/16th of table is occupied, grow
  737. t->tombstone_count_threshold = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild
  738. t->used_count_shrink_threshold = slot_count* 5/16; // if table is only 5/16th full, shrink
  739. #else // C1
  740. t->used_count_threshold = slot_count*14/16; // if 14/16th of table is occupied, grow
  741. t->tombstone_count_threshold = slot_count* 2/16; // if tombstones are 2/16th of table, rebuild
  742. t->used_count_shrink_threshold = slot_count* 6/16; // if table is only 6/16th full, shrink
  743. #endif
  744. // Following statistics were measured on a Core i7-6700 @ 4.00Ghz, compiled with clang 7.0.1 -O2
  745. // Note that the larger tables have high variance as they were run fewer times
  746. // A1 A2 B1 C1
  747. // 0.10ms : 0.10ms : 0.10ms : 0.11ms : 2,000 inserts creating 2K table
  748. // 0.96ms : 0.95ms : 0.97ms : 1.04ms : 20,000 inserts creating 20K table
  749. // 14.48ms : 14.46ms : 10.63ms : 11.00ms : 200,000 inserts creating 200K table
  750. // 195.74ms : 196.35ms : 203.69ms : 214.92ms : 2,000,000 inserts creating 2M table
  751. // 2193.88ms : 2209.22ms : 2285.54ms : 2437.17ms : 20,000,000 inserts creating 20M table
  752. // 65.27ms : 53.77ms : 65.33ms : 65.47ms : 500,000 inserts & deletes in 2K table
  753. // 72.78ms : 62.45ms : 71.95ms : 72.85ms : 500,000 inserts & deletes in 20K table
  754. // 89.47ms : 77.72ms : 96.49ms : 96.75ms : 500,000 inserts & deletes in 200K table
  755. // 97.58ms : 98.14ms : 97.18ms : 97.53ms : 500,000 inserts & deletes in 2M table
  756. // 118.61ms : 119.62ms : 120.16ms : 118.86ms : 500,000 inserts & deletes in 20M table
  757. // 192.11ms : 194.39ms : 196.38ms : 195.73ms : 500,000 inserts & deletes in 200M table
  758. if (slot_count <= STBDS_BUCKET_LENGTH)
  759. t->used_count_shrink_threshold = 0;
  760. // to avoid infinite loop, we need to guarantee that at least one slot is empty and will terminate probes
  761. STBDS_ASSERT(t->used_count_threshold + t->tombstone_count_threshold < t->slot_count);
  762. STBDS_STATS(++stbds_hash_alloc);
  763. if (ot) {
  764. t->string = ot->string;
  765. // reuse old seed so we can reuse old hashes so below "copy out old data" doesn't do any hashing
  766. t->seed = ot->seed;
  767. } else {
  768. size_t a,b,temp;
  769. memset(&t->string, 0, sizeof(t->string));
  770. t->seed = stbds_hash_seed;
  771. // LCG
  772. // in 32-bit, a = 2147001325 b = 715136305
  773. // in 64-bit, a = 2862933555777941757 b = 3037000493
  774. stbds_load_32_or_64(a,temp, 2147001325, 0x27bb2ee6, 0x87b0b0fd);
  775. stbds_load_32_or_64(b,temp, 715136305, 0, 0xb504f32d);
  776. stbds_hash_seed = stbds_hash_seed * a + b;
  777. }
  778. {
  779. size_t i,j;
  780. for (i=0; i < slot_count >> STBDS_BUCKET_SHIFT; ++i) {
  781. stbds_hash_bucket *b = &t->storage[i];
  782. for (j=0; j < STBDS_BUCKET_LENGTH; ++j)
  783. b->hash[j] = STBDS_HASH_EMPTY;
  784. for (j=0; j < STBDS_BUCKET_LENGTH; ++j)
  785. b->index[j] = STBDS_INDEX_EMPTY;
  786. }
  787. }
  788. // copy out the old data, if any
  789. if (ot) {
  790. size_t i,j;
  791. t->used_count = ot->used_count;
  792. for (i=0; i < ot->slot_count >> STBDS_BUCKET_SHIFT; ++i) {
  793. stbds_hash_bucket *ob = &ot->storage[i];
  794. for (j=0; j < STBDS_BUCKET_LENGTH; ++j) {
  795. if (STBDS_INDEX_IN_USE(ob->index[j])) {
  796. size_t hash = ob->hash[j];
  797. size_t pos = stbds_probe_position(hash, t->slot_count, t->slot_count_log2);
  798. size_t step = STBDS_BUCKET_LENGTH;
  799. STBDS_STATS(++stbds_rehash_items);
  800. for (;;) {
  801. size_t limit,z;
  802. stbds_hash_bucket *bucket;
  803. bucket = &t->storage[pos >> STBDS_BUCKET_SHIFT];
  804. STBDS_STATS(++stbds_rehash_probes);
  805. for (z=pos & STBDS_BUCKET_MASK; z < STBDS_BUCKET_LENGTH; ++z) {
  806. if (bucket->hash[z] == 0) {
  807. bucket->hash[z] = hash;
  808. bucket->index[z] = ob->index[j];
  809. goto done;
  810. }
  811. }
  812. limit = pos & STBDS_BUCKET_MASK;
  813. for (z = 0; z < limit; ++z) {
  814. if (bucket->hash[z] == 0) {
  815. bucket->hash[z] = hash;
  816. bucket->index[z] = ob->index[j];
  817. goto done;
  818. }
  819. }
  820. pos += step; // quadratic probing
  821. step += STBDS_BUCKET_LENGTH;
  822. pos &= (t->slot_count-1);
  823. }
  824. }
  825. done:
  826. ;
  827. }
  828. }
  829. }
  830. return t;
  831. }
  832. #define STBDS_ROTATE_LEFT(val, n) (((val) << (n)) | ((val) >> (STBDS_SIZE_T_BITS - (n))))
  833. #define STBDS_ROTATE_RIGHT(val, n) (((val) >> (n)) | ((val) << (STBDS_SIZE_T_BITS - (n))))
  834. size_t stbds_hash_string(char *str, size_t seed)
  835. {
  836. size_t hash = seed;
  837. while (*str)
  838. hash = STBDS_ROTATE_LEFT(hash, 9) + (unsigned char) *str++;
  839. // Thomas Wang 64-to-32 bit mix function, hopefully also works in 32 bits
  840. hash ^= seed;
  841. hash = (~hash) + (hash << 18);
  842. hash ^= hash ^ STBDS_ROTATE_RIGHT(hash,31);
  843. hash = hash * 21;
  844. hash ^= hash ^ STBDS_ROTATE_RIGHT(hash,11);
  845. hash += (hash << 6);
  846. hash ^= STBDS_ROTATE_RIGHT(hash,22);
  847. return hash+seed;
  848. }
  849. #ifdef STBDS_SIPHASH_2_4
  850. #define STBDS_SIPHASH_C_ROUNDS 2
  851. #define STBDS_SIPHASH_D_ROUNDS 4
  852. typedef int STBDS_SIPHASH_2_4_can_only_be_used_in_64_bit_builds[sizeof(size_t) == 8 ? 1 : -1];
  853. #endif
  854. #ifndef STBDS_SIPHASH_C_ROUNDS
  855. #define STBDS_SIPHASH_C_ROUNDS 1
  856. #endif
  857. #ifndef STBDS_SIPHASH_D_ROUNDS
  858. #define STBDS_SIPHASH_D_ROUNDS 1
  859. #endif
  860. #ifdef _MSC_VER
  861. #pragma warning(push)
  862. #pragma warning(disable:4127) // conditional expression is constant, for do..while(0) and sizeof()==
  863. #endif
  864. static size_t stbds_siphash_bytes(void *p, size_t len, size_t seed)
  865. {
  866. unsigned char *d = (unsigned char *) p;
  867. size_t i,j;
  868. size_t v0,v1,v2,v3, data;
  869. // hash that works on 32- or 64-bit registers without knowing which we have
  870. // (computes different results on 32-bit and 64-bit platform)
  871. // derived from siphash, but on 32-bit platforms very different as it uses 4 32-bit state not 4 64-bit
  872. v0 = ((((size_t) 0x736f6d65 << 16) << 16) + 0x70736575) ^ seed;
  873. v1 = ((((size_t) 0x646f7261 << 16) << 16) + 0x6e646f6d) ^ ~seed;
  874. v2 = ((((size_t) 0x6c796765 << 16) << 16) + 0x6e657261) ^ seed;
  875. v3 = ((((size_t) 0x74656462 << 16) << 16) + 0x79746573) ^ ~seed;
  876. #ifdef STBDS_TEST_SIPHASH_2_4
  877. // hardcoded with key material in the siphash test vectors
  878. v0 ^= 0x0706050403020100ull ^ seed;
  879. v1 ^= 0x0f0e0d0c0b0a0908ull ^ ~seed;
  880. v2 ^= 0x0706050403020100ull ^ seed;
  881. v3 ^= 0x0f0e0d0c0b0a0908ull ^ ~seed;
  882. #endif
  883. #define STBDS_SIPROUND() \
  884. do { \
  885. v0 += v1; v1 = STBDS_ROTATE_LEFT(v1, 13); v1 ^= v0; v0 = STBDS_ROTATE_LEFT(v0,STBDS_SIZE_T_BITS/2); \
  886. v2 += v3; v3 = STBDS_ROTATE_LEFT(v3, 16); v3 ^= v2; \
  887. v2 += v1; v1 = STBDS_ROTATE_LEFT(v1, 17); v1 ^= v2; v2 = STBDS_ROTATE_LEFT(v2,STBDS_SIZE_T_BITS/2); \
  888. v0 += v3; v3 = STBDS_ROTATE_LEFT(v3, 21); v3 ^= v0; \
  889. } while (0)
  890. for (i=0; i+sizeof(size_t) <= len; i += sizeof(size_t), d += sizeof(size_t)) {
  891. data = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);
  892. data |= (size_t) (d[4] | (d[5] << 8) | (d[6] << 16) | (d[7] << 24)) << 16 << 16; // discarded if size_t == 4
  893. v3 ^= data;
  894. for (j=0; j < STBDS_SIPHASH_C_ROUNDS; ++j)
  895. STBDS_SIPROUND();
  896. v0 ^= data;
  897. }
  898. data = len << (STBDS_SIZE_T_BITS-8);
  899. switch (len - i) {
  900. case 7: data |= ((size_t) d[6] << 24) << 24; // fall through
  901. case 6: data |= ((size_t) d[5] << 20) << 20; // fall through
  902. case 5: data |= ((size_t) d[4] << 16) << 16; // fall through
  903. case 4: data |= (d[3] << 24); // fall through
  904. case 3: data |= (d[2] << 16); // fall through
  905. case 2: data |= (d[1] << 8); // fall through
  906. case 1: data |= d[0]; // fall through
  907. case 0: break;
  908. }
  909. v3 ^= data;
  910. for (j=0; j < STBDS_SIPHASH_C_ROUNDS; ++j)
  911. STBDS_SIPROUND();
  912. v0 ^= data;
  913. v2 ^= 0xff;
  914. for (j=0; j < STBDS_SIPHASH_D_ROUNDS; ++j)
  915. STBDS_SIPROUND();
  916. #ifdef STBDS_SIPHASH_2_4
  917. return v0^v1^v2^v3;
  918. #else
  919. return v1^v2^v3; // slightly stronger since v0^v3 in above cancels out final round operation? I tweeted at the authors of SipHash about this but they didn't reply
  920. #endif
  921. }
  922. size_t stbds_hash_bytes(void *p, size_t len, size_t seed)
  923. {
  924. #ifdef STBDS_SIPHASH_2_4
  925. return stbds_siphash_bytes(p,len,seed);
  926. #else
  927. unsigned char *d = (unsigned char *) p;
  928. if (len == 4) {
  929. unsigned int hash = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);
  930. #if 0
  931. // HASH32-A Bob Jenkin's hash function w/o large constants
  932. hash ^= seed;
  933. hash -= (hash<<6);
  934. hash ^= (hash>>17);
  935. hash -= (hash<<9);
  936. hash ^= seed;
  937. hash ^= (hash<<4);
  938. hash -= (hash<<3);
  939. hash ^= (hash<<10);
  940. hash ^= (hash>>15);
  941. #elif 1
  942. // HASH32-BB Bob Jenkin's presumably-accidental version of Thomas Wang hash with rotates turned into shifts.
  943. // Note that converting these back to rotates makes it run a lot slower, presumably due to collisions, so I'm
  944. // not really sure what's going on.
  945. hash ^= seed;
  946. hash = (hash ^ 61) ^ (hash >> 16);
  947. hash = hash + (hash << 3);
  948. hash = hash ^ (hash >> 4);
  949. hash = hash * 0x27d4eb2d;
  950. hash ^= seed;
  951. hash = hash ^ (hash >> 15);
  952. #else // HASH32-C - Murmur3
  953. hash ^= seed;
  954. hash *= 0xcc9e2d51;
  955. hash = (hash << 17) | (hash >> 15);
  956. hash *= 0x1b873593;
  957. hash ^= seed;
  958. hash = (hash << 19) | (hash >> 13);
  959. hash = hash*5 + 0xe6546b64;
  960. hash ^= hash >> 16;
  961. hash *= 0x85ebca6b;
  962. hash ^= seed;
  963. hash ^= hash >> 13;
  964. hash *= 0xc2b2ae35;
  965. hash ^= hash >> 16;
  966. #endif
  967. // Following statistics were measured on a Core i7-6700 @ 4.00Ghz, compiled with clang 7.0.1 -O2
  968. // Note that the larger tables have high variance as they were run fewer times
  969. // HASH32-A // HASH32-BB // HASH32-C
  970. // 0.10ms // 0.10ms // 0.10ms : 2,000 inserts creating 2K table
  971. // 0.96ms // 0.95ms // 0.99ms : 20,000 inserts creating 20K table
  972. // 14.69ms // 14.43ms // 14.97ms : 200,000 inserts creating 200K table
  973. // 199.99ms // 195.36ms // 202.05ms : 2,000,000 inserts creating 2M table
  974. // 2234.84ms // 2187.74ms // 2240.38ms : 20,000,000 inserts creating 20M table
  975. // 55.68ms // 53.72ms // 57.31ms : 500,000 inserts & deletes in 2K table
  976. // 63.43ms // 61.99ms // 65.73ms : 500,000 inserts & deletes in 20K table
  977. // 80.04ms // 77.96ms // 81.83ms : 500,000 inserts & deletes in 200K table
  978. // 100.42ms // 97.40ms // 102.39ms : 500,000 inserts & deletes in 2M table
  979. // 119.71ms // 120.59ms // 121.63ms : 500,000 inserts & deletes in 20M table
  980. // 185.28ms // 195.15ms // 187.74ms : 500,000 inserts & deletes in 200M table
  981. // 15.58ms // 14.79ms // 15.52ms : 200,000 inserts creating 200K table with varying key spacing
  982. return (((size_t) hash << 16 << 16) | hash) ^ seed;
  983. } else if (len == 8 && sizeof(size_t) == 8) {
  984. size_t hash = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);
  985. hash |= (size_t) (d[4] | (d[5] << 8) | (d[6] << 16) | (d[7] << 24)) << 16 << 16; // avoid warning if size_t == 4
  986. hash ^= seed;
  987. hash = (~hash) + (hash << 21);
  988. hash ^= STBDS_ROTATE_RIGHT(hash,24);
  989. hash *= 265;
  990. hash ^= STBDS_ROTATE_RIGHT(hash,14);
  991. hash ^= seed;
  992. hash *= 21;
  993. hash ^= STBDS_ROTATE_RIGHT(hash,28);
  994. hash += (hash << 31);
  995. hash = (~hash) + (hash << 18);
  996. return hash;
  997. } else {
  998. return stbds_siphash_bytes(p,len,seed);
  999. }
  1000. #endif
  1001. }
  1002. #ifdef _MSC_VER
  1003. #pragma warning(pop)
  1004. #endif
  1005. static int stbds_is_key_equal(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode, size_t i)
  1006. {
  1007. if (mode >= STBDS_HM_STRING)
  1008. return 0==strcmp((char *) key, * (char **) ((char *) a + elemsize*i + keyoffset));
  1009. else
  1010. return 0==memcmp(key, (char *) a + elemsize*i + keyoffset, keysize);
  1011. }
  1012. #define STBDS_HASH_TO_ARR(x,elemsize) ((char*) (x) - (elemsize))
  1013. #define STBDS_ARR_TO_HASH(x,elemsize) ((char*) (x) + (elemsize))
  1014. #define stbds_hash_table(a) ((stbds_hash_index *) stbds_header(a)->hash_table)
  1015. void stbds_hmfree_func(void *a, size_t elemsize)
  1016. {
  1017. if (a == NULL) return;
  1018. if (stbds_hash_table(a) != NULL) {
  1019. if (stbds_hash_table(a)->string.mode == STBDS_SH_STRDUP) {
  1020. size_t i;
  1021. // skip 0th element, which is default
  1022. for (i=1; i < stbds_header(a)->length; ++i)
  1023. STBDS_FREE(NULL, *(char**) ((char *) a + elemsize*i));
  1024. }
  1025. stbds_strreset(&stbds_hash_table(a)->string);
  1026. }
  1027. STBDS_FREE(NULL, stbds_header(a)->hash_table);
  1028. STBDS_FREE(NULL, stbds_header(a));
  1029. }
  1030. static ptrdiff_t stbds_hm_find_slot(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode)
  1031. {
  1032. void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);
  1033. stbds_hash_index *table = stbds_hash_table(raw_a);
  1034. size_t hash = mode >= STBDS_HM_STRING ? stbds_hash_string((char*)key,table->seed) : stbds_hash_bytes(key, keysize,table->seed);
  1035. size_t step = STBDS_BUCKET_LENGTH;
  1036. size_t limit,i;
  1037. size_t pos;
  1038. stbds_hash_bucket *bucket;
  1039. if (hash < 2) hash += 2; // stored hash values are forbidden from being 0, so we can detect empty slots
  1040. pos = stbds_probe_position(hash, table->slot_count, table->slot_count_log2);
  1041. for (;;) {
  1042. STBDS_STATS(++stbds_hash_probes);
  1043. bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];
  1044. // start searching from pos to end of bucket, this should help performance on small hash tables that fit in cache
  1045. for (i=pos & STBDS_BUCKET_MASK; i < STBDS_BUCKET_LENGTH; ++i) {
  1046. if (bucket->hash[i] == hash) {
  1047. if (stbds_is_key_equal(a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {
  1048. return (pos & ~STBDS_BUCKET_MASK)+i;
  1049. }
  1050. } else if (bucket->hash[i] == STBDS_HASH_EMPTY) {
  1051. return -1;
  1052. }
  1053. }
  1054. // search from beginning of bucket to pos
  1055. limit = pos & STBDS_BUCKET_MASK;
  1056. for (i = 0; i < limit; ++i) {
  1057. if (bucket->hash[i] == hash) {
  1058. if (stbds_is_key_equal(a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {
  1059. return (pos & ~STBDS_BUCKET_MASK)+i;
  1060. }
  1061. } else if (bucket->hash[i] == STBDS_HASH_EMPTY) {
  1062. return -1;
  1063. }
  1064. }
  1065. // quadratic probing
  1066. pos += step;
  1067. step += STBDS_BUCKET_LENGTH;
  1068. pos &= (table->slot_count-1);
  1069. }
  1070. /* NOTREACHED */
  1071. }
  1072. void * stbds_hmget_key_ts(void *a, size_t elemsize, void *key, size_t keysize, ptrdiff_t *temp, int mode)
  1073. {
  1074. size_t keyoffset = 0;
  1075. if (a == NULL) {
  1076. // make it non-empty so we can return a temp
  1077. a = stbds_arrgrowf(0, elemsize, 0, 1);
  1078. stbds_header(a)->length += 1;
  1079. memset(a, 0, elemsize);
  1080. *temp = STBDS_INDEX_EMPTY;
  1081. // adjust a to point after the default element
  1082. return STBDS_ARR_TO_HASH(a,elemsize);
  1083. } else {
  1084. stbds_hash_index *table;
  1085. void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);
  1086. // adjust a to point to the default element
  1087. table = (stbds_hash_index *) stbds_header(raw_a)->hash_table;
  1088. if (table == 0) {
  1089. *temp = -1;
  1090. } else {
  1091. ptrdiff_t slot = stbds_hm_find_slot(a, elemsize, key, keysize, keyoffset, mode);
  1092. if (slot < 0) {
  1093. *temp = STBDS_INDEX_EMPTY;
  1094. } else {
  1095. stbds_hash_bucket *b = &table->storage[slot >> STBDS_BUCKET_SHIFT];
  1096. *temp = b->index[slot & STBDS_BUCKET_MASK];
  1097. }
  1098. }
  1099. return a;
  1100. }
  1101. }
  1102. void * stbds_hmget_key(void *a, size_t elemsize, void *key, size_t keysize, int mode)
  1103. {
  1104. ptrdiff_t temp;
  1105. void *p = stbds_hmget_key_ts(a, elemsize, key, keysize, &temp, mode);
  1106. stbds_temp(STBDS_HASH_TO_ARR(p,elemsize)) = temp;
  1107. return p;
  1108. }
  1109. void * stbds_hmput_default(void *a, size_t elemsize)
  1110. {
  1111. // three cases:
  1112. // a is NULL <- allocate
  1113. // a has a hash table but no entries, because of shmode <- grow
  1114. // a has entries <- do nothing
  1115. if (a == NULL || stbds_header(STBDS_HASH_TO_ARR(a,elemsize))->length == 0) {
  1116. a = stbds_arrgrowf(a ? STBDS_HASH_TO_ARR(a,elemsize) : NULL, elemsize, 0, 1);
  1117. stbds_header(a)->length += 1;
  1118. memset(a, 0, elemsize);
  1119. a=STBDS_ARR_TO_HASH(a,elemsize);
  1120. }
  1121. return a;
  1122. }
  1123. static char *stbds_strdup(char *str);
  1124. void *stbds_hmput_key(void *a, size_t elemsize, void *key, size_t keysize, int mode)
  1125. {
  1126. size_t keyoffset=0;
  1127. void *raw_a;
  1128. stbds_hash_index *table;
  1129. if (a == NULL) {
  1130. a = stbds_arrgrowf(0, elemsize, 0, 1);
  1131. memset(a, 0, elemsize);
  1132. stbds_header(a)->length += 1;
  1133. // adjust a to point AFTER the default element
  1134. a = STBDS_ARR_TO_HASH(a,elemsize);
  1135. }
  1136. // adjust a to point to the default element
  1137. raw_a = a;
  1138. a = STBDS_HASH_TO_ARR(a,elemsize);
  1139. table = (stbds_hash_index *) stbds_header(a)->hash_table;
  1140. if (table == NULL || table->used_count >= table->used_count_threshold) {
  1141. stbds_hash_index *nt;
  1142. size_t slot_count;
  1143. slot_count = (table == NULL) ? STBDS_BUCKET_LENGTH : table->slot_count*2;
  1144. nt = stbds_make_hash_index(slot_count, table);
  1145. if (table)
  1146. STBDS_FREE(NULL, table);
  1147. else
  1148. nt->string.mode = mode >= STBDS_HM_STRING ? STBDS_SH_DEFAULT : 0;
  1149. stbds_header(a)->hash_table = table = nt;
  1150. STBDS_STATS(++stbds_hash_grow);
  1151. }
  1152. // we iterate hash table explicitly because we want to track if we saw a tombstone
  1153. {
  1154. size_t hash = mode >= STBDS_HM_STRING ? stbds_hash_string((char*)key,table->seed) : stbds_hash_bytes(key, keysize,table->seed);
  1155. size_t step = STBDS_BUCKET_LENGTH;
  1156. size_t pos;
  1157. ptrdiff_t tombstone = -1;
  1158. stbds_hash_bucket *bucket;
  1159. // stored hash values are forbidden from being 0, so we can detect empty slots to early out quickly
  1160. if (hash < 2) hash += 2;
  1161. pos = stbds_probe_position(hash, table->slot_count, table->slot_count_log2);
  1162. for (;;) {
  1163. size_t limit, i;
  1164. STBDS_STATS(++stbds_hash_probes);
  1165. bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];
  1166. // start searching from pos to end of bucket
  1167. for (i=pos & STBDS_BUCKET_MASK; i < STBDS_BUCKET_LENGTH; ++i) {
  1168. if (bucket->hash[i] == hash) {
  1169. if (stbds_is_key_equal(raw_a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {
  1170. stbds_temp(a) = bucket->index[i];
  1171. if (mode >= STBDS_HM_STRING)
  1172. stbds_temp_key(a) = * (char **) ((char *) raw_a + elemsize*bucket->index[i] + keyoffset);
  1173. return STBDS_ARR_TO_HASH(a,elemsize);
  1174. }
  1175. } else if (bucket->hash[i] == 0) {
  1176. pos = (pos & ~STBDS_BUCKET_MASK) + i;
  1177. goto found_empty_slot;
  1178. } else if (tombstone < 0) {
  1179. if (bucket->index[i] == STBDS_INDEX_DELETED)
  1180. tombstone = (ptrdiff_t) ((pos & ~STBDS_BUCKET_MASK) + i);
  1181. }
  1182. }
  1183. // search from beginning of bucket to pos
  1184. limit = pos & STBDS_BUCKET_MASK;
  1185. for (i = 0; i < limit; ++i) {
  1186. if (bucket->hash[i] == hash) {
  1187. if (stbds_is_key_equal(raw_a, elemsize, key, keysize, keyoffset, mode, bucket->index[i])) {
  1188. stbds_temp(a) = bucket->index[i];
  1189. return STBDS_ARR_TO_HASH(a,elemsize);
  1190. }
  1191. } else if (bucket->hash[i] == 0) {
  1192. pos = (pos & ~STBDS_BUCKET_MASK) + i;
  1193. goto found_empty_slot;
  1194. } else if (tombstone < 0) {
  1195. if (bucket->index[i] == STBDS_INDEX_DELETED)
  1196. tombstone = (ptrdiff_t) ((pos & ~STBDS_BUCKET_MASK) + i);
  1197. }
  1198. }
  1199. // quadratic probing
  1200. pos += step;
  1201. step += STBDS_BUCKET_LENGTH;
  1202. pos &= (table->slot_count-1);
  1203. }
  1204. found_empty_slot:
  1205. if (tombstone >= 0) {
  1206. pos = tombstone;
  1207. --table->tombstone_count;
  1208. }
  1209. ++table->used_count;
  1210. {
  1211. ptrdiff_t i = (ptrdiff_t) stbds_arrlen(a);
  1212. // we want to do stbds_arraddn(1), but we can't use the macros since we don't have something of the right type
  1213. if ((size_t) i+1 > stbds_arrcap(a))
  1214. *(void **) &a = stbds_arrgrowf(a, elemsize, 1, 0);
  1215. raw_a = STBDS_ARR_TO_HASH(a,elemsize);
  1216. STBDS_ASSERT((size_t) i+1 <= stbds_arrcap(a));
  1217. stbds_header(a)->length = i+1;
  1218. bucket = &table->storage[pos >> STBDS_BUCKET_SHIFT];
  1219. bucket->hash[pos & STBDS_BUCKET_MASK] = hash;
  1220. bucket->index[pos & STBDS_BUCKET_MASK] = i-1;
  1221. stbds_temp(a) = i-1;
  1222. switch (table->string.mode) {
  1223. case STBDS_SH_STRDUP: stbds_temp_key(a) = *(char **) ((char *) a + elemsize*i) = stbds_strdup((char*) key); break;
  1224. case STBDS_SH_ARENA: stbds_temp_key(a) = *(char **) ((char *) a + elemsize*i) = stbds_stralloc(&table->string, (char*)key); break;
  1225. case STBDS_SH_DEFAULT: stbds_temp_key(a) = *(char **) ((char *) a + elemsize*i) = (char *) key; break;
  1226. default: memcpy((char *) a + elemsize*i, key, keysize); break;
  1227. }
  1228. }
  1229. return STBDS_ARR_TO_HASH(a,elemsize);
  1230. }
  1231. }
  1232. void * stbds_shmode_func(size_t elemsize, int mode)
  1233. {
  1234. void *a = stbds_arrgrowf(0, elemsize, 0, 1);
  1235. stbds_hash_index *h;
  1236. memset(a, 0, elemsize);
  1237. stbds_header(a)->length = 1;
  1238. stbds_header(a)->hash_table = h = (stbds_hash_index *) stbds_make_hash_index(STBDS_BUCKET_LENGTH, NULL);
  1239. h->string.mode = (unsigned char) mode;
  1240. return STBDS_ARR_TO_HASH(a,elemsize);
  1241. }
  1242. void * stbds_hmdel_key(void *a, size_t elemsize, void *key, size_t keysize, size_t keyoffset, int mode)
  1243. {
  1244. if (a == NULL) {
  1245. return 0;
  1246. } else {
  1247. stbds_hash_index *table;
  1248. void *raw_a = STBDS_HASH_TO_ARR(a,elemsize);
  1249. table = (stbds_hash_index *) stbds_header(raw_a)->hash_table;
  1250. stbds_temp(raw_a) = 0;
  1251. if (table == 0) {
  1252. return a;
  1253. } else {
  1254. ptrdiff_t slot;
  1255. slot = stbds_hm_find_slot(a, elemsize, key, keysize, keyoffset, mode);
  1256. if (slot < 0)
  1257. return a;
  1258. else {
  1259. stbds_hash_bucket *b = &table->storage[slot >> STBDS_BUCKET_SHIFT];
  1260. int i = slot & STBDS_BUCKET_MASK;
  1261. ptrdiff_t old_index = b->index[i];
  1262. 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'
  1263. STBDS_ASSERT(slot < (ptrdiff_t) table->slot_count);
  1264. --table->used_count;
  1265. ++table->tombstone_count;
  1266. stbds_temp(raw_a) = 1;
  1267. STBDS_ASSERT(table->used_count >= 0);
  1268. //STBDS_ASSERT(table->tombstone_count < table->slot_count/4);
  1269. b->hash[i] = STBDS_HASH_DELETED;
  1270. b->index[i] = STBDS_INDEX_DELETED;
  1271. if (mode == STBDS_HM_STRING && table->string.mode == STBDS_SH_STRDUP)
  1272. STBDS_FREE(NULL, *(char**) ((char *) a+elemsize*old_index));
  1273. // if indices are the same, memcpy is a no-op, but back-pointer-fixup will fail, so skip
  1274. if (old_index != final_index) {
  1275. // swap delete
  1276. memmove((char*) a + elemsize*old_index, (char*) a + elemsize*final_index, elemsize);
  1277. // now find the slot for the last element
  1278. if (mode == STBDS_HM_STRING)
  1279. slot = stbds_hm_find_slot(a, elemsize, *(char**) ((char *) a+elemsize*old_index + keyoffset), keysize, keyoffset, mode);
  1280. else
  1281. slot = stbds_hm_find_slot(a, elemsize, (char* ) a+elemsize*old_index + keyoffset, keysize, keyoffset, mode);
  1282. STBDS_ASSERT(slot >= 0);
  1283. b = &table->storage[slot >> STBDS_BUCKET_SHIFT];
  1284. i = slot & STBDS_BUCKET_MASK;
  1285. STBDS_ASSERT(b->index[i] == final_index);
  1286. b->index[i] = old_index;
  1287. }
  1288. stbds_header(raw_a)->length -= 1;
  1289. if (table->used_count < table->used_count_shrink_threshold && table->slot_count > STBDS_BUCKET_LENGTH) {
  1290. stbds_header(raw_a)->hash_table = stbds_make_hash_index(table->slot_count>>1, table);
  1291. STBDS_FREE(NULL, table);
  1292. STBDS_STATS(++stbds_hash_shrink);
  1293. } else if (table->tombstone_count > table->tombstone_count_threshold) {
  1294. stbds_header(raw_a)->hash_table = stbds_make_hash_index(table->slot_count , table);
  1295. STBDS_FREE(NULL, table);
  1296. STBDS_STATS(++stbds_hash_rebuild);
  1297. }
  1298. return a;
  1299. }
  1300. }
  1301. }
  1302. /* NOTREACHED */
  1303. }
  1304. static char *stbds_strdup(char *str)
  1305. {
  1306. // to keep replaceable allocator simple, we don't want to use strdup.
  1307. // rolling our own also avoids problem of strdup vs _strdup
  1308. size_t len = strlen(str)+1;
  1309. char *p = (char*) STBDS_REALLOC(NULL, 0, len);
  1310. memmove(p, str, len);
  1311. return p;
  1312. }
  1313. #ifndef STBDS_STRING_ARENA_BLOCKSIZE_MIN
  1314. #define STBDS_STRING_ARENA_BLOCKSIZE_MIN 512u
  1315. #endif
  1316. #ifndef STBDS_STRING_ARENA_BLOCKSIZE_MAX
  1317. #define STBDS_STRING_ARENA_BLOCKSIZE_MAX (1u<<20)
  1318. #endif
  1319. char *stbds_stralloc(stbds_string_arena *a, char *str)
  1320. {
  1321. char *p;
  1322. size_t len = strlen(str)+1;
  1323. if (len > a->remaining) {
  1324. // compute the next blocksize
  1325. size_t blocksize = a->block;
  1326. // size is 512, 512, 1024, 1024, 2048, 2048, 4096, 4096, etc., so that
  1327. // there are log(SIZE) allocations to free when we destroy the table
  1328. blocksize = (size_t) (STBDS_STRING_ARENA_BLOCKSIZE_MIN) << (blocksize>>1);
  1329. // if size is under 1M, advance to next blocktype
  1330. if (blocksize < (size_t)(STBDS_STRING_ARENA_BLOCKSIZE_MAX))
  1331. ++a->block;
  1332. if (len > blocksize) {
  1333. // if string is larger than blocksize, then just allocate the full size.
  1334. // note that we still advance string_block so block size will continue
  1335. // increasing, so e.g. if somebody only calls this with 1000-long strings,
  1336. // eventually the arena will start doubling and handling those as well
  1337. stbds_string_block *sb = (stbds_string_block *) STBDS_REALLOC(NULL, 0, sizeof(*sb)-8 + len);
  1338. memmove(sb->storage, str, len);
  1339. if (a->storage) {
  1340. // insert it after the first element, so that we don't waste the space there
  1341. sb->next = a->storage->next;
  1342. a->storage->next = sb;
  1343. } else {
  1344. sb->next = 0;
  1345. a->storage = sb;
  1346. a->remaining = 0; // this is redundant, but good for clarity
  1347. }
  1348. return sb->storage;
  1349. } else {
  1350. stbds_string_block *sb = (stbds_string_block *) STBDS_REALLOC(NULL, 0, sizeof(*sb)-8 + blocksize);
  1351. sb->next = a->storage;
  1352. a->storage = sb;
  1353. a->remaining = blocksize;
  1354. }
  1355. }
  1356. STBDS_ASSERT(len <= a->remaining);
  1357. p = a->storage->storage + a->remaining - len;
  1358. a->remaining -= len;
  1359. memmove(p, str, len);
  1360. return p;
  1361. }
  1362. void stbds_strreset(stbds_string_arena *a)
  1363. {
  1364. stbds_string_block *x,*y;
  1365. x = a->storage;
  1366. while (x) {
  1367. y = x->next;
  1368. STBDS_FREE(NULL, x);
  1369. x = y;
  1370. }
  1371. memset(a, 0, sizeof(*a));
  1372. }
  1373. #endif
  1374. //////////////////////////////////////////////////////////////////////////////
  1375. //
  1376. // UNIT TESTS
  1377. //
  1378. #ifdef STBDS_UNIT_TESTS
  1379. #include <stdio.h>
  1380. #ifdef STBDS_ASSERT_WAS_UNDEFINED
  1381. #undef STBDS_ASSERT
  1382. #endif
  1383. #ifndef STBDS_ASSERT
  1384. #define STBDS_ASSERT assert
  1385. #include <assert.h>
  1386. #endif
  1387. typedef struct { int key,b,c,d; } stbds_struct;
  1388. typedef struct { int key[2],b,c,d; } stbds_struct2;
  1389. static char buffer[256];
  1390. char *strkey(int n)
  1391. {
  1392. #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)
  1393. sprintf_s(buffer, sizeof(buffer), "test_%d", n);
  1394. #else
  1395. sprintf(buffer, "test_%d", n);
  1396. #endif
  1397. return buffer;
  1398. }
  1399. void stbds_unit_tests(void)
  1400. {
  1401. #if defined(_MSC_VER) && _MSC_VER <= 1200 && defined(__cplusplus)
  1402. // VC6 C++ doesn't like the template<> trick on unnamed structures, so do nothing!
  1403. STBDS_ASSERT(0);
  1404. #else
  1405. const int testsize = 100000;
  1406. const int testsize2 = testsize/20;
  1407. int *arr=NULL;
  1408. struct { int key; int value; } *intmap = NULL;
  1409. struct { char *key; int value; } *strmap = NULL, s;
  1410. struct { stbds_struct key; int value; } *map = NULL;
  1411. stbds_struct *map2 = NULL;
  1412. stbds_struct2 *map3 = NULL;
  1413. stbds_string_arena sa = { 0 };
  1414. int key3[2] = { 1,2 };
  1415. ptrdiff_t temp;
  1416. int i,j;
  1417. STBDS_ASSERT(arrlen(arr)==0);
  1418. for (i=0; i < 20000; i += 50) {
  1419. for (j=0; j < i; ++j)
  1420. arrpush(arr,j);
  1421. arrfree(arr);
  1422. }
  1423. for (i=0; i < 4; ++i) {
  1424. arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);
  1425. arrdel(arr,i);
  1426. arrfree(arr);
  1427. arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);
  1428. arrdelswap(arr,i);
  1429. arrfree(arr);
  1430. }
  1431. for (i=0; i < 5; ++i) {
  1432. arrpush(arr,1); arrpush(arr,2); arrpush(arr,3); arrpush(arr,4);
  1433. stbds_arrins(arr,i,5);
  1434. STBDS_ASSERT(arr[i] == 5);
  1435. if (i < 4)
  1436. STBDS_ASSERT(arr[4] == 4);
  1437. arrfree(arr);
  1438. }
  1439. i = 1;
  1440. STBDS_ASSERT(hmgeti(intmap,i) == -1);
  1441. hmdefault(intmap, -2);
  1442. STBDS_ASSERT(hmgeti(intmap, i) == -1);
  1443. STBDS_ASSERT(hmget (intmap, i) == -2);
  1444. for (i=0; i < testsize; i+=2)
  1445. hmput(intmap, i, i*5);
  1446. for (i=0; i < testsize; i+=1) {
  1447. if (i & 1) STBDS_ASSERT(hmget(intmap, i) == -2 );
  1448. else STBDS_ASSERT(hmget(intmap, i) == i*5);
  1449. if (i & 1) STBDS_ASSERT(hmget_ts(intmap, i, temp) == -2 );
  1450. else STBDS_ASSERT(hmget_ts(intmap, i, temp) == i*5);
  1451. }
  1452. for (i=0; i < testsize; i+=2)
  1453. hmput(intmap, i, i*3);
  1454. for (i=0; i < testsize; i+=1)
  1455. if (i & 1) STBDS_ASSERT(hmget(intmap, i) == -2 );
  1456. else STBDS_ASSERT(hmget(intmap, i) == i*3);
  1457. for (i=2; i < testsize; i+=4)
  1458. hmdel(intmap, i); // delete half the entries
  1459. for (i=0; i < testsize; i+=1)
  1460. if (i & 3) STBDS_ASSERT(hmget(intmap, i) == -2 );
  1461. else STBDS_ASSERT(hmget(intmap, i) == i*3);
  1462. for (i=0; i < testsize; i+=1)
  1463. hmdel(intmap, i); // delete the rest of the entries
  1464. for (i=0; i < testsize; i+=1)
  1465. STBDS_ASSERT(hmget(intmap, i) == -2 );
  1466. hmfree(intmap);
  1467. for (i=0; i < testsize; i+=2)
  1468. hmput(intmap, i, i*3);
  1469. hmfree(intmap);
  1470. #if defined(__clang__) || defined(__GNUC__)
  1471. #ifndef __cplusplus
  1472. intmap = NULL;
  1473. hmput(intmap, 15, 7);
  1474. hmput(intmap, 11, 3);
  1475. hmput(intmap, 9, 5);
  1476. STBDS_ASSERT(hmget(intmap, 9) == 5);
  1477. STBDS_ASSERT(hmget(intmap, 11) == 3);
  1478. STBDS_ASSERT(hmget(intmap, 15) == 7);
  1479. #endif
  1480. #endif
  1481. for (i=0; i < testsize; ++i)
  1482. stralloc(&sa, strkey(i));
  1483. strreset(&sa);
  1484. {
  1485. s.key = "a", s.value = 1;
  1486. shputs(strmap, s);
  1487. STBDS_ASSERT(*strmap[0].key == 'a');
  1488. STBDS_ASSERT(strmap[0].key == s.key);
  1489. STBDS_ASSERT(strmap[0].value == s.value);
  1490. shfree(strmap);
  1491. }
  1492. {
  1493. s.key = "a", s.value = 1;
  1494. sh_new_strdup(strmap);
  1495. shputs(strmap, s);
  1496. STBDS_ASSERT(*strmap[0].key == 'a');
  1497. STBDS_ASSERT(strmap[0].key != s.key);
  1498. STBDS_ASSERT(strmap[0].value == s.value);
  1499. shfree(strmap);
  1500. }
  1501. {
  1502. s.key = "a", s.value = 1;
  1503. sh_new_arena(strmap);
  1504. shputs(strmap, s);
  1505. STBDS_ASSERT(*strmap[0].key == 'a');
  1506. STBDS_ASSERT(strmap[0].key != s.key);
  1507. STBDS_ASSERT(strmap[0].value == s.value);
  1508. shfree(strmap);
  1509. }
  1510. for (j=0; j < 2; ++j) {
  1511. STBDS_ASSERT(shgeti(strmap,"foo") == -1);
  1512. if (j == 0)
  1513. sh_new_strdup(strmap);
  1514. else
  1515. sh_new_arena(strmap);
  1516. STBDS_ASSERT(shgeti(strmap,"foo") == -1);
  1517. shdefault(strmap, -2);
  1518. STBDS_ASSERT(shgeti(strmap,"foo") == -1);
  1519. for (i=0; i < testsize; i+=2)
  1520. shput(strmap, strkey(i), i*3);
  1521. for (i=0; i < testsize; i+=1)
  1522. if (i & 1) STBDS_ASSERT(shget(strmap, strkey(i)) == -2 );
  1523. else STBDS_ASSERT(shget(strmap, strkey(i)) == i*3);
  1524. for (i=2; i < testsize; i+=4)
  1525. shdel(strmap, strkey(i)); // delete half the entries
  1526. for (i=0; i < testsize; i+=1)
  1527. if (i & 3) STBDS_ASSERT(shget(strmap, strkey(i)) == -2 );
  1528. else STBDS_ASSERT(shget(strmap, strkey(i)) == i*3);
  1529. for (i=0; i < testsize; i+=1)
  1530. shdel(strmap, strkey(i)); // delete the rest of the entries
  1531. for (i=0; i < testsize; i+=1)
  1532. STBDS_ASSERT(shget(strmap, strkey(i)) == -2 );
  1533. shfree(strmap);
  1534. }
  1535. {
  1536. struct { char *key; char value; } *hash = NULL;
  1537. char name[4] = "jen";
  1538. shput(hash, "bob" , 'h');
  1539. shput(hash, "sally" , 'e');
  1540. shput(hash, "fred" , 'l');
  1541. shput(hash, "jen" , 'x');
  1542. shput(hash, "doug" , 'o');
  1543. shput(hash, name , 'l');
  1544. shfree(hash);
  1545. }
  1546. for (i=0; i < testsize; i += 2) {
  1547. stbds_struct s = { i,i*2,i*3,i*4 };
  1548. hmput(map, s, i*5);
  1549. }
  1550. for (i=0; i < testsize; i += 1) {
  1551. stbds_struct s = { i,i*2,i*3 ,i*4 };
  1552. stbds_struct t = { i,i*2,i*3+1,i*4 };
  1553. if (i & 1) STBDS_ASSERT(hmget(map, s) == 0);
  1554. else STBDS_ASSERT(hmget(map, s) == i*5);
  1555. if (i & 1) STBDS_ASSERT(hmget_ts(map, s, temp) == 0);
  1556. else STBDS_ASSERT(hmget_ts(map, s, temp) == i*5);
  1557. //STBDS_ASSERT(hmget(map, t.key) == 0);
  1558. }
  1559. for (i=0; i < testsize; i += 2) {
  1560. stbds_struct s = { i,i*2,i*3,i*4 };
  1561. hmputs(map2, s);
  1562. }
  1563. hmfree(map);
  1564. for (i=0; i < testsize; i += 1) {
  1565. stbds_struct s = { i,i*2,i*3,i*4 };
  1566. stbds_struct t = { i,i*2,i*3+1,i*4 };
  1567. if (i & 1) STBDS_ASSERT(hmgets(map2, s.key).d == 0);
  1568. else STBDS_ASSERT(hmgets(map2, s.key).d == i*4);
  1569. //STBDS_ASSERT(hmgetp(map2, t.key) == 0);
  1570. }
  1571. hmfree(map2);
  1572. for (i=0; i < testsize; i += 2) {
  1573. stbds_struct2 s = { { i,i*2 }, i*3,i*4, i*5 };
  1574. hmputs(map3, s);
  1575. }
  1576. for (i=0; i < testsize; i += 1) {
  1577. stbds_struct2 s = { { i,i*2}, i*3, i*4, i*5 };
  1578. stbds_struct2 t = { { i,i*2}, i*3+1, i*4, i*5 };
  1579. if (i & 1) STBDS_ASSERT(hmgets(map3, s.key).d == 0);
  1580. else STBDS_ASSERT(hmgets(map3, s.key).d == i*5);
  1581. //STBDS_ASSERT(hmgetp(map3, t.key) == 0);
  1582. }
  1583. #endif
  1584. }
  1585. #endif
  1586. /*
  1587. ------------------------------------------------------------------------------
  1588. This software is available under 2 licenses -- choose whichever you prefer.
  1589. ------------------------------------------------------------------------------
  1590. ALTERNATIVE A - MIT License
  1591. Copyright (c) 2019 Sean Barrett
  1592. Permission is hereby granted, free of charge, to any person obtaining a copy of
  1593. this software and associated documentation files (the "Software"), to deal in
  1594. the Software without restriction, including without limitation the rights to
  1595. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  1596. of the Software, and to permit persons to whom the Software is furnished to do
  1597. so, subject to the following conditions:
  1598. The above copyright notice and this permission notice shall be included in all
  1599. copies or substantial portions of the Software.
  1600. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1601. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1602. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1603. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1604. 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 THE
  1606. 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 this
  1611. 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 this
  1614. software dedicate any and all copyright interest in the software to the public
  1615. domain. We make this dedication for the benefit of the public at large and to
  1616. the detriment of our heirs and successors. We intend this dedication to be an
  1617. overt act of relinquishment in perpetuity of all present and future rights to
  1618. this software under copyright law.
  1619. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1620. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1621. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1622. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  1623. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  1624. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1625. ------------------------------------------------------------------------------
  1626. */