Files
sakurac/core/containers/vector.sakura
T

688 lines
24 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
#! @file vector.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `vector` container. Vectors are a structured
#! container that acts like a regular array, but storing its data dynamically.
module core;
#! A growable array, holding its elements one after another in one block of
#! memory, which it owns.
#!
#! It is the general container wherever an array that grows is wanted: adding at
#! its end, indexing, and walking are cheap, and adding or removing anywhere
#! else moves the elements after it.
#! @tparam T The type of its elements.
pub struct vector<T>
: owning
, copyable
, moveable
, equatable
, hashable
, indexable<u64, T>
, sliceable<T>
, viewable<T>
, iterable<T>
, extendable<T>
{
var _alc: maybe<&mut allocator>;
var _dat: *mut T;
var _len: u64;
var _cap: u64;
}
#! Provides read only access to the length of a vector.
#! @param this The vector to get the length of.
#! @returns The length of the vector.
pub val vector<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a vector.
#! @param this The vector to get the capacity of.
#! @returns The capacity of the vector.
pub val vector<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a vector is empty.
#! @param this The vector to check.
#! @returns Whether the vector is empty.
pub val vector<T>::is_empty: bool {
get => this._len == 0;
}
#! Indicates if a vector is full.
#! @param this The vector to check.
#! @returns Whether the vector is full.
pub val vector<T>::is_full: bool {
get => this._len == this._cap;
}
#! Makes an empty vector, which takes memory from the program's heap once
#! something is added.
#! @returns The vector, which holds no memory yet.
pub def vector<T>::new(): vector<T> {
return vector::<T>::new(nothing{});
}
#! Makes an empty vector, which takes memory once something is added.
#! @param alloc The optional allocator to take memory from, or `nothing` for
#! the program's heap.
#! @returns The vector, which holds no memory yet.
pub def vector<T>::new(alloc: maybe<&mut allocator>): vector<T> {
return vector::<T> { _alc = alloc, _dat = null, _len = 0, _cap = 0 };
}
#! Makes an empty vector with room for a number of elements.
#! @param size How many elements it has room for before it grows.
#! @param alloc The optional allocator to take memory from, or `nothing` for
#! the program's heap.
#! @returns The vector, which holds no elements yet.
#! @remarks An allocator that gives no memory stops the program.
pub def vector<T>::new(size: u64, alloc: maybe<&mut allocator>): vector<T> {
var made := vector::<T>::new(alloc);
made.reserve(size);
return made;
}
#! Builds a vector holding copies of another's elements, with its allocator.
#! @param other The vector to copy elements from.
#! @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. Elements are
#! filled where they stand, so nothing is built only to be written
#! over.
pub def vector<T>::copy_of(other: &vector<T>): vector<T> {
var made := vector::<T>::new(other._len, other._alc);
for index in 0..other._len {
made.append(copy::<T>(&other._dat[index]));
}
return made;
}
#! Creates a new vector by moving the data of another vector into it.
#! @param other The vector to move elements from, which holds none after.
#! @returns The moved vector, which takes the memory and the 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 vector<T>::move_of(other: &mut vector<T>): vector<T> {
var made: vector<T> = vector {
_alc = other._alc,
_dat = other._dat,
_len = other._len,
_cap = other._cap
};
other._dat = null;
other._len = 0;
other._cap = 0;
return made;
}
#! Lends a writable view of the elements, without copying them.
#! @param this The vector to view.
#! @returns A view of its elements, which writes them where they are, and is
#! only good until the vector grows, shrinks, or closes.
pub def vector<T>::slice(&mut this): slice<T> {
# A vector holding any element is never over null, so the slice is made as it
# is rather than through `over`, which would ask.
return slice::<T> { _dat = this._dat, _len = this._len };
}
#! Lends a view of the elements, without copying them.
#! @param this The vector to view.
#! @returns A view of its elements, which is only good until the vector grows,
#! shrinks, or closes.
pub def vector<T>::view(&this): span<T> {
# Made as it is, as `slice` is.
return span::<T> { _dat = this._dat, _len = this._len };
}
#! Reads the element at an index, which `v[index]` calls.
#! @param this The vector to read.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element, which is only good until the vector grows, shrinks, or
#! closes.
pub def vector<T>::at(&this, index: u64): &T {
# Indexed as a view of the elements, it is checked as a view's index is.
return &span::<T> { _dat = this._dat, _len = this._len }[index];
}
#! Reaches the element at an index to write it, which `v[index] = x` calls.
#! @param this The vector to write.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element, which is only good until the vector grows, shrinks, or
#! closes.
pub def vector<T>::at(&mut this, index: u64): &mut T {
return &mut slice::<T> { _dat = this._dat, _len = this._len }[index];
}
#! Gets the element at an index, if the vector holds one there, for an index
#! that may be past the end in a program that is right.
#! @param this The vector to read.
#! @param index The index of the element.
#! @returns Maybe the element, which is only good until the vector grows,
#! shrinks, or closes; otherwise, `nothing`.
pub def vector<T>::get(&this, index: u64): maybe<&T> {
# Reached as a view's element, whose check the test answers.
return index < this._len
? &span::<T> { _dat = this._dat, _len = this._len }[index]
: nothing {};
}
#! Gets the element at an index to write it, if the vector holds one there.
#! @param this The vector to write.
#! @param index The index of the element.
#! @returns Maybe the element, which is only good until the vector grows,
#! shrinks, or closes; otherwise, `nothing`.
pub def vector<T>::get(&mut this, index: u64): maybe<&mut T> {
return index < this._len
? &mut slice::<T> { _dat = this._dat, _len = this._len }[index]
: nothing {};
}
#! Reads the first element.
#! @param this The vector to read, which holds an element, or else a checked
#! program stops.
#! @returns The first element, which is only good until the vector grows,
#! shrinks, or closes.
#! @remarks A view's `first` gives `none` where it is empty instead, as one that
#! is asked whether it holds anything.
pub def vector<T>::first(&this): &T {
if const checking() {
if this._len == 0 {
past_end(0, 0);
}
}
# Reached as a view's element, whose check the test above answers.
return &span::<T> { _dat = this._dat, _len = this._len }[0];
}
#! Reaches the first element to write it.
#! @param this The vector to write, which holds an element, or else a checked
#! program stops.
#! @returns The first element, which is only good until the vector grows,
#! shrinks, or closes.
pub def vector<T>::first(&mut this): &mut T {
if const checking() {
if this._len == 0 {
past_end(0, 0);
}
}
return &mut slice::<T> { _dat = this._dat, _len = this._len }[0];
}
#! Reads the last element, which `v[v.length - 1]` reads.
#! @param this The vector to read, which holds an element, or else a checked
#! program stops.
#! @returns The last element, which is only good until the vector grows,
#! shrinks, or closes.
#! @remarks A view's `last` gives `none` where it is empty instead, as one that
#! is asked whether it holds anything.
pub def vector<T>::last(&this): &T {
if const checking() {
if this._len == 0 {
past_end(0, 0);
}
}
return &this._dat[this._len - 1];
}
#! Reaches the last element to write it.
#! @param this The vector to write, which holds an element, or else a checked
#! program stops.
#! @returns The last element, which is only good until the vector grows,
#! shrinks, or closes.
pub def vector<T>::last(&mut this): &mut T {
if const checking() {
if this._len == 0 {
past_end(0, 0);
}
}
return &mut this._dat[this._len - 1];
}
#! Replaces the element at an index.
#! @param this The vector to write.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @param elem The element to store there.
pub def vector<T>::set(&mut this, index: u64, elem: T): void {
slice::<T> { _dat = this._dat, _len = this._len }[index] = move(elem);
}
#! Adds an element after the last.
#! @param this The vector to append to.
#! @param elem The element to append.
#! @remarks An allocator that gives no more memory stops the program.
pub def vector<T>::append(&mut this, elem: T): void {
if this.is_full {
this.grow();
}
this._dat[this._len++] = move(elem);
}
#! Adds copies of elements after the last, in order, as appending each would.
#! @param this The vector to add to.
#! @param items The elements to add, which are not the vector's own, since
#! growing would move them.
#! @remarks Elements are copied by `copyable` where they provide one, and byte
#! for byte where nothing they hold closes. The vector grows once for
#! all of them. An allocator that gives no more memory stops the
#! program.
pub def vector<T>::extend(&mut this, items: span<T>): void {
val count := items.length;
return if count == 0;
val wanted := this._len + count;
if wanted > this._cap {
this.grow(wanted > this._cap * 2 ? wanted : this._cap * 2);
}
if const T is copyable || T is closeable {
for index in 0..count {
this._dat[this._len + index] = copy::<T>(&items.data[index]);
}
} else {
memcpy((this._dat + this._len) as *mut u8, items.data as *u8, bytes_of::<T>(count));
}
this._len = wanted;
}
#! Removes the first element equal to the one given, where any is, moving the
#! elements after it down one.
#! @param this The vector to remove from.
#! @param elem The element to look for, compared by `equals`.
#! @remarks The element removed is closed where it closes, or holds what does.
pub def vector<T>::remove(&mut this, elem: &T): void {
for index in 0..this._len {
if equals::<T>(&this._dat[index], elem) {
this.remove_at(index);
return;
}
}
}
#! Adds an element at an index, moving the elements from it up one.
#! @param this The vector 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 elem The element to insert.
pub def vector<T>::insert_at(&mut this, index: u64, elem: T): void {
if const checking() {
if index > this._len {
past_end(index, this._len);
}
}
if index == this._len {
this.append(move(elem));
return;
}
if this.is_full {
this.grow();
}
val orig := this._dat;
val src := orig + index;
val dst := src + 1;
memcpy(
dst as *mut u8,
src as *mut u8,
bytes_of::<T>(this._len - index)
);
# The slot still holds the bytes of the element moved up from it, which writing
# over would close, so it is emptied first.
if const T is closeable {
memset(src as *mut u8, 0, bytes_of::<T>(1));
}
this._dat[index] = move(elem);
this._len++;
}
#! Removes the element at an index, moving the elements after it down one.
#! @param this The vector 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 vector<T>::remove_at(&mut this, index: u64): void {
close(&mut slice::<T> { _dat = this._dat, _len = this._len }[index]);
# Removing the last element moves nothing, as a stack popping does.
val orig := this._dat;
val after := this._len - index - 1;
if after != 0 {
val dst := orig + index;
memcpy(dst as *mut u8, (dst + 1) as *mut u8, bytes_of::<T>(after));
}
# The last slot still holds the bytes of the element moved down from it, which
# appending would close.
this._len--;
if const T is closeable {
memset((orig + this._len) as *mut u8, 0, bytes_of::<T>(1));
}
}
#! Removes the last element, as `remove_at(length - 1)` does, without moving
#! any other.
#! @param this The vector to remove from, which holds an element, or else a
#! checked program stops.
#! @remarks The element is closed where it closes, or holds what does, and not
#! given back, so read it with `last` first. It is named apart from the
#! `pop` of the stack, queue and heap, which a vector is not.
pub def vector<T>::truncate(&mut this): void {
if const checking() {
if this._len == 0 {
past_end(0, 0);
}
}
this._len--;
if const T is closeable {
close(&mut this._dat[this._len]);
# The slot past the length is kept empty where appending would close it.
memset((this._dat + this._len) as *mut u8, 0, bytes_of::<T>(1));
}
}
#! Makes room for at least a number of elements, keeping those it holds.
#! @param this The vector to make room in.
#! @param count How many elements it should have room for.
#! @remarks A vector with room for that many already is left as it is, so this
#! never shrinks it. An allocator that gives no more memory stops the
#! program.
pub def vector<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Where the elements begin, `length` of them, for what reads or writes them
#! through a pointer, as a container built on a vector does.
#! @param this The vector.
#! @returns The pointer, which is only good until the vector grows, shrinks, or
#! closes. Nothing checks what is reached through it.
pub val vector<T>::data: *mut T {
get => this._dat;
}
#! Makes the vector hold a number of elements, adding zeroed ones or removing
#! those past it.
#! @param this The vector to resize.
#! @param size How many elements it holds after.
#! @remarks Elements removed are closed where they close, or hold what does. An
#! allocator that gives no more memory stops the program.
pub def vector<T>::resize(&mut this, size: u64): void {
# A vector holding no memory yet takes it zeroed, which memory the system
# gives fresh already is, so it is not cleared again.
if this._dat == null && size != 0 {
this._dat = acquire_zeroed::<T>(this._alc, size);
this._cap = size;
this._len = size;
return;
}
# Growing doubles at least, so resizing a little at a time copies little.
if size > this._cap {
this.grow(size > this._cap * 2 ? size : this._cap * 2);
}
if size < this._len {
if const T is closeable {
for index in size..this._len {
close(&mut this._dat[index]);
}
}
# The slots past the length are kept empty where appending would close them.
if const T is closeable {
memset((this._dat + size) as *mut u8, 0, bytes_of::<T>(this._len - size));
}
}
else {
memset((this._dat + this._len) as *mut u8, 0, bytes_of::<T>(size - this._len));
}
this._len = size;
}
#! Makes the vector hold a number more elements, which hold what their memory
#! happened to, for elements the program writes before it reads them, as a
#! table it fills whole: what `resize` adds, without zeroing it.
#! @param this The vector to grow.
#! @param count How many elements it gains.
#! @remarks Only for what closes nothing, since closing an element would close
#! what its memory held. Reading an element before writing it is the
#! program's mistake, which `run --checks` stops at. An allocator that
#! gives no more memory stops the program.
pub def vector<T>::extend_undefined(&mut this, count: u64): void {
if const T is closeable {
compile_error("Elements left undefined would be closed holding what their memory happened to, so a vector of what closes is grown by `resize`.");
}
val size := this._len + count;
if size > this._cap {
this.grow(size > this._cap * 2 ? size : this._cap * 2);
}
this._len = size;
}
#! Makes the vector hold a number of elements, adding copies of one or removing
#! those past it.
#! @param this The vector to resize.
#! @param size How many elements it holds after.
#! @param fill The element each one added is a copy of.
#! @remarks Elements added are copied by `copyable` where they provide one, and
#! elements removed are closed where they close, or hold what does. An
#! allocator that gives no more memory stops the program.
pub def vector<T>::resize(&mut this, size: u64, fill: T): void {
if size <= this._len {
this.resize(size);
return;
}
if size > this._cap {
this.grow(size > this._cap * 2 ? size : this._cap * 2);
}
for index in this._len..size {
this._dat[index] = copy::<T>(&fill);
}
this._len = size;
}
#! Removes every element, keeping the memory the vector holds them in.
#! @param this The vector to empty.
#! @remarks Elements are closed where they close, or hold what does.
pub def vector<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 every element and gives back the memory the vector holds.
#! @param this The vector to close.
#! @remarks Elements are closed where they close, or hold what does. The vector
#! is left empty, so closing it again does nothing.
pub def vector<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 vector to another for equality.
#! @param this The vector to compare against.
#! @param other The vector to compare with.
#! @returns Whether both hold the same elements, in the same order.
pub def vector<T>::equals(&this, other: &vector<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 where the vector holds
#! them.
pub type vector<T>::cursor = span<T>::cursor;
#! What `iter(&mut this)` lends, which writes the elements where the vector
#! holds them.
pub type vector<T>::mut_cursor = slice<T>::mut_cursor;
#! Lends a cursor that reads the elements, in order, which `for x in v` walks.
#! @param this The vector to walk.
#! @returns The cursor, which is only good until the vector grows, shrinks, or
#! closes.
pub def vector<T>::iter(&this): span<T>::cursor {
return this.view().iter();
}
#! Lends a cursor that writes the elements where they are, which `for &mut x in
#! v` walks.
#! @param this The vector to walk.
#! @returns The cursor, which is only good until the vector grows, shrinks, or
#! closes.
pub def vector<T>::iter(&mut this): slice<T>::mut_cursor {
var whole := this.slice();
return whole.iter();
}
#! Makes a vector of the elements an iterator gives, as its `to_vector` does.
#! @tparam I The iterator.
#! @param from The iterator, walked to its end.
#! @returns The vector, given room for them all at once where the iterator knows
#! how many it has left.
pub def vector<T>::from<I>(from: I): vector<T> where I: iterator<T> {
return from.to_vector();
}
#! Moves the elements a range of indexes covers out of the vector, one at a
#! time, as what it gives is walked. Those not walked to are closed where it
#! closes, and the elements after the range then move down into the gap, so
#! the vector holds only those outside the range.
#! @param this The vector to take from.
#! @param which The indexes, from `0` up to `length`, past which a checked
#! program stops.
#! @returns The elements, from the front or the far end, which the vector is not
#! to be changed by anything else while they are walked.
pub def vector<T>::drain(&mut this, which: range<u64>): vector<T>::drained {
val start := which.start;
val stop := start + which.remaining();
if const checking() {
if stop > this._len || start > stop {
past_end(stop, this._len);
}
}
return vector::<T>::drained { _of = this, _start = start, _at = start, _end = stop, _stop = stop };
}
#! What `drain` gives: the elements of a range of indexes, moved out of the
#! vector as they are given. Closing it closes those it did not give and moves
#! the elements after the range down into the gap.
pub struct vector<T>::drained : owning, sized_iterator<T>, backward_iterator<T> {
var _of: &mut vector<T>; #! The vector drained.
var _start: u64; #! Where the range begins, which the gap begins at.
var _at: u64; #! The next element to give from the front.
var _end: u64; #! Just past the next to give from the far end.
var _stop: u64; #! Where the range ends, after which the rest stay.
}
#! Moves out the next element of the range.
#! @param this The drain.
#! @returns Maybe the element; otherwise, `nothing` once the ends have met.
pub def vector<T>::drained::next(&mut this): maybe<T> {
return nothing {} if this._at == this._end;
val at := this._at;
this._at++;
return move(&mut this._of._dat[at]);
}
#! Moves out the element of the range at its far end.
#! @param this The drain.
#! @returns Maybe the element; otherwise, `nothing` once the ends have met.
pub def vector<T>::drained::next_back(&mut this): maybe<T> {
return nothing {} if this._at == this._end;
this._end--;
return move(&mut this._of._dat[this._end]);
}
#! How many elements of the range it has left to give.
#! @param this The drain.
#! @returns How many.
pub def vector<T>::drained::remaining(&this): u64 {
return this._end - this._at;
}
#! Closes the elements of the range it did not give, and moves the elements
#! after the range down into the gap.
#! @param this The drain.
pub def vector<T>::drained::close(&mut this): void {
if const T is closeable {
for index in this._at..this._end {
close(&mut this._of._dat[index]);
}
}
val after := this._of._len - this._stop;
if after != 0 && this._stop != this._start {
val base := this._of._dat;
memcpy((base + this._start) as *mut u8, (base + this._stop) as *mut u8, bytes_of::<T>(after));
}
this._of._len = this._start + after;
this._at = this._end;
this._stop = this._start;
}
#! Hashes the elements, in order.
#! @param this The vector to hash.
#! @returns The hash code, which vectors holding equal elements share.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def vector<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 vector room for more elements, doubling it.
def vector<T>::grow(&mut this): void {
this.grow(this._cap == 0 ? 4 : this._cap * 2);
}
# Gives the vector 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 vector<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;
}