← core

core/hash.kur

//! Hashing and equality traits, and the keyed hash behind them.
// core::hash -- hashing and equality traits for keyed collections such as
// `alloc::collections::hashmap::HashMap!` (`Hash`, `Eq`) and
// `alloc::collections::arena_map::ArenaMap` (`HashIn`).
//
// The hash is SipHash-1-3 under a 128-bit `Seed`. A key's hash is
// SipHash-1-3, under the seed, of the key's encoding: the 64-bit words its
// `Hash` or `HashIn` instance writes (`HashState::write_u64`), each as its 8
// little-endian bytes. Every instance here writes an encoding that tells the
// values of its type apart and none of which is a prefix of another's (an
// integer or `bool` is one word; a byte string is its length, then its bytes
// eight to a word, the last word padded with zeros; a tuple is its parts in
// order), so two keys hash alike only where SipHash makes them: whoever does
// not know the seed cannot choose many keys that collide, and a map fed
// chosen keys (HashDoS) stays as fast as one fed any others. An instance of
// a type of its own keeps this by writing its parts the same way, with a
// word that tells its variants apart first.
//
// The seed is chosen by whoever makes a map, and every map takes one:
// `HashMap!::new(seed)`, `OwnedMap!::new(seed)`, and for an arena's maps the
// arena's (`alloc::arena::Arena!::new(seed)`). A hosted program passes the
// process's, `std::process::hash_seed()`, which start-up draws from the
// operating system, so it differs from one run to the next. A freestanding
// program draws one from an entropy source of its own (`Seed::new`), or
// picks a fixed one where no key comes from outside. A map's hash order, its
// `each` and `drain`, follows the seed; `ArenaMap` keeps insertion order
// whatever the seed.
//
// `Hash::hash` threads both the value and a running `HashState` through:
// it takes `self` by value and hands it back (`-> (Self, HashState)`), so a
// linear key can be hashed without being consumed. A composite key feeds
// each of its fields through the same state in turn
// (`state = field.hash(state)`).
//
// `Eq` is `Eq[A, B]`: the two sides may be different types. This lets
// values that differ only in brand be compared, as
// `core::borrow::Borrowed!`'s instance does for two lineage brands `'q1` and
// `'q2`. Both sides are handed back (`-> (A, B, bool)`). It is called by its
// full name: `Eq[K, K]::eq(a, b)`.
//
// There are no derived instances: the primitives and tuples of them have
// instances here, and every other key type writes its own.

use package as core;

/// The 128-bit key of the hash: which of SipHash's functions every map made
/// with it computes. Keys hash alike only under one seed, so a map hashes
/// all its keys under the one it was made with.
struct Seed {
    k0: u64,
    k1: u64,
}

impl Seed {
    /// The seed of the two words `k0` and `k1`: random ones, from an entropy
    /// source, for maps that may be fed keys from outside.
    fn new(k0: u64, k1: u64) -> Seed {
        Seed.{ k0, k1 }
    }
}

/// SipHash-1-3's running state: its four words, and how many words have
/// been written. Every field is `u64`, so `HashState` is `Copy` and threads
/// through repeated `write_u64` calls by value.
struct HashState {
    v0: u64,
    v1: u64,
    v2: u64,
    v3: u64,
    words: u64,
}

/// `x` rotated left by `r` bits, `0 < r < 64`.
fn rotl(x: u64, r: u64) -> u64 {
    (x << r) | (x >> (64u64 - r))
}

impl HashState {
    /// A fresh state under `seed`, before anything is written.
    fn new(seed: Seed) -> HashState {
        let { k0, k1 } = seed;
        HashState.{
            v0: k0 ^ 0x736f_6d65_7073_6575u64,
            v1: k1 ^ 0x646f_7261_6e64_6f6du64,
            v2: k0 ^ 0x6c79_6765_6e65_7261u64,
            v3: k1 ^ 0x7465_6462_7974_6573u64,
            words: 0u64,
        }
    }

    /// One SipRound. `u64` arithmetic wraps modulo 2^64.
    fn round(self) -> HashState {
        let { v0, v1, v2, v3, words } = self;
        let v0 = v0 + v1;
        let v1 = rotl(v1, 13u64) ^ v0;
        let v0 = rotl(v0, 32u64);
        let v2 = v2 + v3;
        let v3 = rotl(v3, 16u64) ^ v2;
        let v0 = v0 + v3;
        let v3 = rotl(v3, 21u64) ^ v0;
        let v2 = v2 + v1;
        let v1 = rotl(v1, 17u64) ^ v2;
        let v2 = rotl(v2, 32u64);
        HashState.{ v0, v1, v2, v3, words }
    }

    /// The state with the word `m` compressed in: one SipRound.
    fn compress(self, m: u64) -> HashState {
        let { v0, v1, v2, v3, words } = self;
        let { v0, v1, v2, v3, words } = HashState.{ v0, v1, v2, v3: v3 ^ m, words }.round();
        HashState.{ v0: v0 ^ m, v1, v2, v3, words }
    }

    /// The state with the word `v` written: the next 8 bytes of the
    /// encoding.
    fn write_u64(self, v: u64) -> HashState {
        let { v0, v1, v2, v3, words } = self.compress(v);
        HashState.{ v0, v1, v2, v3, words: words + 1u64 }
    }

    /// The hash of everything written: SipHash-1-3's last block, which
    /// holds the encoding's length in bytes (8 per word) modulo 256 in its
    /// top byte, then its three finishing rounds.
    fn finish(self) -> u64 {
        let { v0, v1, v2, v3, words } = self.compress(self.words << 59u64);
        let s = HashState.{ v0, v1, v2: v2 ^ 0xffu64, v3, words }.round().round().round();
        let { v0, v1, v2, v3, words } = s;
        v0 ^ v1 ^ v2 ^ v3
    }
}

/// Hashing: a value writes its encoding into a running `HashState` and is
/// handed back, so a linear key is not consumed.
forall Self.
trait Hash {
    /// The state with `self` written, and `self` handed back.
    fn hash(self: Self, state: HashState) -> (Self, HashState);
}

/// Equality of an `A` with a `B`, handing both back so linear values can be
/// compared.
forall A, B.
trait Eq {
    /// Whether `a` equals `b`, with both handed back.
    fn eq(a: A, b: B) -> (A, B, bool);
}

/// Hashing and equality for a `Copy` key that points into a domain, read
/// through that domain's capability `C`: a `Str['t]` read with an
/// `Exclusive!['t]`, say. The key is a view rather than an owner, so it is
/// not handed back; the capability is lent by place, as `ReadBytes` lends
/// it. `core::str` and `core::slice` have the byte-view instances; the
/// primitive and tuple ones are at the end of this module.
forall K, C.
trait HashIn {
    /// The state with `key` written, its bytes read through `cx`.
    fn hash_in(&cx: C, key: K, state: HashState) -> HashState;
    /// Whether `a` equals `b`, their bytes read through `cx`.
    fn eq_in(&cx: C, a: K, b: K) -> bool;
}

/// A key's hash under `HashIn` and `seed`.
forall K, C where HashIn[K, C].
fn key_hash(&cx: C, key: K, seed: Seed) -> u64 {
    HashIn[K, C]::hash_in(&cx, key, HashState::new(seed)).finish()
}

/// Whether two keys are equal under `HashIn`.
forall K, C where HashIn[K, C].
fn key_eq(&cx: C, a: K, b: K) -> bool {
    HashIn[K, C]::eq_in(&cx, a, b)
}

// The primitive instances. Every integer writes its 64-bit value (a signed
// one by its two's-complement bits), so equal values hash equally whatever
// their width; `bool` writes 0 or 1.

/// A `u8` hashes as its 64-bit value.
instance Hash[u8] {
    fn hash(self: u8, state: HashState) -> (u8, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `u8`s are equal when their values are.
instance Eq[u8, u8] {
    fn eq(a: u8, b: u8) -> (u8, u8, bool) {
        (a, b, a == b)
    }
}

/// A `u16` hashes as its 64-bit value.
instance Hash[u16] {
    fn hash(self: u16, state: HashState) -> (u16, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `u16`s are equal when their values are.
instance Eq[u16, u16] {
    fn eq(a: u16, b: u16) -> (u16, u16, bool) {
        (a, b, a == b)
    }
}

/// A `u32` hashes as its 64-bit value.
instance Hash[u32] {
    fn hash(self: u32, state: HashState) -> (u32, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `u32`s are equal when their values are.
instance Eq[u32, u32] {
    fn eq(a: u32, b: u32) -> (u32, u32, bool) {
        (a, b, a == b)
    }
}

/// A `u64` hashes as its 64-bit value.
instance Hash[u64] {
    fn hash(self: u64, state: HashState) -> (u64, HashState) {
        (self, state.write_u64(self))
    }
}

/// `u64`s are equal when their values are.
instance Eq[u64, u64] {
    fn eq(a: u64, b: u64) -> (u64, u64, bool) {
        (a, b, a == b)
    }
}

/// A `usize` hashes as its 64-bit value.
instance Hash[usize] {
    fn hash(self: usize, state: HashState) -> (usize, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `usize`s are equal when their values are.
instance Eq[usize, usize] {
    fn eq(a: usize, b: usize) -> (usize, usize, bool) {
        (a, b, a == b)
    }
}

/// A `i8` hashes as its 64-bit value.
instance Hash[i8] {
    fn hash(self: i8, state: HashState) -> (i8, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `i8`s are equal when their values are.
instance Eq[i8, i8] {
    fn eq(a: i8, b: i8) -> (i8, i8, bool) {
        (a, b, a == b)
    }
}

/// A `i16` hashes as its 64-bit value.
instance Hash[i16] {
    fn hash(self: i16, state: HashState) -> (i16, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `i16`s are equal when their values are.
instance Eq[i16, i16] {
    fn eq(a: i16, b: i16) -> (i16, i16, bool) {
        (a, b, a == b)
    }
}

/// A `i32` hashes as its 64-bit value.
instance Hash[i32] {
    fn hash(self: i32, state: HashState) -> (i32, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `i32`s are equal when their values are.
instance Eq[i32, i32] {
    fn eq(a: i32, b: i32) -> (i32, i32, bool) {
        (a, b, a == b)
    }
}

/// A `i64` hashes as its 64-bit value.
instance Hash[i64] {
    fn hash(self: i64, state: HashState) -> (i64, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `i64`s are equal when their values are.
instance Eq[i64, i64] {
    fn eq(a: i64, b: i64) -> (i64, i64, bool) {
        (a, b, a == b)
    }
}

/// A `isize` hashes as its 64-bit value.
instance Hash[isize] {
    fn hash(self: isize, state: HashState) -> (isize, HashState) {
        (self, state.write_u64((self as u64)))
    }
}

/// `isize`s are equal when their values are.
instance Eq[isize, isize] {
    fn eq(a: isize, b: isize) -> (isize, isize, bool) {
        (a, b, a == b)
    }
}

/// A `bool` hashes as 0 or 1.
instance Hash[bool] {
    fn hash(self: bool, state: HashState) -> (bool, HashState) {
        (self, state.write_u64(if self { 1u64 } else { 0u64 }))
    }
}

/// `bool`s are equal when their values are.
instance Eq[bool, bool] {
    fn eq(a: bool, b: bool) -> (bool, bool, bool) {
        (a, b, a == b)
    }
}

// Tuples hash their parts in order through one state and compare part by
// part, handing every part back, so linear parts work too.

/// A pair hashes its parts in order.
forall A, B where Hash[A], Hash[B].
instance Hash[(A, B)] {
    fn hash(self: (A, B), state: HashState) -> ((A, B), HashState) {
        let (a, b) = self;
        let (a, state) = Hash[A]::hash(a, state);
        let (b, state) = Hash[B]::hash(b, state);
        ((a, b), state)
    }
}

/// A triple hashes its parts in order.
forall A, B, D where Hash[A], Hash[B], Hash[D].
instance Hash[(A, B, D)] {
    fn hash(self: (A, B, D), state: HashState) -> ((A, B, D), HashState) {
        let (a, b, d) = self;
        let (a, state) = Hash[A]::hash(a, state);
        let (b, state) = Hash[B]::hash(b, state);
        let (d, state) = Hash[D]::hash(d, state);
        ((a, b, d), state)
    }
}

/// Pairs are equal when their parts are, part by part.
forall A1, B1, A2, B2 where Eq[A1, A2], Eq[B1, B2].
instance Eq[(A1, B1), (A2, B2)] {
    fn eq(x: (A1, B1), y: (A2, B2)) -> ((A1, B1), (A2, B2), bool) {
        let (a1, b1) = x;
        let (a2, b2) = y;
        let (a1, a2, first) = Eq[A1, A2]::eq(a1, a2);
        let (b1, b2, second) = Eq[B1, B2]::eq(b1, b2);
        ((a1, b1), (a2, b2), first && second)
    }
}

/// Triples are equal when their parts are, part by part.
forall A1, B1, D1, A2, B2, D2 where Eq[A1, A2], Eq[B1, B2], Eq[D1, D2].
instance Eq[(A1, B1, D1), (A2, B2, D2)] {
    fn eq(x: (A1, B1, D1), y: (A2, B2, D2)) -> ((A1, B1, D1), (A2, B2, D2), bool) {
        let (a1, b1, d1) = x;
        let (a2, b2, d2) = y;
        let (a1, a2, first) = Eq[A1, A2]::eq(a1, a2);
        let (b1, b2, second) = Eq[B1, B2]::eq(b1, b2);
        let (d1, d2, third) = Eq[D1, D2]::eq(d1, d2);
        ((a1, b1, d1), (a2, b2, d2), first && second && third)
    }
}

// The primitive and tuple keys of a domain-keyed map, under any capability:
// their bytes are their own, so `cx` only passes through, and they hash as
// `Hash` hashes them. A tuple key hashes and compares its parts in order,
// each under the same capability (`(Str['k], u32)` read with an
// `Exclusive!['k]`).

/// A `u8` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[u8, C] {
    fn hash_in(&cx: C, key: u8, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: u8, b: u8) -> bool {
        a == b
    }
}
/// A `u16` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[u16, C] {
    fn hash_in(&cx: C, key: u16, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: u16, b: u16) -> bool {
        a == b
    }
}
/// A `u32` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[u32, C] {
    fn hash_in(&cx: C, key: u32, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: u32, b: u32) -> bool {
        a == b
    }
}
/// A `u64` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[u64, C] {
    fn hash_in(&cx: C, key: u64, state: HashState) -> HashState {
        state.write_u64(key)
    }

    fn eq_in(&cx: C, a: u64, b: u64) -> bool {
        a == b
    }
}
/// A `usize` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[usize, C] {
    fn hash_in(&cx: C, key: usize, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: usize, b: usize) -> bool {
        a == b
    }
}
/// A `i8` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[i8, C] {
    fn hash_in(&cx: C, key: i8, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: i8, b: i8) -> bool {
        a == b
    }
}
/// A `i16` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[i16, C] {
    fn hash_in(&cx: C, key: i16, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: i16, b: i16) -> bool {
        a == b
    }
}
/// A `i32` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[i32, C] {
    fn hash_in(&cx: C, key: i32, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: i32, b: i32) -> bool {
        a == b
    }
}
/// A `i64` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[i64, C] {
    fn hash_in(&cx: C, key: i64, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: i64, b: i64) -> bool {
        a == b
    }
}
/// A `isize` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[isize, C] {
    fn hash_in(&cx: C, key: isize, state: HashState) -> HashState {
        state.write_u64((key as u64))
    }

    fn eq_in(&cx: C, a: isize, b: isize) -> bool {
        a == b
    }
}
/// A `bool` key, under any capability: hashed and compared as `Hash` and `Eq` do.
forall C.
instance HashIn[bool, C] {
    fn hash_in(&cx: C, key: bool, state: HashState) -> HashState {
        state.write_u64(if key { 1u64 } else { 0u64 })
    }

    fn eq_in(&cx: C, a: bool, b: bool) -> bool {
        a == b
    }
}
/// A pair key: its parts hashed and compared in order, each under `cx`.
forall A, B, C where HashIn[A, C], HashIn[B, C], Copy[A], Copy[B].
instance HashIn[(A, B), C] {
    fn hash_in(&cx: C, key: (A, B), state: HashState) -> HashState {
        let (a, b) = key;
        let state = HashIn[A, C]::hash_in(&cx, a, state);
        HashIn[B, C]::hash_in(&cx, b, state)
    }

    fn eq_in(&cx: C, x: (A, B), y: (A, B)) -> bool {
        let (a, b) = x;
        let (c, d) = y;
        HashIn[A, C]::eq_in(&cx, a, c) && HashIn[B, C]::eq_in(&cx, b, d)
    }
}

/// A triple key: its parts hashed and compared in order, each under `cx`.
forall A, B, D, C where HashIn[A, C], HashIn[B, C], HashIn[D, C], Copy[A], Copy[B], Copy[D].
instance HashIn[(A, B, D), C] {
    fn hash_in(&cx: C, key: (A, B, D), state: HashState) -> HashState {
        let (a, b, d) = key;
        let state = HashIn[A, C]::hash_in(&cx, a, state);
        let state = HashIn[B, C]::hash_in(&cx, b, state);
        HashIn[D, C]::hash_in(&cx, d, state)
    }

    fn eq_in(&cx: C, x: (A, B, D), y: (A, B, D)) -> bool {
        let (a, b, d) = x;
        let (e, f, g) = y;
        HashIn[A, C]::eq_in(&cx, a, e) && HashIn[B, C]::eq_in(&cx, b, f) && HashIn[D, C]::eq_in(&cx, d, g)
    }
}