Files
2026-11-14 15:32:55 -06:00

573 lines
18 KiB
Plaintext

#! @file hashset.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `hashset` container. Hash sets are an unordered
#! container that holds each value once, finding it by its hash.
module std::containers;
#! A `hashset` is an unordered data container that holds values, each of them
#! once.
#!
#! They are useful wherever what matters of a value is whether it is held, such
#! as the names already seen, the nodes already visited, and the members two
#! groups have in common.
#!
#! It is laid out as a dictionary is, holding values rather than keys. Its
#! entries live in one block, and it has a bucket for each of them. A bucket
#! holds the first entry whose value 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 value are chained the same way from `_fre`, and `-1`
#! ends either chain. Entries keep their places as the set grows, so only its
#! buckets are made again.
#! @tparam T The type of its values, which are `hashable` and `equatable`.
pub struct hashset<T>
: owning
, hashable
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _bkt: *mut i64;
var _ent: *mut hashset<T>::entry;
var _len: u64;
var _cap: u64;
var _fre: i64;
}
#! A value of a set, with the hash it is found by and the next entry of its
#! bucket, or of the free chain.
struct hashset<T>::entry {
var value: T;
var hash: u64;
var next: i64;
}
#! Provides read only access to the length of a set.
#! @param this The set to get the length of.
#! @returns The number of values it holds.
pub val hashset<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a set.
#! @param this The set to get the capacity of.
#! @returns The number of values it has room for before it grows.
pub val hashset<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a set is empty.
#! @param this The set to check.
#! @returns Whether the set holds no values.
pub val hashset<T>::empty: bool {
get => this._len == 0;
}
#! Indicates if a set is full.
#! @param this The set to check.
#! @returns Whether the next new value makes it grow.
pub val hashset<T>::full: bool {
get => this._len == this._cap;
}
#! Creates a new set with no allocator, which takes memory once something is
#! added.
#! @returns The created set, which holds no values yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def hashset<T>::new(): hashset<T> {
return hashset::<T>::new(nothing{});
}
#! Creates a new set with an optional allocator, which takes memory once
#! something is added.
#! @param alloc The optional allocator for the memory backing of the set.
#! @returns The created set, which holds no values yet.
pub def hashset<T>::new(alloc: maybe<&mut allocator>): hashset<T> {
return hashset::<T> { _alc = alloc, _bkt = null, _ent = null, _len = 0, _cap = 0, _fre = -1 };
}
#! Creates a new set with an optional allocator and room for some values.
#! @param size The number of values to make room for, which may be none.
#! @param alloc The optional allocator for the memory backing of the set.
#! @returns The created set, which holds no values yet.
pub def hashset<T>::new(size: u64, alloc: maybe<&mut allocator>): hashset<T> {
var made := hashset::<T>::new(alloc);
made.reserve(size);
return made;
}
#! Builds a set holding copies of another's values, with its allocator.
#! @param other The set to copy from.
#! @returns The copy, which owns its own memory and values.
#! @remarks Values are copied by `copyable` where they provide one, so a value
#! owning memory is copied rather than shared.
pub def hashset<T>::copy_of(other: &hashset<T>): hashset<T> {
var made := hashset::<T>::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.add(copy::<T>(&held.value), held.hash);
at = held.next;
}
}
return made;
}
#! Creates a new set by moving the data of another set into it.
#! @param other The set to move from, which holds nothing after.
#! @returns The moved set, 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 hashset<T>::move_of(other: &mut hashset<T>): hashset<T> {
val made: hashset<T> = hashset {
_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;
}
#! Adds a value the set does not hold yet.
#! @param this The set to add the value to.
#! @param value The value to add.
#! @returns Whether the value was new and was added. A value the set already
#! holds an equal of is closed, and the one it holds kept.
#! @remarks A new value takes an entry of its own, which grows the set when it
#! is full. An allocator that gives no more memory stops the program.
pub def hashset<T>::insert(&mut this, value: T): bool {
val code := hash::<T>(&value);
if this.find(&value, code) >= 0 {
return false;
}
this.add(move(value), code);
return true;
}
#! Tells whether the set holds a value.
#! @param this The set to search.
#! @param value The value to look for.
#! @returns Whether the set holds a value equal to it.
pub def hashset<T>::contains(&this, value: &T): bool {
return this.find(value, hash::<T>(value)) >= 0;
}
#! Gets the value the set holds that equals the one given, if it holds one.
#! @param this The set to get the value from.
#! @param value The value to look for.
#! @returns The value the set holds, or `none` where it holds none equal to it.
#! @remarks The value held is the set's own, which equals the one given but may
#! be another, as two `string`s holding the same text are, so a set
#! can keep one of each value for whatever asks for it.
pub def hashset<T>::get(&this, value: &T): maybe<&T> {
val found := this.find(value, hash::<T>(value));
if found < 0 {
return nothing {};
}
return &this._ent[found as u64].value;
}
#! Removes a value, if the set holds one equal to it.
#! @param this The set to remove from.
#! @param value The value to remove.
#! @returns Whether the set held the value and it was removed.
#! @remarks The value is closed where it closes, or holds what does, and the
#! entry goes back on the free chain for the next value.
pub def hashset<T>::remove(&mut this, value: &T): bool {
if this._len == 0 {
return false;
}
val code := hash::<T>(value);
val home := hashset::<T>::home(code, this._cap);
var prev := -1 as i64;
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
if held.hash == code && equals::<T>(&held.value, value) {
this.unlink(home, prev, at as u64);
return true;
}
prev = at;
at = held.next;
}
return false;
}
#! Adds a copy of each value of another set that this one does not hold, so that
#! it holds what either held.
#! @param this The set to add to.
#! @param other The set whose values are added.
#! @remarks Values are copied by `copyable` where they provide one, and the
#! other set is left as it was.
pub def hashset<T>::union_with(&mut this, other: &hashset<T>): void {
for home in 0..other._cap {
var at := other._bkt[home] - 1;
while at >= 0 {
val held := &other._ent[at as u64];
if this.find(&held.value, held.hash) < 0 {
this.add(copy::<T>(&held.value), held.hash);
}
at = held.next;
}
}
}
#! Removes each value another set does not hold, so that the set holds what both
#! held.
#! @param this The set to remove from.
#! @param other The set whose values are kept.
#! @remarks The values removed are closed where they close, or hold what does.
pub def hashset<T>::intersect_with(&mut this, other: &hashset<T>): void {
this.keep(other, true);
}
#! Removes each value another set holds, so that the set holds what only it held.
#! @param this The set to remove from.
#! @param other The set whose values are removed.
#! @remarks The values removed are closed where they close, or hold what does.
pub def hashset<T>::subtract(&mut this, other: &hashset<T>): void {
this.keep(other, false);
}
#! Tells whether another set holds every value of this one.
#! @param this The set whose values are looked for.
#! @param other The set to look in.
#! @returns Whether each value of this set is in the other, which an empty set's
#! are of any set.
pub def hashset<T>::is_subset_of(&this, other: &hashset<T>): 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];
return false if other.find(&held.value, held.hash) < 0;
at = held.next;
}
}
return true;
}
#! Tells whether the set holds no value another holds.
#! @param this The set to compare against.
#! @param other The set to compare with.
#! @returns Whether the two hold no value in common.
#! @remarks The values of the smaller set are looked for in the larger.
pub def hashset<T>::is_disjoint_from(&this, other: &hashset<T>): bool {
if this._len > other._len {
return other.is_disjoint_from(this);
}
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
return false if other.find(&held.value, held.hash) >= 0;
at = held.next;
}
}
return true;
}
#! Reserves room for a number of values, so that adding that many grows the set
#! no further.
#! @param this The set to reserve room in.
#! @param count The number of values to make room for.
pub def hashset<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes every value from a set.
#! @param this The set to clear.
#! @remarks Values that close, or hold what does, are closed. The backing memory
#! is kept for the values added after.
pub def hashset<T>::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 value of a set, then disposes the backing memory.
#! @param this The set to close.
#! @remarks The memory is given back as it stands, so the values are closed
#! where they close, or hold what does, but the entries are not
#! emptied.
pub def hashset<T>::close(&mut this): void {
if const T 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;
close(&mut this._ent[here].value);
}
}
}
this._len = 0;
if this._bkt != null {
dispose::<i64>(this._alc, this._bkt, this._cap);
dispose::<hashset<T>::entry>(this._alc, this._ent, this._cap);
}
this._bkt = null;
this._ent = null;
this._cap = 0;
this._fre = -1;
}
#! Compares one set to another for equality.
#! @param this The set to compare against.
#! @param other The set to compare with.
#! @returns Whether both hold the same values, however they are arranged.
pub def hashset<T>::equals(&this, other: &hashset<T>): bool {
return this._len == other._len && this.is_subset_of(other);
}
#! Walks the values of a set, giving a reference that reads each in turn, which
#! is what `iter` lends and `for x in s` walks. Values come in no particular
#! order, and each once.
pub struct hashset<T>::iterator : sized_iterator<&T> {
var _bkt: *mut i64;
var _ent: *mut hashset<T>::entry;
var _cap: u64;
var _bucket: u64;
var _at: i64;
var _left: u64;
}
#! Gives the next value of the set.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the next value; otherwise, `nothing`.
pub def hashset<T>::iterator::next(&mut this): maybe<&T> {
# Every entry holding a value 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].value;
}
#! How many values the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def hashset<T>::iterator::remaining(&this): u64 {
return this._left;
}
#! Lends an iterator that reads the values of the set, which `for x in s` walks.
#! There is none that writes them, since a value changed where it is would no
#! longer be found by its hash.
#! @param this The set to walk.
#! @returns The iterator, which is only good until the set changes or closes.
pub def hashset<T>::iter(&this): hashset<T>::iterator {
return hashset::<T>::iterator { _bkt = this._bkt, _ent = this._ent, _cap = this._cap, _bucket = 0, _at = -1, _left = this._len };
}
#! An iterator that reads the values of the set, as `iter` lends.
#! @param this The set to walk.
#! @returns The iterator, which is only good until the set changes or closes.
pub val hashset<T>::iterator: hashset<T>::iterator {
get => this.iter();
}
#! Hashes the set provided.
#! @param this The set to hash.
#! @returns The hash code of the set, which sets holding the same values share
#! however their entries are arranged.
#! @remarks The values' hashes are added rather than combined in order, since
#! two equal sets may hold them in different places.
pub def hashset<T>::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);
}
# The entry holding a value of a hash, or -1 where the set holds none.
def hashset<T>::find(&this, value: &T, code: u64): i64 {
if this._len == 0 {
return -1;
}
var at := this._bkt[hashset::<T>::home(code, this._cap)] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
return at if held.hash == code && equals::<T>(&held.value, value);
at = held.next;
}
return -1;
}
# Gives a value of a hash, which the set does not hold, an entry of its own,
# growing the set when it is full.
def hashset<T>::add(&mut this, value: T, code: u64): void {
if this._fre < 0 {
this.grow();
}
val slot := this._fre as u64;
val home := hashset::<T>::home(code, this._cap);
this._fre = this._ent[slot].next;
this._ent[slot] = hashset::<T>::entry {
value = move(value),
hash = code,
next = this._bkt[home] - 1
};
this._bkt[home] = slot as i64 + 1;
this._len++;
}
# Takes an entry out of the chain of its bucket, after the entry before it there,
# or -1 where it is first, closes its value, and puts it on the free chain.
def hashset<T>::unlink(&mut this, home: u64, prev: i64, here: u64): void {
val next := this._ent[here].next;
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 = here as i64;
this._len--;
}
# Removes each value whose being held by another set is not what is kept: those
# it holds are kept where `held` is true, and those it does not where it is false.
# The other may be this set, since each entry is looked for before it is removed.
def hashset<T>::keep(&mut this, other: &hashset<T>, held: bool): void {
for home in 0..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 (other.find(&this._ent[here].value, this._ent[here].hash) >= 0) == held {
prev = at;
} else {
this.unlink(home, prev, here);
}
at = next;
}
}
}
# The bucket of a hash among a power of two of them, spread as a dictionary's is.
def hashset<T>::home(code: u64, size: u64): u64 {
return (((code ^ (code >> 32)) * 0x9E3779B97F4A7C15) >> 32) & (size - 1);
}
def hashset<T>::release(&mut this, index: u64): void {
close(&mut this._ent[index].value);
# The entry is emptied where adding another value in it would close what it held.
if const T is closeable {
memset((this._ent + index) as *mut u8, 0, bytes_of::<hashset<T>::entry>(1));
}
}
def hashset<T>::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 set room for more values, doubling it.
def hashset<T>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the set room for a number of values, where it has less. An allocator that
# gives no memory stops the program, as `acquire` and `resize` do.
def hashset<T>::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 value.
val buckets := acquire::<i64>(this._alc, size);
memset(buckets as *mut u8, 0, bytes_of::<i64>(size));
val entries := this._ent == null
? acquire::<hashset<T>::entry>(this._alc, size)
: resize::<hashset<T>::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 := hashset::<T>::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);
}