#! @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 : owning , copyable , moveable , equatable , hashable , indexable , assignable , sliceable , spannable , iterable , extendable { 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::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::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::empty: bool { get => this._len == 0; } #! Indicates if a vector is full, so the next element added makes it grow. #! @param this The vector to check. #! @returns Whether the vector is full. pub val vector::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::new(): vector { return vector::::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::new(alloc: maybe<&mut allocator>): vector { return vector:: { _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::new(size: u64, alloc: maybe<&mut allocator>): vector { var made := vector::::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::copy_of(other: &vector): vector { var made := vector::::new(other._len, other._alc); for index in 0..other._len { made.append(copy::(&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::move_of(other: &mut vector): vector { var made: vector = 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 some of the elements of a vector, without copying #! them, as `sliceable` asks, which `v[start:count]` calls where `v` can be #! written. #! @param other The vector to view, which can be written. #! @param start The index of the first element viewed. #! @param count How many elements are viewed, or `~0u` for every one after #! the start. #! @returns A view of those elements, which writes them where they are, and is #! only good until the vector grows, shrinks, or closes. #! @remarks A start or count past the last element stops a checked program. pub def vector::slice_of(other: &mut vector, start: u64 = 0, count: u64 = ~0u): slice { # A vector holding any element is never over null, so the slice is made as it # is rather than through `over`, which would ask. val whole := slice:: { _dat = other._dat, _len = other._len }; return count == ~0u ? whole[start:] : whole[start:count]; } #! Lends a view of some of the elements of a vector, without copying them, as #! `spannable` asks, which `v[start:count]` calls. #! @param other The vector to view. #! @param start The index of the first element viewed. #! @param count How many elements are viewed, or `~0u` for every one after #! the start. #! @returns A view of those elements, which is only good until the vector grows, #! shrinks, or closes. #! @remarks A start or count past the last element stops a checked program. pub def vector::span_of(other: &vector, start: u64 = 0, count: u64 = ~0u): span { # Made as it is, as the slice is. val whole := span:: { _dat = other._dat, _len = other._len }; return count == ~0u ? whole[start:] : whole[start:count]; } #! A view of the elements, which copies nothing. #! @param this The vector to view. #! @returns A view of its elements, which is only good until the vector grows, #! shrinks, or closes. @inline pub val vector::span: span { get => span:: { _dat = this._dat, _len = this._len }; } #! A writable view of the elements, read of a vector that can be written. #! @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. @inline pub val vector::slice: slice { get mut => slice:: { _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::at(&this, index: u64): &T { # Indexed as a view of the elements, it is checked as a view's index is. return &span:: { _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::at(&mut this, index: u64): &mut T { return &mut slice:: { _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::get(&this, index: u64): maybe<&T> { # Reached as a view's element, whose check the test answers. return index < this._len ? &span:: { _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::get(&mut this, index: u64): maybe<&mut T> { return index < this._len ? &mut slice:: { _dat = this._dat, _len = this._len }[index] : nothing {}; } #! The first element, which a vector that can be written writes through. #! @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 val vector::first: &T { get { expects(!this.empty, "The vector is empty."); # Reached as a view's element, whose check the test above answers. return &span:: { _dat = this._dat, _len = this._len }[0]; } get mut { expects(!this.empty, "The vector is empty."); return &mut slice:: { _dat = this._dat, _len = this._len }[0]; } } #! The last element, which `v[v.length - 1]` reads, and which a vector that can #! be written writes through. #! @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 val vector::last: &T { get { expects(!this.empty, "The vector is empty."); return &this._dat[this._len - 1]; } get mut { expects(!this.empty, "The vector is empty."); 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::set(&mut this, index: u64, elem: T): void { slice:: { _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::append(&mut this, elem: T): void { if this.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::extend(&mut this, items: span): 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::(&items.data[index]); } } else { memcpy((this._dat + this._len) as *mut u8, items.data as *u8, bytes_of::(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::remove(&mut this, elem: &T): void { for index in 0..this._len { if equals::(&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::insert_at(&mut this, index: u64, elem: T): void { expects(index <= this._len); if index == this._len { this.append(move(elem)); return; } if this.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::(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::(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::remove_at(&mut this, index: u64): void { close(&mut slice:: { _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::(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::(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::truncate(&mut this): void { expects(!this.empty, "The vector is empty."); 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::(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::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::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::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::(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::(this._len - size)); } } else { memset((this._dat + this._len) as *mut u8, 0, bytes_of::(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::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::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::(&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::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::(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::close(&mut this): void { if const T is closeable { for index in 0..this._len { close(&mut this._dat[index]); } } dispose::(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::equals(&this, other: &vector): bool { if this._len != other._len { return false; } for index in 0..this._len { return false if !equals::( &this._dat[index], &other._dat[index] ); } return true; } #! What `iter(&this)` lends, which reads the elements where the vector holds #! them. pub type vector::iterator = span::iterator; #! What `iter(&mut this)` lends, which writes the elements where the vector #! holds them. pub type vector::mutator = slice::mutator; #! Lends an iterator that reads the elements, in order, which `for x in v` #! walks. #! @param this The vector to walk. #! @returns The iterator, which is only good until the vector grows, shrinks, or #! closes. pub def vector::iter(&this): span::iterator { return this.span.iter(); } #! Lends a mutator that writes the elements where they are, which `for &mut x #! in v` walks. #! @param this The vector to walk. #! @returns The mutator, which is only good until the vector grows, shrinks, or #! closes. pub def vector::iter(&mut this): slice::mutator { var whole := this.slice; return whole.iter(); } #! An iterator that reads the elements, in order, as `iter` lends. #! @param this The vector to walk. #! @returns The iterator, which is only good until the vector grows, shrinks, or #! closes. @inline pub val vector::iterator: span::iterator { get => this.span.iter(); } #! A mutator that writes the elements where they are, read of a vector that can #! be written. #! @param this The vector to walk. #! @returns The mutator, which is only good until the vector grows, shrinks, or #! closes. @inline pub val vector::mutator: slice::mutator { get mut => this.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::from(from: I): vector where I: iter { 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::drain(&mut this, which: range): vector::drained { val start := which.start; val stop := start + which.remaining(); expects(stop <= this._len && start <= stop); return vector::::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::drained : owning, sized_iterator, backward_iterator { var _of: &mut vector; #! 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::drained::next(&mut this): maybe { 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::drained::next_back(&mut this): maybe { 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::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::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::(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::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::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::grow(&mut this, size: u64): void { if size <= this._cap { return; } this._dat = this._dat == null ? acquire::(this._alc, size) : resize::(this._alc, this._dat, this._cap, size); this._cap = size; }