Debian Codegraph @

runtime-lib/test/perfect_hash.ml

raw symbols SCIP
1 open Core
2 open Poly
3
4 (* This is not intended as a realistic candidate hash function since it allocates when
5 hashing, but as some kind of `perfect' baseline against which other hash functions can
6 be compared and judged.
7
8 It is a perfect hash in the sense that it produces no collisions of intermediate state
9 (trivially). It's also achieving about as good quality as possible in [get_hash_value]
10 by virtue of using a (former) cryptographically secure hash function.
11
12 Additionally, it tries to enforce the invariant well-behaved [hash_fold_t] functions
13 must obey: different values of the same type must produce mix-in sequences
14 of form (a @ [b1] @ c1) and (a @ [b2] @ c2) where b1 and b2 are "meaningfully"
15 different (see the checks in [compare]).
16
17 This requirement is a way to resolve possible systematic collisions resulting from e.g.
18 forgetting to write down a tag of a variant, or a length of an array.
19
20 It's not crazy to think about relaxing this requirement, but you can't relax it
21 too much: you can't allow some [hash_fold_t] functions to write their tag
22 to the end because that leads to a problem:
23 even though [1; 2] differs from [1] in last position and [3] differs from [2; 3] in
24 first position, ([1; 2] @ [3]) and ([1] @ [2; 3]) is a collision!
25 *)
26
27 let description = "perfect hash"
28
29 type hash_value = int
30
31 type v =
32 | Int of int
33 | Int64 of int64
34 | String of string
35 | Float of float
36 [@@deriving sexp]
37
38 let compare_v a b =
39 match a, b with
40 | Int a, Int b -> compare a b
41 | Int64 a, Int64 b -> compare a b
42 | String a, String b -> compare a b
43 | Float a, Float b -> compare a b
44 | _, _ -> failwith "uncomparable"
45 ;;
46
47 module State = struct
48 module T = struct
49 type t = v list [@@deriving sexp]
50
51 let rec compare a b =
52 match a, b with
53 | x :: xs, y :: ys -> [%compare: v * t] (x, xs) (y, ys)
54 | [], [] -> 0
55 | _, _ -> failwith "perfect hashes of different lengths"
56 ;;
57
58 let compare a b = compare (List.rev a) (List.rev b)
59 end
60
61 include T
62 include Comparable.Make (T)
63 end
64
65 type state = State.t
66
67 let fold_int t i = Int i :: t
68 let fold_int64 t i = Int64 i :: t
69 let fold_string t i = String i :: t
70 let fold_float t i = Float i :: t
71
72 type seed = unit
73
74 let alloc () = []
75 let reset ?seed:_ _ = []
76
77 let get_hash_value t =
78 Stdlib.Int64.to_int
79 (Int64.of_string
80 ("0x"
81 ^ String.prefix
82 (Md5.to_hex (Md5.digest_string (Sexplib.Sexp.to_string (State.sexp_of_t t))))
83 16))
84 ;;
85
86 module For_tests = struct
87 let state_to_string t = Sexplib.Sexp.to_string (State.sexp_of_t t)
88 let compare_state = State.compare
89 end