Initial Commit
This commit is contained in:
782 files changed
+145156
No files matched your search
@@ -0,0 +1,170 @@
|
||||
#! @file allocator.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the `allocator` trait, which hands out blocks of memory and takes
|
||||
#! them back, and the functions containers acquire, dispose of, and resize their
|
||||
#! memory through: each uses the allocator it is given, or the program's heap
|
||||
#! where it is given none. Each block is asked for with its size and its
|
||||
#! alignment, and an allocator must outlive every block it gave.
|
||||
|
||||
module core;
|
||||
|
||||
#! Defines what all allocators should be able to do.
|
||||
#!
|
||||
#! Allocators are simply a structured mechanism for being able to manage memory
|
||||
#! in a way that is clear and simple, as an arena, a pool, or the program's heap
|
||||
#! does.
|
||||
#!
|
||||
#! A block is given back with the size it was asked for with, so an allocator
|
||||
#! need not keep the size of each block itself.
|
||||
pub trait allocator {
|
||||
#! The purpose of acquire is to provide you with a block of memory from the
|
||||
#! backing data store that the allocator is managing.
|
||||
#! @param this The allocator to acquire from.
|
||||
#! @param size The number of bytes the block holds.
|
||||
#! @param align What the address of its first byte is a multiple of, a power
|
||||
#! of two no wider than `max_align`.
|
||||
#! @returns The block if it could be acquired; otherwise `null`.
|
||||
#! @remarks The block may hold anything at first.
|
||||
def acquire(&mut this, size: u64, align: u64): *mut u8;
|
||||
|
||||
#! The purpose of dispose is to reclaim the block of memory that was allocated
|
||||
#! to you, freeing it in the backing data store that the allocator is
|
||||
#! managing.
|
||||
#! @param this The allocator to dispose to.
|
||||
#! @param addr The block of memory to dispose.
|
||||
#! @param size The number of bytes it was acquired or last resized with.
|
||||
def dispose(&mut this, addr: *mut u8, size: u64): void;
|
||||
|
||||
#! The purpose of resize is to provide you with a block of memory of another
|
||||
#! size, holding what a block it handed out holds, as far as both reach.
|
||||
#!
|
||||
#! It will allocate the new block, copy the data of the old block to the newly
|
||||
#! allocated one, then release the old block in most cases. The allocator
|
||||
#! implementation has discretion in how it actually accomplishes this, and may
|
||||
#! grow or shrink the block where it is.
|
||||
#! @param this The allocator to resize the allocation.
|
||||
#! @param addr The block to resize, or `null` to acquire one.
|
||||
#! @param old The number of bytes it was acquired or last resized with, or
|
||||
#! 0 where `addr` is `null`.
|
||||
#! @param size The number of bytes the new block holds.
|
||||
#! @param align What the address of its first byte is a multiple of, as it
|
||||
#! was acquired with.
|
||||
#! @returns The new block if it could be acquired; otherwise `null`, leaving
|
||||
#! the old block as it was.
|
||||
#! @remarks What the new block holds past what it keeps may be anything.
|
||||
def resize(&mut this, addr: *mut u8, old: u64, size: u64, align: u64): *mut u8;
|
||||
}
|
||||
|
||||
#! Acquires memory for a number of elements, from an allocator or the heap.
|
||||
#!
|
||||
#! When the allocator is present, its `acquire` gives the block. Otherwise the
|
||||
#! program's heap gives it, as `raw_allocate` does, uncleared.
|
||||
#! @tparam T The type of the elements the memory holds.
|
||||
#! @param alloc The optional allocator to acquire from.
|
||||
#! @param count How many elements the memory holds.
|
||||
#! @returns The block, as a pointer to its first element.
|
||||
#! @remarks The block is zeroed where `T` is `closeable`, so that assigning an
|
||||
#! element into it closes nothing; otherwise it may hold anything at
|
||||
#! first. An allocator that gives no memory stops the program, as
|
||||
#! `raw_allocate` does where the system gives none, so what is given is
|
||||
#! never `null` where any memory was asked for.
|
||||
pub def acquire<T>(alloc: maybe<&mut allocator>, count: u64): *mut T {
|
||||
if const T is closeable {
|
||||
return acquire_zeroed::<T>(alloc, count);
|
||||
}
|
||||
val wanted := bytes_of::<T>(count);
|
||||
val block := match alloc {
|
||||
some(held) => held.acquire(wanted, align_of::<T>()),
|
||||
none => raw_allocate(wanted)
|
||||
};
|
||||
if block == null && wanted != 0 {
|
||||
exhausted(wanted);
|
||||
}
|
||||
return block as *mut T;
|
||||
}
|
||||
|
||||
#! Takes zeroed memory for a number of elements, from an allocator or, where
|
||||
#! none is given, from the program's heap, which clears only memory it used
|
||||
#! before, as `raw_allocate_zeroed` does.
|
||||
#! @tparam T The type of the elements.
|
||||
#! @param alloc The optional allocator to take it from.
|
||||
#! @param count How many elements.
|
||||
#! @returns The first element, zeroed.
|
||||
#! @remarks An allocator that gives no memory stops the program, as `acquire`
|
||||
#! does.
|
||||
pub def acquire_zeroed<T>(alloc: maybe<&mut allocator>, count: u64): *mut T {
|
||||
val wanted := bytes_of::<T>(count);
|
||||
val block := match alloc {
|
||||
some(held) => held.acquire(wanted, align_of::<T>()),
|
||||
none => raw_allocate_zeroed(wanted)
|
||||
};
|
||||
if block == null && wanted != 0 {
|
||||
exhausted(wanted);
|
||||
}
|
||||
if alloc is some(_) {
|
||||
memset(block, 0, wanted);
|
||||
}
|
||||
return block as *mut T;
|
||||
}
|
||||
|
||||
#! Gives memory back to the allocator it came from, or to the heap.
|
||||
#!
|
||||
#! When the allocator is present, its `dispose` takes the block. Otherwise
|
||||
#! `raw_release` gives it back to the program's heap.
|
||||
#! @tparam T The type of the elements the memory holds.
|
||||
#! @param alloc The optional allocator the memory came from.
|
||||
#! @param addr The first element of the block to give back, or `null`, which
|
||||
#! gives back nothing.
|
||||
#! @param count How many elements it was acquired or last resized for.
|
||||
#! @remarks The block must have come from the same allocator, or from the heap
|
||||
#! where none is given. Where it did not, what happens is up to the
|
||||
#! allocator, which may stop the program.
|
||||
pub def dispose<T>(alloc: maybe<&mut allocator>, addr: *mut T, count: u64): void {
|
||||
if addr == null {
|
||||
return;
|
||||
}
|
||||
match alloc {
|
||||
some(held) => held.dispose(addr as *mut u8, bytes_of::<T>(count));
|
||||
none => raw_release(addr as *mut u8);
|
||||
}
|
||||
}
|
||||
|
||||
#! Resizes memory for a number of elements, from an allocator or the heap.
|
||||
#!
|
||||
#! When the allocator is present, its `resize` gives the new block. Otherwise
|
||||
#! `raw_resize` gives it, from the program's heap, or `acquire` does where there
|
||||
#! is no block yet. Either keeps what the old block held, as far as the new one
|
||||
#! reaches, and gives the old block back.
|
||||
#! @tparam T The type of the elements the memory holds.
|
||||
#! @param alloc The optional allocator the memory came from.
|
||||
#! @param addr The first element of the block to resize, which may be `null`
|
||||
#! to acquire a new one.
|
||||
#! @param old How many elements it was acquired or last resized for, or 0
|
||||
#! where `addr` is `null`.
|
||||
#! @param count How many elements the new block holds.
|
||||
#! @returns The new block, as a pointer to its first element.
|
||||
#! @remarks The new block is zeroed past what was kept where `T` is
|
||||
#! `closeable`, as `acquire` zeroes it. The block must have come from
|
||||
#! the same allocator, or from the heap where none is given. An
|
||||
#! allocator that gives no memory stops the program, as `acquire` does.
|
||||
pub def resize<T>(alloc: maybe<&mut allocator>, addr: *mut T, old: u64, count: u64): *mut T {
|
||||
# The old count is one the memory was acquired for, as `dispose` counts it.
|
||||
val had := addr == null ? 0 : old * size_of::<T>();
|
||||
val wanted := bytes_of::<T>(count);
|
||||
val block := match alloc {
|
||||
some(held) => held.resize(addr as *mut u8, had, wanted, align_of::<T>()),
|
||||
none => addr == null ? raw_allocate(wanted) : raw_resize(addr as *mut u8, wanted)
|
||||
};
|
||||
if block == null && wanted != 0 {
|
||||
exhausted(wanted);
|
||||
}
|
||||
if const T is closeable {
|
||||
if wanted > had {
|
||||
memset(block + had, 0, wanted - had);
|
||||
}
|
||||
}
|
||||
return block as *mut T;
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
#! @file atomic.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains atomics: values that several threads, or a thread and a signal
|
||||
#! handler, read and write without a lock, the orders that say what each of
|
||||
#! them sees of the reads and writes around them, and fences.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! How an atomic operation orders the reads and writes around it, as C11's
|
||||
#! memory model has them, which C, C++, Rust, and Zig share.
|
||||
#!
|
||||
#! Within a thread, everything happens in the order the program says. Between
|
||||
#! threads, a `release` store that an `acquire` load reads makes everything the
|
||||
#! storing thread did before the store visible to the loading thread after the
|
||||
#! load. `seq_cst` operations also fall in one order that every thread agrees
|
||||
#! on, and `relaxed` ones are atomic and nothing more. Two threads touching the
|
||||
#! same memory that is not atomic, at least one of them writing, with neither
|
||||
#! happening before the other, is a race, which is the program's mistake: what
|
||||
#! either then reads is not defined.
|
||||
pub enum order : u8 {
|
||||
relaxed, #! Only the operation itself is atomic.
|
||||
acquire, #! What follows a load stays after it.
|
||||
release, #! What comes before a store stays before it.
|
||||
acq_rel, #! Both, for operations that read and write.
|
||||
seq_cst, #! Both, and every `seq_cst` operation falls in one order all threads see.
|
||||
}
|
||||
|
||||
#! The types an atomic holds: those of a word or less that every processor reads
|
||||
#! and writes whole without a lock, which are the integers, `bool`, enums, and
|
||||
#! pointers. The compiler decides what is lock-free, so no type can implement it.
|
||||
pub trait lockfree {}
|
||||
|
||||
#! A value that threads read and write without a lock.
|
||||
#!
|
||||
#! Every operation takes an order, `seq_cst` where none is written, so code that
|
||||
#! does not care writes none, and code that does says exactly what it needs.
|
||||
#! Writing takes `&mut this` and reading `&this`, so no read-only reference
|
||||
#! ever writes; threads share one atomic through `&mut atomic<T>`.
|
||||
#!
|
||||
#! It is `owning`, closing nothing, so it is never copied by accident: a copy
|
||||
#! would read the value without an atomic load, which is a race where another
|
||||
#! thread writes it. A struct holding one is not copied implicitly either, which
|
||||
#! is what shared state wants.
|
||||
#! @tparam T What it holds: an integer, `bool`, enum, or pointer.
|
||||
pub struct atomic<T> : owning where T: lockfree {
|
||||
var _value: T;
|
||||
}
|
||||
|
||||
#! Makes an atomic.
|
||||
#! @param value What it holds first.
|
||||
#! @returns The atomic.
|
||||
pub def atomic<T>::new(value: T): atomic<T> {
|
||||
return atomic::<T> { _value = value };
|
||||
}
|
||||
|
||||
#! Reads what an atomic holds.
|
||||
#! @param this The atomic.
|
||||
#! @param how The order: `relaxed`, `acquire`, or `seq_cst`, since a load
|
||||
#! publishes nothing. Another stops the program with a fault,
|
||||
#! which no switch leaves out.
|
||||
#! @returns What it holds.
|
||||
pub def atomic<T>::load(&this, how: order = order::seq_cst): T {
|
||||
if how == order::release || how == order::acq_rel {
|
||||
misordered(0, how);
|
||||
}
|
||||
return atomic_load::<T>((&this._value) as *T, how);
|
||||
}
|
||||
|
||||
#! Writes a value into an atomic.
|
||||
#! @param this The atomic.
|
||||
#! @param value What it holds after.
|
||||
#! @param how The order: `relaxed`, `release`, or `seq_cst`, since a store
|
||||
#! sees nothing. Another stops the program with a fault, which
|
||||
#! no switch leaves out.
|
||||
pub def atomic<T>::store(&mut this, value: T, how: order = order::seq_cst): void {
|
||||
if how == order::acquire || how == order::acq_rel {
|
||||
misordered(1, how);
|
||||
}
|
||||
atomic_store::<T>((&mut this._value) as *mut T, value, how);
|
||||
}
|
||||
|
||||
#! Writes a value into an atomic, giving what it held, in one step.
|
||||
#! @param this The atomic.
|
||||
#! @param value What it holds after.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::exchange(&mut this, value: T, how: order = order::seq_cst): T {
|
||||
return atomic_exchange::<T>((&mut this._value) as *mut T, value, how);
|
||||
}
|
||||
|
||||
#! Writes a value into an atomic where it holds what is expected, in one step.
|
||||
#! @param this The atomic.
|
||||
#! @param expected What it must hold to be written.
|
||||
#! @param desired What it holds after, where it is written.
|
||||
#! @param success The order where it is written.
|
||||
#! @param failure The order where it is not, which only reads: `relaxed`,
|
||||
#! `acquire`, or `seq_cst`, and no stronger than what
|
||||
#! `success` reads. Another stops the program with a fault,
|
||||
#! which no switch leaves out.
|
||||
#! @returns What it held: as the `value` where it was written, and as the
|
||||
#! `error` where it was not.
|
||||
pub def atomic<T>::compare_exchange(
|
||||
&mut this,
|
||||
expected: T,
|
||||
desired: T,
|
||||
success: order = order::seq_cst,
|
||||
failure: order = order::seq_cst
|
||||
): result<T, T> {
|
||||
if ((failures_taken >> (success as u64 * 5 + failure as u64)) & 1) == 0 {
|
||||
misordered(2, failure);
|
||||
}
|
||||
var found := expected;
|
||||
if atomic_compare_exchange::<T>((&mut this._value) as *mut T, expected, desired, (&mut found) as *mut T, success, failure) {
|
||||
return result::<T, T> { value = expected };
|
||||
}
|
||||
return result::<T, T> { error = found };
|
||||
}
|
||||
|
||||
#! As `compare_exchange`, but may fail although the atomic holds what is
|
||||
#! expected, which costs less on some processors, so it is meant for loops that
|
||||
#! try again. On x86-64 it never fails so.
|
||||
#! @param this The atomic.
|
||||
#! @param expected What it must hold to be written.
|
||||
#! @param desired What it holds after, where it is written.
|
||||
#! @param success The order where it is written.
|
||||
#! @param failure The order where it is not, as `compare_exchange` takes.
|
||||
#! @returns What it held: as the `value` where it was written, and as the
|
||||
#! `error` where it was not.
|
||||
pub def atomic<T>::compare_exchange_weak(
|
||||
&mut this,
|
||||
expected: T,
|
||||
desired: T,
|
||||
success: order = order::seq_cst,
|
||||
failure: order = order::seq_cst
|
||||
): result<T, T> {
|
||||
return this.compare_exchange(expected, desired, success, failure);
|
||||
}
|
||||
|
||||
#! Adds to an integer an atomic holds, wrapping, giving what it held.
|
||||
#! @param this The atomic.
|
||||
#! @param amount What is added.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::fetch_add(&mut this, amount: T, how: order = order::seq_cst): T {
|
||||
if const !(T is integer) {
|
||||
compile_error("`fetch_add` adds to an integer, and the atomic holds none.");
|
||||
}
|
||||
return atomic_fetch::<T, atomic_add>((&mut this._value) as *mut T, amount, how);
|
||||
}
|
||||
|
||||
#! Subtracts from an integer an atomic holds, wrapping, giving what it held.
|
||||
#! @param this The atomic.
|
||||
#! @param amount What is subtracted.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::fetch_sub(&mut this, amount: T, how: order = order::seq_cst): T {
|
||||
if const !(T is integer) {
|
||||
compile_error("`fetch_sub` subtracts from an integer, and the atomic holds none.");
|
||||
}
|
||||
return atomic_fetch::<T, atomic_sub>((&mut this._value) as *mut T, amount, how);
|
||||
}
|
||||
|
||||
#! Keeps the bits of an integer an atomic holds that are also set in others,
|
||||
#! giving what it held.
|
||||
#! @param this The atomic.
|
||||
#! @param bits The others.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::fetch_and(&mut this, bits: T, how: order = order::seq_cst): T {
|
||||
if const !(T is integer) {
|
||||
compile_error("`fetch_and` combines the bits of an integer, and the atomic holds none.");
|
||||
}
|
||||
return atomic_fetch::<T, atomic_and>((&mut this._value) as *mut T, bits, how);
|
||||
}
|
||||
|
||||
#! Sets bits of an integer an atomic holds, giving what it held.
|
||||
#! @param this The atomic.
|
||||
#! @param bits The bits set.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::fetch_or(&mut this, bits: T, how: order = order::seq_cst): T {
|
||||
if const !(T is integer) {
|
||||
compile_error("`fetch_or` combines the bits of an integer, and the atomic holds none.");
|
||||
}
|
||||
return atomic_fetch::<T, atomic_or>((&mut this._value) as *mut T, bits, how);
|
||||
}
|
||||
|
||||
#! Flips bits of an integer an atomic holds, giving what it held.
|
||||
#! @param this The atomic.
|
||||
#! @param bits The bits flipped.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::fetch_xor(&mut this, bits: T, how: order = order::seq_cst): T {
|
||||
if const !(T is integer) {
|
||||
compile_error("`fetch_xor` combines the bits of an integer, and the atomic holds none.");
|
||||
}
|
||||
return atomic_fetch::<T, atomic_xor>((&mut this._value) as *mut T, bits, how);
|
||||
}
|
||||
|
||||
#! Lowers an integer an atomic holds to a value where that is less, compared as
|
||||
#! `T` is, signed or unsigned, giving what it held.
|
||||
#! @param this The atomic.
|
||||
#! @param value The value.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::fetch_min(&mut this, value: T, how: order = order::seq_cst): T {
|
||||
if const !(T is integer) {
|
||||
compile_error("`fetch_min` compares integers, and the atomic holds none.");
|
||||
}
|
||||
return atomic_fetch::<T, atomic_min>((&mut this._value) as *mut T, value, how);
|
||||
}
|
||||
|
||||
#! Raises an integer an atomic holds to a value where that is greater, compared
|
||||
#! as `T` is, signed or unsigned, giving what it held.
|
||||
#! @param this The atomic.
|
||||
#! @param value The value.
|
||||
#! @param how The order.
|
||||
#! @returns What it held before.
|
||||
pub def atomic<T>::fetch_max(&mut this, value: T, how: order = order::seq_cst): T {
|
||||
if const !(T is integer) {
|
||||
compile_error("`fetch_max` compares integers, and the atomic holds none.");
|
||||
}
|
||||
return atomic_fetch::<T, atomic_max>((&mut this._value) as *mut T, value, how);
|
||||
}
|
||||
|
||||
#! Closes an atomic, which owns nothing, so it does nothing; an atomic is
|
||||
#! `owning` only so that it is never copied by accident.
|
||||
#! @param this The atomic.
|
||||
pub def atomic<T>::close(&mut this): void {
|
||||
}
|
||||
|
||||
#! Orders the reads and writes around it as an atomic operation of the order
|
||||
#! would, without one.
|
||||
#! @param how The order.
|
||||
pub def fence(how: order): void {
|
||||
atomic_fence(how);
|
||||
}
|
||||
|
||||
# Stops the program where an atomic operation is given an order it does not
|
||||
# take, as a fault. It is called only where the check fails, so where the
|
||||
# check holds it costs a compare, which folds away where the order is known, and
|
||||
# what calls it stays short enough to be emitted where it is called.
|
||||
# The operation is 0 for a load, 1 for a store, and 2 for a compare-exchange
|
||||
# failing, whose text it says.
|
||||
def misordered(operation: u8, how: order): void {
|
||||
val what := operation == 0 ? "A load's order is `relaxed`, `acquire`, or `seq_cst`"
|
||||
: operation == 1 ? "A store's order is `relaxed`, `release`, or `seq_cst`"
|
||||
: "A compare-exchange failing only reads, so its order is `relaxed`, `acquire`, or `seq_cst`, and no stronger than what it reads succeeding";
|
||||
fault($"{what}, not `{how}`.");
|
||||
}
|
||||
|
||||
# The orders a failed compare-exchange takes, of each it takes where it writes:
|
||||
# the bit `5 * success + failure` is set where that failure order only reads, as
|
||||
# `relaxed`, `acquire`, and `seq_cst` do, no more strongly than what the success
|
||||
# order reads. `relaxed` and `release` read as `relaxed`, `acquire` and
|
||||
# `acq_rel` as `acquire`, and `seq_cst` as itself.
|
||||
const failures_taken: u64 = 0x1 | 0x60 | 0x400 | 0x18000 | 0x1300000;
|
||||
|
||||
# The operations `atomic_fetch` works, as the compilers number them, after a
|
||||
# load, store, exchange, and compare-exchange.
|
||||
const atomic_add: u32 = 4; # Adds, wrapping.
|
||||
const atomic_sub: u32 = 5; # Subtracts, wrapping.
|
||||
const atomic_and: u32 = 6; # Keeps the bits both have.
|
||||
const atomic_or: u32 = 7; # Keeps the bits either has.
|
||||
const atomic_xor: u32 = 8; # Keeps the bits one has.
|
||||
const atomic_min: u32 = 9; # Keeps the less, compared as `T` is.
|
||||
const atomic_max: u32 = 10; # Keeps the greater.
|
||||
|
||||
# Reads `T` at the pointer, in one step, ordered as `how` says.
|
||||
@intrinsic def atomic_load<T>(at: *T, how: order): T where T: lockfree;
|
||||
|
||||
# Writes a value at the pointer, in one step.
|
||||
@intrinsic def atomic_store<T>(at: *mut T, value: T, how: order): void where T: lockfree;
|
||||
|
||||
# Writes a value at the pointer, giving what was there, in one step.
|
||||
@intrinsic def atomic_exchange<T>(at: *mut T, value: T, how: order): T where T: lockfree;
|
||||
|
||||
# Writes `desired` at the pointer where it holds `expected`, in one step, giving
|
||||
# whether it wrote, and writing what it held where `found` points.
|
||||
@intrinsic def atomic_compare_exchange<T>(at: *mut T, expected: T, desired: T, found: *mut T, success: order, failure: order): bool where T: lockfree;
|
||||
|
||||
# Works operation `OP` on the integer at the pointer and the operand, writing
|
||||
# what it gives there, in one step, and giving what was there.
|
||||
@intrinsic def atomic_fetch<T, const OP: u32>(at: *mut T, operand: T, how: order): T where T: lockfree;
|
||||
|
||||
# Orders the reads and writes around it.
|
||||
@intrinsic def atomic_fence(how: order): void;
|
||||
@@ -0,0 +1,122 @@
|
||||
#! @file attribute.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the `attribute` trait a struct declares to be written after `@`, the
|
||||
#! `usage` attribute saying what each attribute may be written on, and the
|
||||
#! attributes the compiler itself reads: `optional`, `intrinsic`, `nodiscard`,
|
||||
#! `allow`, `inline`, `kept`, and `sealed`.
|
||||
|
||||
module core;
|
||||
|
||||
#! Marks a struct as one that may be written after `@` on a declaration, as
|
||||
#! `@test def parses(): void {}`.
|
||||
#!
|
||||
#! It asks for no methods: a struct is an attribute only by declaring it, as
|
||||
#! `struct test : attribute`, and only a struct can be one, since an attribute
|
||||
#! is written as a struct literal. What it may be written on is said by
|
||||
#! `@usage`.
|
||||
pub trait attribute {}
|
||||
|
||||
#! The kinds of declaration an attribute may be written on, which `usage`
|
||||
#! combines, as `target::functions | target::constants`.
|
||||
pub enum target : u32 {
|
||||
functions = 0x0001, #! Functions declared outside any type.
|
||||
methods = 0x0002, #! Functions declared on a type, as `def list<T>::push`.
|
||||
constants = 0x0004, #! Constants, including a type's own, as `const u8::top`.
|
||||
variables = 0x0008, #! Variables outside any function, including a type's own.
|
||||
fields = 0x0010, #! Fields of structs and unions.
|
||||
structs = 0x0020, #! Structs.
|
||||
unions = 0x0040, #! Unions.
|
||||
enums = 0x0080, #! Enums.
|
||||
members = 0x0100, #! Members of enums.
|
||||
traits = 0x0200, #! Traits.
|
||||
requirements = 0x0400, #! What a trait declares: its methods, properties, and constants.
|
||||
aliases = 0x0800, #! Declarations of aliases, as `type id = u64`.
|
||||
properties = 0x1000, #! Properties, both of whose accessors share their attributes.
|
||||
parameters = 0x2000, #! Parameters of functions, written before the parameter's name.
|
||||
all = 0xFFFF, #! Every kind of declaration.
|
||||
}
|
||||
|
||||
#! Says what the attribute struct it is written on may describe.
|
||||
#!
|
||||
#! The compiler reads it where each attribute is written, so an attribute on a
|
||||
#! declaration its usage leaves out, or a second on the same declaration, is an
|
||||
#! error there. A struct without one may go anywhere, once per declaration.
|
||||
@usage{ on = target::structs }
|
||||
pub struct usage : attribute {
|
||||
#! The kinds of declaration it may be written on.
|
||||
#!
|
||||
#! It is defined as a `flags32<target>` to make it explicitly convertible to
|
||||
#! and from an unsigned integer. By combining targets, an attribute with a
|
||||
#! non-defaulted `@usage{}` then declares what the attribute may be used on,
|
||||
#! which becomes enforced by the compiler.
|
||||
pub val on: flags32<target> = target::all;
|
||||
|
||||
#! Whether a declaration may have more than one of it.
|
||||
#!
|
||||
#! Multiple attributes of the same kind are typically discouraged, but allowed.
|
||||
#! For example, it may be useful to an application to be able to define an
|
||||
#! `@alias{ name = ... }` attribute on some object whose name can be many
|
||||
#! different values.
|
||||
pub val many: bool = false;
|
||||
|
||||
#! Whether an alias of the declaration it is written on has it too, as reflection
|
||||
#! sees it.
|
||||
pub val through: bool = true;
|
||||
}
|
||||
|
||||
#! Marks a trait's method as one a type may leave out. A call reaches it where
|
||||
#! the type is known to have it, and through a trait reference, the call goes to
|
||||
#! the method the trait requires instead, as `at(&this)` stands in for an
|
||||
#! `indexable`'s `@optional def at(&mut this, key: K): &mut V;`.
|
||||
@usage{ on = target::requirements }
|
||||
pub struct optional : attribute {}
|
||||
|
||||
#! Marks what the compiler gives, which ends at its signature: a function, as
|
||||
#! `@intrinsic def size_of<T>(): u64;`, or a property whose accessors do.
|
||||
@usage{ on = target::functions | target::methods | target::properties | target::structs }
|
||||
pub struct intrinsic : attribute {}
|
||||
|
||||
#! Marks what must be handled where it is made: a function whose result each
|
||||
#! call must use, or a type whose values must be, as `result<T, E>` is. A call
|
||||
#! written as a statement of its own that lets such a value go is an error, and
|
||||
#! `_ = f();` lets it go on purpose.
|
||||
@usage{ on = target::functions | target::methods | target::requirements | target::structs | target::unions | target::enums }
|
||||
pub struct nodiscard : attribute {}
|
||||
|
||||
#! Quiets the warnings the checker makes of a function, as of a reference kept
|
||||
#! past what it refers to, where the function is right for reasons the checker
|
||||
#! cannot see.
|
||||
@usage{ on = target::functions | target::methods }
|
||||
pub struct allow : attribute {}
|
||||
|
||||
#! Marks a function whose calls are each replaced by a copy of its body, at
|
||||
#! every level of optimizing, `-O0` too, whatever its size. A call it cannot
|
||||
#! copy stays a call: one through a trait reference, or a function value whose
|
||||
#! function is not known, and the one closing a loop of calls, as a function
|
||||
#! calling itself. Written on a property, it marks both accessors. A function
|
||||
#! C or the compiler gives has no body to copy, so it is never `@inline`. A run
|
||||
#! checking its memory copies none, so each function's locals end where its
|
||||
#! frame does.
|
||||
@usage{ on = target::functions | target::methods | target::properties }
|
||||
pub struct inline : attribute {}
|
||||
|
||||
#! Marks a parameter whose argument what the function returns keeps, as a
|
||||
#! `function` keeps the callable it is made of, or a thread's handle the
|
||||
#! function the thread runs. What the argument refers to, the result then
|
||||
#! refers to as well, so a result outliving the locals an anonymous function
|
||||
#! given for it names is warned of, as the function itself would be.
|
||||
@usage{ on = target::parameters }
|
||||
pub struct kept : attribute {}
|
||||
|
||||
#! Marks a trait nothing implements, which says something of the types it is
|
||||
#! given rather than asking anything of one, as
|
||||
#! `@sealed pub trait closes<T> { const value := T is closeable; }`. Its
|
||||
#! constants and types are its own, read through it given its type arguments,
|
||||
#! as `closes::<T>::value`, and each holds a value. No type or trait names it,
|
||||
#! and nothing satisfies it, so it bounds nothing and is never tested with `is`
|
||||
#! or referred to.
|
||||
@usage{ on = target::traits }
|
||||
pub struct sealed : attribute {}
|
||||
@@ -0,0 +1,74 @@
|
||||
#! @file bits.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains counting and reversing the bits and bytes of an integer, which no
|
||||
#! operator writes, and which text, memory, and vectors are searched with.
|
||||
#!
|
||||
#! The compiler gives the operations of a whole word they are built on: the
|
||||
#! virtual machine runs its own, and an executable the instructions `bsr`,
|
||||
#! `bsf`, and `bswap`, and a sequence counting ones, since SSE2 alone has no
|
||||
#! `popcnt`.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! How many bits of an integer are 1, as its type holds it, so -1 of an `i8` has
|
||||
#! 8.
|
||||
#! @tparam T The type of integer.
|
||||
#! @param x The integer.
|
||||
#! @returns How many.
|
||||
pub def count_ones<T>(x: T): u32 where T: integer {
|
||||
return ones_in(x as u64 & bits_mask::<T>()) as u32;
|
||||
}
|
||||
|
||||
#! How many 0 bits lead an integer, from its top bit, as its type holds it.
|
||||
#! @tparam T The type of integer.
|
||||
#! @param x The integer.
|
||||
#! @returns How many: the width of the type where it is zero, and 0 where it is
|
||||
#! below zero.
|
||||
pub def leading_zeros<T>(x: T): u32 where T: integer {
|
||||
return (zeros_leading(x as u64 & bits_mask::<T>()) - (64 - size_of::<T>() * 8)) as u32;
|
||||
}
|
||||
|
||||
#! How many 0 bits trail an integer, from its bottom bit.
|
||||
#! @tparam T The type of integer.
|
||||
#! @param x The integer.
|
||||
#! @returns How many: the width of the type where it is zero.
|
||||
@inline
|
||||
pub def trailing_zeros<T>(x: T): u32 where T: integer {
|
||||
if const size_of::<T>() == 8 {
|
||||
return zeros_trailing(x as u64) as u32;
|
||||
}
|
||||
return zeros_trailing(x as u64 | (1u << (size_of::<T>() * 8))) as u32;
|
||||
}
|
||||
|
||||
#! An integer with its bytes in the reverse order, as converting between little
|
||||
#! and big endian does.
|
||||
#! @tparam T The type of integer.
|
||||
#! @param x The integer.
|
||||
#! @returns The integer reversed.
|
||||
pub def swap_bytes<T>(x: T): T where T: integer {
|
||||
return (bytes_reversed(x as u64) >> (64 - size_of::<T>() * 8)) as T;
|
||||
}
|
||||
|
||||
# The bits of a word a type of integer holds.
|
||||
def bits_mask<T>(): u64 where T: integer {
|
||||
if const size_of::<T>() == 8 {
|
||||
return 0xFFFFFFFFFFFFFFFFu;
|
||||
}
|
||||
return (1u << (size_of::<T>() * 8)) - 1;
|
||||
}
|
||||
|
||||
# How many bits of a word are 1.
|
||||
@intrinsic def ones_in(word: u64): u64;
|
||||
|
||||
# How many 0 bits lead a word from its top: 64 where it is zero.
|
||||
@intrinsic def zeros_leading(word: u64): u64;
|
||||
|
||||
# How many 0 bits trail a word from its bottom: 64 where it is zero.
|
||||
@intrinsic def zeros_trailing(word: u64): u64;
|
||||
|
||||
# A word with its bytes in the reverse order.
|
||||
@intrinsic def bytes_reversed(word: u64): u64;
|
||||
@@ -0,0 +1,14 @@
|
||||
#! @file bool.ext.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#!
|
||||
module core;
|
||||
|
||||
#!
|
||||
pub def bool::parse(value: &strview): bool {
|
||||
return
|
||||
value == "true" || value == "1" ||
|
||||
value == "yes" || value == "on";
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
#! @file decimal.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the conversion of decimal text to the nearest 64-bit float, which
|
||||
#! `real::parse` reads numbers with.
|
||||
#!
|
||||
#! Most numbers have few enough digits, and a small enough exponent, that one
|
||||
#! multiplication or division of two exact floats gives the nearest float. The
|
||||
#! rest are converted as Go's `strconv` converts them: the number is held as
|
||||
#! decimal digits, and multiplied and divided by powers of two, which a decimal
|
||||
#! holds exactly, until its 53 bits can be read off and rounded.
|
||||
|
||||
module core;
|
||||
|
||||
# Digits a decimal holds; past them, only whether any was not zero matters.
|
||||
const decimal_capacity: u64 = 800;
|
||||
|
||||
# Digits a shift by 60 bits can add, which is how far one shift goes.
|
||||
const decimal_room: u64 = 19;
|
||||
|
||||
# The largest integer every integer below which a float holds exactly.
|
||||
const decimal_exact: u64 = 9007199254740992;
|
||||
|
||||
# How far to shift a decimal whose point is a number of digits from where it should
|
||||
# be, so the shift moves it by no more than that.
|
||||
const decimal_shifts: u64[9] = [1, 3, 6, 9, 13, 16, 19, 23, 26];
|
||||
|
||||
# A number as decimal digits, each from 0 to 9, with the point `point` digits from
|
||||
# the first, which may be before it or past the last.
|
||||
struct decimal_digits {
|
||||
var digits: u8[decimal_capacity + decimal_room];
|
||||
var count: u64;
|
||||
var point: i64;
|
||||
var truncated: bool; #! Whether a digit past those held was not zero.
|
||||
}
|
||||
|
||||
# The float nearest the number some digits write, which may hold a `.`, times ten
|
||||
# to an exponent, or `nothing` where it is too large for one.
|
||||
def decimal_digits::nearest(written: strview, exponent: i64): maybe<f64> {
|
||||
# The first 19 digits after the leading zeros, and whether those after were all
|
||||
# zero, which is all one exact multiplication needs.
|
||||
var mantissa := 0u;
|
||||
var held := 0u;
|
||||
var scale := exponent;
|
||||
var exact: bool = true;
|
||||
var dotted: bool = false;
|
||||
for byte in written {
|
||||
if byte == '.' {
|
||||
dotted = true;
|
||||
continue;
|
||||
}
|
||||
if held == 0 && byte == '0' {
|
||||
if dotted {
|
||||
scale--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if held < 19 {
|
||||
mantissa = mantissa * 10 + byte.digit_value;
|
||||
held++;
|
||||
if dotted {
|
||||
scale--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if byte != '0' {
|
||||
exact = false;
|
||||
}
|
||||
if !dotted {
|
||||
scale++;
|
||||
}
|
||||
}
|
||||
|
||||
if mantissa == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
if exact && mantissa <= decimal_exact && scale >= -22 && scale <= 22 {
|
||||
val whole := mantissa as f64;
|
||||
return scale < 0 ? whole / decimal_digits::power_of_ten(-scale) : whole * decimal_digits::power_of_ten(scale);
|
||||
}
|
||||
|
||||
var number: decimal_digits;
|
||||
number.read(written, exponent);
|
||||
return number.to_float();
|
||||
}
|
||||
|
||||
# Reads the digits some text writes, without their leading zeros.
|
||||
def decimal_digits::read(&mut this, written: strview, exponent: i64): void {
|
||||
var dotted: bool = false;
|
||||
for byte in written {
|
||||
if byte == '.' {
|
||||
dotted = true;
|
||||
continue;
|
||||
}
|
||||
if this.count == 0 && byte == '0' {
|
||||
if dotted {
|
||||
this.point--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if !dotted {
|
||||
this.point++;
|
||||
}
|
||||
if this.count < decimal_capacity {
|
||||
this.digits[this.count] = byte.digit_value as u8;
|
||||
this.count++;
|
||||
} else if byte != '0' {
|
||||
this.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.point += exponent;
|
||||
this.trim();
|
||||
}
|
||||
|
||||
# The float nearest the number, as Go's `strconv` finds it, or `nothing` where it
|
||||
# is too large for one.
|
||||
def decimal_digits::to_float(&mut this): maybe<f64> {
|
||||
if this.count == 0 || this.point < -330 {
|
||||
return 0.0;
|
||||
}
|
||||
if this.point > 310 {
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
# Halve or double the number, counting how often, until it is in [0.5, 1).
|
||||
var exponent: i64 = 0;
|
||||
while this.point > 0 {
|
||||
val by := decimal_digits::shift_for(this.point);
|
||||
this.shift(-by);
|
||||
exponent += by;
|
||||
}
|
||||
while this.point < 0 || (this.point == 0 && this.digits[0] < 5) {
|
||||
val by := decimal_digits::shift_for(-this.point);
|
||||
this.shift(by);
|
||||
exponent -= by;
|
||||
}
|
||||
|
||||
# A float's significand is in [1, 2), and below the smallest exponent a float
|
||||
# holds, the number is subnormal, with fewer bits.
|
||||
exponent--;
|
||||
if exponent < -1022 {
|
||||
val by := -1022 - exponent;
|
||||
this.shift(-by);
|
||||
exponent += by;
|
||||
}
|
||||
if exponent > 1023 {
|
||||
return nothing{};
|
||||
}
|
||||
|
||||
# Its 53 bits, rounded, which may round up to one bit more.
|
||||
this.shift(53);
|
||||
var mantissa := this.rounded();
|
||||
if mantissa == decimal_exact {
|
||||
mantissa = mantissa >> 1;
|
||||
exponent++;
|
||||
if exponent > 1023 {
|
||||
return nothing{};
|
||||
}
|
||||
}
|
||||
return (mantissa as f64) * decimal_digits::power_of_two(exponent - 52);
|
||||
}
|
||||
|
||||
# Multiplies the number by two to a power, which divides it where the power is
|
||||
# negative, sixty bits at a time.
|
||||
def decimal_digits::shift(&mut this, by: i64): void {
|
||||
if this.count == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
var left := by;
|
||||
while left > 60 {
|
||||
this.shift_left(60);
|
||||
left -= 60;
|
||||
}
|
||||
while left < -60 {
|
||||
this.shift_right(60);
|
||||
left += 60;
|
||||
}
|
||||
if left > 0 {
|
||||
this.shift_left(left as u64);
|
||||
}
|
||||
if left < 0 {
|
||||
this.shift_right((-left) as u64);
|
||||
}
|
||||
}
|
||||
|
||||
# Multiplies the number by two to a power of at most 60, writing the digits from
|
||||
# the last into the room past those held, then moving them to the front.
|
||||
def decimal_digits::shift_left(&mut this, by: u64): void {
|
||||
var read := this.count;
|
||||
var write := this.count + decimal_room;
|
||||
var carry := 0u;
|
||||
while read > 0 {
|
||||
read--;
|
||||
carry += (this.digits[read] as u64) << by;
|
||||
val quotient := carry / 10;
|
||||
write--;
|
||||
this.digits[write] = (carry - quotient * 10) as u8;
|
||||
carry = quotient;
|
||||
}
|
||||
while carry > 0 {
|
||||
val quotient := carry / 10;
|
||||
write--;
|
||||
this.digits[write] = (carry - quotient * 10) as u8;
|
||||
carry = quotient;
|
||||
}
|
||||
|
||||
val made := this.count + decimal_room - write;
|
||||
val first := (&mut this.digits) as *mut u8;
|
||||
memcpy(first, first + write, made);
|
||||
for k in decimal_capacity..made {
|
||||
if this.digits[k] != 0 {
|
||||
this.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.point += (made - this.count) as i64;
|
||||
this.count = made < decimal_capacity ? made : decimal_capacity;
|
||||
this.trim();
|
||||
}
|
||||
|
||||
# Divides the number by two to a power of at most 60.
|
||||
def decimal_digits::shift_right(&mut this, by: u64): void {
|
||||
var read := 0u;
|
||||
var write := 0u;
|
||||
var carry := 0u;
|
||||
|
||||
# Enough of the first digits to divide, counting zeros past the last as digits.
|
||||
while (carry >> by) == 0 {
|
||||
if read >= this.count {
|
||||
if carry == 0 {
|
||||
this.count = 0;
|
||||
return;
|
||||
}
|
||||
while (carry >> by) == 0 {
|
||||
carry = carry * 10;
|
||||
read++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
carry = carry * 10 + this.digits[read];
|
||||
read++;
|
||||
}
|
||||
|
||||
this.point -= (read as i64) - 1;
|
||||
val mask := (1u << by) - 1;
|
||||
while read < this.count {
|
||||
val next := this.digits[read];
|
||||
this.digits[write] = (carry >> by) as u8;
|
||||
write++;
|
||||
carry = (carry & mask) * 10 + next;
|
||||
read++;
|
||||
}
|
||||
while carry > 0 {
|
||||
val digit := carry >> by;
|
||||
carry = (carry & mask) * 10;
|
||||
if write < decimal_capacity {
|
||||
this.digits[write] = digit as u8;
|
||||
write++;
|
||||
} else if digit > 0 {
|
||||
this.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.count = write;
|
||||
this.trim();
|
||||
}
|
||||
|
||||
# The integer part of the number, rounded by the digits after the point, halfway
|
||||
# going to an even integer.
|
||||
def decimal_digits::rounded(&this): u64 {
|
||||
if this.point > 20 {
|
||||
return 0xFFFFFFFFFFFFFFFF;
|
||||
}
|
||||
|
||||
var whole := 0u;
|
||||
var at: i64 = 0;
|
||||
while at < this.point && at < (this.count as i64) {
|
||||
whole = whole * 10 + this.digits[at as u64];
|
||||
at++;
|
||||
}
|
||||
while at < this.point {
|
||||
whole = whole * 10;
|
||||
at++;
|
||||
}
|
||||
if this.rounds_up() {
|
||||
whole++;
|
||||
}
|
||||
return whole;
|
||||
}
|
||||
|
||||
# Whether the digits after the point round the integer part up: past halfway, or
|
||||
# exactly halfway with an odd integer part, or halfway with digits left out past it.
|
||||
def decimal_digits::rounds_up(&this): bool {
|
||||
if this.point < 0 || this.point >= (this.count as i64) {
|
||||
return false;
|
||||
}
|
||||
|
||||
val at := this.point as u64;
|
||||
if this.digits[at] == 5 && at + 1 == this.count {
|
||||
if this.truncated {
|
||||
return true;
|
||||
}
|
||||
return at > 0 && this.digits[at - 1] % 2 == 1;
|
||||
}
|
||||
return this.digits[at] >= 5;
|
||||
}
|
||||
|
||||
# Drops the zeros after the last digit that is not one.
|
||||
def decimal_digits::trim(&mut this): void {
|
||||
while this.count > 0 && this.digits[this.count - 1] == 0 {
|
||||
this.count--;
|
||||
}
|
||||
if this.count == 0 {
|
||||
this.point = 0;
|
||||
}
|
||||
}
|
||||
|
||||
def decimal_digits::shift_for(digits: i64): i64 {
|
||||
return digits < 9 ? decimal_shifts[digits as u64] as i64 : 27;
|
||||
}
|
||||
|
||||
# Ten to a power from 0 to 22, which a float holds exactly.
|
||||
def decimal_digits::power_of_ten(power: i64): f64 {
|
||||
var made: f64 = 1;
|
||||
for _ in 0..power {
|
||||
made *= 10;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Two to a power from -1074 to 1023, which a float holds exactly.
|
||||
def decimal_digits::power_of_two(power: i64): f64 {
|
||||
var made: f64 = 1;
|
||||
var left := power;
|
||||
while left > 0 {
|
||||
made *= 2;
|
||||
left--;
|
||||
}
|
||||
while left < 0 {
|
||||
made *= 0.5;
|
||||
left++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#! @file pair.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `pair`, two values kept together, as `enumerate` gives each element
|
||||
#! with its index and `zip` the elements of two iterators side by side.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Two values kept together, each named for where it stands.
|
||||
#! @tparam A The type of the first.
|
||||
#! @tparam B The type of the second.
|
||||
pub struct pair<A, B> {
|
||||
pub var first: A; #! The first value.
|
||||
pub var second: B; #! The second value.
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
#! @file slice.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the methods of `slice`, a writable view over elements that something
|
||||
#! else holds. It is the counterpart of `span<T>`, which only reads, and lends one
|
||||
#! of itself wherever a reader is wanted.
|
||||
#!
|
||||
#! `slice` is among the types the syntax makes, which the compiler declares
|
||||
#! itself. A slice owns nothing: writing through it writes the elements where
|
||||
#! they already live, and closing whatever holds them leaves the slice pointing
|
||||
#! at memory that is no longer there, so keep a slice no longer than the thing
|
||||
#! it views. It converts to a `span<T>` wherever a reader is wanted, which drops
|
||||
#! the right to write.
|
||||
module core;
|
||||
|
||||
|
||||
#! The number of elements the view covers.
|
||||
#! @param this The slice to measure.
|
||||
#! @returns How many elements it covers, starting at `data`.
|
||||
pub val slice<T>::length: u64 {
|
||||
get => this._len;
|
||||
}
|
||||
|
||||
#! The first element the view covers, which is `null` for an empty view.
|
||||
#! @param this The slice to read the address of.
|
||||
#! @returns Where the elements begin.
|
||||
pub val slice<T>::data: *mut T {
|
||||
get => this._dat;
|
||||
}
|
||||
|
||||
#! Makes a writable view over a run of elements.
|
||||
#! @param data The first element, or `null` for a view over nothing.
|
||||
#! @param length The number of elements the view covers.
|
||||
#! @returns The view, which covers nothing where `data` is `null`.
|
||||
#! @remarks A fixed array holds its elements where it stands, so a writable view
|
||||
#! over a `var` one is `array[0:N]`.
|
||||
pub def slice<T>::over(data: *mut T, length: u64): slice<T> {
|
||||
return data == null
|
||||
? slice { _dat = null, _len = 0 }
|
||||
: slice { _dat = data, _len = length };
|
||||
}
|
||||
|
||||
#! Makes a view over nothing, which is the zero value of a slice.
|
||||
#! @returns A view of no elements.
|
||||
pub def slice<T>::blank(): slice<T> {
|
||||
return slice { _dat = null, _len = 0 };
|
||||
}
|
||||
|
||||
#! Whether the view covers no elements.
|
||||
#! @param this The slice to test.
|
||||
#! @returns Whether its length is zero.
|
||||
@inline
|
||||
pub val slice<T>::empty: bool {
|
||||
get => this._len == 0;
|
||||
}
|
||||
|
||||
|
||||
#! Reads the element at an index, which `slice[index]` does without calling it.
|
||||
#! @param this The slice to read.
|
||||
#! @param index The index of the element, below `length`, past which a checked
|
||||
#! program stops.
|
||||
#! @returns The element, which refers into whatever holds the elements.
|
||||
pub def slice<T>::at(&this, index: u64): &T {
|
||||
# Indexed as a view, it is checked as `slice[index]` is, which the compiler does
|
||||
# itself rather than calling this.
|
||||
val whole: slice<T> = this;
|
||||
return &whole[index];
|
||||
}
|
||||
|
||||
#! Reaches the element at an index to write it, which `slice[index] = x` does
|
||||
#! without calling it.
|
||||
#! @param this The slice to write through.
|
||||
#! @param index The index of the element, below `length`, past which a checked
|
||||
#! program stops.
|
||||
#! @returns The element, which refers into whatever holds the elements.
|
||||
pub def slice<T>::at(&mut this, index: u64): &mut T {
|
||||
var whole: slice<T> = this;
|
||||
return &mut whole[index];
|
||||
}
|
||||
|
||||
#! Gets the element at an index, if the slice covers one there.
|
||||
#! @param this The slice to read.
|
||||
#! @param index The index of the element.
|
||||
#! @returns Maybe the element, which refers into whatever holds the elements;
|
||||
#! otherwise, `nothing`.
|
||||
pub def slice<T>::get(&this, index: u64): maybe<&T> {
|
||||
# Reached as the view's element, whose check the test answers.
|
||||
val whole: slice<T> = this;
|
||||
return index < this._len ? &whole[index] : nothing {};
|
||||
}
|
||||
|
||||
#! Gets the element at an index to write it, if the slice covers one there.
|
||||
#! @param this The slice to write through.
|
||||
#! @param index The index of the element.
|
||||
#! @returns Maybe the element, which refers into whatever holds the elements;
|
||||
#! otherwise, `nothing`.
|
||||
pub def slice<T>::get(&mut this, index: u64): maybe<&mut T> {
|
||||
var whole: slice<T> = this;
|
||||
return index < this._len ? &mut whole[index] : nothing {};
|
||||
}
|
||||
|
||||
#! Lends a writable view of some of the same elements, as `sliceable` asks,
|
||||
#! which `slice[start:count]` is without calling it.
|
||||
#! @param other The slice to lend.
|
||||
#! @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 slice covering those elements, which is the slice itself where it
|
||||
#! covers all of them.
|
||||
#! @remarks A start or count past the last element stops a checked program, as
|
||||
#! `slice[start:count]` does.
|
||||
pub def slice<T>::slice_of(other: &mut slice<T>, start: u64 = 0, count: u64 = ~0u): slice<T> {
|
||||
val whole: slice<T> = other;
|
||||
return count == ~0u ? whole[start:] : whole[start:count];
|
||||
}
|
||||
|
||||
#! A writable view of the same elements, which is the slice itself, read of a
|
||||
#! slice that can be written.
|
||||
#! @param this The slice to lend.
|
||||
#! @returns A copy of the slice, covering the same elements.
|
||||
@inline
|
||||
pub val slice<T>::slice: slice<T> {
|
||||
get mut => this;
|
||||
}
|
||||
|
||||
#! Lends a read-only view of some of the same elements, as `spannable` asks.
|
||||
#! @param other The slice to lend.
|
||||
#! @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 `span<T>` over those elements.
|
||||
#! @remarks A start or count past the last element stops a checked program.
|
||||
pub def slice<T>::span_of(other: &slice<T>, start: u64 = 0, count: u64 = ~0u): span<T> {
|
||||
# A slice is never over null while it covers anything, so the view is made as
|
||||
# it is.
|
||||
val whole := span::<T> { _dat = other._dat as *T, _len = other._len };
|
||||
return count == ~0u ? whole[start:] : whole[start:count];
|
||||
}
|
||||
|
||||
#! A read-only view of the same elements.
|
||||
#! @param this The slice to lend.
|
||||
#! @returns A `span<T>` over the elements it covers.
|
||||
#! @remarks A slice converts to a span on its own wherever one is wanted, so
|
||||
#! this is only written where the conversion needs to be named.
|
||||
@inline
|
||||
pub val slice<T>::span: span<T> {
|
||||
get => span::<T> { _dat = this._dat as *T, _len = this._len };
|
||||
}
|
||||
|
||||
#! What `iter(&this)` lends, which reads the elements a slice covers as the
|
||||
#! span it converts to does, and which `for x` and `for &x` walk.
|
||||
pub type slice<T>::iterator = span<T>::iterator;
|
||||
|
||||
#! Walks the elements a slice covers, giving a reference that writes each in
|
||||
#! turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
|
||||
pub struct slice<T>::mutator : sized_iterator<&mut T>, backward_iterator<&mut T> {
|
||||
var _at: *mut T;
|
||||
var _left: u64;
|
||||
}
|
||||
|
||||
#! Gives the next element the slice covers, to be written.
|
||||
#! @param this The mutator to advance.
|
||||
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
|
||||
pub def slice<T>::mutator::next(&mut this): maybe<&mut T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
val here := this._at;
|
||||
this._at = here + 1;
|
||||
this._left = this._left - 1;
|
||||
return &mut here[0];
|
||||
}
|
||||
|
||||
#! How many elements the mutator has left to give.
|
||||
#! @param this The mutator.
|
||||
#! @returns How many.
|
||||
pub def slice<T>::mutator::remaining(&this): u64 {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
#! Gives the last element the mutator has left, from the far end of the slice,
|
||||
#! to be written.
|
||||
#! @param this The mutator to advance from its far end.
|
||||
#! @returns Maybe a reference to the element; otherwise, `nothing`.
|
||||
pub def slice<T>::mutator::next_back(&mut this): maybe<&mut T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
this._left = this._left - 1;
|
||||
return &mut this._at[this._left];
|
||||
}
|
||||
|
||||
#! Lends an iterator that reads the elements the slice covers.
|
||||
#! @param this The slice to walk.
|
||||
#! @returns The iterator, which refers into whatever holds the elements.
|
||||
pub def slice<T>::iter(&this): span<T>::iterator {
|
||||
return this.span.iter();
|
||||
}
|
||||
|
||||
#! Lends a mutator that writes the elements the slice covers where they are.
|
||||
#! @param this The slice to walk.
|
||||
#! @returns The mutator, which refers into whatever holds the elements.
|
||||
pub def slice<T>::iter(&mut this): slice<T>::mutator {
|
||||
return slice::<T>::mutator { _at = this._dat, _left = this._len };
|
||||
}
|
||||
|
||||
#! An iterator that reads the elements the slice covers, as `iter` lends.
|
||||
#! @param this The slice to walk.
|
||||
#! @returns The iterator, which refers into whatever holds the elements.
|
||||
@inline
|
||||
pub val slice<T>::iterator: span<T>::iterator {
|
||||
get => this.span.iter();
|
||||
}
|
||||
|
||||
#! A mutator that writes the elements the slice covers where they are, read of
|
||||
#! a slice that can be written.
|
||||
#! @param this The slice to walk.
|
||||
#! @returns The mutator, which refers into whatever holds the elements.
|
||||
@inline
|
||||
pub val slice<T>::mutator: slice<T>::mutator {
|
||||
get mut => this.iter();
|
||||
}
|
||||
|
||||
#! Narrows the view to a run of the elements it already covers.
|
||||
#! @param this The slice to narrow.
|
||||
#! @param from The index the narrower view starts at, from `0` to `length`.
|
||||
#! @param length The number of elements it covers.
|
||||
#! @returns Maybe the narrower view if this one covers all of it; otherwise,
|
||||
#! `nothing`.
|
||||
pub def slice<T>::sub(&this, from: u64, length: u64): maybe<slice<T>> {
|
||||
if from > this._len || length > this._len - from {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
return length == 0
|
||||
? slice::<T>::blank()
|
||||
: slice::<T>::over(this._dat + from, length);
|
||||
}
|
||||
|
||||
#! Compares one view to another for equality.
|
||||
#! @param this The slice to compare against.
|
||||
#! @param other The slice to compare with.
|
||||
#! @returns Whether both cover the same number of equal elements, in the same
|
||||
#! order, which is what comparing the spans they lend answers.
|
||||
pub def slice<T>::equals(&this, other: &slice<T>): bool {
|
||||
val mine := this.span;
|
||||
val yours := other.span;
|
||||
return mine.equals(&yours);
|
||||
}
|
||||
|
||||
#! Hashes the view provided.
|
||||
#! @param this The slice to hash.
|
||||
#! @returns The hash code of the view, which it shares with the span it lends.
|
||||
pub def slice<T>::hash(&this): u64 {
|
||||
return this.span.hash();
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
#! @file sort.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the sorts of slices and vectors: `sort`, by the order `<` gives, and
|
||||
#! `sort_by`, by a function saying whether one element comes before another.
|
||||
#! Both are stable, keeping elements neither comes before in the order they were
|
||||
#! in, so what is sorted comes out the same however many times it is sorted.
|
||||
module core;
|
||||
|
||||
|
||||
#! Puts the elements in order, least first, by the order `<` gives.
|
||||
#! @param this The slice to sort, whose elements are `ordered`.
|
||||
#! @remarks The sort is stable: elements equal to each other keep the order they
|
||||
#! were in. Runs of a few are sorted by insertion and then merged, which
|
||||
#! takes memory for as many elements again while it sorts. Elements
|
||||
#! are moved byte for byte, so nothing is closed or copied.
|
||||
pub def slice<T>::sort(&mut this): void {
|
||||
sort_elements::<T, natural_order<T>>(this._dat, this._len, &natural_order::<T> {});
|
||||
}
|
||||
|
||||
#! Puts the elements in an order a function gives.
|
||||
#! @param this The slice to sort.
|
||||
#! @param before Whether one element comes before another, which holds of no
|
||||
#! element and itself, as `<` does.
|
||||
#! @remarks The sort is stable, as `sort` is: elements neither comes before keep
|
||||
#! the order they were in.
|
||||
pub def slice<T>::sort_by(&mut this, before: def(&T, &T): bool): void {
|
||||
sort_elements::<T, given_order<T>>(this._dat, this._len, &given_order::<T> { before_of = before });
|
||||
}
|
||||
|
||||
#! Puts the elements in order, least first, by the order `<` gives.
|
||||
#! @param this The vector to sort, whose elements are `ordered`.
|
||||
#! @remarks The sort is stable, as a slice's `sort` is.
|
||||
pub def vector<T>::sort(&mut this): void {
|
||||
var whole := this.slice;
|
||||
whole.sort();
|
||||
}
|
||||
|
||||
#! Puts the elements in an order a function gives.
|
||||
#! @param this The vector to sort.
|
||||
#! @param before Whether one element comes before another, which holds of no
|
||||
#! element and itself, as `<` does.
|
||||
#! @remarks The sort is stable, as a slice's `sort_by` is.
|
||||
pub def vector<T>::sort_by(&mut this, before: def(&T, &T): bool): void {
|
||||
var whole := this.slice;
|
||||
whole.sort_by(before);
|
||||
}
|
||||
|
||||
# What a sort orders elements by: whether one comes before another.
|
||||
trait sort_order<T> {
|
||||
def before(&this, first: &T, second: &T): bool;
|
||||
}
|
||||
|
||||
# The order `<` gives.
|
||||
struct natural_order<T> : sort_order<T> {}
|
||||
|
||||
def natural_order<T>::before(&this, first: &T, second: &T): bool {
|
||||
if const !(T is ordered) {
|
||||
compile_error("`sort` puts elements in the order `<` gives, so they are `ordered`. `sort_by` takes an order of its own.");
|
||||
}
|
||||
return first < second;
|
||||
}
|
||||
|
||||
# The order a function gives.
|
||||
struct given_order<T> : sort_order<T> {
|
||||
var before_of: def(&T, &T): bool;
|
||||
}
|
||||
|
||||
def given_order<T>::before(&this, first: &T, second: &T): bool {
|
||||
return this.before_of(first, second);
|
||||
}
|
||||
|
||||
# How many elements a run sorted by insertion holds, before runs are merged.
|
||||
const sort_run: u64 = 16;
|
||||
|
||||
# Sorts elements in place, stably: runs of a few by insertion, then each pair of
|
||||
# runs merged, back and forth between the elements and as many slots again.
|
||||
def sort_elements<T, O>(data: *mut T, count: u64, order: &O): void where O: sort_order<T> {
|
||||
return if count < 2;
|
||||
|
||||
var at: u64 = 0;
|
||||
while at < count {
|
||||
insert_sorted::<T, O>(data + at, count - at < sort_run ? count - at : sort_run, order);
|
||||
at += sort_run;
|
||||
}
|
||||
return if count <= sort_run;
|
||||
|
||||
# The spare slots hold the elements a while, so they are cleared where the
|
||||
# elements close, as `acquire` clears them.
|
||||
val spare := acquire::<T>(nothing {}, count);
|
||||
var from := data;
|
||||
var to := spare;
|
||||
var width := sort_run;
|
||||
while width < count {
|
||||
var low: u64 = 0;
|
||||
while low < count {
|
||||
val middle := low + width < count ? low + width : count;
|
||||
val high := low + 2 * width < count ? low + 2 * width : count;
|
||||
merge_runs::<T, O>(from, low, middle, high, to, order);
|
||||
low = high;
|
||||
}
|
||||
val swap := from;
|
||||
from = to;
|
||||
to = swap;
|
||||
width *= 2;
|
||||
}
|
||||
|
||||
if from != data {
|
||||
move_elements::<T>(data, from, count);
|
||||
}
|
||||
dispose::<T>(nothing {}, spare, count);
|
||||
}
|
||||
|
||||
# Sorts a few elements in place by insertion, which keeps equal ones in order.
|
||||
# Where each goes is found while it is still in its place, so the order is only
|
||||
# asked about elements in the block: one held aside in a local would be put on
|
||||
# the heap each time, where the order is a function's.
|
||||
def insert_sorted<T, O>(data: *mut T, count: u64, order: &O): void where O: sort_order<T> {
|
||||
if const T is closeable {
|
||||
# What closes is held aside byte for byte, in a slot of its own, so nothing is
|
||||
# closed or copied as it moves.
|
||||
val held := acquire::<T>(nothing {}, 1);
|
||||
for i in 1..count {
|
||||
val j := insertion_place::<T, O>(data, i, order);
|
||||
continue if j == i;
|
||||
move_elements::<T>(held, data + i, 1);
|
||||
var k := i;
|
||||
while k > j {
|
||||
move_elements::<T>(data + k, data + k - 1, 1);
|
||||
k--;
|
||||
}
|
||||
move_elements::<T>(data + j, held, 1);
|
||||
}
|
||||
dispose::<T>(nothing {}, held, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
for i in 1..count {
|
||||
val j := insertion_place::<T, O>(data, i, order);
|
||||
continue if j == i;
|
||||
val held: T = data[i];
|
||||
var k := i;
|
||||
while k > j {
|
||||
data[k] = data[k - 1];
|
||||
k--;
|
||||
}
|
||||
data[j] = held;
|
||||
}
|
||||
}
|
||||
|
||||
# Where an element goes among those before it, which are in order: after the
|
||||
# last it does not come before.
|
||||
def insertion_place<T, O>(data: *mut T, at: u64, order: &O): u64 where O: sort_order<T> {
|
||||
var j := at;
|
||||
while j > 0 && order.before(&data[at], &data[j - 1]) {
|
||||
j--;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
# Merges two runs next to each other, each in order, into the same places of
|
||||
# another block, taking from the first where neither comes before the other.
|
||||
def merge_runs<T, O>(from: *mut T, low: u64, middle: u64, high: u64, to: *mut T, order: &O): void where O: sort_order<T> {
|
||||
var left := low;
|
||||
var right := middle;
|
||||
var out := low;
|
||||
while left < middle && right < high {
|
||||
if order.before(&from[right], &from[left]) {
|
||||
move_elements::<T>(to + out, from + right, 1);
|
||||
right++;
|
||||
} else {
|
||||
move_elements::<T>(to + out, from + left, 1);
|
||||
left++;
|
||||
}
|
||||
out++;
|
||||
}
|
||||
|
||||
if left < middle {
|
||||
move_elements::<T>(to + out, from + left, middle - left);
|
||||
out += middle - left;
|
||||
}
|
||||
if right < high {
|
||||
move_elements::<T>(to + out, from + right, high - right);
|
||||
}
|
||||
}
|
||||
|
||||
# Moves elements byte for byte, which neither closes what they land on nor copies
|
||||
# what they hold, as a sort only puts them in other places.
|
||||
def move_elements<T>(to: *mut T, from: *mut T, count: u64): void {
|
||||
if const !(T is closeable) {
|
||||
for i in 0..count {
|
||||
to[i] = from[i];
|
||||
}
|
||||
return;
|
||||
}
|
||||
memcpy(to as *mut u8, from as *u8, bytes_of::<T>(count));
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
#! @file span.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the methods of `span`, a read-only view over elements that something
|
||||
#! else holds, which read and narrow such a view. The writable counterpart is
|
||||
#! `slice<T>`, which lends a span of itself.
|
||||
#!
|
||||
#! `span` is among the types the syntax makes, which the compiler declares
|
||||
#! itself, as `a[:]` makes one: where the elements begin, and how many there
|
||||
#! are. A span owns nothing and writes nothing. It is not `owning`, and closing
|
||||
#! whatever holds the elements leaves the span pointing at memory that is no
|
||||
#! longer there, the same way a raw pointer does, so keep a span no longer than
|
||||
#! the thing it views. A view only reads, so it can be taken of anything,
|
||||
#! including memory that cannot be written such as the text of a literal.
|
||||
module core;
|
||||
|
||||
|
||||
#! The number of elements the view covers.
|
||||
#! @param this The span to measure.
|
||||
#! @returns How many elements it reads, starting at `data`.
|
||||
@inline
|
||||
pub val span<T>::length: u64 {
|
||||
get => this._len;
|
||||
}
|
||||
|
||||
#! The first element the view covers, which is `null` for an empty view.
|
||||
#! @param this The span to read the address of.
|
||||
#! @returns Where the elements begin.
|
||||
@inline
|
||||
pub val span<T>::data: *T {
|
||||
get => this._dat;
|
||||
}
|
||||
|
||||
#! Makes a view over a run of elements.
|
||||
#! @param data The first element, or `null` for a view over nothing.
|
||||
#! @param length The number of elements the view covers.
|
||||
#! @returns The view, which covers nothing where `data` is `null`.
|
||||
#! @remarks A fixed array holds its elements where it stands, so a view over one
|
||||
#! is `array[0:N]`, or `span::<T>::over((&array) as *T, N)` written
|
||||
#! out.
|
||||
pub def span<T>::over(data: *T, length: u64): span<T> {
|
||||
return data == null
|
||||
? span { _dat = null, _len = 0 }
|
||||
: span { _dat = data, _len = length };
|
||||
}
|
||||
|
||||
#! Makes a view over nothing, which is the zero value of a span.
|
||||
#! @returns A view of no elements.
|
||||
pub def span<T>::blank(): span<T> {
|
||||
return span { _dat = null, _len = 0 };
|
||||
}
|
||||
|
||||
#! Whether the view covers no elements.
|
||||
#! @param this The span to test.
|
||||
#! @returns Whether its length is zero.
|
||||
@inline
|
||||
pub val span<T>::empty: bool {
|
||||
get => this._len == 0;
|
||||
}
|
||||
|
||||
|
||||
#! Reads the element at an index, which `span[index]` does without calling it.
|
||||
#! @param this The span to read.
|
||||
#! @param index The index of the element, below `length`.
|
||||
#! @returns The element, which refers into whatever holds the elements.
|
||||
#! @remarks It is what makes a span `indexable`, so generic code bounded by that
|
||||
#! trait reads a view as it reads any other container. An index past
|
||||
#! the end stops a checked program, as `span[index]` does.
|
||||
pub def span<T>::at(&this, index: u64): &T {
|
||||
# Indexed as a view, it is checked as `span[index]` is, which the compiler does
|
||||
# itself rather than calling this.
|
||||
val whole: span<T> = this;
|
||||
return &whole[index];
|
||||
}
|
||||
|
||||
#! Lends a view of some of the same elements, as `spannable` asks, which
|
||||
#! `span[start:count]` is without calling it.
|
||||
#! @param other The span to lend.
|
||||
#! @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 span covering those elements, which is the span itself where it
|
||||
#! covers all of them.
|
||||
#! @remarks A start or count past the last element stops a checked program, as
|
||||
#! `span[start:count]` does.
|
||||
pub def span<T>::span_of(other: &span<T>, start: u64 = 0, count: u64 = ~0u): span<T> {
|
||||
val whole: span<T> = other;
|
||||
return count == ~0u ? whole[start:] : whole[start:count];
|
||||
}
|
||||
|
||||
#! A view of the same elements, which is the span itself.
|
||||
#! @param this The span to lend.
|
||||
#! @returns A copy of the span, covering the same elements.
|
||||
@inline
|
||||
pub val span<T>::span: span<T> {
|
||||
get => this;
|
||||
}
|
||||
|
||||
#! Walks the elements a view covers, giving a reference to each in turn, which
|
||||
#! is what `iter` lends and `for` walks.
|
||||
pub struct span<T>::iterator : sized_iterator<&T>, backward_iterator<&T> {
|
||||
var _at: *T;
|
||||
var _left: u64;
|
||||
}
|
||||
|
||||
#! Gives the next element the view covers.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
|
||||
pub def span<T>::iterator::next(&mut this): maybe<&T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
val here := this._at;
|
||||
this._at = here + 1;
|
||||
this._left = this._left - 1;
|
||||
# Reached as the one element of a view, which is never over null and whose
|
||||
# index is known, so reaching it checks nothing.
|
||||
return &span::<T> { _dat = here, _len = 1 }[0];
|
||||
}
|
||||
|
||||
#! How many elements the iterator has left to give.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def span<T>::iterator::remaining(&this): u64 {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
#! Gives the last element the iterator has left, from the far end of the view.
|
||||
#! @param this The iterator to advance from its far end.
|
||||
#! @returns Maybe a reference to the element; otherwise, `nothing`.
|
||||
pub def span<T>::iterator::next_back(&mut this): maybe<&T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
this._left = this._left - 1;
|
||||
return &span::<T> { _dat = this._at + this._left, _len = 1 }[0];
|
||||
}
|
||||
|
||||
#! Lends an iterator over the elements the view covers, which `for` walks.
|
||||
#! @param this The span to walk.
|
||||
#! @returns The iterator, which refers into whatever holds the elements.
|
||||
pub def span<T>::iter(&this): span<T>::iterator {
|
||||
return span::<T>::iterator { _at = this._dat, _left = this._len };
|
||||
}
|
||||
|
||||
#! An iterator over the elements the view covers, as `iter` lends.
|
||||
#! @param this The span to walk.
|
||||
#! @returns The iterator, which refers into whatever holds the elements.
|
||||
@inline
|
||||
pub val span<T>::iterator: span<T>::iterator {
|
||||
get => this.iter();
|
||||
}
|
||||
|
||||
#! Gets the element at an index, if the view covers one there.
|
||||
#! @param this The span to read.
|
||||
#! @param index The index of the element, below `length`.
|
||||
#! @returns Maybe the element if the index is one it covers; otherwise,
|
||||
#! `nothing`.
|
||||
#! @remarks What it gives refers into whatever holds the elements, so it is only
|
||||
#! good for as long as the view is.
|
||||
pub def span<T>::get(&this, index: u64): maybe<&T> {
|
||||
# Reached as the view's element, whose check the test answers.
|
||||
return index < this._len
|
||||
? &span::<T> { _dat = this._dat, _len = this._len }[index]
|
||||
: nothing {};
|
||||
}
|
||||
|
||||
#! The first element the view covers.
|
||||
#! @param this The span to read.
|
||||
#! @returns Maybe the first element; otherwise, `nothing` for an empty view.
|
||||
pub val span<T>::first: maybe<&T> {
|
||||
get => this.get(0);
|
||||
}
|
||||
|
||||
#! The last element the view covers.
|
||||
#! @param this The span to read.
|
||||
#! @returns Maybe the last element; otherwise, `nothing` for an empty view.
|
||||
pub val span<T>::last: maybe<&T> {
|
||||
get => this._len == 0 ? nothing {} : this.get(this._len - 1);
|
||||
}
|
||||
|
||||
#! Narrows the view to a run of the elements it already covers.
|
||||
#! @param this The span to narrow.
|
||||
#! @param from The index the narrower view starts at, from `0` to `length`.
|
||||
#! @param length The number of elements it covers.
|
||||
#! @returns Maybe the narrower view if this one covers all of it; otherwise,
|
||||
#! `nothing`.
|
||||
pub def span<T>::sub(&this, from: u64, length: u64): maybe<span<T>> {
|
||||
if from > this._len || length > this._len - from {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
return length == 0
|
||||
? span::<T>::blank()
|
||||
: span::<T>::over(this._dat + from, length);
|
||||
}
|
||||
|
||||
#! Finds where the view first covers an element equal to the one given.
|
||||
#! @param this The span to search.
|
||||
#! @param elem The element to look for.
|
||||
#! @returns Maybe the index of the first equal element; otherwise, `nothing`.
|
||||
#! @remarks Elements are compared with `equals`, so they are `equatable`. Bytes,
|
||||
#! as text is, are searched eight or sixteen at a time.
|
||||
pub def span<T>::index_of(&this, elem: &T): maybe<u64> {
|
||||
if const T is integer && size_of::<T>() == 1 {
|
||||
val at := find_byte(this._dat as *u8, 0, this._len, *(elem as *u8));
|
||||
return nothing {} if at == this._len;
|
||||
return at;
|
||||
}
|
||||
|
||||
for index in 0..this._len {
|
||||
if equals::<T>(&this._dat[index], elem) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Finds where the view last covers an element equal to the one given.
|
||||
#! @param this The span to search.
|
||||
#! @param elem The element to look for.
|
||||
#! @returns Maybe the index of the last equal element; otherwise, `nothing`.
|
||||
#! @remarks Elements are compared with `equals`, so they are `equatable`. Bytes,
|
||||
#! as text is, are searched eight at a time.
|
||||
pub def span<T>::last_index_of(&this, elem: &T): maybe<u64> {
|
||||
if const T is integer && size_of::<T>() == 1 {
|
||||
val at := find_last_byte(this._dat as *u8, 0, this._len, *(elem as *u8));
|
||||
return nothing {} if at == this._len;
|
||||
return at;
|
||||
}
|
||||
|
||||
var index := this._len;
|
||||
while index > 0 {
|
||||
index--;
|
||||
if equals::<T>(&this._dat[index], elem) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Counts the elements of the view equal to the one given.
|
||||
#! @param this The span to search.
|
||||
#! @param elem The element to count.
|
||||
#! @returns How many equal it.
|
||||
#! @remarks Elements are compared with `equals`, so they are `equatable`. Bytes,
|
||||
#! as text is, are counted eight at a time, as the lines of text are
|
||||
#! by counting `'\n'`.
|
||||
pub def span<T>::count_of(&this, elem: &T): u64 {
|
||||
if const T is integer && size_of::<T>() == 1 {
|
||||
return count_byte(this._dat as *u8, 0, this._len, *(elem as *u8));
|
||||
}
|
||||
|
||||
var count: u64 = 0;
|
||||
for index in 0..this._len {
|
||||
if equals::<T>(&this._dat[index], elem) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
#! Tells whether the view covers an element equal to the one given.
|
||||
#! @param this The span to search.
|
||||
#! @param elem The element to look for.
|
||||
#! @returns Whether any element equals it.
|
||||
pub def span<T>::contains(&this, elem: &T): bool {
|
||||
return this.index_of(elem) is some;
|
||||
}
|
||||
|
||||
#! Finds where a value goes among elements kept in order: the first element that
|
||||
#! is not less than it.
|
||||
#! @param this The span to search, whose elements are in the order `<` gives.
|
||||
#! @param value The value to look for.
|
||||
#! @returns The index of the first element not less than the value, or the
|
||||
#! length where every element is less.
|
||||
#! @remarks The elements are `ordered`, and halved until one is found, so a view
|
||||
#! out of order gives an index that means nothing.
|
||||
pub def span<T>::lower_bound(&this, value: &T): u64 {
|
||||
if const !(T is ordered) {
|
||||
compile_error("`lower_bound` searches by the order `<` gives, so the elements are `ordered`.");
|
||||
}
|
||||
|
||||
var low: u64 = 0;
|
||||
var high: u64 = this._len;
|
||||
while low < high {
|
||||
val middle := low + (high - low) / 2;
|
||||
if this._dat[middle] < value {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
#! Finds where a value goes after those equal to it among elements kept in
|
||||
#! order: the first element greater than it.
|
||||
#! @param this The span to search, whose elements are in the order `<` gives.
|
||||
#! @param value The value to look for.
|
||||
#! @returns The index of the first element greater than the value, or the length
|
||||
#! where none is.
|
||||
#! @remarks The elements are `ordered`, and halved until one is found, so a view
|
||||
#! out of order gives an index that means nothing.
|
||||
pub def span<T>::upper_bound(&this, value: &T): u64 {
|
||||
if const !(T is ordered) {
|
||||
compile_error("`upper_bound` searches by the order `<` gives, so the elements are `ordered`.");
|
||||
}
|
||||
|
||||
var low: u64 = 0;
|
||||
var high: u64 = this._len;
|
||||
while low < high {
|
||||
val middle := low + (high - low) / 2;
|
||||
if value < this._dat[middle] {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
#! Finds where elements a test holds of give way to those it does not, among
|
||||
#! elements kept so that every one it holds of comes first.
|
||||
#! @param this The span to search.
|
||||
#! @param held The test, which holds of the elements before the index given
|
||||
#! and of none from it on.
|
||||
#! @returns The index of the first element the test does not hold of, or the
|
||||
#! length where it holds of every one.
|
||||
#! @remarks Elements are halved until it is found, so the test is called about
|
||||
#! `log2(length)` times. It finds by a part of each element, such as an
|
||||
#! offset, where `lower_bound` finds by the whole.
|
||||
pub def span<T>::partition_point(&this, held: def(&T): bool): u64 {
|
||||
var low: u64 = 0;
|
||||
var high: u64 = this._len;
|
||||
while low < high {
|
||||
val middle := low + (high - low) / 2;
|
||||
if held(&this._dat[middle]) {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
#! Compares one view to another for equality.
|
||||
#! @param this The span to compare against.
|
||||
#! @param other The span to compare with.
|
||||
#! @returns Whether both cover the same number of equal elements, in the same
|
||||
#! order. Two views of the same elements are equal, and so are two
|
||||
#! empty views.
|
||||
pub def span<T>::equals(&this, other: &span<T>): bool {
|
||||
if this._len != other._len {
|
||||
return false;
|
||||
}
|
||||
|
||||
if this._dat == other._dat || this._len == 0 {
|
||||
return true;
|
||||
}
|
||||
|
||||
# Integers are equal where their bytes are, which are compared a word at a time.
|
||||
if const T is integer {
|
||||
return memcmp(this._dat as *u8, other._dat as *u8, bytes_of::<T>(this._len)) == 0;
|
||||
}
|
||||
|
||||
for index in 0..this._len {
|
||||
if !equals::<T>(&this._dat[index], &other._dat[index]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Hashes the view provided.
|
||||
#! @param this The span to hash.
|
||||
#! @returns The hash code of the view, which spans of equal elements share.
|
||||
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
|
||||
pub def span<T>::hash(&this): u64 {
|
||||
# Integers hash as their bytes, a word at a time, which equal ones share.
|
||||
if const T is integer {
|
||||
return hash_bytes(this._dat as *u8, bytes_of::<T>(this._len));
|
||||
}
|
||||
|
||||
var code := this._len;
|
||||
for index in 0..this._len {
|
||||
code = mix(code, hash(this._dat[index]));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
#! @file string.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the methods of `string`, which owns the bytes of text it holds, and
|
||||
#! the functions that build one and give it back.
|
||||
#!
|
||||
#! `string` is among the types the syntax makes, which the compiler declares
|
||||
#! itself, since interpolation, as `$"{count} items"`, builds one. A string is
|
||||
#! `owning`, so the memory goes back where its scope ends. Text that is only read
|
||||
#! is a `strview`, which owns nothing: a literal such as `"hello"` is one, and so
|
||||
#! is what `span` gives. A string whose allocator is `nothing` holds memory from
|
||||
#! `raw_allocate`, and one made with an allocator gives its memory back to that
|
||||
#! allocator. Either way the zero value of a string holds no memory, so closing
|
||||
#! one that was never built does nothing.
|
||||
module core;
|
||||
|
||||
|
||||
#! The number of bytes the string holds.
|
||||
#! @param this The string to measure.
|
||||
#! @returns How many bytes of text it holds, which is no more than its capacity.
|
||||
pub val string::length: u64 {
|
||||
get => this._len;
|
||||
}
|
||||
|
||||
#! The number of bytes the string has room for.
|
||||
#! @param this The string to measure.
|
||||
#! @returns How many bytes it can hold before it has to grow.
|
||||
pub val string::capacity: u64 {
|
||||
get => this._cap;
|
||||
}
|
||||
|
||||
#! The allocator the string takes its memory from, or `nothing` where it takes
|
||||
#! it from `raw_allocate`, so what is made from it can take memory alike.
|
||||
#! @param this The string.
|
||||
#! @returns The allocator, or `nothing`.
|
||||
pub val string::alloc: maybe<&mut allocator> {
|
||||
get => this._alc;
|
||||
}
|
||||
|
||||
#! Whether the string holds no text.
|
||||
#! @param this The string to check.
|
||||
#! @returns Whether its length is zero.
|
||||
pub val string::empty: bool {
|
||||
get => this._len == 0;
|
||||
}
|
||||
|
||||
#! Whether the string has no room left, so the next byte added makes it grow.
|
||||
#! @param this The string to check.
|
||||
#! @returns Whether its length is its capacity.
|
||||
pub val string::full: bool {
|
||||
get => this._len == this._cap;
|
||||
}
|
||||
|
||||
#! Makes a string that holds no text yet.
|
||||
#! @param alloc An optional allocator for the string to take memory from. A
|
||||
#! string given none takes it from `raw_allocate`.
|
||||
#! @returns The empty string, which holds no memory until it is written to.
|
||||
pub def string::new(alloc: maybe<&mut allocator>): string {
|
||||
return string { _alc = alloc, _dat = null, _len = 0, _cap = 0 };
|
||||
}
|
||||
|
||||
#! Makes a string holding a copy of the text given.
|
||||
#! @param text The text to copy, such as a literal or a view of one.
|
||||
#! @param alloc An optional allocator for the string to take memory from.
|
||||
#! @returns The string, which holds no text where there was no memory for it.
|
||||
#! @remarks An allocator that gives no memory stops the program.
|
||||
pub def string::from(text: strview, alloc: maybe<&mut allocator>): string {
|
||||
var made := string::new(alloc);
|
||||
made.append(text);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Views some of the text a string holds, without copying it, as `spannable`
|
||||
#! asks, which `s[start:count]` calls.
|
||||
#! @param other The string to view.
|
||||
#! @param start The index of the first byte viewed.
|
||||
#! @param count How many bytes are viewed, or `~0u` for every one after the
|
||||
#! start.
|
||||
#! @returns A view of those bytes, which is only good until the string grows,
|
||||
#! shrinks, or closes.
|
||||
#! @remarks A start or count past the last byte stops a checked program.
|
||||
pub def string::span_of(other: &string, start: u64 = 0, count: u64 = ~0u): strview {
|
||||
val whole := strview::over(other._dat as *u8, other._len);
|
||||
return count == ~0u ? whole[start:] : whole[start:count];
|
||||
}
|
||||
|
||||
#! Lends a writable view of some of the bytes a string holds, without copying
|
||||
#! them, as `sliceable` asks, which `s[start:count]` calls where `s` can be
|
||||
#! written.
|
||||
#! @param other The string to view, which can be written.
|
||||
#! @param start The index of the first byte viewed.
|
||||
#! @param count How many bytes are viewed, or `~0u` for every one after the
|
||||
#! start.
|
||||
#! @returns A view of those bytes, which writes them where they are, and is only
|
||||
#! good until the string grows, shrinks, or closes.
|
||||
#! @remarks A start or count past the last byte stops a checked program.
|
||||
pub def string::slice_of(other: &mut string, start: u64 = 0, count: u64 = ~0u): slice<u8> {
|
||||
val whole := slice::<u8>::over(other._dat, other._len);
|
||||
return count == ~0u ? whole[start:] : whole[start:count];
|
||||
}
|
||||
|
||||
#! A view of the text the string holds, which copies nothing.
|
||||
#! @param this The string to view.
|
||||
#! @returns A view of its bytes, which is only good until the string grows,
|
||||
#! shrinks, or closes.
|
||||
@inline
|
||||
pub val string::span: strview {
|
||||
get => strview::over(this._dat as *u8, this._len);
|
||||
}
|
||||
|
||||
#! A writable view of the bytes the string holds, read of a string that can be
|
||||
#! written.
|
||||
#! @param this The string to view.
|
||||
#! @returns A view of its bytes, which writes them where they are, and is only
|
||||
#! good until the string grows, shrinks, or closes.
|
||||
@inline
|
||||
pub val string::slice: slice<u8> {
|
||||
get mut => slice::<u8>::over(this._dat, this._len);
|
||||
}
|
||||
|
||||
#! Reads the byte at an index, which `s[index]` calls.
|
||||
#! @param this The string to read.
|
||||
#! @param index The index of the byte, below `length`, past which a checked
|
||||
#! program stops.
|
||||
#! @returns The byte, which is only good until the string grows, shrinks, or
|
||||
#! closes.
|
||||
pub def string::at(&this, index: u64): &u8 {
|
||||
# Indexed as a view of the bytes, it is checked as a view's index is.
|
||||
return &span::<u8> { _dat = this._dat, _len = this._len }[index];
|
||||
}
|
||||
|
||||
#! Reaches the byte at an index to write it, which `s[index] = b` calls.
|
||||
#! @param this The string to write.
|
||||
#! @param index The index of the byte, below `length`, past which a checked
|
||||
#! program stops.
|
||||
#! @returns The byte, which is only good until the string grows, shrinks, or
|
||||
#! closes.
|
||||
pub def string::at(&mut this, index: u64): &mut u8 {
|
||||
return &mut slice::<u8> { _dat = this._dat, _len = this._len }[index];
|
||||
}
|
||||
|
||||
#! Gets the byte at an index, if the string holds one there, for an index that
|
||||
#! may be past the end in a program that is right.
|
||||
#! @param this The string to read.
|
||||
#! @param index The index of the byte.
|
||||
#! @returns Maybe the byte, which is only good until the string grows, shrinks,
|
||||
#! or closes; otherwise, `nothing`.
|
||||
pub def string::get(&this, index: u64): maybe<&u8> {
|
||||
# Reached as a view's byte, whose check the test answers.
|
||||
return index < this._len
|
||||
? &span::<u8> { _dat = this._dat, _len = this._len }[index]
|
||||
: nothing {};
|
||||
}
|
||||
|
||||
#! Gets the byte at an index to write it, if the string holds one there.
|
||||
#! @param this The string to write.
|
||||
#! @param index The index of the byte.
|
||||
#! @returns Maybe the byte, which is only good until the string grows, shrinks,
|
||||
#! or closes; otherwise, `nothing`.
|
||||
pub def string::get(&mut this, index: u64): maybe<&mut u8> {
|
||||
return index < this._len
|
||||
? &mut slice::<u8> { _dat = this._dat, _len = this._len }[index]
|
||||
: nothing {};
|
||||
}
|
||||
|
||||
#! Makes room for at least a number of bytes, keeping the text it holds.
|
||||
#! @param this The string to make room in.
|
||||
#! @param capacity The number of bytes it should have room for.
|
||||
#! @remarks A string already that large is left as it is, and an allocator that
|
||||
#! gives no more memory stops the program.
|
||||
pub def string::reserve(&mut this, capacity: u64): void {
|
||||
if capacity <= this._cap {
|
||||
return;
|
||||
}
|
||||
|
||||
this.recapacity(capacity);
|
||||
}
|
||||
|
||||
#! Makes the string hold a number of bytes, adding zero bytes after the last or
|
||||
#! removing those past it, as a reader filling the room it made does.
|
||||
#! @param this The string to resize.
|
||||
#! @param length How many bytes it holds after.
|
||||
#! @remarks The memory is kept where it shrinks, and an allocator that gives no
|
||||
#! more memory stops the program where it grows.
|
||||
pub def string::resize(&mut this, length: u64): void {
|
||||
if length > this._cap {
|
||||
this.grow(length);
|
||||
}
|
||||
if length > this._len {
|
||||
memset(this._dat + this._len, 0, length - this._len);
|
||||
}
|
||||
this._len = length;
|
||||
}
|
||||
|
||||
#! Adds a byte after the last.
|
||||
#! @param this The string to append to.
|
||||
#! @param byte The byte to append.
|
||||
#! @remarks An allocator that gives no more memory stops the program.
|
||||
pub def string::push(&mut this, byte: u8): void {
|
||||
if this._len == this._cap {
|
||||
this.grow(this._len + 1);
|
||||
}
|
||||
|
||||
this._dat[this._len] = byte;
|
||||
this._len++;
|
||||
}
|
||||
|
||||
#! Adds the bytes of some text after the last.
|
||||
#! @param this The string to append to.
|
||||
#! @param text The text to append, which may view this string's own bytes.
|
||||
#! @remarks An allocator that gives no more memory stops the program.
|
||||
pub def string::append(&mut this, text: strview): void {
|
||||
val count := text.length;
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
if this._len + count > this._cap {
|
||||
this.grow(this._len + count);
|
||||
}
|
||||
|
||||
memcpy(this._dat + this._len, text.data, count);
|
||||
this._len += count;
|
||||
}
|
||||
|
||||
#! Removes every byte, keeping the memory the string holds them in.
|
||||
#! @param this The string to empty.
|
||||
pub def string::clear(&mut this): void {
|
||||
this._len = 0;
|
||||
}
|
||||
|
||||
#! Gives back the memory the string holds, leaving it empty.
|
||||
#! @param this The string to close out.
|
||||
pub def string::close(&mut this): void {
|
||||
if this._dat == null {
|
||||
return;
|
||||
}
|
||||
|
||||
match this._alc {
|
||||
some(owner) => owner.dispose(this._dat, this._cap);
|
||||
none => raw_release(this._dat);
|
||||
}
|
||||
|
||||
this._dat = null;
|
||||
this._len = 0;
|
||||
this._cap = 0;
|
||||
}
|
||||
|
||||
#! Compares one string to another for equality.
|
||||
#! @param this The string to compare against.
|
||||
#! @param other The string to compare with.
|
||||
#! @returns Whether both hold the same bytes, in the same order.
|
||||
pub def string::equals(&this, other: &string): bool {
|
||||
return this.span.equals(&other.span);
|
||||
}
|
||||
|
||||
#! Compares one string with another, by their bytes and then by their length.
|
||||
#! @param this The string to compare against.
|
||||
#! @param other The string to compare with.
|
||||
#! @retval -1 Where this string orders before the other.
|
||||
#! @retval 0 Where they hold the same bytes.
|
||||
#! @retval 1 Where this string orders after the other.
|
||||
pub def string::compare(&this, other: &string): i64 {
|
||||
return this.span.compare(other.span);
|
||||
}
|
||||
|
||||
#! What `iter(&this)` lends, which reads the bytes where the string holds them.
|
||||
pub type string::iterator = span<u8>::iterator;
|
||||
|
||||
#! What `iter(&mut this)` lends, which writes the bytes where the string holds
|
||||
#! them.
|
||||
pub type string::mutator = slice<u8>::mutator;
|
||||
|
||||
#! Lends an iterator that reads the bytes, in order, which `for byte in s`
|
||||
#! walks.
|
||||
#! @param this The string to walk.
|
||||
#! @returns The iterator, which is only good until the string grows, shrinks, or
|
||||
#! closes.
|
||||
pub def string::iter(&this): span<u8>::iterator {
|
||||
return this.span.iter();
|
||||
}
|
||||
|
||||
#! Lends a mutator that writes the bytes where they are, which `for &mut byte
|
||||
#! in s` walks.
|
||||
#! @param this The string to walk.
|
||||
#! @returns The mutator, which is only good until the string grows, shrinks, or
|
||||
#! closes.
|
||||
pub def string::iter(&mut this): slice<u8>::mutator {
|
||||
var whole := this.slice;
|
||||
return whole.iter();
|
||||
}
|
||||
|
||||
#! An iterator that reads the bytes, in order, as `iter` lends.
|
||||
#! @param this The string to walk.
|
||||
#! @returns The iterator, which is only good until the string grows, shrinks, or
|
||||
#! closes.
|
||||
@inline
|
||||
pub val string::iterator: span<u8>::iterator {
|
||||
get => this.span.iter();
|
||||
}
|
||||
|
||||
#! A mutator that writes the bytes where they are, read of a string that can be
|
||||
#! written.
|
||||
#! @param this The string to walk.
|
||||
#! @returns The mutator, which is only good until the string grows, shrinks, or
|
||||
#! closes.
|
||||
@inline
|
||||
pub val string::mutator: slice<u8>::mutator {
|
||||
get mut => this.iter();
|
||||
}
|
||||
|
||||
#! Hashes the string provided.
|
||||
#! @param this The string to hash.
|
||||
#! @returns The hash code of the text it holds, which equal strings share.
|
||||
pub def string::hash(&this): u64 {
|
||||
return this.span.hash();
|
||||
}
|
||||
|
||||
#! Builds a string holding the same text as another, with its allocator.
|
||||
#! @param other The string to copy text from.
|
||||
#! @returns The copy, which owns memory of its own.
|
||||
pub def string::copy_of(other: &string): string {
|
||||
return string::from(other.span, other._alc);
|
||||
}
|
||||
|
||||
#! Builds a string holding the text of another, leaving the other empty.
|
||||
#! @param other The string to move text from, which holds nothing after.
|
||||
#! @returns The moved string, which takes the memory and the 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 string::move_of(other: &mut string): string {
|
||||
var made: string = string {
|
||||
_alc = other._alc,
|
||||
_dat = other._dat,
|
||||
_len = other._len,
|
||||
_cap = other._cap
|
||||
};
|
||||
|
||||
other._dat = null;
|
||||
other._len = 0;
|
||||
other._cap = 0;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Views a run of the text, from an index for a number of bytes.
|
||||
#! @param this The string to narrow.
|
||||
#! @param start Where the narrower view begins, from `0` to `length`.
|
||||
#! @param count How many bytes it covers, cut short by the end of the text.
|
||||
#! @returns A view of that run, which is empty where it begins past the end, and
|
||||
#! is only good until the string grows, shrinks, or closes.
|
||||
pub def string::substr(&this, start: u64, count: u64): strview {
|
||||
return this.span.substr(start, count);
|
||||
}
|
||||
|
||||
#! Tells whether the text begins with some other text.
|
||||
#! @param this The string to read.
|
||||
#! @param prefix The text to look for at its beginning.
|
||||
#! @returns Whether it begins with the prefix, which empty text always does.
|
||||
pub def string::starts_with(&this, prefix: strview): bool {
|
||||
return this.span.starts_with(prefix);
|
||||
}
|
||||
|
||||
#! Tells whether the text ends with some other text.
|
||||
#! @param this The string to read.
|
||||
#! @param suffix The text to look for at its end.
|
||||
#! @returns Whether it ends with the suffix, which empty text always does.
|
||||
pub def string::ends_with(&this, suffix: strview): bool {
|
||||
return this.span.ends_with(suffix);
|
||||
}
|
||||
|
||||
#! Makes a string of the text without the whitespace at its beginning.
|
||||
#! @param this The string to read.
|
||||
#! @returns A new string holding what is left, from the same allocator.
|
||||
pub def string::ltrim(&this): string {
|
||||
return string::from(this.span.ltrim(), this._alc);
|
||||
}
|
||||
|
||||
#! Makes a string of the text without the whitespace at its end.
|
||||
#! @param this The string to read.
|
||||
#! @returns A new string holding what is left, from the same allocator.
|
||||
pub def string::rtrim(&this): string {
|
||||
return string::from(this.span.rtrim(), this._alc);
|
||||
}
|
||||
|
||||
#! Makes a string of the text without the whitespace at either end.
|
||||
#! @param this The string to read.
|
||||
#! @returns A new string holding what is left, from the same allocator.
|
||||
pub def string::trim(&this): string {
|
||||
return string::from(this.span.trim(), this._alc);
|
||||
}
|
||||
|
||||
#! Compares the text with other text, by their bytes and then by their length.
|
||||
#! @param this The string to compare against.
|
||||
#! @param other The text to compare with.
|
||||
#! @retval -1 Where this string orders before the other.
|
||||
#! @retval 0 Where they hold the same bytes.
|
||||
#! @retval 1 Where this string orders after the other.
|
||||
pub def string::compare(&this, other: strview): i64 {
|
||||
return this.span.compare(other);
|
||||
}
|
||||
|
||||
#! Makes text of the string with every letter in upper case.
|
||||
#! @param this The string to read.
|
||||
#! @returns A new string holding the converted text.
|
||||
pub def string::upper(&this): string {
|
||||
return this.span.upper();
|
||||
}
|
||||
|
||||
#! Makes text of the string with every letter in lower case.
|
||||
#! @param this The string to read.
|
||||
#! @returns A new string holding the converted text.
|
||||
pub def string::lower(&this): string {
|
||||
return this.span.lower();
|
||||
}
|
||||
|
||||
#! Makes text of a width, with the string's text at its end and a byte before
|
||||
#! it.
|
||||
#! @param this The string to read.
|
||||
#! @param width How many bytes the text should hold.
|
||||
#! @param fill The byte to put before it.
|
||||
#! @returns A new string holding the padded text, which is a copy of this one
|
||||
#! where it is already that wide.
|
||||
pub def string::lpad(&this, width: u64, fill: u8): string {
|
||||
return this.span.lpad(width, fill);
|
||||
}
|
||||
|
||||
#! Makes text of a width, with the string's text at its beginning and a byte
|
||||
#! after it.
|
||||
#! @param this The string to read.
|
||||
#! @param width How many bytes the text should hold.
|
||||
#! @param fill The byte to put after it.
|
||||
#! @returns A new string holding the padded text, which is a copy of this one
|
||||
#! where it is already that wide.
|
||||
pub def string::rpad(&this, width: u64, fill: u8): string {
|
||||
return this.span.rpad(width, fill);
|
||||
}
|
||||
|
||||
# Gives the string room for more bytes than it holds, which is what it needs
|
||||
# before more are added.
|
||||
def string::grow(&mut this, wanted: u64): void {
|
||||
var capacity := this._cap == 0 ? 16u : this._cap;
|
||||
while capacity < wanted {
|
||||
capacity *= 2;
|
||||
}
|
||||
|
||||
this.recapacity(capacity);
|
||||
}
|
||||
|
||||
# Moves the bytes to memory of another size, keeping what fits. An allocator that
|
||||
# gives no memory stops the program, as `resize` does.
|
||||
def string::recapacity(&mut this, capacity: u64): void {
|
||||
if capacity == this._cap {
|
||||
return;
|
||||
}
|
||||
|
||||
if capacity == 0 {
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
|
||||
this._dat = resize::<u8>(this._alc, this._dat, this._cap, capacity);
|
||||
this._cap = capacity;
|
||||
if this._len > capacity {
|
||||
this._len = capacity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
#! @file strview.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `strview`, the view of text that is only read, and the methods of
|
||||
#! text: narrowing, splitting, finding, trimming, comparing, changing case,
|
||||
#! padding, and reading numbers.
|
||||
#!
|
||||
#! Anything that only reads text takes a `strview`, so a literal, a view of one,
|
||||
#! and the text a `string` lends are all read by the same function, since a
|
||||
#! string lends a view of itself wherever one is wanted. Anything that makes new
|
||||
#! text gives a `string`, which owns the memory it is written into and gives it
|
||||
#! back where its scope ends.
|
||||
#!
|
||||
#! `strview` is an alias of `span<u8>`, among the types the syntax makes, which
|
||||
#! the compiler declares itself, so it converts to and from one implicitly and
|
||||
#! has its methods too. The methods of text are declared on the
|
||||
#! alias because a method cannot be declared on one instance of a generic type:
|
||||
#! `def span<u8>::trim` would declare a type parameter named `u8`.
|
||||
|
||||
import core::swar;
|
||||
module core;
|
||||
|
||||
|
||||
#! Views a run of the text, from an index for a number of bytes.
|
||||
#! @param this The text to narrow.
|
||||
#! @param start Where the narrower view begins, from `0` to `length`.
|
||||
#! @param count How many bytes it covers, cut short by the end of the text.
|
||||
#! @returns A view of that run, which is empty where it begins past the end.
|
||||
@inline
|
||||
pub def strview::substr(&this, start: u64, count: u64): strview {
|
||||
if start >= this.length {
|
||||
return strview::blank();
|
||||
}
|
||||
|
||||
val left := this.length - start;
|
||||
return this.sub(start, count < left ? count : left).some;
|
||||
}
|
||||
|
||||
#! Tells whether the text begins with some other text.
|
||||
#! @param this The text to read.
|
||||
#! @param prefix The text to look for at its beginning.
|
||||
#! @returns Whether it begins with the prefix, which empty text always does.
|
||||
pub def strview::starts_with(&this, prefix: strview): bool {
|
||||
return
|
||||
this.length >= prefix.length &&
|
||||
this.substr(0, prefix.length).equals(&prefix);
|
||||
}
|
||||
|
||||
#! Tells whether the text ends with some other text.
|
||||
#! @param this The text to read.
|
||||
#! @param suffix The text to look for at its end.
|
||||
#! @returns Whether it ends with the suffix, which empty text always does.
|
||||
pub def strview::ends_with(&this, suffix: strview): bool {
|
||||
return
|
||||
this.length >= suffix.length &&
|
||||
this.substr(this.length - suffix.length, suffix.length).equals(&suffix);
|
||||
}
|
||||
|
||||
#! Finds where a run of text first begins within the text.
|
||||
#! @param this The text to search.
|
||||
#! @param text The run to look for.
|
||||
#! @returns Maybe the index where it first begins; otherwise, `nothing`. Empty
|
||||
#! text is found at 0.
|
||||
#! @remarks Its first and last bytes are looked for at once, at eight places a
|
||||
#! step, and the bytes between compared only where both are found, as
|
||||
#! Wojciech Muła's search does with vectors.
|
||||
pub def strview::find(&this, text: strview): maybe<u64> {
|
||||
val length := text.length;
|
||||
return 0 if length == 0;
|
||||
return nothing {} if length > this._len;
|
||||
return this.index_of(&text[0]) if length == 1;
|
||||
|
||||
# The places it may begin are 0 to `last`, eight at a time, then the last few
|
||||
# read without passing the end.
|
||||
val data := this._dat;
|
||||
val last := this._len - length;
|
||||
val first_byte := swar::repeat(text[0]);
|
||||
val last_byte := swar::repeat(text[length - 1]);
|
||||
var at: u64 = 0;
|
||||
while at <= last {
|
||||
val places := last + 1 - at;
|
||||
var firsts: swar::bytes8;
|
||||
var lasts: swar::bytes8;
|
||||
if places >= 8 {
|
||||
firsts = swar::load(data + at) ^ first_byte;
|
||||
lasts = swar::load(data + at + length - 1) ^ last_byte;
|
||||
} else {
|
||||
firsts = swar::load_last(data + at, places) ^ first_byte;
|
||||
lasts = swar::load_last(data + at + length - 1, places) ^ last_byte;
|
||||
}
|
||||
var found: swar::mask8 = firsts.zero() & lasts.zero() & swar::mask8::leading(places);
|
||||
while found.any() {
|
||||
val begins := at + found.first();
|
||||
return begins if memcmp(data + begins + 1, text._dat + 1, length - 2) == 0;
|
||||
found = found.rest();
|
||||
}
|
||||
at += 8;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Finds where the text first holds any of some bytes.
|
||||
#! @param this The text to search.
|
||||
#! @param bytes The bytes to look for.
|
||||
#! @returns Maybe the index of the first; otherwise, `nothing`, as for no bytes.
|
||||
#! @remarks Up to four bytes are looked for eight places a step, and more a byte
|
||||
#! at a time, through a set of the 256.
|
||||
pub def strview::find_any(&this, bytes: span<u8>): maybe<u64> {
|
||||
val count := bytes.length;
|
||||
return nothing {} if count == 0;
|
||||
val data := this._dat;
|
||||
if count <= 4 {
|
||||
# Each byte repeated, where the first stands for any not given.
|
||||
val a := swar::repeat(bytes[0]);
|
||||
val b := swar::repeat(bytes[count > 1 ? 1 : 0]);
|
||||
val c := swar::repeat(bytes[count > 2 ? 2 : 0]);
|
||||
val d := swar::repeat(bytes[count > 3 ? 3 : 0]);
|
||||
var at: u64 = 0;
|
||||
while at < this._len {
|
||||
val left := this._len - at;
|
||||
val word := left >= 8 ? swar::load(data + at) : swar::load_last(data + at, left);
|
||||
val wa: swar::bytes8 = word ^ a;
|
||||
val wb: swar::bytes8 = word ^ b;
|
||||
val wc: swar::bytes8 = word ^ c;
|
||||
val wd: swar::bytes8 = word ^ d;
|
||||
val found: swar::mask8 = (wa.zero() | wb.zero() | wc.zero() | wd.zero()) & swar::mask8::leading(left);
|
||||
return at + found.first() if found.any();
|
||||
at += 8;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
var set: u64[4] = [0, 0, 0, 0];
|
||||
for byte in bytes {
|
||||
set[(byte >> 6) as u64] |= 1u << (byte & 63) as u64;
|
||||
}
|
||||
for at in 0..this._len {
|
||||
val byte := data[at];
|
||||
return at if ((set[(byte >> 6) as u64] >> (byte & 63) as u64) & 1) != 0;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Tells whether the text is all ASCII, every byte below 128.
|
||||
#! @param this The text to check.
|
||||
#! @returns Whether it is, which empty text is.
|
||||
#! @remarks Thirty-two bytes are read a step, as four words whose high bits are
|
||||
#! gathered, then eight, then the last few.
|
||||
pub def strview::is_ascii(&this): bool {
|
||||
val data := this._dat;
|
||||
var at: u64 = 0;
|
||||
while at + 32 <= this._len {
|
||||
val high := (swar::load(data + at) | swar::load(data + at + 8) | swar::load(data + at + 16) | swar::load(data + at + 24))
|
||||
& 0x8080808080808080;
|
||||
return false if high != 0;
|
||||
at += 32;
|
||||
}
|
||||
while at + 8 <= this._len {
|
||||
return false if (swar::load(data + at) & 0x8080808080808080) != 0;
|
||||
at += 8;
|
||||
}
|
||||
return (swar::load_last(data + at, this._len - at) & 0x8080808080808080) == 0;
|
||||
}
|
||||
|
||||
#! Views the text without the whitespace at its beginning.
|
||||
#! @param this The text to read.
|
||||
#! @returns A view of what is left, which views into the same text.
|
||||
pub def strview::ltrim(&this): strview {
|
||||
var at := 0u;
|
||||
while at < this.length && this[at].is_space {
|
||||
at++;
|
||||
}
|
||||
|
||||
return this.substr(at, this.length - at);
|
||||
}
|
||||
|
||||
#! Views the text without the whitespace at its end.
|
||||
#! @param this The text to read.
|
||||
#! @returns A view of what is left, which views into the same text.
|
||||
pub def strview::rtrim(&this): strview {
|
||||
var count := this.length;
|
||||
while count > 0 && this[count - 1].is_space {
|
||||
count--;
|
||||
}
|
||||
|
||||
return this.substr(0, count);
|
||||
}
|
||||
|
||||
#! Views the text without the whitespace at either end.
|
||||
#! @param this The text to read.
|
||||
#! @returns A view of what is left, which views into the same text.
|
||||
pub def strview::trim(&this): strview {
|
||||
return this.rtrim().ltrim();
|
||||
}
|
||||
|
||||
#! Compares text with other text, by their bytes and then by their length.
|
||||
#! @param this The text to compare against.
|
||||
#! @param other The text to compare with.
|
||||
#! @retval -1 Where this text orders before the other.
|
||||
#! @retval 0 Where they hold the same bytes.
|
||||
#! @retval 1 Where this text orders after the other.
|
||||
pub def strview::compare(&this, other: strview): i64 {
|
||||
val shorter := this.length < other.length ? this.length : other.length;
|
||||
if shorter != 0 {
|
||||
val order := memcmp(this._dat, other._dat, shorter);
|
||||
return order if order != 0;
|
||||
}
|
||||
|
||||
if this.length == other.length {
|
||||
return 0;
|
||||
}
|
||||
return this.length < other.length ? -1 : 1;
|
||||
}
|
||||
|
||||
#! Makes a copy of the text with every ASCII letter in upper case.
|
||||
#! @param this The text to read.
|
||||
#! @returns A string holding the converted text.
|
||||
pub def strview::upper(&this): string {
|
||||
var made := string::from(this, nothing {});
|
||||
change_case(made._dat, made._len, true);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Makes a copy of the text with every ASCII letter in lower case.
|
||||
#! @param this The text to read.
|
||||
#! @returns A string holding the converted text.
|
||||
pub def strview::lower(&this): string {
|
||||
var made := string::from(this, nothing {});
|
||||
change_case(made._dat, made._len, false);
|
||||
return made;
|
||||
}
|
||||
|
||||
# Changes the case of the ASCII letters of bytes where they are, eight at a time,
|
||||
# the last word ending where the bytes do, over letters the words before changed,
|
||||
# which changing again leaves as they are. Fewer than eight a byte at a time.
|
||||
def change_case(data: *mut u8, length: u64, upper: bool): void {
|
||||
if length < 8 {
|
||||
for at in 0..length {
|
||||
data[at] = upper ? data[at].to_upper : data[at].to_lower;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var at: u64 = 0;
|
||||
while true {
|
||||
val word := swar::load(data + at);
|
||||
*((data + at) as *mut u64) = upper ? word.upper() : word.lower();
|
||||
break if at + 8 == length;
|
||||
at = at + 16 <= length ? at + 8 : length - 8;
|
||||
}
|
||||
}
|
||||
|
||||
#! Makes text of a width, with this text at its end and a byte repeated before
|
||||
#! it.
|
||||
#! @param this The text to read.
|
||||
#! @param width How many bytes the text should hold.
|
||||
#! @param fill The byte to put before it.
|
||||
#! @returns A string holding the padded text, which is a copy of this text where
|
||||
#! it is already that wide.
|
||||
pub def strview::lpad(&this, width: u64, fill: u8): string {
|
||||
var made := string::new(nothing {});
|
||||
made.reserve(width > this.length ? width : this.length);
|
||||
var at := this.length;
|
||||
while at < width {
|
||||
made.push(fill);
|
||||
at++;
|
||||
}
|
||||
|
||||
made.append(this);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Makes text of a width, with this text at its beginning and a byte repeated
|
||||
#! after it.
|
||||
#! @param this The text to read.
|
||||
#! @param width How many bytes the text should hold.
|
||||
#! @param fill The byte to put after it.
|
||||
#! @returns A string holding the padded text, which is a copy of this text where
|
||||
#! it is already that wide.
|
||||
pub def strview::rpad(&this, width: u64, fill: u8): string {
|
||||
var made := string::new(nothing {});
|
||||
made.reserve(width > this.length ? width : this.length);
|
||||
made.append(this);
|
||||
var at := this.length;
|
||||
while at < width {
|
||||
made.push(fill);
|
||||
at++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
|
||||
# NOTE: Extremely fragile! Should be moved somewhere else or dropped because
|
||||
# it is just storing a string. Replace with a standard error when it is
|
||||
# finally added.
|
||||
#! Explains why text could not be read as a number.
|
||||
pub struct failure {
|
||||
pub var message: string; #! What was wrong with the text.
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#! @file tuple.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `tuple`, values of any number of types kept together, each reached
|
||||
#! by its index, as `pair` keeps two, each reached by its name.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Values of any number of types kept together in order, each reached by its
|
||||
#! index, known while compiling, as `t.items[0]` or `t.at::<0>()`. What closes
|
||||
#! among them is closed where the tuple is, the last first, as fields are.
|
||||
#! @tparam Ts The types of the values.
|
||||
pub struct tuple<Ts...> {
|
||||
pub var items: Ts...; #! The values, one of each type, as a pack is used.
|
||||
}
|
||||
|
||||
#! Makes a tuple of the values given, moving those that close into it.
|
||||
#! @param items The values.
|
||||
#! @returns The tuple.
|
||||
pub def tuple<Ts...>::of(items: Ts...): tuple<Ts...> {
|
||||
return tuple { items = items };
|
||||
}
|
||||
|
||||
#! Reads the value at an index.
|
||||
#! @tparam index The index, known while compiling.
|
||||
#! @param this The tuple to read.
|
||||
#! @returns The value.
|
||||
pub def tuple<Ts...>::at<const index: u64>(&this): &Ts...[index] {
|
||||
return &this.items[index];
|
||||
}
|
||||
|
||||
#! Reaches the value at an index to write it.
|
||||
#! @tparam index The index, known while compiling.
|
||||
#! @param this The tuple to write.
|
||||
#! @returns The value.
|
||||
pub def tuple<Ts...>::at<const index: u64>(&mut this): &mut Ts...[index] {
|
||||
return &mut this.items[index];
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
#! @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>
|
||||
, assignable<u64, T>
|
||||
, sliceable<T>
|
||||
, spannable<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>::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<T>::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 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<T>::slice_of(other: &mut vector<T>, start: u64 = 0, count: u64 = ~0u): 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.
|
||||
val whole := slice::<T> { _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<T>::span_of(other: &vector<T>, start: u64 = 0, count: u64 = ~0u): span<T> {
|
||||
# Made as it is, as the slice is.
|
||||
val whole := span::<T> { _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<T>::span: span<T> {
|
||||
get => span::<T> { _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<T>::slice: slice<T> {
|
||||
get mut => slice::<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 {};
|
||||
}
|
||||
|
||||
#! 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<T>::first: &T {
|
||||
get {
|
||||
expects(!this.empty, "The vector is empty.");
|
||||
# Reached as a view's element, whose check the test above answers.
|
||||
return &span::<T> { _dat = this._dat, _len = this._len }[0];
|
||||
}
|
||||
get mut {
|
||||
expects(!this.empty, "The vector is empty.");
|
||||
return &mut slice::<T> { _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<T>::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<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.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 {
|
||||
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::<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 {
|
||||
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::<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>::iterator = span<T>::iterator;
|
||||
|
||||
#! What `iter(&mut this)` lends, which writes the elements where the vector
|
||||
#! holds them.
|
||||
pub type vector<T>::mutator = slice<T>::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<T>::iter(&this): span<T>::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<T>::iter(&mut this): slice<T>::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<T>::iterator: span<T>::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<T>::mutator: slice<T>::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<T>::from<I>(from: I): vector<T> where I: iter<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();
|
||||
expects(stop <= this._len && start <= stop);
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
#! @file fault.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `fault`, which stops a program that has found a mistake of its own,
|
||||
#! saying what, as an index past the end of a view stops it, as a contract that
|
||||
#! fails does, `contracts`, which says whether they are checked, and the fault
|
||||
#! the allocators of `core` stop with.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Stops the program at once, as a fault does: the report is "runtime error: "
|
||||
#! and the text given, then the functions that were running, and the status is
|
||||
#! 1, as every fault's.
|
||||
#!
|
||||
#! This is for a mistake the program cannot go on from, as a container asked
|
||||
#! for an element past its end. It needs nothing of the system it runs on, so
|
||||
#! every place a program runs gives it, and it never returns.
|
||||
#! @param why What went wrong, as `Index 5 is out of bounds: the length is 3.`
|
||||
@intrinsic
|
||||
pub def fault(why: strview): void;
|
||||
|
||||
#! Whether the program's contracts are checked: where the program is checked,
|
||||
#! as where it runs on the machine but for `run --fast`, and where it was built
|
||||
#! with `--checks`, unless `--contracts on` or `--contracts off` says otherwise.
|
||||
#! Left out, each `expects`, `asserts`, and `ensures` goes, conditions and all.
|
||||
#!
|
||||
#! The containers of `core` and std check what they are asked for with
|
||||
#! contracts, as `expects(index < this._len)`, so a checked program stops where
|
||||
#! one is asked for what it does not hold, as it stops at an index past the end
|
||||
#! of a view, and one that is not checked trusts the program, as C does.
|
||||
#!
|
||||
#! It is known while compiling, so `if const contracts()` keeps work that only
|
||||
#! contracts read out of a program that leaves them out.
|
||||
#! @returns Whether they are.
|
||||
@intrinsic
|
||||
pub def contracts(): bool;
|
||||
|
||||
# Stops the program where an allocator gives no memory for what is asked of it,
|
||||
# as `raw_allocate` stops it where the system gives none, which every program
|
||||
# does, checked or not.
|
||||
def exhausted(size: u64): void {
|
||||
fault($"The allocator gave no memory for {size} bytes.");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#! @file ffi.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `cfn`, the address of a C function. C's functions, structs, and
|
||||
#! unions are declared in an `extern module`, and `extern import` names the
|
||||
#! library they are found in.
|
||||
|
||||
module core;
|
||||
|
||||
#! The address of a C function taking and giving what `F` does, as
|
||||
#! `cfn<def(i32): void>`, which may be `null`. It is callable, and converts with
|
||||
#! `as` to and from pointers, integers, and other addresses of C functions. A
|
||||
#! function of the program given where one is expected is the address of an
|
||||
#! entry C calls it back through.
|
||||
#! @tparam F The function type the C function has, as `def(i32): void`.
|
||||
@intrinsic
|
||||
pub struct cfn<F> {}
|
||||
@@ -0,0 +1,73 @@
|
||||
#! @file flags.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `flags32`, a set of up to 32 flags held as a `u32`, whose bits are
|
||||
#! named by the members of an enum.
|
||||
|
||||
module core;
|
||||
|
||||
#! A set of up to 32 flags, held as a `u32`, whose bits are named by the members
|
||||
#! of an enum.
|
||||
#!
|
||||
#! It converts to and from `u32` as any alias does, so it is written where an
|
||||
#! integer of flags is wanted, and its methods read and write the bits by member
|
||||
#! or by index.
|
||||
#! @tparam T The enum naming the bits, whose members' values are the bits they
|
||||
#! set.
|
||||
pub type flags32<T> = u32
|
||||
where T : ordinal;
|
||||
|
||||
|
||||
#! Whether the flags hold any bit of a value.
|
||||
#! @param this The flags to read.
|
||||
#! @param value The value whose bits to look for.
|
||||
#! @returns Whether any of its bits is set.
|
||||
pub def flags32<T>::get(&this, value: T): bool {
|
||||
return (this & value as u32) != 0;
|
||||
}
|
||||
|
||||
#! Whether the flags hold a bit.
|
||||
#! @param this The flags to read.
|
||||
#! @param index Which bit, from 0 to 31.
|
||||
#! @returns Whether it is set.
|
||||
pub def flags32<T>::get(&this, index: u8): bool {
|
||||
return (this & ((1 as u32) << index as u32)) != 0;
|
||||
}
|
||||
|
||||
#! Sets the bits of a value.
|
||||
#! @param this The flags to change.
|
||||
#! @param value The value whose bits to set.
|
||||
pub def flags32<T>::set(&mut this, value: T): void {
|
||||
this |= value as u32;
|
||||
}
|
||||
|
||||
#! Sets or clears a bit.
|
||||
#! @param this The flags to change.
|
||||
#! @param index Which bit, from 0 to 31.
|
||||
#! @param value Whether the bit is set, or else cleared.
|
||||
pub def flags32<T>::set(&mut this, index: u8, value: bool): void {
|
||||
val bit := (1 as u32) << index as u32;
|
||||
this = value ? this | bit : this & ~bit;
|
||||
}
|
||||
|
||||
#! The flags with the bits of a value set too.
|
||||
#! @param this The flags to start from.
|
||||
#! @param value The value whose bits to set.
|
||||
#! @returns The flags with those bits set, leaving these as they are.
|
||||
pub def flags32<T>::with(&this, value: T): flags32<T> {
|
||||
return this | value as u32;
|
||||
}
|
||||
|
||||
#! The flags with a bit set or cleared.
|
||||
#! @param this The flags to start from.
|
||||
#! @param index Which bit, from 0 to 31.
|
||||
#! @param value Whether the bit is set, or else cleared.
|
||||
#! @returns The flags with the bit changed, leaving these as they are.
|
||||
pub def flags32<T>::with(&this, index: u8, value: bool): flags32<T> {
|
||||
val bit := (1 as u32) << index as u32;
|
||||
return value ? this | bit : this & ~bit;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
#! @file function.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `function`, one callable of a signature, whatever its type, which it
|
||||
#! owns, as C++'s `std::function` and Rust's `Box<dyn FnMut>`: for a callable kept
|
||||
#! past the call that is given it, where its type is not one to name.
|
||||
|
||||
module core;
|
||||
|
||||
#! A callable of one signature, whatever its type, which it owns and closes where
|
||||
#! it closes: a functor, a function, a lambda, or the address of a C function, as
|
||||
#! `function<def(&event): void>`.
|
||||
#!
|
||||
#! It holds a callable of 24 bytes or fewer, aligned to 8 or less, in the value
|
||||
#! itself, as it does a function value, a C function's address, and most
|
||||
#! functors, and a larger one in a `box`. A call goes through one table of what
|
||||
#! the held type does, which each type has one of, so calling it costs one load
|
||||
#! and one indirect call more than calling what it holds.
|
||||
#!
|
||||
#! It is moved, never copied: `move` leaves the one moved from empty. Its zero
|
||||
#! value holds nothing, so a field or a variable needs none given, and calling a
|
||||
#! function that holds nothing stops the program, as reaching through `null`
|
||||
#! does.
|
||||
#!
|
||||
#! ```sakura
|
||||
#! var handlers := vector::<function<def(&event): void>>::new();
|
||||
#! handlers.append(function::new(tally {}));
|
||||
#! handlers.append(function::new(def(e: &event) { println(e.name); }));
|
||||
#! for &h in handlers { h(&e); }
|
||||
#! ```
|
||||
#! @tparam S The signature, as `def(i64): bool`.
|
||||
#! @remarks A lambda refers to the locals it uses, so a function holding one
|
||||
#! refers to them too, and must not outlive them. What must outlive the
|
||||
#! frame making it is a functor holding what it needs. A function is no
|
||||
#! constant, since a constant would keep the words of what it holds but
|
||||
#! not the function a function value among them is.
|
||||
pub struct function<S> : invokable<S>, owning where S: signature {
|
||||
var _ops: *function_ops<S>; #! What the held type does, or `null` where it holds nothing.
|
||||
var _held: u64[3]; #! The callable where it fits, or a `box` of it.
|
||||
}
|
||||
|
||||
# What a function does with the type it holds: one constant for each type, so its
|
||||
# address names the type.
|
||||
struct function_ops<S> where S: signature {
|
||||
var call: def(*mut u8, S::params...): S::result; # Calls the callable held at the buffer.
|
||||
var close: def(*mut u8): void; # Closes it, and its box where it has one.
|
||||
}
|
||||
|
||||
# Whether a function holds a callable of a type in its buffer, rather than in a box.
|
||||
def function_ops<S>::fits<F>(): bool {
|
||||
return size_of::<F>() <= 24 && align_of::<F>() <= 8;
|
||||
}
|
||||
|
||||
# The table of what a function does with a type it holds, at one address for each
|
||||
# type.
|
||||
def function_ops<S>::of<F>(): *function_ops<S> where F: invokable<S> {
|
||||
if const function_ops::<S>::fits::<F>() {
|
||||
const held: function_ops<S> = function_ops::<S> {
|
||||
call = function_ops::<S>::call_held::<F>,
|
||||
close = function_ops::<S>::close_held::<F>
|
||||
};
|
||||
return &held as *function_ops<S>;
|
||||
} else {
|
||||
const boxed: function_ops<S> = function_ops::<S> {
|
||||
call = function_ops::<S>::call_boxed::<F>,
|
||||
close = function_ops::<S>::close_boxed::<F>
|
||||
};
|
||||
return &boxed as *function_ops<S>;
|
||||
}
|
||||
}
|
||||
|
||||
# Calls a callable held in the buffer.
|
||||
def function_ops<S>::call_held<F>(at: *mut u8, args: S::params...): S::result where F: invokable<S> {
|
||||
return (at as *mut F)[0](...args);
|
||||
}
|
||||
|
||||
# Closes a callable held in the buffer.
|
||||
def function_ops<S>::close_held<F>(at: *mut u8): void {
|
||||
close(through(at as *mut F));
|
||||
}
|
||||
|
||||
# Calls a callable the buffer holds a box of.
|
||||
def function_ops<S>::call_boxed<F>(at: *mut u8, args: S::params...): S::result where F: invokable<S> {
|
||||
val held := &mut (at as *mut box<F>)[0].get();
|
||||
return held(...args);
|
||||
}
|
||||
|
||||
# Closes the box the buffer holds, which closes the callable and gives back its
|
||||
# memory.
|
||||
def function_ops<S>::close_boxed<F>(at: *mut u8): void {
|
||||
close(through(at as *mut box<F>));
|
||||
}
|
||||
|
||||
#! Makes a function holding a callable: a functor, a function value, named or a
|
||||
#! lambda, the address of a C function, or a method taken through its type, as
|
||||
#! `vec2::length`, which takes its receiver first.
|
||||
#! @tparam F The callable's type.
|
||||
#! @param callable The callable, which the function then owns, so it keeps
|
||||
#! what a lambda given for it refers to.
|
||||
#! @returns The function.
|
||||
pub def function<S>::new<F>(@kept callable: F): function<S> where F: invokable<S> {
|
||||
var made := function::<S> { _ops = function_ops::<S>::of::<F>() };
|
||||
# Reached through the buffer's address as a number, which no constant is made
|
||||
# by, since a constant would keep the callable's words but not the function a
|
||||
# function value among them is.
|
||||
if const function_ops::<S>::fits::<F>() {
|
||||
(made.buffer() as *mut F)[0] = move(&mut callable);
|
||||
} else {
|
||||
(made.buffer() as *mut box<F>)[0] = box::<F>::new(move(&mut callable));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Calls what a function holds, as `f(args)` does.
|
||||
#! @param this The function, which must hold a callable.
|
||||
#! @param args The arguments, one of each of the signature's parameter types.
|
||||
#! @returns What the call gives.
|
||||
#! @remarks The callable may change what it holds, as a functor's `invoke`
|
||||
#! taking `&mut this` does, though the function is called as it is, as
|
||||
#! a function value is.
|
||||
pub def function<S>::invoke(&this, args: S::params...): S::result {
|
||||
return (*this._ops).call(this.buffer(), ...args);
|
||||
}
|
||||
|
||||
# The buffer's address, which a callable held there is called with, and which it
|
||||
# may change through, as calling a function value may change what it refers to.
|
||||
def function<S>::buffer(&this): *mut u8 {
|
||||
return (&this._held as *u8) as u64 as *mut u8;
|
||||
}
|
||||
|
||||
#! Whether a function holds a callable, which one moved from or closed does not.
|
||||
#! @param this The function.
|
||||
#! @returns Whether it does.
|
||||
pub def function<S>::holds(&this): bool {
|
||||
return this._ops != null;
|
||||
}
|
||||
|
||||
#! Lends the callable a function holds, where it is of a type.
|
||||
#! @tparam F The type asked for.
|
||||
#! @param this The function.
|
||||
#! @returns The callable, good while the function holds it, or `nothing` where
|
||||
#! it holds nothing, or a callable of another type.
|
||||
pub def function<S>::get<F>(&this): maybe<&F> where F: invokable<S> {
|
||||
if this._ops != function_ops::<S>::of::<F>() {
|
||||
return nothing {};
|
||||
}
|
||||
if const function_ops::<S>::fits::<F>() {
|
||||
return through(&this._held as *F);
|
||||
} else {
|
||||
return (&this._held as *box<F>)[0].get();
|
||||
}
|
||||
}
|
||||
|
||||
#! Closes what a function holds.
|
||||
#! @param this The function, which holds nothing after, so closing it again
|
||||
#! does nothing.
|
||||
pub def function<S>::close(&mut this): void {
|
||||
val ops := this._ops;
|
||||
return if ops == null;
|
||||
this._ops = null;
|
||||
(*ops).close(&mut this._held as *mut u8);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
#! @file intrinsics.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the operations of the machine the compiler gives that libraries
|
||||
#! build on, and which no operator writes: a square root, which IEEE 754
|
||||
#! defines to the bit, and working an operation on lanes of numbers with the
|
||||
#! instructions the processor has. `std::math` builds its functions of real
|
||||
#! numbers and of lanes on them.
|
||||
#!
|
||||
#! The compiler gives them: the virtual machine runs its own, and an executable
|
||||
#! the instruction `sqrtsd`, and the vector instructions the processor running
|
||||
#! it has. A square root is the true root rounded once, so they agree to the
|
||||
#! bit, and a constant worked out while compiling is what running gives.
|
||||
#!
|
||||
#! They are a module within `core`, rather than its root, so their names are
|
||||
#! seen only where it is imported.
|
||||
|
||||
module core::intrinsics;
|
||||
|
||||
|
||||
#! The square root of a double, correctly rounded: `-0` for `-0`, infinity for
|
||||
#! infinity, and not a number for what is below zero or not a number.
|
||||
#! @param x The double.
|
||||
#! @returns Its square root.
|
||||
@intrinsic pub def square_root(x: f64): f64;
|
||||
|
||||
#! Whether the processor running the program has the instructions working `OP`
|
||||
#! on `N` lanes of `L`, which the program asked it once as it started.
|
||||
#! @tparam L The type of each lane.
|
||||
#! @tparam OP The operation, as the compiler numbers it.
|
||||
#! @tparam N How many lanes.
|
||||
#! @returns Whether it has them: never in the virtual machine.
|
||||
@intrinsic pub def lanes_have<L, const OP: u32, const N: u64>(): bool;
|
||||
|
||||
#! Works `OP` on `N` lanes of `L`, from the bytes `a`, `b`, and `c` into those
|
||||
#! of `into`, with the instructions `lanes_have` says the processor has.
|
||||
#! @tparam L The type of each lane.
|
||||
#! @tparam OP The operation, as the compiler numbers it.
|
||||
#! @tparam N How many lanes.
|
||||
#! @param into Where the lanes worked out are written.
|
||||
#! @param a The first operand's lanes.
|
||||
#! @param b The second's, or null where the operation takes one.
|
||||
#! @param c The third's, or null where it takes fewer.
|
||||
@intrinsic pub def lanes_apply<L, const OP: u32, const N: u64>(into: *mut u8, a: *u8, b: *u8, c: *u8): void;
|
||||
@@ -0,0 +1,547 @@
|
||||
#! @file adapters.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the adapters, each the iterator one of `iterator`'s defaults makes of
|
||||
#! another, which it owns: what it gives, and, where what it adapts knows how
|
||||
#! many elements it has left or walks backward, how many it has left or its
|
||||
#! elements from the far end. Each is named for what it does, and only written
|
||||
#! out where a program keeps one in a field.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! What `map` makes: what a function makes of each element.
|
||||
#! @tparam T What the iterator it adapts gives.
|
||||
#! @tparam U What the function gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
#! @tparam F The function.
|
||||
pub struct mapped<T, U, I, F> : iter<U> where I: iter<T> where F: invokable<def(T): U> {
|
||||
var _from: I;
|
||||
var _f: F;
|
||||
}
|
||||
|
||||
#! Gives what the function makes of the next element.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe what it makes; otherwise, `nothing`.
|
||||
pub def mapped<T, U, I, F>::next(&mut this): maybe<U> {
|
||||
if this._from.next() is some(x) {
|
||||
return this._f(move(&mut x));
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How many elements it has left, which are what it adapts has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def mapped<T, U, I, F>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
return this._from.remaining();
|
||||
}
|
||||
|
||||
#! Gives what the function makes of the element at the far end.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe what it makes; otherwise, `nothing`.
|
||||
pub def mapped<T, U, I, F>::next_back(&mut this): maybe<U> where I: backward_iterator<T> {
|
||||
if this._from.next_back() is some(x) {
|
||||
return this._f(move(&mut x));
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `filter` makes: each element a test passes.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
#! @tparam F The test.
|
||||
pub struct filtered<T, I, F> : iter<T> where I: iter<T> where F: invokable<def(&T): bool> {
|
||||
var _from: I;
|
||||
var _test: F;
|
||||
}
|
||||
|
||||
#! Gives the next element the test passes.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def filtered<T, I, F>::next(&mut this): maybe<T> {
|
||||
while this._from.next() is some(x) {
|
||||
return move(&mut x) if this._test(&x);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Gives the element nearest the far end the test passes.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def filtered<T, I, F>::next_back(&mut this): maybe<T> where I: backward_iterator<T> {
|
||||
while this._from.next_back() is some(x) {
|
||||
return move(&mut x) if this._test(&x);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `filter_map` makes: what a function makes of each element, where it
|
||||
#! makes something.
|
||||
#! @tparam T What the iterator it adapts gives.
|
||||
#! @tparam U What the function may give.
|
||||
#! @tparam I The iterator it adapts.
|
||||
#! @tparam F The function.
|
||||
pub struct filter_mapped<T, U, I, F> : iter<U> where I: iter<T> where F: invokable<def(T): maybe<U>> {
|
||||
var _from: I;
|
||||
var _f: F;
|
||||
}
|
||||
|
||||
#! Gives the next thing the function makes.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe what it makes; otherwise, `nothing`.
|
||||
pub def filter_mapped<T, U, I, F>::next(&mut this): maybe<U> {
|
||||
while this._from.next() is some(x) {
|
||||
var made := this._f(move(&mut x));
|
||||
if made is some(&mut kept) {
|
||||
return move(kept);
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Gives the thing the function makes nearest the far end.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe what it makes; otherwise, `nothing`.
|
||||
pub def filter_mapped<T, U, I, F>::next_back(&mut this): maybe<U> where I: backward_iterator<T> {
|
||||
while this._from.next_back() is some(x) {
|
||||
var made := this._f(move(&mut x));
|
||||
if made is some(&mut kept) {
|
||||
return move(kept);
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `enumerate` makes: each element with its index, counting from 0.
|
||||
#! @tparam T What the iterator it adapts gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
pub struct enumerated<T, I> : iter<pair<u64, T>> where I: iter<T> {
|
||||
var _from: I;
|
||||
var _at: u64;
|
||||
}
|
||||
|
||||
#! Gives the next element with its index.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the pair; otherwise, `nothing`.
|
||||
pub def enumerated<T, I>::next(&mut this): maybe<pair<u64, T>> {
|
||||
if this._from.next() is some(x) {
|
||||
val at := this._at;
|
||||
this._at++;
|
||||
return pair::<u64, T> { first = at, second = move(&mut x) };
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How many elements it has left, which are what it adapts has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def enumerated<T, I>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
return this._from.remaining();
|
||||
}
|
||||
|
||||
#! Gives the element at the far end with its index, which how many are left
|
||||
#! says.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the pair; otherwise, `nothing`.
|
||||
pub def enumerated<T, I>::next_back(&mut this): maybe<pair<u64, T>> where I: backward_iterator<T>, sized_iterator<T> {
|
||||
val left := this._from.remaining();
|
||||
if this._from.next_back() is some(x) {
|
||||
return pair::<u64, T> { first = this._at + left - 1, second = move(&mut x) };
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `zip` makes: the elements of two iterators side by side, until either
|
||||
#! ends.
|
||||
#! @tparam T What the first gives.
|
||||
#! @tparam U What the second gives.
|
||||
#! @tparam I The first.
|
||||
#! @tparam J The second.
|
||||
pub struct zipped<T, U, I, J> : iter<pair<T, U>> where I: iter<T> where J: iter<U> {
|
||||
var _from: I;
|
||||
var _other: J;
|
||||
}
|
||||
|
||||
#! Gives the next element of each, side by side.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the pair; otherwise, `nothing` once either ends.
|
||||
pub def zipped<T, U, I, J>::next(&mut this): maybe<pair<T, U>> {
|
||||
var first := this._from.next();
|
||||
if first is not some(&mut a) {
|
||||
return nothing {};
|
||||
}
|
||||
var second := this._other.next();
|
||||
if second is not some(&mut b) {
|
||||
return nothing {};
|
||||
}
|
||||
return pair::<T, U> { first = move(a), second = move(b) };
|
||||
}
|
||||
|
||||
#! How many pairs it has left: as many as the shorter has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def zipped<T, U, I, J>::remaining(&this): u64 where I: sized_iterator<T> where J: sized_iterator<U> {
|
||||
val a := this._from.remaining();
|
||||
val b := this._other.remaining();
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
#! What `chain` makes: the elements of one iterator, then another's.
|
||||
#! @tparam T What both give.
|
||||
#! @tparam I The first.
|
||||
#! @tparam J The second.
|
||||
pub struct chained<T, I, J> : iter<T> where I: iter<T> where J: iter<T> {
|
||||
var _first: I;
|
||||
var _second: J;
|
||||
var _on_second: bool;
|
||||
}
|
||||
|
||||
#! Gives the next element of the first, or once it has ended, of the second.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def chained<T, I, J>::next(&mut this): maybe<T> {
|
||||
if !this._on_second {
|
||||
if this._first.next() is some(x) {
|
||||
return move(&mut x);
|
||||
}
|
||||
this._on_second = true;
|
||||
}
|
||||
return this._second.next();
|
||||
}
|
||||
|
||||
#! How many elements it has left: what both have.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def chained<T, I, J>::remaining(&this): u64 where I: sized_iterator<T> where J: sized_iterator<T> {
|
||||
return (this._on_second ? 0 : this._first.remaining()) + this._second.remaining();
|
||||
}
|
||||
|
||||
#! Gives the element at the far end of the second, or once it has met its
|
||||
#! front, of the first.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def chained<T, I, J>::next_back(&mut this): maybe<T> where I: backward_iterator<T> where J: backward_iterator<T> {
|
||||
if this._second.next_back() is some(x) {
|
||||
return move(&mut x);
|
||||
}
|
||||
return nothing {} if this._on_second;
|
||||
return this._first.next_back();
|
||||
}
|
||||
|
||||
#! What `take` makes: the first elements, up to a count.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
pub struct taken<T, I> : iter<T> where I: iter<T> {
|
||||
var _from: I;
|
||||
var _left: u64;
|
||||
}
|
||||
|
||||
#! Gives the next element, while the count lasts.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def taken<T, I>::next(&mut this): maybe<T> {
|
||||
return nothing {} if this._left == 0;
|
||||
this._left--;
|
||||
return this._from.next();
|
||||
}
|
||||
|
||||
#! How many elements it has left: the fewer of the count and what it adapts has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def taken<T, I>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
val held := this._from.remaining();
|
||||
return held < this._left ? held : this._left;
|
||||
}
|
||||
|
||||
#! What `skip` makes: the elements after the first, up to a count.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
pub struct skipped<T, I> : iter<T> where I: iter<T> {
|
||||
var _from: I;
|
||||
var _skip: u64;
|
||||
}
|
||||
|
||||
#! Gives the next element, passing over those to skip the first time.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def skipped<T, I>::next(&mut this): maybe<T> {
|
||||
if this._skip != 0 {
|
||||
val n := this._skip;
|
||||
this._skip = 0;
|
||||
return this._from.nth(n);
|
||||
}
|
||||
return this._from.next();
|
||||
}
|
||||
|
||||
#! How many elements it has left: what it adapts has, past those to skip.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def skipped<T, I>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
val held := this._from.remaining();
|
||||
return held > this._skip ? held - this._skip : 0;
|
||||
}
|
||||
|
||||
#! Gives the element at the far end, while it is past those to skip.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def skipped<T, I>::next_back(&mut this): maybe<T> where I: backward_iterator<T>, sized_iterator<T> {
|
||||
return nothing {} if this._from.remaining() <= this._skip;
|
||||
return this._from.next_back();
|
||||
}
|
||||
|
||||
#! What `take_while` makes: the elements while a test passes them.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
#! @tparam F The test.
|
||||
pub struct taken_while<T, I, F> : iter<T> where I: iter<T> where F: invokable<def(&T): bool> {
|
||||
var _from: I;
|
||||
var _test: F;
|
||||
var _done: bool;
|
||||
}
|
||||
|
||||
#! Gives the next element where the test passes it, and ends at the first it
|
||||
#! does not.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def taken_while<T, I, F>::next(&mut this): maybe<T> {
|
||||
return nothing {} if this._done;
|
||||
if this._from.next() is some(x) {
|
||||
return move(&mut x) if this._test(&x);
|
||||
}
|
||||
this._done = true;
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `skip_while` makes: the elements from the first a test does not pass.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
#! @tparam F The test.
|
||||
pub struct skipped_while<T, I, F> : iter<T> where I: iter<T> where F: invokable<def(&T): bool> {
|
||||
var _from: I;
|
||||
var _test: F;
|
||||
var _past: bool;
|
||||
}
|
||||
|
||||
#! Gives the next element, passing over those the test passes the first time.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def skipped_while<T, I, F>::next(&mut this): maybe<T> {
|
||||
return this._from.next() if this._past;
|
||||
this._past = true;
|
||||
while this._from.next() is some(x) {
|
||||
return move(&mut x) if !this._test(&x);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `step` makes: every `n`th element, the first included.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
pub struct stepped<T, I> : iter<T> where I: iter<T> {
|
||||
var _from: I;
|
||||
var _by: u64;
|
||||
var _first: bool;
|
||||
}
|
||||
|
||||
#! Gives the next element, passing over those between.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def stepped<T, I>::next(&mut this): maybe<T> {
|
||||
if this._first {
|
||||
this._first = false;
|
||||
return this._from.next();
|
||||
}
|
||||
return this._from.nth(this._by - 1);
|
||||
}
|
||||
|
||||
#! How many elements it has left: every `n`th of what it adapts has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def stepped<T, I>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
val held := this._from.remaining();
|
||||
return this._first ? (held + this._by - 1) / this._by : held / this._by;
|
||||
}
|
||||
|
||||
#! What `rev` makes: the elements from the far end.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts, which walks backward.
|
||||
pub struct reversed<T, I> : iter<T> where I: backward_iterator<T> {
|
||||
var _from: I;
|
||||
}
|
||||
|
||||
#! Gives the element at the far end of what it adapts.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def reversed<T, I>::next(&mut this): maybe<T> {
|
||||
return this._from.next_back();
|
||||
}
|
||||
|
||||
#! Gives the element at the front of what it adapts, its own far end.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def reversed<T, I>::next_back(&mut this): maybe<T> {
|
||||
return this._from.next();
|
||||
}
|
||||
|
||||
#! How many elements it has left, which are what it adapts has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def reversed<T, I>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
return this._from.remaining();
|
||||
}
|
||||
|
||||
#! What `peekable` makes: the elements, with the next looked at by `peek`
|
||||
#! before it is given.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
pub struct peeking<T, I> : iter<T> where I: iter<T> {
|
||||
var _from: I;
|
||||
var _held: maybe<T>;
|
||||
var _peeked: bool;
|
||||
}
|
||||
|
||||
#! Gives the next element, the one `peek` looked at where it did.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def peeking<T, I>::next(&mut this): maybe<T> {
|
||||
if this._peeked {
|
||||
this._peeked = false;
|
||||
return move(&mut this._held);
|
||||
}
|
||||
return this._from.next();
|
||||
}
|
||||
|
||||
#! Looks at the next element without giving it, so `next` gives it after.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe a reference to the element, which it holds; otherwise,
|
||||
#! `nothing`.
|
||||
pub def peeking<T, I>::peek(&mut this): maybe<&T> {
|
||||
if !this._peeked {
|
||||
this._held = this._from.next();
|
||||
this._peeked = true;
|
||||
}
|
||||
if this._held is some(&x) {
|
||||
return x;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How many elements it has left: what it adapts has, and the one it holds.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def peeking<T, I>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
var made := this._from.remaining();
|
||||
if this._peeked && this._held is some(&x) {
|
||||
made++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! What `flat_map` makes: the elements of each iterator a function makes of
|
||||
#! each element, in turn.
|
||||
#! @tparam T What the iterator it adapts gives.
|
||||
#! @tparam U What the iterators the function makes give.
|
||||
#! @tparam I The iterator it adapts.
|
||||
#! @tparam J The iterators the function makes.
|
||||
#! @tparam F The function.
|
||||
pub struct flat_mapped<T, U, I, J, F> : iter<U>
|
||||
where I: iter<T> where J: iter<U> where F: invokable<def(T): J> {
|
||||
var _from: I;
|
||||
var _f: F;
|
||||
var _inner: maybe<J>;
|
||||
}
|
||||
|
||||
#! Gives the next element of the iterator it is walking, or of the next it
|
||||
#! makes, once that one ends.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def flat_mapped<T, U, I, J, F>::next(&mut this): maybe<U> {
|
||||
while true {
|
||||
if this._inner is some(&mut inner) {
|
||||
if inner.next() is some(x) {
|
||||
return move(&mut x);
|
||||
}
|
||||
}
|
||||
if this._from.next() is not some(y) {
|
||||
return nothing {};
|
||||
}
|
||||
this._inner = this._f(move(&mut y));
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `copied` makes: a copy of what each reference refers to.
|
||||
#! @tparam X What the references refer to.
|
||||
#! @tparam I The iterator of references it adapts.
|
||||
pub struct copying<X, I> : iter<X> where I: iter<&X> {
|
||||
var _from: I;
|
||||
}
|
||||
|
||||
#! Gives a copy of what the next reference refers to.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the copy; otherwise, `nothing`.
|
||||
pub def copying<X, I>::next(&mut this): maybe<X> {
|
||||
if this._from.next() is some(r) {
|
||||
return copy(r);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How many elements it has left, which are what it adapts has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def copying<X, I>::remaining(&this): u64 where I: sized_iterator<&X> {
|
||||
return this._from.remaining();
|
||||
}
|
||||
|
||||
#! Gives a copy of what the reference at the far end refers to.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the copy; otherwise, `nothing`.
|
||||
pub def copying<X, I>::next_back(&mut this): maybe<X> where I: backward_iterator<&X> {
|
||||
if this._from.next_back() is some(r) {
|
||||
return copy(r);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What `inspect` makes: the elements as they are, after a function is called on
|
||||
#! each.
|
||||
#! @tparam T What it gives.
|
||||
#! @tparam I The iterator it adapts.
|
||||
#! @tparam F The function.
|
||||
pub struct inspected<T, I, F> : iter<T> where I: iter<T> where F: invokable<def(&T): void> {
|
||||
var _from: I;
|
||||
var _f: F;
|
||||
}
|
||||
|
||||
#! Gives the next element, once the function has seen it.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def inspected<T, I, F>::next(&mut this): maybe<T> {
|
||||
if this._from.next() is some(x) {
|
||||
this._f(&x);
|
||||
return move(&mut x);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How many elements it has left, which are what it adapts has.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def inspected<T, I, F>::remaining(&this): u64 where I: sized_iterator<T> {
|
||||
return this._from.remaining();
|
||||
}
|
||||
|
||||
#! Gives the element at the far end, once the function has seen it.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
pub def inspected<T, I, F>::next_back(&mut this): maybe<T> where I: backward_iterator<T> {
|
||||
if this._from.next_back() is some(x) {
|
||||
this._f(&x);
|
||||
return move(&mut x);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
#! @file range.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the methods of `range`, the integers from a start up to an end, or
|
||||
#! the members of an enum between two, which `a..b` and `a..=b` make wherever
|
||||
#! they are written as a value.
|
||||
#!
|
||||
#! `range` is among the types the syntax makes, which the compiler declares
|
||||
#! itself. It is an iterator, walked forward or from its far end, that knows how
|
||||
#! many it has left, so `(0..n).rev()` and `(0..n).step(2)` count as a loop
|
||||
#! would. A `for` loop over `a..b` written in place counts without making one.
|
||||
#!
|
||||
#! A range of an enum's members gives them in the order of their values, each
|
||||
#! value once, passing over those no member has, as `color::red..=color::blue`
|
||||
#! gives `red`, `green`, and `blue` of `enum color { red, green = 4, blue }`.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! The place of a member of an enum among the values of its members, from 0 for
|
||||
#! the least, each value counted once.
|
||||
#! @tparam T The enum.
|
||||
#! @param member The member.
|
||||
#! @returns Its place.
|
||||
@intrinsic
|
||||
def rank_of<T>(member: T): u64;
|
||||
|
||||
#! The member of an enum at a place among the values of its members, as
|
||||
#! `rank_of` gives it.
|
||||
#! @tparam T The enum.
|
||||
#! @param rank The place, before the count of the members' values.
|
||||
#! @returns The member.
|
||||
@intrinsic
|
||||
def member_at<T>(rank: u64): T;
|
||||
|
||||
#! The value a number of places past another, as a range counts: the integer
|
||||
#! that far past it, or the member of an enum that many members past it.
|
||||
#! @tparam T The integer type, or the enum.
|
||||
#! @param from The value to count from.
|
||||
#! @param n How many places past it.
|
||||
#! @returns The value.
|
||||
def range<T>::past(from: T, n: u64): T {
|
||||
if const T is integer {
|
||||
return ((from as u64) + n) as T;
|
||||
}
|
||||
return member_at::<T>(rank_of(from) + n);
|
||||
}
|
||||
|
||||
#! How many places a range counts from one value up to another, which does not
|
||||
#! come before it.
|
||||
#! @tparam T The integer type, or the enum.
|
||||
#! @param from The first value.
|
||||
#! @param to The value it counts up to.
|
||||
#! @returns How many.
|
||||
def range<T>::between(from: T, to: T): u64 {
|
||||
if const T is integer {
|
||||
return (to as u64) - (from as u64);
|
||||
}
|
||||
return rank_of(to) - rank_of(from);
|
||||
}
|
||||
|
||||
|
||||
#! Gives the next value, counting up from the start.
|
||||
#! @param this The range.
|
||||
#! @returns Maybe the value; otherwise, `nothing` once it has given them all.
|
||||
pub def range<T>::next(&mut this): maybe<T> {
|
||||
if this.start < this.end {
|
||||
val at := this.start;
|
||||
if const T is integer {
|
||||
this.start++;
|
||||
} else {
|
||||
this.start = range::<T>::past(at, 1);
|
||||
}
|
||||
return at;
|
||||
}
|
||||
if this._last && this.start == this.end {
|
||||
this._last = false;
|
||||
return this.end;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Gives the value at the far end, counting down from the end.
|
||||
#! @param this The range.
|
||||
#! @returns Maybe the value; otherwise, `nothing` once the ends have met.
|
||||
pub def range<T>::next_back(&mut this): maybe<T> {
|
||||
if this._last && !(this.end < this.start) {
|
||||
this._last = false;
|
||||
return this.end;
|
||||
}
|
||||
if this.start < this.end {
|
||||
if const T is integer {
|
||||
this.end--;
|
||||
} else {
|
||||
this.end = member_at::<T>(rank_of(this.end) - 1);
|
||||
}
|
||||
return this.end;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How many values it has left to give.
|
||||
#! @param this The range.
|
||||
#! @returns How many.
|
||||
pub def range<T>::remaining(&this): u64 {
|
||||
var made: u64 = this.start < this.end ? range::<T>::between(this.start, this.end) : 0;
|
||||
if this._last && !(this.end < this.start) {
|
||||
made++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! How many values it has left to give, as `remaining` says.
|
||||
#! @param this The range.
|
||||
#! @returns How many.
|
||||
pub val range<T>::length: u64 {
|
||||
get => this.remaining();
|
||||
}
|
||||
|
||||
#! Whether it has given every value, or had none to give.
|
||||
#! @param this The range.
|
||||
#! @returns Whether it has none left.
|
||||
pub def range<T>::is_empty(&this): bool {
|
||||
return !(this.start < this.end) && !(this._last && this.start == this.end);
|
||||
}
|
||||
|
||||
#! Whether a value is among those it has left to give.
|
||||
#! @param this The range.
|
||||
#! @param x The value.
|
||||
#! @returns Whether it is.
|
||||
pub def range<T>::contains(&this, x: T): bool {
|
||||
return !(x < this.start) && (x < this.end || (this._last && x == this.end));
|
||||
}
|
||||
|
||||
#! The value `n` along, counting from 0, passing over those before it at once.
|
||||
#! @param this The range.
|
||||
#! @param n How many to pass over first.
|
||||
#! @returns Maybe the value; otherwise, `nothing` where it has fewer left.
|
||||
pub def range<T>::nth(&mut this, n: u64): maybe<T> {
|
||||
val held: u64 = this.start < this.end ? range::<T>::between(this.start, this.end) : 0;
|
||||
if n < held {
|
||||
this.start = range::<T>::past(this.start, n);
|
||||
return this.next();
|
||||
}
|
||||
if this.start < this.end {
|
||||
this.start = this.end;
|
||||
}
|
||||
return this.next() if n == held;
|
||||
this._last = false;
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Gives every value it has left at once, counting them.
|
||||
#! @param this The range.
|
||||
#! @returns How many it had left.
|
||||
pub def range<T>::count(&mut this): u64 {
|
||||
val made := this.remaining();
|
||||
if this.start < this.end {
|
||||
this.start = this.end;
|
||||
}
|
||||
this._last = false;
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
#! @file text.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains text walked lazily, each piece a view into the text as it is
|
||||
#! reached, without a vector of them: its runs between a byte, its lines, its
|
||||
#! words, and its code points. `.to_vector()` gives the pieces as a vector.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Splits text by a byte, giving a view of each run between them in turn: one
|
||||
#! more than there are of the byte, so `"a,,b"` gives `a`, an empty run, and
|
||||
#! `b`, and empty text gives one empty run.
|
||||
#! @param this The text to split.
|
||||
#! @param delim The byte to split by, which no run holds.
|
||||
#! @returns The runs, each viewing into the text, so they are only good for as
|
||||
#! long as it is.
|
||||
pub def strview::split(&this, delim: u8): splits {
|
||||
return splits { _left = this, _delim = delim, _done = false };
|
||||
}
|
||||
|
||||
#! Splits the text by a byte, giving a view of each run between them in turn.
|
||||
#! @param this The string to split.
|
||||
#! @param delim The byte to split by, which no run holds.
|
||||
#! @returns The runs, each viewing into the string, so they are only good until
|
||||
#! it grows, shrinks, or closes.
|
||||
pub def string::split(&this, delim: u8): splits {
|
||||
return this.span.split(delim);
|
||||
}
|
||||
|
||||
#! What `split` gives: the runs of text between each of a byte, from the front
|
||||
#! or the far end.
|
||||
pub struct splits : backward_iterator<strview> {
|
||||
var _left: strview; #! The text not yet given.
|
||||
var _delim: u8; #! The byte split by.
|
||||
var _done: bool; #! Whether the last run has been given.
|
||||
}
|
||||
|
||||
#! A split that gives no runs at all, as of what has nothing to split.
|
||||
#! @returns The split.
|
||||
pub def splits::empty(): splits {
|
||||
return splits { _left = strview::blank(), _delim = 0, _done = true };
|
||||
}
|
||||
|
||||
#! Gives the next run, up to the next of the byte or the end of the text.
|
||||
#! @param this The split.
|
||||
#! @returns Maybe a view of the run; otherwise, `nothing` once the last is given.
|
||||
pub def splits::next(&mut this): maybe<strview> {
|
||||
return nothing {} if this._done;
|
||||
val text := this._left;
|
||||
val at := find_byte(text._dat, 0, text._len, this._delim);
|
||||
if at == text._len {
|
||||
this._done = true;
|
||||
return text;
|
||||
}
|
||||
this._left = text.substr(at + 1, text._len - at - 1);
|
||||
return text.substr(0, at);
|
||||
}
|
||||
|
||||
#! Gives the run at the far end, back to the last of the byte or the front of
|
||||
#! what is left.
|
||||
#! @param this The split.
|
||||
#! @returns Maybe a view of the run; otherwise, `nothing` once the last is given.
|
||||
pub def splits::next_back(&mut this): maybe<strview> {
|
||||
return nothing {} if this._done;
|
||||
val text := this._left;
|
||||
val at := find_last_byte(text._dat, 0, text._len, this._delim);
|
||||
if at == text._len {
|
||||
this._done = true;
|
||||
return text;
|
||||
}
|
||||
this._left = text.substr(0, at);
|
||||
return text.substr(at + 1, text._len - at - 1);
|
||||
}
|
||||
|
||||
#! Gives each line of text without the `\n` that ends it or a `\r` before that,
|
||||
#! as reading a stream's lines does: a last line without a line break is still a
|
||||
#! line, and text ending in one has no empty line after it.
|
||||
#! @param this The text to walk.
|
||||
#! @returns The lines, each viewing into the text.
|
||||
pub def strview::lines(&this): text_lines {
|
||||
return text_lines { _left = this };
|
||||
}
|
||||
|
||||
#! What `lines` gives: each line of text.
|
||||
pub struct text_lines : iter<strview> {
|
||||
var _left: strview; #! The text not yet given.
|
||||
}
|
||||
|
||||
#! Gives the next line.
|
||||
#! @param this The lines.
|
||||
#! @returns Maybe a view of the line; otherwise, `nothing` once the text ends.
|
||||
pub def text_lines::next(&mut this): maybe<strview> {
|
||||
val text := this._left;
|
||||
return nothing {} if text._len == 0;
|
||||
val at := find_byte(text._dat, 0, text._len, '\n');
|
||||
var line := text.substr(0, at);
|
||||
this._left = at == text._len ? text.substr(text._len, 0) : text.substr(at + 1, text._len - at - 1);
|
||||
if at < text._len && line._len > 0 && line[line._len - 1] == '\r' {
|
||||
line = line.substr(0, line._len - 1);
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
#! Gives each word of text: each run between whitespace, as `is_space` says,
|
||||
#! which no word holds.
|
||||
#! @param this The text to walk.
|
||||
#! @returns The words, each viewing into the text.
|
||||
pub def strview::words(&this): text_words {
|
||||
return text_words { _left = this };
|
||||
}
|
||||
|
||||
#! What `words` gives: each run of text between whitespace.
|
||||
pub struct text_words : iter<strview> {
|
||||
var _left: strview; #! The text not yet given.
|
||||
}
|
||||
|
||||
#! Gives the next word.
|
||||
#! @param this The words.
|
||||
#! @returns Maybe a view of the word; otherwise, `nothing` once the text ends.
|
||||
pub def text_words::next(&mut this): maybe<strview> {
|
||||
val text := this._left;
|
||||
var start: u64 = 0;
|
||||
while start < text._len && text[start].is_space {
|
||||
start++;
|
||||
}
|
||||
var end := start;
|
||||
while end < text._len && !text[end].is_space {
|
||||
end++;
|
||||
}
|
||||
this._left = text.substr(end, text._len - end);
|
||||
return nothing {} if start == end;
|
||||
return text.substr(start, end - start);
|
||||
}
|
||||
|
||||
#! Gives each code point of text, decoding UTF-8. A byte that begins no
|
||||
#! character, as one past a sequence's end, or a sequence that is cut short,
|
||||
#! too long for its value, or a surrogate's, gives U+FFFD, one for each byte
|
||||
#! that starts none.
|
||||
#! @param this The text to walk.
|
||||
#! @returns The code points.
|
||||
pub def strview::chars(&this): code_points {
|
||||
return code_points { _left = this };
|
||||
}
|
||||
|
||||
#! What `chars` gives: each code point of UTF-8 text.
|
||||
pub struct code_points : iter<u32> {
|
||||
var _left: strview; #! The text not yet given.
|
||||
}
|
||||
|
||||
#! What a malformed byte gives, U+FFFD.
|
||||
const replacement: u32 = 0xFFFD;
|
||||
|
||||
#! Gives the next code point.
|
||||
#! @param this The code points.
|
||||
#! @returns Maybe the code point; otherwise, `nothing` once the text ends.
|
||||
pub def code_points::next(&mut this): maybe<u32> {
|
||||
val text := this._left;
|
||||
return nothing {} if text._len == 0;
|
||||
val lead := text[0];
|
||||
if lead < 0x80 {
|
||||
this._left = text.substr(1, text._len - 1);
|
||||
return lead as u32;
|
||||
}
|
||||
|
||||
# How many bytes follow the lead, what it gives of the value, and the least
|
||||
# value that many encode, below which the sequence is too long.
|
||||
var follow: u64 = 0;
|
||||
var value: u32 = 0;
|
||||
var least: u32 = 0;
|
||||
if (lead & 0xE0) == 0xC0 {
|
||||
follow = 1;
|
||||
value = (lead & 0x1F) as u32;
|
||||
least = 0x80;
|
||||
} else if (lead & 0xF0) == 0xE0 {
|
||||
follow = 2;
|
||||
value = (lead & 0x0F) as u32;
|
||||
least = 0x800;
|
||||
} else if (lead & 0xF8) == 0xF0 {
|
||||
follow = 3;
|
||||
value = (lead & 0x07) as u32;
|
||||
least = 0x10000;
|
||||
}
|
||||
|
||||
var valid := follow != 0 && follow < text._len;
|
||||
for k in 1..=follow {
|
||||
break if !valid;
|
||||
val byte := text[k];
|
||||
valid = (byte & 0xC0) == 0x80;
|
||||
value = (value << 6) | (byte & 0x3F) as u32;
|
||||
}
|
||||
valid = valid && value >= least && value <= 0x10FFFF && (value < 0xD800 || value > 0xDFFF);
|
||||
if !valid {
|
||||
this._left = text.substr(1, text._len - 1);
|
||||
return replacement;
|
||||
}
|
||||
this._left = text.substr(follow + 1, text._len - follow - 1);
|
||||
return value;
|
||||
}
|
||||
+422
@@ -0,0 +1,422 @@
|
||||
#! @file mem.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what a program manages memory with itself: the sizes and alignments
|
||||
#! of types, allocating, resizing, and releasing blocks, reaching through
|
||||
#! pointers, and copying, filling, and comparing bytes.
|
||||
#!
|
||||
#! A block is the program's until it releases it, and nothing keeps one alive:
|
||||
#! a pointer or a reference into one is good while the block is, and using one
|
||||
#! past that is the program's mistake. Owners such as `box`, `rc`, `arc`, and
|
||||
#! the containers release what they allocate where they close.
|
||||
|
||||
import core::swar;
|
||||
module core;
|
||||
|
||||
#! The number of bytes a value of a type takes in memory, which the compiler
|
||||
#! gives.
|
||||
#! @tparam T The type to measure.
|
||||
#! @returns Its size in bytes, known while compiling.
|
||||
@intrinsic
|
||||
pub def size_of<T>(): u64;
|
||||
|
||||
#! The alignment a value of a type needs in memory, which the compiler gives.
|
||||
#! @tparam T The type to measure.
|
||||
#! @returns Its alignment in bytes, known while compiling.
|
||||
@intrinsic
|
||||
pub def align_of<T>(): u64;
|
||||
|
||||
#! The widest alignment any type needs, which `raw_allocate` aligns every block
|
||||
#! to.
|
||||
pub const max_align := 16u;
|
||||
|
||||
#! Allocates a block of bytes from the program's heap, as C's `malloc` does,
|
||||
#! without clearing it, for what is written before it is read.
|
||||
#! @param size The number of bytes to allocate.
|
||||
#! @returns The first byte of the block, aligned to `max_align`, which may hold
|
||||
#! anything at first.
|
||||
#! @remarks Where the system gives no memory, the program stops, so this never
|
||||
#! gives `null` where any memory was asked for. Reading a byte before
|
||||
#! writing it is the program's mistake, which `run --checks` stops at.
|
||||
@intrinsic
|
||||
pub def raw_allocate(size: u64): *mut u8;
|
||||
|
||||
#! Allocates a block of zeroed bytes from the program's heap, as C's `calloc`
|
||||
#! does. Memory the system gives fresh is zero already, so only a block used
|
||||
#! before is cleared.
|
||||
#! @param size The number of bytes to allocate.
|
||||
#! @returns The first byte of the block, aligned to `max_align`.
|
||||
#! @remarks Where the system gives no memory, the program stops, as
|
||||
#! `raw_allocate` does.
|
||||
@intrinsic
|
||||
pub def raw_allocate_zeroed(size: u64): *mut u8;
|
||||
|
||||
# Allocates a block a value of a type is written into: zeroed where the type
|
||||
# closes, since writing it closes what the block held, and as it is otherwise.
|
||||
def allocate_for<T>(size: u64): *mut u8 {
|
||||
if const T is closeable {
|
||||
return raw_allocate_zeroed(size);
|
||||
}
|
||||
return raw_allocate(size);
|
||||
}
|
||||
|
||||
#! Releases a block allocated by `raw_allocate`, `raw_allocate_zeroed`, or
|
||||
#! `raw_resize`.
|
||||
#! @param pointer The first byte of the block, or `null`, which does nothing.
|
||||
#! @remarks Releasing a block twice stops the program.
|
||||
@intrinsic
|
||||
pub def raw_release(pointer: *mut u8): void;
|
||||
|
||||
#! Moves an allocated block to one of another size, keeping as many bytes as
|
||||
#! fit, then releases the old one.
|
||||
#! @param pointer The first byte of the block, or `null` to allocate a new
|
||||
#! one as `raw_allocate` does.
|
||||
#! @param size The number of bytes the new block holds.
|
||||
#! @returns The first byte of the new block, which may hold anything past what
|
||||
#! was kept. It may be the old block, where that is large enough
|
||||
#! already.
|
||||
#! @remarks Where the system gives no memory, the program stops, as
|
||||
#! `raw_allocate` does.
|
||||
@intrinsic
|
||||
pub def raw_resize(pointer: *mut u8, size: u64): *mut u8;
|
||||
|
||||
#! A reference that reads what a pointer points at.
|
||||
#!
|
||||
#! A pointer is an address with no members of its own, so this reaches them, as
|
||||
#! `through(node).next` does, the same as `(*node).next`.
|
||||
#! @tparam T The type pointed at.
|
||||
#! @param pointer The pointer to read through.
|
||||
#! @returns A reference that only reads what the pointer points at.
|
||||
#! @remarks A null pointer stops the program.
|
||||
pub def through<T>(pointer: *T): &T {
|
||||
return &pointer[0];
|
||||
}
|
||||
|
||||
#! A reference that writes what a pointer points at, as `through(node).next =
|
||||
#! null` does.
|
||||
#! @tparam T The type pointed at.
|
||||
#! @param pointer The pointer to write through.
|
||||
#! @returns A reference that writes what the pointer points at.
|
||||
#! @remarks A null pointer stops the program.
|
||||
pub def through<T>(pointer: *mut T): &mut T {
|
||||
return &mut pointer[0];
|
||||
}
|
||||
|
||||
#! A pointer that writes what a reference refers to, as `through` gives a
|
||||
#! reference at what a pointer points at, as `address(node)` is `&mut node as
|
||||
#! *mut node`. Given a place, a call lends it, as `address(x)` does a `var x`.
|
||||
#! @tparam T The type referred to.
|
||||
#! @param value The reference.
|
||||
#! @returns A pointer at what the reference refers to, which keeps nothing alive.
|
||||
pub def address<T>(value: &mut T): *mut T {
|
||||
return value as *mut T;
|
||||
}
|
||||
|
||||
#! A pointer that reads what a reference refers to, as `address(x)` is of a
|
||||
#! `val x`.
|
||||
#! @tparam T The type referred to.
|
||||
#! @param value The reference.
|
||||
#! @returns A pointer at what the reference refers to, which keeps nothing alive.
|
||||
pub def address<T>(value: &T): *T {
|
||||
return value as *T;
|
||||
}
|
||||
|
||||
# The bytes a number of elements take, or more than can be allocated when that
|
||||
# overflows, so the allocation stops the program instead of being too small.
|
||||
#! The bytes a number of elements of a type take.
|
||||
#! @tparam T The type of the elements.
|
||||
#! @param count How many elements.
|
||||
#! @returns Their size in bytes, or the largest `u64` where that overflows, so
|
||||
#! that allocating it stops the program rather than giving too small a
|
||||
#! block.
|
||||
pub def bytes_of<T>(count: u64): u64 {
|
||||
val size := size_of::<T>();
|
||||
if size != 0 && count > 0xFFFFFFFFFFFFFFFF / size {
|
||||
return 0xFFFFFFFFFFFFFFFF;
|
||||
}
|
||||
return count * size;
|
||||
}
|
||||
|
||||
#! Rounds an address up to the next multiple of an alignment.
|
||||
#! @param addr The address to align.
|
||||
#! @param align The alignment, which is a power of two.
|
||||
#! @returns The address, or the next past it that is a multiple of the
|
||||
#! alignment.
|
||||
pub def align(addr: u64, align: u64): u64 {
|
||||
return (addr + (align - 1)) & ~(align - 1);
|
||||
}
|
||||
|
||||
#! Copies bytes from one buffer into another.
|
||||
#! @param dst The first byte to copy to.
|
||||
#! @param src The first byte to copy from.
|
||||
#! @param len How many bytes to copy.
|
||||
#! @returns The destination, `dst`.
|
||||
#! @remarks The buffers may overlap. Either pointer being `null` copies nothing.
|
||||
pub def memcpy(dst: *mut u8, src: *u8, len: u64): *mut u8 {
|
||||
if dst == null || src == null { return dst; }
|
||||
if dst == src || len == 0 { return dst; }
|
||||
if len >= 8 {
|
||||
return (dst as u64) - (src as u64) >= len
|
||||
? copyfwd(dst, src, len)
|
||||
: copybwd(dst, src, len);
|
||||
}
|
||||
|
||||
if len >= 4 {
|
||||
val head := *(src as *u32);
|
||||
val tail := *((src + len - 4) as *u32);
|
||||
*(dst as *mut u32) = head;
|
||||
*((dst + len - 4) as *mut u32) = tail;
|
||||
return dst;
|
||||
}
|
||||
|
||||
if len >= 2 {
|
||||
val head := *(src as *u16);
|
||||
val tail := *((src + len - 2) as *u16);
|
||||
*(dst as *mut u16) = head;
|
||||
*((dst + len - 2) as *mut u16) = tail;
|
||||
return dst;
|
||||
}
|
||||
|
||||
*dst = *src;
|
||||
return dst;
|
||||
}
|
||||
|
||||
#! Sets every byte of a buffer to one value.
|
||||
#! @param dst The first byte to set.
|
||||
#! @param data The value to set each byte to.
|
||||
#! @param len How many bytes to set.
|
||||
#! @returns The destination, `dst`.
|
||||
#! @remarks The bytes are set a word at a time, each word the byte repeated, and
|
||||
#! the last word ends where the buffer does, over what the words before
|
||||
#! it set, so no byte is set alone. A buffer shorter than a word is set
|
||||
#! by two halves of one, which overlap the same way. A `null`
|
||||
#! destination sets nothing.
|
||||
pub def memset(dst: *mut u8, data: u8, len: u64): *mut u8 {
|
||||
if dst == null { return dst; }
|
||||
if len == 0 { return dst; }
|
||||
|
||||
val end := dst + len;
|
||||
# Where vectors are held in registers, 16 bytes at a time, the last ending
|
||||
# where the buffer does.
|
||||
if len >= 32 && lanes_held() {
|
||||
val pattern := u8x16::splat(data);
|
||||
var at := dst;
|
||||
val last := end - 16;
|
||||
while at < last {
|
||||
lanes_apply::<u8, lanes_copy, 16>(at, (&pattern._lanes) as *u8, null, null);
|
||||
at = at + 16;
|
||||
}
|
||||
lanes_apply::<u8, lanes_copy, 16>(last, (&pattern._lanes) as *u8, null, null);
|
||||
return dst;
|
||||
}
|
||||
if len >= 8 {
|
||||
val word := (data as u64) * 0x0101010101010101;
|
||||
var each := dst as *mut u64;
|
||||
val last := each + (len >> 3);
|
||||
while each < last { *each++ = word; }
|
||||
*((end - 8) as *mut u64) = word;
|
||||
return dst;
|
||||
}
|
||||
|
||||
if len >= 4 {
|
||||
val half := (data as u32) * 0x01010101;
|
||||
*(dst as *mut u32) = half;
|
||||
*((end - 4) as *mut u32) = half;
|
||||
return dst;
|
||||
}
|
||||
|
||||
if len >= 2 {
|
||||
val pair := (data as u16) * 0x0101;
|
||||
*(dst as *mut u16) = pair;
|
||||
*((end - 2) as *mut u16) = pair;
|
||||
return dst;
|
||||
}
|
||||
|
||||
*dst = data;
|
||||
return dst;
|
||||
}
|
||||
|
||||
#! Compares the bytes of two buffers, in order, as unsigned numbers.
|
||||
#! @param bpa The first byte of the first buffer.
|
||||
#! @param bpb The first byte of the second buffer.
|
||||
#! @param len How many bytes to compare.
|
||||
#! @retval -1 Where the first buffer orders before the second.
|
||||
#! @retval 0 Where their bytes are the same.
|
||||
#! @retval 1 Where the first buffer orders after the second.
|
||||
#! @remarks Where either is `null`, the pointers themselves are compared.
|
||||
pub def memcmp(bpa: *u8, bpb: *u8, len: u64): i64 {
|
||||
if bpa == null || bpb == null {
|
||||
if bpa < bpb { return -1; }
|
||||
if bpa > bpb { return 1; }
|
||||
return 0;
|
||||
}
|
||||
|
||||
# Whole words first, then what is left a byte at a time, and the word that
|
||||
# differs a byte at a time to say which way. Fewer than eight bytes that are the
|
||||
# same are found so with two words of half or a quarter as many, which may overlap.
|
||||
var p := bpa;
|
||||
var q := bpb;
|
||||
var i := len;
|
||||
# Where vectors are held in registers, 16 bytes at a time, the first that
|
||||
# differs found from the lanes that do.
|
||||
while i >= 16 && lanes_held() {
|
||||
var a: u8x16;
|
||||
var b: u8x16;
|
||||
lanes_apply::<u8, lanes_copy, 16>((&mut a._lanes) as *mut u8, p, null, null);
|
||||
lanes_apply::<u8, lanes_copy, 16>((&mut b._lanes) as *mut u8, q, null, null);
|
||||
val same := a.equal(&b).bits();
|
||||
if same != 0xFFFF {
|
||||
val k := trailing_zeros(~same) as u64;
|
||||
return p[k] < q[k] ? -1 : 1;
|
||||
}
|
||||
p = p + 16;
|
||||
q = q + 16;
|
||||
i = i - 16;
|
||||
}
|
||||
while i >= 8 && *(p as *u64) == *(q as *u64) {
|
||||
p = p + 8;
|
||||
q = q + 8;
|
||||
i = i - 8;
|
||||
}
|
||||
if i >= 4 && i < 8 && *(p as *u32) == *(q as *u32) && *((p + i - 4) as *u32) == *((q + i - 4) as *u32) {
|
||||
return 0;
|
||||
}
|
||||
if i >= 2 && i < 4 && *(p as *u16) == *(q as *u16) && *((p + i - 2) as *u16) == *((q + i - 2) as *u16) {
|
||||
return 0;
|
||||
}
|
||||
while i > 0 {
|
||||
val a := *p++;
|
||||
val b := *q++;
|
||||
if a != b { return a < b ? -1 : 1; }
|
||||
i--;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
# The first place from `from` up to `end` where the bytes hold one byte, or
|
||||
# `end` where none does: sixteen at a time where vectors are held in registers,
|
||||
# the first found from the bits of those that are it, then eight at a time as
|
||||
# words, and the last few as one word read without passing the end.
|
||||
def find_byte(data: *u8, from: u64, end: u64, byte: u8): u64 {
|
||||
var at := from;
|
||||
if lanes_held() {
|
||||
val wanted := u8x16::splat(byte);
|
||||
while at + 16 <= end {
|
||||
var chunk: u8x16;
|
||||
lanes_apply::<u8, lanes_copy, 16>((&mut chunk._lanes) as *mut u8, data + at, null, null);
|
||||
val found := chunk.equal(&wanted).bits();
|
||||
if found != 0 {
|
||||
return at + trailing_zeros(found) as u64;
|
||||
}
|
||||
at += 16;
|
||||
}
|
||||
}
|
||||
val wanted := swar::repeat(byte);
|
||||
while at + 8 <= end {
|
||||
val word: swar::bytes8 = swar::load(data + at) ^ wanted;
|
||||
val found := word.zero();
|
||||
return at + found.first() if found.any();
|
||||
at += 8;
|
||||
}
|
||||
if at < end {
|
||||
val word: swar::bytes8 = swar::load_last(data + at, end - at) ^ wanted;
|
||||
val found: swar::mask8 = word.zero() & swar::mask8::leading(end - at);
|
||||
return at + found.first() if found.any();
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
# The last place from `from` up to `end` where the bytes hold one byte, or
|
||||
# `end` where none does: eight at a time as words from the end back, and the
|
||||
# first few as one word read without passing their beginning.
|
||||
def find_last_byte(data: *u8, from: u64, end: u64, byte: u8): u64 {
|
||||
val wanted := swar::repeat(byte);
|
||||
var at := end;
|
||||
while at >= from + 8 {
|
||||
val word: swar::bytes8 = swar::load(data + at - 8) ^ wanted;
|
||||
val found := word.zero();
|
||||
return at - 8 + found.last() if found.any();
|
||||
at -= 8;
|
||||
}
|
||||
if at > from {
|
||||
val word: swar::bytes8 = swar::load_last(data + from, at - from) ^ wanted;
|
||||
val found: swar::mask8 = word.zero() & swar::mask8::leading(at - from);
|
||||
return from + found.last() if found.any();
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
# How many of the bytes from `from` up to `end` are one byte: eight at a time
|
||||
# as words, and the last few as one word read without passing the end.
|
||||
def count_byte(data: *u8, from: u64, end: u64, byte: u8): u64 {
|
||||
val wanted := swar::repeat(byte);
|
||||
var count: u64 = 0;
|
||||
var at := from;
|
||||
while at + 8 <= end {
|
||||
val word: swar::bytes8 = swar::load(data + at) ^ wanted;
|
||||
count += word.zero().count();
|
||||
at += 8;
|
||||
}
|
||||
if at < end {
|
||||
val word: swar::bytes8 = swar::load_last(data + at, end - at) ^ wanted;
|
||||
val found: swar::mask8 = word.zero() & swar::mask8::leading(end - at);
|
||||
count += found.count();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
# Copies at least a word from the first byte up, a word at a time, each read before
|
||||
# it is written, so a destination below the source never writes over what is left
|
||||
# to read. The last word ends where the buffers do, read before anything is written.
|
||||
def copyfwd(dst: *mut u8, src: *u8, len: u64): *mut u8 {
|
||||
# Where vectors are held in registers, 16 bytes at a time, the same way.
|
||||
if len >= 32 && lanes_held() {
|
||||
var last: u8x16;
|
||||
lanes_apply::<u8, lanes_copy, 16>((&mut last._lanes) as *mut u8, src + len - 16, null, null);
|
||||
var to := dst;
|
||||
var from := src;
|
||||
val end := dst + len - 16;
|
||||
while to < end {
|
||||
lanes_apply::<u8, lanes_copy, 16>(to, from, null, null);
|
||||
to = to + 16;
|
||||
from = from + 16;
|
||||
}
|
||||
lanes_apply::<u8, lanes_copy, 16>(end, (&last._lanes) as *u8, null, null);
|
||||
return dst;
|
||||
}
|
||||
val tail := *((src + len - 8) as *u64);
|
||||
var dw := dst as *mut u64;
|
||||
var sw := src as *u64;
|
||||
val last := dw + (len >> 3);
|
||||
while dw < last { *dw++ = *sw++; }
|
||||
*((dst + len - 8) as *mut u64) = tail;
|
||||
return dst;
|
||||
}
|
||||
|
||||
# Copies at least a word from the last byte down, so a destination above the source
|
||||
# never writes over what is left. The first word begins where the buffers do, read
|
||||
# before anything is written.
|
||||
def copybwd(dst: *mut u8, src: *u8, len: u64): *mut u8 {
|
||||
if len >= 32 && lanes_held() {
|
||||
var first: u8x16;
|
||||
lanes_apply::<u8, lanes_copy, 16>((&mut first._lanes) as *mut u8, src, null, null);
|
||||
var to := dst + len;
|
||||
var from := src + len;
|
||||
while to > dst + 16 {
|
||||
to = to - 16;
|
||||
from = from - 16;
|
||||
lanes_apply::<u8, lanes_copy, 16>(to, from, null, null);
|
||||
}
|
||||
lanes_apply::<u8, lanes_copy, 16>(dst, (&first._lanes) as *u8, null, null);
|
||||
return dst;
|
||||
}
|
||||
val head := *(src as *u64);
|
||||
var dw := (dst + len) as *mut u64;
|
||||
var sw := (src + len) as *u64;
|
||||
val first := dw - (len >> 3);
|
||||
while dw > first { *--dw = *--sw; }
|
||||
*(dst as *mut u64) = head;
|
||||
return dst;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#! @file box.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `box`, one value on the heap, which it owns alone, as C++'s
|
||||
#! `unique_ptr` and Rust's `Box`: for a value that outlives the scope making it
|
||||
#! without being copied, one too large for a frame, or a structure linking to
|
||||
#! more of itself.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! One value on the heap, which the box owns alone and closes where the box
|
||||
#! closes.
|
||||
#!
|
||||
#! A box is one word, the value's address, which is never null, so a
|
||||
#! `maybe<box<T>>` is one word too, holding `nothing` where the address is
|
||||
#! null. Moving a box moves the address, never the value, and leaves the box
|
||||
#! moved from empty: closing it again does nothing, and reaching its value
|
||||
#! reaches through `null`.
|
||||
#! @tparam T What it holds.
|
||||
pub struct box<T> : owning, moveable {
|
||||
var _at: &mut T;
|
||||
}
|
||||
|
||||
#! Moves a value to the heap.
|
||||
#! @param value The value, which the box then owns.
|
||||
#! @returns The box.
|
||||
pub def box<T>::new(value: T): box<T> {
|
||||
val size := size_of::<T>();
|
||||
val at := allocate_for::<T>(size == 0 ? 1 : size) as *mut T;
|
||||
at[0] = move(&mut value);
|
||||
return box::<T> { _at = through(at) };
|
||||
}
|
||||
|
||||
#! Lends the value a box holds.
|
||||
#! @param this The box.
|
||||
#! @returns The value, good while the box holds it.
|
||||
pub def box<T>::get(&this): &T {
|
||||
return this._at;
|
||||
}
|
||||
|
||||
#! Lends the value a box holds, to be changed.
|
||||
#! @param this The box.
|
||||
#! @returns The value, good while the box holds it.
|
||||
pub def box<T>::get(&mut this): &mut T {
|
||||
return this._at;
|
||||
}
|
||||
|
||||
#! Whether a box holds a value, which one moved from or taken from does not.
|
||||
#! @param this The box.
|
||||
#! @returns Whether it does.
|
||||
pub def box<T>::holds(&this): bool {
|
||||
return this._at as *T != null;
|
||||
}
|
||||
|
||||
#! Moves the value out of a box, giving back its memory.
|
||||
#! @param this The box, which is empty after.
|
||||
#! @returns The value.
|
||||
pub def box<T>::take(&mut this): T {
|
||||
val at := this._at as *mut T;
|
||||
var made := move(through(at));
|
||||
raw_release(at as *mut u8);
|
||||
(this as *mut u64)[0] = 0;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Closes the value a box holds and gives back its memory.
|
||||
#! @param this The box, which is empty after, so closing it again does
|
||||
#! nothing.
|
||||
pub def box<T>::close(&mut this): void {
|
||||
val at := this._at as *mut T;
|
||||
return if at == null;
|
||||
(this as *mut u64)[0] = 0;
|
||||
close(through(at));
|
||||
raw_release(at as *mut u8);
|
||||
}
|
||||
|
||||
#! Moves a box, leaving the one moved from empty.
|
||||
#! @param other The box to move from.
|
||||
#! @returns The box holding what it held.
|
||||
pub def box<T>::move_of(other: &mut box<T>): box<T> {
|
||||
val made := box::<T> { _at = other._at };
|
||||
(other as *mut u64)[0] = 0;
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
#! @file reflect.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains compile-time reflection: `decl`, which describes a declaration of
|
||||
#! the program, and the intrinsics that find declarations, walk what they
|
||||
#! declare, read their attributes, reach what they name, and report errors while
|
||||
#! compiling.
|
||||
|
||||
module core;
|
||||
|
||||
#! Describes a declaration of the program, as the compiler found it.
|
||||
#!
|
||||
#! A `decl` is plain data, made only by the intrinsics below, the way
|
||||
#! `call_site()` makes a `site`. Walked by `for const`, each one is known while
|
||||
#! compiling, so `value_of(d)` and `x.(d)` reach what it declares as though its
|
||||
#! name were written.
|
||||
pub struct decl {
|
||||
pub val id: u32; #! Which declaration. Meaningful only while compiling.
|
||||
pub val kind: target; #! What it is, as the bit `@usage` checks attributes against.
|
||||
pub val name: strview; #! As written: `interns_keywords`, `push`, `red`.
|
||||
pub val path: strview; #! Qualified: `sakura::analyzer::interns_keywords`.
|
||||
pub val at: site; #! Where it is declared.
|
||||
pub val exported: bool; #! Whether it is `pub`.
|
||||
pub val generic: bool; #! Whether it has type parameters of its own.
|
||||
}
|
||||
|
||||
#! Gives every declaration outside a function in the program, including methods,
|
||||
#! a type's own constants and variables, and nested types, in the order the
|
||||
#! files were given and then the order they are written in.
|
||||
#!
|
||||
#! Only those the calling module could name are given, and those carrying an
|
||||
#! attribute whose type the calling module declares, since writing that
|
||||
#! attribute is consent for the module owning it to find and use what it marks.
|
||||
#! @returns The declarations, which are known while compiling.
|
||||
@intrinsic
|
||||
pub def declarations(): span<decl>;
|
||||
|
||||
#! Gives the declaration of a type, as `decl_of::<list<i64>>()`.
|
||||
#! @tparam T The type, which is an instance where it is generic.
|
||||
#! @returns Its declaration.
|
||||
@intrinsic
|
||||
pub def decl_of<T>(): decl;
|
||||
|
||||
#! Gives what a type declares: the fields of a struct or union, with the fields
|
||||
#! of a spread in its place, the members of an enum, or what a trait requires,
|
||||
#! and then the methods, properties, constants, variables, and nested types
|
||||
#! declared on it.
|
||||
#! @param d The declaration of a type.
|
||||
#! @returns The members, in the order they are declared.
|
||||
@intrinsic
|
||||
pub def members_of(d: decl): span<decl>;
|
||||
|
||||
#! Gives the type a field, member, method, or a type's own declaration belongs
|
||||
#! to.
|
||||
#! @param d A declaration belonging to a type.
|
||||
#! @returns The declaration of the type it belongs to.
|
||||
@intrinsic
|
||||
pub def owner_of(d: decl): decl;
|
||||
|
||||
#! Gives the declarations of every attribute written on a declaration, in the
|
||||
#! order they are written, each a constant whose value `value_of` reads.
|
||||
#! @param d The declaration the attributes are written on.
|
||||
#! @returns The attributes, each a constant whose value `value_of` reads.
|
||||
@intrinsic
|
||||
pub def attributes_of(d: decl): span<decl>;
|
||||
|
||||
#! Gives the values of the `@A` attributes written on a declaration: often none,
|
||||
#! and at most one unless the usage of `A` allows `many`. An alias also has
|
||||
#! those of what it aliases, when the usage of `A` says `through`.
|
||||
#! @tparam A The type of attribute to look for.
|
||||
#! @param d The declaration the attributes are written on.
|
||||
#! @returns Their values, which are known while compiling.
|
||||
@intrinsic
|
||||
pub def attached<A>(d: decl): span<A> where A: attribute;
|
||||
|
||||
#! Stands for what a declaration names, as though its name were written here: a
|
||||
#! function, a constant, a member of an enum, a global variable, or an
|
||||
#! attribute's value.
|
||||
#!
|
||||
#! A generic function is given its type arguments after the call, as
|
||||
#! `value_of(d)::<i64>`.
|
||||
#! @param d The declaration, which must be known while compiling.
|
||||
#! @remarks Its type is that of what it names, rather than the `void` it is
|
||||
#! declared with.
|
||||
@intrinsic
|
||||
pub def value_of(d: decl): void;
|
||||
|
||||
#! Gives the parameters of a function, including `this`, in the order they are
|
||||
#! declared. `type_of(p)` is the type of each, written wherever a type is, as
|
||||
#! `var fixture: type_of(params_of(d)[1]);`. Anything but a function has none.
|
||||
#! @param d The declaration of a function.
|
||||
#! @returns Its parameters, or none where it is not a function.
|
||||
@intrinsic
|
||||
pub def params_of(d: decl): span<decl>;
|
||||
|
||||
#! Gives a type's name as errors spell it, without the modules of the types it
|
||||
#! names, as `list<i64>` or `&mut position`.
|
||||
#! @tparam T The type to name.
|
||||
#! @returns Its name, which is known while compiling.
|
||||
@intrinsic
|
||||
pub def name_of<T>(): strview;
|
||||
|
||||
#! Gives a type's name with the module of each type it names, as
|
||||
#! `std::containers::dict<core::string, game::item>` or `&mut game::position`,
|
||||
#! which no two types share, as `decl.path` qualifies `decl.name`.
|
||||
#! @tparam T The type to name.
|
||||
#! @returns Its name, which is known while compiling.
|
||||
@intrinsic
|
||||
pub def path_of<T>(): strview;
|
||||
|
||||
#! Reports an error while compiling, where checking reaches the call, which a
|
||||
#! branch of `if const` that is not taken never does.
|
||||
#! @param text What the error says, as text known while compiling, which may
|
||||
#! be worked out, as interpolated text is.
|
||||
#! @param at Where the error is, which a library gives as the `at` of a
|
||||
#! declaration it was handed, to point at its user's code.
|
||||
@intrinsic
|
||||
pub def compile_error(text: strview, at: site = call_site()): void;
|
||||
@@ -0,0 +1,286 @@
|
||||
#! @file maybe.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the properties and methods of `maybe`, and `something`, which wraps
|
||||
#! a value in one.
|
||||
#!
|
||||
#! `maybe`, which holds a value or `nothing`, is among the types the syntax
|
||||
#! makes, which the compiler declares itself, as it does `i64`: `none` comes
|
||||
#! first, so a `maybe` left without a value holds nothing. A value converts to
|
||||
#! a `maybe` of its type wherever one is wanted, and it is read by `is`,
|
||||
#! `match`, or `else`, as `val x := find(key) else { return; };`. `nothing` is
|
||||
#! apart from `void`, the value of what gives nothing, so `maybe<void>` tells a
|
||||
#! value missing from the value of `void`.
|
||||
#!
|
||||
#! The methods reading the value, as `unwrap`, move it out of what can be
|
||||
#! written, as `move` does, so a `maybe` of what closes is left holding
|
||||
#! nothing, and copy it out of what is only read, which a value that closes
|
||||
#! refuses. Those making another value of it, as `map`, move it in, as an
|
||||
#! iterator's adapters do: `as_ref` lends them what one that is only read
|
||||
#! holds.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Whether it holds a value.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns Whether it does.
|
||||
pub val maybe<T>::is_some: bool { get => this is some; }
|
||||
|
||||
#! Whether it holds nothing.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns Whether it does.
|
||||
pub val maybe<T>::is_none: bool { get => this is none; }
|
||||
|
||||
#! Whether it holds a value a test passes.
|
||||
#! @tparam F The test.
|
||||
#! @param this The `maybe`.
|
||||
#! @param test The test, given a reference to the value.
|
||||
#! @returns Whether it holds one that passes.
|
||||
pub def maybe<T>::is_some_and<F>(&this, test: F): bool
|
||||
where F: invokable<def(&T): bool>
|
||||
{
|
||||
return this is some(&value) && test(value);
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `move` moves it, so one that closes
|
||||
#! leaves it holding nothing. It stops the program where it holds nothing.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns The value.
|
||||
pub def maybe<T>::unwrap(&mut this): T {
|
||||
var held := move(this);
|
||||
return move(value) if held is some(&mut value);
|
||||
fault("A `maybe` holding nothing was unwrapped.");
|
||||
}
|
||||
|
||||
#! Gives a copy of the value it holds, which a value that closes refuses. It
|
||||
#! stops the program where it holds nothing.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns The value.
|
||||
pub def maybe<T>::unwrap(&this): T {
|
||||
if const T is closeable {
|
||||
copied::<T>();
|
||||
} else {
|
||||
return value if this is some(value);
|
||||
}
|
||||
fault("A `maybe` holding nothing was unwrapped.");
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `unwrap` moves it. It stops the
|
||||
#! program where it holds nothing, saying why.
|
||||
#! @param this The `maybe`.
|
||||
#! @param why What went wrong, where it holds nothing.
|
||||
#! @returns The value.
|
||||
pub def maybe<T>::expect(&mut this, why: strview): T {
|
||||
var held := move(this);
|
||||
return move(value) if held is some(&mut value);
|
||||
fault(why);
|
||||
}
|
||||
|
||||
#! Gives a copy of the value it holds, which a value that closes refuses. It
|
||||
#! stops the program where it holds nothing, saying why.
|
||||
#! @param this The `maybe`.
|
||||
#! @param why What went wrong, where it holds nothing.
|
||||
#! @returns The value.
|
||||
pub def maybe<T>::expect(&this, why: strview): T {
|
||||
if const T is closeable {
|
||||
copied::<T>();
|
||||
} else {
|
||||
return value if this is some(value);
|
||||
}
|
||||
fault(why);
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `unwrap` moves it, or a fallback
|
||||
#! where it holds nothing.
|
||||
#! @param this The `maybe`.
|
||||
#! @param fallback The value given where it holds nothing.
|
||||
#! @returns The value, or the fallback.
|
||||
pub def maybe<T>::unwrap_or(&mut this, fallback: T): T {
|
||||
var held := move(this);
|
||||
return move(value) if held is some(&mut value);
|
||||
return move(&mut fallback);
|
||||
}
|
||||
|
||||
#! Gives a copy of the value it holds, which a value that closes refuses, or a
|
||||
#! fallback where it holds nothing.
|
||||
#! @param this The `maybe`.
|
||||
#! @param fallback The value given where it holds nothing.
|
||||
#! @returns The value, or the fallback.
|
||||
pub def maybe<T>::unwrap_or(&this, fallback: T): T {
|
||||
if const T is closeable {
|
||||
copied::<T>();
|
||||
} else {
|
||||
return value if this is some(value);
|
||||
}
|
||||
return move(&mut fallback);
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `unwrap` moves it, or what a
|
||||
#! function makes where it holds nothing, which is called only then.
|
||||
#! @tparam F The function.
|
||||
#! @param this The `maybe`.
|
||||
#! @param make The function, making the value where it holds nothing.
|
||||
#! @returns The value, or what the function made.
|
||||
pub def maybe<T>::unwrap_or_else<F>(&mut this, make: F): T where F: invokable<def(): T> {
|
||||
var held := move(this);
|
||||
return move(value) if held is some(&mut value);
|
||||
return make();
|
||||
}
|
||||
|
||||
#! Takes what it holds, leaving it holding nothing, whatever the value is.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns What it held.
|
||||
pub def maybe<T>::take(&mut this): maybe<T> {
|
||||
var made := move(this);
|
||||
this = nothing {};
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Puts a value in it, in place of what it held.
|
||||
#! @param this The `maybe`.
|
||||
#! @param value The value it holds from now on.
|
||||
#! @returns What it held before.
|
||||
pub def maybe<T>::replace(&mut this, value: T): maybe<T> {
|
||||
var made := move(this);
|
||||
this = maybe::<T> { some = move(&mut value) };
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Lends what it holds: a reference to the value, or nothing.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns Maybe a reference to the value; otherwise, `nothing`.
|
||||
pub def maybe<T>::as_ref(&this): maybe<&T> {
|
||||
return maybe::<&T> { some = value } if this is some(&value);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Lends what it holds to be written: a reference to the value, or nothing.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns Maybe a reference to the value; otherwise, `nothing`.
|
||||
pub def maybe<T>::as_mut(&mut this): maybe<&mut T> {
|
||||
return maybe::<&mut T> { some = value } if this is some(&mut value);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Makes a value of the value it holds, which a function is given, moved in.
|
||||
#! @tparam U What the function makes.
|
||||
#! @tparam F The function.
|
||||
#! @param this The `maybe`, moved in as `unwrap` moves it.
|
||||
#! @param f The function, called on the value where it holds one.
|
||||
#! @returns Maybe what the function made; otherwise, `nothing`.
|
||||
pub def maybe<T>::map<U, F>(&mut this, f: F): maybe<U> where F: invokable<def(T): U> {
|
||||
var held := move(this);
|
||||
return maybe::<U> { some = f(move(value)) } if held is some(&mut value);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Gives what a function makes of the value it holds, which may be nothing:
|
||||
#! the next step of work that may find nothing.
|
||||
#! @tparam U What the function may make.
|
||||
#! @tparam F The function.
|
||||
#! @param this The `maybe`, moved in as `unwrap` moves it.
|
||||
#! @param f The function, called on the value where it holds one.
|
||||
#! @returns What the function gave; otherwise, `nothing`.
|
||||
pub def maybe<T>::and_then<U, F>(&mut this, f: F): maybe<U> where F: invokable<def(T): maybe<U>> {
|
||||
var held := move(this);
|
||||
return f(move(value)) if held is some(&mut value);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Keeps the value it holds where a test passes it.
|
||||
#! @tparam F The test.
|
||||
#! @param this The `maybe`, moved in as `unwrap` moves it.
|
||||
#! @param test The test, given a reference to the value.
|
||||
#! @returns Maybe the value; otherwise, `nothing` where it fails the test.
|
||||
pub def maybe<T>::filter<F>(&mut this, test: F): maybe<T> where F: invokable<def(&T): bool> {
|
||||
var held := move(this);
|
||||
return held if held is some(&value) && test(value);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Gives what it holds where it holds a value, and another `maybe` otherwise.
|
||||
#! @param this The `maybe`, moved in as `unwrap` moves it.
|
||||
#! @param other What is given where it holds nothing.
|
||||
#! @returns It, or the other.
|
||||
pub def maybe<T>::or(&mut this, other: maybe<T>): maybe<T> {
|
||||
var held := move(this);
|
||||
return held if held is some;
|
||||
return move(&mut other);
|
||||
}
|
||||
|
||||
#! Gives what it holds where it holds a value, and what a function makes
|
||||
#! otherwise, which is called only then.
|
||||
#! @tparam F The function.
|
||||
#! @param this The `maybe`, moved in as `unwrap` moves it.
|
||||
#! @param make The function, making what is given where it holds nothing.
|
||||
#! @returns It, or what the function made.
|
||||
pub def maybe<T>::or_else<F>(&mut this, make: F): maybe<T> where F: invokable<def(): maybe<T>> {
|
||||
var held := move(this);
|
||||
return held if held is some;
|
||||
return make();
|
||||
}
|
||||
|
||||
#! Makes a `result` of it: the value it holds, or an error where it holds
|
||||
#! nothing.
|
||||
#! @tparam E The error's type.
|
||||
#! @param this The `maybe`, moved in as `unwrap` moves it.
|
||||
#! @param error The error, where it holds nothing.
|
||||
#! @returns The result.
|
||||
pub def maybe<T>::ok_or<E>(&mut this, error: E): result<T, E> {
|
||||
var held := move(this);
|
||||
return result::<T, E> { value = move(value) } if held is some(&mut value);
|
||||
return result::<T, E> { error = move(&mut error) };
|
||||
}
|
||||
|
||||
#! Whether it holds what another does: both nothing, or equal values, as `==`
|
||||
#! compares them.
|
||||
#! @param this The `maybe`.
|
||||
#! @param other The other.
|
||||
#! @returns Whether they are equal.
|
||||
#! @remarks A `maybe` of a type that is not `equatable` is an error where it is
|
||||
#! compared.
|
||||
pub def maybe<T>::equals(&this, other: &maybe<T>): bool {
|
||||
if this is some(&mine) {
|
||||
return other is some(&theirs) && equals::<T>(mine, theirs);
|
||||
}
|
||||
return other is none;
|
||||
}
|
||||
|
||||
#! Hashes what it holds, so a `maybe` holding nothing hashes apart from one
|
||||
#! holding a value.
|
||||
#! @param this The `maybe`.
|
||||
#! @returns The hash.
|
||||
#! @remarks A `maybe` of a type that is not `hashable` is an error where it is
|
||||
#! hashed.
|
||||
pub def maybe<T>::hash(&this): u64 {
|
||||
return mix(1, hash::<T>(value)) if this is some(&value);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Builds a copy of a `maybe`, holding a copy of its value, as `copy` makes it.
|
||||
#! @param other The `maybe` to copy.
|
||||
#! @returns The copy.
|
||||
pub def maybe<T>::copy_of(other: &maybe<T>): maybe<T> {
|
||||
return maybe::<T> { some = copy::<T>(value) } if other is some(&value);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Refuses a copy of a value that closes, which a `maybe` or a `result` only
|
||||
#! read would give of what it holds.
|
||||
#! @tparam T The type of what it holds.
|
||||
def copied<T>(): void {
|
||||
if const T is closeable {
|
||||
compile_error("A `maybe` or `result` that is only read gives a copy of what it holds, which a value that closes refuses: call it on one that can be written, as a `var`, which moves the value out.");
|
||||
}
|
||||
}
|
||||
|
||||
#! Wraps a value in a `maybe`, holding it.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param data The value to hold.
|
||||
#! @returns A `maybe` holding the value, as `some`.
|
||||
pub def something<T>(data: T): maybe<T> {
|
||||
return maybe::<T> { some = move(&mut data) };
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
#! @file result.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the properties and methods of `result`, and `ok` and `err`, which
|
||||
#! make one holding a value or an error.
|
||||
#!
|
||||
#! `result`, which holds either the value an operation gave or the error that
|
||||
#! stopped it, is among the types the syntax makes, which the compiler declares
|
||||
#! itself. It must be handled where it is made, since letting it go would lose
|
||||
#! the error it may hold: by `match`, by `is`, or by `else`, as
|
||||
#! `val f := open(path) else (e) { return e; };`.
|
||||
#!
|
||||
#! The methods reading what it holds, as `unwrap`, move it out of what can be
|
||||
#! written, as `move` does, and copy it out of what is only read, which a value
|
||||
#! that closes refuses. Those making another `result` of it, as `map`, move it
|
||||
#! in, as an iterator's adapters do: `as_ref` lends them what one that is only
|
||||
#! read holds. Each makes what it gives by naming the field, so a `result` whose
|
||||
#! value and error are of one type is told apart.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Makes a result holding a value.
|
||||
#! @param value The value to hold.
|
||||
#! @returns The result, holding the value.
|
||||
pub def result<T, E>::ok(value: T): result<T, E> {
|
||||
return result::<T, E> { value = move(&mut value) };
|
||||
}
|
||||
|
||||
#! Makes a result holding an error.
|
||||
#! @param error The error to hold.
|
||||
#! @returns The result, holding the error.
|
||||
pub def result<T, E>::err(error: E): result<T, E> {
|
||||
return result::<T, E> { error = move(&mut error) };
|
||||
}
|
||||
|
||||
#! Whether it holds the value, where the work succeeded.
|
||||
#! @param this The result.
|
||||
#! @returns Whether it does.
|
||||
pub val result<T, E>::is_ok: bool { get => this is value; }
|
||||
|
||||
#! Whether it holds the error, where the work failed.
|
||||
#! @param this The result.
|
||||
#! @returns Whether it does.
|
||||
pub val result<T, E>::is_err: bool { get => this is error; }
|
||||
|
||||
#! Whether it holds a value a test passes.
|
||||
#! @tparam F The test.
|
||||
#! @param this The result.
|
||||
#! @param test The test, given a reference to the value.
|
||||
#! @returns Whether it holds one that passes.
|
||||
pub def result<T, E>::is_ok_and<F>(&this, test: F): bool
|
||||
where F: invokable<def(&T): bool>
|
||||
{
|
||||
return this is value(&held) && test(held);
|
||||
}
|
||||
|
||||
#! Whether it holds an error a test passes.
|
||||
#! @tparam F The test.
|
||||
#! @param this The result.
|
||||
#! @param test The test, given a reference to the error.
|
||||
#! @returns Whether it holds one that passes.
|
||||
pub def result<T, E>::is_err_and<F>(&this, test: F): bool
|
||||
where F: invokable<def(&E): bool>
|
||||
{
|
||||
return this is error(&held) && test(held);
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `move` moves it. It stops the program
|
||||
#! where it holds an error.
|
||||
#! @param this The result.
|
||||
#! @returns The value.
|
||||
pub def result<T, E>::unwrap(&mut this): T {
|
||||
var held := move(this);
|
||||
return move(got) if held is value(&mut got);
|
||||
fault("A `result` holding an error was unwrapped.");
|
||||
}
|
||||
|
||||
#! Gives a copy of the value it holds, which a value that closes refuses. It
|
||||
#! stops the program where it holds an error.
|
||||
#! @param this The result.
|
||||
#! @returns The value.
|
||||
pub def result<T, E>::unwrap(&this): T {
|
||||
if const T is closeable {
|
||||
copied::<T>();
|
||||
} else {
|
||||
return got if
|
||||
this is value(got);
|
||||
}
|
||||
fault("A `result` holding an error was unwrapped.");
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `unwrap` moves it. It stops the
|
||||
#! program where it holds an error, saying why.
|
||||
#! @param this The result.
|
||||
#! @param why What went wrong, where it holds an error.
|
||||
#! @returns The value.
|
||||
pub def result<T, E>::expect(&mut this, why: strview): T {
|
||||
var held := move(this);
|
||||
return move(got) if
|
||||
held is value(&mut got);
|
||||
fault(why);
|
||||
}
|
||||
|
||||
#! Gives a copy of the value it holds, which a value that closes refuses. It
|
||||
#! stops the program where it holds an error, saying why.
|
||||
#! @param this The result.
|
||||
#! @param why What went wrong, where it holds an error.
|
||||
#! @returns The value.
|
||||
pub def result<T, E>::expect(&this, why: strview): T {
|
||||
if const T is closeable {
|
||||
copied::<T>();
|
||||
} else {
|
||||
return got if
|
||||
this is value(got);
|
||||
}
|
||||
fault(why);
|
||||
}
|
||||
|
||||
#! Gives the error it holds, moved out as `move` moves it. It stops the program
|
||||
#! where it holds a value.
|
||||
#! @param this The result.
|
||||
#! @returns The error.
|
||||
pub def result<T, E>::unwrap_err(&mut this): E {
|
||||
var held := move(this);
|
||||
return move(got) if
|
||||
held is error(&mut got);
|
||||
fault("A `result` holding a value was unwrapped for its error.");
|
||||
}
|
||||
|
||||
#! Gives a copy of the error it holds, which an error that closes refuses. It
|
||||
#! stops the program where it holds a value.
|
||||
#! @param this The result.
|
||||
#! @returns The error.
|
||||
pub def result<T, E>::unwrap_err(&this): E {
|
||||
if const E is closeable {
|
||||
copied::<E>();
|
||||
} else {
|
||||
return got if
|
||||
this is error(got);
|
||||
}
|
||||
fault("A `result` holding a value was unwrapped for its error.");
|
||||
}
|
||||
|
||||
#! Gives the error it holds, moved out as `unwrap_err` moves it. It stops the
|
||||
#! program where it holds a value, saying why.
|
||||
#! @param this The result.
|
||||
#! @param why What went wrong, where it holds a value.
|
||||
#! @returns The error.
|
||||
pub def result<T, E>::expect_err(&mut this, why: strview): E {
|
||||
var held := move(this);
|
||||
return move(got) if
|
||||
held is error(&mut got);
|
||||
fault(why);
|
||||
}
|
||||
|
||||
#! Gives a copy of the error it holds, which an error that closes refuses. It
|
||||
#! stops the program where it holds a value, saying why.
|
||||
#! @param this The result.
|
||||
#! @param why What went wrong, where it holds a value.
|
||||
#! @returns The error.
|
||||
pub def result<T, E>::expect_err(&this, why: strview): E {
|
||||
if const E is closeable {
|
||||
copied::<E>();
|
||||
} else {
|
||||
return got if
|
||||
this is error(got);
|
||||
}
|
||||
fault(why);
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `unwrap` moves it, or a fallback
|
||||
#! where it holds an error.
|
||||
#! @param this The result.
|
||||
#! @param fallback The value given where it holds an error.
|
||||
#! @returns The value, or the fallback.
|
||||
pub def result<T, E>::unwrap_or(&mut this, fallback: T): T {
|
||||
var held := move(this);
|
||||
return move(got) if
|
||||
held is value(&mut got);
|
||||
return move(&mut fallback);
|
||||
}
|
||||
|
||||
#! Gives a copy of the value it holds, which a value that closes refuses, or a
|
||||
#! fallback where it holds an error.
|
||||
#! @param this The result.
|
||||
#! @param fallback The value given where it holds an error.
|
||||
#! @returns The value, or the fallback.
|
||||
pub def result<T, E>::unwrap_or(&this, fallback: T): T {
|
||||
if const T is closeable {
|
||||
copied::<T>();
|
||||
} else {
|
||||
return got if
|
||||
this is value(got);
|
||||
}
|
||||
return move(&mut fallback);
|
||||
}
|
||||
|
||||
#! Gives the value it holds, moved out as `unwrap` moves it, or what a function
|
||||
#! makes of the error, which it is called on only then.
|
||||
#! @tparam F The function.
|
||||
#! @param this The result.
|
||||
#! @param make The function, given the error, moved out.
|
||||
#! @returns The value, or what the function made.
|
||||
pub def result<T, E>::unwrap_or_else<F>(&mut this, make: F): T where F: invokable<def(E): T> {
|
||||
var held := move(this);
|
||||
return match held {
|
||||
value(&mut got) => move(got),
|
||||
error(&mut bad) => make(move(bad))
|
||||
};
|
||||
}
|
||||
|
||||
#! Lends what it holds: a reference to the value or to the error.
|
||||
#! @param this The result.
|
||||
#! @returns The result of the references.
|
||||
pub def result<T, E>::as_ref(&this): result<&T, &E> {
|
||||
return match this {
|
||||
value(&got) => result::<&T, &E> { value = got },
|
||||
error(&bad) => result::<&T, &E> { error = bad }
|
||||
};
|
||||
}
|
||||
|
||||
#! Lends what it holds to be written: a reference to the value or to the
|
||||
#! error.
|
||||
#! @param this The result.
|
||||
#! @returns The result of the references.
|
||||
pub def result<T, E>::as_mut(&mut this): result<&mut T, &mut E> {
|
||||
return match this {
|
||||
value(&mut got) => result::<&mut T, &mut E> { value = got },
|
||||
error(&mut bad) => result::<&mut T, &mut E> { error = bad }
|
||||
};
|
||||
}
|
||||
|
||||
#! Makes a value of the value it holds, which a function is given, moved in,
|
||||
#! keeping the error it holds otherwise.
|
||||
#! @tparam U What the function makes.
|
||||
#! @tparam F The function.
|
||||
#! @param this The result, moved in as `unwrap` moves it.
|
||||
#! @param f The function, called on the value where it holds one.
|
||||
#! @returns The result of what the function made, or of the error.
|
||||
pub def result<T, E>::map<U, F>(&mut this, f: F): result<U, E>
|
||||
where F: invokable<def(T): U>
|
||||
{
|
||||
var held := move(this);
|
||||
return match held {
|
||||
value(&mut got) => result::<U, E> { value = f(move(got)) },
|
||||
error(&mut bad) => result::<U, E> { error = move(bad) }
|
||||
};
|
||||
}
|
||||
|
||||
#! Makes another error of the error it holds, which a function is given, moved
|
||||
#! in, keeping the value it holds otherwise.
|
||||
#! @tparam D What the function makes.
|
||||
#! @tparam F The function.
|
||||
#! @param this The result, moved in as `unwrap` moves it.
|
||||
#! @param f The function, called on the error where it holds one.
|
||||
#! @returns The result of the value, or of what the function made.
|
||||
pub def result<T, E>::map_err<D, F>(&mut this, f: F): result<T, D>
|
||||
where F: invokable<def(E): D>
|
||||
{
|
||||
var held := move(this);
|
||||
return match held {
|
||||
value(&mut got) => result::<T, D> { value = move(got) },
|
||||
error(&mut bad) => result::<T, D> { error = f(move(bad)) }
|
||||
};
|
||||
}
|
||||
|
||||
#! Gives what a function makes of the value it holds, which may fail too: the
|
||||
#! next step of work that may fail, keeping the error it holds otherwise.
|
||||
#! @tparam U What the function may make.
|
||||
#! @tparam F The function.
|
||||
#! @param this The result, moved in as `unwrap` moves it.
|
||||
#! @param f The function, called on the value where it holds one.
|
||||
#! @returns What the function gave, or the result of the error.
|
||||
pub def result<T, E>::and_then<U, F>(&mut this, f: F): result<U, E>
|
||||
where F: invokable<def(T): result<U, E>>
|
||||
{
|
||||
var held := move(this);
|
||||
return match held {
|
||||
value(&mut got) => f(move(got)),
|
||||
error(&mut bad) => result::<U, E> { error = move(bad) }
|
||||
};
|
||||
}
|
||||
|
||||
#! Gives what a function makes of the error it holds, which may recover from
|
||||
#! it, keeping the value it holds otherwise.
|
||||
#! @tparam D The error of what the function makes.
|
||||
#! @tparam F The function.
|
||||
#! @param this The result, moved in as `unwrap` moves it.
|
||||
#! @param f The function, called on the error where it holds one.
|
||||
#! @returns The result of the value, or what the function gave.
|
||||
pub def result<T, E>::or_else<D, F>(&mut this, f: F): result<T, D>
|
||||
where F: invokable<def(E): result<T, D>>
|
||||
{
|
||||
var held := move(this);
|
||||
return match held {
|
||||
value(&mut got) => result::<T, D> { value = move(got) },
|
||||
error(&mut bad) => f(move(bad))
|
||||
};
|
||||
}
|
||||
|
||||
#! Gives the value it holds, as a `maybe`, losing the error.
|
||||
#! @param this The result, moved in as `unwrap` moves it.
|
||||
#! @returns Maybe the value; otherwise, `nothing` where it holds an error.
|
||||
pub def result<T, E>::to_maybe(&mut this): maybe<T> {
|
||||
var held := move(this);
|
||||
return maybe::<T> { some = move(got) } if held is value(&mut got);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Gives the error it holds, as a `maybe`, losing the value.
|
||||
#! @param this The result, moved in as `unwrap` moves it.
|
||||
#! @returns Maybe the error; otherwise, `nothing` where it holds a value.
|
||||
pub def result<T, E>::err_to_maybe(&mut this): maybe<E> {
|
||||
var held := move(this);
|
||||
return maybe::<E> { some = move(got) } if held is error(&mut got);
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Whether it holds what another does: equal values, or equal errors, as `==`
|
||||
#! compares them.
|
||||
#! @param this The result.
|
||||
#! @param other The other.
|
||||
#! @returns Whether they are equal.
|
||||
#! @remarks A `result` whose value or error is of a type that is not
|
||||
#! `equatable` is an error where it is compared.
|
||||
pub def result<T, E>::equals(&this, other: &result<T, E>): bool {
|
||||
return match this {
|
||||
value(&mine) => other is value(&theirs) && equals::<T>(mine, theirs),
|
||||
error(&mine) => other is error(&theirs) && equals::<E>(mine, theirs)
|
||||
};
|
||||
}
|
||||
|
||||
#! Hashes what it holds, so a value hashes apart from an error.
|
||||
#! @param this The result.
|
||||
#! @returns The hash.
|
||||
#! @remarks A `result` whose value or error is of a type that is not `hashable`
|
||||
#! is an error where it is hashed.
|
||||
pub def result<T, E>::hash(&this): u64 {
|
||||
return match this {
|
||||
value(&got) => mix(1, hash::<T>(got)),
|
||||
error(&bad) => mix(2, hash::<E>(bad))
|
||||
};
|
||||
}
|
||||
|
||||
#! Builds a copy of a result, holding a copy of its value or its error, as
|
||||
#! `copy` makes it.
|
||||
#! @param other The result to copy.
|
||||
#! @returns The copy.
|
||||
pub def result<T, E>::copy_of(other: &result<T, E>): result<T, E> {
|
||||
return match other {
|
||||
value(&got) => result::<T, E> { value = copy::<T>(got) },
|
||||
error(&bad) => result::<T, E> { error = copy::<E>(bad) }
|
||||
};
|
||||
}
|
||||
+1258
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,57 @@
|
||||
#! @file site.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `site`, where a call is written, and the intrinsics the compiler
|
||||
#! fills in where a call is written: `call_site`, which gives that site, and
|
||||
#! `source_of` and `values_of`, which give an expression's text and its
|
||||
#! operands' values, as checks report them.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Where a call is written, which the compiler fills in at each call site.
|
||||
#!
|
||||
#! A `site` is made only by `call_site`, which gives the site of the call it is
|
||||
#! written in, so a function is told where it was called from by taking one and
|
||||
#! being passed `call_site()`.
|
||||
pub struct site {
|
||||
pub val path: strview; #! The file the call is written in.
|
||||
pub val line: u32; #! Its one-based line.
|
||||
pub val column: u32; #! Its one-based column.
|
||||
pub val signature: strview; #! The function the call is written in, as it is declared.
|
||||
}
|
||||
|
||||
#! Gives where this call is written.
|
||||
#! @returns The path, line, and column of the call, and the signature of the
|
||||
#! function holding it. The compiler fills each in while compiling, so
|
||||
#! this costs nothing where the program runs.
|
||||
@intrinsic
|
||||
pub def call_site(): site;
|
||||
|
||||
#! Gives the text of an expression as it is written.
|
||||
#!
|
||||
#! The expression is not evaluated: only the source it was written as is taken,
|
||||
#! so `source_of(count != 0)` is the text `count != 0` and nothing runs. The
|
||||
#! text is written into the program, so this costs nothing where it runs.
|
||||
#! @tparam T The type of the expression, which is never evaluated.
|
||||
#! @param value The expression to take the text of.
|
||||
#! @returns Its text, exactly as it is written.
|
||||
@intrinsic
|
||||
pub def source_of<T>(value: T): strview;
|
||||
|
||||
#! Gives the values the operands of an expression held.
|
||||
#!
|
||||
#! Unlike `source_of`, this evaluates the expression's operands, so it costs
|
||||
#! what they cost and what printing them costs. A comparison gives both of its
|
||||
#! operands, as `count = 0`, leaving out any that is written as a literal. An
|
||||
#! expression that is neither a comparison nor a value of its own gives no text,
|
||||
#! since the operands of `&&` and `||` are not both evaluated.
|
||||
#! @tparam T The type of the expression.
|
||||
#! @param value The expression to take the values of.
|
||||
#! @returns What its operands held, or empty text. The text is built where the
|
||||
#! call is written, so it is a `string` that gives its memory back
|
||||
#! there.
|
||||
@intrinsic
|
||||
pub def values_of<T>(value: T): string;
|
||||
@@ -0,0 +1,287 @@
|
||||
#! @file swar.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains words of bytes: eight bytes of text held in a `u64`, `bytes8`, and
|
||||
#! tested at once with the arithmetic every processor has, which is SIMD within
|
||||
#! a register. A test gives a `mask8`, the bytes it chose, which then says where
|
||||
#! the first of them is, the last, or how many there are, so text is searched
|
||||
#! eight bytes a step rather than one.
|
||||
#!
|
||||
#! The first byte of text is the lowest byte of its word, as x86-64 reads it.
|
||||
#! Every test is exact in every byte: each adds within a byte's low seven bits,
|
||||
#! which carry nothing into the byte above, so a mask can be counted, and read
|
||||
#! past its first byte, as well as tested.
|
||||
#!
|
||||
#! The text functions of `core`, as `index_of`, `find`, and `is_ascii`, work this
|
||||
#! way where vectors are not held in registers, as in the virtual machine, and
|
||||
#! on the last few bytes where they are, so most programs use words without
|
||||
#! naming them. A program reading text its own way, as the JSON reader does,
|
||||
#! names them here. What a loop asks of each word is `@inline`, so code built at
|
||||
#! `-O0` reads a word without a call for each test.
|
||||
|
||||
module core::swar;
|
||||
|
||||
|
||||
#! Eight bytes of text in a `u64`, the first in its lowest byte.
|
||||
pub type bytes8 = u64;
|
||||
|
||||
#! A choice of the bytes of a `bytes8`: the high bit of each byte chosen, and
|
||||
#! nothing else.
|
||||
pub type mask8 = u64;
|
||||
|
||||
# The low seven bits of each byte, and the high bit of each.
|
||||
const low7: u64 = 0x7F7F7F7F7F7F7F7F;
|
||||
const high1: u64 = 0x8080808080808080;
|
||||
# One in each byte, which a byte multiplied by repeats into each.
|
||||
const ones: u64 = 0x0101010101010101;
|
||||
|
||||
|
||||
#! A word of one byte repeated.
|
||||
#! @param byte The byte.
|
||||
#! @returns Eight of it.
|
||||
@inline
|
||||
pub def repeat(byte: u8): bytes8 {
|
||||
return (byte as u64) * ones;
|
||||
}
|
||||
|
||||
#! The eight bytes of text from a place.
|
||||
#! @param text The text.
|
||||
#! @param at Where the first is.
|
||||
#! @returns The word.
|
||||
#! @remarks Reading past the text's end stops the program, as indexing does, so
|
||||
#! eight bytes must be left; `load_last` reads fewer.
|
||||
pub def load(text: strview, at: u64): bytes8 {
|
||||
_ = text[at];
|
||||
_ = text[at + 7];
|
||||
return *((text.data + at) as *u64);
|
||||
}
|
||||
|
||||
#! The eight bytes from a pointer, which needn't be aligned.
|
||||
#! @param from The first byte.
|
||||
#! @returns The word.
|
||||
#! @remarks Nothing checks that eight bytes are there, as `*` checks nothing.
|
||||
@inline
|
||||
pub def load(from: *u8): bytes8 {
|
||||
return *(from as *u64);
|
||||
}
|
||||
|
||||
#! The bytes of text from a place to its end, eight at most, and zero bytes
|
||||
#! after them.
|
||||
#! @param text The text.
|
||||
#! @param at Where the first is, within the text.
|
||||
#! @returns The word, whose bytes past the text's end are zero.
|
||||
#! @remarks No byte past the text's end is read: the last few are read as
|
||||
#! `load_last` of a pointer reads them. Beginning past the end stops
|
||||
#! the program, as indexing does.
|
||||
pub def load_last(text: strview, at: u64): bytes8 {
|
||||
_ = text[at];
|
||||
val left := text.length - at;
|
||||
return load_last(text.data + at, left < 8 ? left : 8);
|
||||
}
|
||||
|
||||
#! A number of bytes from a pointer, eight at most, and zero bytes after them,
|
||||
#! read without reading any byte past them.
|
||||
#! @param from The first byte.
|
||||
#! @param count How many to read, from 0 to 8.
|
||||
#! @returns The word, whose bytes from `count` up are zero.
|
||||
#! @remarks Four to seven are read as two halves of four, which overlap, and two
|
||||
#! or three as two of two, each shifted into its place, as `hash_bytes`
|
||||
#! reads its last few.
|
||||
pub def load_last(from: *u8, count: u64): bytes8 {
|
||||
if count >= 8 {
|
||||
return *(from as *u64);
|
||||
}
|
||||
if count >= 4 {
|
||||
val low := *(from as *u32) as u64;
|
||||
val high := *((from + count - 4) as *u32) as u64;
|
||||
return low | (high << ((count - 4) * 8));
|
||||
}
|
||||
if count >= 2 {
|
||||
val low := *(from as *u16) as u64;
|
||||
val high := *((from + count - 2) as *u16) as u64;
|
||||
return low | (high << ((count - 2) * 8));
|
||||
}
|
||||
return count == 1 ? *from as u64 : 0;
|
||||
}
|
||||
|
||||
|
||||
# Tests, each exact in every byte.
|
||||
|
||||
#! The bytes that are zero.
|
||||
#! @param this The word.
|
||||
#! @returns Them.
|
||||
@inline
|
||||
pub def bytes8::zero(&this): mask8 {
|
||||
# Adding the low seven bits to seven ones sets a byte's high bit unless they
|
||||
# are all zero, and `| this` sets it where the byte's own is.
|
||||
val word: u64 = this;
|
||||
return ~(((word & low7) + low7) | word | low7);
|
||||
}
|
||||
|
||||
#! The bytes equal to a byte.
|
||||
#! @param this The word.
|
||||
#! @param byte The byte.
|
||||
#! @returns Them.
|
||||
@inline
|
||||
pub def bytes8::equal(&this, byte: u8): mask8 {
|
||||
val word: bytes8 = this ^ repeat(byte);
|
||||
return word.zero();
|
||||
}
|
||||
|
||||
#! The bytes below a bound, as unsigned numbers.
|
||||
#! @param this The word.
|
||||
#! @param bound The bound, which no byte chosen reaches.
|
||||
#! @returns Them: none where the bound is 0.
|
||||
@inline
|
||||
pub def bytes8::below(&this, bound: u8): mask8 {
|
||||
val word: u64 = this;
|
||||
# A byte under 128 reaches its high bit by the sum where it is at least the
|
||||
# bound, and one of 128 or more has it already. Over 128, a byte of 128 or more
|
||||
# is below where its low seven bits don't reach the bound less 128, and every
|
||||
# byte under 128 is.
|
||||
if bound <= 128 {
|
||||
return ~(((word & low7) + repeat(128 - bound)) | word) & high1;
|
||||
}
|
||||
return ~(((word & low7) + repeat((256 - bound as u64) as u8)) & word) & high1;
|
||||
}
|
||||
|
||||
#! The bytes above a bound, as unsigned numbers.
|
||||
#! @param this The word.
|
||||
#! @param bound The bound, which every byte chosen passes.
|
||||
#! @returns Them: none where the bound is 255.
|
||||
pub def bytes8::above(&this, bound: u8): mask8 {
|
||||
return 0 if bound == 255;
|
||||
return ~this.below(bound + 1) & high1;
|
||||
}
|
||||
|
||||
#! The bytes from one bound to another, both included, as unsigned numbers.
|
||||
#! @param this The word.
|
||||
#! @param low The least byte chosen.
|
||||
#! @param high The greatest.
|
||||
#! @returns Them: none where `low` is above `high`.
|
||||
@inline
|
||||
pub def bytes8::within(&this, low: u8, high: u8): mask8 {
|
||||
val under: u64 = high == 255 ? high1 : this.below(high + 1);
|
||||
return under & ~this.below(low);
|
||||
}
|
||||
|
||||
#! The bytes that are ASCII, below 128.
|
||||
#! @param this The word.
|
||||
#! @returns Them.
|
||||
pub def bytes8::ascii(&this): mask8 {
|
||||
return ~this & high1;
|
||||
}
|
||||
|
||||
|
||||
# Changes.
|
||||
|
||||
#! The word with each ASCII letter in upper case, as `u8::to_upper` has it.
|
||||
#! @param this The word.
|
||||
#! @returns The word changed, where `a` to `z` become `A` to `Z`.
|
||||
pub def bytes8::upper(&this): bytes8 {
|
||||
# A letter's cases differ by 0x20, which is a mask's high bit moved down two.
|
||||
return this ^ (this.within('a', 'z') >> 2);
|
||||
}
|
||||
|
||||
#! The word with each ASCII letter in lower case, as `u8::to_lower` has it.
|
||||
#! @param this The word.
|
||||
#! @returns The word changed, where `A` to `Z` become `a` to `z`.
|
||||
pub def bytes8::lower(&this): bytes8 {
|
||||
return this ^ (this.within('A', 'Z') >> 2);
|
||||
}
|
||||
|
||||
#! One byte of the word.
|
||||
#! @param this The word.
|
||||
#! @param index Which, from 0 for the first to 7.
|
||||
#! @returns It.
|
||||
pub def bytes8::byte(&this, index: u64): u8 {
|
||||
return ((this >> ((index & 7) * 8)) & 0xFF) as u8;
|
||||
}
|
||||
|
||||
#! The number eight ASCII digits write, the first the most significant, as
|
||||
#! `20261016` is written.
|
||||
#! @param this The word.
|
||||
#! @returns The number, or `nothing` where a byte is no digit.
|
||||
pub def bytes8::digits(&this): maybe<u64> {
|
||||
return nothing {} if this.within('0', '9') != high1;
|
||||
|
||||
# Each byte its digit, which joins its neighbor's into pairs, quads, and the
|
||||
# eight: the first of each is the more significant, and lower in the word.
|
||||
var value: u64 = this - repeat('0');
|
||||
value = (value * 10 + (value >> 8)) & 0x00FF00FF00FF00FF;
|
||||
value = (value * 100 + (value >> 16)) & 0x0000FFFF0000FFFF;
|
||||
value = (value * 10000 + (value >> 32)) & 0xFFFFFFFF;
|
||||
return value;
|
||||
}
|
||||
|
||||
#! The bytes of one word where a mask chooses them, and of another elsewhere.
|
||||
#! @param which The mask.
|
||||
#! @param then The word whose bytes the mask chooses.
|
||||
#! @param otherwise The word whose bytes it doesn't.
|
||||
#! @returns The word of both.
|
||||
pub def choose(which: mask8, then: bytes8, otherwise: bytes8): bytes8 {
|
||||
val chosen := which.spread();
|
||||
return (then & chosen) | (otherwise & ~chosen);
|
||||
}
|
||||
|
||||
|
||||
# Masks.
|
||||
|
||||
#! Whether the mask chooses any byte.
|
||||
#! @param this The mask.
|
||||
#! @returns Whether it does.
|
||||
@inline
|
||||
pub def mask8::any(&this): bool {
|
||||
return this != 0;
|
||||
}
|
||||
|
||||
#! The first byte the mask chooses, the lowest.
|
||||
#! @param this The mask.
|
||||
#! @returns Its index, from 0 to 7, or 8 where it chooses none.
|
||||
@inline
|
||||
pub def mask8::first(&this): u64 {
|
||||
return trailing_zeros::<u64>(this) as u64 >> 3;
|
||||
}
|
||||
|
||||
#! The last byte the mask chooses, the highest.
|
||||
#! @param this The mask.
|
||||
#! @returns Its index, from 0 to 7, or 8 where it chooses none.
|
||||
pub def mask8::last(&this): u64 {
|
||||
return 8 if this == 0;
|
||||
return (63 - leading_zeros::<u64>(this) as u64) >> 3;
|
||||
}
|
||||
|
||||
#! How many bytes the mask chooses.
|
||||
#! @param this The mask.
|
||||
#! @returns How many, from 0 to 8.
|
||||
@inline
|
||||
pub def mask8::count(&this): u64 {
|
||||
# Each byte's 1, multiplied by ones, is summed into the top byte.
|
||||
return ((this >> 7) * ones) >> 56;
|
||||
}
|
||||
|
||||
#! The mask without its first byte, to go on to the next.
|
||||
#! @param this The mask.
|
||||
#! @returns It.
|
||||
@inline
|
||||
pub def mask8::rest(&this): mask8 {
|
||||
return this & (this - 1);
|
||||
}
|
||||
|
||||
#! The mask of the first bytes of a word, as the end of text keeps them.
|
||||
#! @param count How many, from 0; 8 or more chooses every byte.
|
||||
#! @returns It.
|
||||
@inline
|
||||
pub def mask8::leading(count: u64): mask8 {
|
||||
return high1 if count >= 8;
|
||||
return high1 & ((1u << (count * 8)) - 1);
|
||||
}
|
||||
|
||||
#! Every bit of each byte the mask chooses.
|
||||
#! @param this The mask.
|
||||
#! @returns A word of `0xFF` in each byte chosen, and zero in the rest.
|
||||
pub def mask8::spread(&this): bytes8 {
|
||||
return (this >> 7) * 0xFF;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#! @file target.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the intrinsics naming the platform the program was checked for, as
|
||||
#! text, and the version of the compiler checking it.
|
||||
#!
|
||||
#! Code only for some platforms goes in `when os == linux { ... }`, or in a file
|
||||
#! declared `module path when os == linux;`, since both leave out what other
|
||||
#! platforms have. Code only for some compilers goes in
|
||||
#! `when compiler >= 1.2.0 { ... }` the same way. These give the same facts
|
||||
#! where code wants them as values.
|
||||
|
||||
module core;
|
||||
|
||||
#! The operating system the program was checked for.
|
||||
#! @returns `linux`, `macos`, `windows`, `freebsd`, or `unknown`.
|
||||
@intrinsic pub def os(): strview;
|
||||
|
||||
#! The processor the program was checked for.
|
||||
#! @returns `x86_64`, `aarch64`, or `unknown`.
|
||||
@intrinsic pub def arch(): strview;
|
||||
|
||||
#! How the program runs.
|
||||
#! @returns `vm` when run by `sakura run`, or `native` as an executable.
|
||||
@intrinsic pub def backend(): strview;
|
||||
|
||||
#! A version of the compiler, as `compiler` gives it: three numbers, compared
|
||||
#! in order, so `1.10.0` comes after `1.9.0`. One is written to compare with as
|
||||
#! `version { 1, 2 }`, the parts left out 0.
|
||||
pub struct version : equatable, ordered {
|
||||
pub val major: u32; #! Changes where what a program means changes.
|
||||
pub val minor: u32; #! Changes where the language gains what it lacked.
|
||||
pub val patch: u32; #! Changes where only mistakes are fixed.
|
||||
}
|
||||
|
||||
#! Whether two versions are the same.
|
||||
#! @param this The version.
|
||||
#! @param other The other.
|
||||
#! @returns Whether they are.
|
||||
pub def version::equals(&this, other: &version): bool {
|
||||
return this.compare(other) == 0;
|
||||
}
|
||||
|
||||
#! How a version stands to another, part by part.
|
||||
#! @param this The version.
|
||||
#! @param other The other.
|
||||
#! @returns Negative where it comes first, 0 where they are the same, and
|
||||
#! positive where it comes after.
|
||||
pub def version::compare(&this, other: &version): i64 {
|
||||
return this.major as i64 - other.major as i64 if this.major != other.major;
|
||||
return this.minor as i64 - other.minor as i64 if this.minor != other.minor;
|
||||
return this.patch as i64 - other.patch as i64;
|
||||
}
|
||||
|
||||
#! The version as it is written, as `1.2.0`.
|
||||
pub val version::text: string {
|
||||
get => $"{this.major}.{this.minor}.{this.patch}";
|
||||
}
|
||||
|
||||
#! The version of the compiler checking the program: the one reading it, not
|
||||
#! the one it was written for, so a library read by an older compiler can
|
||||
#! choose what that compiler understands.
|
||||
#!
|
||||
#! It is known while checking, so `if const compiler() >= (version { 1, 2 })`
|
||||
#! checks only the branch it takes. `when compiler >= 1.2` chooses declarations
|
||||
#! by it the same way.
|
||||
#! @returns The version, which the compiler fills in, so this costs nothing
|
||||
#! where the program runs.
|
||||
@intrinsic pub def compiler(): version;
|
||||
@@ -0,0 +1,17 @@
|
||||
#! @file toolchain.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the release of the compiler this `core` is written for, which the
|
||||
#! compiler checks as it reads `core`. The two agree on what the language is,
|
||||
#! as the types the syntax makes and the intrinsics, so a `core` of another
|
||||
#! release is refused rather than misread. `core` changes with the compiler,
|
||||
#! in the same release, as `system` and the runtime need not.
|
||||
|
||||
module core::toolchain;
|
||||
|
||||
|
||||
#! The release of the compiler this `core` is written for, as `1.0.0`: the
|
||||
#! compiler's `compiler_version`, changed with it.
|
||||
pub const release: strview = "1.0.0";
|
||||
@@ -0,0 +1,118 @@
|
||||
#! @file arithmetic.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the traits of arithmetic: one for each operator, asking for the
|
||||
#! method `+`, `-`, `*`, `/`, `%`, or a prefix `-` calls between values of one
|
||||
#! type, and `additive` and `multiplicative`, which gather those that add and
|
||||
#! those that multiply, and which every number has.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! A type whose values add to another of the type, giving one more.
|
||||
#!
|
||||
#! `a + b` calls `add`, and `a += b` writes what it gives over `a`. A type has
|
||||
#! `+` by declaring the method, whether or not it names this trait, and may
|
||||
#! declare others taking other types, as `instant::add(&this, by: &duration)`.
|
||||
#! The trait is what generic code asks for to add two values of a type. Numbers
|
||||
#! are addable without declaring anything.
|
||||
pub trait addable {
|
||||
#! Adds another value to this one, as `+` does.
|
||||
#! @param this The value to add to.
|
||||
#! @param other The value to add.
|
||||
#! @returns The sum.
|
||||
def add(&this, other: &self): self;
|
||||
}
|
||||
|
||||
#! A type whose values subtract from another of the type, giving one more.
|
||||
#!
|
||||
#! `a - b` calls `sub`, and `a -= b` writes what it gives over `a`. A type has
|
||||
#! `-` by declaring the method, and may declare others taking or giving other
|
||||
#! types, as `instant::sub(&this, since: &instant): duration`. The trait is
|
||||
#! what generic code asks for to subtract two values of a type. Numbers are
|
||||
#! subtractable without declaring anything.
|
||||
pub trait subtractable {
|
||||
#! Subtracts another value from this one, as `-` does.
|
||||
#! @param this The value to subtract from.
|
||||
#! @param other The value to subtract.
|
||||
#! @returns The difference.
|
||||
def sub(&this, other: &self): self;
|
||||
}
|
||||
|
||||
#! A type whose values multiply by another of the type, giving one more.
|
||||
#!
|
||||
#! `a * b` calls `mul`, and `a *= b` writes what it gives over `a`. A type has
|
||||
#! `*` by declaring the method, and may declare others taking other types, as
|
||||
#! `vec2::mul(&this, by: &f64)`. The trait is what generic code asks for to
|
||||
#! multiply two values of a type, as two matrices. Numbers are multipliable
|
||||
#! without declaring anything.
|
||||
pub trait multipliable {
|
||||
#! Multiplies this value by another, as `*` does.
|
||||
#! @param this The value to multiply.
|
||||
#! @param other The value to multiply by.
|
||||
#! @returns The product.
|
||||
def mul(&this, other: &self): self;
|
||||
}
|
||||
|
||||
#! A type whose values divide by another of the type, giving one more.
|
||||
#!
|
||||
#! `a / b` calls `div`, and `a /= b` writes what it gives over `a`. A type has
|
||||
#! `/` by declaring the method, and may declare others taking other types, as
|
||||
#! `duration::div(&this, by: &i64)`. The trait is what generic code asks for to
|
||||
#! divide two values of a type. Numbers are divisible without declaring
|
||||
#! anything.
|
||||
pub trait divisible {
|
||||
#! Divides this value by another, as `/` does.
|
||||
#! @param this The value to divide.
|
||||
#! @param other The value to divide by.
|
||||
#! @returns The quotient.
|
||||
def div(&this, other: &self): self;
|
||||
}
|
||||
|
||||
#! A type whose values leave a remainder when divided by another of the type.
|
||||
#!
|
||||
#! `a % b` calls `rem`, and `a %= b` writes what it gives over `a`. A type has
|
||||
#! `%` by declaring the method. The trait is what generic code asks for to take
|
||||
#! the remainder of two values of a type. Numbers are modular without declaring
|
||||
#! anything.
|
||||
pub trait modular {
|
||||
#! The remainder of dividing this value by another, as `%` gives it.
|
||||
#! @param this The value to divide.
|
||||
#! @param other The value to divide by.
|
||||
#! @returns The remainder.
|
||||
def rem(&this, other: &self): self;
|
||||
}
|
||||
|
||||
#! A type whose values negate, giving another of the type.
|
||||
#!
|
||||
#! `-a` calls `negate`. A type has it by declaring the method. The trait is
|
||||
#! what generic code asks for to negate a value. Numbers are negatable without
|
||||
#! declaring anything.
|
||||
pub trait negatable {
|
||||
#! Negates this value, as `-x` does.
|
||||
#! @param this The value to negate.
|
||||
#! @returns The negated value.
|
||||
def negate(&this): self;
|
||||
}
|
||||
|
||||
#! A type whose values add, subtract, and negate, all as one type: lengths of
|
||||
#! time, vectors, matrices, amounts of money.
|
||||
#!
|
||||
#! It composes `addable`, `subtractable`, and `negatable`, which give `+`, `-`,
|
||||
#! and `-x`, beside `equatable`. It asks for no multiplication, since two
|
||||
#! lengths of time have no product. Numbers are additive without declaring
|
||||
#! anything.
|
||||
#!
|
||||
#! Within a generic bounded by it, a constant does not stand for a value, as it
|
||||
#! does under `numeric`: a length of time is no number.
|
||||
pub trait additive : equatable, addable, subtractable, negatable {}
|
||||
|
||||
#! A type whose values multiply, as one type: matrices, and whatever is
|
||||
#! numeric.
|
||||
#!
|
||||
#! It composes `multipliable`, which gives `*`, beside `equatable`. It asks for
|
||||
#! no division, since not every matrix divides another. Numbers are
|
||||
#! multiplicative without declaring anything.
|
||||
pub trait multiplicative : equatable, multipliable {}
|
||||
@@ -0,0 +1,140 @@
|
||||
#! @file comparison.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the traits comparing values: `equatable`, which `==` calls, with
|
||||
#! `equals`, which compares two values through it; `ordered`, which gives values
|
||||
#! an order, as numbers, enums, and pointers have; and `hashable`, which hashes
|
||||
#! values, as a dictionary's keys are, with `hash` and `mix`, which hash values
|
||||
#! and fold words into a hash.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! A type whose values can be compared for equality, by a method comparing a
|
||||
#! value with another of the same type.
|
||||
#!
|
||||
#! A type that is `equatable` is compared by `==` and `!=`, which call its
|
||||
#! `equals`, and the method can be called by name too.
|
||||
pub trait equatable {
|
||||
#! Compares this value with another of the same type.
|
||||
#! @param this The value to compare against.
|
||||
#! @param other The value to compare with.
|
||||
#! @returns Whether the two are equal.
|
||||
def equals(&this, other: &self): bool;
|
||||
}
|
||||
|
||||
#! Compares two values of the same type through its `equals`, as `==` does.
|
||||
#! @tparam T The type of the values.
|
||||
#! @param first The value to compare against.
|
||||
#! @param second The value to compare with.
|
||||
#! @returns Whether the two are equal.
|
||||
#! @remarks A type that is not `equatable` is an error where it is compared, as
|
||||
#! it is with `==`, since its bytes may differ where its values do not,
|
||||
#! as the padding between fields does.
|
||||
pub def equals<T>(first: &T, second: &T): bool {
|
||||
if const !(T is equatable) {
|
||||
compile_error("`equals` compares values through `equatable`, which this type does not implement, as `==` does.");
|
||||
}
|
||||
return first.equals(second);
|
||||
}
|
||||
|
||||
#! A type whose values have an order.
|
||||
#!
|
||||
#! `compare` gives a negative number when `this` comes before `other`, zero when
|
||||
#! they are equal, and a positive number when it comes after. `<`, `<=`, `>`,
|
||||
#! and `>=` between two values of the type call it, as `==` calls `equals`,
|
||||
#! which an ordered type also gives, so the two always agree. Numbers, enums,
|
||||
#! and pointers are ordered without declaring anything.
|
||||
pub trait ordered : equatable {
|
||||
#! Compares this value with another of the same type, for their order.
|
||||
#! @param this The value to compare against.
|
||||
#! @param other The value to compare with.
|
||||
#! @returns A negative number where this value comes first, zero where they
|
||||
#! are equal, and a positive number where it comes after.
|
||||
def compare(&this, other: &self): i64;
|
||||
}
|
||||
|
||||
#! A type whose values can be hashed into a `u64`, as a dictionary's keys are.
|
||||
#!
|
||||
#! Equal values must hash alike, and values that differ should hash differently
|
||||
#! as often as possible.
|
||||
pub trait hashable {
|
||||
#! Hashes this value.
|
||||
#! @param this The value to hash.
|
||||
#! @returns Its hash code, which equal values share.
|
||||
def hash(&this): u64;
|
||||
}
|
||||
|
||||
#! Shortcut function for hashing a value, providing a 64-bit hashed value.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param item The object to hash.
|
||||
#! @returns The hash value of the object, from its `hash`.
|
||||
#! @remarks A type that is not `hashable` is an error where it is hashed, since
|
||||
#! its bytes may differ where its values do not, as the padding between
|
||||
#! fields does, and equal values must hash alike.
|
||||
pub def hash<T>(item: &T): u64 {
|
||||
if const !(T is hashable) {
|
||||
compile_error("`hash` hashes values through `hashable`, which this type does not implement.");
|
||||
}
|
||||
return item.hash();
|
||||
}
|
||||
|
||||
# Hashes bytes a word at a time, the last few as one word read without passing
|
||||
# their end, so that equal bytes always hash alike.
|
||||
def hash_bytes(data: *u8, len: u64): u64 {
|
||||
var code := len;
|
||||
var at := data;
|
||||
var left := len;
|
||||
while left >= 8 {
|
||||
code = mix(code, *(at as *u64));
|
||||
at = at + 8;
|
||||
left = left - 8;
|
||||
}
|
||||
if left >= 4 {
|
||||
return mix(code, (*(at as *u32) as u64) | ((*((at + left - 4) as *u32) as u64) << 32));
|
||||
}
|
||||
if left >= 2 {
|
||||
return mix(code, (*(at as *u16) as u64) | ((*((at + left - 2) as *u16) as u64) << 16));
|
||||
}
|
||||
if left == 1 {
|
||||
return mix(code, *at as u64);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
#! Packs two 32-bit numbers into one word, the first in its high half, as a key
|
||||
#! naming a pair, such as a type and a trait, is made for a dictionary.
|
||||
#! @param high The number held in the high half.
|
||||
#! @param low The number held in the low half.
|
||||
#! @returns The word, which `pair_high` and `pair_low` take apart, and which no
|
||||
#! other pair packs into.
|
||||
pub def pair_key(high: u32, low: u32): u64 {
|
||||
return (high as u64 << 32) | low as u64;
|
||||
}
|
||||
|
||||
#! The number held in the high half of a word `pair_key` packed.
|
||||
#! @param key The word.
|
||||
#! @returns The first number given to `pair_key`.
|
||||
pub def pair_high(key: u64): u32 {
|
||||
return (key >> 32) as u32;
|
||||
}
|
||||
|
||||
#! The number held in the low half of a word `pair_key` packed.
|
||||
#! @param key The word.
|
||||
#! @returns The second number given to `pair_key`.
|
||||
pub def pair_low(key: u64): u32 {
|
||||
return (key & 0xFFFFFFFF) as u32;
|
||||
}
|
||||
|
||||
#! Folds a word into a hash code, as hashing a value made of several does for
|
||||
#! each.
|
||||
#! @param code The hash code so far.
|
||||
#! @param value The word to fold in.
|
||||
#! @returns The new hash code.
|
||||
pub def mix(code: u64, value: u64): u64 {
|
||||
var bits := code ^ value;
|
||||
bits *= 0x9E3779B97F4A7C15;
|
||||
return bits ^ (bits >> 29);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
#! @file containers.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the traits a container implements to lend its elements: `indexable`
|
||||
#! and `assignable`, which let it be written `d[key]` to read and to write, the
|
||||
#! way the language already writes a fixed array, a pointer, and a view;
|
||||
#! `spannable` and `sliceable`, which lend a view of its elements that reads and
|
||||
#! one that writes, and let it be written `x[a:n]` to take them, as a view is;
|
||||
#! and `extendable`, which has values appended to it, as an
|
||||
#! iterator's `into` appends each element it gives.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Defines that a type is indexed by a key, giving the element it holds there to
|
||||
#! read.
|
||||
#!
|
||||
#! `d[key]` is `d.at(key)`: the reference the accessor gives, which is read and
|
||||
#! bound as any reference is, so indexing copies nothing. `val e := d[key]`
|
||||
#! refers to the element, and `val e: V = d[key]` copies it. A type whose
|
||||
#! elements are written where they are is `assignable` too, which adds the
|
||||
#! accessor that writes. One that is only ever read is read through `at(&this)`
|
||||
#! however it is held, so writing an element of it is an error where it is
|
||||
#! written.
|
||||
#!
|
||||
#! The accessor is expected to stop a checked program where the key is one the
|
||||
#! value does not hold, as indexing a fixed array outside its length does, with
|
||||
#! a contract, as `expects(key < this._len)`: one that is not checked trusts the
|
||||
#! key, as C does. A
|
||||
#! key that may be one the value does not hold in a program that is right is
|
||||
#! asked of a `get` the type gives beside this trait, returning `maybe<&V>`, as
|
||||
#! each container of std's does.
|
||||
#!
|
||||
#! Traits are satisfied by shape, as they are everywhere else, so a type with
|
||||
#! `at` is indexable whether or not it names the trait. Naming it is still worth
|
||||
#! doing: it says the type means to be indexed, and it is what a `where` clause
|
||||
#! bounds a type parameter by.
|
||||
#! @tparam K The type of the keys it is indexed by.
|
||||
#! @tparam V The type of the elements it holds.
|
||||
pub trait indexable<K, V> {
|
||||
#! Reaches the element held at a key, to read it.
|
||||
#! @param this The value to index.
|
||||
#! @param key The key of the element.
|
||||
#! @returns The element.
|
||||
#! @remarks A key the value does not hold stops a checked program.
|
||||
def at(&this, key: K): &V;
|
||||
}
|
||||
|
||||
#! Defines that a type is indexed by a key and written there too: the half of
|
||||
#! indexing that writes, which a type adds to `indexable` where its elements
|
||||
#! may be changed in place.
|
||||
#!
|
||||
#! There are then two accessors, both named `at`: the one `indexable` asks for,
|
||||
#! taking `&this` and giving a `&V`, and this one, taking `&mut this` and giving
|
||||
#! a `&mut V`. The receiver chooses between them, so a value that can be written
|
||||
#! is given the element to write, and one that cannot is given it only to read.
|
||||
#! Both are given the same key, and both stop a checked program where the key
|
||||
#! is one the value does not hold.
|
||||
#!
|
||||
#! Generic code bounded by it writes `d[key] = value` and `d[key] += 1`, which a
|
||||
#! bound of `indexable` alone does not let it, and `position_mutator` writes
|
||||
#! each element of what is indexed by position through it.
|
||||
#! @tparam K The type of the keys it is indexed by.
|
||||
#! @tparam V The type of the elements it holds.
|
||||
pub trait assignable<K, V> : indexable<K, V> {
|
||||
#! Reaches the element held at a key, to write it.
|
||||
#! @param this The value to index.
|
||||
#! @param key The key of the element.
|
||||
#! @returns The element.
|
||||
#! @remarks A key the value does not hold stops a checked program.
|
||||
def at(&mut this, key: K): &mut V;
|
||||
}
|
||||
|
||||
#! A type that lends a view of the elements it holds, as a `string` lends its
|
||||
#! text and a container its elements.
|
||||
#!
|
||||
#! `x[start:count]` is `T::span_of(&x, start, count)`, the way the language
|
||||
#! already slices a fixed array, a pointer, and a view: `count` elements from
|
||||
#! `start`, as a `span<T>`. A type whose elements are written where they are is
|
||||
#! `sliceable` too, and a value of it that can be written is sliced through
|
||||
#! `slice_of` instead. Either bound may be left out, which gives it as `span_of`
|
||||
#! takes it by default: the start as 0, and the count as `~0u`, which stands for
|
||||
#! every element after the start, so `x[2:]` is all but the first two and `x[:]`
|
||||
#! is all of them.
|
||||
#!
|
||||
#! Generic code bounded by it reads the elements of whatever it is given through
|
||||
#! `span_of`, as `C::span_of(c)` for all of them, or `c[a:n]`. A container lends
|
||||
#! the whole view as its `span` property too, as `v.span`, which is what code
|
||||
#! that knows its type reads.
|
||||
#!
|
||||
#! A type gives `span_of` the same defaults, so a call leaving them out calls it
|
||||
#! as it calls the trait's, and is expected to stop a checked program where the
|
||||
#! start or the count reaches past its last element, as slicing a fixed array
|
||||
#! does. Slicing the whole view does both, as `whole[start:]` where `count` is
|
||||
#! `~0u`, and `whole[start:count]` where it isn't.
|
||||
#! @tparam T The type of the elements.
|
||||
pub trait spannable<T> {
|
||||
#! Lends a view of elements of a value, without copying them.
|
||||
#! @param other The value 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 The view, which is only good until the value changes or closes.
|
||||
#! @remarks A start or count past the last element stops a checked program.
|
||||
def span_of(other: &self, start: u64 = 0, count: u64 = ~0u): span<T>;
|
||||
}
|
||||
|
||||
#! A type that lends a writable view of the elements it holds, as a container
|
||||
#! lends one of its elements.
|
||||
#!
|
||||
#! `x[start:count]` is `T::slice_of(&mut x, start, count)` where `x` can be
|
||||
#! written, as a `slice<T>` that writes the elements where they are, and
|
||||
#! `T::span_of(&x, start, count)` where it cannot. The bounds are given and left
|
||||
#! out as `spannable` says.
|
||||
#!
|
||||
#! Generic code bounded by it writes the elements of whatever it is given
|
||||
#! through `slice_of`, as `C::slice_of(c)` for all of them, or `c[a:n]` of a
|
||||
#! `c` that can be written. A container lends the whole view as its `slice`
|
||||
#! property too, as `v.slice`, which only a value that can be written reads.
|
||||
#! @tparam T The type of the elements.
|
||||
pub trait sliceable<T> {
|
||||
#! Lends a writable view of elements of a value, without copying them.
|
||||
#! @param other The value 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 The view, which writes the elements where they are, and is only
|
||||
#! good until the value changes or closes.
|
||||
#! @remarks A start or count past the last element stops a checked program.
|
||||
def slice_of(other: &mut self, start: u64 = 0, count: u64 = ~0u): slice<T>;
|
||||
}
|
||||
|
||||
#! A container values are appended to one at a time, as a `vector` takes its
|
||||
#! elements and a `string` its text.
|
||||
#! @tparam T The type of what is appended.
|
||||
pub trait extendable<T> {
|
||||
#! Appends a value, after those the container holds.
|
||||
#! @param this The container.
|
||||
#! @param value The value, which the container then owns.
|
||||
def append(&mut this, value: T): void;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#! @file functions.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the traits of functions: `invokable`, which a type implements to be
|
||||
#! called as a function is, `f(args)`, and which every function is, and
|
||||
#! `signature`, which the compiler gives every function type, and which names
|
||||
#! what a function takes and what it gives.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! What is called as a function of a signature: a function value, the address of
|
||||
#! a C function, or a value of a type with an `invoke` taking the arguments.
|
||||
#!
|
||||
#! The trait is given the signature whole, as `invokable<def(i64, bool): u8>`,
|
||||
#! whose parameter types it names `Ts` and whose result `R`, so `invoke` takes a
|
||||
#! parameter of each of the types, as `def adder::invoke(&mut this, a: i64, b:
|
||||
#! bool): u8` does. A variadic signature, as `def(i64...): i64`, asks for a
|
||||
#! variadic `invoke`. Generic code over any signature names it through a type
|
||||
#! parameter bounded by `signature`, as `invokable<F>`.
|
||||
#!
|
||||
#! A call of a value whose type is no function, `f(1, true)`, calls its `invoke`,
|
||||
#! as `f.invoke(1, true)`, by the rules a method's call has: the overloads are
|
||||
#! chosen between as they are, and one taking `&mut this` is called on what can be
|
||||
#! written. Any type with an `invoke` is called so, whether or not it names this
|
||||
#! trait, which bounds generic code taking functions and callable values alike:
|
||||
#!
|
||||
#! ```sakura
|
||||
#! def twice<F>(f: &mut F, x: i64): i64 where F: invokable<def(i64): i64> {
|
||||
#! return f(f(x));
|
||||
#! }
|
||||
#! ```
|
||||
#!
|
||||
#! A function value, and the address of a C function, have an `invoke` the
|
||||
#! compiler gives them, which calls them, so each is `invokable` of its own type.
|
||||
#! An `invoke` taking `&this` meets the trait too, since what can be written can
|
||||
#! be read.
|
||||
#! @tparam Ts The types of the arguments it is called with.
|
||||
#! @tparam R The type it gives.
|
||||
pub trait invokable<def(Ts...): R> {
|
||||
#! Calls it with the arguments, as `f(args)` does.
|
||||
#! @param this The value called.
|
||||
#! @param args The arguments, one of each of the signature's parameter types.
|
||||
#! @returns What the call gives.
|
||||
def invoke(&mut this, args: Ts...): R;
|
||||
}
|
||||
|
||||
#! A function type, as `def(i64, bool): u8`, a variadic one, as `def(i64...):
|
||||
#! i64`, or the address of a C function, as `cfn<def(i32): void>`.
|
||||
#!
|
||||
#! Generic code bounded by it names the parts of the type it is given: `F::result`
|
||||
#! is what a function of it gives, and `F::params` the types it takes, as a pack,
|
||||
#! so `args: F::params...` takes the arguments it does. A variadic function's
|
||||
#! pack ends in the type of the values its last parameter takes, so a parameter
|
||||
#! of the pack is variadic too.
|
||||
#!
|
||||
#! A pattern parameter, as `def(Ts...): R` of `invokable`, is given a signature
|
||||
#! whole: `invokable<F>` where `F: signature` names `F::params` and `F::result`
|
||||
#! as `Ts` and `R`.
|
||||
#!
|
||||
#! The compiler decides what is a signature, so no type implements it.
|
||||
pub trait signature {
|
||||
#! What a function of the type gives.
|
||||
type result;
|
||||
|
||||
#! The types a function of the type takes, as a pack, which only the compiler
|
||||
#! gives.
|
||||
type params...;
|
||||
}
|
||||
@@ -0,0 +1,691 @@
|
||||
#! @file iteration.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the traits of iteration, and the iterators any container may lend:
|
||||
#! `iter`, which gives elements one at a time and which a `for` loop walks, with
|
||||
#! the adapters making one iterator of another and the consumers walking one to
|
||||
#! its end as its defaults; `sized_iterator`, which knows how many elements it
|
||||
#! has left; `backward_iterator`, which also walks from its far end; `iterable`,
|
||||
#! which lends an iterator over the elements a container holds; and
|
||||
#! `positions_iterator` and `position_mutator`, which read and write the
|
||||
#! elements of whatever is indexed by position, so a container need not write
|
||||
#! iterators of its own.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Gives elements one at a time, as `some` of each while there are more and
|
||||
#! `none` once there are no more.
|
||||
#!
|
||||
#! `for x in it` walks an iterator where it is, calling `next` until it gives
|
||||
#! `none`, so one that a loop stops early carries on from there in the next. An
|
||||
#! iterator that is `owning` and that a loop is given as a value, rather than as
|
||||
#! a variable, is closed where the loop ends, however it ends.
|
||||
#!
|
||||
#! A type naming the trait has its defaults: the adapters, which make an
|
||||
#! iterator of it, as `v.iter().filter(odd).map(square)`, and the consumers,
|
||||
#! which walk it to its end, or until they know their answer, as `.sum()`. Each
|
||||
#! is compiled for the type, so what it calls of the type is called directly. An
|
||||
#! adapter moves the iterator it is called on into what it makes, which closes
|
||||
#! it where that closes, so `it.map(f)` leaves `it` walked to its end.
|
||||
#!
|
||||
#! It is named as the types the syntax makes are, short, leaving `iterator` to
|
||||
#! the type a container lends, as `vector<T>::iterator`.
|
||||
#! @tparam T The type of what it gives.
|
||||
pub trait iter<T> {
|
||||
#! Gives the next element, or `none` once there are no more.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns Maybe the next element; otherwise, `nothing`.
|
||||
def next(&mut this): maybe<T>;
|
||||
|
||||
#! Gives what a function makes of each element.
|
||||
#! @tparam U What the function gives.
|
||||
#! @tparam F The function, a lambda, or anything `invokable`.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param f The function, called on each element as it is given.
|
||||
#! @returns The iterator of what it makes.
|
||||
def map<U, F>(&mut this, f: F): mapped<T, U, self, F> where F: invokable<def(T): U> {
|
||||
return mapped::<T, U, self, F> { _from = move(this), _f = move(&mut f) };
|
||||
}
|
||||
|
||||
#! Gives each element a test passes.
|
||||
#! @tparam F The test.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param test The test, given a reference to each element.
|
||||
#! @returns The iterator of those that pass.
|
||||
def filter<F>(&mut this, test: F): filtered<T, self, F> where F: invokable<def(&T): bool> {
|
||||
return filtered::<T, self, F> { _from = move(this), _test = move(&mut test) };
|
||||
}
|
||||
|
||||
#! Gives what a function makes of each element where it makes something, as
|
||||
#! `some`.
|
||||
#! @tparam U What the function may give.
|
||||
#! @tparam F The function.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param f The function, called on each element.
|
||||
#! @returns The iterator of what it makes.
|
||||
def filter_map<U, F>(&mut this, f: F): filter_mapped<T, U, self, F> where F: invokable<def(T): maybe<U>> {
|
||||
return filter_mapped::<T, U, self, F> { _from = move(this), _f = move(&mut f) };
|
||||
}
|
||||
|
||||
#! Gives each element with its index, counting from 0, as a `pair`.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @returns The iterator of pairs.
|
||||
def enumerate(&mut this): enumerated<T, self> {
|
||||
return enumerated::<T, self> { _from = move(this), _at = 0 };
|
||||
}
|
||||
|
||||
#! Gives the elements of this iterator and another side by side, as a `pair`,
|
||||
#! until either ends.
|
||||
#! @tparam U What the other gives.
|
||||
#! @tparam J The other iterator.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param other The other iterator, moved into what is made.
|
||||
#! @returns The iterator of pairs.
|
||||
def zip<U, J>(&mut this, other: J): zipped<T, U, self, J> where J: iter<U> {
|
||||
return zipped::<T, U, self, J> { _from = move(this), _other = move(&mut other) };
|
||||
}
|
||||
|
||||
#! Gives this iterator's elements, then another's.
|
||||
#! @tparam J The other iterator, giving what this one gives.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param other The other iterator, moved into what is made.
|
||||
#! @returns The iterator of both.
|
||||
def chain<J>(&mut this, other: J): chained<T, self, J> where J: iter<T> {
|
||||
return chained::<T, self, J> { _first = move(this), _second = move(&mut other), _on_second = false };
|
||||
}
|
||||
|
||||
#! Gives the first elements, up to a count.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param n How many to give at most.
|
||||
#! @returns The iterator of those.
|
||||
def take(&mut this, n: u64): taken<T, self> {
|
||||
return taken::<T, self> { _from = move(this), _left = n };
|
||||
}
|
||||
|
||||
#! Gives the elements after the first, up to a count, which it passes over.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param n How many to pass over.
|
||||
#! @returns The iterator of the rest.
|
||||
def skip(&mut this, n: u64): skipped<T, self> {
|
||||
return skipped::<T, self> { _from = move(this), _skip = n };
|
||||
}
|
||||
|
||||
#! Gives the elements while a test passes them, ending at the first it does
|
||||
#! not.
|
||||
#! @tparam F The test.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param test The test, given a reference to each element.
|
||||
#! @returns The iterator of the run that passes.
|
||||
def take_while<F>(&mut this, test: F): taken_while<T, self, F> where F: invokable<def(&T): bool> {
|
||||
return taken_while::<T, self, F> { _from = move(this), _test = move(&mut test), _done = false };
|
||||
}
|
||||
|
||||
#! Gives the elements from the first a test does not pass on, passing over
|
||||
#! those before it.
|
||||
#! @tparam F The test.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param test The test, given a reference to each element.
|
||||
#! @returns The iterator of the rest.
|
||||
def skip_while<F>(&mut this, test: F): skipped_while<T, self, F> where F: invokable<def(&T): bool> {
|
||||
return skipped_while::<T, self, F> { _from = move(this), _test = move(&mut test), _past = false };
|
||||
}
|
||||
|
||||
#! Gives every `n`th element, the first included.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param n How far apart the elements given are, at least 1.
|
||||
#! @returns The iterator of those.
|
||||
def step(&mut this, n: u64): stepped<T, self> {
|
||||
if n == 0 {
|
||||
fault("An iterator steps by 0, which is no step.");
|
||||
}
|
||||
return stepped::<T, self> { _from = move(this), _by = n, _first = true };
|
||||
}
|
||||
|
||||
#! Gives the elements from the far end.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @returns The iterator walking backward.
|
||||
def rev(&mut this): reversed<T, self> where self: backward_iterator<T> {
|
||||
return reversed::<T, self> { _from = move(this) };
|
||||
}
|
||||
|
||||
#! Gives the elements, and looks at the next before it is given, by `peek`.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @returns The iterator that peeks.
|
||||
def peekable(&mut this): peeking<T, self> {
|
||||
return peeking::<T, self> { _from = move(this), _held = nothing {} };
|
||||
}
|
||||
|
||||
#! Gives the elements of each iterator a function makes of each element.
|
||||
#! @tparam U What the iterators it makes give.
|
||||
#! @tparam J The iterators it makes.
|
||||
#! @tparam F The function.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param f The function, called on each element.
|
||||
#! @returns The iterator of what each gives, in turn.
|
||||
def flat_map<U, J, F>(&mut this, f: F): flat_mapped<T, U, self, J, F>
|
||||
where F: invokable<def(T): J> where J: iter<U> {
|
||||
return flat_mapped::<T, U, self, J, F> { _from = move(this), _f = move(&mut f), _inner = nothing {} };
|
||||
}
|
||||
|
||||
#! Gives a copy of what each reference it gives refers to, of what closes
|
||||
#! nothing.
|
||||
#! @tparam X What the references refer to.
|
||||
#! @param this The iterator of references, moved into what is made.
|
||||
#! @returns The iterator of copies.
|
||||
def copied<X>(&mut this): copying<X, self> where self: iter<&X> {
|
||||
return copying::<X, self> { _from = move(this) };
|
||||
}
|
||||
|
||||
#! Gives the elements as they are, after calling a function on each.
|
||||
#! @tparam F The function.
|
||||
#! @param this The iterator, moved into what is made.
|
||||
#! @param f The function, given a reference to each element.
|
||||
#! @returns The iterator.
|
||||
def inspect<F>(&mut this, f: F): inspected<T, self, F> where F: invokable<def(&T): void> {
|
||||
return inspected::<T, self, F> { _from = move(this), _f = move(&mut f) };
|
||||
}
|
||||
|
||||
#! Walks to the end, counting the elements.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many it gave.
|
||||
def count(&mut this): u64 {
|
||||
var n: u64 = 0;
|
||||
while this.next() is some(x) {
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
#! Walks to the end, adding the elements up.
|
||||
#! @param this The iterator, of numbers.
|
||||
#! @returns The sum, or 0 where it gives none.
|
||||
def sum(&mut this): T where T: numeric {
|
||||
var total: T = 0;
|
||||
while this.next() is some(x) {
|
||||
total += x;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
#! Walks to the end, multiplying the elements together.
|
||||
#! @param this The iterator, of numbers.
|
||||
#! @returns The product, or 1 where it gives none.
|
||||
def product(&mut this): T where T: numeric {
|
||||
var total: T = 1;
|
||||
while this.next() is some(x) {
|
||||
total *= x;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
#! Walks to the end, folding each element into a value: `f(f(start, x0), x1)`
|
||||
#! and on.
|
||||
#! @tparam A The value.
|
||||
#! @tparam F The function folding each in.
|
||||
#! @param this The iterator.
|
||||
#! @param start The value before any element is folded in.
|
||||
#! @param f The function, given the value so far and the element.
|
||||
#! @returns The value once every element is folded in.
|
||||
def fold<A, F>(&mut this, start: A, f: F): A where F: invokable<def(A, T): A> {
|
||||
var made := move(&mut start);
|
||||
while this.next() is some(x) {
|
||||
made = f(move(&mut made), move(&mut x));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Walks to the end, folding the elements into the first: `f(f(x0, x1), x2)`
|
||||
#! and on.
|
||||
#! @tparam F The function folding each in.
|
||||
#! @param this The iterator.
|
||||
#! @param f The function, given the value so far and the element.
|
||||
#! @returns Maybe the value; otherwise, `nothing` where it gives no elements.
|
||||
def reduce<F>(&mut this, f: F): maybe<T> where F: invokable<def(T, T): T> {
|
||||
var first := this.next();
|
||||
if first is not some(&mut start) {
|
||||
return nothing {};
|
||||
}
|
||||
var made := move(start);
|
||||
while this.next() is some(x) {
|
||||
made = f(move(&mut made), move(&mut x));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether a test passes any element, walking until one does.
|
||||
#! @tparam F The test.
|
||||
#! @param this The iterator.
|
||||
#! @param test The test, given a reference to each element.
|
||||
#! @returns Whether it passes one.
|
||||
def any<F>(&mut this, test: F): bool where F: invokable<def(&T): bool> {
|
||||
while this.next() is some(x) {
|
||||
return true if test(&x);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether a test passes every element, walking until one fails it.
|
||||
#! @tparam F The test.
|
||||
#! @param this The iterator.
|
||||
#! @param test The test, given a reference to each element.
|
||||
#! @returns Whether it passes all of them, as it does where there are none.
|
||||
def all<F>(&mut this, test: F): bool where F: invokable<def(&T): bool> {
|
||||
while this.next() is some(x) {
|
||||
return false if !test(&x);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The first element a test passes, walking until it finds one.
|
||||
#! @tparam F The test.
|
||||
#! @param this The iterator.
|
||||
#! @param test The test, given a reference to each element.
|
||||
#! @returns Maybe the element; otherwise, `nothing`.
|
||||
def find<F>(&mut this, test: F): maybe<T> where F: invokable<def(&T): bool> {
|
||||
while this.next() is some(x) {
|
||||
return move(&mut x) if test(&x);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! The index of the first element a test passes, counting from 0, walking
|
||||
#! until it finds one.
|
||||
#! @tparam F The test.
|
||||
#! @param this The iterator.
|
||||
#! @param test The test, given a reference to each element.
|
||||
#! @returns Maybe the index; otherwise, `nothing`.
|
||||
def position<F>(&mut this, test: F): maybe<u64> where F: invokable<def(&T): bool> {
|
||||
var at: u64 = 0;
|
||||
while this.next() is some(x) {
|
||||
return at if test(&x);
|
||||
at++;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Walks to the end, keeping the least element, the first of those equally
|
||||
#! least.
|
||||
#! @param this The iterator, of what is ordered.
|
||||
#! @returns Maybe the least; otherwise, `nothing` where it gives none.
|
||||
def min(&mut this): maybe<T> where T: ordered {
|
||||
var first := this.next();
|
||||
if first is not some(&mut start) {
|
||||
return nothing {};
|
||||
}
|
||||
var best := move(start);
|
||||
while this.next() is some(x) {
|
||||
if x < best {
|
||||
best = move(&mut x);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
#! Walks to the end, keeping the greatest element, the last of those equally
|
||||
#! greatest.
|
||||
#! @param this The iterator, of what is ordered.
|
||||
#! @returns Maybe the greatest; otherwise, `nothing` where it gives none.
|
||||
def max(&mut this): maybe<T> where T: ordered {
|
||||
var first := this.next();
|
||||
if first is not some(&mut start) {
|
||||
return nothing {};
|
||||
}
|
||||
var best := move(start);
|
||||
while this.next() is some(x) {
|
||||
if !(x < best) {
|
||||
best = move(&mut x);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
#! Walks to the end, keeping the least element as an order says, the first of
|
||||
#! those equally least.
|
||||
#! @tparam F The order.
|
||||
#! @param this The iterator.
|
||||
#! @param order Whether one element comes before another.
|
||||
#! @returns Maybe the least; otherwise, `nothing` where it gives none.
|
||||
def min_by<F>(&mut this, order: F): maybe<T> where F: invokable<def(&T, &T): bool> {
|
||||
var first := this.next();
|
||||
if first is not some(&mut start) {
|
||||
return nothing {};
|
||||
}
|
||||
var best := move(start);
|
||||
while this.next() is some(x) {
|
||||
if order(&x, &best) {
|
||||
best = move(&mut x);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
#! Walks to the end, keeping the greatest element as an order says, the last
|
||||
#! of those equally greatest.
|
||||
#! @tparam F The order.
|
||||
#! @param this The iterator.
|
||||
#! @param order Whether one element comes before another.
|
||||
#! @returns Maybe the greatest; otherwise, `nothing` where it gives none.
|
||||
def max_by<F>(&mut this, order: F): maybe<T> where F: invokable<def(&T, &T): bool> {
|
||||
var first := this.next();
|
||||
if first is not some(&mut start) {
|
||||
return nothing {};
|
||||
}
|
||||
var best := move(start);
|
||||
while this.next() is some(x) {
|
||||
if !order(&x, &best) {
|
||||
best = move(&mut x);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
#! Walks to the end, keeping the element whose key is least, the first of
|
||||
#! those equally least.
|
||||
#! @tparam K The key, which is ordered.
|
||||
#! @tparam F The function giving the key.
|
||||
#! @param this The iterator.
|
||||
#! @param key The function, given a reference to each element.
|
||||
#! @returns Maybe the element; otherwise, `nothing` where it gives none.
|
||||
def min_by_key<K, F>(&mut this, key: F): maybe<T> where F: invokable<def(&T): K> where K: ordered {
|
||||
var first := this.next();
|
||||
if first is not some(&mut start) {
|
||||
return nothing {};
|
||||
}
|
||||
var best := move(start);
|
||||
var least := key(&best);
|
||||
while this.next() is some(x) {
|
||||
var made := key(&x);
|
||||
if made < least {
|
||||
best = move(&mut x);
|
||||
least = move(&mut made);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
#! Walks to the end, keeping the element whose key is greatest, the last of
|
||||
#! those equally greatest.
|
||||
#! @tparam K The key, which is ordered.
|
||||
#! @tparam F The function giving the key.
|
||||
#! @param this The iterator.
|
||||
#! @param key The function, given a reference to each element.
|
||||
#! @returns Maybe the element; otherwise, `nothing` where it gives none.
|
||||
def max_by_key<K, F>(&mut this, key: F): maybe<T> where F: invokable<def(&T): K> where K: ordered {
|
||||
var first := this.next();
|
||||
if first is not some(&mut start) {
|
||||
return nothing {};
|
||||
}
|
||||
var best := move(start);
|
||||
var most := key(&best);
|
||||
while this.next() is some(x) {
|
||||
var made := key(&x);
|
||||
if !(made < most) {
|
||||
best = move(&mut x);
|
||||
most = move(&mut made);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
#! The last element: from the far end where the iterator walks backward,
|
||||
#! and otherwise by walking to the end.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the last element; otherwise, `nothing` where it gives none.
|
||||
def last(&mut this): maybe<T> {
|
||||
if const self is backward_iterator<T> {
|
||||
return this.next_back();
|
||||
}
|
||||
var kept: maybe<T> = nothing {};
|
||||
while this.next() is some(x) {
|
||||
kept = move(&mut x);
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
#! The element `n` along, counting from 0, passing over those before it.
|
||||
#! @param this The iterator.
|
||||
#! @param n How many to pass over first.
|
||||
#! @returns Maybe the element; otherwise, `nothing` where it gives fewer.
|
||||
def nth(&mut this, n: u64): maybe<T> {
|
||||
var left := n;
|
||||
while left != 0 {
|
||||
return nothing {} if this.next() is not some(x);
|
||||
left--;
|
||||
}
|
||||
return this.next();
|
||||
}
|
||||
|
||||
#! Walks to the end, calling a function on each element.
|
||||
#! @tparam F The function.
|
||||
#! @param this The iterator.
|
||||
#! @param f The function, given each element.
|
||||
def for_each<F>(&mut this, f: F): void where F: invokable<def(T): void> {
|
||||
while this.next() is some(x) {
|
||||
f(move(&mut x));
|
||||
}
|
||||
}
|
||||
|
||||
#! Walks to the end, collecting the elements into a vector, which is given
|
||||
#! room for them all at once where the iterator knows how many it has left.
|
||||
#! @param this The iterator.
|
||||
#! @returns The vector.
|
||||
def to_vector(&mut this): vector<T> {
|
||||
var made := vector::<T>::new();
|
||||
if const self is sized_iterator<T> {
|
||||
made.reserve(this.remaining());
|
||||
}
|
||||
while this.next() is some(x) {
|
||||
made.append(move(&mut x));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Walks to the end, joining the text of the elements, as `$"{x}"` writes
|
||||
#! each, with text between each two.
|
||||
#! @param this The iterator.
|
||||
#! @param between What is written between each two elements.
|
||||
#! @returns The text.
|
||||
def to_string(&mut this, between: strview): string {
|
||||
var made := string::new(nothing {});
|
||||
var first := true;
|
||||
while this.next() is some(x) {
|
||||
if !first {
|
||||
made.append(between);
|
||||
}
|
||||
first = false;
|
||||
val text := $"{x}";
|
||||
made.append(text.span);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Walks to the end, appending each element to a container, as a `vector`, a
|
||||
#! `string`, or anything `extendable` is.
|
||||
#! @tparam C The container.
|
||||
#! @param this The iterator.
|
||||
#! @param target The container, which keeps what it held before.
|
||||
def into<C>(&mut this, target: &mut C): void where C: extendable<T> {
|
||||
while this.next() is some(x) {
|
||||
target.append(move(&mut x));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! An iterator that knows how many elements it has left, as a view, a range,
|
||||
#! and the containers' iterators do, so collecting it makes room for them at
|
||||
#! once.
|
||||
#! @tparam T The type of what it gives.
|
||||
pub trait sized_iterator<T> : iter<T> {
|
||||
#! How many elements it has left to give.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
def remaining(&this): u64;
|
||||
}
|
||||
|
||||
#! An iterator that also walks from its far end, until the two ends meet, as a
|
||||
#! view, a range, a `deque`, and a `chain` do, which `rev` and `last` take.
|
||||
#! @tparam T The type of what it gives.
|
||||
pub trait backward_iterator<T> : iter<T> {
|
||||
#! Gives the element at the far end, or `none` once the ends have met.
|
||||
#! @param this The iterator.
|
||||
#! @returns Maybe the last element left; otherwise, `nothing`.
|
||||
def next_back(&mut this): maybe<T>;
|
||||
}
|
||||
|
||||
#! Lends an iterator over the elements it holds, as references to them.
|
||||
#!
|
||||
#! `for x in c` calls `iter(&this)` once and walks what it gives, copying each
|
||||
#! element, and `for &x in c` refers to each instead. `for &mut x in c` calls
|
||||
#! `iter(&mut this)`, which a container whose elements may be changed in place
|
||||
#! gives, and which one that only reads leaves out. What `iter` gives is closed
|
||||
#! where the loop ends, however it ends, where it is `owning`.
|
||||
#!
|
||||
#! The iterator types are asked of the container: an `iterator`, which only
|
||||
#! reads, and a `mutator`, which writes, as `type list<T>::iterator = ...;`, so
|
||||
#! generic code names them through a bound, as `C::iterator` where
|
||||
#! `C: iterable<T>`. A container lends them as properties of the same names too,
|
||||
#! as `v.iterator`. A container indexed by position need write neither, since
|
||||
#! `positions_iterator` and `position_mutator` walk it through its `at`.
|
||||
#!
|
||||
#! Within the container, as within this trait, `iterator` names the type it
|
||||
#! lends, so the trait is `iter` there, as `where I: iter<T>`.
|
||||
#! @tparam T The type of the elements, which the iterators give references to.
|
||||
pub trait iterable<T> {
|
||||
#! What `iter(&this)` gives, which gives references that read the elements.
|
||||
type iterator: iter<&T>;
|
||||
|
||||
#! What `iter(&mut this)` gives, which gives references that write them.
|
||||
@optional
|
||||
type mutator: iter<&mut T>;
|
||||
|
||||
#! Lends an iterator that reads the elements.
|
||||
#! @param this The container to iterate.
|
||||
#! @returns The iterator, which refers into the container.
|
||||
def iter(&this): iterator;
|
||||
|
||||
#! Lends an iterator that writes the elements where they are.
|
||||
#! @param this The container to iterate.
|
||||
#! @returns The iterator, which refers into the container.
|
||||
@optional
|
||||
def iter(&mut this): mutator;
|
||||
}
|
||||
|
||||
#! Walks the elements of whatever is indexed by position, from `0` up to a
|
||||
#! length, giving a reference that reads each in turn through its `at`, from
|
||||
#! either end. It is the `iterator` of a container that has no faster way to
|
||||
#! walk its elements, as a ring buffer, whose elements are not one run, so the
|
||||
#! container writes none of its own: `type ring<T>::iterator =
|
||||
#! positions_iterator<ring<T>, T>;`.
|
||||
#!
|
||||
#! It refers to the container rather than to its elements, so it is only good
|
||||
#! while the container stays where it is and holds at least as many elements.
|
||||
#! @tparam C The container, indexed by position.
|
||||
#! @tparam T The type of its elements.
|
||||
pub struct positions_iterator<C, T> : sized_iterator<&T>, backward_iterator<&T> where C: indexable<u64, T> {
|
||||
var _of: *C;
|
||||
var _at: u64;
|
||||
var _left: u64;
|
||||
}
|
||||
|
||||
#! Makes an iterator over the elements of a container, from position `0` up to
|
||||
#! a length.
|
||||
#! @param of The container, which the iterator refers to.
|
||||
#! @param length How many elements it gives, which the container holds.
|
||||
#! @returns The iterator.
|
||||
pub def positions_iterator<C, T>::over(of: &C, length: u64): positions_iterator<C, T> {
|
||||
return positions_iterator::<C, T> { _of = &of, _at = 0, _left = length };
|
||||
}
|
||||
|
||||
#! Gives the next element of the container.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
|
||||
pub def positions_iterator<C, T>::next(&mut this): maybe<&T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
val here := this._at;
|
||||
this._at = here + 1;
|
||||
this._left = this._left - 1;
|
||||
return &(*this._of)[here];
|
||||
}
|
||||
|
||||
#! How many elements the iterator has left to give.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def positions_iterator<C, T>::remaining(&this): u64 {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
#! Gives the last element the iterator has left, from the far end.
|
||||
#! @param this The iterator to advance from its far end.
|
||||
#! @returns Maybe a reference to the element; otherwise, `nothing`.
|
||||
pub def positions_iterator<C, T>::next_back(&mut this): maybe<&T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
this._left = this._left - 1;
|
||||
return &(*this._of)[this._at + this._left];
|
||||
}
|
||||
|
||||
#! Walks the elements of whatever is indexed by position and written there,
|
||||
#! from `0` up to a length, giving a reference that writes each in turn through
|
||||
#! its `at`, from either end. It is the `mutator` of a container that has no
|
||||
#! faster way to walk its elements, as `positions_iterator` is its `iterator`.
|
||||
#!
|
||||
#! It refers to the container rather than to its elements, so it is only good
|
||||
#! while the container stays where it is and holds at least as many elements.
|
||||
#! @tparam C The container, indexed by position and written there.
|
||||
#! @tparam T The type of its elements.
|
||||
pub struct position_mutator<C, T> : sized_iterator<&mut T>, backward_iterator<&mut T> where C: assignable<u64, T> {
|
||||
var _of: *mut C;
|
||||
var _at: u64;
|
||||
var _left: u64;
|
||||
}
|
||||
|
||||
#! Makes an iterator writing the elements of a container, from position `0` up
|
||||
#! to a length.
|
||||
#! @param of The container, which the iterator refers to.
|
||||
#! @param length How many elements it gives, which the container holds.
|
||||
#! @returns The iterator.
|
||||
pub def position_mutator<C, T>::over(of: &mut C, length: u64): position_mutator<C, T> {
|
||||
return position_mutator::<C, T> { _of = &mut of, _at = 0, _left = length };
|
||||
}
|
||||
|
||||
#! Gives the next element of the container, to be written.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
|
||||
pub def position_mutator<C, T>::next(&mut this): maybe<&mut T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
val here := this._at;
|
||||
this._at = here + 1;
|
||||
this._left = this._left - 1;
|
||||
return &mut (*this._of)[here];
|
||||
}
|
||||
|
||||
#! How many elements the iterator has left to give.
|
||||
#! @param this The iterator.
|
||||
#! @returns How many.
|
||||
pub def position_mutator<C, T>::remaining(&this): u64 {
|
||||
return this._left;
|
||||
}
|
||||
|
||||
#! Gives the last element the iterator has left, from the far end, to be
|
||||
#! written.
|
||||
#! @param this The iterator to advance from its far end.
|
||||
#! @returns Maybe a reference to the element; otherwise, `nothing`.
|
||||
pub def position_mutator<C, T>::next_back(&mut this): maybe<&mut T> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
this._left = this._left - 1;
|
||||
return &mut (*this._of)[this._at + this._left];
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
#! @file kinds.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the traits saying what kind of value a type's are: `numeric`, which
|
||||
#! a type implements to have all of arithmetic, and which every number has, and
|
||||
#! those the compiler gives: `integer` and `real`, with the functions parsing
|
||||
#! each from text, `ordinal`, which every integer type and every enum is,
|
||||
#! `zeroable`, which every type with a zero value is, and those naming the parts
|
||||
#! of a type, as `signature` does a function's: `pointer`, `reference`, `array`,
|
||||
#! and `generic`.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! A type with arithmetic.
|
||||
#!
|
||||
#! It composes `additive` and `multiplicative`, and `divisible` and `modular`
|
||||
#! beside them, so it asks for `add`, `sub`, `mul`, `div`, `rem`, and `negate`
|
||||
#! between two values of the type, with their `equals`. `+`, `-`, `*`, `/`, and
|
||||
#! `%` call them, the compound assignments such as `+=` call them too, and `-x`
|
||||
#! calls `negate`. Numbers are numeric without declaring anything. It does not
|
||||
#! ask for an order, so vectors and matrices can be numeric; write
|
||||
#! `where T: numeric, ordered` for both.
|
||||
#!
|
||||
#! A type has each operator by the method that gives it, so one that means only
|
||||
#! some of them declares only those, and satisfies the smaller traits this one
|
||||
#! composes.
|
||||
#!
|
||||
#! Within a generic bounded by it, a constant such as `x + 1`, and `as` between
|
||||
#! numbers, work where `T` is a number and are errors in an instance where it is
|
||||
#! not.
|
||||
pub trait numeric : additive, multiplicative, divisible, modular {}
|
||||
|
||||
#! An integer type, signed or unsigned, of any width.
|
||||
#!
|
||||
#! A type parameter bounded by `integer` has what numbers have, as `numeric` and
|
||||
#! `ordered` give, along with bitwise operators, shifts, and indexing, and it is
|
||||
#! `ordinal`. The compiler decides what is an integer, so no other type can
|
||||
#! implement it.
|
||||
pub trait integer {}
|
||||
|
||||
|
||||
#! Reads the text as a signed 64-bit integer, in decimal or with a `0x`, `0o`,
|
||||
#! or `0b` prefix, where `_` may separate digits.
|
||||
#! @param this The text to read, which may start with `-` or `+`.
|
||||
#! @returns The integer, or why the text is not one.
|
||||
pub def integer::parse<T>(text: strview):
|
||||
result<T, failure> where T : integer
|
||||
{
|
||||
var at := 0u;
|
||||
var neg := false;
|
||||
if text.length > 0 {
|
||||
neg = text[0] == '-';
|
||||
at = (text[0] == '+' || neg) as uint;
|
||||
}
|
||||
|
||||
var base := 10u;
|
||||
if text.length > at + 1 && text[at] == '0' {
|
||||
val marker := text[at + 1];
|
||||
if marker == 'x' || marker == 'X' { base = 16; } else
|
||||
if marker == 'o' || marker == 'O' { base = 8; } else
|
||||
if marker == 'b' || marker == 'B' { base = 2; }
|
||||
|
||||
if base != 10 { at += 2; }
|
||||
}
|
||||
|
||||
return failure { $"`{text}` has no digits" }
|
||||
if at >= text.length;
|
||||
|
||||
const signed := 0x8000000000000000u;
|
||||
const unsigned := 0x7FFFFFFFFFFFFFFFu;
|
||||
val limit := neg ? signed : unsigned;
|
||||
var magnitude := 0u;
|
||||
for byte in text[at:] {
|
||||
continue if byte == '_';
|
||||
|
||||
val digit := byte.digit_value;
|
||||
return failure { $"`{text}` is not a base {base} integer" }
|
||||
if digit >= base;
|
||||
|
||||
return failure { $"`{text}` does not fit in 64 bits" }
|
||||
if magnitude > (limit - digit) / base;
|
||||
|
||||
magnitude = magnitude * base + digit;
|
||||
}
|
||||
|
||||
return neg
|
||||
? (0 - magnitude) as T
|
||||
: magnitude as T;
|
||||
}
|
||||
|
||||
#! A type of real numbers: `f32` or `f64`, or an alias of either.
|
||||
#!
|
||||
#! A type parameter bounded by `real` has what numbers have, as `numeric` and
|
||||
#! `ordered` give, along with a zero value, and `as` to and from the other
|
||||
#! numbers. It is what the functions of `std::math` ask of what they take, as
|
||||
#! `math::sqrt<T>(x: T): T where T: real`. The compiler decides what is real, so
|
||||
#! no other type can implement it.
|
||||
pub trait real {}
|
||||
|
||||
|
||||
#! Reads the text as a real number such as `42`, `-0.5`, `.25`, or `6.02e23`.
|
||||
#! @param this The text to read, which may start with `-` or `+`, and may end
|
||||
#! with an exponent: `e` or `E`, an optional sign, and digits.
|
||||
#! @returns The 64-bit float nearest the number, halfway between two going to
|
||||
#! the one whose last bit is zero, or why the text is not one. A number
|
||||
#! too large for 64 bits is a failure, and one too small is zero.
|
||||
pub def real::parse<T>(text: strview):
|
||||
result<T, failure> where T : real
|
||||
{
|
||||
var at := 0u;
|
||||
var neg := false;
|
||||
if text.length > 0 {
|
||||
neg = text[0] == '-';
|
||||
at = (text[0] == '+' || neg) as uint;
|
||||
}
|
||||
|
||||
# The digits, with at most one `.` among them.
|
||||
val start := at;
|
||||
var digits := 0u;
|
||||
var dotted := false;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte == '.' && !dotted {
|
||||
dotted = true;
|
||||
} else {
|
||||
break if !byte.is_digit;
|
||||
digits++;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
|
||||
return failure { $"`{text}` is not a number" }
|
||||
if digits == 0;
|
||||
|
||||
# The exponent, which is held at a hundred thousand, far past where every number
|
||||
# is too large or too small, so a long one cannot overflow it.
|
||||
var exponent := 0;
|
||||
val written := text.substr(start, at - start);
|
||||
if at < text.length && (text[at] == 'e' || text[at] == 'E') {
|
||||
at++;
|
||||
|
||||
var down := false;
|
||||
if at < text.length {
|
||||
down = text[at] == '-';
|
||||
at += (text[at] == '+' || down) as uint;
|
||||
}
|
||||
|
||||
val first := at;
|
||||
while at < text.length && text[at].is_digit {
|
||||
if exponent < 100000 {
|
||||
exponent = exponent * 10 + (text[at].digit_value as i64);
|
||||
}
|
||||
at++;
|
||||
}
|
||||
|
||||
return failure { $"`{text}` has a malformed exponent" }
|
||||
if at == first;
|
||||
|
||||
if down {
|
||||
exponent = -exponent;
|
||||
}
|
||||
}
|
||||
|
||||
return failure { $"`{text}` is not a number" }
|
||||
if at != text.length;
|
||||
|
||||
return failure { $"`{text}` is too large for 64 bits" }
|
||||
if decimal_digits::nearest(written, exponent)
|
||||
is not some(result);
|
||||
|
||||
return neg
|
||||
? -result as T
|
||||
: result as T;
|
||||
}
|
||||
|
||||
#! A value that is an integer underneath: every integer type, and every enum.
|
||||
#!
|
||||
#! A type parameter bounded by `ordinal` compares with `==`, orders with `<`,
|
||||
#! and converts to and from the integer types with `as`, which is what flags and
|
||||
#! tables indexed by an enum need. An integer becomes an enum only when it is
|
||||
#! some member's value, and stops the program otherwise.
|
||||
#!
|
||||
#! The compiler decides what is ordinal, so no other type can implement it.
|
||||
pub trait ordinal {}
|
||||
|
||||
#! A pointer, whatever it points at, however many pointers deep.
|
||||
#!
|
||||
#! A pointer is an address. It is compared, ordered, and hashed as one, starts
|
||||
#! as `null`, and moves by whole elements, so `p + 1` is the element after `p`,
|
||||
#! and two pointers subtract to the number of elements between them. Nothing of
|
||||
#! what it points at is reached through it: `*p`, `p[i]`, and `through(p)` reach
|
||||
#! that.
|
||||
#!
|
||||
#! A type parameter bounded by `pointer` has what pointers have, as `equatable`,
|
||||
#! `ordered`, and `zeroable` give, along with moving by an integer and
|
||||
#! subtracting. The compiler decides what is a pointer, so no type can implement
|
||||
#! it.
|
||||
#!
|
||||
#! A pointer names what it points at, `T::target`, and whether what it points at
|
||||
#! is written through it, `T::mutable`, so `*mut u8` gives `u8` and `true`. A
|
||||
#! pointer to a pointer gives the pointer it points at, one step at a time.
|
||||
pub trait pointer {
|
||||
#! The type it points at.
|
||||
type target;
|
||||
|
||||
#! Whether it writes what it points at, as `*mut T` does.
|
||||
const mutable: bool;
|
||||
}
|
||||
|
||||
#! A reference, `&T` or `&mut T`.
|
||||
#!
|
||||
#! A reference names what it refers to, `T::target`, and whether it writes it,
|
||||
#! `T::mutable`, so `&mut point` gives `point` and `true`. A type parameter is
|
||||
#! a reference where it was given one, as `f(&x)` gives `T` the reference. A
|
||||
#! reference satisfies other traits through what it refers to, but this one only
|
||||
#! by being one. The compiler decides what is a reference, so no type can
|
||||
#! implement it.
|
||||
pub trait reference {
|
||||
#! The type it refers to.
|
||||
type target;
|
||||
|
||||
#! Whether it writes what it refers to, as `&mut T` does.
|
||||
const mutable: bool;
|
||||
}
|
||||
|
||||
#! A fixed array, `T[N]`.
|
||||
#!
|
||||
#! An array names the type of its elements, `T::element`, and how many it holds,
|
||||
#! `T::length`, so `u8[16]` gives `u8` and `16`. An array of arrays gives the
|
||||
#! array it holds, one step at a time. The compiler decides what is an array, so
|
||||
#! no type can implement it.
|
||||
pub trait array {
|
||||
#! The type of its elements.
|
||||
type element;
|
||||
|
||||
#! How many elements it holds.
|
||||
const length: u64;
|
||||
}
|
||||
|
||||
#! A generic type given its type arguments, as `vector<u8>` or `map<K, V>`.
|
||||
#!
|
||||
#! It names the pack of what it was given, `T::args`, in the order they are
|
||||
#! written, with what a pack parameter was given in its place, so `pair<i64,
|
||||
#! bool>` gives `(i64, bool)`, and `T is vector`, without arguments, says
|
||||
#! whether it is an instance of `vector`. An alias is the type it names, so
|
||||
#! `strview` gives `(u8)` as `span<u8>` does. A type without type parameters, a
|
||||
#! pointer, a reference, an array, and a function are not generic. The compiler
|
||||
#! decides what is generic, so no type can implement it.
|
||||
pub trait generic {
|
||||
#! The type arguments, as a pack, which only the compiler gives.
|
||||
type args...;
|
||||
}
|
||||
|
||||
#! A type with a zero value, which a variable left without a value starts at: a
|
||||
#! number, `bool`, a pointer, an enum with a member of value 0, and an array,
|
||||
#! struct, or union of what is, where a struct's fields with defaults start at
|
||||
#! their defaults instead. A reference or a function is not, nor is what holds
|
||||
#! one.
|
||||
#!
|
||||
#! Generic code bounded by it may write `var made: T;`, and code that only may
|
||||
#! asks `if const T is zeroable` first.
|
||||
#!
|
||||
#! The compiler decides what is zeroable, so no type can implement it.
|
||||
pub trait zeroable {}
|
||||
@@ -0,0 +1,169 @@
|
||||
#! @file ownership.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the traits saying what becomes of a value: `owning`, which a type
|
||||
#! names to own what it holds and close it where its values go away, with the
|
||||
#! function closing a value where it stands; `closeable`, which the compiler
|
||||
#! gives every type whose values are closed; `copyable`, with `copy`, which
|
||||
#! copies a value through it, or byte for byte where nothing it holds closes;
|
||||
#! and `moveable`, with `move`, which moves a value through it, or byte for
|
||||
#! byte.
|
||||
|
||||
module core;
|
||||
|
||||
|
||||
#! Defines that a type owns what it holds, such as memory or a file, and
|
||||
#! disposes of it in `close`. A value of a type naming `owning` is closed where
|
||||
#! its scope ends, as RAII does, so that something like an allocator or
|
||||
#! collection has released its data by the time it goes away.
|
||||
#!
|
||||
#! A type is owning only by naming the trait, so a `close` meant to be called by
|
||||
#! hand never becomes a destructor by accident. A reference to an owning value
|
||||
#! owns nothing, so it is never owning, though `close` is called through it.
|
||||
#!
|
||||
#! Unlike `copyable` and `moveable`, nothing fails where a type is not owning:
|
||||
#! generic code asks `if const owns::<T>::value`, or calls `close`, which closes
|
||||
#! whatever is given as its scope ending would.
|
||||
pub trait owning {
|
||||
#! Disposes of what the value owns, as its scope ending does.
|
||||
#! @param this The value to close, which should be left empty, so closing it
|
||||
#! again does nothing.
|
||||
def close(&mut this): void;
|
||||
}
|
||||
|
||||
#! Closes a value where it stands, as its scope ending would: through its own
|
||||
#! `close` where it is `owning`, then each value it holds that closes, such as
|
||||
#! a `string` in a field, the last first. A value that closes nothing is left
|
||||
#! alone.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to close, which is left empty.
|
||||
#! @remarks Containers close their elements with it, so that an element holding
|
||||
#! something that closes is closed as a local holding it would be.
|
||||
pub def close<T>(value: &mut T): void {
|
||||
if const T is closeable {
|
||||
close_where_it_is(value);
|
||||
memset(value as *mut u8, 0, size_of::<T>());
|
||||
}
|
||||
}
|
||||
|
||||
# Closes a value where it is, as the compiler closes a local whose scope ends:
|
||||
# its own `close` where it is `owning`, then each field that closes, the last
|
||||
# first, or the field a union holds, or each element of a fixed array.
|
||||
@intrinsic
|
||||
def close_where_it_is<T>(value: &mut T): void;
|
||||
|
||||
#! A type whose values are closed where they go away: one that is `owning`, or
|
||||
#! one holding a value that is, in a field or an element.
|
||||
#!
|
||||
#! Generic code asks `if const T is closeable` where what it does only matters
|
||||
#! for values that close, such as emptying the memory a value was moved out of
|
||||
#! so that it is not closed twice, which plain data has no need of.
|
||||
#!
|
||||
#! The compiler decides what is closeable, so no type can implement it.
|
||||
pub trait closeable {}
|
||||
|
||||
#! A type whose values can be copied, by a static function building a copy of
|
||||
#! another value.
|
||||
#!
|
||||
#! The function is static, and gives the copy back rather than filling a
|
||||
#! destination that already exists, so that returning it writes straight into
|
||||
#! whatever takes it and nothing throwaway is built on the way.
|
||||
#!
|
||||
#! A type that must not be copied simply does not implement this trait, which is
|
||||
#! why the function gives the copy rather than an error: the type system says
|
||||
#! what cannot be copied, and running out of memory stops the program, as
|
||||
#! `acquire` does.
|
||||
pub trait copyable {
|
||||
#! Builds a copy of a value, which owns copies of whatever the value owns.
|
||||
#! @param other The value to copy.
|
||||
#! @returns The copy.
|
||||
def copy_of(other: &self): self;
|
||||
}
|
||||
|
||||
#! Shortcut function for copying a value, giving the copy back.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param src The source object to copy.
|
||||
#! @returns The copy, which whatever takes it owns. A type that is `copyable` is
|
||||
#! copied by its `copy_of`, and one that closes nothing byte for byte.
|
||||
#! @remarks The copy is given back rather than written into a destination that
|
||||
#! already exists, so that returning it writes straight into whatever
|
||||
#! takes it. A type that closes, or holds what does, and is not
|
||||
#! `copyable` is an error where it is copied, since its bytes would
|
||||
#! share what it closes, and both copies would close it.
|
||||
pub def copy<T>(src: &T): T {
|
||||
if const T is copyable {
|
||||
return T::copy_of(src);
|
||||
}
|
||||
if const T is closeable {
|
||||
compile_error("`copy` copies a value that closes, or holds one that does, only through `copyable`, which this type does not implement.");
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
#! Defines that a type or generic must conform to being moveable, where the data
|
||||
#! of one object is handed to a new one and the source left empty.
|
||||
#!
|
||||
#! The function is static, and gives the moved value back rather than filling a
|
||||
#! destination that already exists, so that returning it writes straight into
|
||||
#! whatever takes it and nothing throwaway is built on the way.
|
||||
#!
|
||||
#! The source is `&mut` because a move empties it, which is the whole difference
|
||||
#! between this and `copyable`. What it leaves is valid but empty rather than
|
||||
#! dead, so closing it afterwards is harmless.
|
||||
pub trait moveable {
|
||||
#! Builds a value from what another holds, leaving the other empty.
|
||||
#! @param other The value to move from, which is left empty but valid.
|
||||
#! @returns The new value, holding what the other held.
|
||||
def move_of(other: &mut self): self;
|
||||
}
|
||||
|
||||
#! Moves a value out of where it stands, leaving it empty.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param src The value to move from, which holds nothing after.
|
||||
#! @returns The moved value, which whatever takes it owns. A type that is
|
||||
#! `moveable` is moved by its `move_of`, and any other byte for byte.
|
||||
#! @remarks The source is left valid but empty rather than dead, so closing it
|
||||
#! afterwards is harmless: one that closes, or holds what does, is
|
||||
#! zeroed. Plain data, which nothing closes, is left as it was.
|
||||
pub def move<T>(src: &mut T): T {
|
||||
if const T is moveable {
|
||||
return T::move_of(src);
|
||||
}
|
||||
|
||||
# Plain data, which nothing closes, is copied as it is.
|
||||
if const !(T is closeable) {
|
||||
return src;
|
||||
}
|
||||
|
||||
# Fallback: read the value out byte for byte, then leave the source zeroed, so it
|
||||
# is not closed twice: by a store of each word where it is one to four words, as
|
||||
# most that close are, and by `memset` otherwise.
|
||||
val made := bits_of(src as *T);
|
||||
val words := src as *mut u64;
|
||||
if const size_of::<T>() == 8 {
|
||||
words[0] = 0;
|
||||
} else if const size_of::<T>() == 16 {
|
||||
words[0] = 0;
|
||||
words[1] = 0;
|
||||
} else if const size_of::<T>() == 24 {
|
||||
words[0] = 0;
|
||||
words[1] = 0;
|
||||
words[2] = 0;
|
||||
} else if const size_of::<T>() == 32 {
|
||||
words[0] = 0;
|
||||
words[1] = 0;
|
||||
words[2] = 0;
|
||||
words[3] = 0;
|
||||
} else {
|
||||
memset(src as *mut u8, 0, size_of::<T>());
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# The value a pointer points at, byte for byte. A `return` hands over what a pointer
|
||||
# points at without emptying it, so the caller decides what is left there.
|
||||
def bits_of<T>(from: *T): T {
|
||||
return from[0];
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
#! @file u8.ext.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what a byte of text is asked: whether it is a letter, a digit of
|
||||
#! some base, whitespace, or one of several bytes, and its letter's other case.
|
||||
|
||||
module core;
|
||||
|
||||
#! The zero byte, which ends text C reads and marks the end of text a scanner
|
||||
#! reads.
|
||||
pub const nullbyte: u8 = '\0';
|
||||
#! The line feed byte, `'\n'`, which ends a line.
|
||||
pub const newline: u8 = '\n';
|
||||
|
||||
#! Whether the byte is the zero byte.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is `'\0'`.
|
||||
pub val u8::is_null: bool { get => this == nullbyte; }
|
||||
|
||||
#! Whether the byte marks the end of text, as the zero byte does to a scanner.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is `'\0'`.
|
||||
pub val u8::is_eof: bool { get => this == nullbyte; }
|
||||
|
||||
#! Whether the byte ends a line.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is `'\n'`.
|
||||
pub val u8::is_eol: bool { get => this == newline; }
|
||||
|
||||
#! Whether the byte is whitespace.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is a space, or a tab, line feed, vertical tab, form feed,
|
||||
#! or carriage return.
|
||||
@inline
|
||||
pub val u8::is_space: bool {
|
||||
get => this == ' ' || (this >= '\t' && this <= '\r');
|
||||
}
|
||||
|
||||
#! Whether the byte is an uppercase ASCII letter.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is one of `A` to `Z`.
|
||||
@inline
|
||||
pub val u8::is_upper: bool { get => this >= 'A' && this <= 'Z'; }
|
||||
|
||||
#! Whether the byte is a lowercase ASCII letter.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is one of `a` to `z`.
|
||||
@inline
|
||||
pub val u8::is_lower: bool { get => this >= 'a' && this <= 'z'; }
|
||||
|
||||
#! The byte in uppercase, where it is a lowercase ASCII letter.
|
||||
#! @param this The byte to convert.
|
||||
#! @returns The uppercase letter, or the byte as it is where it is no lowercase
|
||||
#! letter.
|
||||
@inline
|
||||
pub val u8::to_upper: u8 { get => this.is_lower ? this - 32 : this; }
|
||||
|
||||
#! The byte in lowercase, where it is an uppercase ASCII letter.
|
||||
#! @param this The byte to convert.
|
||||
#! @returns The lowercase letter, or the byte as it is where it is no uppercase
|
||||
#! letter.
|
||||
@inline
|
||||
pub val u8::to_lower: u8 { get => this.is_upper ? this + 32 : this; }
|
||||
|
||||
#! Whether the byte is an ASCII letter of either case.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is a letter.
|
||||
pub val u8::is_alpha: bool { get => this.is_lower || this.is_upper; }
|
||||
|
||||
#! Whether the byte is an ASCII letter or a decimal digit.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is a letter or a digit.
|
||||
pub val u8::is_alnum: bool { get => this.is_alpha || this.is_digit; }
|
||||
|
||||
#! Whether the byte may begin a name: a letter, or `_`.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is a letter or `_`.
|
||||
pub val u8::is_name: bool { get => this.is_alpha || this == '_'; }
|
||||
|
||||
#! Whether the byte may go on a name: a letter, a digit, or `_`.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is a letter, a digit, or `_`.
|
||||
pub val u8::is_ident: bool { get => this.is_alnum || this == '_'; }
|
||||
|
||||
#! Whether the byte is a decimal digit.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is one of `0` to `9`.
|
||||
@inline
|
||||
pub val u8::is_digit: bool { get => this >= '0' && this <= '9'; }
|
||||
|
||||
#! Whether the byte is a binary digit.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is `0` or `1`.
|
||||
pub val u8::is_bin: bool { get => this == '0' || this == '1'; }
|
||||
|
||||
#! Whether the byte is an octal digit.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is one of `0` to `7`.
|
||||
pub val u8::is_oct: bool { get => this >= '0' && this <= '7'; }
|
||||
|
||||
#! Whether the byte is a lowercase letter a hexadecimal digit may be.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is one of `a` to `f`.
|
||||
pub val u8::is_hex_lower: bool { get => this >= 'a' && this <= 'f'; }
|
||||
|
||||
#! Whether the byte is an uppercase letter a hexadecimal digit may be.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is one of `A` to `F`.
|
||||
pub val u8::is_hex_upper: bool { get => this >= 'A' && this <= 'F'; }
|
||||
|
||||
#! Whether the byte is a hexadecimal digit, of either case.
|
||||
#! @param this The byte to check.
|
||||
#! @returns Whether it is a decimal digit, or one of `a` to `f` or `A` to `F`.
|
||||
pub val u8::is_hex: bool {
|
||||
get => this.is_digit || this.is_hex_lower || this.is_hex_upper;
|
||||
}
|
||||
|
||||
#! Gives the value of the current byte as a digit of any base up to 36, where
|
||||
#! the letters follow `9` in either case.
|
||||
#! @param this The byte to convert.
|
||||
#! @returns The value of the digit, or 99 when the byte is not a digit.
|
||||
pub val u8::digit_value: u64 {
|
||||
get {
|
||||
if this.is_digit { return this - '0'; }
|
||||
if this.is_lower { return this - 'a' + 10; }
|
||||
if this.is_upper { return this - 'A' + 10; }
|
||||
return 99;
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks if the current byte is a digit of the given base, of any base up to
|
||||
#! 36, where the letters follow `9` in either case, as `digit_value` reads them.
|
||||
#! @param this The byte that we are checking.
|
||||
#! @param base The base of the number we are checking for.
|
||||
#! @returns Whether the byte is a digit of the given base.
|
||||
pub def u8::is_base_digit(&this, base: u8): bool {
|
||||
return this.digit_value < base as u64;
|
||||
}
|
||||
|
||||
#! Whether the byte is any of several bytes.
|
||||
#! @param this The byte to check.
|
||||
#! @param chars The bytes to look for.
|
||||
#! @returns Whether it is one of them.
|
||||
pub def u8::matches(&this, chars: u8...): bool {
|
||||
for value in chars { return true if this == value; }
|
||||
return false;
|
||||
}
|
||||
Reference in new issue
Block a user