Modules

Hash

moduleSource

Available on macOS, Linux, Windows, Wasm

#import "Hash";

Hash functions for strings, bytes and scalars: get_hash for general use, fnv1a_hash and sdbm_hash for bytes, djb2_hash for strings.

The functions are fast and well spread, not secure: don't use them for passwords or to guard against crafted input.

Example↗
assert(get_hash("jacket") == get_hash("jacket"));
assert(get_hash(1) != get_hash(2));

Procedures#

(data: *void, size: int, h := HASH_INIT) -> u32

A 32-bit hash of size bytes at data. Pass the previous result as h to hash several pieces as one.

whole := "hello world";
one := sdbm_hash(whole.data, whole.count);
part := sdbm_hash(whole.data, 5);
two := sdbm_hash(whole.data + 5, whole.count - 5, part);
assert(one == two);
↗
fnv1a_hash2 overloadsSource
(val: u64, h := FNV_64_OFFSET_BIAS) -> u64
(data: *void, size: int, h := FNV_64_OFFSET_BIAS) -> u64

One step of 64-bit FNV-1a: mixes val into the hash h.

h := fnv1a_hash(1);
assert(h != fnv1a_hash(2));
assert(fnv1a_hash(2, h) != h);
↗
(x: u64) -> u64

Scrambles an integer by multiplying it with a large odd constant. The high bits of the result are the well mixed ones.

assert(knuth_hash(1) != knuth_hash(2));
↗
get_hash3 overloadsSource
(s: string, h := HASH_INIT) -> u32
(array: [] $T, h := HASH_INIT) -> u32
(x: $T, h := HASH_INIT) -> u32

A 32-bit hash of a string. This is the hash Table uses for string keys.

assert(get_hash("key") == get_hash("key"));
assert(get_hash("key") != get_hash("other"));
↗

Constants#

:: 0x100000001b3

The 64-bit FNV prime and offset basis that fnv1a_hash starts from.