Files
std/containers/interner.sakura
T
2026-11-10 09:08:39 -06:00

405 lines
15 KiB
Plaintext

#! @file interner.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for an `interner` container. Interners give each
#! value an ID, the same for equal values, counting up in the order values are
#! first given.
module std::containers;
#! An `interner` gives each distinct value an ID of its own, a `u32` counted up
#! from zero in the order the values are first given, and keeps one copy of
#! each, which its ID reads back.
#!
#! They are useful wherever values are compared or kept many times over, such
#! as the names a compiler reads and the strings a file writes once each: two
#! values are equal exactly where their IDs are, and an ID is a small number
#! wherever the value would be large.
#!
#! Nothing is removed but by `clear`, so an ID is good for as long as the
#! interner is. Its values are held one after another, by ID, and a table of
#! slots finds a value's ID by its hash. The table is open, a power of two of
#! slots at least twice as many as the values, and a value is in the first slot
#! from where its hash begins that is free or holds it. A slot is 0, or one more
#! than an ID with the high half of the value's hash above it, which most values
#! that differ are told apart by without being compared.
#! @tparam T The type of its values, which are `hashable` and `equatable`.
pub struct interner<T>
: owning
, hashable
, indexable<u32, T>
, viewable<T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _val: vector<T>;
var _slt: *mut u64;
var _cap: u64;
}
#! Provides read only access to the length of an interner.
#! @param this The interner to get the length of.
#! @returns The number of values it holds, which is one more than the newest's
#! ID.
pub val interner<T>::length: u64 {
get => this._val.length;
}
#! Indicates if an interner is empty.
#! @param this The interner to check.
#! @returns Whether the interner holds no values.
pub val interner<T>::is_empty: bool {
get => this._val.length == 0;
}
#! Creates a new interner with no allocator, which takes memory once something
#! is interned.
#! @returns The created interner, which holds no values yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def interner<T>::new(): interner<T> {
return interner::<T>::new(nothing{});
}
#! Creates a new interner with an optional allocator, which takes memory once
#! something is interned.
#! @param alloc The optional allocator for the memory backing of the
#! interner.
#! @returns The created interner, which holds no values yet.
pub def interner<T>::new(alloc: maybe<&mut allocator>): interner<T> {
return interner::<T> { _alc = alloc, _val = vector::<T>::new(alloc), _slt = null, _cap = 0 };
}
#! Creates a new interner 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
#! interner.
#! @returns The created interner, which holds no values yet.
pub def interner<T>::new(size: u64, alloc: maybe<&mut allocator>): interner<T> {
var made := interner::<T>::new(alloc);
made.reserve(size);
return made;
}
#! Builds an interner holding copies of another's values, each with the same
#! ID, with its allocator.
#! @param other The interner 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. The slots are copied as
#! they are, since a copy hashes as what it copies does.
pub def interner<T>::copy_of(other: &interner<T>): interner<T> {
var made := interner::<T> {
_alc = other._alc,
_val = vector::<T>::copy_of(&other._val),
_slt = null,
_cap = other._cap
};
if other._slt != null {
made._slt = acquire::<u64>(other._alc, other._cap);
memcpy(made._slt as *mut u8, other._slt as *u8, bytes_of::<u64>(other._cap));
}
return made;
}
#! Creates a new interner by moving the data of another interner into it.
#! @param other The interner to move from, which holds nothing after.
#! @returns The moved interner, which takes the memory and allocator with it.
#! @remarks Nothing is copied: the memory moves as it stands, and the other is
#! left empty rather than dead, so closing it afterwards is harmless.
pub def interner<T>::move_of(other: &mut interner<T>): interner<T> {
val made: interner<T> = interner {
_alc = other._alc,
_val = move(&mut other._val),
_slt = other._slt,
_cap = other._cap
};
other._slt = null;
other._cap = 0;
return made;
}
#! Gives the ID of a value, adding the value where the interner holds none
#! equal to it.
#! @param this The interner to intern the value in.
#! @param value The value to intern.
#! @returns The ID of the value equal to it the interner holds, or else the new
#! ID it is given, one more than the newest's.
#! @remarks A value equal to one held is closed, and the one held kept. A new
#! value grows the interner where it needs room, and an allocator that
#! gives no more memory stops the program, as does a new value past
#! the last ID a `u32` holds.
pub def interner<T>::intern(&mut this, value: T): u32 {
if this._cap == 0 {
this.rehash(8);
}
val code := interner::<T>::spread(hash::<T>(&value));
val at := this.slot_of(&value, code);
val held := this._slt[at];
if held != 0 {
return ((held & 0xFFFFFFFF) - 1) as u32;
}
return this.add(move(value), code, at);
}
#! Gives the ID of the value whose view equals a view, making the value from the
#! view where the interner holds none, so that the view is copied only where it
#! is new, as a `strview` is into a `string`.
#! @tparam U The type of the elements of the view.
#! @param this The interner to intern the value in.
#! @param view The view of the value to intern.
#! @returns The ID of the value viewed as it, or else the new ID of the value
#! made from it, one more than the newest's.
#! @remarks The values are `viewable`, are made by a `from` taking the view and
#! the interner's allocator, as `string::from` is, and must hash as
#! their views do, as a `string` hashes as its text. A new value grows
#! the interner as `intern` does.
pub def interner<T>::intern_view<U>(&mut this, view: span<U>): u32 {
if const !(T is viewable<U>) || !(T is interner_made<U>) {
compile_error("`intern_view` finds values by their views and makes them from those views, so they are `viewable` as the view given, with a `from` taking it and an allocator.");
}
if this._cap == 0 {
this.rehash(8);
}
val code := interner::<T>::spread(view.hash());
val mask := this._cap - 1;
var at := code & mask;
while true {
val held := this._slt[at];
break if held == 0;
if (held >> 32) == (code >> 32) {
val id := (held & 0xFFFFFFFF) - 1;
return id as u32 if this._val.data[id].view() == view;
}
at = (at + 1) & mask;
}
return this.add(T::from(view, this._alc), code, at);
}
# A value made from a view of its elements and an allocator, as a `string` is
# from a `strview`, which `intern_view` makes what it does not hold of.
trait interner_made<U> {
def from(view: span<U>, alloc: maybe<&mut allocator>): self;
}
#! Gives the ID of a value, if the interner holds one equal to it.
#! @param this The interner to search.
#! @param value The value to look for.
#! @returns The ID of the value equal to it, or `none` where it holds none.
pub def interner<T>::find(&this, value: &T): maybe<u32> {
if this._cap == 0 {
return nothing {};
}
val held := this._slt[this.slot_of(value, interner::<T>::spread(hash::<T>(value)))];
if held == 0 {
return nothing {};
}
return ((held & 0xFFFFFFFF) - 1) as u32;
}
#! Gives the ID of the value whose view equals a view, if the interner holds
#! one, without making a value to look for, as a `string` would be made to look
#! for a `strview`.
#! @tparam U The type of the elements of the view.
#! @param this The interner to search.
#! @param view The view to look for.
#! @returns The ID of the value viewed as it, or `none` where it holds none.
#! @remarks The values are `viewable`, and must hash as their views do, as a
#! `string` hashes as its text, or this finds none of them. A value
#! that is to be interned where it is not found is interned at once
#! by `intern_view`.
pub def interner<T>::find_view<U>(&this, view: span<U>): maybe<u32> {
if const !(T is viewable<U>) {
compile_error("`find_view` finds values by their views, so they are `viewable` as the view given.");
}
if this._cap == 0 {
return nothing {};
}
val code := interner::<T>::spread(view.hash());
val mask := this._cap - 1;
var at := code & mask;
while true {
val held := this._slt[at];
break if held == 0;
if (held >> 32) == (code >> 32) {
val id := (held & 0xFFFFFFFF) - 1;
return id as u32 if this._val.data[id].view() == view;
}
at = (at + 1) & mask;
}
return nothing {};
}
#! Tells whether the interner holds a value.
#! @param this The interner to search.
#! @param value The value to look for.
#! @returns Whether it holds a value equal to it.
pub def interner<T>::contains(&this, value: &T): bool {
return this.find(value) is some;
}
#! Reads the value of an ID, which `i[id]` calls.
#! @param this The interner to read.
#! @param id The ID, below `length`, past which a checked program stops.
#! @returns The value, which is only good until the interner grows or closes.
#! There is none that writes it, since a value changed where it is
#! would no longer be found by its hash.
pub def interner<T>::at(&this, id: u32): &T {
return this._val.at(id as u64);
}
#! Lends a view of the values, by ID, without copying them.
#! @param this The interner to view.
#! @returns A view of its values, the value of each ID at that index, which is
#! only good until the interner grows or closes.
pub def interner<T>::view(&this): span<T> {
return this._val.view();
}
#! Reserves room for a number of values, so that interning that many new ones
#! grows the interner no further.
#! @param this The interner to reserve room in.
#! @param count The number of values to make room for.
pub def interner<T>::reserve(&mut this, count: u64): void {
this._val.reserve(count);
var size: u64 = this._cap != 0 ? this._cap : 8;
while size < count * 2 {
size *= 2;
}
if size > this._cap {
this.rehash(size);
}
}
#! Removes every value from an interner, so that the next value interned is
#! given the ID 0 again.
#! @param this The interner to clear.
#! @remarks Values that close, or hold what does, are closed. The backing memory
#! is kept for the values interned after.
pub def interner<T>::clear(&mut this): void {
this._val.clear();
if this._slt != null {
memset(this._slt as *mut u8, 0, bytes_of::<u64>(this._cap));
}
}
#! Removes every value of an interner, then disposes the backing memory.
#! @param this The interner to close.
#! @remarks Values that close, or hold what does, are closed.
pub def interner<T>::close(&mut this): void {
this._val.close();
if this._slt != null {
dispose::<u64>(this._alc, this._slt, this._cap);
}
this._slt = null;
this._cap = 0;
}
#! Compares one interner to another for equality.
#! @param this The interner to compare against.
#! @param other The interner to compare with.
#! @returns Whether both hold equal values, each with the same ID.
pub def interner<T>::equals(&this, other: &interner<T>): bool {
return this._val.equals(&other._val);
}
#! What `iter(&this)` lends, by the name `iterable` asks for it by.
pub type interner<T>::iterator = interner<T>::cursor;
#! What `iter(&this)` lends, which reads the values by ID.
pub type interner<T>::cursor = span<T>::cursor;
#! Lends a cursor that reads the values in the order of their IDs, which `for x
#! in i` walks.
#! @param this The interner to walk.
#! @returns The cursor, which is only good until the interner grows or closes.
pub def interner<T>::iter(&this): span<T>::cursor {
return this._val.iter();
}
#! Hashes the values, in the order of their IDs.
#! @param this The interner to hash.
#! @returns The hash code, which interners holding equal values with the same
#! IDs share.
pub def interner<T>::hash(&this): u64 {
return this._val.hash();
}
# The slot holding the ID of a value of a hash, or the free slot it would be in.
# There is always one free, as the slots are at least twice as many as the values.
def interner<T>::slot_of(&this, value: &T, code: u64): u64 {
val mask := this._cap - 1;
var at := code & mask;
while true {
val held := this._slt[at];
break if held == 0;
if (held >> 32) == (code >> 32) && equals::<T>(&this._val.data[(held & 0xFFFFFFFF) - 1], value) {
break;
}
at = (at + 1) & mask;
}
return at;
}
# Holds a value of a hash, which the interner holds none equal to, giving it the
# next ID in the free slot found for it, then grows the slots where the values
# are more than half of them.
def interner<T>::add(&mut this, value: T, code: u64, at: u64): u32 {
val id := this._val.length;
if id >= 0xFFFFFFFF {
fault("The interner has no ID left for a new value.");
}
this._val.append(move(value));
this._slt[at] = (code & 0xFFFFFFFF00000000u) | (id + 1);
if this._val.length * 2 > this._cap {
this.rehash(this._cap * 2);
}
return id as u32;
}
# Makes the slots again, a power of two of them at least twice the values,
# putting each value's ID in its slot again. An allocator that gives no memory
# stops the program, as `acquire` does.
def interner<T>::rehash(&mut this, size: u64): void {
val slots := acquire::<u64>(this._alc, size);
memset(slots as *mut u8, 0, bytes_of::<u64>(size));
val mask := size - 1;
for id in 0..this._val.length {
val code := interner::<T>::spread(hash::<T>(&this._val.data[id]));
var at := code & mask;
while slots[at] != 0 {
at = (at + 1) & mask;
}
slots[at] = (code & 0xFFFFFFFF00000000u) | (id + 1);
}
if this._slt != null {
dispose::<u64>(this._alc, this._slt, this._cap);
}
this._slt = slots;
this._cap = size;
}
# Spreads a hash, so that its low bits say where it begins in the slots and its
# high half tells it from others there, however the values hash, as integers
# hash as themselves.
def interner<T>::spread(code: u64): u64 {
var bits := (code ^ (code >> 31)) * 0xBF58476D1CE4E5B9u;
return bits ^ (bits >> 29);
}