dynamic_map_internal.odin 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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 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) -> int {
  189. return int(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. // Computes the desired position in the array. This is just index % capacity,
  225. // but a procedure as there's some math involved here to recover the capacity.
  226. @(require_results)
  227. map_desired_position :: #force_inline proc "contextless" (m: Raw_Map, hash: Map_Hash) -> uintptr {
  228. // We do not use map_cap since we know the capacity will not be zero here.
  229. capacity := uintptr(1) << map_log2_cap(m)
  230. return uintptr(hash & Map_Hash(capacity - 1))
  231. }
  232. @(require_results)
  233. map_probe_distance :: #force_inline proc "contextless" (m: Raw_Map, hash: Map_Hash, slot: uintptr) -> uintptr {
  234. // We do not use map_cap since we know the capacity will not be zero here.
  235. capacity := uintptr(1) << map_log2_cap(m)
  236. return (slot + capacity - map_desired_position(m, hash)) & (capacity - 1)
  237. }
  238. // When working with the type-erased structure at runtime we need information
  239. // about the map to make working with it possible. This info structure stores
  240. // that.
  241. //
  242. // `Map_Info` and `Map_Cell_Info` are read only data structures and cannot be
  243. // modified after creation
  244. //
  245. // 32-bytes on 64-bit
  246. // 16-bytes on 32-bit
  247. Map_Info :: struct {
  248. ks: ^Map_Cell_Info, // 8-bytes on 64-bit, 4-bytes on 32-bit
  249. vs: ^Map_Cell_Info, // 8-bytes on 64-bit, 4-bytes on 32-bit
  250. key_hasher: proc "contextless" (key: rawptr, seed: Map_Hash) -> Map_Hash, // 8-bytes on 64-bit, 4-bytes on 32-bit
  251. key_equal: proc "contextless" (lhs, rhs: rawptr) -> bool, // 8-bytes on 64-bit, 4-bytes on 32-bit
  252. }
  253. // The Map_Info structure is basically a pseudo-table of information for a given K and V pair.
  254. // map_info :: proc "contextless" ($T: typeid/map[$K]$V) -> ^Map_Info {...}
  255. map_info :: intrinsics.type_map_info
  256. @(require_results)
  257. 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) {
  258. INFO_HS := intrinsics.type_map_cell_info(Map_Hash)
  259. capacity := uintptr(1) << map_log2_cap(m)
  260. ks = map_data(m)
  261. vs = map_cell_index_dynamic(ks, info.ks, capacity) // Skip past ks to get start of vs
  262. hs_ := map_cell_index_dynamic(vs, info.vs, capacity) // Skip past vs to get start of hs
  263. sk = map_cell_index_dynamic(hs_, INFO_HS, capacity) // Skip past hs to get start of sk
  264. // Need to skip past two elements in the scratch key space to get to the start
  265. // of the scratch value space, of which there's only two elements as well.
  266. sv = map_cell_index_dynamic_const(sk, info.ks, 2)
  267. hs = ([^]Map_Hash)(hs_)
  268. return
  269. }
  270. @(require_results)
  271. map_kvh_data_values_dynamic :: proc "contextless" (m: Raw_Map, #no_alias info: ^Map_Info) -> (vs: uintptr) {
  272. capacity := uintptr(1) << map_log2_cap(m)
  273. return map_cell_index_dynamic(map_data(m), info.ks, capacity) // Skip past ks to get start of vs
  274. }
  275. @(private, require_results)
  276. map_total_allocation_size :: #force_inline proc "contextless" (capacity: uintptr, info: ^Map_Info) -> uintptr {
  277. round :: #force_inline proc "contextless" (value: uintptr) -> uintptr {
  278. CACHE_MASK :: MAP_CACHE_LINE_SIZE - 1
  279. return (value + CACHE_MASK) &~ CACHE_MASK
  280. }
  281. INFO_HS := intrinsics.type_map_cell_info(Map_Hash)
  282. size := uintptr(0)
  283. size = round(map_cell_index_dynamic(size, info.ks, capacity))
  284. size = round(map_cell_index_dynamic(size, info.vs, capacity))
  285. size = round(map_cell_index_dynamic(size, INFO_HS, capacity))
  286. size = round(map_cell_index_dynamic(size, info.ks, 2)) // Two additional ks for scratch storage
  287. size = round(map_cell_index_dynamic(size, info.vs, 2)) // Two additional vs for scratch storage
  288. return size
  289. }
  290. // The only procedure which needs access to the context is the one which allocates the map.
  291. @(require_results)
  292. map_alloc_dynamic :: proc "odin" (info: ^Map_Info, log2_capacity: uintptr, allocator := context.allocator, loc := #caller_location) -> (result: Raw_Map, err: Allocator_Error) {
  293. result.allocator = allocator // set the allocator always
  294. if log2_capacity == 0 {
  295. return
  296. }
  297. if log2_capacity >= 64 {
  298. // Overflowed, would be caused by log2_capacity > 64
  299. return {}, .Out_Of_Memory
  300. }
  301. capacity := uintptr(1) << max(log2_capacity, MAP_MIN_LOG2_CAPACITY)
  302. CACHE_MASK :: MAP_CACHE_LINE_SIZE - 1
  303. size := map_total_allocation_size(capacity, info)
  304. data := mem_alloc_non_zeroed(int(size), MAP_CACHE_LINE_SIZE, allocator, loc) or_return
  305. data_ptr := uintptr(raw_data(data))
  306. if data_ptr == 0 {
  307. err = .Out_Of_Memory
  308. return
  309. }
  310. if intrinsics.expect(data_ptr & CACHE_MASK != 0, false) {
  311. panic("allocation not aligned to a cache line", loc)
  312. } else {
  313. result.data = data_ptr | log2_capacity // Tagged pointer representation for capacity.
  314. result.len = 0
  315. map_clear_dynamic(&result, info)
  316. }
  317. return
  318. }
  319. // This procedure has to stack allocate storage to store local keys during the
  320. // Robin Hood hashing technique where elements are swapped in the backing
  321. // arrays to reduce variance. This swapping can only be done with memcpy since
  322. // there is no type information.
  323. //
  324. // This procedure returns the address of the just inserted value.
  325. @(require_results)
  326. 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) {
  327. h := h
  328. pos := map_desired_position(m^, h)
  329. distance := uintptr(0)
  330. mask := (uintptr(1) << map_log2_cap(m^)) - 1
  331. ks, vs, hs, sk, sv := map_kvh_data_dynamic(m^, info)
  332. // Avoid redundant loads of these values
  333. size_of_k := info.ks.size_of_type
  334. size_of_v := info.vs.size_of_type
  335. k := map_cell_index_dynamic(sk, info.ks, 0)
  336. v := map_cell_index_dynamic(sv, info.vs, 0)
  337. intrinsics.mem_copy_non_overlapping(rawptr(k), rawptr(ik), size_of_k)
  338. intrinsics.mem_copy_non_overlapping(rawptr(v), rawptr(iv), size_of_v)
  339. // Temporary k and v dynamic storage for swap below
  340. tk := map_cell_index_dynamic(sk, info.ks, 1)
  341. tv := map_cell_index_dynamic(sv, info.vs, 1)
  342. for {
  343. hp := &hs[pos]
  344. element_hash := hp^
  345. if map_hash_is_empty(element_hash) {
  346. k_dst := map_cell_index_dynamic(ks, info.ks, pos)
  347. v_dst := map_cell_index_dynamic(vs, info.vs, pos)
  348. intrinsics.mem_copy_non_overlapping(rawptr(k_dst), rawptr(k), size_of_k)
  349. intrinsics.mem_copy_non_overlapping(rawptr(v_dst), rawptr(v), size_of_v)
  350. hp^ = h
  351. return result if result != 0 else v_dst
  352. }
  353. if probe_distance := map_probe_distance(m^, element_hash, pos); distance > probe_distance {
  354. if map_hash_is_deleted(element_hash) {
  355. k_dst := map_cell_index_dynamic(ks, info.ks, pos)
  356. v_dst := map_cell_index_dynamic(vs, info.vs, pos)
  357. intrinsics.mem_copy_non_overlapping(rawptr(k_dst), rawptr(k), size_of_k)
  358. intrinsics.mem_copy_non_overlapping(rawptr(v_dst), rawptr(v), size_of_v)
  359. hp^ = h
  360. return result if result != 0 else v_dst
  361. }
  362. if result == 0 {
  363. result = map_cell_index_dynamic(vs, info.vs, pos)
  364. }
  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(tk), rawptr(k), size_of_k)
  368. intrinsics.mem_copy_non_overlapping(rawptr(k), rawptr(kp), size_of_k)
  369. intrinsics.mem_copy_non_overlapping(rawptr(kp), rawptr(tk), size_of_k)
  370. intrinsics.mem_copy_non_overlapping(rawptr(tv), rawptr(v), size_of_v)
  371. intrinsics.mem_copy_non_overlapping(rawptr(v), rawptr(vp), size_of_v)
  372. intrinsics.mem_copy_non_overlapping(rawptr(vp), rawptr(tv), size_of_v)
  373. th := h
  374. h = hp^
  375. hp^ = th
  376. distance = probe_distance
  377. }
  378. pos = (pos + 1) & mask
  379. distance += 1
  380. }
  381. }
  382. @(require_results)
  383. map_grow_dynamic :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, loc := #caller_location) -> Allocator_Error {
  384. log2_capacity := map_log2_cap(m^)
  385. new_capacity := uintptr(1) << max(log2_capacity + 1, MAP_MIN_LOG2_CAPACITY)
  386. return map_reserve_dynamic(m, info, new_capacity, loc)
  387. }
  388. @(require_results)
  389. map_reserve_dynamic :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, new_capacity: uintptr, loc := #caller_location) -> Allocator_Error {
  390. @(require_results)
  391. ceil_log2 :: #force_inline proc "contextless" (x: uintptr) -> uintptr {
  392. z := intrinsics.count_leading_zeros(x)
  393. if z > 0 && x & (x-1) != 0 {
  394. z -= 1
  395. }
  396. return size_of(uintptr)*8 - 1 - z
  397. }
  398. if m.allocator.procedure == nil {
  399. m.allocator = context.allocator
  400. }
  401. new_capacity := new_capacity
  402. old_capacity := uintptr(map_cap(m^))
  403. if old_capacity >= new_capacity {
  404. return nil
  405. }
  406. // ceiling nearest power of two
  407. log2_new_capacity := ceil_log2(new_capacity)
  408. log2_min_cap := max(MAP_MIN_LOG2_CAPACITY, log2_new_capacity)
  409. if m.data == 0 {
  410. m^ = map_alloc_dynamic(info, log2_min_cap, m.allocator, loc) or_return
  411. return nil
  412. }
  413. resized := map_alloc_dynamic(info, log2_min_cap, m.allocator, loc) or_return
  414. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  415. // Cache these loads to avoid hitting them in the for loop.
  416. n := m.len
  417. for i in 0..<old_capacity {
  418. hash := hs[i]
  419. if map_hash_is_empty(hash) {
  420. continue
  421. }
  422. if map_hash_is_deleted(hash) {
  423. continue
  424. }
  425. k := map_cell_index_dynamic(ks, info.ks, i)
  426. v := map_cell_index_dynamic(vs, info.vs, i)
  427. _ = map_insert_hash_dynamic(&resized, info, hash, k, v)
  428. // Only need to do this comparison on each actually added pair, so do not
  429. // fold it into the for loop comparator as a micro-optimization.
  430. n -= 1
  431. if n == 0 {
  432. break
  433. }
  434. }
  435. map_free_dynamic(m^, info, loc) or_return
  436. m.data = resized.data
  437. return nil
  438. }
  439. @(require_results)
  440. map_shrink_dynamic :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, loc := #caller_location) -> Allocator_Error {
  441. if m.allocator.procedure == nil {
  442. m.allocator = context.allocator
  443. }
  444. // Cannot shrink the capacity if the number of items in the map would exceed
  445. // one minus the current log2 capacity's resize threshold. That is the shrunk
  446. // map needs to be within the max load factor.
  447. log2_capacity := map_log2_cap(m^)
  448. if uintptr(m.len) >= map_load_factor(log2_capacity - 1) {
  449. return nil
  450. }
  451. shrunk := map_alloc_dynamic(info, log2_capacity - 1, m.allocator) or_return
  452. capacity := uintptr(1) << log2_capacity
  453. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  454. n := m.len
  455. for i in 0..<capacity {
  456. hash := hs[i]
  457. if map_hash_is_empty(hash) {
  458. continue
  459. }
  460. if map_hash_is_deleted(hash) {
  461. continue
  462. }
  463. k := map_cell_index_dynamic(ks, info.ks, i)
  464. v := map_cell_index_dynamic(vs, info.vs, i)
  465. _ = map_insert_hash_dynamic(&shrunk, info, hash, k, v)
  466. // Only need to do this comparison on each actually added pair, so do not
  467. // fold it into the for loop comparator as a micro-optimization.
  468. n -= 1
  469. if n == 0 {
  470. break
  471. }
  472. }
  473. map_free_dynamic(m^, info, loc) or_return
  474. m.data = shrunk.data
  475. return nil
  476. }
  477. @(require_results)
  478. map_free_dynamic :: proc "odin" (m: Raw_Map, info: ^Map_Info, loc := #caller_location) -> Allocator_Error {
  479. ptr := rawptr(map_data(m))
  480. size := int(map_total_allocation_size(uintptr(map_cap(m)), info))
  481. err := mem_free_with_size(ptr, size, m.allocator, loc)
  482. #partial switch err {
  483. case .None, .Mode_Not_Implemented:
  484. return nil
  485. }
  486. return err
  487. }
  488. @(require_results)
  489. map_lookup_dynamic :: proc "contextless" (m: Raw_Map, #no_alias info: ^Map_Info, k: uintptr) -> (index: uintptr, ok: bool) {
  490. if map_len(m) == 0 {
  491. return 0, false
  492. }
  493. h := info.key_hasher(rawptr(k), 0)
  494. p := map_desired_position(m, h)
  495. d := uintptr(0)
  496. c := (uintptr(1) << map_log2_cap(m)) - 1
  497. ks, _, hs, _, _ := map_kvh_data_dynamic(m, info)
  498. for {
  499. element_hash := hs[p]
  500. if map_hash_is_empty(element_hash) {
  501. return 0, false
  502. } else if d > map_probe_distance(m, element_hash, p) {
  503. return 0, false
  504. } else if element_hash == h && info.key_equal(rawptr(k), rawptr(map_cell_index_dynamic(ks, info.ks, p))) {
  505. return p, true
  506. }
  507. p = (p + 1) & c
  508. d += 1
  509. }
  510. }
  511. @(require_results)
  512. map_exists_dynamic :: proc "contextless" (m: Raw_Map, #no_alias info: ^Map_Info, k: uintptr) -> (ok: bool) {
  513. if map_len(m) == 0 {
  514. return false
  515. }
  516. h := info.key_hasher(rawptr(k), 0)
  517. p := map_desired_position(m, h)
  518. d := uintptr(0)
  519. c := (uintptr(1) << map_log2_cap(m)) - 1
  520. ks, _, hs, _, _ := map_kvh_data_dynamic(m, info)
  521. for {
  522. element_hash := hs[p]
  523. if map_hash_is_empty(element_hash) {
  524. return false
  525. } else if d > map_probe_distance(m, element_hash, p) {
  526. return false
  527. } else if element_hash == h && info.key_equal(rawptr(k), rawptr(map_cell_index_dynamic(ks, info.ks, p))) {
  528. return true
  529. }
  530. p = (p + 1) & c
  531. d += 1
  532. }
  533. }
  534. @(require_results)
  535. 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) {
  536. index := map_lookup_dynamic(m^, info, k) or_return
  537. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  538. hs[index] |= TOMBSTONE_MASK
  539. old_k = map_cell_index_dynamic(ks, info.ks, index)
  540. old_v = map_cell_index_dynamic(vs, info.vs, index)
  541. m.len -= 1
  542. ok = true
  543. { // coalesce tombstones
  544. // HACK NOTE(bill): This is an ugly bodge but it is coalescing the tombstone slots
  545. // TODO(bill): we should do backward shift deletion and not rely on tombstone slots
  546. mask := (uintptr(1)<<map_log2_cap(m^)) - 1
  547. curr_index := uintptr(index)
  548. // TODO(bill): determine a good value for this empirically
  549. // if we do not implement backward shift deletion
  550. PROBE_COUNT :: 8
  551. for _ in 0..<PROBE_COUNT {
  552. next_index := (curr_index + 1) & mask
  553. if next_index == index {
  554. // looped around
  555. break
  556. }
  557. // if the next element is empty or has zero probe distance, then any lookup
  558. // will always fail on the next, so we can clear both of them
  559. hash := hs[next_index]
  560. if map_hash_is_empty(hash) || map_probe_distance(m^, hash, next_index) == 0 {
  561. hs[curr_index] = 0
  562. return
  563. }
  564. // now the next element will have a probe count of at least one,
  565. // so it can use the delete slot instead
  566. hs[curr_index] = hs[next_index]
  567. mem_copy_non_overlapping(
  568. rawptr(map_cell_index_dynamic(ks, info.ks, curr_index)),
  569. rawptr(map_cell_index_dynamic(ks, info.ks, next_index)),
  570. int(info.ks.size_of_type),
  571. )
  572. mem_copy_non_overlapping(
  573. rawptr(map_cell_index_dynamic(vs, info.vs, curr_index)),
  574. rawptr(map_cell_index_dynamic(vs, info.vs, next_index)),
  575. int(info.vs.size_of_type),
  576. )
  577. curr_index = next_index
  578. }
  579. hs[curr_index] |= TOMBSTONE_MASK
  580. }
  581. return
  582. }
  583. map_clear_dynamic :: #force_inline proc "contextless" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info) {
  584. if m.data == 0 {
  585. return
  586. }
  587. _, _, hs, _, _ := map_kvh_data_dynamic(m^, info)
  588. intrinsics.mem_zero(rawptr(hs), map_cap(m^) * size_of(Map_Hash))
  589. m.len = 0
  590. }
  591. @(require_results)
  592. map_kvh_data_static :: #force_inline proc "contextless" (m: $T/map[$K]$V) -> (ks: [^]Map_Cell(K), vs: [^]Map_Cell(V), hs: [^]Map_Hash) {
  593. capacity := uintptr(cap(m))
  594. ks = ([^]Map_Cell(K))(map_data(transmute(Raw_Map)m))
  595. vs = ([^]Map_Cell(V))(map_cell_index_static(ks, capacity))
  596. hs = ([^]Map_Hash)(map_cell_index_static(vs, capacity))
  597. return
  598. }
  599. @(require_results)
  600. map_get :: proc "contextless" (m: $T/map[$K]$V, key: K) -> (stored_key: K, stored_value: V, ok: bool) {
  601. rm := transmute(Raw_Map)m
  602. if rm.len == 0 {
  603. return
  604. }
  605. info := intrinsics.type_map_info(T)
  606. key := key
  607. h := info.key_hasher(&key, 0)
  608. pos := map_desired_position(rm, h)
  609. distance := uintptr(0)
  610. mask := (uintptr(1) << map_log2_cap(rm)) - 1
  611. ks, vs, hs := map_kvh_data_static(m)
  612. for {
  613. element_hash := hs[pos]
  614. if map_hash_is_empty(element_hash) {
  615. return
  616. } else if distance > map_probe_distance(rm, element_hash, pos) {
  617. return
  618. } else if element_hash == h {
  619. element_key := map_cell_index_static(ks, pos)
  620. if info.key_equal(&key, rawptr(element_key)) {
  621. element_value := map_cell_index_static(vs, pos)
  622. stored_key = (^K)(element_key)^
  623. stored_value = (^V)(element_value)^
  624. ok = true
  625. return
  626. }
  627. }
  628. pos = (pos + 1) & mask
  629. distance += 1
  630. }
  631. }
  632. // IMPORTANT: USED WITHIN THE COMPILER
  633. __dynamic_map_get :: proc "contextless" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, h: Map_Hash, key: rawptr) -> (ptr: rawptr) {
  634. if m.len == 0 {
  635. return nil
  636. }
  637. pos := map_desired_position(m^, h)
  638. distance := uintptr(0)
  639. mask := (uintptr(1) << map_log2_cap(m^)) - 1
  640. ks, vs, hs, _, _ := map_kvh_data_dynamic(m^, info)
  641. for {
  642. element_hash := hs[pos]
  643. if map_hash_is_empty(element_hash) {
  644. return nil
  645. } else if distance > map_probe_distance(m^, element_hash, pos) {
  646. return nil
  647. } else if element_hash == h && info.key_equal(key, rawptr(map_cell_index_dynamic(ks, info.ks, pos))) {
  648. return rawptr(map_cell_index_dynamic(vs, info.vs, pos))
  649. }
  650. pos = (pos + 1) & mask
  651. distance += 1
  652. }
  653. }
  654. // IMPORTANT: USED WITHIN THE COMPILER
  655. __dynamic_map_check_grow :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, loc := #caller_location) -> Allocator_Error {
  656. if m.len >= map_resize_threshold(m^) {
  657. return map_grow_dynamic(m, info, loc)
  658. }
  659. return nil
  660. }
  661. __dynamic_map_set_without_hash :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, key, value: rawptr, loc := #caller_location) -> rawptr {
  662. return __dynamic_map_set(m, info, info.key_hasher(key, 0), key, value, loc)
  663. }
  664. // IMPORTANT: USED WITHIN THE COMPILER
  665. __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 {
  666. if found := __dynamic_map_get(m, info, hash, key); found != nil {
  667. intrinsics.mem_copy_non_overlapping(found, value, info.vs.size_of_type)
  668. return found
  669. }
  670. if __dynamic_map_check_grow(m, info, loc) != nil {
  671. return nil
  672. }
  673. result := map_insert_hash_dynamic(m, info, hash, uintptr(key), uintptr(value))
  674. m.len += 1
  675. return rawptr(result)
  676. }
  677. // IMPORTANT: USED WITHIN THE COMPILER
  678. @(private)
  679. __dynamic_map_reserve :: proc "odin" (#no_alias m: ^Raw_Map, #no_alias info: ^Map_Info, new_capacity: uint, loc := #caller_location) -> Allocator_Error {
  680. return map_reserve_dynamic(m, info, uintptr(new_capacity), loc)
  681. }
  682. // NOTE: the default hashing algorithm derives from fnv64a, with some minor modifications to work for `map` type:
  683. //
  684. // * Convert a `0` result to `1`
  685. // * "empty entry"
  686. // * Prevent the top bit from being set
  687. // * "deleted entry"
  688. //
  689. // Both of these modification are necessary for the implementation of the `map`
  690. INITIAL_HASH_SEED :: 0xcbf29ce484222325
  691. HASH_MASK :: 1 << (8*size_of(uintptr) - 1) -1
  692. default_hasher :: #force_inline proc "contextless" (data: rawptr, seed: uintptr, N: int) -> uintptr {
  693. h := u64(seed) + INITIAL_HASH_SEED
  694. p := ([^]byte)(data)
  695. for _ in 0..<N {
  696. h = (h ~ u64(p[0])) * 0x100000001b3
  697. p = p[1:]
  698. }
  699. h &= HASH_MASK
  700. return uintptr(h) | uintptr(uintptr(h) == 0)
  701. }
  702. default_hasher_string :: proc "contextless" (data: rawptr, seed: uintptr) -> uintptr {
  703. str := (^[]byte)(data)
  704. return default_hasher(raw_data(str^), seed, len(str))
  705. }
  706. default_hasher_cstring :: proc "contextless" (data: rawptr, seed: uintptr) -> uintptr {
  707. h := u64(seed) + INITIAL_HASH_SEED
  708. if ptr := (^[^]byte)(data)^; ptr != nil {
  709. for ptr[0] != 0 {
  710. h = (h ~ u64(ptr[0])) * 0x100000001b3
  711. ptr = ptr[1:]
  712. }
  713. }
  714. h &= HASH_MASK
  715. return uintptr(h) | uintptr(uintptr(h) == 0)
  716. }