| 1 |
open Core |
| 2 |
open Poly |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 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 |