From 5e7d02e4ea8048b22639c1e71f055237c90d7d64 Mon Sep 17 00:00:00 2001 From: Kim Morrison Date: Wed, 30 Oct 2024 13:26:18 +1100 Subject: [PATCH] feat: Hashable (BitVec n) (#5881) --- src/Init/Data/BitVec/Basic.lean | 10 ++++++++++ src/Init/Data/Hashable.lean | 3 +++ 2 files changed, 13 insertions(+) diff --git a/src/Init/Data/BitVec/Basic.lean b/src/Init/Data/BitVec/Basic.lean index 3d4b311d12..43465f4612 100644 --- a/src/Init/Data/BitVec/Basic.lean +++ b/src/Init/Data/BitVec/Basic.lean @@ -634,6 +634,16 @@ def twoPow (w : Nat) (i : Nat) : BitVec w := 1#w <<< i end bitwise +/-- Compute a hash of a bitvector, combining 64-bit words using `mixHash`. -/ +def hash (bv : BitVec n) : UInt64 := + if n ≤ 64 then + bv.toFin.val.toUInt64 + else + mixHash (bv.toFin.val.toUInt64) (hash ((bv >>> 64).setWidth (n - 64))) + +instance : Hashable (BitVec n) where + hash := hash + section normalization_eqs /-! We add simp-lemmas that rewrite bitvector operations into the equivalent notation -/ @[simp] theorem append_eq (x : BitVec w) (y : BitVec v) : BitVec.append x y = x ++ y := rfl diff --git a/src/Init/Data/Hashable.lean b/src/Init/Data/Hashable.lean index da29eeffff..e964c7c342 100644 --- a/src/Init/Data/Hashable.lean +++ b/src/Init/Data/Hashable.lean @@ -48,6 +48,9 @@ instance : Hashable UInt64 where instance : Hashable USize where hash n := n.toUInt64 +instance : Hashable ByteArray where + hash as := as.foldl (fun r a => mixHash r (hash a)) 7 + instance : Hashable (Fin n) where hash v := v.val.toUInt64