Files
std/containers/dict.sakura
T
2026-11-10 11:26:34 -06:00

668 lines
21 KiB
Plaintext

#! @file dict.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `dict` container. Dictionaries are an unordered
#! container that stores each value by a key, finding it by the hash of that key.
module std::containers;
#! A `dict` is an unordered data container that stores values by key, holding
#! one value for each key.
#!
#! They are useful wherever something is looked up by name or by some other
#! value, such as symbol tables, caches, and counting occurrences.
#!
#! Its entries live in one block, and it has a bucket for each of them. A bucket
#! holds the first entry whose key hashes to it, one past its index so that zero
#! is an empty bucket, and an entry holds the next of its bucket as `next`. The
#! entries holding no key are chained the same way from `_fre`, and `-1` ends
#! either chain. Entries keep their places as the dictionary grows, so only its
#! buckets are made again.
#! @tparam K The type of its keys, which are `hashable` and `equatable`.
#! @tparam V The type of its values.
pub struct dict<K, V>
: owning
, hashable
, indexable<K, V>
, assignable<K, V>
, iterable<dict<K, V>::entry>
, extendable<pair<K, V>>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _bkt: *mut i64;
var _ent: *mut dict<K, V>::entry;
var _len: u64;
var _cap: u64;
var _fre: i64;
}
#! A key and its value, with the hash the key is found by and the next entry of
#! its bucket, or of the free chain. Iterating a dictionary gives a reference to
#! each, which reads its `key` and `value`.
pub struct dict<K, V>::entry {
#! The key, which no other entry of the dictionary holds.
pub var key: K;
#! The value the key holds.
pub var value: V;
#! The key's hash, kept so the entry is found and moved without hashing again.
pub var hash: u64;
#! The index of the next entry of its bucket, or of the free chain, or `-1`.
pub var next: i64;
}
#! Provides read only access to the length of a dictionary.
#! @param this The dictionary to get the length of.
#! @returns The number of keys it holds a value for.
pub val dict<K, V>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a dictionary.
#! @param this The dictionary to get the capacity of.
#! @returns The number of keys it has room for before it grows.
pub val dict<K, V>::capacity: u64 {
get => this._cap;
}
#! Indicates if a dictionary is empty.
#! @param this The dictionary to check.
#! @returns Whether the dictionary holds no keys.
pub val dict<K, V>::empty: bool {
get => this._len == 0;
}
#! Indicates if a dictionary is full.
#! @param this The dictionary to check.
#! @returns Whether the next new key makes it grow.
pub val dict<K, V>::full: bool {
get => this._len == this._cap;
}
#! Creates a new dictionary with no allocator, which takes memory once something
#! is added.
#! @returns The created dictionary, which holds no keys yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def dict<K, V>::new(): dict<K, V> {
return dict::<K, V>::new(nothing{});
}
#! Creates a new dictionary with an optional allocator, which takes memory once
#! something is added.
#! @param alloc The optional allocator for the memory backing of the
#! dictionary.
#! @returns The created dictionary, which holds no keys yet.
pub def dict<K, V>::new(alloc: maybe<&mut allocator>): dict<K, V> {
return dict::<K, V> { _alc = alloc, _bkt = null, _ent = null, _len = 0, _cap = 0, _fre = -1 };
}
#! Creates a new dictionary with an optional allocator and room for some keys.
#! @param size The number of keys to make room for, which may be none.
#! @param alloc The optional allocator for the memory backing of the
#! dictionary.
#! @returns The created dictionary, which holds no keys yet.
pub def dict<K, V>::new(size: u64, alloc: maybe<&mut allocator>): dict<K, V> {
var made := dict::<K, V>::new(alloc);
made.reserve(size);
return made;
}
#! Builds a dictionary holding copies of another's keys and values, with its
#! allocator.
#! @param other The dictionary to copy from.
#! @returns The copy, which owns its own memory, keys, and values.
#! @remarks Keys and values are copied by `copyable` where they provide one, so
#! a key or value owning memory is copied rather than shared.
pub def dict<K, V>::copy_of(other: &dict<K, V>): dict<K, V> {
var made := dict::<K, V>::new(other._cap, other._alc);
for home in 0..other._cap {
var at := other._bkt[home] - 1;
while at >= 0 {
val held := &other._ent[at as u64];
made.set(copy::<K>(&held.key), copy::<V>(&held.value));
at = held.next;
}
}
return made;
}
#! Creates a new dictionary by moving the data of another dictionary into it.
#! @param other The dictionary to move from, which holds nothing after.
#! @returns The moved dictionary, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no entry is touched: the memory moves as it
#! stands, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def dict<K, V>::move_of(other: &mut dict<K, V>): dict<K, V> {
val made: dict<K, V> = dict {
_alc = other._alc,
_bkt = other._bkt,
_ent = other._ent,
_len = other._len,
_cap = other._cap,
_fre = other._fre
};
other._bkt = null;
other._ent = null;
other._len = 0;
other._cap = 0;
other._fre = -1;
return made;
}
#! Gets the value of a key the dictionary holds.
#! @param this The dictionary to get the value from.
#! @param key The key of the value, which the dictionary must hold, or else a
#! checked program stops.
#! @returns The value of the key.
pub def dict<K, V>::at(&this, key: K): &V {
val found := this.find(&key);
if const checking() {
if found < 0 {
fault("The dictionary does not hold the key.");
}
}
return &this._ent[found as u64].value;
}
#! Gets the value of a key the dictionary holds.
#! @param this The dictionary to get the value from.
#! @param key The key of the value, which the dictionary must hold, or else a
#! checked program stops.
#! @returns The value of the key.
pub def dict<K, V>::at(&mut this, key: K): &mut V {
val found := this.find(&key);
if const checking() {
if found < 0 {
fault("The dictionary does not hold the key.");
}
}
return &mut this._ent[found as u64].value;
}
#! Gets the value of a key, if the dictionary holds one.
#! @param this The dictionary to get the value from.
#! @param key The key of the value.
#! @returns The value of the key, or `none` where it holds none.
pub def dict<K, V>::get(&this, key: &K): maybe<&V> {
val found := this.find(key);
if found < 0 {
return nothing {};
}
return &this._ent[found as u64].value;
}
#! Gets the value of a key, if the dictionary holds one.
#! @param this The dictionary to get the value from.
#! @param key The key of the value.
#! @returns The value of the key, or `none` where it holds none.
pub def dict<K, V>::get(&mut this, key: &K): maybe<&mut V> {
val found := this.find(key);
if found < 0 {
return nothing {};
}
return &mut this._ent[found as u64].value;
}
#! Gets a copy of the value of a key, or another value where the dictionary
#! holds none for it.
#! @param this The dictionary to get the value from.
#! @param key The key of the value.
#! @param fallback The value given where the dictionary holds none for the
#! key.
#! @returns A copy of the value of the key, or else `fallback`.
#! @remarks The value is copied by `copyable` where it provides one, as `copy`
#! copies it.
pub def dict<K, V>::get_or(&this, key: &K, fallback: V): V {
val found := this.find(key);
if found < 0 {
return fallback;
}
return copy::<V>(&this._ent[found as u64].value);
}
#! Sets the value of a key the dictionary does not hold yet.
#! @param this The dictionary to set the value in.
#! @param key The key to set the value of.
#! @param value The value to store for the key.
#! @returns Whether the key was new and took the value. A key the dictionary
#! already holds keeps the value it has.
#! @remarks An allocator that gives no more memory stops the program.
pub def dict<K, V>::insert(&mut this, key: K, value: V): bool {
if this.find(&key) >= 0 {
return false;
}
this.add(move(key), move(value));
return true;
}
#! Sets the value of a key.
#! @param this The dictionary to set the value in.
#! @param key The key to set the value of.
#! @param value The value to store for the key.
#! @remarks A key the dictionary already holds takes the new value, and one it
#! does not takes an entry of its own, which grows the dictionary when
#! it is full. An allocator that gives no more memory stops the
#! program.
pub def dict<K, V>::set(&mut this, key: K, value: V): void {
val found := this.find(&key);
if found >= 0 {
this._ent[found as u64].value = move(value);
return;
}
this.add(move(key), move(value));
}
# Gives a key the dictionary does not hold an entry of its own, growing it when
# it is full.
def dict<K, V>::add(&mut this, key: K, value: V): void {
if this._fre < 0 {
this.grow();
}
val slot := this._fre as u64;
val code := hash::<K>(&key);
val home := dict::<K, V>::home(code, this._cap);
this._fre = this._ent[slot].next;
this._ent[slot] = dict::<K, V>::entry {
key = move(key),
value = move(value),
hash = code,
next = this._bkt[home] - 1
};
this._bkt[home] = slot as i64 + 1;
this._len++;
}
#! Tells whether the dictionary holds a value for a key.
#! @param this The dictionary to search.
#! @param key The key to look for.
#! @returns Whether the key has a value in it.
pub def dict<K, V>::contains(&this, key: &K): bool {
return this.find(key) >= 0;
}
#! Removes the value of a key, if the dictionary holds one.
#! @param this The dictionary to remove from.
#! @param key The key of the value to remove.
#! @returns Whether the key had a value that was removed.
#! @remarks The key and value are closed where they close, or hold what does,
#! and the entry goes back on the free chain for the next key.
pub def dict<K, V>::remove(&mut this, key: &K): bool {
if this._len == 0 {
return false;
}
val code := hash::<K>(key);
val home := dict::<K, V>::home(code, this._cap);
var prev := -1 as i64;
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
val next := this._ent[here].next;
if this._ent[here].hash != code || !equals::<K>(&this._ent[here].key, key) {
prev = at;
at = next;
continue;
}
if prev < 0 {
this._bkt[home] = next + 1;
} else {
this._ent[prev as u64].next = next;
}
this.release(here);
this._ent[here].next = this._fre;
this._fre = at;
this._len--;
return true;
}
return false;
}
#! Reserves room for a number of keys, so that setting that many grows the
#! dictionary no further.
#! @param this The dictionary to reserve room in.
#! @param count The number of keys to make room for.
pub def dict<K, V>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes every key and value from a dictionary.
#! @param this The dictionary to clear.
#! @remarks Keys and values that close, or hold what does, are closed. The
#! backing memory is kept for the keys set after.
pub def dict<K, V>::clear(&mut this): void {
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
at = this._ent[here].next;
this.release(here);
}
}
memset(this._bkt as *mut u8, 0, bytes_of::<i64>(this._cap));
this._fre = -1;
this._len = 0;
this.free(0, this._cap);
}
#! Removes every key and value of a dictionary, then disposes the backing
#! memory.
#! @param this The dictionary to close.
#! @remarks The memory is given back as it stands, so the keys and values are
#! closed where they close, or hold what does, but the entries are not
#! emptied.
pub def dict<K, V>::close(&mut this): void {
if const K is closeable || V is closeable {
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
at = this._ent[here].next;
this.close_entry(here);
}
}
}
this._len = 0;
if this._bkt != null {
dispose::<i64>(this._alc, this._bkt, this._cap);
dispose::<dict<K, V>::entry>(this._alc, this._ent, this._cap);
}
this._bkt = null;
this._ent = null;
this._cap = 0;
this._fre = -1;
}
#! Compares one dictionary to another for equality.
#! @param this The dictionary to compare against.
#! @param other The dictionary to compare with.
#! @returns Whether both hold the same keys, each with an equal value.
pub def dict<K, V>::equals(&this, other: &dict<K, V>): bool {
if this._len != other._len {
return false;
}
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
val found := other.find(&held.key);
return false if found < 0 || !equals::<V>(
&other._ent[found as u64].value,
&held.value
);
at = held.next;
}
}
return true;
}
#! Walks the entries of a dictionary, giving a reference that reads each in
#! turn, which is what `iter` lends and `for e in d` walks. Entries come in no
#! particular order, and each key once.
pub struct dict<K, V>::iterator : sized_iterator<&dict<K, V>::entry> {
var _bkt: *mut i64;
var _ent: *mut dict<K, V>::entry;
var _cap: u64;
var _bucket: u64;
var _at: i64;
var _left: u64;
}
#! Gives the next entry of the dictionary.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the next entry; otherwise, `nothing`.
pub def dict<K, V>::iterator::next(&mut this): maybe<&dict<K, V>::entry> {
# Every entry holding a key is in the chain of its bucket, and nothing else is.
while this._at < 0 {
if this._bucket >= this._cap {
return nothing {};
}
this._at = this._bkt[this._bucket] - 1;
this._bucket++;
}
val here := this._at as u64;
this._at = this._ent[here].next;
this._left = this._left - 1;
return &this._ent[here];
}
#! How many entries the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def dict<K, V>::iterator::remaining(&this): u64 {
return this._left;
}
#! Lends an iterator that reads the entries of the dictionary, which
#! `for e in d` walks. Values are changed through `d[key]`, since a key never
#! changes.
#! @param this The dictionary to walk.
#! @returns The iterator, which is only good until the dictionary changes or
#! closes.
pub def dict<K, V>::iter(&this): dict<K, V>::iterator {
return dict::<K, V>::iterator { _bkt = this._bkt, _ent = this._ent, _cap = this._cap, _bucket = 0, _at = -1, _left = this._len };
}
#! An iterator that reads the entries of the dictionary, as `iter` lends.
#! @param this The dictionary to walk.
#! @returns The iterator, which is only good until the dictionary changes or
#! closes.
pub val dict<K, V>::iterator: dict<K, V>::iterator {
get => this.iter();
}
#! Makes a dictionary of the keys and values an iterator gives as pairs, each
#! key's last value kept.
#! @tparam I The iterator.
#! @param from The iterator, walked to its end.
#! @returns The dictionary.
pub def dict<K, V>::from<I>(from: I): dict<K, V> where I: iter<pair<K, V>> {
var made := dict::<K, V>::new();
if const I is sized_iterator<pair<K, V>> {
made.reserve(from.remaining());
}
while from.next() is some(entry) {
made.set(move(&mut entry.first), move(&mut entry.second));
}
return made;
}
#! Gives a key a value, as `set` does, from a pair of them, so a dictionary is
#! what an iterator's `into` appends pairs to.
#! @param this The dictionary.
#! @param entry The key, first, and its value.
pub def dict<K, V>::append(&mut this, entry: pair<K, V>): void {
this.set(move(&mut entry.first), move(&mut entry.second));
}
#! Lends an iterator over the keys, in the order `iter` gives the entries.
#! @param this The dictionary to walk.
#! @returns The iterator, which is only good until the dictionary changes or
#! closes.
pub def dict<K, V>::keys(&this): dict<K, V>::key_iterator {
return dict::<K, V>::key_iterator { _from = this.iter() };
}
#! Lends an iterator over the values, in the order `iter` gives the entries.
#! @param this The dictionary to walk.
#! @returns The iterator, which is only good until the dictionary changes or
#! closes.
pub def dict<K, V>::values(&this): dict<K, V>::value_iterator {
return dict::<K, V>::value_iterator { _from = this.iter() };
}
#! Walks the keys of a dictionary, giving a reference that reads each in turn.
pub struct dict<K, V>::key_iterator : sized_iterator<&K> {
var _from: dict<K, V>::iterator;
}
#! Gives the next key.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the key; otherwise, `nothing`.
pub def dict<K, V>::key_iterator::next(&mut this): maybe<&K> {
if this._from.next() is some(&entry) {
return &entry.key;
}
return nothing {};
}
#! How many keys the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def dict<K, V>::key_iterator::remaining(&this): u64 {
return this._from.remaining();
}
#! Walks the values of a dictionary, giving a reference that reads each in turn.
pub struct dict<K, V>::value_iterator : sized_iterator<&V> {
var _from: dict<K, V>::iterator;
}
#! Gives the next value.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the value; otherwise, `nothing`.
pub def dict<K, V>::value_iterator::next(&mut this): maybe<&V> {
if this._from.next() is some(&entry) {
return &entry.value;
}
return nothing {};
}
#! How many values the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def dict<K, V>::value_iterator::remaining(&this): u64 {
return this._from.remaining();
}
#! Hashes the dictionary provided.
#! @param this The dictionary to hash.
#! @returns The hash code of the dictionary, which dictionaries holding the same
#! keys share however their entries are arranged.
#! @remarks Only the keys are hashed, and they are added rather than combined in
#! order, since two equal dictionaries may hold them in different
#! places.
pub def dict<K, V>::hash(&this): u64 {
var code := 0u;
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
code += mix(held.hash, 0x9E3779B97F4A7C15);
at = held.next;
}
}
return mix(code, this._len);
}
def dict<K, V>::find(&this, key: &K): i64 {
if this._len == 0 {
return -1;
}
val code := hash::<K>(key);
var at := this._bkt[dict::<K, V>::home(code, this._cap)] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
return at if held.hash == code && equals::<K>(&held.key, key);
at = held.next;
}
return -1;
}
# The bucket of a hash among a power of two of them. The hash is spread first, so
# that keys differing only in their high bits, as pairs packed into one integer
# do, and integers, which are their own hash, still fall in buckets of their own.
def dict<K, V>::home(code: u64, size: u64): u64 {
return (((code ^ (code >> 32)) * 0x9E3779B97F4A7C15) >> 32) & (size - 1);
}
def dict<K, V>::release(&mut this, index: u64): void {
this.close_entry(index);
# The entry is emptied where setting another key in it would close what it held.
if const K is closeable || V is closeable {
memset((this._ent + index) as *mut u8, 0, bytes_of::<dict<K, V>::entry>(1));
}
}
def dict<K, V>::close_entry(&mut this, index: u64): void {
close(&mut this._ent[index].key);
close(&mut this._ent[index].value);
}
def dict<K, V>::free(&mut this, from: u64, to: u64): void {
var index := to;
while index > from {
index--;
this._ent[index].next = this._fre;
this._fre = index as i64;
}
}
# Gives the dictionary room for more keys, doubling it.
def dict<K, V>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the dictionary room for a number of keys, where it has less. An allocator
# that gives no memory stops the program, as `acquire` and `resize` do.
def dict<K, V>::grow(&mut this, wanted: u64): void {
if wanted <= this._cap {
return;
}
# There is a power of two of buckets, which `home` masks a hash to.
var size: u64 = 4;
while size < wanted {
size *= 2;
}
# A bucket holding 0 holds no key.
val buckets := acquire::<i64>(this._alc, size);
memset(buckets as *mut u8, 0, bytes_of::<i64>(size));
val entries := this._ent == null
? acquire::<dict<K, V>::entry>(this._alc, size)
: resize::<dict<K, V>::entry>(this._alc, this._ent, this._cap, size);
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
val moved := dict::<K, V>::home(entries[here].hash, size);
at = entries[here].next;
entries[here].next = buckets[moved] - 1;
buckets[moved] = here as i64 + 1;
}
}
if this._bkt != null {
dispose::<i64>(this._alc, this._bkt, this._cap);
}
val from := this._cap;
this._bkt = buckets;
this._ent = entries;
this._cap = size;
this.free(from, size);
}