Skip to content

Hashable

Hashable is the protocol a class adopts so its instances can key a Map or be stored in a Set. It pairs a hash code with value equality.

class MyKey <Hashable, Comparable> { ... }

A hashed collection finds a candidate slot from a key’s hash, then confirms the match by equality. Hashable therefore declares both a hash and an equals. A hash alone can only select a bucket; it cannot decide which entry in the bucket is the one you want.

The equals slot is the same slot Comparable declares, so a class listing <Comparable, Hashable> writes one equals body and satisfies both protocols: two vtable entries, one implementation.

Topics · hash · equals

u32 hash(void); // xt6502: u8

Return a hash code derived from the value of self. The hard requirement is consistency: equal values (per equals) must produce equal hash codes, or a lookup misses what set() stored. The distribution need not be perfect; any non-degenerate hash keeps probe chains short at realistic loads. Foundation’s byte-hashing implementation (String) FNV-1a-folds the bytes, and Number and Object fold their value or address with an XOR–multiply. Either approach is easy to copy for a user type.

↑ Topics

bool equals(Object* other);

Value equality, identical to Comparable.equals: downcast other with a safe-checked cast and return true only when the values match. A lookup uses it to pick the right entry out of a bucket’s probe chain.

↑ Topics

Standard-library classes that conform (each implements hash and equals):

  • Object: the root declares <Hashable, Comparable>, so every object has an identity-based default hash and equality until it overrides them.
  • String: FNV-1a over the bytes.
  • Number: hashes the numeric value.
  • Data: hashes the byte buffer.

See also the sibling protocols Comparable and Copying.

Conform to Hashable (plus Comparable) to use a type as a Map key or Set member. Hashable locates the bucket, and Comparable’s equals confirms the match inside it. The two protocols are independent, so a value-only collection can use Comparable alone without a hash.