Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-13 21:54:22 -06:00
commit 1ec33daf7a
1624 files changed
+43422

No files matched your search

+169
View File
@@ -0,0 +1,169 @@
#! @file arc.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `arc`, one value on the heap that every copy owns, counted
#! atomically, for values threads share, as Rust's `Arc`; and `arc_weak`, which
#! refers to it without keeping it.
#!
#! Copies count with a relaxed add, as nothing is read through the count, and
#! close with a subtraction that releases, so what each owner did to the value
#! comes before the last owner closes it, which acquires before it does, as
#! Rust's `Arc` and C++'s `shared_ptr` do.
module std::containers;
# What an `arc` points at: the counts, then the value. The weak count holds one
# for all the owners together, as `rc_cell` does.
struct arc_cell<T> {
var owners: atomic<u64>;
var weak: atomic<u64>;
var value: T;
}
#! One value on the heap, owned by every copy, which `copy` makes, on any
#! thread, and closed where the last copy closes.
#!
#! Threads reading what they share need nothing more, but what they change
#! through `get` is guarded as any memory threads share is: an `arc<mutex<T>>`
#! or an `arc<atomic<T>>` is the usual way. An `arc` is one word, the counted
#! value's address, which is never null, so `maybe<arc<T>>` is one word too.
#! @tparam T What it holds.
pub struct arc<T> : owning, copyable, moveable {
var _at: &mut arc_cell<T>;
}
#! A reference to a value an `arc` owns that does not keep it: `lock` gives an
#! owner while any other is left.
#! @tparam T What it refers to.
pub struct arc_weak<T> : owning, copyable, moveable {
var _at: *mut arc_cell<T>;
}
#! Moves a value to the heap, with one owner.
#! @param value The value.
#! @returns Its first owner.
pub def arc<T>::new(value: T): arc<T> {
val at := allocate_for::<arc_cell<T>>(size_of::<arc_cell<T>>()) as *mut arc_cell<T>;
at[0] = arc_cell::<T> {
owners = atomic::<u64>::new(1),
weak = atomic::<u64>::new(1),
value = move(&mut value)
};
return arc::<T> { _at = through(at) };
}
#! Lends the value an `arc` owns.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def arc<T>::get(&this): &T {
return &this._at.value;
}
#! Lends the value an `arc` owns, to be changed, which threads guard as they do
#! any memory they share.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def arc<T>::get(&mut this): &mut T {
return &mut this._at.value;
}
#! How many owners share the value, which other threads may change at once.
#! @param this An owner.
#! @returns How many, this one among them.
pub def arc<T>::count(&this): u64 {
return this._at.owners.load(order::relaxed);
}
#! A reference to the value that does not keep it.
#! @param this An owner.
#! @returns The reference.
pub def arc<T>::weak(&this): arc_weak<T> {
_ = this._at.weak.fetch_add(1, order::relaxed);
return arc_weak::<T> { _at = this._at as *mut arc_cell<T> };
}
#! Makes another owner of the same value.
#! @param other An owner.
#! @returns The new owner.
pub def arc<T>::copy_of(other: &arc<T>): arc<T> {
_ = other._at.owners.fetch_add(1, order::relaxed);
return arc::<T> { _at = other._at };
}
#! Moves an owner, leaving the one moved from empty.
#! @param other The owner to move from.
#! @returns The owner it was.
pub def arc<T>::move_of(other: &mut arc<T>): arc<T> {
val made := arc::<T> { _at = other._at };
(other as *mut u64)[0] = 0;
return made;
}
#! Closes an owner: the value too where it was the last, and the memory where no
#! weak reference is left either.
#! @param this The owner, which is empty after.
pub def arc<T>::close(&mut this): void {
val at := this._at as *mut arc_cell<T>;
return if at == null;
(this as *mut u64)[0] = 0;
return if at[0].owners.fetch_sub(1, order::release) != 1;
fence(order::acquire);
close(&mut at[0].value);
arc_cell_let_go::<T>(at);
}
#! An owner of the value a weak reference refers to, where any is left.
#! @param this The weak reference.
#! @returns The new owner, or nothing where the last closed.
pub def arc_weak<T>::lock(&this): maybe<arc<T>> {
return nothing {} if this._at == null;
var count := this._at[0].owners.load(order::relaxed);
while count != 0 {
if this._at[0].owners.compare_exchange_weak(count, count + 1, order::acquire, order::relaxed) is error(found) {
count = found;
} else {
return arc::<T> { _at = through(this._at) };
}
}
return nothing {};
}
#! Makes another weak reference to the same value.
#! @param other A weak reference.
#! @returns The new one.
pub def arc_weak<T>::copy_of(other: &arc_weak<T>): arc_weak<T> {
if other._at != null {
_ = other._at[0].weak.fetch_add(1, order::relaxed);
}
return arc_weak::<T> { _at = other._at };
}
#! Moves a weak reference, leaving the one moved from empty.
#! @param other The weak reference to move from.
#! @returns The weak reference it was.
pub def arc_weak<T>::move_of(other: &mut arc_weak<T>): arc_weak<T> {
val made := arc_weak::<T> { _at = other._at };
other._at = null;
return made;
}
#! Closes a weak reference, giving back the memory where it was the last
#! reference of any kind.
#! @param this The weak reference, which is empty after.
pub def arc_weak<T>::close(&mut this): void {
val at := this._at;
return if at == null;
this._at = null;
arc_cell_let_go::<T>(at);
}
# Lets go of the weak count's one, giving back the memory where it was the last.
def arc_cell_let_go<T>(at: *mut arc_cell<T>): void {
if at[0].weak.fetch_sub(1, order::release) == 1 {
fence(order::acquire);
raw_release(at as *mut u8);
}
}
+504
View File
@@ -0,0 +1,504 @@
#! @file chain.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `chain` container. Chains are a structured
#! container that stores each element in a node of its own, linked to the nodes
#! before and after it.
module std::containers;
#! A `chain` is a structured data container, doubly linked, that stores each of
#! its elements in a node of its own.
#!
#! They are useful where elements are added and removed at either end, and where
#! an element must never move once it is added, since each keeps its own node
#! until it is removed. Reaching an element by index walks the chain from
#! whichever end is nearer.
#! @tparam T The type of its elements.
pub struct chain<T>
: owning
, hashable
, indexable<u64, T>
, assignable<u64, T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _hed: *mut chain<T>::node;
var _tal: *mut chain<T>::node;
var _len: u64;
}
#! An element of a chain, with the nodes before and after it.
struct chain<T>::node {
var value: T;
var prev: *mut chain<T>::node;
var next: *mut chain<T>::node;
}
#! Walks the elements of a chain from its front, giving a reference that reads
#! each in turn, which is what `iter(&this)` lends and `for x` and `for &x`
#! walk.
pub struct chain<T>::iterator : sized_iterator<&T>, backward_iterator<&T> {
var _at: *mut chain<T>::node;
var _end: *mut chain<T>::node;
var _left: u64;
}
#! Gives the next element of the chain.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def chain<T>::iterator::next(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &(*here).value;
}
#! How many elements the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def chain<T>::iterator::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the iterator has left, from the back of the chain.
#! @param this The iterator to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def chain<T>::iterator::next_back(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._end;
this._end = (*here).prev;
this._left = this._left - 1;
return &(*here).value;
}
#! Walks the elements of a chain from its front, giving a reference that writes
#! each in turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
pub struct chain<T>::mutator : sized_iterator<&mut T>, backward_iterator<&mut T> {
var _at: *mut chain<T>::node;
var _end: *mut chain<T>::node;
var _left: u64;
}
#! Gives the next element of the chain, to be written.
#! @param this The mutator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def chain<T>::mutator::next(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &mut (*here).value;
}
#! How many elements the mutator has left to give.
#! @param this The mutator.
#! @returns How many.
pub def chain<T>::mutator::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the mutator has left, from the back of the chain, to
#! be written.
#! @param this The mutator to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def chain<T>::mutator::next_back(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._end;
this._end = (*here).prev;
this._left = this._left - 1;
return &mut (*here).value;
}
#! Provides read only access to the length of a chain.
#! @param this The chain to get the length of.
#! @returns The length of the chain.
pub val chain<T>::length: u64 {
get => this._len;
}
#! Indicates if a chain is empty.
#! @param this The chain to check.
#! @returns Whether the chain is empty.
pub val chain<T>::empty: bool {
get => this._len == 0;
}
#! Creates a new chain with no allocator.
#! @returns The created chain container.
#! @remarks Will use the built in `raw_allocate` and `raw_release` for memory
#! management.
pub def chain<T>::new(): chain<T> {
return chain::<T>::new(nothing{});
}
#! Creates a new chain with an optional allocator.
#! @param alloc The optional allocator for the nodes of the chain.
#! @returns The created chain container, which holds no elements yet.
pub def chain<T>::new(alloc: maybe<&mut allocator>): chain<T> {
return chain::<T> { _alc = alloc, _hed = null, _tal = null, _len = 0 };
}
#! Creates a copy of the provided chain.
#! @param other The chain to copy.
#! @returns The copy, which owns its own nodes and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def chain<T>::copy_of(other: &chain<T>): chain<T> {
var made := chain::<T>::new(other._alc);
var at := other._hed;
while at != null {
made.push_back(copy::<T>(&(*at).value));
at = (*at).next;
}
return made;
}
#! Creates a new chain by moving the nodes of another chain into it.
#! @param other The chain to move elements from, which holds none after.
#! @returns The moved chain, which takes the nodes and allocator with it.
#! @remarks Nothing is copied and no element is touched: the nodes move as they
#! stand, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def chain<T>::move_of(other: &mut chain<T>): chain<T> {
val made: chain<T> = chain {
_alc = other._alc,
_hed = other._hed,
_tal = other._tal,
_len = other._len
};
other._hed = null;
other._tal = null;
other._len = 0;
return made;
}
#! Gets the element at the provided index, walking from the nearer end.
#! @param this The chain to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def chain<T>::at(&this, index: u64): &T {
expects(index < this._len);
return &(*this.node_at(index)).value;
}
#! Gets the element at the provided index, walking from the nearer end.
#! @param this The chain to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def chain<T>::at(&mut this, index: u64): &mut T {
expects(index < this._len);
return &mut (*this.node_at(index)).value;
}
#! Gets the element at an index, if the chain holds one there, for an index
#! that may be past the end in a program that is right.
#! @param this The chain to read.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def chain<T>::get(&this, index: u64): maybe<&T> {
return nothing {} if index >= this._len;
return &(*this.node_at(index)).value;
}
#! Gets the element at an index to write it, if the chain holds one there.
#! @param this The chain to write.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def chain<T>::get(&mut this, index: u64): maybe<&mut T> {
return nothing {} if index >= this._len;
return &mut (*this.node_at(index)).value;
}
#! The element at the front of a chain, which a chain that can be written
#! writes through.
#! @param this The chain to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val chain<T>::first: &T {
get {
expects(!this.empty, "The chain is empty.");
return &(*this._hed).value;
}
get mut {
expects(!this.empty, "The chain is empty.");
return &mut (*this._hed).value;
}
}
#! The element at the back of a chain, which a chain that can be written writes
#! through.
#! @param this The chain to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val chain<T>::last: &T {
get {
expects(!this.empty, "The chain is empty.");
return &(*this._tal).value;
}
get mut {
expects(!this.empty, "The chain is empty.");
return &mut (*this._tal).value;
}
}
#! Pushes a new element onto the front of a chain.
#! @param this The chain to push the value onto.
#! @param value The value to push onto the chain.
#! @remarks An allocator that gives no more memory stops the program.
pub def chain<T>::push_front(&mut this, value: T): void {
this.link(null, this._hed, move(value));
}
#! Pushes a new element onto the back of a chain.
#! @param this The chain to push the value onto.
#! @param value The value to push onto the chain.
#! @remarks An allocator that gives no more memory stops the program.
pub def chain<T>::push_back(&mut this, value: T): void {
this.link(this._tal, null, move(value));
}
#! Pops the element off the front of a chain.
#! @param this The chain to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def chain<T>::pop_front(&mut this): void {
expects(!this.empty, "The chain is empty.");
this.unlink(this._hed);
}
#! Pops the element off the back of a chain.
#! @param this The chain to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def chain<T>::pop_back(&mut this): void {
expects(!this.empty, "The chain is empty.");
this.unlink(this._tal);
}
#! Adds an element at an index, after the elements before it.
#! @param this The chain to insert into.
#! @param index Where the element goes, from `0` to `length`, where `length`
#! appends. An index past that stops a checked program.
#! @param value The element to insert.
#! @remarks An allocator that gives no more memory stops the program.
pub def chain<T>::insert_at(&mut this, index: u64, value: T): void {
expects(index <= this._len);
if index == this._len {
this.push_back(move(value));
return;
}
val next := this.node_at(index);
this.link((*next).prev, next, move(value));
}
#! Removes the element at an index.
#! @param this The chain to remove from.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @remarks The element is closed where it closes, or holds what does.
pub def chain<T>::remove_at(&mut this, index: u64): void {
expects(index < this._len);
this.unlink(this.node_at(index));
}
#! Removes the first element equal to the one given.
#! @param this The chain to remove from.
#! @param elem The element to look for.
#! @returns Whether an element equalled it and was removed.
#! @remarks The element is closed where it closes, or holds what does.
pub def chain<T>::remove(&mut this, elem: &T): bool {
var at := this._hed;
while at != null {
if equals::<T>(&(*at).value, elem) {
this.unlink(at);
return true;
}
at = (*at).next;
}
return false;
}
#! Tells whether the chain holds an element equal to the one given.
#! @param this The chain to search.
#! @param elem The element to look for.
#! @returns Whether any element equals it.
pub def chain<T>::contains(&this, elem: &T): bool {
var at := this._hed;
while at != null {
return true if equals::<T>(&(*at).value, elem);
at = (*at).next;
}
return false;
}
#! Removes all elements from a chain, disposing their nodes.
#! @param this The chain to clear.
#! @remarks Elements that close, or hold what does, are closed.
pub def chain<T>::clear(&mut this): void {
var at := this._hed;
while at != null {
val next := (*at).next;
this.release(at);
at = next;
}
this._hed = null;
this._tal = null;
this._len = 0;
}
#! Removes all elements of a chain, disposing their nodes.
#! @param this The chain to close.
pub def chain<T>::close(&mut this): void {
this.clear();
}
#! Compares one chain to another by equality.
#! @param this The chain to compare against.
#! @param other The chain to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def chain<T>::equals(&this, other: &chain<T>): bool {
if this._len != other._len {
return false;
}
var mine := this._hed;
var theirs := other._hed;
while mine != null {
return false if !equals::<T>(&(*mine).value, &(*theirs).value);
mine = (*mine).next;
theirs = (*theirs).next;
}
return true;
}
#! Lends an iterator that reads the elements from the front of the chain, which
#! `for x in c` walks.
#! @param this The chain to walk.
#! @returns The iterator, which is only good until the chain changes or closes.
pub def chain<T>::iter(&this): chain<T>::iterator {
return chain::<T>::iterator { _at = this._hed, _end = this._tal, _left = this._len };
}
#! Lends a mutator that writes the elements where they are, from the front of
#! the chain, which `for &mut x in c` walks.
#! @param this The chain to walk.
#! @returns The mutator, which is only good until the chain changes or closes.
pub def chain<T>::iter(&mut this): chain<T>::mutator {
return chain::<T>::mutator { _at = this._hed, _end = this._tal, _left = this._len };
}
#! An iterator that reads the elements from the front of the chain, as `iter`
#! lends.
#! @param this The chain to walk.
#! @returns The iterator, which is only good until the chain changes or closes.
pub val chain<T>::iterator: chain<T>::iterator {
get => this.iter();
}
#! A mutator that writes the elements where they are, read of a chain that can
#! be written.
#! @param this The chain to walk.
#! @returns The mutator, which is only good until the chain changes or closes.
pub val chain<T>::mutator: chain<T>::mutator {
get mut => this.iter();
}
#! Hashes the provided chain.
#! @param this The chain to hash.
#! @returns The hashed value of the chain.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def chain<T>::hash(&this): u64 {
var code := this._len;
var at := this._hed;
while at != null {
code = mix(code, hash::<T>(&(*at).value));
at = (*at).next;
}
return code;
}
# The node at an index, which is below the length, walked to from the nearer end.
def chain<T>::node_at(&this, index: u64): *mut chain<T>::node {
if index < this._len / 2 {
var at := this._hed;
for _ in 0..index {
at = (*at).next;
}
return at;
}
var at := this._tal;
for _ in 0..(this._len - 1 - index) {
at = (*at).prev;
}
return at;
}
def chain<T>::link(
&mut this,
prev: *mut chain<T>::node,
next: *mut chain<T>::node,
value: T
): void {
# An allocator that gives no memory stops the program, as `acquire` does.
val made := acquire::<chain<T>::node>(this._alc, 1);
(*made).value = move(value);
(*made).prev = prev;
(*made).next = next;
if prev == null {
this._hed = made;
} else {
(*prev).next = made;
}
if next == null {
this._tal = made;
} else {
(*next).prev = made;
}
this._len++;
}
def chain<T>::unlink(&mut this, node: *mut chain<T>::node): void {
if (*node).prev == null {
this._hed = (*node).next;
} else {
(*(*node).prev).next = (*node).next;
}
if (*node).next == null {
this._tal = (*node).prev;
} else {
(*(*node).next).prev = (*node).prev;
}
this.release(node);
this._len--;
}
def chain<T>::release(&mut this, node: *mut chain<T>::node): void {
close(&mut (*node).value);
dispose::<chain<T>::node>(this._alc, node, 1);
}
+408
View File
@@ -0,0 +1,408 @@
#! @file deque.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `deque` container. Deques are a structured
#! container where data is pushed and popped at either end.
module std::containers;
#! A `deque` is a structured data container, a double-ended queue, that stores
#! its content in order and is pushed and popped at either end.
#!
#! They are useful wherever work is taken from both ends, such as undo
#! histories, sliding windows, and work-stealing schedulers, and wherever a
#! queue must also be indexed.
#!
#! Its elements live in one block used as a ring: the front is at `_hed`, and
#! each element after it is at the next index, wrapping to the start of the
#! block.
#! @tparam T The type of its elements.
pub struct deque<T>
: owning
, hashable
, indexable<u64, T>
, assignable<u64, T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _dat: *mut T;
var _hed: u64;
var _len: u64;
var _cap: u64;
}
#! Provides read only access to the length of a deque.
#! @param this The deque to get the length of.
#! @returns The length of the deque.
pub val deque<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a deque.
#! @param this The deque to get the capacity of.
#! @returns The capacity of the deque.
pub val deque<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a deque is empty.
#! @param this The deque to check.
#! @returns Whether the deque is empty.
pub val deque<T>::empty: bool {
get => this._len == 0;
}
#! Indicates if a deque is full, so the next push makes it grow.
#! @param this The deque to check.
#! @returns Whether the deque is full.
pub val deque<T>::full: bool {
get => this._len == this._cap;
}
#! Creates a new deque with no allocator and a default size.
#! @returns The created deque container.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def deque<T>::new(): deque<T> {
return deque::<T>::new(4, nothing{});
}
#! Creates a new deque with an optional allocator and a default size.
#! @param alloc The optional allocator for the memory backing of the deque.
#! @returns The created deque container.
pub def deque<T>::new(alloc: maybe<&mut allocator>): deque<T> {
return deque::<T>::new(4, alloc);
}
#! Creates a new deque with an optional allocator and a provided size.
#! @param size The initial capacity of the deque, which may be none.
#! @param alloc The optional allocator for the memory backing of the deque.
#! @returns The created deque container, which holds no elements yet.
pub def deque<T>::new(size: u64, alloc: maybe<&mut allocator>): deque<T> {
var made: deque<T> = deque {
_alc = alloc,
_dat = null,
_hed = 0,
_len = 0,
_cap = 0
};
made.reserve(size);
return made;
}
#! Creates a copy of the provided deque.
#! @param other The deque to copy.
#! @returns The copy, which owns its own memory and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def deque<T>::copy_of(other: &deque<T>): deque<T> {
var made := deque::<T>::new(other._len, other._alc);
for index in 0..other._len {
made.push_back(copy::<T>(&other._dat[other.slot(index)]));
}
return made;
}
#! Creates a new deque by moving the data of another deque into it.
#! @param other The deque to move elements from, which holds none after.
#! @returns The moved deque, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no element 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 deque<T>::move_of(other: &mut deque<T>): deque<T> {
val made: deque<T> = deque {
_alc = other._alc,
_dat = other._dat,
_hed = other._hed,
_len = other._len,
_cap = other._cap
};
other._dat = null;
other._hed = 0;
other._len = 0;
other._cap = 0;
return made;
}
#! Gets the element at the provided index, counted from the front.
#! @param this The deque to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def deque<T>::at(&this, index: u64): &T {
expects(index < this._len);
return &this._dat[this.slot(index)];
}
#! Gets the element at the provided index, counted from the front.
#! @param this The deque to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def deque<T>::at(&mut this, index: u64): &mut T {
expects(index < this._len);
return &mut this._dat[this.slot(index)];
}
#! Gets the element at an index, if the deque holds one there, for an index
#! that may be past the end in a program that is right.
#! @param this The deque to read.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def deque<T>::get(&this, index: u64): maybe<&T> {
return nothing {} if index >= this._len;
return &this._dat[this.slot(index)];
}
#! Gets the element at an index to write it, if the deque holds one there.
#! @param this The deque to write.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def deque<T>::get(&mut this, index: u64): maybe<&mut T> {
return nothing {} if index >= this._len;
return &mut this._dat[this.slot(index)];
}
#! The element at the front of a deque, which a deque that can be written
#! writes through.
#! @param this The deque to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val deque<T>::first: &T {
get {
expects(!this.empty, "The deque is empty.");
return &this._dat[this._hed];
}
get mut {
expects(!this.empty, "The deque is empty.");
return &mut this._dat[this._hed];
}
}
#! The element at the back of a deque, which a deque that can be written writes
#! through.
#! @param this The deque to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val deque<T>::last: &T {
get {
expects(!this.empty, "The deque is empty.");
return &this._dat[this.slot(this._len - 1)];
}
get mut {
expects(!this.empty, "The deque is empty.");
return &mut this._dat[this.slot(this._len - 1)];
}
}
#! Pushes a new element onto the front of a deque.
#! @param this The deque to push the value onto.
#! @param value The value to push onto the deque.
#! @remarks An allocator that gives no more memory stops the program.
pub def deque<T>::push_front(&mut this, value: T): void {
if this.full {
this.grow();
}
this._hed = (this._hed + this._cap - 1) % this._cap;
this._dat[this._hed] = move(value);
this._len++;
}
#! Pushes a new element onto the back of a deque.
#! @param this The deque to push the value onto.
#! @param value The value to push onto the deque.
#! @remarks An allocator that gives no more memory stops the program.
pub def deque<T>::push_back(&mut this, value: T): void {
if this.full {
this.grow();
}
this._dat[this.slot(this._len)] = move(value);
this._len++;
}
#! Pops the element off the front of a deque.
#! @param this The deque to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def deque<T>::pop_front(&mut this): void {
expects(!this.empty, "The deque is empty.");
this.release(this._hed);
this._hed = (this._hed + 1) % this._cap;
this._len--;
}
#! Pops the element off the back of a deque.
#! @param this The deque to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def deque<T>::pop_back(&mut this): void {
expects(!this.empty, "The deque is empty.");
this.release(this.slot(this._len - 1));
this._len--;
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the deque provided.
#! @param this The deque to reserve elements for.
#! @param count The number of elements to reserve for a deque.
pub def deque<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes all elements from a deque.
#! @param this The deque to clear.
#! @remarks Elements that close, or hold what does, are closed. The backing data
#! is kept but not disposed.
pub def deque<T>::clear(&mut this): void {
for index in 0..this._len {
this.release(this.slot(index));
}
this._hed = 0;
this._len = 0;
}
#! Removes all elements of a deque then disposes the backing memory.
#! @param this The deque to close.
pub def deque<T>::close(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[this.slot(index)]);
}
}
this._hed = 0;
this._len = 0;
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = null;
this._cap = 0;
}
#! Compares one deque to another by equality.
#! @param this The deque to compare against.
#! @param other The deque to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def deque<T>::equals(&this, other: &deque<T>): bool {
if this._len != other._len {
return false;
}
for index in 0..this._len {
return false if !equals::<T>(
&this._dat[this.slot(index)],
&other._dat[other.slot(index)]
);
}
return true;
}
#! What `iter(&this)` lends, which reads the elements from the front of the
#! deque through its `at`, and which `for x` and `for &x` walk.
pub type deque<T>::iterator = positions_iterator<deque<T>, T>;
#! What `iter(&mut this)` lends, which writes the elements where they are, from
#! the front of the deque, and which `for &mut x` walks.
pub type deque<T>::mutator = position_mutator<deque<T>, T>;
#! Lends an iterator that reads the elements from the front of the deque, which
#! `for x in d` walks.
#! @param this The deque to walk.
#! @returns The iterator, which is only good until the deque changes, moves, or
#! closes.
pub def deque<T>::iter(&this): deque<T>::iterator {
return positions_iterator::<deque<T>, T>::over(this, this._len);
}
#! Lends a mutator that writes the elements where they are, from the front of
#! the deque, which `for &mut x in d` walks.
#! @param this The deque to walk.
#! @returns The mutator, which is only good until the deque changes, moves, or
#! closes.
pub def deque<T>::iter(&mut this): deque<T>::mutator {
return position_mutator::<deque<T>, T>::over(this, this._len);
}
#! An iterator that reads the elements from the front of the deque, as `iter`
#! lends.
#! @param this The deque to walk.
#! @returns The iterator, which is only good until the deque changes, moves, or
#! closes.
pub val deque<T>::iterator: deque<T>::iterator {
get => this.iter();
}
#! A mutator that writes the elements where they are, read of a deque that can
#! be written.
#! @param this The deque to walk.
#! @returns The mutator, which is only good until the deque changes, moves, or
#! closes.
pub val deque<T>::mutator: deque<T>::mutator {
get mut => this.iter();
}
#! Hashes the provided deque.
#! @param this The deque to hash.
#! @returns The hashed value of the deque.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def deque<T>::hash(&this): u64 {
var code := this._len;
for index in 0..this._len {
code = mix(code, hash::<T>(&this._dat[this.slot(index)]));
}
return code;
}
def deque<T>::slot(&this, index: u64): u64 {
return (this._hed + index) % this._cap;
}
def deque<T>::release(&mut this, slot: u64): void {
close(&mut this._dat[slot]);
# The slot is emptied where writing over it would close what it held.
if const T is closeable {
memset((this._dat + slot) as *mut u8, 0, bytes_of::<T>(1));
}
}
# Gives the deque room for more elements, doubling it.
def deque<T>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the deque room for a number of elements, where it has less, with them
# from its first slot. An allocator that gives no memory stops the program, as
# `acquire` does.
def deque<T>::grow(&mut this, size: u64): void {
if size <= this._cap {
return;
}
val block := acquire::<T>(this._alc, size);
val first := this._cap - this._hed;
val lead := this._len < first ? this._len : first;
memcpy(block as *mut u8, (this._dat + this._hed) as *mut u8, bytes_of::<T>(lead));
memcpy((block + lead) as *mut u8, this._dat as *mut u8, bytes_of::<T>(this._len - lead));
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = block;
this._hed = 0;
this._cap = size;
}
+659
View File
@@ -0,0 +1,659 @@
#! @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);
expects(found >= 0, "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);
expects(found >= 0, "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);
}
+214
View File
@@ -0,0 +1,214 @@
#! @file groups.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `groups` container. Groups hold elements
#! gathered by a key numbered from zero, those of each key one after another, so
#! that the elements of a key are a view.
module std::containers;
#! A `groups` holds elements gathered by key, those of each key one after
#! another in one block, so that the elements of a key are a view of it.
#!
#! They are useful wherever items are listed by what they belong to, such as
#! the reads of each value, the edges into each block, or the members of each
#! scope, which a vector for each key would scatter over the heap.
#!
#! Groups are filled in two passes, as compressed sparse rows are: the first
#! counts the elements of each key, `seal` works out where those of each key
#! begin, and the second puts each element in its place. The elements of a key
#! keep the order they were put in. The keys are numbered from zero, up to the
#! number the groups are made or reset for.
#! @tparam T The type of the elements.
pub struct groups<T>
: owning
, moveable
{
var _first: vector<u64>; # Where the elements of each key begin, then where the last end: zeros until sealed.
var _place: vector<u64>; # How many elements each key has until sealed, then where the next of each goes.
var _items: vector<T>;
var _sealed: bool;
}
#! Provides read only access to how many keys the groups have.
#! @param this The groups.
#! @returns The number of keys, each of which has a group, empty or not.
pub val groups<T>::keys: u64 {
get => this._first.length == 0 ? 0 : this._first.length - 1;
}
#! Provides read only access to how many elements the groups hold together.
#! @param this The groups.
#! @returns The number of elements, which is how many were counted once the
#! groups are sealed, and 0 before.
pub val groups<T>::size: u64 {
get => this._items.length;
}
#! Indicates whether the groups are sealed, so that elements are put rather
#! than counted.
#! @param this The groups.
#! @returns Whether `seal` was called since they were made or reset.
pub val groups<T>::is_sealed: bool {
get => this._sealed;
}
#! Creates groups for a number of keys, with no allocator, ready to count.
#! @param keys The number of keys.
#! @returns The created groups, each empty.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def groups<T>::new(keys: u64): groups<T> {
return groups::<T>::new(keys, nothing{});
}
#! Creates groups for a number of keys, with an optional allocator, ready to
#! count.
#! @param keys The number of keys.
#! @param alloc The optional allocator for the memory backing of the groups.
#! @returns The created groups, each empty.
pub def groups<T>::new(keys: u64, alloc: maybe<&mut allocator>): groups<T> {
var made := groups::<T> {
_first = vector::<u64>::new(alloc),
_place = vector::<u64>::new(alloc),
_items = vector::<T>::new(alloc),
_sealed = false
};
made._first.resize(keys + 1);
made._place.resize(keys);
return made;
}
#! Creates new groups by moving the data of others into them.
#! @param other The groups to move from, which have no keys after.
#! @returns The moved groups, which take the memory and allocator with them.
pub def groups<T>::move_of(other: &mut groups<T>): groups<T> {
val made := groups::<T> {
_first = move(&mut other._first),
_place = move(&mut other._place),
_items = move(&mut other._items),
_sealed = other._sealed
};
other._first.resize(1);
other._sealed = false;
return made;
}
#! Empties the groups and gives them a number of keys, ready to count again,
#! keeping the memory.
#! @param this The groups to reset.
#! @param keys The number of keys.
#! @remarks Elements are closed where they close, or hold what does.
pub def groups<T>::reset(&mut this, keys: u64): void {
this._items.clear();
this._place.clear();
this._place.resize(keys);
this._first.clear();
this._first.resize(keys + 1);
this._sealed = false;
}
#! Counts an element of a key, which is put once the groups are sealed.
#! @param this The groups, which are not sealed, or else the program stops.
#! @param key The key, below `keys`, past which a checked program stops.
pub def groups<T>::count(&mut this, key: u64): void {
this.count(key, 1);
}
#! Counts a number of elements of a key, which are put once the groups are
#! sealed.
#! @param this The groups, which are not sealed, or else the program stops.
#! @param key The key, below `keys`, past which a checked program stops.
#! @param many How many elements.
pub def groups<T>::count(&mut this, key: u64, many: u64): void {
if this._sealed {
fault("The groups are counted after they were sealed.");
}
this.check(key);
this._place.data[key] += many;
}
#! Works out where the elements of each key begin, from those counted, so that
#! they can be put.
#! @param this The groups, which are not sealed, or else the program stops.
#! @remarks Every key's elements are made room for at once, zeroed until they
#! are put. An allocator that gives no more memory stops the program.
pub def groups<T>::seal(&mut this): void {
if this._sealed {
fault("The groups are sealed a second time.");
}
val keys := this._first.length - 1;
val first := this._first.data;
val place := this._place.data;
for key in 0..keys {
first[key + 1] = first[key] + place[key];
place[key] = first[key];
}
this._items.resize(first[keys]);
this._sealed = true;
}
#! Puts an element of a key in its place, after those of the key put before it.
#! @param this The groups, which are sealed, or else a checked program stops.
#! @param key The key, below `keys`, past which a checked program stops, with
#! an element counted that is not put yet, or else a checked
#! program stops.
#! @param item The element.
#! @remarks Each check stops a checked program as indexing past an end does,
#! which keeps `put` short enough to be written where it is called.
pub def groups<T>::put(&mut this, key: u64, item: T): void {
expects(key < this._place.length);
# Groups not sealed end every key at zero, so no element fits there.
val at := this._place.data[key];
val end := this._first.data[key + 1];
expects(at < end);
this._items.data[at] = move(item);
this._place.data[key] = at + 1;
}
#! How many elements a key has.
#! @param this The groups.
#! @param key The key, below `keys`, past which a checked program stops.
#! @returns The number of its elements: those counted, before the groups are
#! sealed, and those made room for after.
pub def groups<T>::length(&this, key: u64): u64 {
this.check(key);
if !this._sealed {
return this._place.data[key];
}
return this._first.data[key + 1] - this._first.data[key];
}
#! Lends a view of the elements of a key, in the order they were put.
#! @param this The groups.
#! @param key The key, below `keys`, past which a checked program stops.
#! @returns The view, which is only good until the groups are reset or closed,
#! and whose elements not put yet are zero. Before the groups are
#! sealed, it is empty.
pub def groups<T>::of(&this, key: u64): span<T> {
# Groups not sealed begin and end every key at zero, so its view is empty.
val next := key + 1;
expects(next < this._first.length);
val start := this._first.data[key];
return this._items[start:this._first.data[next] - start];
}
#! Removes every element and every key, and gives back the memory the groups
#! hold.
#! @param this The groups to close.
#! @remarks Elements are closed where they close, or hold what does.
pub def groups<T>::close(&mut this): void {
this._items.close();
this._place.close();
this._first.close();
this._sealed = false;
}
# Stops the program where a key is not one of the groups'.
def groups<T>::check(&this, key: u64): void {
expects(key + 1 < this._first.length);
}
+572
View File
@@ -0,0 +1,572 @@
#! @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);
}
+203
View File
@@ -0,0 +1,203 @@
#! @file heap.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `heap` container. Heaps keep the least of the
#! values they hold at hand, adding a value and taking the least each in time
#! that grows with the logarithm of how many there are.
module std::containers;
#! A `heap` holds values so that the least of them, by the order `<` gives, is
#! always first, which `peek` reads and `pop` removes.
#!
#! They are useful wherever the next of many things to do is the least of them,
#! such as the soonest event, the cheapest path found so far, or the interval
#! that begins first.
#!
#! Its values are held in one vector as a binary tree, each no greater than the
#! two below it: those below the value at index `i` are at `2i + 1` and `2i + 2`.
#! Values equal to each other come out in no particular order.
#! @tparam T The type of its values, which are `ordered`.
pub struct heap<T>
: owning
, copyable
, moveable
{
var _val: vector<T>;
}
#! Provides read only access to the length of a heap.
#! @param this The heap to get the length of.
#! @returns The number of values it holds.
pub val heap<T>::length: u64 {
get => this._val.length;
}
#! Indicates if a heap is empty.
#! @param this The heap to check.
#! @returns Whether the heap holds no values.
pub val heap<T>::empty: bool {
get => this._val.length == 0;
}
#! Creates a new heap with no allocator, which takes memory once something is
#! pushed.
#! @returns The created heap, which holds no values yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def heap<T>::new(): heap<T> {
return heap::<T>::new(nothing{});
}
#! Creates a new heap with an optional allocator, which takes memory once
#! something is pushed.
#! @param alloc The optional allocator for the memory backing of the heap.
#! @returns The created heap, which holds no values yet.
pub def heap<T>::new(alloc: maybe<&mut allocator>): heap<T> {
if const !(T is ordered) {
compile_error("A heap keeps its least value first, by the order `<` gives, so its values are `ordered`.");
}
return heap::<T> { _val = vector::<T>::new(alloc) };
}
#! Creates a new heap 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 heap.
#! @returns The created heap, which holds no values yet.
pub def heap<T>::new(size: u64, alloc: maybe<&mut allocator>): heap<T> {
var made := heap::<T>::new(alloc);
made._val.reserve(size);
return made;
}
#! Builds a heap holding copies of another's values, with its allocator.
#! @param other The heap to copy from.
#! @returns The copy, which owns its own memory and values.
#! @remarks Values are copied by `copyable` where they provide one.
pub def heap<T>::copy_of(other: &heap<T>): heap<T> {
return heap::<T> { _val = vector::<T>::copy_of(&other._val) };
}
#! Creates a new heap by moving the data of another heap into it.
#! @param other The heap to move from, which holds nothing after.
#! @returns The moved heap, which takes the memory and allocator with it.
pub def heap<T>::move_of(other: &mut heap<T>): heap<T> {
return heap::<T> { _val = move(&mut other._val) };
}
#! Adds a value.
#! @param this The heap to add the value to.
#! @param value The value to add.
#! @remarks The value rises past each value above it that is greater. An
#! allocator that gives no more memory stops the program.
pub def heap<T>::push(&mut this, value: T): void {
if const !(T is ordered) {
compile_error("A heap keeps its least value first, by the order `<` gives, so its values are `ordered`.");
}
this._val.append(move(value));
var at := this._val.length - 1;
val data := this._val.data;
while at > 0 {
val parent := (at - 1) / 2;
break if data[parent] <= data[at];
heap::<T>::swap(data, parent, at);
at = parent;
}
}
#! Reads the least value.
#! @param this The heap to read, which holds a value, or else a checked
#! program stops.
#! @returns The least value, which is only good until the heap changes or
#! closes.
pub def heap<T>::peek(&this): &T {
expects(!this.empty, "The heap is empty.");
return &this._val.data[0];
}
#! Removes the least value.
#! @param this The heap to remove from, which holds a value, or else a checked
#! program stops.
#! @remarks The value is closed where it closes, or holds what does, and not
#! given back, so read it with `peek` first. The last value takes its
#! place and sinks past each value below it that is less.
pub def heap<T>::pop(&mut this): void {
if const !(T is ordered) {
compile_error("A heap keeps its least value first, by the order `<` gives, so its values are `ordered`.");
}
expects(!this.empty, "The heap is empty.");
val data := this._val.data;
val last := this._val.length - 1;
heap::<T>::swap(data, 0, last);
this._val.truncate();
val count := this._val.length;
var at: u64 = 0;
while 2 * at + 1 < count {
var child := 2 * at + 1;
if child + 1 < count && data[child + 1] < data[child] {
child++;
}
break if data[at] <= data[child];
heap::<T>::swap(data, at, child);
at = child;
}
}
#! Lends a view of some of the values of a heap, in the order the heap holds
#! them, which is not the order they come out in, as `spannable` asks, which
#! `h[start:count]` calls.
#! @param other The heap to view.
#! @param start The index of the first value viewed.
#! @param count How many values are viewed, or `~0u` for every one after the
#! start.
#! @returns The view, which is only good until the heap changes or closes.
#! @remarks A start or count past the last value stops a checked program.
pub def heap<T>::span_of(other: &heap<T>, start: u64 = 0, count: u64 = ~0u): span<T> {
return vector::<T>::span_of(&other._val, start, count);
}
#! A view of the values, in the order the heap holds them, which is not the
#! order they come out in.
#! @param this The heap to view.
#! @returns The view, which is only good until the heap changes or closes.
pub val heap<T>::span: span<T> {
get => this._val.span;
}
#! Removes every value, keeping the memory the heap holds them in.
#! @param this The heap to empty.
#! @remarks Values are closed where they close, or hold what does.
pub def heap<T>::clear(&mut this): void {
this._val.clear();
}
#! Removes every value and gives back the memory the heap holds.
#! @param this The heap to close.
#! @remarks Values are closed where they close, or hold what does.
pub def heap<T>::close(&mut this): void {
this._val.close();
}
# Swaps two values byte for byte, so that neither is closed or copied.
def heap<T>::swap(data: *mut T, first: u64, second: u64): void {
return if first == second;
if const !(T is closeable) {
val held: T = data[first];
data[first] = data[second];
data[second] = held;
return;
}
val a := (data + first) as *mut u8;
val b := (data + second) as *mut u8;
for at in 0..size_of::<T>() {
val held: u8 = a[at];
a[at] = b[at];
b[at] = held;
}
}
+422
View File
@@ -0,0 +1,422 @@
#! @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>
, spannable<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>::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 `spannable`, 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 spannable<U>) || !(T is interner_made<U>) {
compile_error("`intern_view` finds values by their views and makes them from those views, so they are `spannable` 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 T::span_of(&this._val.data[id]) == 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 `spannable`, 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 spannable<U>) {
compile_error("`find_view` finds values by their views, so they are `spannable` 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 T::span_of(&this._val.data[id]) == 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 some of the values of an interner, by ID, without copying
#! them, as `spannable` asks, which `i[start:count]` calls.
#! @param other The interner to view.
#! @param start The ID of the first value viewed.
#! @param count How many values are viewed, or `~0u` for every one after the
#! start.
#! @returns A view of those values, the value of each ID at its index less the
#! start, which is only good until the interner grows or closes.
#! @remarks A start or count past the last value stops a checked program.
pub def interner<T>::span_of(other: &interner<T>, start: u64 = 0, count: u64 = ~0u): span<T> {
return vector::<T>::span_of(&other._val, start, count);
}
#! A view of the values, by ID, which copies nothing.
#! @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 val interner<T>::span: span<T> {
get => this._val.span;
}
#! 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, which reads the values by ID.
pub type interner<T>::iterator = span<T>::iterator;
#! Lends an iterator that reads the values in the order of their IDs, which
#! `for x in i` walks.
#! @param this The interner to walk.
#! @returns The iterator, which is only good until the interner grows or closes.
pub def interner<T>::iter(&this): span<T>::iterator {
return this._val.iter();
}
#! An iterator that reads the values in the order of their IDs, as `iter`
#! lends.
#! @param this The interner to walk.
#! @returns The iterator, which is only good until the interner grows or closes.
pub val interner<T>::iterator: span<T>::iterator {
get => this.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);
}
+478
View File
@@ -0,0 +1,478 @@
#! @file list.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `list` container. Lists are a structured
#! container that stores each element in a node of its own, linked to the next.
module std::containers;
#! A `list` is a structured data container, singly linked, that stores each of
#! its elements in a node of its own.
#!
#! They are useful where elements are added and removed at the front, and where
#! an element must never move once it is added, since each keeps its own node
#! until it is removed. Reaching an element by index walks the list from the
#! front.
#!
#! It holds its first and last nodes, so pushing onto either end takes the same
#! time however long it is, but only the front is popped without walking.
#! @tparam T The type of its elements.
pub struct list<T>
: owning
, hashable
, indexable<u64, T>
, assignable<u64, T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _hed: *mut list<T>::node;
var _tal: *mut list<T>::node;
var _len: u64;
}
#! An element of a list, with the node after it.
struct list<T>::node {
var value: T;
var next: *mut list<T>::node;
}
#! Walks the elements of a list from its front, giving a reference that reads
#! each in turn, which is what `iter(&this)` lends and `for x` and `for &x`
#! walk.
pub struct list<T>::iterator : sized_iterator<&T> {
var _at: *mut list<T>::node;
var _left: u64;
}
#! Gives the next element of the list.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def list<T>::iterator::next(&mut this): maybe<&T> {
if this._at == null {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &(*here).value;
}
#! How many elements the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def list<T>::iterator::remaining(&this): u64 {
return this._left;
}
#! Walks the elements of a list from its front, giving a reference that writes
#! each in turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
pub struct list<T>::mutator : sized_iterator<&mut T> {
var _at: *mut list<T>::node;
var _left: u64;
}
#! Gives the next element of the list, to be written.
#! @param this The mutator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def list<T>::mutator::next(&mut this): maybe<&mut T> {
if this._at == null {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &mut (*here).value;
}
#! How many elements the mutator has left to give.
#! @param this The mutator.
#! @returns How many.
pub def list<T>::mutator::remaining(&this): u64 {
return this._left;
}
#! Provides read only access to the length of a list.
#! @param this The list to get the length of.
#! @returns The length of the list.
pub val list<T>::length: u64 {
get => this._len;
}
#! Indicates if a list is empty.
#! @param this The list to check.
#! @returns Whether the list is empty.
pub val list<T>::empty: bool {
get => this._len == 0;
}
#! Creates a new list with no allocator.
#! @returns The created list container.
#! @remarks Will use the built in `raw_allocate` and `raw_release` for memory
#! management.
pub def list<T>::new(): list<T> {
return list::<T>::new(nothing{});
}
#! Creates a new list with an optional allocator.
#! @param alloc The optional allocator for the nodes of the list.
#! @returns The created list container, which holds no elements yet.
pub def list<T>::new(alloc: maybe<&mut allocator>): list<T> {
return list::<T> { _alc = alloc, _hed = null, _tal = null, _len = 0 };
}
#! Creates a copy of the provided list.
#! @param other The list to copy.
#! @returns The copy, which owns its own nodes and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def list<T>::copy_of(other: &list<T>): list<T> {
var made := list::<T>::new(other._alc);
var at := other._hed;
while at != null {
made.push_back(copy::<T>(&(*at).value));
at = (*at).next;
}
return made;
}
#! Creates a new list by moving the nodes of another list into it.
#! @param other The list to move elements from, which holds none after.
#! @returns The moved list, which takes the nodes and allocator with it.
#! @remarks Nothing is copied and no element is touched: the nodes move as they
#! stand, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def list<T>::move_of(other: &mut list<T>): list<T> {
val made: list<T> = list {
_alc = other._alc,
_hed = other._hed,
_tal = other._tal,
_len = other._len
};
other._hed = null;
other._tal = null;
other._len = 0;
return made;
}
#! Gets the element at the provided index, walking from the front.
#! @param this The list to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def list<T>::at(&this, index: u64): &T {
expects(index < this._len);
return &(*this.node_at(index)).value;
}
#! Gets the element at the provided index, walking from the front.
#! @param this The list to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def list<T>::at(&mut this, index: u64): &mut T {
expects(index < this._len);
return &mut (*this.node_at(index)).value;
}
#! Gets the element at an index, if the list holds one there, for an index
#! that may be past the end in a program that is right.
#! @param this The list to read.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def list<T>::get(&this, index: u64): maybe<&T> {
return nothing {} if index >= this._len;
return &(*this.node_at(index)).value;
}
#! Gets the element at an index to write it, if the list holds one there.
#! @param this The list to write.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def list<T>::get(&mut this, index: u64): maybe<&mut T> {
return nothing {} if index >= this._len;
return &mut (*this.node_at(index)).value;
}
#! The element at the front of a list, which a list that can be written writes
#! through.
#! @param this The list to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val list<T>::first: &T {
get {
expects(!this.empty, "The list is empty.");
return &(*this._hed).value;
}
get mut {
expects(!this.empty, "The list is empty.");
return &mut (*this._hed).value;
}
}
#! The element at the back of a list, which a list that can be written writes
#! through.
#! @param this The list to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val list<T>::last: &T {
get {
expects(!this.empty, "The list is empty.");
return &(*this._tal).value;
}
get mut {
expects(!this.empty, "The list is empty.");
return &mut (*this._tal).value;
}
}
#! Pushes a new element onto the front of a list.
#! @param this The list to push the value onto.
#! @param value The value to push onto the list.
#! @remarks An allocator that gives no more memory stops the program.
pub def list<T>::push_front(&mut this, value: T): void {
val made := this.make(move(value));
(*made).next = this._hed;
this._hed = made;
if this._tal == null {
this._tal = made;
}
this._len++;
}
#! Pushes a new element onto the back of a list.
#! @param this The list to push the value onto.
#! @param value The value to push onto the list.
#! @remarks An allocator that gives no more memory stops the program.
pub def list<T>::push_back(&mut this, value: T): void {
val made := this.make(move(value));
if this._tal == null {
this._hed = made;
} else {
(*this._tal).next = made;
}
this._tal = made;
this._len++;
}
#! Pops the element off the front of a list.
#! @param this The list to pop the value off of, which stops a checked program
#! where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def list<T>::pop_front(&mut this): void {
expects(!this.empty, "The list is empty.");
val gone := this._hed;
this._hed = (*gone).next;
if this._hed == null {
this._tal = null;
}
this.release(gone);
this._len--;
}
#! Adds an element at an index, after the elements before it.
#! @param this The list to insert into.
#! @param index Where the element goes, from `0` to `length`, where `length`
#! appends. An index past that stops a checked program.
#! @param value The element to insert.
#! @remarks An allocator that gives no more memory stops the program.
pub def list<T>::insert_at(&mut this, index: u64, value: T): void {
expects(index <= this._len);
if index == 0 {
this.push_front(move(value));
return;
}
if index == this._len {
this.push_back(move(value));
return;
}
val made := this.make(move(value));
val prev := this.node_at(index - 1);
(*made).next = (*prev).next;
(*prev).next = made;
this._len++;
}
#! Removes the element at an index.
#! @param this The list to remove from.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @remarks The element is closed where it closes, or holds what does.
pub def list<T>::remove_at(&mut this, index: u64): void {
expects(index < this._len);
if index == 0 {
this.pop_front();
return;
}
this.unlink(this.node_at(index - 1));
}
#! Removes the first element equal to the one given.
#! @param this The list to remove from.
#! @param elem The element to look for.
#! @returns Whether an element equalled it and was removed.
#! @remarks The element is closed where it closes, or holds what does.
pub def list<T>::remove(&mut this, elem: &T): bool {
if this._len == 0 {
return false;
}
if equals::<T>(&(*this._hed).value, elem) {
this.pop_front();
return true;
}
var prev := this._hed;
while (*prev).next != null {
if equals::<T>(&(*(*prev).next).value, elem) {
this.unlink(prev);
return true;
}
prev = (*prev).next;
}
return false;
}
#! Tells whether the list holds an element equal to the one given.
#! @param this The list to search.
#! @param elem The element to look for.
#! @returns Whether any element equals it.
pub def list<T>::contains(&this, elem: &T): bool {
var at := this._hed;
while at != null {
return true if equals::<T>(&(*at).value, elem);
at = (*at).next;
}
return false;
}
#! Removes all elements from a list, disposing their nodes.
#! @param this The list to clear.
#! @remarks Elements that close, or hold what does, are closed.
pub def list<T>::clear(&mut this): void {
var at := this._hed;
while at != null {
val next := (*at).next;
this.release(at);
at = next;
}
this._hed = null;
this._tal = null;
this._len = 0;
}
#! Removes all elements of a list, disposing their nodes.
#! @param this The list to close.
pub def list<T>::close(&mut this): void {
this.clear();
}
#! Compares one list to another by equality.
#! @param this The list to compare against.
#! @param other The list to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def list<T>::equals(&this, other: &list<T>): bool {
if this._len != other._len {
return false;
}
var mine := this._hed;
var theirs := other._hed;
while mine != null {
return false if !equals::<T>(&(*mine).value, &(*theirs).value);
mine = (*mine).next;
theirs = (*theirs).next;
}
return true;
}
#! Lends an iterator that reads the elements from the front of the list, which
#! `for x in l` walks.
#! @param this The list to walk.
#! @returns The iterator, which is only good until the list changes or closes.
pub def list<T>::iter(&this): list<T>::iterator {
return list::<T>::iterator { _at = this._hed, _left = this._len };
}
#! Lends a mutator that writes the elements where they are, from the front of
#! the list, which `for &mut x in l` walks.
#! @param this The list to walk.
#! @returns The mutator, which is only good until the list changes or closes.
pub def list<T>::iter(&mut this): list<T>::mutator {
return list::<T>::mutator { _at = this._hed, _left = this._len };
}
#! An iterator that reads the elements from the front of the list, as `iter`
#! lends.
#! @param this The list to walk.
#! @returns The iterator, which is only good until the list changes or closes.
pub val list<T>::iterator: list<T>::iterator {
get => this.iter();
}
#! A mutator that writes the elements where they are, read of a list that can
#! be written.
#! @param this The list to walk.
#! @returns The mutator, which is only good until the list changes or closes.
pub val list<T>::mutator: list<T>::mutator {
get mut => this.iter();
}
#! Hashes the provided list.
#! @param this The list to hash.
#! @returns The hashed value of the list.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def list<T>::hash(&this): u64 {
var code := this._len;
var at := this._hed;
while at != null {
code = mix(code, hash::<T>(&(*at).value));
at = (*at).next;
}
return code;
}
# The node at an index, which is below the length.
def list<T>::node_at(&this, index: u64): *mut list<T>::node {
var at := this._hed;
for _ in 0..index {
at = (*at).next;
}
return at;
}
# A node holding the value, from the list's allocator, which stops the program
# where it gives no memory, as `acquire` does.
def list<T>::make(&mut this, value: T): *mut list<T>::node {
val made := acquire::<list<T>::node>(this._alc, 1);
(*made).value = move(value);
(*made).next = null;
return made;
}
def list<T>::unlink(&mut this, prev: *mut list<T>::node): void {
val gone := (*prev).next;
(*prev).next = (*gone).next;
if gone == this._tal {
this._tal = prev;
}
this.release(gone);
this._len--;
}
def list<T>::release(&mut this, node: *mut list<T>::node): void {
close(&mut (*node).value);
dispose::<list<T>::node>(this._alc, node, 1);
}
+430
View File
@@ -0,0 +1,430 @@
#! @file queue.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `queue` container. Queues are a structured
#! container where data is pushed onto the back and popped off the front, in a
#! first-in-first-out (FIFO) manner.
module std::containers;
#! A `queue` is a structured data container that stores its content in a first-
#! in-first-out (FIFO) manner.
#!
#! They are useful wherever work is handled in the order it arrives, such as
#! event loops, breadth-first searches, and buffers between a producer and a
#! consumer.
#!
#! Its elements live in one block used as a ring: the front is at `_hed`, and
#! each element after it is at the next index, wrapping to the start of the
#! block.
#! @tparam T The type of its elements.
pub struct queue<T>
: owning
, hashable
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _dat: *mut T;
var _hed: u64;
var _len: u64;
var _cap: u64;
}
#! Provides read only access to the length of a queue.
#! @param this The queue to get the length of.
#! @returns The length of the queue.
pub val queue<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a queue.
#! @param this The queue to get the capacity of.
#! @returns The capacity of the queue.
pub val queue<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a queue is empty.
#! @param this The queue to check.
#! @returns Whether the queue is empty.
pub val queue<T>::empty: bool {
get => this._len == 0;
}
#! Indicates if a queue is full.
#! @param this The queue to check.
#! @returns Whether the queue is full.
pub val queue<T>::full: bool {
get => this._len == this._cap;
}
#! Creates a new queue with no allocator and a default size.
#! @returns The created queue container.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def queue<T>::new(): queue<T> {
return queue::<T>::new(4, nothing{});
}
#! Creates a new queue with an optional allocator and a default size.
#! @param alloc The optional allocator for the memory backing of the queue.
#! @returns The created queue container.
pub def queue<T>::new(alloc: maybe<&mut allocator>): queue<T> {
return queue::<T>::new(4, alloc);
}
#! Creates a new queue with an optional allocator and a provided size.
#! @param size The initial capacity of the queue, which may be none.
#! @param alloc The optional allocator for the memory backing of the queue.
#! @returns The created queue container, which holds no elements yet.
pub def queue<T>::new(size: u64, alloc: maybe<&mut allocator>): queue<T> {
var made: queue<T> = queue {
_alc = alloc,
_dat = null,
_hed = 0,
_len = 0,
_cap = 0
};
made.reserve(size);
return made;
}
#! Creates a copy of the provided queue.
#! @param other The queue to copy.
#! @returns The copy, which owns its own memory and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def queue<T>::copy_of(other: &queue<T>): queue<T> {
var made := queue::<T>::new(other._len, other._alc);
for index in 0..other._len {
made.push(copy::<T>(&other._dat[other.slot(index)]));
}
return made;
}
#! Creates a new queue by moving the data of another queue into it.
#! @param other The queue to move elements from, which holds none after.
#! @returns The moved queue, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no element 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 queue<T>::move_of(other: &mut queue<T>): queue<T> {
val made: queue<T> = queue {
_alc = other._alc,
_dat = other._dat,
_hed = other._hed,
_len = other._len,
_cap = other._cap
};
other._dat = null;
other._hed = 0;
other._len = 0;
other._cap = 0;
return made;
}
#! Pushes a new element onto the back of a queue.
#! @param this The queue to push the value onto.
#! @param value The value to push onto the queue.
#! @remarks An allocator that gives no more memory stops the program.
pub def queue<T>::push(&mut this, value: T): void {
if this.full {
this.grow();
}
this._dat[this.slot(this._len)] = move(value);
this._len++;
}
#! Pops the element off the front of a queue.
#! @param this The queue to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def queue<T>::pop(&mut this): void {
expects(!this.empty, "The queue is empty.");
this.release(this._hed);
this._hed = (this._hed + 1) % this._cap;
this._len--;
}
#! Peeks the element at the front of a queue without removing it.
#! @param this The queue to peek the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def queue<T>::peek(&this): &T {
expects(!this.empty, "The queue is empty.");
return &this._dat[this._hed];
}
#! Peeks the element at the front of a queue without removing it.
#! @param this The queue to peek the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def queue<T>::peek(&mut this): &mut T {
expects(!this.empty, "The queue is empty.");
return &mut this._dat[this._hed];
}
#! The element at the front of a queue, as `peek` reads it, which a queue that
#! can be written writes through.
#! @param this The queue to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val queue<T>::first: &T {
get => this.peek();
get mut => this.peek();
}
#! The element at the back of a queue, pushed last, which a queue that can be
#! written writes through.
#! @param this The queue to read, which stops a checked program where it is
#! empty.
#! @returns A reference to the element.
pub val queue<T>::last: &T {
get {
expects(!this.empty, "The queue is empty.");
return &this._dat[this.slot(this._len - 1)];
}
get mut {
expects(!this.empty, "The queue is empty.");
return &mut this._dat[this.slot(this._len - 1)];
}
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the queue provided.
#! @param this The queue to reserve elements for.
#! @param count The number of elements to reserve for a queue.
pub def queue<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes all elements from a queue.
#! @param this The queue to clear.
#! @remarks Elements that close, or hold what does, are closed. The backing data
#! is kept but not disposed.
pub def queue<T>::clear(&mut this): void {
for index in 0..this._len {
this.release(this.slot(index));
}
this._hed = 0;
this._len = 0;
}
#! Removes all elements of a queue then disposes the backing memory.
#! @param this The queue to close.
pub def queue<T>::close(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[this.slot(index)]);
}
}
this._hed = 0;
this._len = 0;
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = null;
this._cap = 0;
}
#! Compares one queue to another by equality.
#! @param this The queue to compare against.
#! @param other The queue to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def queue<T>::equals(&this, other: &queue<T>): bool {
if this._len != other._len {
return false;
}
for index in 0..this._len {
return false if !equals::<T>(
&this._dat[this.slot(index)],
&other._dat[other.slot(index)]
);
}
return true;
}
#! Walks the elements of a queue from its front, giving a reference that reads
#! each in turn, which is what `iter(&this)` lends and `for x` and `for &x`
#! walk.
pub struct queue<T>::iterator : sized_iterator<&T>, backward_iterator<&T> {
var _dat: *mut T;
var _at: u64;
var _cap: u64;
var _left: u64;
}
#! Gives the next element of the queue.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def queue<T>::iterator::next(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (here + 1) % this._cap;
this._left = this._left - 1;
return &this._dat[here];
}
#! How many elements the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def queue<T>::iterator::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the iterator has left, from the back of the queue.
#! @param this The iterator to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def queue<T>::iterator::next_back(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &this._dat[(this._at + this._left) % this._cap];
}
#! Walks the elements of a queue from its front, giving a reference that writes
#! each in turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
pub struct queue<T>::mutator : sized_iterator<&mut T>, backward_iterator<&mut T> {
var _dat: *mut T;
var _at: u64;
var _cap: u64;
var _left: u64;
}
#! Gives the next element of the queue, to be written.
#! @param this The mutator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def queue<T>::mutator::next(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (here + 1) % this._cap;
this._left = this._left - 1;
return &mut this._dat[here];
}
#! How many elements the mutator has left to give.
#! @param this The mutator.
#! @returns How many.
pub def queue<T>::mutator::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the mutator has left, from the back of the queue, to
#! be written.
#! @param this The mutator to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def queue<T>::mutator::next_back(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &mut this._dat[(this._at + this._left) % this._cap];
}
#! Lends an iterator that reads the elements from the front of the queue, which
#! `for x in q` walks.
#! @param this The queue to walk.
#! @returns The iterator, which is only good until the queue changes or closes.
pub def queue<T>::iter(&this): queue<T>::iterator {
return queue::<T>::iterator { _dat = this._dat, _at = this._hed, _cap = this._cap, _left = this._len };
}
#! Lends a mutator that writes the elements where they are, from the front of
#! the queue, which `for &mut x in q` walks.
#! @param this The queue to walk.
#! @returns The mutator, which is only good until the queue changes or closes.
pub def queue<T>::iter(&mut this): queue<T>::mutator {
return queue::<T>::mutator { _dat = this._dat, _at = this._hed, _cap = this._cap, _left = this._len };
}
#! An iterator that reads the elements from the front of the queue, as `iter`
#! lends.
#! @param this The queue to walk.
#! @returns The iterator, which is only good until the queue changes or closes.
pub val queue<T>::iterator: queue<T>::iterator {
get => this.iter();
}
#! A mutator that writes the elements where they are, read of a queue that can
#! be written.
#! @param this The queue to walk.
#! @returns The mutator, which is only good until the queue changes or closes.
pub val queue<T>::mutator: queue<T>::mutator {
get mut => this.iter();
}
#! Hashes the provided queue.
#! @param this The queue to hash.
#! @returns The hashed value of the queue.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def queue<T>::hash(&this): u64 {
var code := this._len;
for index in 0..this._len {
code = mix(code, hash::<T>(&this._dat[this.slot(index)]));
}
return code;
}
def queue<T>::slot(&this, index: u64): u64 {
return (this._hed + index) % this._cap;
}
def queue<T>::release(&mut this, slot: u64): void {
close(&mut this._dat[slot]);
# The slot is emptied where writing over it would close what it held.
if const T is closeable {
memset((this._dat + slot) as *mut u8, 0, bytes_of::<T>(1));
}
}
# Gives the queue room for more elements, doubling it.
def queue<T>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the queue room for a number of elements, where it has less, with them
# from its first slot. An allocator that gives no memory stops the program, as
# `acquire` does.
def queue<T>::grow(&mut this, size: u64): void {
if size <= this._cap {
return;
}
val block := acquire::<T>(this._alc, size);
val first := this._cap - this._hed;
val lead := this._len < first ? this._len : first;
memcpy(block as *mut u8, (this._dat + this._hed) as *mut u8, bytes_of::<T>(lead));
memcpy((block + lead) as *mut u8, this._dat as *mut u8, bytes_of::<T>(this._len - lead));
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = block;
this._hed = 0;
this._cap = size;
}
+167
View File
@@ -0,0 +1,167 @@
#! @file rc.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `rc`, one value on the heap that every copy owns, counted plainly,
#! for values one thread shares, as Rust's `Rc`; and `rc_weak`, which refers to
#! it without keeping it. `arc` counts atomically, for values threads share.
#!
#! Each copy counts one more owner, and the last to close closes the value.
#! Counting plainly costs an add, where counting atomically costs a locked add:
#! fourteen times as long for a copy alone, and half again as long for a list
#! walked with a counted cursor, measured as `docs/performance.md` says.
module std::containers;
# Allocates a block a counted value is written into: zeroed where the value
# closes, since writing it closes what the block held, as `box` allocates.
def allocate_for<T>(size: u64): *mut u8 {
if const T is closeable {
return raw_allocate_zeroed(size);
}
return raw_allocate(size);
}
# What an `rc` points at: the counts, then the value. The weak count holds one
# for all the owners together, so the last owner to close and the last weak
# reference to close agree on which gives the memory back.
struct rc_cell<T> {
var owners: u64;
var weak: u64;
var value: T;
}
#! One value on the heap, owned by every copy, which `copy` makes, and closed
#! where the last copy closes. Copies count plainly, so threads never share
#! one; `arc` is for that.
#!
#! An `rc` is one word, the counted value's address, which is never null, so
#! `maybe<rc<T>>` is one word too. Moving one moves the address and leaves the
#! one moved from empty, closing nothing.
#! @tparam T What it holds.
pub struct rc<T> : owning, copyable, moveable {
var _at: &mut rc_cell<T>;
}
#! A reference to a value an `rc` owns that does not keep it: `lock` gives an
#! owner while any other is left.
#! @tparam T What it refers to.
pub struct rc_weak<T> : owning, copyable, moveable {
var _at: *mut rc_cell<T>;
}
#! Moves a value to the heap, with one owner.
#! @param value The value.
#! @returns Its first owner.
pub def rc<T>::new(value: T): rc<T> {
val at := allocate_for::<rc_cell<T>>(size_of::<rc_cell<T>>()) as *mut rc_cell<T>;
at[0] = rc_cell::<T> { owners = 1, weak = 1, value = move(&mut value) };
return rc::<T> { _at = through(at) };
}
#! Lends the value an `rc` owns.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def rc<T>::get(&this): &T {
return &this._at.value;
}
#! Lends the value an `rc` owns, to be changed, which every copy sees.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def rc<T>::get(&mut this): &mut T {
return &mut this._at.value;
}
#! How many owners share the value.
#! @param this An owner.
#! @returns How many, this one among them.
pub def rc<T>::count(&this): u64 {
return this._at.owners;
}
#! A reference to the value that does not keep it.
#! @param this An owner.
#! @returns The reference.
pub def rc<T>::weak(&this): rc_weak<T> {
this._at.weak++;
return rc_weak::<T> { _at = this._at as *mut rc_cell<T> };
}
#! Makes another owner of the same value.
#! @param other An owner.
#! @returns The new owner.
pub def rc<T>::copy_of(other: &rc<T>): rc<T> {
other._at.owners++;
return rc::<T> { _at = other._at };
}
#! Moves an owner, leaving the one moved from empty.
#! @param other The owner to move from.
#! @returns The owner it was.
pub def rc<T>::move_of(other: &mut rc<T>): rc<T> {
val made := rc::<T> { _at = other._at };
(other as *mut u64)[0] = 0;
return made;
}
#! Closes an owner: the value too where it was the last, and the memory where no
#! weak reference is left either.
#! @param this The owner, which is empty after.
pub def rc<T>::close(&mut this): void {
val at := this._at as *mut rc_cell<T>;
return if at == null;
(this as *mut u64)[0] = 0;
at[0].owners--;
return if at[0].owners != 0;
close(&mut at[0].value);
rc_cell_let_go::<T>(at);
}
#! An owner of the value a weak reference refers to, where any is left.
#! @param this The weak reference.
#! @returns The new owner, or nothing where the last closed.
pub def rc_weak<T>::lock(&this): maybe<rc<T>> {
return nothing {} if this._at == null || this._at[0].owners == 0;
this._at[0].owners++;
return rc::<T> { _at = through(this._at) };
}
#! Makes another weak reference to the same value.
#! @param other A weak reference.
#! @returns The new one.
pub def rc_weak<T>::copy_of(other: &rc_weak<T>): rc_weak<T> {
if other._at != null {
other._at[0].weak++;
}
return rc_weak::<T> { _at = other._at };
}
#! Moves a weak reference, leaving the one moved from empty.
#! @param other The weak reference to move from.
#! @returns The weak reference it was.
pub def rc_weak<T>::move_of(other: &mut rc_weak<T>): rc_weak<T> {
val made := rc_weak::<T> { _at = other._at };
other._at = null;
return made;
}
#! Closes a weak reference, giving back the memory where it was the last
#! reference of any kind.
#! @param this The weak reference, which is empty after.
pub def rc_weak<T>::close(&mut this): void {
val at := this._at;
return if at == null;
this._at = null;
rc_cell_let_go::<T>(at);
}
# Lets go of the weak count's one, giving back the memory where it was the last.
def rc_cell_let_go<T>(at: *mut rc_cell<T>): void {
at[0].weak--;
if at[0].weak == 0 {
raw_release(at as *mut u8);
}
}
+185
View File
@@ -0,0 +1,185 @@
#! @file runs.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `runs` container. Runs hold many short lists,
#! each a run of elements one after another in one block, named by an ID.
module std::containers;
#! A `runs` holds many lists of elements, each a run of them one after another
#! in one block, which a `u32` ID names.
#!
#! They are useful wherever many short lists are made and kept, such as the
#! parts of each type, the parameters of each function, or the children of each
#! node, which a vector each would scatter over the heap.
#!
#! The elements of every run are held in one vector, in the order the runs were
#! made, and where each run begins in another. A run is made by adding a view of
#! its elements, or by pushing them one at a time and then ending it. Runs are
#! never changed, and none is removed but by `rewind` and `clear`, so an ID is
#! good for as long as its run is. ID 0 is the empty run, which every empty view
#! added is given.
#! @tparam T The type of the elements.
pub struct runs<T>
: owning
, copyable
, moveable
{
var _items: vector<T>;
var _start: vector<u64>;
}
#! Provides read only access to how many runs there are.
#! @param this The runs to count.
#! @returns The number of runs, the empty one included, which is one more than
#! the newest's ID.
pub val runs<T>::count: u64 {
get => this._start.length - 1;
}
#! Provides read only access to how many elements the runs hold together.
#! @param this The runs to count the elements of.
#! @returns The number of elements, those of a run still being pushed included.
pub val runs<T>::size: u64 {
get => this._items.length;
}
#! Creates new runs with no allocator, holding only the empty run.
#! @returns The created runs.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def runs<T>::new(): runs<T> {
return runs::<T>::new(nothing{});
}
#! Creates new runs with an optional allocator, holding only the empty run.
#! @param alloc The optional allocator for the memory backing of the runs.
#! @returns The created runs.
pub def runs<T>::new(alloc: maybe<&mut allocator>): runs<T> {
var made := runs::<T> { _items = vector::<T>::new(alloc), _start = vector::<u64>::new(alloc) };
made._start.resize(2);
return made;
}
#! Builds runs holding copies of another's, each with the same ID, with its
#! allocator.
#! @param other The runs to copy from.
#! @returns The copy, which owns its own memory and elements.
#! @remarks Elements are copied by `copyable` where they provide one.
pub def runs<T>::copy_of(other: &runs<T>): runs<T> {
return runs::<T> { _items = vector::<T>::copy_of(&other._items), _start = vector::<u64>::copy_of(&other._start) };
}
#! Creates new runs by moving the data of others into them.
#! @param other The runs to move from, which hold nothing after, not even the
#! empty run, until they are cleared.
#! @returns The moved runs, which take the memory and allocator with them.
pub def runs<T>::move_of(other: &mut runs<T>): runs<T> {
return runs::<T> { _items = move(&mut other._items), _start = move(&mut other._start) };
}
#! Adds a run of copies of elements.
#! @param this The runs to add to.
#! @param items The elements of the run, in order.
#! @returns The run's ID, or 0, the empty run's, where there are no elements.
#! @remarks Elements are copied as a vector's `extend` copies them. Elements
#! pushed and not yet ended begin the run. An allocator that gives no
#! more memory stops the program.
pub def runs<T>::add(&mut this, items: span<T>): u32 {
this._items.extend(items);
return this.end();
}
#! Adds an element to the run being made, which `end` ends.
#! @param this The runs to add to.
#! @param item The element, which follows those pushed before it.
pub def runs<T>::push(&mut this, item: T): void {
this._items.append(move(item));
}
#! Ends the run being made, of the elements pushed since the last run ended.
#! @param this The runs to end the run of.
#! @returns The run's ID, or 0, the empty run's, where none was pushed.
pub def runs<T>::end(&mut this): u32 {
val open := this._start.data[this._start.length - 1];
return 0 if this._items.length == open;
val id := this._start.length - 1;
this._start.append(this._items.length);
return id as u32;
}
#! How many elements a run holds.
#! @param this The runs.
#! @param id The run's ID, below `count`, past which a checked program
#! stops.
#! @returns The number of its elements.
pub def runs<T>::length(&this, id: u32): u64 {
expects(id as u64 + 1 < this._start.length);
return this._start.data[id as u64 + 1] - this._start.data[id];
}
#! Reads an element of a run.
#! @param this The runs.
#! @param id The run's ID, below `count`, past which a checked program
#! stops.
#! @param index The element's place in the run, below its length, past which a
#! checked program stops.
#! @returns The element, which is only good until the runs grow or close.
pub def runs<T>::at(&this, id: u32, index: u64): &T {
expects(id as u64 + 1 < this._start.length);
val start := this._start.data[id];
val length := this._start.data[id as u64 + 1] - start;
expects(index < length);
return &this._items.data[start + index];
}
#! Lends a view of a run's elements.
#! @param this The runs.
#! @param id The run's ID, below `count`, past which a checked program
#! stops.
#! @returns The view, which is only good until the runs grow or close, so a loop
#! that adds runs while it walks one reads it by `at` instead.
pub def runs<T>::view(&this, id: u32): span<T> {
val next := id as u64 + 1;
expects(next < this._start.length);
val start := this._start.data[id];
return this._items[start:this._start.data[next] - start];
}
#! Removes the runs from an ID on, so that the next run made is given it.
#! @param this The runs to remove from.
#! @param count How many runs to keep, from 1, which keeps only the empty one,
#! to `count`, which keeps them all.
#! @remarks Elements removed are closed where they close, or hold what does, and
#! so are those pushed and not yet ended.
pub def runs<T>::rewind(&mut this, count: u64): void {
expects(count != 0 && count <= this.count);
this._items.resize(this._start.data[count]);
this._start.resize(count + 1);
}
#! Removes every run but the empty one, keeping the memory.
#! @param this The runs to empty.
#! @remarks Elements are closed where they close, or hold what does.
pub def runs<T>::clear(&mut this): void {
this._items.clear();
this._start.clear();
this._start.resize(2);
}
#! Removes every run and gives back the memory the runs hold.
#! @param this The runs to close.
#! @remarks Elements are closed where they close, or hold what does. Closed runs
#! hold not even the empty run, until they are cleared.
pub def runs<T>::close(&mut this): void {
this._items.close();
this._start.close();
}
# Stops the program where an ID names no run.
def runs<T>::check(&this, id: u32): void {
expects(id as u64 + 1 < this._start.length);
}
+396
View File
@@ -0,0 +1,396 @@
#! @file stack.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `stack` container. Stacks are a structured
#! container where data is pushed and popped from the memory region in a last-
#! in-first-out (LIFO) manner.
module std::containers;
#! A `stack` is a structured data container that stores its content in a last-
#! in-first-out (LIFO) manner.
#!
#! They are useful in situations where data needs to be tracked in that exact
#! LIFO manner. Situations like that often include things like lexers, parsers,
#! GUI layers, etc.
#! @tparam T The type of its elements.
pub struct stack<T>
: owning
, hashable
, sliceable<T>
, spannable<T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _dat: *mut T;
var _len: u64;
var _cap: u64;
}
#! Provides read only access to the length of a stack.
#! @param this The stack to get the length of.
#! @returns The length of the stack.
pub val stack<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a stack.
#! @param this The stack to get the capacity of.
#! @returns The capacity of the stack.
pub val stack<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a stack is empty.
#! @param this The stack to check.
#! @returns Whether the stack is empty.
pub val stack<T>::empty: bool {
get => this._len == 0;
}
#! Indicates if a stack is full, so the next push makes it grow.
#! @param this The stack to check.
#! @returns Whether the stack is full.
pub val stack<T>::full: bool {
get => this._len == this._cap;
}
#! A view of the elements, from the bottom of the stack to its top.
#! @param this The stack to view.
#! @returns A span of its elements, which is only good until the stack grows,
#! shrinks, or closes.
pub val stack<T>::span: span<T> {
get => span::<T>::over(this._dat, this._len);
}
#! A writable view of the elements, read of a stack that can be written.
#! @param this The stack to view.
#! @returns A slice of its elements, which is only good until the stack grows,
#! shrinks, or closes.
pub val stack<T>::slice: slice<T> {
get mut => slice::<T>::over(this._dat, this._len);
}
#! The element at the bottom of the stack, which a stack that can be written
#! writes through.
#! @param this The stack to read, which holds an element, or else a checked
#! program stops.
#! @returns The element, which is only good until the stack grows, shrinks, or
#! closes.
pub val stack<T>::first: &T {
get => &this.span[0];
get mut => &mut this.slice[0];
}
#! The element on top of the stack, as `peek` reads it, which a stack that can
#! be written writes through.
#! @param this The stack to read, which holds an element, or else a checked
#! program stops.
#! @returns The element, which is only good until the stack grows, shrinks, or
#! closes.
pub val stack<T>::last: &T {
get => &this.span[this._len - 1];
get mut => &mut this.slice[this._len - 1];
}
#! Creates a new stack with no allocator, which takes memory once something is
#! added.
#! @returns The created stack container.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def stack<T>::new(): stack<T> {
return stack::<T>::new(nothing{});
}
#! Creates a new stack with an optional allocator, which takes memory once
#! something is added.
#! @param alloc The optional allocator for the memory backing of the stack.
#! @returns The created stack container.
pub def stack<T>::new(alloc: maybe<&mut allocator>): stack<T> {
return stack::<T> { _alc = alloc, _dat = null, _len = 0, _cap = 0 };
}
#! Creates a new stack with an optional allocator and a provided size.
#! @param size The initial capacity of the stack.
#! @param alloc The optional allocator for the memory backing of the stack.
#! @returns The created stack container.
pub def stack<T>::new(size: u64, alloc: maybe<&mut allocator>): stack<T> {
var made := stack::<T>::new(alloc);
made.reserve(size);
return made;
}
#! Creates a copy of the provided stack.
#! @param other The stack to copy.
#! @returns The created stack container.
pub def stack<T>::copy_of(other: &stack<T>): stack<T> {
var made := stack::<T>::new(other._len, other._alc);
for index in 0..other._len {
made.push(copy::<T>(&other._dat[index]));
}
return made;
}
#! Creates a new stack by moving the data of another stack into it.
#! @param other The stack to move elements from, which holds none after.
#! @returns The moved stack, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no element 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 stack<T>::move_of(other: &mut stack<T>): stack<T> {
val made: stack<T> = stack {
_alc = other._alc,
_dat = other._dat,
_len = other._len,
_cap = other._cap
};
other._dat = null;
other._len = 0;
other._cap = 0;
return made;
}
#! Creates a slice of some of the elements of a stack, from the bottom up, as
#! `sliceable` asks, which `s[start:count]` calls where `s` can be written.
#! @param other The stack to slice, which can be written.
#! @param start The index of the first element viewed, the bottom being 0.
#! @param count How many elements are viewed, or `~0u` for every one after
#! the start.
#! @returns A slice of those elements, which is only good until the stack grows,
#! shrinks, or closes.
#! @remarks A start or count past the top stops a checked program.
pub def stack<T>::slice_of(other: &mut stack<T>, start: u64 = 0, count: u64 = ~0u): slice<T> {
val whole := slice::<T>::over(other._dat, other._len);
return count == ~0u ? whole[start:] : whole[start:count];
}
#! Creates a view of some of the elements of a stack, from the bottom up, as
#! `spannable` asks, which `s[start:count]` calls.
#! @param other The stack to view.
#! @param start The index of the first element viewed, the bottom being 0.
#! @param count How many elements are viewed, or `~0u` for every one after
#! the start.
#! @returns A span of those elements, which is only good until the stack grows,
#! shrinks, or closes.
#! @remarks A start or count past the top stops a checked program.
pub def stack<T>::span_of(other: &stack<T>, start: u64 = 0, count: u64 = ~0u): span<T> {
val whole := span::<T>::over(other._dat, other._len);
return count == ~0u ? whole[start:] : whole[start:count];
}
#! Pushes a new element onto a stack.
#! @param this The stack to push the value onto.
#! @param value The value to push onto a stack.
#! @remarks An allocator that gives no more memory stops the program.
pub def stack<T>::push(&mut this, value: T): void {
if this.full {
this.grow();
}
this._dat[this._len++] = move(value);
}
#! Pops an old value off of a stack.
#! @param this The stack to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def stack<T>::pop(&mut this): void {
expects(!this.empty, "The stack is empty.");
close(&mut this._dat[this._len - 1]);
# The slot is emptied where pushing would close what it held.
if const T is closeable {
memset((this._dat + (this._len - 1)) as *mut u8, 0, bytes_of::<T>(1));
}
this._len--;
}
#! Peeks the element on top of a stack without removing it.
#! @param this The stack to peek the top of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def stack<T>::peek(&this): &T {
expects(!this.empty, "The stack is empty.");
return &this._dat[this._len - 1];
}
#! Peeks the element on top of a stack without removing it.
#! @param this The stack to peek the top of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def stack<T>::peek(&mut this): &mut T {
expects(!this.empty, "The stack is empty.");
return &mut this._dat[this._len - 1];
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the stack provided.
#! @param this The stack to reserve elements for.
#! @param count The number of elements to reserve for a stack.
#! @remarks A stack with room for that many already is left as it is, so this
#! never shrinks it.
pub def stack<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the stack provided, then makes those new elements
#! available.
#! @param this The stack to resize.
#! @param count The number of elements to resize a stack to.
#! @remarks New elements are zeroed. Elements past a smaller count are removed,
#! and closed where they close, or hold what does. An allocator that
#! gives no more memory stops the program.
pub def stack<T>::resize(&mut this, count: u64): void {
# Growing doubles at least, so resizing a little at a time copies little.
if count > this._cap {
this.grow(count > this._cap * 2 ? count : this._cap * 2);
}
if count < this._len {
if const T is closeable {
for index in count..this._len {
close(&mut this._dat[index]);
}
}
# The slots past the length are kept empty where pushing would close them.
if const T is closeable {
memset((this._dat + count) as *mut u8, 0, bytes_of::<T>(this._len - count));
}
}
else {
memset((this._dat + this._len) as *mut u8, 0, bytes_of::<T>(count - this._len));
}
this._len = count;
}
#! Removes all elements from a stack.
#! @param this The stack to clear.
#! @remarks Elements that close, or hold what does, are closed. Once all are
#! closed, the backing data will be cleared but not disposed.
pub def stack<T>::clear(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[index]);
}
}
if const T is closeable {
memset(this._dat as *mut u8, 0, bytes_of::<T>(this._len));
}
this._len = 0;
}
#! Removes all elements of a stack then disposes the backing memory.
#! @param this The stack to close.
pub def stack<T>::close(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[index]);
}
}
dispose::<T>(this._alc, this._dat, this._cap);
this._dat = null;
this._len = 0;
this._cap = 0;
}
#! Compares one stack to another by equality.
#! @param this The stack to compare against.
#! @param other The stack to compare with.
#! @returns Whether the stacks are equal by value.
pub def stack<T>::equals(&this, other: &stack<T>): bool {
if this._len != other._len {
return false;
}
for index in 0..this._len {
return false if !equals::<T>(
&this._dat[index],
&other._dat[index]
);
}
return true;
}
#! What `iter(&this)` lends, which reads the elements from the bottom of the
#! stack.
pub type stack<T>::iterator = span<T>::iterator;
#! What `iter(&mut this)` lends, which writes the elements where the stack holds
#! them.
pub type stack<T>::mutator = slice<T>::mutator;
#! Lends an iterator that reads the elements from the bottom of the stack to
#! its top, which `for x in s` walks.
#! @param this The stack to walk.
#! @returns The iterator, which is only good until the stack grows, shrinks, or
#! closes.
pub def stack<T>::iter(&this): span<T>::iterator {
return this.span.iter();
}
#! Lends a mutator that writes the elements where they are, from the bottom of
#! the stack to its top, which `for &mut x in s` walks.
#! @param this The stack to walk.
#! @returns The mutator, which is only good until the stack grows, shrinks, or
#! closes.
pub def stack<T>::iter(&mut this): slice<T>::mutator {
var whole := this.slice;
return whole.iter();
}
#! An iterator that reads the elements from the bottom of the stack to its top,
#! as `iter` lends.
#! @param this The stack to walk.
#! @returns The iterator, which is only good until the stack grows, shrinks, or
#! closes.
pub val stack<T>::iterator: span<T>::iterator {
get => this.iter();
}
#! A mutator that writes the elements where they are, read of a stack that can
#! be written.
#! @param this The stack to walk.
#! @returns The mutator, which is only good until the stack grows, shrinks, or
#! closes.
pub val stack<T>::mutator: slice<T>::mutator {
get mut => this.iter();
}
#! Hashes the provided stack.
#! @param this The stack to hash.
#! @returns The hashed value of the stack.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def stack<T>::hash(&this): u64 {
var code := this._len;
for index in 0..this._len {
code = mix(code, hash(this._dat[index]));
}
return code;
}
# Gives the stack room for more elements, doubling it.
def stack<T>::grow(&mut this): void {
this.grow(this._cap == 0 ? 4 : this._cap * 2);
}
# Gives the stack room for a number of elements, where it has less. An allocator
# that gives no memory stops the program, as `acquire` and `resize` do.
def stack<T>::grow(&mut this, size: u64): void {
if size <= this._cap {
return;
}
this._dat = this._dat == null
? acquire::<T>(this._alc, size)
: resize::<T>(this._alc, this._dat, this._cap, size);
this._cap = size;
}