base icon indicating copy to clipboard operation
base copied to clipboard

Question about negative hash values (Base.Int.hash)

Open mbarbin opened this issue 1 year ago • 0 comments

I noticed some inputs for which Base.Int.hash returns negative values (v0.17.1).

I was surprised and searched a bit in the doc comments. In particular, I found this in hashable_intf.ml:

  (** Values returned by [hash] must be non-negative.  An exception will be raised in the
      case that [hash] returns a negative value. *)
  val hash : t -> int

This made me more confident that I should indeed be surprised. Below is an expect-test I used to reproduce this:

open! Base

let%expect_test "base int hash" =
  (* In this test we monitor the hashes of some int values using [Base].

     We note here that we would not have expected [Base.Int.hash] to sometimes
     return negative values, nor encounter cases where [Base.Int.hash_fold_t]
     applied to an empty state returns a result that differs from that of
     [Base.Int.hash]. *)
  let test i =
    let h = Base.Int.hash i in
    let h2 = Base.Hash.run Base.Int.hash_fold_t i in
    print_s [%sexp (i : int), (h : int), (h2 : int), (h = h2 : bool)]
  in
  List.iter ~f:test [ 0; 1; 2; 4; 5; -123456789 ];
  [%expect
    {|
    (0 4316648529147585864 1058613066 false)
    (1 -2609136240614377266 129913994 false)
    (2 4005111014598772340 462777137 false)
    (4 -1213116315786261967 607293368 false)
    (5 -3822126110415902464 648017920 false)
    (-123456789 -547221948126359607 131804527 false)
    |}];
  ()
;;

I'd be interested to learn more about this. In particular I am curious whether you consider this is a bug, or if there's some weird architecture related overflow I am hitting in the way I run the test or print the results here. Thanks!

mbarbin avatar Oct 20 '24 14:10 mbarbin