dynamic_map_internal.odin 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. package runtime
  2. import "core:intrinsics"
  3. _ :: intrinsics
  4. // High performance, cache-friendly, open-addressed Robin Hood hashing hash map
  5. // data structure with various optimizations for Odin.
  6. //
  7. // Copyright 2022 (c) Dale Weiler
  8. //
  9. // The core of the hash map data structure is the Raw_Map struct which is a
  10. // type-erased representation of the map. This type-erased representation is
  11. // used in two ways: static and dynamic. When static type information is known,
  12. // the procedures suffixed with _static should be used instead of _dynamic. The
  13. // static procedures are optimized since they have type information. Hashing of
  14. // keys, comparison of keys, and data lookup are all optimized. When type
  15. // information is not known, the procedures suffixed with _dynamic should be
  16. // used. The representation of the map is the same for both static and dynamic,
  17. // and procedures of each can be mixed and matched. The purpose of the dynamic
  18. // representation is to enable reflection and runtime manipulation of the map.
  19. // The dynamic procedures all take an additional Map_Info structure parameter
  20. // which carries runtime values describing the size, alignment, and offset of
  21. // various traits of a given key and value type pair. The Map_Info value can
  22. // be created by calling map_info(K, V) with the key and value typeids.
  23. //
  24. // This map implementation makes extensive use of uintptr for representing
  25. // sizes, lengths, capacities, masks, pointers, offsets, and addresses to avoid
  26. // expensive sign extension and masking that would be generated if types were
  27. // casted all over. The only place regular ints show up is in the cap() and
  28. // len() implementations.
  29. //
  30. // To make this map cache-friendly it uses a novel strategy to ensure keys and
  31. // values of the map are always cache-line aligned and that no single key or
  32. // value of any type ever straddles a cache-line. This cache efficiency makes
  33. // for quick lookups because the linear-probe always addresses data in a cache
  34. // friendly way. This is enabled through the use of a special meta-type called
  35. // a Map_Cell which packs as many values of a given type into a local array adding
  36. // internal padding to round to MAP_CACHE_LINE_SIZE. One other benefit to storing
  37. // the internal data in this manner is false sharing no longer occurs when using
  38. // a map, enabling efficient concurrent access of the map data structure with
  39. // minimal locking if desired.
  40. // With Robin Hood hashing a maximum load factor of 75% is ideal.
  41. MAP_LOAD_FACTOR :: 75
  42. // Minimum log2 capacity.
  43. MAP_MIN_LOG2_CAPACITY :: 6 // 64 elements
  44. // Has to be less than 100% though.
  45. #assert(MAP_LOAD_FACTOR < 100)
  46. // This is safe to change. The log2 size of a cache-line. At minimum it has to
  47. // be six though. Higher cache line sizes are permitted.
  48. MAP_CACHE_LINE_LOG2 :: 6
  49. // The size of a cache-line.
  50. MAP_CACHE_LINE_SIZE :: 1 << MAP_CACHE_LINE_LOG2
  51. // The minimum cache-line size allowed by this implementation is 64 bytes since
  52. // we need 6 bits in the base pointer to store the integer log2 capacity, which
  53. // at maximum is 63. Odin uses signed integers to represent length and capacity,
  54. // so only 63 bits are needed in the maximum case.
  55. #assert(MAP_CACHE_LINE_SIZE >= 64)
  56. // Map_Cell type that packs multiple T in such a way to ensure that each T stays
  57. // aligned by align_of(T) and such that align_of(Map_Cell(T)) % MAP_CACHE_LINE_SIZE == 0
  58. //
  59. // This means a value of type T will never straddle a cache-line.
  60. //
  61. // When multiple Ts can fit in a single cache-line the data array will have more
  62. // than one element. When it cannot, the data array will have one element and
  63. // an array of Map_Cell(T) will be padded to stay a multiple of MAP_CACHE_LINE_SIZE.
  64. //
  65. // We rely on the type system to do all the arithmetic and padding for us here.
  66. //
  67. // The usual array[index] indexing for []T backed by a []Map_Cell(T) becomes a bit
  68. // more involved as there now may be internal padding. The indexing now becomes
  69. //
  70. // N :: len(Map_Cell(T){}.data)
  71. // i := index / N
  72. // j := index % N
  73. // cell[i].data[j]
  74. //
  75. // However, since len(Map_Cell(T){}.data) is a compile-time constant, there are some
  76. // optimizations we can do to eliminate the need for any divisions as N will
  77. // be bounded by [1, 64).
  78. //
  79. // In the optimal case, len(Map_Cell(T){}.data) = 1 so the cell array can be treated
  80. // as a regular array of T, which is the case for hashes.
  81. Map_Cell :: struct($T: typeid) #align MAP_CACHE_LINE_SIZE {
  82. data: [MAP_CACHE_LINE_SIZE / size_of(T) when 0 < size_of(T) && size_of(T) < MAP_CACHE_LINE_SIZE else 1]T,
  83. }
  84. // So we can operate on a cell data structure at runtime without any type
  85. // information, we have a simple table that stores some traits about the cell.
  86. //
  87. // 32-bytes on 64-bit
  88. // 16-bytes on 32-bit
  89. Map_Cell_Info :: struct {
  90. size_of_type: uintptr, // 8-bytes on 64-bit, 4-bytes on 32-bits
  91. align_of_type: uintptr, // 8-bytes on 64-bit, 4-bytes on 32-bits
  92. size_of_cell: uintptr, // 8-bytes on 64-bit, 4-bytes on 32-bits
  93. elements_per_cell: uintptr, // 8-bytes on 64-bit, 4-bytes on 32-bits
  94. }
  95. // map_cell_info :: proc "contextless" ($T: typeid) -> ^Map_Cell_Info {...}
  96. map_cell_info :: intrinsics.type_map_cell_info
  97. // Same as the above procedure but at runtime with the cell Map_Cell_Info value.
  98. @(require_results)
  99. map_cell_index_dynamic :: #force_inline proc "contextless" (base: uintptr, #no_alias info: ^Map_Cell_Info, index: uintptr) -> uintptr {
  100. // Micro-optimize the common cases to save on integer division.
  101. elements_per_cell := uintptr(info.elements_per_cell)
  102. size_of_cell := uintptr(info.size_of_cell)
  103. switch elements_per_cell {
  104. case 1:
  105. return base + (index * size_of_cell)
  106. case 2:
  107. cell_index := index >> 1
  108. data_index := index & 1
  109. size_of_type := uintptr(info.size_of_type)
  110. return base + (cell_index * size_of_cell) + (data_index * size_of_type)
  111. case:
  112. cell_index := index / elements_per_cell
  113. data_index := index % elements_per_cell
  114. size_of_type := uintptr(info.size_of_type)
  115. return base + (cell_index * size_of_cell) + (data_index * size_of_type)
  116. }
  117. }
  118. // Same as above procedure but with compile-time constant index.
  119. @(require_results)
  120. map_cell_index_dynamic_const :: proc "contextless" (base: uintptr, #no_alias info: ^Map_Cell_Info, $INDEX: uintptr) -> uintptr {
  121. elements_per_cell := uintptr(info.elements_per_cell)
  122. size_of_cell := uintptr(info.size_of_cell)
  123. size_of_type := uintptr(info.size_of_type)
  124. cell_index := INDEX / elements_per_cell
  125. data_index := INDEX % elements_per_cell
  126. return base + (cell_index * size_of_cell) + (data_index * size_of_type)
  127. }
  128. // We always round the capacity to a power of two so this becomes [16]Foo, which
  129. // works out to [4]Cell(Foo).
  130. //
  131. // The following compile-time procedure indexes such a [N]Cell(T) structure as
  132. // if it were a flat array accounting for the internal padding introduced by the
  133. // Cell structure.
  134. @(require_results)
  135. map_cell_index_static :: #force_inline proc "contextless" (cells: [^]Map_Cell($T), index: uintptr) -> ^T #no_bounds_check {
  136. N :: size_of(Map_Cell(T){}.data) / size_of(T) when size_of(T) > 0 else 1
  137. #assert(N <= MAP_CACHE_LINE_SIZE)
  138. when size_of(Map_Cell(T)) == size_of([N]T) {
  139. // No padding case, can treat as a regular array of []T.
  140. return &([^]T)(cells)[index]
  141. } else when (N & (N - 1)) == 0 && N <= 8*size_of(uintptr) {
  142. // Likely case, N is a power of two because T is a power of two.
  143. // Compute the integer log 2 of N, this is the shift amount to index the
  144. // correct cell. Odin's intrinsics.count_leading_zeros does not produce a
  145. // constant, hence this approach. We only need to check up to N = 64.
  146. SHIFT :: 1 when N < 2 else
  147. 2 when N < 4 else
  148. 3 when N < 8 else
  149. 4 when N < 16 else
  150. 5 when N < 32 else 6
  151. #assert(SHIFT <= MAP_CACHE_LINE_LOG2)
  152. // Unique case, no need to index data here since only one element.
  153. when N == 1 {
  154. return &cells[index >> SHIFT].data[0]
  155. } else {
  156. return &cells[index >> SHIFT].data[index & (N - 1)]
  157. }
  158. } else {
  159. // Least likely (and worst case), we pay for a division operation but we
  160. // assume the compiler does not actually generate a division. N will be in the
  161. // range [1, CACHE_LINE_SIZE) and not a power of two.
  162. return &cells[index / N].data[index % N]
  163. }
  164. }
  165. // len() for map
  166. @(require_results)
  167. map_len :: #force_inline proc "contextless" (m: Raw_Map) -> int {
  168. return int(m.len)
  169. }
  170. // cap() for map
  171. @(require_results)
  172. map_cap :: #force_inline proc "contextless" (m: Raw_Map) -> int {
  173. // The data uintptr stores the capacity in the lower six bits which gives the
  174. // a maximum value of 2^6-1, or 63. We store the integer log2 of capacity
  175. // since our capacity is always a power of two. We only need 63 bits as Odin
  176. // represents length and capacity as a signed integer.
  177. return 0 if m.data == 0 else 1 << map_log2_cap(m)
  178. }
  179. // Query the load factor of the map. This is not actually configurable, but
  180. // some math is needed to compute it. Compute it as a fixed point percentage to
  181. // avoid floating point operations. This division can be optimized out by
  182. // multiplying by the multiplicative inverse of 100.
  183. @(require_results)
  184. map_load_factor :: #force_inline proc "contextless" (log2_capacity: uintptr) -> uintptr {
  185. return ((uintptr(1) << log2_capacity) * MAP_LOAD_FACTOR) / 100
  186. }
  187. @(require_results)
  188. map_resize_threshold :: #force_inline proc "contextless" (m: Raw_Map) -> uintptr {
  189. return map_load_factor(map_log2_cap(m))
  190. }
  191. // The data stores the log2 capacity in the lower six bits. This is primarily
  192. // used in the implementation rather than map_cap since the check for data = 0
  193. // isn't necessary in the implementation. cap() on the otherhand needs to work
  194. // when called on an empty map.
  195. @(require_results)
  196. map_log2_cap :: #force_inline proc "contextless" (m: Raw_Map) -> uintptr {
  197. return m.data & (64 - 1)
  198. }
  199. // Canonicalize the data by removing the tagged capacity stored in the lower six
  200. // bits of the data uintptr.
  201. @(require_results)
  202. map_data :: #force_inline proc "contextless" (m: Raw_Map) -> uintptr {
  203. return m.data &~ uintptr(64 - 1)
  204. }
  205. Map_Hash :: uintptr
  206. TOMBSTONE_MASK :: 1<<(size_of(Map_Hash)*8 - 1)
  207. // Procedure to check if a slot is empty for a given hash. This is represented
  208. // by the zero value to make the zero value useful. This is a procedure just
  209. // for prose reasons.
  210. @(require_results)
  211. map_hash_is_empty :: #force_inline proc "contextless" (hash: Map_Hash) -> bool {
  212. return hash == 0
  213. }
  214. @(require_results)
  215. map_hash_is_deleted :: #force_no_inline proc "contextless" (hash: Map_Hash) -> bool {
  216. // The MSB indicates a tombstone
  217. return hash & TOMBSTONE_MASK != 0
  218. }
  219. @(require_results)
  220. map_hash_is_valid :: #force_inline proc "contextless" (hash: Map_Hash) -> bool {
  221. // The MSB indicates a tombstone
  222. return (hash != 0) & (hash & TOMBSTONE_MASK == 0)
  223. }
  224. @(require_results)
  225. map_seed :: #force_inline proc "contextless" (m: Raw_Map) -> uintptr {
  226. return map_seed_from_map_data(map_data(m))
  227. }
  228. // splitmix for uintptr
  229. @(require_results)
  230. map_seed_from_map_data :: #force_inline proc "contextless" (data: uintptr) -> uintptr {
  231. when size_of(uintptr) == size_of(u64) {
  232. mix := data + 0x9e3779b97f4a7c15
  233. mix = (mix ~ (mix >> 30)) * 0xbf58476d1ce4e5b9
  234. mix = (mix ~ (mix >> 27)) * 0x94d049bb133111eb
  235. return mix ~ (mix >> 31)
  236. } else {
  237. mix := data + 0x9e3779b9
  238. mix = (mix ~ (mix >> 16)) * 0x21f0aaad
  239. mix = (mix ~ (mix >> 15)) * 0x735a2d97
  240. return mix ~ (mix >> 15)
  241. }
  242. }
  243. // Computes the desired position in the array. This is just index % capacity,
  244. // but a procedure as there's some math involved here to recover the capacity.
  245. @(require_results)
  246. map_desired_position :: #force_inline proc "contextless" (m: Raw_Map, hash: Map_Hash) -> uintptr {
  247. // We do not use map_cap since we know the capacity will not be zero here.
  248. capacity := uintptr(1) << map_log2_cap(m)
  249. return uintptr(hash & Map_Hash(capacity - 1))
  250. }
  251. @(require_results)
  252. map_probe_distance :: #force_inline proc "contextless" (m: Raw_Map, hash: Map_Hash, slot: uintptr) -> uintptr {
  253. // We do not use map_cap since we know the capacity will not be zero here.
  254. capacity := uintptr(1) << map_log2_cap(m)
  255. return (slot + capacity - map_desired_position(m, hash)) & (capacity - 1)
  256. }
  257. // When working with the type-erased structure at runtime we need information
  258. // about the map to make working with it possible. This info structure stores
  259. // that.
  260. //
  261. // `Map_Info` and `Map_Cell_Info` are read only data structures and cannot be
  262. // modified after creation
  263. //
  264. // 32-bytes on 64-bit
  265. // 16-bytes on 32-bit
  266. Map_Info :: struct {
  267. ks: ^Map_Cell_Info, // 8-bytes on 64-bit, 4-bytes on 32-bit
  268. vs: ^Map_Cell_Info, // 8-bytes on 64-bit, 4-bytes on 32-bit
  269. key_hasher: proc "contextless" (key: rawptr, seed: Map_Hash) -> Map_Hash, // 8-bytes on 64-bit, 4-bytes on 32-bit
  270. key_equal: proc "contextless" (lhs, rhs: rawptr) -> bool, // 8-bytes on 64-bit, 4-bytes on 32-bit
  271. }
  272. // The Map_Info structure is basically a pseudo-table of information for a given K and V pair.
  273. // map_info :: proc "contextless" ($T: typeid/map[$K]$V) -> ^Map_Info {...}
  274. map_info :: intrinsics.type_map_info
  275. @(require_results)
  276. map_kvh_data_dynamic :: proc "contextless" (m: Raw_Map, #no_alias info: ^Map_Info) -> (ks: uintptr, vs: uintptr, hs: [^]Map_Hash, sk: uintptr, sv: uintptr) {
  277. INFO_HS := intrinsics.type_map_cell_info(Map_Hash)
  278. capacity := uintptr(1) << map_log2_cap(m)
  279. ks = map_data(m)
  280. vs = map_cell_index_dynamic(ks, info.ks, capacity) // Skip past ks to get start of vs
  281. hs_ := map_cell_index_dynamic(vs, info.vs, capacity) // Skip past vs to get start of hs
  282. sk = map_cell_index_dynamic(hs_, INFO_HS, capacity) // Skip past hs to get start of sk
  283. // Need to skip past two elements in the scratch key space to get to the start
  284. // of the scratch value space, of which there's only two elements as well.
  285. sv = map_cell_index_dynamic_const(sk, info.ks, 2)
  286. hs = ([^]Map_Hash)(hs_)
  287. return
  288. }
  289. @(require_results)
  290. map_kvh_data_values_dynamic :: proc "contextless" (m: Raw_Map, #no_alias info: ^Map_Info) -> (vs: uintptr) {
  291. capacity := uintptr(1) << map_log2_cap(m)
  292. return map_cell_index_dynamic(map_data(m), info.ks, capacity) // Skip past ks to get start of vs
  293. }
  294. @(private, require_results)
  295. map_total_allocation_size :: #force_inline proc "contextless" (capacity: uintptr, info: ^Map_Info) -> uintptr {
  296. round :: #force_inline proc "contextless" (value: uintptr) -> uintptr {
  297. CACHE_MASK :: MAP_CACHE_LINE_SIZE - 1
  298. return (value + CACHE_MASK) &~ CACHE_MASK
  299. }
  300. INFO_HS := intrinsics.type_map_cell_info(Map_Hash)
  301. size := uintptr(0)
  302. size = round(map_cell_index_dynamic(size, info.ks, capacity))
  303. size = round(map_cell_index_dynamic(size, info.vs, capacity))
  304. size = round(map_cell_index_dynamic(size, INFO_HS, capacity))
  305. size = round(map_cell_index_dynamic(size, info.ks, 2)) // Two additional ks for scratch storage
  306. size = round(map_cell_index_dynamic(size, info.vs, 2)) // Two additional vs for scratch storage
  307. return size
  308. }
  309. // The only procedure which needs access to the context is the one which allocates the map.
  310. @(require_results)
  311. map_alloc_dynamic :: proc "odin" (info: ^Map_Info, log2_capacity: uintptr, allocator := context.allocator, loc := #caller_location) -> (result: Raw_Map, err: Allocator_Error) {
  312. result.allocator = allocator // set the allocator always
  313. if log2_capacity == 0 {
  314. return
  315. }
  316. if log2_capacity >= 64 {
  317. // Overflowed, would be caused by log2_capacity > 64
  318. return {}, .Out_Of_Memory
  319. }
  320. capacity := uintptr(1) << max(log2_capacity, MAP_MIN_LOG2_CAPACITY)
  321. CACHE_MASK :: MAP_CACHE_LINE_SIZE - 1
  322. size := map_total_allocation_size(capacity, info)
  323. data := mem_alloc_non_zeroed(int(size), MAP_CACHE_LINE_SIZE, allocator, loc) or_return
  324. data_ptr := uintptr(raw_data(data))
  325. if data_ptr == 0 {
  326. err = .Out_Of_Memory
  327. return
  328. }
  329. if intrinsics.expect(data_ptr & CACHE_MASK != 0, false) {
  330. panic("allocation not aligned to a cache line", loc)
  331. } else {
  332. result.data = data_ptr | log2_capacity // Tagged pointer representation for capacity.
  333. result.len = 0
  334. map_clear_dynamic(&result, info)
  335. }
  336. return
  337. }
  338. // This procedure has to stack allocate storage to store local keys during the
  339. // Robin Hood hashing technique where elements are swapped in the backing
  340. // arrays to reduce variance. This swapping can only be done with memcpy since
  341. // there is no type information.
  342. //
  343. // This procedure returns the address of the just inserted value.
  344. @(require_results)
  345. map_insert_hash_dynamic :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, h: Map_Hash, ik: uintptr, iv: uintptr) -> (result: uintptr) {
  346. h := h
  347. pos := map_desired_position(m^, h)
  348. distance := uintptr(0)
  349. mask := (uintptr(1) << map_log2_cap(m^)) - 1
  350. ks, vs, hs, sk, sv := map_kvh_data_dynamic(m^, info)
  351. // Avoid redundant loads of these values
  352. size_of_k := info.ks.size_of_type
  353. size_of_v := info.vs.size_of_type
  354. k := map_cell_index_dynamic(sk, info.ks, 0)
  355. v := map_cell_index_dynamic(sv, info.vs, 0)
  356. intrinsics.mem_copy_non_overlapping(rawptr(k), rawptr(ik), size_of_k)
  357. intrinsics.mem_copy_non_overlapping(rawptr(v), rawptr(iv), size_of_v)
  358. // Temporary k and v dynamic storage for swap below
  359. tk := map_cell_index_dynamic(sk, info.ks, 1)
  360. tv := map_cell_index_dynamic(sv, info.vs, 1)
  361. for {
  362. hp := &hs[pos]
  363. element_hash := hp^
  364. if map_hash_is_empty(element_hash) {
  365. kp := map_cell_index_dynamic(ks, info.ks, pos)
  366. vp := map_cell_index_dynamic(vs, info.vs, pos)
  367. intrinsics.mem_copy_non_overlapping(rawptr(kp), rawptr(k), size_of_k)
  368. intrinsics.mem_copy_non_overlapping(rawptr(vp), rawptr(v), size_of_v)
  369. hp^ = h
  370. return result if result != 0 else vp
  371. }
  372. if map_hash_is_deleted(element_hash) {
  373. next_pos := (pos + 1) & mask
  374. // backward shift
  375. for !map_hash_is_empty(hs[next_pos]) {
  376. probe_distance := map_probe_distance(m^, hs[next_pos], next_pos)
  377. if probe_distance == 0 {
  378. break
  379. }
  380. probe_distance -= 1
  381. kp := map_cell_index_dynamic(ks, info.ks, pos)
  382. vp := map_cell_index_dynamic(vs, info.vs, pos)
  383. kn := map_cell_index_dynamic(ks, info.ks, next_pos)
  384. vn := map_cell_index_dynamic(vs, info.vs, next_pos)
  385. if distance > probe_distance {
  386. if result == 0 {
  387. result = vp
  388. }
  389. // move stored into pos; store next
  390. intrinsics.mem_copy_non_overlapping(rawptr(kp), rawptr(k), size_of_k)
  391. intrinsics.mem_copy_non_overlapping(rawptr(vp), rawptr(v), size_of_v)
  392. hs[pos] = h
  393. intrinsics.mem_copy_non_overlapping(rawptr(k), rawptr(kn), size_of_k)
  394. intrinsics.mem_copy_non_overlapping(rawptr(v), rawptr(vn), size_of_v)
  395. h = hs[next_pos]
  396. } else {
  397. // move next back 1
  398. intrinsics.mem_copy_non_overlapping(rawptr(kp), rawptr(kn), size_of_k)
  399. intrinsics.mem_copy_non_overlapping(rawptr(vp), rawptr(vn), size_of_v)
  400. hs[pos] = hs[next_pos]
  401. distance = probe_distance
  402. }
  403. hs[next_pos] = 0
  404. pos = (pos + 1) & mask
  405. next_pos = (next_pos + 1) & mask
  406. distance += 1
  407. }
  408. kp := map_cell_index_dynamic(ks, info.ks, pos)
  409. vp := map_cell_index_dynamic(vs, info.vs, pos)
  410. intrinsics.mem_copy_non_overlapping(rawptr(kp), rawptr(k), size_of_k)
  411. intrinsics.mem_copy_non_overlapping(rawptr(vp), rawptr(v), size_of_v)
  412. hs[pos] = h
  413. return result if result != 0 else vp
  414. }
  415. if probe_distance := map_probe_distance(m^, element_hash, pos); distance > probe_distance {
  416. if result == 0 {
  417. result = map_cell_index_dynamic(vs, info.vs, pos)
  418. }
  419. kp := map_cell_index_dynamic(ks, info.ks, pos)
  420. vp := map_cell_index_dynamic(vs, info.vs, pos)
  421. intrinsics.mem_copy_non_overlapping(rawptr(tk), rawptr(k), size_of_k)
  422. intrinsics.mem_copy_non_overlapping(rawptr(k), rawptr(kp), size_of_k)
  423. intrinsics.mem_copy_non_overlapping(rawptr(kp), rawptr(tk), size_of_k)
  424. intrinsics.mem_copy_non_overlapping(rawptr(tv), rawptr(v), size_of_v)
  425. intrinsics.mem_copy_non_overlapping(rawptr(v), rawptr(vp), size_of_v)
  426. intrinsics.mem_copy_non_overlapping(rawptr(vp), rawptr(tv), size_of_v)
  427. th := h
  428. h = hp^
  429. hp^ = th
  430. distance = probe_distance
  431. }
  432. pos = (pos + 1) & mask
  433. distance += 1
  434. }
  435. }
  436. @(require_results)
  437. map_grow_dynamic :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, loc := #caller_location) -> Allocator_Error {
  438. log2_capacity := map_log2_cap(m^)
  439. new_capacity := uintptr(1) << max(log2_capacity + 1, MAP_MIN_LOG2_CAPACITY)
  440. return map_reserve_dynamic(m, info, new_capacity, loc)
  441. }
  442. @(require_results)
  443. map_reserve_dynamic :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, new_capacity: uintptr, loc := #caller_location) -> Allocator_Error {
  444. @(require_results)
  445. ceil_log2 :: #force_inline proc "contextless" (x: uintptr) -> uintptr {
  446. z := intrinsics.count_leading_zeros(x)
  447. if z > 0 && x & (x-1) != 0 {
  448. z -= 1
  449. }
  450. return size_of(uintptr)*8 - 1 - z
  451. }
  452. if m.allocator.procedure == nil {
  453. m.allocator = context.allocator
  454. }
  455. new_capacity := new_capacity
  456. old_capacity := uintptr(map_cap(m^))
  457. if old_capacity >= new_capacity {
  458. return nil
  459. }
  460. // ceiling nearest power of two
  461. log2_new_capacity := ceil_log2(new_capacity)
  462. log2_min_cap := max(MAP_MIN_LOG2_CAPACITY, log2_new_capacity)
  463. if m.data == 0 {
  464. m^ = map_alloc_dynamic(info, log2_min_cap, m.allocator, loc) or_return
  465. return nil
  466. }
  467. resized := map_alloc_dynamic(info, log2_min_cap, m.allocator, loc) or_return
  468. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  469. // Cache these loads to avoid hitting them in the for loop.
  470. n := m.len
  471. for i in 0..<old_capacity {
  472. hash := hs[i]
  473. if map_hash_is_empty(hash) {
  474. continue
  475. }
  476. if map_hash_is_deleted(hash) {
  477. continue
  478. }
  479. k := map_cell_index_dynamic(ks, info.ks, i)
  480. v := map_cell_index_dynamic(vs, info.vs, i)
  481. hash = info.key_hasher(rawptr(k), map_seed(resized))
  482. _ = map_insert_hash_dynamic(&resized, info, hash, k, v)
  483. // Only need to do this comparison on each actually added pair, so do not
  484. // fold it into the for loop comparator as a micro-optimization.
  485. n -= 1
  486. if n == 0 {
  487. break
  488. }
  489. }
  490. map_free_dynamic(m^, info, loc) or_return
  491. m.data = resized.data
  492. return nil
  493. }
  494. @(require_results)
  495. map_shrink_dynamic :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, loc := #caller_location) -> Allocator_Error {
  496. if m.allocator.procedure == nil {
  497. m.allocator = context.allocator
  498. }
  499. // Cannot shrink the capacity if the number of items in the map would exceed
  500. // one minus the current log2 capacity's resize threshold. That is the shrunk
  501. // map needs to be within the max load factor.
  502. log2_capacity := map_log2_cap(m^)
  503. if uintptr(m.len) >= map_load_factor(log2_capacity - 1) {
  504. return nil
  505. }
  506. shrunk := map_alloc_dynamic(info, log2_capacity - 1, m.allocator) or_return
  507. capacity := uintptr(1) << log2_capacity
  508. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  509. n := m.len
  510. for i in 0..<capacity {
  511. hash := hs[i]
  512. if map_hash_is_empty(hash) {
  513. continue
  514. }
  515. if map_hash_is_deleted(hash) {
  516. continue
  517. }
  518. k := map_cell_index_dynamic(ks, info.ks, i)
  519. v := map_cell_index_dynamic(vs, info.vs, i)
  520. hash = info.key_hasher(rawptr(k), map_seed(shrunk))
  521. _ = map_insert_hash_dynamic(&shrunk, info, hash, k, v)
  522. // Only need to do this comparison on each actually added pair, so do not
  523. // fold it into the for loop comparator as a micro-optimization.
  524. n -= 1
  525. if n == 0 {
  526. break
  527. }
  528. }
  529. map_free_dynamic(m^, info, loc) or_return
  530. m.data = shrunk.data
  531. return nil
  532. }
  533. @(require_results)
  534. map_free_dynamic :: proc "odin" (m: Raw_Map, info: ^Map_Info, loc := #caller_location) -> Allocator_Error {
  535. ptr := rawptr(map_data(m))
  536. size := int(map_total_allocation_size(uintptr(map_cap(m)), info))
  537. err := mem_free_with_size(ptr, size, m.allocator, loc)
  538. #partial switch err {
  539. case .None, .Mode_Not_Implemented:
  540. return nil
  541. }
  542. return err
  543. }
  544. @(require_results)
  545. map_lookup_dynamic :: proc "contextless" (m: Raw_Map, #no_alias info: ^Map_Info, k: uintptr) -> (index: uintptr, ok: bool) {
  546. if map_len(m) == 0 {
  547. return 0, false
  548. }
  549. h := info.key_hasher(rawptr(k), map_seed(m))
  550. p := map_desired_position(m, h)
  551. d := uintptr(0)
  552. c := (uintptr(1) << map_log2_cap(m)) - 1
  553. ks, _, hs, _, _ := map_kvh_data_dynamic(m, info)
  554. for {
  555. element_hash := hs[p]
  556. if map_hash_is_empty(element_hash) {
  557. return 0, false
  558. } else if d > map_probe_distance(m, element_hash, p) {
  559. return 0, false
  560. } else if element_hash == h && info.key_equal(rawptr(k), rawptr(map_cell_index_dynamic(ks, info.ks, p))) {
  561. return p, true
  562. }
  563. p = (p + 1) & c
  564. d += 1
  565. }
  566. }
  567. @(require_results)
  568. map_exists_dynamic :: proc "contextless" (m: Raw_Map, #no_alias info: ^Map_Info, k: uintptr) -> (ok: bool) {
  569. if map_len(m) == 0 {
  570. return false
  571. }
  572. h := info.key_hasher(rawptr(k), map_seed(m))
  573. p := map_desired_position(m, h)
  574. d := uintptr(0)
  575. c := (uintptr(1) << map_log2_cap(m)) - 1
  576. ks, _, hs, _, _ := map_kvh_data_dynamic(m, info)
  577. for {
  578. element_hash := hs[p]
  579. if map_hash_is_empty(element_hash) {
  580. return false
  581. } else if d > map_probe_distance(m, element_hash, p) {
  582. return false
  583. } else if element_hash == h && info.key_equal(rawptr(k), rawptr(map_cell_index_dynamic(ks, info.ks, p))) {
  584. return true
  585. }
  586. p = (p + 1) & c
  587. d += 1
  588. }
  589. }
  590. @(require_results)
  591. map_erase_dynamic :: #force_inline proc "contextless" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, k: uintptr) -> (old_k, old_v: uintptr, ok: bool) {
  592. index := map_lookup_dynamic(m^, info, k) or_return
  593. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  594. hs[index] |= TOMBSTONE_MASK
  595. old_k = map_cell_index_dynamic(ks, info.ks, index)
  596. old_v = map_cell_index_dynamic(vs, info.vs, index)
  597. m.len -= 1
  598. ok = true
  599. { // coalesce tombstones
  600. // HACK NOTE(bill): This is an ugly bodge but it is coalescing the tombstone slots
  601. mask := (uintptr(1)<<map_log2_cap(m^)) - 1
  602. curr_index := uintptr(index)
  603. // TODO(bill): determine a good value for this empirically
  604. // if we do not implement backward shift deletion
  605. PROBE_COUNT :: 8
  606. for _ in 0..<PROBE_COUNT {
  607. next_index := (curr_index + 1) & mask
  608. if next_index == index {
  609. // looped around
  610. break
  611. }
  612. // if the next element is empty or has zero probe distance, then any lookup
  613. // will always fail on the next, so we can clear both of them
  614. hash := hs[next_index]
  615. if map_hash_is_empty(hash) || map_probe_distance(m^, hash, next_index) == 0 {
  616. hs[curr_index] = 0
  617. return
  618. }
  619. // now the next element will have a probe count of at least one,
  620. // so it can use the delete slot instead
  621. hs[curr_index] = hs[next_index]
  622. mem_copy_non_overlapping(
  623. rawptr(map_cell_index_dynamic(ks, info.ks, curr_index)),
  624. rawptr(map_cell_index_dynamic(ks, info.ks, next_index)),
  625. int(info.ks.size_of_type),
  626. )
  627. mem_copy_non_overlapping(
  628. rawptr(map_cell_index_dynamic(vs, info.vs, curr_index)),
  629. rawptr(map_cell_index_dynamic(vs, info.vs, next_index)),
  630. int(info.vs.size_of_type),
  631. )
  632. curr_index = next_index
  633. }
  634. hs[curr_index] |= TOMBSTONE_MASK
  635. }
  636. return
  637. }
  638. map_clear_dynamic :: #force_inline proc "contextless" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info) {
  639. if m.data == 0 {
  640. return
  641. }
  642. _, _, hs, _, _ := map_kvh_data_dynamic(m^, info)
  643. intrinsics.mem_zero(rawptr(hs), map_cap(m^) * size_of(Map_Hash))
  644. m.len = 0
  645. }
  646. @(require_results)
  647. map_kvh_data_static :: #force_inline proc "contextless" (m: $T/map[$K]$V) -> (ks: [^]Map_Cell(K), vs: [^]Map_Cell(V), hs: [^]Map_Hash) {
  648. capacity := uintptr(cap(m))
  649. ks = ([^]Map_Cell(K))(map_data(transmute(Raw_Map)m))
  650. vs = ([^]Map_Cell(V))(map_cell_index_static(ks, capacity))
  651. hs = ([^]Map_Hash)(map_cell_index_static(vs, capacity))
  652. return
  653. }
  654. @(require_results)
  655. map_get :: proc "contextless" (m: $T/map[$K]$V, key: K) -> (stored_key: K, stored_value: V, ok: bool) {
  656. rm := transmute(Raw_Map)m
  657. if rm.len == 0 {
  658. return
  659. }
  660. info := intrinsics.type_map_info(T)
  661. key := key
  662. h := info.key_hasher(&key, map_seed(rm))
  663. pos := map_desired_position(rm, h)
  664. distance := uintptr(0)
  665. mask := (uintptr(1) << map_log2_cap(rm)) - 1
  666. ks, vs, hs := map_kvh_data_static(m)
  667. for {
  668. element_hash := hs[pos]
  669. if map_hash_is_empty(element_hash) {
  670. return
  671. } else if distance > map_probe_distance(rm, element_hash, pos) {
  672. return
  673. } else if element_hash == h {
  674. element_key := map_cell_index_static(ks, pos)
  675. if info.key_equal(&key, rawptr(element_key)) {
  676. element_value := map_cell_index_static(vs, pos)
  677. stored_key = (^K)(element_key)^
  678. stored_value = (^V)(element_value)^
  679. ok = true
  680. return
  681. }
  682. }
  683. pos = (pos + 1) & mask
  684. distance += 1
  685. }
  686. }
  687. // IMPORTANT: USED WITHIN THE COMPILER
  688. __dynamic_map_get :: proc "contextless" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, h: Map_Hash, key: rawptr) -> (ptr: rawptr) {
  689. if m.len == 0 {
  690. return nil
  691. }
  692. pos := map_desired_position(m^, h)
  693. distance := uintptr(0)
  694. mask := (uintptr(1) << map_log2_cap(m^)) - 1
  695. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  696. for {
  697. element_hash := hs[pos]
  698. if map_hash_is_empty(element_hash) {
  699. return nil
  700. } else if distance > map_probe_distance(m^, element_hash, pos) {
  701. return nil
  702. } else if element_hash == h && info.key_equal(key, rawptr(map_cell_index_dynamic(ks, info.ks, pos))) {
  703. return rawptr(map_cell_index_dynamic(vs, info.vs, pos))
  704. }
  705. pos = (pos + 1) & mask
  706. distance += 1
  707. }
  708. }
  709. // IMPORTANT: USED WITHIN THE COMPILER
  710. __dynamic_map_check_grow :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, loc := #caller_location) -> (err: Allocator_Error, has_grown: bool) {
  711. if m.len >= map_resize_threshold(m^) {
  712. return map_grow_dynamic(m, info, loc), true
  713. }
  714. return nil, false
  715. }
  716. __dynamic_map_set_without_hash :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, key, value: rawptr, loc := #caller_location) -> rawptr {
  717. return __dynamic_map_set(m, info, info.key_hasher(key, map_seed(m^)), key, value, loc)
  718. }
  719. // IMPORTANT: USED WITHIN THE COMPILER
  720. __dynamic_map_set :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, hash: Map_Hash, key, value: rawptr, loc := #caller_location) -> rawptr {
  721. if found := __dynamic_map_get(m, info, hash, key); found != nil {
  722. intrinsics.mem_copy_non_overlapping(found, value, info.vs.size_of_type)
  723. return found
  724. }
  725. hash := hash
  726. err, has_grown := __dynamic_map_check_grow(m, info, loc)
  727. if err != nil {
  728. return nil
  729. }
  730. if has_grown {
  731. hash = info.key_hasher(key, map_seed(m^))
  732. }
  733. result := map_insert_hash_dynamic(m, info, hash, uintptr(key), uintptr(value))
  734. m.len += 1
  735. return rawptr(result)
  736. }
  737. // IMPORTANT: USED WITHIN THE COMPILER
  738. @(private)
  739. __dynamic_map_reserve :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, new_capacity: uint, loc := #caller_location) -> Allocator_Error {
  740. return map_reserve_dynamic(m, info, uintptr(new_capacity), loc)
  741. }
  742. // NOTE: the default hashing algorithm derives from fnv64a, with some minor modifications to work for `map` type:
  743. //
  744. // * Convert a `0` result to `1`
  745. // * "empty entry"
  746. // * Prevent the top bit from being set
  747. // * "deleted entry"
  748. //
  749. // Both of these modification are necessary for the implementation of the `map`
  750. INITIAL_HASH_SEED :: 0xcbf29ce484222325
  751. HASH_MASK :: 1 << (8*size_of(uintptr) - 1) -1
  752. default_hasher :: #force_inline proc "contextless" (data: rawptr, seed: uintptr, N: int) -> uintptr {
  753. h := u64(seed) + INITIAL_HASH_SEED
  754. p := ([^]byte)(data)
  755. for _ in 0..<N {
  756. h = (h ~ u64(p[0])) * 0x100000001b3
  757. p = p[1:]
  758. }
  759. h &= HASH_MASK
  760. return uintptr(h) | uintptr(uintptr(h) == 0)
  761. }
  762. default_hasher_string :: proc "contextless" (data: rawptr, seed: uintptr) -> uintptr {
  763. str := (^[]byte)(data)
  764. return default_hasher(raw_data(str^), seed, len(str))
  765. }
  766. default_hasher_cstring :: proc "contextless" (data: rawptr, seed: uintptr) -> uintptr {
  767. h := u64(seed) + INITIAL_HASH_SEED
  768. if ptr := (^[^]byte)(data)^; ptr != nil {
  769. for ptr[0] != 0 {
  770. h = (h ~ u64(ptr[0])) * 0x100000001b3
  771. ptr = ptr[1:]
  772. }
  773. }
  774. h &= HASH_MASK
  775. return uintptr(h) | uintptr(uintptr(h) == 0)
  776. }