| 1 |
open Core |
| 2 |
|
| 3 |
let ( --> ) a b = (not a) || b |
| 4 |
|
| 5 |
let check_safety ~hash ~compare ~sexp_of_t (a, b) = |
| 6 |
let same_as_determined_by_compare = 0 = compare a b in |
| 7 |
let hash_a = hash a in |
| 8 |
let hash_b = hash b in |
| 9 |
let same_hash = 0 = Int.compare hash_a hash_b in |
| 10 |
let safe = same_as_determined_by_compare --> same_hash in |
| 11 |
if not safe |
| 12 |
then |
| 13 |
failwiths |
| 14 |
~here:[%here] |
| 15 |
"safety violation: equal values hash differently" |
| 16 |
((a, hash_a), (b, hash_b)) |
| 17 |
[%sexp_of: (t * Int.t) * (t * Int.t)] |
| 18 |
;; |
| 19 |
|
| 20 |
module Labelled_float = struct |
| 21 |
type t = string * float |
| 22 |
|
| 23 |
let hash (_, f) = [%hash: float] f |
| 24 |
let compare (_, f1) (_, f2) = compare_float f1 f2 |
| 25 |
let sexp_of_t (s, f) = sexp_of_string (Printf.sprintf "(%s)%f" s f) |
| 26 |
end |
| 27 |
|
| 28 |
let f int64 float = |
| 29 |
let module Int64 = struct |
| 30 |
include Int64 |
| 31 |
|
| 32 |
let sexp_of_t t = Sexp.Atom (sprintf "%Lx" t) |
| 33 |
end |
| 34 |
in |
| 35 |
[%test_result: Int64.t] ~expect:int64 (Int64.bits_of_float float); |
| 36 |
float |
| 37 |
;; |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
let f_nan int64 = |
| 42 |
let float = Int64.float_of_bits int64 in |
| 43 |
assert (Float.is_nan float); |
| 44 |
f int64 float |
| 45 |
;; |
| 46 |
|
| 47 |
|
| 48 |
let labelled () = |
| 49 |
[ "0.", f 0x0000000000000000L 0. |
| 50 |
; "1.", f 0x3ff0000000000000L 1. |
| 51 |
; "-0.", f 0x8000000000000000L (-0.) |
| 52 |
; "-1.", f 0xbff0000000000000L (-1.) |
| 53 |
; "Float.nan", f_nan 0x7ff8000000000001L |
| 54 |
; "Float.infinity", f 0x7ff0000000000000L Float.infinity |
| 55 |
; "-.Float.nan", f_nan 0xfff8000000000001L |
| 56 |
; "-.Float.infinity", f 0xfff0000000000000L (-.Float.infinity) |
| 57 |
; "0./.0.", f 0xfff8000000000000L (0. /. 0.) |
| 58 |
] |
| 59 |
;; |
| 60 |
|
| 61 |
let%test_unit "float safety test" = |
| 62 |
let open Labelled_float in |
| 63 |
List.iter |
| 64 |
(List.cartesian_product (labelled ()) (labelled ())) |
| 65 |
~f:(check_safety ~hash ~compare ~sexp_of_t) |
| 66 |
;; |