(* Copyright (c) 2026 Thomas Gazagnaire Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) (* hashmap.c: HASHMAP_INITIAL_SIZE, HASHMAP_RESIZE_BITS, HASHMAP_LOAD_FACTOR. *) let initial_size = 64 let resize_bits = 2 let load_factor = 80 type 'a t = { values : (string, 'a) Hashtbl.t; mutable buckets : string list array; mutable count : int; mutable grow_at : int; mutable shrink_at : int; } let strhash s = let h = ref 0x811c9dc5 in String.iter (fun c -> h := !h * 0x01000193 land 0xffffffff lxor Char.code c) s; !h (* alloc_table *) let resize_thresholds m = let size = Array.length m.buckets in m.grow_at <- size * load_factor / 100; m.shrink_at <- (if size <= initial_size then 0 else m.grow_at / ((1 lsl resize_bits) + 1)) let v () = let m = { values = Hashtbl.create initial_size; buckets = Array.make initial_size []; count = 0; grow_at = 0; shrink_at = 0; } in resize_thresholds m; m let bucket m k = strhash k land (Array.length m.buckets - 1) (* rehash: each old bucket in order, each of its entries pushed at the head of its new bucket. *) let rehash m size = let old = m.buckets in m.buckets <- Array.make size []; resize_thresholds m; Array.iter (List.iter (fun k -> let b = bucket m k in m.buckets.(b) <- k :: m.buckets.(b))) old let find m k = Hashtbl.find_opt m.values k let mem m k = Hashtbl.mem m.values k let is_empty m = m.count = 0 let replace m k v = if Hashtbl.mem m.values k then Hashtbl.replace m.values k v else begin Hashtbl.replace m.values k v; let b = bucket m k in m.buckets.(b) <- k :: m.buckets.(b); m.count <- m.count + 1; if m.count > m.grow_at then rehash m (Array.length m.buckets lsl resize_bits) end let remove m k = if Hashtbl.mem m.values k then begin Hashtbl.remove m.values k; let b = bucket m k in m.buckets.(b) <- List.filter (fun k' -> not (String.equal k k')) m.buckets.(b); m.count <- m.count - 1; if m.count < m.shrink_at then rehash m (Array.length m.buckets lsr resize_bits) end let iter f m = Array.iter (List.iter (fun k -> f k (Hashtbl.find m.values k))) m.buckets let to_list m = let acc = ref [] in iter (fun k v -> acc := (k, v) :: !acc) m; List.rev !acc