Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-27 16:22:18 -05:00
commit a250609dff
1625 files changed
+43221

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
+1
View File
@@ -0,0 +1 @@
.blossom
+58
View File
@@ -0,0 +1,58 @@
# Changelog
Each version's changes, newest first. Versions follow [semantic
versioning](https://semver.org).
## 1.0.0 - Unreleased
- The standard library, moved out of the Sakura compiler's repository into one
of its own, each module a library of its own in the folder of its name:
`std::containers`, `std::allocators`, `std::io`, `std::math`, `std::time`,
`std::thread`, `std::process`, `std::serial`, `std::testing`, `std::text`,
`std::net`, `std::semver`, `std::json`, `std::yaml`, and `std::args`. A
program requires the repository and names among its `deps` the modules it
reads, as `std.io`.
- There is no module `std` itself. What its root held went to modules of
their own:
- `deque`, `list`, `chain`, `heap`, `queue`, `stack`, `groups`, `runs`, and
`interner` to `std::containers`, and `pool` to `std::allocators`;
- `byte_writer` to `std::io`, where it's the stream that writes to memory,
with a `write`, so it's `writable`;
- regular expressions to `std::text`, URIs to `std::net`, with `std::io`'s
`uri::from_path` and `uri::to_path`, and versions to `std::semver`;
- `predicate`, which nothing used, went.
- `std::io` reads nothing of URIs or containers now, so a program printing a
line reads less.
- What `core` held that the compiler doesn't name, and that `core`, `system`,
and the runtime aren't built from, is std's:
- `dict`, `hashset`, `rc`, `arc`, `rc_weak`, and `arc_weak` are
`std::containers`', and `arena` is `std::allocators`';
- the streams' traits, `readable`, `writable`, and `flushable`, are
`std::io`'s, with `string`'s `write` and `strview`'s `read`, so a string is
`writable` where a file imports `std::io`;
- `io_error` is `system`'s, which reports it, so a file naming it imports
`system`.
- std declares no intrinsic: `std::math` builds on `core::intrinsics`'s
`square_root`, `lanes_have`, and `lanes_apply`, and its own `count_ones`,
`leading_zeros`, `trailing_zeros`, and `swap_bytes` went, since `core`'s are
the same. `std::thread` starts its threads with `system::start`.
- `std::json`, `std::yaml`, and `std::args`, packages of their own since
2026-10-24, joined again, keeping their names, with their tests and JSON's and
YAML's conformance suites.
- `std::io::glob`, globs read, matched, and found, which was `malunal::glob`, a
package of its own, is a module within `std::io`, which the library `std.io`
holds.
- Each module's tests, in `tests/` in the folder of its name, built and run as
executables, `std::serial`'s through JSON and YAML among them. Those of
`core` and `system` stayed with the compiler, but for those testing what came
here from `core`.
- `std::xml`, which reads XML 1.0 strictly, with Namespaces in XML 1.0:
`xml::parse` into a `xml::document` of elements, attributes, text, comments,
and processing instructions, and `xml::reader`, one token at a time. The
document type's internal subset is read, and its entities, attributes'
defaults, and attribute types used; nothing outside the text is. Limits on
depth and on what entities expand to stop text written to exhaust a reader.
- A program built without blossom finds the standard library as `sakurac`
does: the folder `--lib std=DIR` names, or a `std` folder beside the compiler
or above it, or its libraries in the `share/sakura` folder above it, where
`blossom install` puts them.
+18
View File
@@ -0,0 +1,18 @@
MIT License
Copyright (c) 2026 Malunal Studios, LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
+197
View File
@@ -0,0 +1,197 @@
# std
The Sakura programming language's standard library: what programs build on beyond `core` and `system`, which ship with the compiler, [sakurac](https://git.malunal.studio/sakura/sakurac). Each module is a library of its own, in the folder of its name, which reads `core`, `system`, and the modules it lists:
| Module | Folder | Holds |
|---|---|---|
| `std::containers` | `containers/` | `dict`, `hashset`, `deque`, `list`, `chain`, `heap`, `queue`, `stack`, `groups`, `runs`, and `interner`, beside `core`'s `vector`; and `rc` and `arc`, owners shared by every copy, beside `core`'s `box` |
| `std::allocators` | `allocators/` | `arena` and `pool` |
| `std::io` | `io/` | The console, files, directories, paths, and pipes; the streams' traits, `readable`, `writable`, and `flushable`, and the streams `reader`, `writer`, and `byte_writer`; and globs, as [`std::io::glob`](io/glob/README.md), in `io/glob/` |
| `std::process` | `process/` | Running other programs |
| `std::thread` | `thread/` | Threads, and what guards what they share: mutexes, conditions, channels, and `once` |
| `std::time` | `time/` | Lengths of time, the clocks, the calendar, time zones, and RFC 3339 text |
| `std::math` | `math/` | The functions of real numbers and their constants, and the operations of integers the operators don't give |
| `std::serial` | `serial/` | Writing and reading typed values by their `@serial` marks, in any format |
| `std::testing` | `testing/` | Tests found by reflection |
| `std::text` | `text/` | Regular expressions |
| `std::net` | `net/` | URIs, and the `file` URIs of paths |
| `std::semver` | `semver/` | Semantic versions |
| [`std::json`](json/README.md) | `json/` | JSON, read and written strictly, as RFC 8259 writes it |
| [`std::yaml`](yaml/README.md) | `yaml/` | YAML 1.2.2, read and written by its core schema |
| [`std::xml`](xml/README.md) | `xml/` | XML 1.0, read strictly, with its namespaces and its document type's internal subset |
| [`std::args`](args/README.md) | `args/` | A program's arguments, read into a struct by its marks, and the help they write |
std is built on `core` and `system` alone, declares no intrinsic, and holds nothing the compiler names, so it changes as a library does, versioned apart from the compiler.
## Using it
Require it in your blossomfile, and name among a target's `deps` the modules it reads:
```yaml
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
targets:
- name: app
type: program
deps: [std.io, std.time]
```
blossom gives each with `--lib`, as `--lib std::io=DIR`. A program built without blossom reads the standard library the compiler finds:
- the folder `--lib std=DIR` names, as this repository checked out;
- or else a `std` folder beside the `sakurac` executable or in the nearest folder above it, as a copy of this repository;
- or else its libraries in the `share/sakura` folder nearest above the executable, as `share/sakura/std.io` for `std::io`, where `blossom install` puts them.
Installed with `blossom install --prefix ~/.local`, it's found by a `sakurac` in `~/.local/bin`.
There is no module `std` itself: a file imports the modules it uses.
## The modules
**Files**: `std::io` takes `path`s, and gives what can fail inside a `result` with an `io_error`:
```sakura
val dir := path::parse("build") else (_) { return; };
io::create_directories(dir) else (e) { println($"cannot make it: {e}"); return; };
val notes := dir.join("notes.txt");
io::write_file(notes, "first\n") else (e) { return; };
val text := io::read_file(notes) else (e) { return; };
var listing := io::directory::open(dir) else (_) { return; };
for entry in listing { println($"{entry.name} {entry.kind}"); } # notes.txt regular
```
On Windows, paths are UTF-8 to the program, as arguments and variables are, and UTF-16 to the system. Windows keeps only whether a file is read only, so setting `permissions` looks only at whether the owner may write, and they read as everyone reading the file, writing it unless it is read only, and running it where it is a directory or its name ends in `.exe`, `.com`, `.bat`, or `.cmd`.
**Streams**: anything bytes are read from is `readable`, and anything they're written to is `writable`, so one function serves files, the console, and strings. A `string` is `writable`, and a `strview` `readable`, where a file imports `std::io`, which declares their `write` and `read`. `io::reader_of` and `io::writer_of` buffer any stream, `byte_writer` writes to memory, laying words out one after another as a binary format wants them, and `io::read_line()` reads the standard input.
**Programs**:
```sakura
var git := process::command::new("git");
git.arguments(["rev-parse", "HEAD"]);
val head := git.capture() else (e) { return; }; # head.output, head.error, head.status
```
A name without a `/` is looked for in the `PATH` the child will have. On Windows, a `\` or a drive, as `C:`, also makes a name a path, `PATH` is split at `;`, a name ending in none of the endings `PATHEXT` lists is tried with each of them, and variables are the same whatever their case, as `Path` is `PATH`. A batch file is run by `cmd.exe`, which can't be given an argument holding a `"`, a `%`, or a new line unchanged, so one with such an argument fails with `invalid` rather than start.
**Typed values** are written and read by their marks:
```sakura
@serial struct position { @serial var line: u32; @serial{ name = "char" } var column: u32; }
val text := json::to_text(&position{ line = 3, column = 7 }) else (_) { return; }; # {"line":3,"char":7}
val back := json::from_text::<position>(text.view()) else (e) { return; };
```
**Arguments** are read into a struct the program marks, whose marks also write the help text, by `std::args`, whose [README](args/README.md) says what it reads and how:
```sakura
@command{ name = "greet", help = "Greets people.", version = "1.0" }
struct greet {
@option{ short = 'n', value = "N", help = "How many times." } var times: u32 = 1;
@option{ short = 'l', help = "Says it loudly." } var loud: bool;
@argument{ value = "NAME", help = "Whom to greet." } var names: vector<strview>;
}
def main(args: span<strview>): void {
val given := args::parse_or_exit::<greet>(args); # greet -l -n2 Ann Bo, or greet --help
for &name in given.names {
for _ in 0..given.times { println(given.loud ? $"HELLO, {name}!" : $"Hello, {name}!"); }
}
}
```
**Time**: `std::time` has lengths of time, moments of two clocks, and the calendar in any zone:
```sakura
import std::time;
val began := instant::now(); # the steady clock, for measuring
build();
println($"built in {began.elapsed().describe()}"); # built in 2.31s
val now := timestamp::now(); # the wall clock, in UTC
println(now.rfc3339()); # 2026-10-07T12:42:03.451Z
println(now.at(zone::local()).rfc3339()); # 2026-10-07T07:42:03.451-05:00
val due := date::of(2026, month::october, 31) else (e) { return; };
println(due.plus_months(1).iso()); # 2026-11-30
```
- **Arithmetic is operators.** Durations add, subtract, and negate, scale by a count, and divide into a ratio: `seconds(90) + milliseconds(500)`, `timeout * 2`, `done / total`. A moment moves by a duration, and one less another is the duration between them: `deadline - instant::now()`.
- **Durations** are made by `nanoseconds`, `microseconds`, `milliseconds`, `seconds`, `minutes`, and `hours`, and read by `in_nanoseconds` and `in_seconds`.
- **The range**: moments and durations count nanoseconds in an `i64`, so a `timestamp` reaches from 1677 to 2262. Arithmetic past that stops the program, as indexing past an end does.
- **Two clocks**: an `instant` never goes back, and means nothing but against another. A `timestamp` says when, and the system may set its clock back.
- **The calendar** is the Gregorian one, without leap seconds. `date` has `weekday`, `day_of_year`, `plus_days`, `plus_months`, `days_since`, and `iso`.
- **Zones**: `zone::utc()`, `zone::fixed(offset)`, `zone::named("Asia/Tokyo")` from the system's database, and `zone::local()`. Windows keeps no database, so there `zone::named` reads the directory `TZDIR` names, and finds no zone without it, and `zone::local()` is the rule the system's setting keeps the clocks by now, which says nothing of the years before that rule. `timestamp::at` gives the `date_time` a zone's clocks show, and `zone::resolve` the moment they show a date and time: one they skip is taken that long after the change, and one they show twice at its first.
- **Text**: `rfc3339` writes a moment, and `parse_rfc3339` and `parse_date` read one, giving a `time::error` for text that is none.
- **Waiting**: `time::sleep(milliseconds(50))`. A signal the program handles ends the wait, as it ends every wait.
**Math**: `std::math` has the functions of real numbers, for `f32` and `f64` alike, and the operations of integers that the operators don't give:
```sakura
import std::math;
val length := math::sqrt(x * x + y * y); # an f64, as x and y are
val angle: f32 = math::atan2(dy, dx); # an f32, as dy and dx are
val half := math::sin(math::pi / 6); # 0.49999999999999994, not 0.5
val wrapped := math::div_floor(-7, 2); # -4, where -7 / 2 is -3
val sum := math::checked_add(a, b) else { return; }; # nothing where it overflows
```
- **Functions** of any `T` that is `real`: `sqrt`, `cbrt`, `hypot`, `exp`, `exp2`, `expm1`, `log`, `log2`, `log10`, `log1p`, `pow`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, and `atanh`, all in radians.
- **Exact operations**: `floor`, `ceil`, `trunc`, `round`, which takes halves away from zero, `round_even`, `copysign`, and `fma`, which rounds once. `abs`, `min`, `max`, and `clamp` take any ordered type, as integers and `duration`s. Of reals, `min` and `max` give NaN where either is NaN, and put `-0` below `0`.
- **The same bits everywhere**: the functions are std's own Sakura, ported from musl, so they give the same results in the VM, in executables, and in constants. `sqrt` is the machine's, correctly rounded. Results are within an ulp of the true value, but for `atan2`, `sinh`, `tanh`, `asinh`, `acosh`, and `atanh`, which are within 2, as musl's are. An `f32` is worked in `f64` and rounded, which is almost always the nearest `f32`.
- **Nothing stops the program**: a result outside a function's domain is NaN, and one too large is infinity, as IEEE 754 says.
- **Constants**: `pi`, `tau`, `e`, `sqrt_2`, `ln_2`, and `ln_10` are `f64`s, which `as f32` rounds for floats. `largest`, `smallest`, `epsilon`, `infinity`, and `nan` are per type, as `math::infinity::<f32>()`.
- **Classifying**: `is_nan`, `is_infinite`, `is_finite`, `is_subnormal`, and `sign_bit`, and a real's bits, `bits_of` and `real_of_bits`.
- **Integers**, of every integer type: `rotate_left` and `rotate_right`. `count_ones`, `leading_zeros`, `trailing_zeros`, and `swap_bytes` are `core`'s, with no import. `checked_add`, `checked_sub`, `checked_mul`, and `checked_pow` give `nothing` where the result overflows, and the `saturating_` ones hold it at the type's limit. Also `int_pow`, `gcd`, `lcm`, `isqrt`, `div_floor`, and `rem_floor`.
- **An element read by indexing is a reference**, which is not `real`, so give the type: `math::sqrt::<f64>(xs[i])`.
**Threads** run functions at the same time, sharing the program's memory. A thread's handle is `owning`, and closing it waits for the thread, so a thread started in a scope ends before the scope does:
```sakura
import std::thread;
var total := thread::mutex::<u64>::new(0);
{
var workers := vector::<thread::handle<void>>::new();
for part in 0..thread::cpu_count() {
var started := thread::spawn(def() {
val sum := add_up(part);
var held := total.lock(); # unlocks where `held` closes
held.value() += sum;
}) else (e) { return; };
workers.append(move(started));
}
} # closing `workers` joins every thread
var parsed := thread::spawn(def(): u64 { return parse_all(); }) else (e) { return; };
println($"{parsed.join()}"); # what the function gave
var jobs := thread::channel::<job>::new(64); # at most 64 waiting; 0 for no bound
var worker := thread::spawn(def() { while jobs.receive() is some(next) { run(next); } }) else (e) { return; };
jobs.send(make_job()) else (j) { ... };
```
- **Starting one**: `spawn` takes a function, and `join` gives back what it gave, `void` where it gives nothing. `spawn_with(f, move(x))` gives the function a value the thread then owns alone, and closes where it ends. A closure refers to the locals it uses, as every closure does, so a thread may use the locals of the scope starting it while its handle is open, since closing the handle waits for the thread; a loop's variable, which changes, is given with `spawn_with`.
- **Guarding what's shared**: a `mutex<T>` owns its value, and `lock` gives a `@nodiscard` guard lending it, which unlocks where it closes; `try_lock` doesn't wait. A `condition`'s `wait` lets go of a mutex until notified, and `wait_for` until a time passes too. A `channel<T>` hands each value sent to one receiver, in the order one sender sent them; `close` wakes every waiter, gives back what's sent after, and closes what it held. `once` runs a function once however many threads ask. Atomics are the rest.
- **A race is the program's mistake**: two threads touching the same memory that isn't atomic or guarded, at least one writing, with neither happening before the other. What either then reads isn't defined. Containers take no lock; share one through a `mutex`. `print` and `println` hold the standard output for each call, so lines from two threads never mix, and `io::output_locked()` holds it across several.
- **Stopping**: a fault in any thread stops the program with that thread's trace, and `system::exit` from any thread stops them all. Signal handlers run in the thread the program began with. A program forks before it starts threads, as `std::testing` does for each test on Linux.
- **In the VM**, threads take turns running bytecode, one at a time, letting the next run as they wait and every few thousand steps; executables run them in parallel. A program right in one is right in the other. No thread starts while compiling.
- **Also**: `thread::sleep`, `thread::id()`, `thread::cpu_count()`, and in `system`, `futex_wait` and `futex_wake`, which the rest is built on.
**Tests** are functions marked `@test`, each run in a copy of the program, so one that faults fails alone:
```sakura
import system;
import std::testing;
@test def adds(t: &mut tester): void { t.expects(1 + 1 == 2); }
def main(args: span<strview>): void { exit(tester::run(args)); }
```
`t.expects(cond)` reports a failed condition as written, with its operands' values. A test may take a `fixture`, and `--only TEXT` runs the tests whose names hold the text.
Windows can't fork, and `system::fork` gives `unsupported` there, so each copy is the program started again, with the same command line and `SAKURA_TEST_ONE` naming the one test it runs. What the program does before `tester::run`, each copy does again.
## Testing
From the repository's root, `blossom test` runs each module's tests as a test of its own, built and run as an executable, or, for those of `std::io`:
```sh
sakurac run --lib std=. tests/main.sakura tests/io/*.sakura tests/io/glob/*.sakura
```
The tests of `std::serial` write and read through JSON and YAML. JSON's and YAML's conformance suites are in `tests/json/parsing` and `tests/yaml/suite`, under their licenses, and are found from the root.
## License
MIT. See [LICENSE](LICENSE).
+287
View File
@@ -0,0 +1,287 @@
#! @file arena.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the `arena` allocator, which hands out blocks of large chunks of
#! memory one after another and takes them all back at once.
module std::allocators;
#! An allocator handing out blocks of chunks of memory one after another, which
#! it owns, and taking them all back at once.
#!
#! A block is handed out where the last one ended, which costs a comparison and
#! an addition, and none is given back by itself: they all go back where the
#! arena is reset, rewound, or closed. The last block handed out grows and
#! shrinks where it is, and goes back where it is disposed of. What a block
#! holds at first may be anything.
#!
#! An arena is for memory whose lifetime is one phase of the work, as what a pass
#! of a compiler makes and drops: `reset` frees all of it at once and keeps the
#! chunks for the next phase, and `mark` and `rewind` free what was handed out
#! after a point, as a stack does. Nodes linked to one another by reference may
#! live in one, as long as nothing refers to them past where it frees them.
#! @remarks A container given an arena refers to it, so the arena must not move
#! while one does, and must not be reset, rewound, or closed while one
#! holds memory it handed out.
pub struct arena : allocator, owning {
var _size: u64; #! How many bytes each chunk it takes holds, at least.
var _blocks: arena::run; #! Its blocks, from its chunks.
}
#! Where an arena had handed out to, which `rewind` takes it back to.
pub struct arena::point {
var _spot: arena::spot; #! Where it had handed out to.
}
# Where a run of blocks had handed out to.
struct arena::spot {
var chunk: *mut arena::chunk; # The chunk it handed out of, or null.
var at: *mut u8; # Where the next block would have begun.
}
# The blocks an arena hands out, from a list of chunks.
struct arena::run {
var first: *mut arena::chunk; # The first chunk, or null where it has none.
var chunk: *mut arena::chunk; # The chunk it hands out of, or null.
var at: *mut u8; # Where the next block begins.
var end: *mut u8; # Where the chunk's memory ends.
var last: *mut u8; # The last block it handed out, while it may grow.
}
# A chunk: this header, then the memory blocks are handed out of.
struct arena::chunk {
var next: *mut arena::chunk; # The chunk after it, or null.
var size: u64; # The bytes of memory after the header.
var owned: bool; # Whether the arena took it, and gives it back.
}
#! The fewest bytes a chunk of an arena holds.
pub const arena::least: u64 = 256;
#! Makes an arena that takes chunks of 64 KiB from the program's heap as it needs
#! them.
#! @returns The arena, which holds no memory yet.
pub def arena::new(): arena {
return arena::new(65536);
}
#! Makes an arena that takes chunks of at least a size from the program's heap as
#! it needs them. A block larger than that has a chunk of its own size.
#! @param size How many bytes each chunk holds, at least, which is raised to
#! `arena::least`.
#! @returns The arena, which holds no memory yet.
pub def arena::new(size: u64): arena {
return arena { _size = size < arena::least ? arena::least : size };
}
#! Makes an arena that hands out the bytes of a buffer first, then takes chunks
#! of 64 KiB from the program's heap once the buffer is full.
#! @param buffer The bytes to hand out first, which the arena never gives back
#! and which must outlive it.
#! @returns The arena.
pub def arena::over(buffer: slice<u8>): arena {
var made := arena::new();
val low := align(buffer.data as u64, max_align);
val high := buffer.data as u64 + buffer.length;
if high < low || high - low < arena::header() + max_align {
return made;
}
val chunk := low as *mut arena::chunk;
(*chunk).next = null;
(*chunk).size = high - low - arena::header();
(*chunk).owned = false;
made._blocks.first = chunk;
made._blocks.enter(chunk);
return made;
}
#! Gives back every chunk the arena took, which frees every block it handed out.
#! @param this The arena to close.
#! @remarks A buffer it was made over is not given back. The arena is left
#! holding nothing, so it may hand out blocks again.
pub def arena::close(&mut this): void {
this._blocks.free();
}
#! Hands out a block after the last it handed out, or at the start of another
#! chunk where the chunk has too little left.
#! @param this The arena 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, which may hold anything at first.
#! @remarks Where the program's heap gives no memory, the program stops, so this
#! never gives `null`.
pub def arena::acquire(&mut this, size: u64, align: u64): *mut u8 {
return this._blocks.take(size, align, this._size);
}
#! Takes back a block, which an arena does only for the last it handed out, so
#! that the next block takes its place. Any other goes back where the arena is
#! reset, rewound, or closed.
#! @param this The arena the block came from.
#! @param addr The block.
#! @param size The number of bytes it was acquired or last resized with.
pub def arena::dispose(&mut this, addr: *mut u8, size: u64): void {
this._blocks.give_back(addr, size);
}
#! Hands out a block of another size holding what a block it handed out held.
#! The last block it handed out grows or shrinks where it is while its chunk has
#! room; any other is copied to a new block.
#! @param this The arena the block came from.
#! @param addr The block to resize, or `null` to acquire one.
#! @param old The number of bytes it was acquired or last resized with.
#! @param size The number of bytes the new block holds.
#! @param align What the address of its first byte is a multiple of.
#! @returns The new block, which may hold anything past what it keeps.
pub def arena::resize(&mut this, addr: *mut u8, old: u64, size: u64, align: u64): *mut u8 {
return this._blocks.regrow(addr, old, size, align, this._size);
}
#! Frees every block the arena handed out, keeping its chunks to hand out again.
#! @param this The arena to reset.
pub def arena::reset(&mut this): void {
this._blocks.restart();
}
#! Where the arena has handed out to, which `rewind` takes it back to.
#! @param this The arena.
#! @returns The point.
pub def arena::mark(&this): arena::point {
return arena::point { _spot = arena::spot { chunk = this._blocks.chunk, at = this._blocks.at } };
}
#! Frees every block the arena handed out after a point `mark` gave, keeping its
#! chunks to hand out again.
#! @param this The arena to rewind.
#! @param to The point, which must be one `mark` gave since the arena was last
#! reset, and not one already rewound past.
pub def arena::rewind(&mut this, to: arena::point): void {
this._blocks.back_to(to._spot);
}
# The bytes of a chunk before its memory, which keeps the memory aligned as the
# heap aligns blocks.
def arena::header(): u64 {
return align(size_of::<arena::chunk>(), max_align);
}
# The first byte of a chunk's memory.
def arena::data_of(chunk: *mut arena::chunk): *mut u8 {
return (chunk as *mut u8) + arena::header();
}
# Hands out the blocks of a chunk from its start.
def arena::run::enter(&mut this, chunk: *mut arena::chunk): void {
this.chunk = chunk;
this.at = arena::data_of(chunk);
this.end = this.at + (*chunk).size;
this.last = null;
}
def arena::run::take(&mut this, size: u64, alignment: u64, least: u64): *mut u8 {
var start := align(this.at as u64, alignment);
if this.chunk == null || start > this.end as u64 || size > this.end as u64 - start {
start = this.next_chunk(size, alignment, least);
}
this.at = (start + size) as *mut u8;
this.last = start as *mut u8;
return start as *mut u8;
}
# Moves on to a chunk the block fits: one after this chunk, kept from before the
# arena was reset or rewound, or a new one put after this chunk. Gives where the
# block begins in it.
def arena::run::next_chunk(&mut this, size: u64, alignment: u64, least: u64): u64 {
var after := this.chunk == null ? this.first : (*this.chunk).next;
while after != null {
val start := align(arena::data_of(after) as u64, alignment);
val end := arena::data_of(after) as u64 + (*after).size;
if start <= end && size <= end - start {
this.enter(after);
return start;
}
after = (*after).next;
}
val bytes := size + alignment > least ? size + alignment : least;
val made := raw_allocate(arena::header() + bytes) as *mut arena::chunk;
(*made).size = bytes;
(*made).owned = true;
if this.chunk == null {
(*made).next = this.first;
this.first = made;
}
else {
(*made).next = (*this.chunk).next;
(*this.chunk).next = made;
}
this.enter(made);
return align(this.at as u64, alignment);
}
# Takes back the last block handed out, where it is that. Gives whether it was.
def arena::run::give_back(&mut this, addr: *mut u8, size: u64): bool {
if addr == null || addr != this.last || addr + size != this.at {
return false;
}
this.at = addr;
this.last = null;
return true;
}
def arena::run::regrow(&mut this, addr: *mut u8, old: u64, size: u64, alignment: u64, least: u64): *mut u8 {
if addr == null {
return this.take(size, alignment, least);
}
if addr == this.last && addr + old == this.at && size <= this.end as u64 - addr as u64 {
this.at = addr + size;
return addr;
}
val made := this.take(size, alignment, least);
memcpy(made, addr, old < size ? old : size);
return made;
}
# Hands out from the first chunk again.
def arena::run::restart(&mut this): void {
if this.first == null {
return;
}
this.enter(this.first);
}
# Hands out from a spot again.
def arena::run::back_to(&mut this, to: arena::spot): void {
if to.chunk == null {
this.restart();
return;
}
this.chunk = to.chunk;
this.at = to.at;
this.end = arena::data_of(to.chunk) + (*to.chunk).size;
this.last = null;
}
# Gives back every chunk the run took, leaving it holding none.
def arena::run::free(&mut this): void {
var each := this.first;
while each != null {
val next := (*each).next;
if (*each).owned {
raw_release(each as *mut u8);
}
each = next;
}
this.first = null;
this.chunk = null;
this.at = null;
this.end = null;
this.last = null;
}
+222
View File
@@ -0,0 +1,222 @@
#! @file pool.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the `pool` allocator, which hands out blocks of one size from chunks
#! of memory it owns, and takes each back to hand out again.
module std::allocators;
#! An allocator handing out blocks of one size, carved from chunks of memory it
#! owns, and taking each back to hand out again: for values made and released
#! often, as the nodes of a list or a tree.
#!
#! A block given back goes on a list the next block is taken from, so handing one
#! out or taking one back costs a few instructions, and nothing goes back to the
#! program's heap until the pool is closed. `reset` takes back every block at
#! once, keeping the chunks to hand out again. What a block holds at first may be
#! anything.
#!
#! As an `allocator` it hands out blocks no larger and no more aligned than its
#! own, and gives `null` for any other, so a container given a pool holds one
#! element in each block it asks for, as a node does. `make` and `unmake` hand out
#! and take back values of a type.
#! @remarks A pool must outlive every block it handed out, and must not move while
#! a container refers to it.
pub struct pool : allocator, owning {
var _size: u64; #! The bytes of each block, a multiple of `_align`.
var _align: u64; #! What each block's address is a multiple of.
var _per: u64; #! How many blocks each chunk holds.
var _first: *mut pool::chunk; #! The chunks it took, the oldest first.
var _chunk: *mut pool::chunk; #! The chunk blocks are carved from, or null.
var _at: *mut u8; #! Where the next block carved begins.
var _end: *mut u8; #! Where the chunk's blocks end.
var _free: *mut u8; #! The last block given back, whose first word holds the address of the one before, or null.
var _out: u64; #! How many blocks are handed out.
}
# A chunk: this header, then its blocks.
struct pool::chunk {
var next: *mut pool::chunk; # The chunk taken after it, or null.
var size: u64; # The bytes of memory after the header.
}
# The bytes of a chunk before its blocks, which keeps them aligned as the heap
# aligns blocks.
def pool::header(): u64 {
return align(size_of::<pool::chunk>(), max_align);
}
#! Makes a pool handing out blocks of a size, aligned to a power of two, from
#! chunks of 64 KiB, or of one block where a block is larger.
#! @param size How many bytes each block holds, raised to a word, so a block
#! given back holds the address of the next.
#! @param alignment What each block's address is a multiple of, a power of two
#! no wider than `max_align`, raised to a word.
#! @returns The pool, which holds no memory yet.
pub def pool::new(size: u64, alignment: u64): pool {
val aligned := alignment < 8 ? 8 : alignment;
if aligned > max_align || (aligned & (aligned - 1)) != 0 {
fault("The alignment is not a power of two, or is wider than `max_align`.");
}
val each := align(size < 8 ? 8 : size, aligned);
val per := 65536 / each;
return pool { _size = each, _align = aligned, _per = per == 0 ? 1 : per };
}
#! Makes a pool handing out blocks for values of a type.
#! @tparam T The type.
#! @returns The pool, which holds no memory yet.
pub def pool::of<T>(): pool {
return pool::new(size_of::<T>(), align_of::<T>());
}
#! Gives back every chunk the pool took, which frees every block it handed out.
#! @param this The pool to close.
#! @remarks Values `make` put in blocks still handed out are not closed. The pool
#! is left holding nothing, so it may hand out blocks again.
pub def pool::close(&mut this): void {
var chunk := this._first;
while chunk != null {
val next := (*chunk).next;
raw_release(chunk as *mut u8);
chunk = next;
}
this._first = null;
this._chunk = null;
this._at = null;
this._end = null;
this._free = null;
this._out = 0;
}
#! The bytes each block holds.
#! @param this The pool.
#! @returns The bytes.
pub def pool::block_size(&this): u64 {
return this._size;
}
#! How many blocks are handed out and not yet given back.
#! @param this The pool.
#! @returns How many.
pub def pool::count(&this): u64 {
return this._out;
}
#! Hands out a block: the last given back, or one carved from a chunk, taking
#! another chunk from the program's heap where every one is carved.
#! @param this The pool to acquire from.
#! @param size The number of bytes the block holds, no more than the pool's.
#! @param align What the address of its first byte is a multiple of, no wider
#! than the pool's.
#! @returns The block, which may hold anything at first, or `null` where it is
#! larger or more aligned than the pool's.
pub def pool::acquire(&mut this, size: u64, align: u64): *mut u8 {
if size > this._size || align > this._align {
return null;
}
this._out++;
if this._free != null {
val made := this._free;
this._free = (made as *mut *mut u8)[0];
return made;
}
if this._at == this._end {
this.next_chunk();
}
val made := this._at;
this._at = this._at + this._size;
return made;
}
# Carves the chunk after the one carved, taking a chunk from the program's heap
# where there is none after it.
def pool::next_chunk(&mut this): void {
var next := this._chunk == null ? this._first : (*this._chunk).next;
if next == null {
val bytes := this._per * this._size;
next = raw_allocate(pool::header() + bytes) as *mut pool::chunk;
(*next).next = null;
(*next).size = bytes;
# Only the last chunk has none after it, and only a pool with none has none
# carved.
if this._chunk == null {
this._first = next;
} else {
(*this._chunk).next = next;
}
}
this._chunk = next;
this._at = next as *mut u8 + pool::header();
this._end = this._at + (*next).size;
}
#! Takes back a block, which the next block handed out is.
#! @param this The pool the block came from.
#! @param addr The block, or `null`, which takes back nothing.
#! @param size The number of bytes it was acquired with.
pub def pool::dispose(&mut this, addr: *mut u8, size: u64): void {
return if addr == null;
(addr as *mut *mut u8)[0] = this._free;
this._free = addr;
this._out--;
}
#! Hands out a block of another size holding what a block it handed out held,
#! which is the block itself, as every block holds the pool's size.
#! @param this The pool the block came from.
#! @param addr The block to resize, or `null` to acquire one.
#! @param old The number of bytes it was acquired with.
#! @param size The number of bytes the new block holds.
#! @param align What the address of its first byte is a multiple of.
#! @returns The block, or `null` where the size or alignment is larger than the
#! pool's, leaving the block as it was.
pub def pool::resize(&mut this, addr: *mut u8, old: u64, size: u64, align: u64): *mut u8 {
if size > this._size || align > this._align {
return null;
}
return addr == null ? this.acquire(size, align) : addr;
}
#! Takes back every block the pool handed out, keeping its chunks to hand out
#! again.
#! @param this The pool to reset.
#! @remarks Values `make` put in blocks still handed out are not closed.
pub def pool::reset(&mut this): void {
this._chunk = null;
this._at = null;
this._end = null;
this._free = null;
this._out = 0;
}
#! Moves a value into a block the pool hands out.
#! @tparam T The value's type, no larger and no more aligned than the pool's
#! blocks.
#! @param this The pool.
#! @param value The value, which the block then holds.
#! @returns The value's address, until `unmake` takes it back.
pub def pool::make<T>(&mut this, value: T): *mut T {
val at := this.acquire(size_of::<T>(), align_of::<T>()) as *mut T;
if at == null {
fault("The value is larger, or more aligned, than the pool's blocks.");
}
if const T is closeable {
memset(at as *mut u8, 0, size_of::<T>());
}
at[0] = move(&mut value);
return at;
}
#! Closes a value `make` put in a block, and takes the block back.
#! @tparam T The value's type.
#! @param this The pool the value came from.
#! @param at The value's address, or `null`, which takes back nothing.
pub def pool::unmake<T>(&mut this, at: *mut T): void {
return if at == null;
close(through(at));
this.dispose(at as *mut u8, size_of::<T>());
}
+70
View File
@@ -0,0 +1,70 @@
# std::args
`std::args` reads a program's arguments into a struct, by the attributes the
program marks it with, and writes the help that says what it reads from the
same marks. A struct marked `@args::command` is read: each field marked
`@args::option` from `--name value`, `--name=value`, or its short form, and
those marked `@args::argument` from what's left. A union of commands is a
command's subcommands, each a field. `args::parse` gives what was read or why it
couldn't be, and `args::parse_or_exit` prints the help or the mistake and exits
where it is asked to.
## Using it
Require the standard library in your blossomfile, and name the module among a
target's `deps`, with the other modules of std it reads:
```yaml
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
targets:
- name: app
type: program
deps: [std.args, std.io]
```
```sakura
import std::io;
import std::args;
@args::command{ name = "greet", help = "Says hello." }
struct greeting {
@args::option{ short = 'n', value = "N", help = "How many times." }
var times: u32 = 1;
@args::option{ short = 'l', help = "Says it loudly." }
var loud: bool;
@args::argument{ value = "NAME", help = "Who to greet." }
var names: vector<strview>;
}
def main(args: span<strview>): void {
val asked := args::parse_or_exit::<greeting>(args);
for &name in asked.names {
for _ in 0..asked.times {
io::println(asked.loud ? $"HELLO, {name}!" : $"Hello, {name}.");
}
}
}
```
## What it reads
The marks are `args::command`, `args::option`, `args::argument`, `args::group`, and
`args::choice`, written with `args::`, as above, or without it, as below, where the file
imports `std::args`.
- **Options** are read by their long names, `--times 2` or `--times=2`, which are their fields' with each `_` written `-`, and by short names, `-n 2` or `-n2`. A `bool` is a switch, and switches are written together, as `-ln2`. A value may begin with `-`, and `--` ends the options, as a lone `-` is positional.
- **Values**: integers within their range, reals, `strview`, `string`, `path`, an enum by the names of its members marked `@choice`, and a program's own type implementing `args::value`. `maybe` may be left out, and a `vector` takes each one written. `count = true` counts how often an integer's option is written, as `-vvv`, and any other option keeps the last one written.
- **Positional arguments** go to the `@argument` fields in turn: a plain one takes one, a `maybe` one where one is left over, a `vector` what is left over, and the one marked `rest = true` what follows `--`.
- **Subcommands**: a union marked `@command`, whose fields are marked `@command`, is either what `parse` is given or a struct's last argument. Its word picks the field, whose own struct reads the arguments after it.
- **Groups**: options several commands share are written once, in a struct marked `@group`. A field of that type, also marked `@group`, reads them as if the command declared them in its place, and the help text shows them there. A group may hold groups, but no positional arguments.
- **Help and mistakes**: `-h`, `--help`, and, where a command gives a `version`, `--version` print the help text or the version and exit with 0, and a mistake in the arguments prints why and exits with 2. `args::parse` gives each as an `args::error` instead, and `args::help::<T>(args)` and `args::usage::<T>(args)` give the text of the subcommand the arguments reach. A mistake in the marks, as two options of one name, stops the program the first time it runs.
## Testing
From the standard library's root, `blossom test --only std.args` runs them, or:
```sh
sakurac run --lib std=. tests/main.sakura tests/args/*.sakura
```
+228
View File
@@ -0,0 +1,228 @@
#! @file args.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what reading a program's arguments knows apart from the walk: the
#! attributes a program marks the struct it reads them into with, the traits of
#! the types read, the errors, and `args::parse` with the functions around it.
#! The help text is written from the same marks, so it says what is read.
import std::io;
import system;
module std::args;
#! Marks a struct or union `args::parse` reads, and each field of a union of
#! subcommands, which is a subcommand of the field's name.
#!
#! The marks are also what lets `std::args` see a type private to the program,
#! since reflection gives a module what carries an attribute it declares. So a
#! command is marked, and each field read, even where it is `pub`.
@core::usage{ on = target::structs | target::unions | target::fields }
pub struct command : attribute {
pub val name: strview = ""; #! Its word, or the program's name in the help text, in place of the declaration's.
pub val help: strview = ""; #! What it does, in a sentence or two.
pub val version: strview = ""; #! What `--version` prints, where it is not empty.
}
#! Marks a field read from an option: `--name value` or `--name=value`, and,
#! where it has a short name, `-n value` or `-nvalue`.
@core::usage{ on = target::fields }
pub struct option : attribute {
pub val name: strview = ""; #! Its long name, without `--`, in place of the field's, whose `_` are written `-`.
pub val short: u8 = 0; #! Its short name, a letter or digit, or 0 for none.
pub val value: strview = ""; #! What the help text calls its value, as `DIR`, in place of its name in capitals.
pub val help: strview = ""; #! What it does.
pub val required: bool = false; #! Whether leaving it out is an error.
pub val count: bool = false; #! Whether an integer counts how often it is written, as `-vvv`.
}
#! Marks a field read from the positional arguments, which go to such fields in
#! the order they are declared. The last may be a union marked `@command`,
#! whose subcommand the next positional argument names.
@core::usage{ on = target::fields }
pub struct argument : attribute {
pub val value: strview = ""; #! What the help text calls it, as `FILE`, in place of its name in capitals.
pub val help: strview = ""; #! What it is.
pub val rest: bool = false; #! Whether it takes only what follows `--`.
}
#! Marks a struct of options several commands share, and each field of such a
#! struct that a command reads, whose options are read, and shown in the help
#! text, as if the command declared them in place of the field. A group holds
#! options, and groups of them, but no positional arguments.
@core::usage{ on = target::structs | target::fields }
pub struct group : attribute {}
#! Marks an enum member read by its name, which is the member's, whose `_` are
#! written `-`, or the `name` given. Members left unmarked are not read.
@core::usage{ on = target::members }
pub struct choice : attribute {
pub val name: strview = ""; #! The word for it, in place of the member's.
pub val help: strview = ""; #! What it means.
}
#! A type an option or an argument is read as, from the text written.
#!
#! std's numbers, `strview`, `string`, `path`, and `maybe` of any of them
#! implement it, and a program's own type may, by declaring it, as
#! `struct celsius : args::value`. An enum whose members are marked `@choice`
#! is read by their names without it.
pub trait value {
#! Reads a value from an argument.
#! @param text The argument, as written.
#! @returns The value, or why the text is not one, as `is not a whole number`.
def from_argument(text: strview): result<self, strview>;
}
#! A type an option is a switch of: on where the option is written, which
#! takes no value. Only `bool` is one.
pub trait switch {
#! The value a switch has where it is written.
#! @returns The value.
def switched_on(): self;
}
#! Why the arguments could not be read.
pub enum error_kind: u8 {
unknown_option, #! An option no field takes, as `--colour`.
missing_value, #! An option taking a value ends the arguments.
invalid_value, #! A value its type refuses, as `300` for a `u8`.
switch_given_value, #! A switch written with a value, as `--verbose=yes`.
missing_option, #! A `required` option is left out.
missing_argument, #! A positional argument that is not a `maybe` or `vector` is left out.
unexpected_argument, #! A positional argument no field takes.
unknown_command, #! A word that names no subcommand.
missing_command, #! The arguments end where a subcommand is needed.
help_asked, #! `-h` or `--help` was written.
version_asked, #! `--version` was written.
}
#! Why the arguments could not be read, and where.
#!
#! An error is plain data, viewing the arguments and the marks, so `else (e)`
#! names it, and it lasts as long as the arguments do.
pub struct error {
pub var kind: error_kind; #! What went wrong.
pub var at: u64; #! The argument's index, or how many there are, at their end.
pub var text: strview; #! That argument, as written, or the value alone where one is wrong, as `300` of `-O300`.
pub var name: strview; #! The option, as written, or the argument, as the help text names it.
pub var reason: strview; #! Why the value was refused, from `value`, or empty.
}
#! Says what went wrong, in a sentence.
#! @param this The error to describe.
#! @returns The sentence, as "`-O 300`: 300 is not between 0 and 255."
pub def error::describe(&this): string {
return match this.kind {
unknown_option => $"`{this.name}` is not an option.",
missing_value => $"`{this.name}` needs a value.",
invalid_value => this.name.length != 0 && this.name[0] == '-'
? $"`{this.name} {this.text}`: {this.text} {this.reason}."
: $"{this.name} `{this.text}` {this.reason}.",
switch_given_value => $"`{this.name}` takes no value, but is given `{this.text}`.",
missing_option => $"`{this.name}` is required.",
missing_argument => $"{this.name} is missing.",
unexpected_argument => $"`{this.text}` is more than the arguments taken.",
unknown_command => $"`{this.text}` is not a command.",
missing_command => string::from("A command is needed.", nothing {}),
help_asked => string::from("The help text is asked for.", nothing {}),
version_asked => string::from("The version is asked for.", nothing {}),
};
}
#! Reads the arguments into a `T`, a struct or union marked `@command`.
#!
#! Each field marked `@option` is read from the option of its name, each marked
#! `@argument` from the positional arguments, in turn, and each marked `@group`
#! from the options of its struct, as the README's "Command-line arguments"
#! says. A field left unmarked, or left out of the arguments, keeps its default,
#! or else its zero value. Before the arguments are read, the marks of `T` and of
#! every subcommand and group within it are checked, and a mistake in them, as
#! two options of one name, stops the program, so it is found the first time the
#! program runs, whatever it is given.
#! @tparam T The command, which is `zeroable`, so a field left unread has a
#! value.
#! @param args The arguments, as `main` is given them.
#! @returns The command read, or why the arguments are not one of it, which is
#! `help_asked` or `version_asked` where they ask for those.
pub def parse<T>(args: span<strview>): result<T, error> where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
return read_command::<T>(args, &mut reached);
}
#! Reads the arguments into a `T`, as `parse` does, or else writes why not and
#! stops the program: the help text to the standard output, or the version,
#! with status 0, or the error to the standard error, with a line saying where
#! the help text is, with status 2.
#! @tparam T The command, which is `zeroable`.
#! @param args The arguments, as `main` is given them.
#! @returns The command read.
pub def parse_or_exit<T>(args: span<strview>): T where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
var made := read_command::<T>(args, &mut reached) else (wrong) {
stop::<T>(&wrong, &reached);
var none: T;
return move(none);
};
return move(made);
}
#! The help text of the command the arguments reach, so `tool build --help`
#! gives `build`'s: its usage, what it does, its arguments, its subcommands,
#! and its options, each with what it does.
#! @tparam T The command, which is `zeroable`, so the defaults of its
#! options are shown.
#! @param args The arguments, of which only the subcommands are followed.
#! @returns The text, ending in a line break.
pub def help<T>(args: span<strview> = span::<strview>::empty()): string where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
_ = read_command::<T>(args, &mut reached);
val program := program_name::<T>();
return help_at::<T>(reached.words.view(), 0, program, "", true);
}
#! The usage of the command the arguments reach, in one line.
#! @tparam T The command, which is `zeroable`.
#! @param args The arguments, of which only the subcommands are followed.
#! @returns The line, as "usage: sakura build [options] FILE...", without a
#! line break.
pub def usage<T>(args: span<strview> = span::<strview>::empty()): string where T: zeroable {
var reached := reach { words = vector::<strview>::new() };
_ = read_command::<T>(args, &mut reached);
val program := program_name::<T>();
return help_at::<T>(reached.words.view(), 0, program, "", false);
}
# What reading the arguments reached, which the help text and the report of an
# error follow: the word of each subcommand the arguments named, in turn, and
# the version of the command `--version` was written to.
struct reach {
var words: vector<strview>;
var version: strview;
}
# Writes why the arguments could not be read, or the help text or version they
# ask for, and stops the program.
def stop<T>(wrong: &error, reached: &reach): void where T: zeroable {
if wrong.kind == error_kind::help_asked {
val text := help_at::<T>(reached.words.view(), 0, program_name::<T>(), "", true);
print(text.view());
system::exit(0);
}
if wrong.kind == error_kind::version_asked {
print($"{reached.version}\n");
system::exit(0);
}
var named := string::from(program_name::<T>(), nothing {});
for &each in reached.words {
named.append(" ");
named.append(each);
}
val described := wrong.describe();
val said := $"{program_name::<T>()}: {described}\nTry `{named} --help`.\n";
_ = io::error_output().write(said.view());
system::exit(2);
}
+403
View File
@@ -0,0 +1,403 @@
#! @file help.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the help text `args::help` and `args::usage` write from the marks of
#! a command: its usage, what it does, its arguments, its subcommands, and its
#! options, each with what it does, its default, and the choices it takes, in
#! columns.
import std::semver;
import std::io;
module std::args;
# A type whose default an option's help text shows, as std's numbers and text
# are.
trait shown {
def shown_argument(&this): string;
}
# A type holding values of another, whose choices an option's help text lists,
# as a `maybe` or a vector of an enum does.
trait listed {
def list_choices(into: &mut page): void;
}
# Where a row of the help text goes: under the arguments, the subcommands, or
# the options, or under the option before it, as one of its choices.
enum row_place: u8 { arguments, commands, options, choices }
# The rows of a help text, each a name and what it is, in turn.
struct page {
var places: vector<row_place>;
var lefts: vector<string>;
var rights: vector<string>;
}
# Makes a help text with no rows.
def page::new(): page {
return page {
places = vector::<row_place>::new(),
lefts = vector::<string>::new(),
rights = vector::<string>::new()
};
}
# Adds a row to a help text.
def page::add(&mut this, place: row_place, left: string, right: string): void {
this.places.append(place);
this.lefts.append(move(left));
this.rights.append(move(right));
}
# Writes the sections of a help text, each a heading and its rows, whose names
# are padded so what each is begins in one column, with an option's choices in
# a column of their own under it.
def page::write(&this, into: &mut string): void {
var width := 0u;
for i in 0..this.places.length {
if this.places[i] != row_place::choices && this.lefts[i].length > width {
width = this.lefts[i].length;
}
}
width += 3;
val sections: row_place[3] = [row_place::arguments, row_place::commands, row_place::options];
val headings: strview[3] = ["arguments", "commands", "options"];
for s in 0u..3u {
var any := false;
for &each in this.places {
any = any || each == sections[s];
}
continue if !any;
into.append($"\n{headings[s]}:\n");
for i in 0..this.places.length {
continue if this.places[i] != sections[s];
line(into, this.lefts[i].view(), width, this.rights[i].view());
# The choices after an option are padded to the widest of them.
var end := i + 1;
var widest := 0u;
while end < this.places.length && this.places[end] == row_place::choices {
widest = this.lefts[end].length > widest ? this.lefts[end].length : widest;
end++;
}
for j in i + 1..end {
var left := spaces(width + 2);
left.append(this.lefts[j].view());
line(into, left.view(), width + 4 + widest, this.rights[j].view());
}
}
}
}
# Writes a row: its name, padded to a width where something follows it, and
# what follows.
def line(into: &mut string, left: strview, width: u64, right: strview): void {
into.append(left);
if right.length != 0 {
for _ in left.length..width {
into.push(' ');
}
into.append(right);
}
into.append("\n");
}
# Text of a number of spaces.
def spaces(count: u64): string {
var made := string::new(nothing {});
for _ in 0..count {
made.push(' ');
}
return made;
}
# The name of the program, as the help text and errors call it: the command's
# `name`, or else its declaration's.
def program_name<T>(): strview {
if const T is switch || T is value || T is repeated {
return "";
} else {
val given := attached::<command>(decl_of::<T>())[0].name;
return given.length != 0 ? given : decl_of::<T>().name;
}
}
# The help text, or only its usage, of the command the words reach within a
# command, through each subcommand they name in turn.
def help_at<T>(words: span<strview>, depth: u64, path: strview, about: strview, whole: bool): string where T: zeroable {
if const T is switch || T is value || T is repeated {
return string::new(nothing {});
} else if const decl_of::<T>().kind == target::unions {
if depth < words.length {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
if named_as(words[depth], field.name, attached::<command>(field)[0].name) {
val deeper := $"{path} {words[depth]}";
return help_at::<type_of(field)>(words, depth + 1, deeper.view(), attached::<command>(field)[0].help, whole);
}
}
}
}
return union_help::<T>(path, about, whole);
} else {
if depth < words.length {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
return help_within::<type_of(field)>(words, depth, path, about, whole);
}
}
}
}
return struct_help::<T>(path, about, whole);
}
}
# The help text the words reach within a field's union of subcommands, or
# nothing for any other field.
def help_within<V>(words: span<strview>, depth: u64, path: strview, about: strview, whole: bool): string {
if const V is switch || V is value || V is repeated {
return string::new(nothing {});
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
if const V is zeroable {
return help_at::<V>(words, depth, path, about, whole);
} else {
return string::new(nothing {});
}
} else {
return string::new(nothing {});
}
}
# The help text, or only its usage, of a union of subcommands.
def union_help<U>(path: strview, about: strview, whole: bool): string {
var made := $"usage: {path} [options] COMMAND ...";
return made if !whole;
made.append("\n");
val own := attached::<command>(decl_of::<U>())[0].help;
val said := own.length != 0 ? own : about;
if said.length != 0 {
made.append($"\n{said}\n");
}
var rows := page::new();
commands_of::<U>(&mut rows);
helped(&mut rows, true, true, attached::<command>(decl_of::<U>())[0].version.length != 0);
rows.write(&mut made);
return made;
}
# The help text, or only its usage, of a struct of options and arguments.
def struct_help<T>(path: strview, about: strview, whole: bool): string where T: zeroable {
var made := $"usage: {path} [options]";
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
made.append(" COMMAND ...");
} else {
val marked := attached::<argument>(field)[0];
val name := value_name(field.name, marked.value);
made.append(" ");
made.append(argument_shown(name.view(), shape_of::<type_of(field)>(), marked.rest).view());
}
}
}
return made if !whole;
made.append("\n");
val own := attached::<command>(decl_of::<T>())[0].help;
val said := own.length != 0 ? own : about;
if said.length != 0 {
made.append($"\n{said}\n");
}
var rows := page::new();
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
commands_within::<type_of(field)>(&mut rows);
} else {
val marked := attached::<argument>(field)[0];
val name := value_name(field.name, marked.value);
var left := string::from(" ", nothing {});
var shown := argument_shown(name.view(), shape_of::<type_of(field)>(), marked.rest);
if marked.rest {
shown = $"-- {name}...";
}
left.append(shown.view());
rows.add(row_place::arguments, move(left), string::from(marked.help, nothing {}));
}
}
}
var defaults: T;
option_rows::<T>(&mut rows, &defaults);
helped(&mut rows, helps::<T>(true), helps::<T>(false), attached::<command>(decl_of::<T>())[0].version.length != 0);
rows.write(&mut made);
return made;
}
# Adds a row for each option of a command, or of a group within it, in the
# order they are declared, those of a group where its field is: its names, and
# what it does, with its default, read from what holds the defaults, or that it
# is required, and its choices under it.
def option_rows<T>(rows: &mut page, defaults: &T): void {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
val marked := attached::<option>(field)[0];
var left := string::from(marked.short != 0 ? $" {short_written(marked.short)}, --" : " --", nothing {});
left.append(long_name(field.name, marked.name).view());
var switched := marked.count;
if const type_of(field) is switch {
switched = true;
}
if !switched {
left.append(" ");
left.append(value_name(marked.name.length != 0 ? marked.name : field.name, marked.value).view());
}
var right := string::from(marked.help, nothing {});
if marked.required {
right.append(right.length != 0 ? " Required." : "Required.");
} else if !marked.count {
val shown := default_of::<type_of(field)>(&defaults.(field));
if shown.length != 0 {
right.append(right.length != 0 ? " Default: " : "Default: ");
right.append(shown.view());
right.append(".");
}
}
rows.add(row_place::options, move(left), move(right));
choices_of::<type_of(field)>(rows);
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
option_rows::<type_of(field)>(rows, &defaults.(field));
}
}
}
# How a positional argument is shown: as its name, in brackets where it may be
# left out, and followed by `...` where it takes as many as are left over.
def argument_shown(name: strview, taken: shape, rest: bool): string {
if rest {
return $"[-- {name}...]";
}
return match taken {
shape::one => string::from(name, nothing {}),
shape::optional => $"[{name}]",
shape::many => $"{name}...",
};
}
# Adds the rows of the options every command has: `-h` and `--help`, where no
# option of its own takes their names, and `--version`, where it gives one.
def helped(rows: &mut page, short: bool, long: bool, version: bool): void {
if short || long {
val left: strview = short && long ? " -h, --help" : short ? " -h" : " --help";
rows.add(row_place::options, string::from(left, nothing {}), string::from("Shows this help.", nothing {}));
}
if version {
rows.add(row_place::options, string::from(" --version", nothing {}), string::from("Shows the version.", nothing {}));
}
}
# Adds a row for each subcommand of a field's union of them, or none for any
# other field.
def commands_within<V>(rows: &mut page): void {
if const V is switch || V is value || V is repeated {
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
commands_of::<V>(rows);
}
}
# Adds a row for each subcommand of a union of them: its word, and what it does,
# as its mark in the union says, or else the mark of its own type.
def commands_of<U>(rows: &mut page): void {
for const field in members_of(decl_of::<U>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
val given := attached::<command>(field)[0].help;
val said := given.length != 0 ? given : command_help::<type_of(field)>();
var left := string::from(" ", nothing {});
left.append(long_name(field.name, attached::<command>(field)[0].name).view());
rows.add(row_place::commands, move(left), string::from(said, nothing {}));
}
}
}
# What a command says it does, in its own mark.
def command_help<V>(): strview {
if const V is switch || V is value || V is repeated {
return "";
} else if const attached::<command>(decl_of::<V>()).length > 0 {
return attached::<command>(decl_of::<V>())[0].help;
} else {
return "";
}
}
# Adds a row for each choice an option of a type takes, under it: those of an
# enum, or of the enum a `maybe` or a vector holds.
def choices_of<V>(rows: &mut page): void {
if const V is listed {
V::list_choices(rows);
} else if const V is switch || V is value {
} else if const decl_of::<V>().kind == target::enums {
for const member in members_of(decl_of::<V>()) {
if const member.kind == target::members && attached::<choice>(member).length > 0 {
rows.add(
row_place::choices,
long_name(member.name, attached::<choice>(member)[0].name),
string::from(attached::<choice>(member)[0].help, nothing {})
);
}
}
}
}
# The default an option's help text shows, or nothing for a switch, a `maybe`,
# a vector, empty text, and a program's own type.
def default_of<V>(value: &V): string {
if const V is switch || V is vacant || V is repeated {
return string::new(nothing {});
} else if const V is shown {
return value.shown_argument();
} else if const V is value {
return string::new(nothing {});
} else if const decl_of::<V>().kind == target::enums {
for const member in members_of(decl_of::<V>()) {
if const member.kind == target::members && attached::<choice>(member).length > 0 {
if value == value_of(member) {
return long_name(member.name, attached::<choice>(member)[0].name);
}
}
}
return string::new(nothing {});
} else {
return string::new(nothing {});
}
}
def i8::shown_argument(&this): string { return $"{this}"; }
def i16::shown_argument(&this): string { return $"{this}"; }
def i32::shown_argument(&this): string { return $"{this}"; }
def i64::shown_argument(&this): string { return $"{this}"; }
def u8::shown_argument(&this): string { return $"{this}"; }
def u16::shown_argument(&this): string { return $"{this}"; }
def u32::shown_argument(&this): string { return $"{this}"; }
def u64::shown_argument(&this): string { return $"{this}"; }
def f32::shown_argument(&this): string { return $"{this}"; }
def f64::shown_argument(&this): string { return $"{this}"; }
def strview::shown_argument(&this): string { return string::from(this, nothing {}); }
def string::shown_argument(&this): string { return string::copy_of(this); }
def path::shown_argument(&this): string { return string::from(this.view(), nothing {}); }
def maybe<T>::list_choices(into: &mut page): void {
choices_of::<T>(into);
}
def vector<T>::list_choices(into: &mut page): void {
choices_of::<T>(into);
}
+996
View File
@@ -0,0 +1,996 @@
#! @file walk.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the walk `args::parse` reads the arguments by, through what the
#! program marks of the command it is given, the checks of those marks, and the
#! forms of the types std gives: numbers, text, paths, `maybe`, and vectors.
#!
#! A field's type decides how it is read, which `if const` tells by the traits
#! the type implements, and by the kind of its declaration, which only a type
#! the program or std declares has: a switch, a `value`, a vector, an enum of
#! choices, or a union of subcommands. Each step on a field is a function
#! deciding so itself, since `if const` decides by types and kinds alone, not by
#! what a function gives.
#!
#! The options of a command are counted in the order they are declared, those
#! of a group where the group's field is, so each step on an option given by its
#! index goes into the group holding it with the index within the group.
import std::semver;
import std::io;
module std::args;
# A type each argument for it is added to, as a vector is, rather than the last
# being kept.
trait repeated {
def add_argument(&mut this, text: strview): result<void, strview>;
}
# A type that may be left out, as `maybe` is, so a positional argument of it
# takes one only where one is left over.
trait vacant {
def vacant_argument(): self;
}
# How many positional arguments a field takes: one, one where one is left over,
# or as many as are left over.
enum shape: u8 { one, optional, many }
# The index of no option.
const no_option: u64 = 0xFFFFFFFFFFFFFFFF;
# Reads the arguments into a command, after checking its marks.
def read_command<T>(args: span<strview>, reached: &mut reach): result<T, error> where T: zeroable {
check_command::<T>();
return read_part::<T>(args, 0, reached);
}
# Reads the arguments from an index into a command: a struct of options and
# arguments, or a union of subcommands.
def read_part<T>(args: span<strview>, from: u64, reached: &mut reach): result<T, error> where T: zeroable {
if const T is switch || T is value || T is repeated {
compile_error("The type is not `@command`, so its arguments are not read. Mark a struct or union `@command`, and each field to read `@option` or `@argument`.");
return error { kind = error_kind::missing_command, at = from };
} else if const attached::<command>(decl_of::<T>()).length == 0 {
compile_error("The type is not `@command`, so its arguments are not read. Mark it `@command`, and each field to read `@option` or `@argument`.");
return error { kind = error_kind::missing_command, at = from };
} else if const decl_of::<T>().kind == target::unions {
return read_union::<T>(args, from, reached);
} else {
return read_struct::<T>(args, from, reached);
}
}
# Reads a union of subcommands: the options it has, which are only those asking
# for the help text and the version, then the word naming the subcommand, then
# the subcommand's own arguments.
def read_union<U>(args: span<strview>, from: u64, reached: &mut reach): result<U, error> where U: zeroable {
var at := from;
while at < args.length {
val arg := args[at];
if arg == "--" {
at++;
break;
}
break if arg.length < 2 || arg[0] != '-';
if arg == "-h" || arg == "--help" {
return asked(error_kind::help_asked, at, arg);
}
val version := attached::<command>(decl_of::<U>())[0].version;
if arg == "--version" && version.length != 0 {
reached.version = version;
return asked(error_kind::version_asked, at, arg);
}
return error { kind = error_kind::unknown_option, at = at, text = arg, name = arg };
}
if at >= args.length {
return error { kind = error_kind::missing_command, at = args.length };
}
val word := args[at];
for const field in members_of(decl_of::<U>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
if named_as(word, field.name, attached::<command>(field)[0].name) {
reached.words.append(word);
var sub := read_part::<type_of(field)>(args, at + 1, reached) else (wrong) { return wrong; };
var made: U;
made.(field) = move(sub);
return move(made);
}
}
}
return error { kind = error_kind::unknown_command, at = at, text = word, name = word };
}
# Reads a struct of options and positional arguments, the last of which may be
# a union of subcommands, which every argument after its word belongs to.
def read_struct<T>(args: span<strview>, from: u64, reached: &mut reach): result<T, error> where T: zeroable {
var made: T;
var seen := vector::<u64>::new();
var positional := vector::<u64>::new();
var after := vector::<u64>::new();
val before := arguments_before_command::<T>();
val commanded := before != no_option;
var named := false;
var ended := false;
var at := from;
while at < args.length {
val arg := args[at];
var plain := ended;
if !ended {
if arg == "--" {
ended = true;
} else if arg.length > 2 && arg[0] == '-' && arg[1] == '-' {
_ = read_long::<T>(&mut made, args, &mut at, &mut seen, reached) else (wrong) { return wrong; };
} else if arg.length > 1 && arg[0] == '-' && !(arg[1].is_digit && !digit_named::<T>()) {
_ = read_short::<T>(&mut made, args, &mut at, &mut seen, reached) else (wrong) { return wrong; };
} else {
plain = true;
}
}
if plain {
# The positional argument after those the fields before it take names a
# subcommand, which reads the rest.
if commanded && positional.length + after.length == before {
_ = read_subcommand::<T>(&mut made, args, at, reached) else (wrong) { return wrong; };
named = true;
break;
}
if ended {
after.append(at);
} else {
positional.append(at);
}
}
at++;
}
if commanded && !named {
return error { kind = error_kind::missing_command, at = args.length };
}
val left := required_left::<T>(&seen, 0);
if left.length != 0 {
return error { kind = error_kind::missing_option, at = args.length, name = keep($"--{left}") };
}
_ = read_positional::<T>(&mut made, args, &mut positional, &after) else (wrong) { return wrong; };
return move(made);
}
# Reads an option written by its long name, as `--name value` or `--name=value`,
# taking its value from the next argument where none is attached, or the help
# text or the version where it asks for them.
def read_long<T>(made: &mut T, args: span<strview>, at: &mut u64, seen: &mut vector<u64>, reached: &mut reach): result<void, error> where T: zeroable {
val arg := args[at];
var name := arg.substr(2, arg.length - 2);
var value: strview = "";
var joined := false;
for i in 0..name.length {
if name[i] == '=' {
value = name.substr(i + 1, name.length - i - 1);
name = name.substr(0, i);
joined = true;
break;
}
}
val written := arg.substr(0, name.length + 2);
val which := option_named::<T>(name);
if which == no_option {
if name == "help" && !joined && helps::<T>(false) {
return asked(error_kind::help_asked, at, arg);
}
val version := attached::<command>(decl_of::<T>())[0].version;
if name == "version" && !joined && version.length != 0 {
reached.version = version;
return asked(error_kind::version_asked, at, arg);
}
return error { kind = error_kind::unknown_option, at = at, text = arg, name = written };
}
seen.append(which);
if !takes_value::<T>(which) {
if joined {
return error { kind = error_kind::switch_given_value, at = at, text = value, name = written };
}
return take_option::<T>(made, which, "", at, written);
}
if !joined {
if at + 1 >= args.length {
return error { kind = error_kind::missing_value, at = args.length, text = arg, name = written };
}
at++;
value = args[at];
}
return take_option::<T>(made, which, value, at, written);
}
# Reads options written by their short names, as `-v`, `-vq`, `-O 2`, or `-vO2`:
# switches may be written together, and the last written together may take a
# value, which is what follows it, or the next argument.
def read_short<T>(made: &mut T, args: span<strview>, at: &mut u64, seen: &mut vector<u64>, reached: &mut reach): result<void, error> where T: zeroable {
val arg := args[at];
var i := 1u;
while i < arg.length {
val letter := arg[i];
val written := short_written(letter);
val which := option_lettered::<T>(letter);
if which == no_option {
if letter == 'h' && helps::<T>(true) {
return asked(error_kind::help_asked, at, arg);
}
return error { kind = error_kind::unknown_option, at = at, text = arg, name = written.length == 2 ? written : arg };
}
seen.append(which);
if !takes_value::<T>(which) {
_ = take_option::<T>(made, which, "", at, written) else (wrong) { return wrong; };
i++;
continue;
}
if i + 1 < arg.length {
return take_option::<T>(made, which, arg.substr(i + 1, arg.length - i - 1), at, written);
}
if at + 1 >= args.length {
return error { kind = error_kind::missing_value, at = args.length, text = arg, name = written };
}
at++;
return take_option::<T>(made, which, args[at], at, written);
}
return;
}
# Reads the subcommand whose word is at an index into the field holding the
# union of them.
def read_subcommand<T>(made: &mut T, args: span<strview>, at: u64, reached: &mut reach): result<void, error> where T: zeroable {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
_ = read_into::<type_of(field)>(&mut made.(field), args, at, reached) else (wrong) { return wrong; };
}
}
return;
}
# Reads a subcommand into a field, where the field holds a union of them, and
# does nothing to any other.
def read_into<V>(place: &mut V, args: span<strview>, at: u64, reached: &mut reach): result<void, error> {
if const V is switch || V is value || V is repeated {
return;
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
if const V is zeroable {
var sub := read_part::<V>(args, at, reached) else (wrong) { return wrong; };
place = move(sub);
}
return;
} else {
return;
}
}
# Reads the positional arguments into the fields marked `@argument`, in the
# order they are declared: one takes one, a `maybe` one where one is left over
# for those after it, and a vector as many as are left over. The arguments after
# `--` go to the one taking the rest, where there is one, and are otherwise read
# as the others are.
def read_positional<T>(made: &mut T, args: span<strview>, positional: &mut vector<u64>, after: &vector<u64>): result<void, error> where T: zeroable {
var shapes := vector::<shape>::new();
var rests := vector::<bool>::new();
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if !is_command::<type_of(field)>() {
shapes.append(shape_of::<type_of(field)>());
rests.append(attached::<argument>(field)[0].rest);
}
}
}
var resting := false;
for &each in rests {
resting = resting || each;
}
if !resting {
for &each in after {
positional.append(each);
}
}
# How many each takes, leaving those after it the one each needs.
var counts := vector::<u64>::new();
var left := positional.length;
for k in 0..shapes.length {
var needed := 0u;
for j in k + 1..shapes.length {
if !rests[j] && shapes[j] == shape::one {
needed++;
}
}
var taken := 0u;
if !rests[k] {
if shapes[k] == shape::one {
taken = left > 0 ? 1 : 0;
} else if shapes[k] == shape::optional {
taken = left > needed ? 1 : 0;
} else {
taken = left > needed ? left - needed : 0;
}
}
counts.append(taken);
left -= taken;
}
if left > 0 {
val extra := positional[positional.length - left];
return error { kind = error_kind::unexpected_argument, at = extra, text = args[extra] };
}
var k := 0u;
var next := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if !is_command::<type_of(field)>() {
val name := attached::<argument>(field)[0].value;
if rests[k] {
for &each in after {
_ = store::<type_of(field)>(&mut made.(field), args[each]) else (why) {
return refused(each, args[each], argument_name(field.name, name), why);
};
}
} else {
if shapes[k] == shape::one && counts[k] == 0 {
return error { kind = error_kind::missing_argument, at = args.length, name = argument_name(field.name, name) };
}
for _ in 0..counts[k] {
val each := positional[next];
next++;
_ = store::<type_of(field)>(&mut made.(field), args[each]) else (why) {
return refused(each, args[each], argument_name(field.name, name), why);
};
}
}
k++;
}
}
}
return;
}
# Reads an option into its field, by its index among the options: a count adds
# one, a switch is turned on, and anything else reads the value written.
def take_option<T>(made: &mut T, which: u64, value: strview, at: u64, written: strview): result<void, error> where T: zeroable {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if index == which {
if attached::<option>(field)[0].count {
count_one::<type_of(field)>(&mut made.(field));
return;
}
if const type_of(field) is switch {
made.(field) = switched::<type_of(field)>();
return;
} else {
_ = store::<type_of(field)>(&mut made.(field), value) else (why) {
return refused(at, value, written, why);
};
return;
}
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val held := options_in::<type_of(field)>();
if which < index + held {
return take_option::<type_of(field)>(&mut made.(field), which - index, value, at, written);
}
index += held;
}
}
return;
}
# How many options a struct holds, those of its groups among them.
def options_in<T>(): u64 {
var count := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
count++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
count += options_in::<type_of(field)>();
}
}
return count;
}
# The index among the options of the one of a long name, or `no_option`.
def option_named<T>(name: strview): u64 {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if named_as(name, field.name, attached::<option>(field)[0].name) {
return index;
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val found := option_named::<type_of(field)>(name);
if found != no_option {
return index + found;
}
index += options_in::<type_of(field)>();
}
}
return no_option;
}
# The index among the options of the one of a short name, or `no_option`.
def option_lettered<T>(letter: u8): u64 {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if attached::<option>(field)[0].short == letter {
return index;
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val found := option_lettered::<type_of(field)>(letter);
if found != no_option {
return index + found;
}
index += options_in::<type_of(field)>();
}
}
return no_option;
}
# Whether the option of an index takes a value, which a switch and a count do
# not.
def takes_value<T>(which: u64): bool {
var index := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if index == which {
if attached::<option>(field)[0].count {
return false;
}
if const type_of(field) is switch {
return false;
} else {
return true;
}
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val held := options_in::<type_of(field)>();
if which < index + held {
return takes_value::<type_of(field)>(which - index);
}
index += held;
}
}
return false;
}
# The long name of the first `required` option left out, counting the options
# from an index, or empty text where none is.
def required_left<T>(seen: &vector<u64>, from: u64): string {
var index := from;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if attached::<option>(field)[0].required && !holds(seen, index) {
return long_name(field.name, attached::<option>(field)[0].name);
}
index++;
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
val left := required_left::<type_of(field)>(seen, index);
if left.length != 0 {
return left;
}
index += options_in::<type_of(field)>();
}
}
return string::new(nothing {});
}
# Whether any option's short name is a digit, which makes `-5` an option rather
# than a positional argument.
def digit_named<T>(): bool {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if attached::<option>(field)[0].short.is_digit {
return true;
}
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
if digit_named::<type_of(field)>() {
return true;
}
}
}
return false;
}
# Whether the command has `-h`, where `short`, or else `--help`, which it has
# unless an option of its own takes the name.
def helps<T>(short: bool): bool {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if short && attached::<option>(field)[0].short == 'h' {
return false;
}
if !short && named_as("help", field.name, attached::<option>(field)[0].name) {
return false;
}
} else if const field.kind == target::fields && attached::<group>(field).length > 0 {
if !helps::<type_of(field)>(short) {
return false;
}
}
}
return true;
}
# How many positional arguments come before a struct's union of subcommands, or
# `no_option` where it has none.
def arguments_before_command<T>(): u64 {
var count := 0u;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
if is_command::<type_of(field)>() {
return count;
}
count++;
}
}
return no_option;
}
# Whether a type is a union of subcommands, which a field marked `@argument`
# holds. Only a type with a declaration of its own may be one, which the
# language's own types are not.
def is_command<V>(): bool {
if const V is switch || V is value || V is repeated {
return false;
} else if const decl_of::<V>().kind == target::unions && attached::<command>(decl_of::<V>()).length > 0 {
return true;
} else {
return false;
}
}
# How many positional arguments a field of a type takes.
def shape_of<V>(): shape {
if const V is repeated {
return shape::many;
} else if const V is vacant {
return shape::optional;
} else {
return shape::one;
}
}
# Stores what an argument gives into a field: one more element of what is
# repeated, or else the value read, in place of any before. A union of
# subcommands is read otherwise, and takes nothing here.
def store<V>(place: &mut V, text: strview): result<void, strview> {
if const V is repeated {
return place.add_argument(text);
} else if const V is value {
var read := V::from_argument(text) else (why) { return why; };
place = move(read);
return;
} else if const V is switch {
return "is a switch";
} else if const decl_of::<V>().kind == target::enums {
var read := read_value::<V>(text) else (why) { return why; };
place = move(read);
return;
} else {
return "is not read";
}
}
# Reads a value of a type from the text written: a `value` reads itself, and an
# enum is read by the name of a member marked `@choice`.
def read_value<V>(text: strview): result<V, strview> {
if const V is value {
return V::from_argument(text);
} else if const V is switch {
compile_error("A switch is turned on by its option alone, so it is not read from text: a `maybe` or `vector` of `bool` is not read.");
return "is not read";
} else if const decl_of::<V>().kind == target::enums {
for const member in members_of(decl_of::<V>()) {
if const member.kind == target::members && attached::<choice>(member).length > 0 {
if named_as(text, member.name, attached::<choice>(member)[0].name) {
return value_of(member);
}
}
}
return "is not one of the choices";
} else {
compile_error("The type is not read from an argument. A field read is a `bool` switch, an enum of members marked `@choice`, or what implements `args::value`, or a `maybe` or `vector` of one.");
return "is not read";
}
}
# Adds one to a count, which is an integer.
def count_one<V>(place: &mut V): void {
if const V is integer {
place = place + 1;
}
}
# The value a switch has where its option is written.
def switched<V>(): V where V: switch {
return V::switched_on();
}
# Whether the indices hold one.
def holds(indices: &vector<u64>, index: u64): bool {
for &each in indices {
return true if each == index;
}
return false;
}
# The error of a value its type refused, at the argument holding it.
def refused(at: u64, text: strview, name: strview, why: strview): error {
return error { kind = error_kind::invalid_value, at = at, text = text, name = name, reason = why };
}
# The error of the help text or the version asked for, at the argument asking.
def asked(kind: error_kind, at: u64, text: strview): error {
return error { kind = kind, at = at, text = text, name = text };
}
# Whether a word names what is declared: the name given in its mark, where it
# is not empty, as it is written, or else the declaration's, whose `_` are
# written `-`.
def named_as(word: strview, declared: strview, given: strview): bool {
if given.length != 0 {
return word == given;
}
if word.length != declared.length {
return false;
}
for i in 0..word.length {
if word[i] != (declared[i] == '_' ? '-' : declared[i]) {
return false;
}
}
return true;
}
# A name as it is written: the name given in a mark, where it is not empty, or
# else the declaration's, whose `_` are written `-`.
def long_name(declared: strview, given: strview): string {
if given.length != 0 {
return string::from(given, nothing {});
}
var made := string::new(nothing {});
for each in declared {
made.push(each == '_' ? '-' : each);
}
return made;
}
# What the help text calls a positional argument, or an option's value: the
# name given in its mark, or else the declaration's in capitals.
def value_name(declared: strview, given: strview): string {
if given.length != 0 {
return string::from(given, nothing {});
}
var made := string::new(nothing {});
for each in declared {
made.push(each.to_upper);
}
return made;
}
# What an error calls a positional argument, as the help text does.
def argument_name(declared: strview, given: strview): strview {
return given.length != 0 ? given : keep(value_name(declared, given));
}
# Each short name as written, `-` and the letter or digit, which an error views.
const shorts: strview = "-0-1-2-3-4-5-6-7-8-9-A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z-a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z";
# A short name as written, as an error names it, or `-` alone for a byte that
# is no letter or digit.
def short_written(letter: u8): strview {
for i in 0..shorts.length / 2 {
if shorts[i * 2 + 1] == letter {
return shorts.substr(i * 2, 2);
}
}
return shorts.substr(0, 1);
}
# Text made for an error, which views it, kept for as long as the program runs,
# as an error's views of the arguments are.
var kept: vector<string>;
# Keeps text for as long as the program runs.
def keep(text: string): strview {
kept.append(move(text));
return kept[kept.length - 1].view();
}
# Checks the marks of a command, and of each command within it: while compiling,
# that each field read is of a type read from an argument, and before reading,
# what `if const` cannot decide, stopping the program with an `asserts` at the
# first mistake.
def check_command<T>(): void {
if const decl_of::<T>().kind == target::unions {
var names := vector::<string>::new();
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<command>(field).length > 0 {
if const type_of(field) is switch || type_of(field) is value || type_of(field) is repeated {
compile_error("A subcommand is a struct or union marked `@command`.", field.at);
} else if const attached::<command>(decl_of::<type_of(field)>()).length == 0 {
compile_error("A subcommand is a struct or union marked `@command`.", field.at);
} else {
check_command::<type_of(field)>();
}
var name := long_name(field.name, attached::<command>(field)[0].name);
for &other in names {
asserts(other.view() != name.view(), $"Two subcommands are named `{name}`.");
}
names.append(move(name));
}
}
} else {
var longs := vector::<string>::new();
var letters := vector::<u8>::new();
check_options::<T>(&mut longs, &mut letters);
var rests := 0u;
var commanded := false;
var single := true;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
asserts(!commanded, "A union of subcommands is the last argument.");
if const type_of(field) is switch {
compile_error("A switch is an option, which a positional argument is not.", field.at);
} else if const type_of(field) is value || type_of(field) is repeated {
} else if const decl_of::<type_of(field)>().kind == target::enums {
} else if const decl_of::<type_of(field)>().kind == target::unions && attached::<command>(decl_of::<type_of(field)>()).length > 0 {
asserts(single, "The arguments before a union of subcommands each take one.");
commanded = true;
check_command::<type_of(field)>();
} else {
compile_error("The type is not read from an argument. An argument is an enum of members marked `@choice`, or what implements `args::value`, or a `maybe` or `vector` of one, or a union of subcommands.", field.at);
}
if !commanded {
val rest := attached::<argument>(field)[0].rest;
single = single && !rest && shape_of::<type_of(field)>() == shape::one;
if rest {
rests++;
asserts(shape_of::<type_of(field)>() == shape::many, "The argument taking what follows `--` is a vector.");
asserts(rests <= 1, "Only one argument takes what follows `--`.");
}
}
}
}
}
}
# Checks the marks of the options of a command, or of a group within it, and of
# the groups within that, which share the names the options are given: while
# compiling, that each is of a type read from an argument, and that a group is
# a struct of options marked `@group`, and before reading, that no two options
# share a name, which an `asserts` stops the program at.
def check_options<T>(longs: &mut vector<string>, letters: &mut vector<u8>): void {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<option>(field).length > 0 && attached::<argument>(field).length > 0 {
compile_error("A field is read from an option or from the positional arguments, not both.", field.at);
}
if const field.kind == target::fields && attached::<group>(field).length > 0 && (attached::<option>(field).length > 0 || attached::<argument>(field).length > 0) {
compile_error("A group's field is read from the options of its struct, so it is marked only `@group`.", field.at);
}
if const field.kind == target::fields && attached::<option>(field).length > 0 {
if const type_of(field) is switch || type_of(field) is value || type_of(field) is repeated {
} else if const decl_of::<type_of(field)>().kind == target::enums {
} else if const decl_of::<type_of(field)>().kind == target::unions && attached::<command>(decl_of::<type_of(field)>()).length > 0 {
compile_error("Subcommands are read from the positional arguments, so their union is marked `@argument`.", field.at);
} else {
compile_error("The type is not read from an argument. An option is a `bool` switch, an enum of members marked `@choice`, or what implements `args::value`, or a `maybe` or `vector` of one.", field.at);
}
val marked := attached::<option>(field)[0];
var name := long_name(field.name, marked.name);
for &other in longs {
asserts(other.view() != name.view(), $"Two options are named `--{name}`.");
}
longs.append(move(name));
if marked.short != 0 {
asserts(marked.short.is_alnum, "A short name is a letter or a digit.");
for &other in letters {
asserts(other != marked.short, $"Two options are named `{short_written(marked.short)}`.");
}
letters.append(marked.short);
}
asserts(!marked.count || counts::<type_of(field)>(), "A `count` option is an integer.");
}
if const field.kind == target::fields && attached::<group>(field).length > 0 {
if const type_of(field) is switch || type_of(field) is value || type_of(field) is repeated {
compile_error("A group is a struct of options marked `@group`.", field.at);
} else if const decl_of::<type_of(field)>().kind != target::structs || attached::<group>(decl_of::<type_of(field)>()).length == 0 {
compile_error("A group is a struct of options marked `@group`.", field.at);
} else {
check_group::<type_of(field)>(longs, letters);
}
}
}
}
# Checks the marks of a group, which holds options and groups of them, as
# `check_options` does, and no positional argument.
def check_group<G>(longs: &mut vector<string>, letters: &mut vector<u8>): void {
for const field in members_of(decl_of::<G>()) {
if const field.kind == target::fields && attached::<argument>(field).length > 0 {
compile_error("A group holds options, and groups of them, but no positional argument.", field.at);
}
}
check_options::<G>(longs, letters);
}
# Whether a type counts how often its option is written, as an integer does.
def counts<V>(): bool {
if const V is integer {
return true;
} else {
return false;
}
}
def bool::switched_on(): bool { return true; }
def i8::from_argument(text: strview): result<i8, strview> {
val read := signed_within(text, 0 - 128, 127) else (why) { return why; };
return read as i8;
}
def i16::from_argument(text: strview): result<i16, strview> {
val read := signed_within(text, 0 - 32768, 32767) else (why) { return why; };
return read as i16;
}
def i32::from_argument(text: strview): result<i32, strview> {
val read := signed_within(text, 0 - 2147483648, 2147483647) else (why) { return why; };
return read as i32;
}
def i64::from_argument(text: strview): result<i64, strview> {
return signed_within(text, 0 - 9223372036854775807 - 1, 9223372036854775807);
}
def u8::from_argument(text: strview): result<u8, strview> {
val read := unsigned_within(text, 255) else (why) { return why; };
return read as u8;
}
def u16::from_argument(text: strview): result<u16, strview> {
val read := unsigned_within(text, 65535) else (why) { return why; };
return read as u16;
}
def u32::from_argument(text: strview): result<u32, strview> {
val read := unsigned_within(text, 4294967295) else (why) { return why; };
return read as u32;
}
def u64::from_argument(text: strview): result<u64, strview> {
return unsigned_within(text, 18446744073709551615);
}
def f32::from_argument(text: strview): result<f32, strview> {
val read := real_of(text) else (why) { return why; };
if read > 3.4028234663852886e38 || read < -3.4028234663852886e38 {
return "is too large";
}
return read as f32;
}
def f64::from_argument(text: strview): result<f64, strview> {
return real_of(text);
}
# A view of the argument, which lasts as long as the arguments do.
def strview::from_argument(text: strview): result<strview, strview> {
return result::<strview, strview> { value = text };
}
def string::from_argument(text: strview): result<string, strview> {
return string::from(text, nothing {});
}
def path::from_argument(text: strview): result<path, strview> {
var read := path::parse(text) else (_) { return "is not a path"; };
return move(read);
}
def maybe<T>::from_argument(text: strview): result<maybe<T>, strview> {
var read := read_value::<T>(text) else (why) { return why; };
var made: maybe<T> = move(read);
return move(made);
}
def maybe<T>::vacant_argument(): maybe<T> {
return nothing {};
}
def vector<T>::add_argument(&mut this, text: strview): result<void, strview> {
var read := read_value::<T>(text) else (why) { return why; };
this.append(move(read));
return;
}
# A whole number written in decimal, or after `0x`, `0o`, or `0b`, where `_` may
# separate digits, and a sign may come first: how large it is, and its sign.
struct whole {
var magnitude: u64;
var negative: bool;
}
# Reads a whole number, giving nothing where the text is no such number, or one
# past 64 bits.
def whole_of(text: strview): maybe<whole> {
var at := 0u;
var negative := false;
if text.length > 0 && (text[0] == '-' || text[0] == '+') {
negative = text[0] == '-';
at = 1;
}
var base := 10u;
if text.length > at + 1 && text[at] == '0' {
val marker := text[at + 1];
if marker == 'x' || marker == 'X' { base = 16; }
if marker == 'o' || marker == 'O' { base = 8; }
if marker == 'b' || marker == 'B' { base = 2; }
if base != 10 { at += 2; }
}
var digits := 0u;
var magnitude := 0u;
while at < text.length {
val byte := text[at];
at++;
continue if byte == '_' && digits != 0;
return nothing {} if !byte.is_alnum;
val digit := byte.digit_value;
return nothing {} if digit >= base;
return nothing {} if magnitude > (18446744073709551615 - digit) / base;
magnitude = magnitude * base + digit;
digits++;
}
return nothing {} if digits == 0;
return whole { magnitude = magnitude, negative = negative };
}
# A signed integer read from text, within bounds.
def signed_within(text: strview, low: i64, high: i64): result<i64, strview> {
val read := whole_of(text) else { return "is not a whole number"; };
val limit: u64 = read.negative ? (0 - (low + 1)) as u64 + 1 : high as u64;
if read.magnitude > limit {
return keep($"is not between {low} and {high}");
}
return read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64;
}
# An unsigned integer read from text, within a bound.
def unsigned_within(text: strview, high: u64): result<u64, strview> {
val read := whole_of(text) else { return "is not a whole number"; };
if read.magnitude > high || (read.negative && read.magnitude != 0) {
return keep($"is not between 0 and {high}");
}
return read.magnitude;
}
# A real number read from text.
def real_of(text: strview): result<f64, strview> {
return match real::parse::<f64>(text) {
value(read) => read,
error(_) => "is not a number",
};
}
+188
View File
@@ -0,0 +1,188 @@
name: std
gpid: malunal
semv: 1.0.0
# Each module is a library of its own, in the folder of its name, which reads
# `core`, `system`, and the modules it lists.
targets:
- name: std.containers
type: library
root: ./containers
- name: std.allocators
type: library
root: ./allocators
# `std::io::glob` is a module within `std::io`, in `io/glob/`, so it comes with it.
- name: std.io
type: library
root: ./io
- name: std.math
type: library
root: ./math
- name: std.time
type: library
root: ./time
deps: [std.io]
- name: std.thread
type: library
root: ./thread
deps: [std.containers, std.time]
- name: std.process
type: library
root: ./process
deps: [std.io]
- name: std.serial
type: library
root: ./serial
deps: [std.containers]
- name: std.testing
type: library
root: ./testing
deps: [std.io]
- name: std.text
type: library
root: ./text
- name: std.net
type: library
root: ./net
deps: [std.containers, std.io]
- name: std.semver
type: library
root: ./semver
- name: std.json
type: library
root: ./json
deps: [std.io, std.serial]
- name: std.yaml
type: library
root: ./yaml
deps: [std.containers, std.io, std.serial]
- name: std.xml
type: library
root: ./xml
deps: [std.containers]
- name: std.args
type: library
root: ./args
deps: [std.io, std.semver]
# Each module's tests, in the folder of its name, built and run as executables.
# Their `main` reads `std::io` and `std::process`, so each lists them. Those
# reading files of their own, as JSON's and YAML's suites, find them from the
# root of the repository.
tests:
- name: std.containers.tests
type: program
runs: native
deps: [std.containers, std.io, std.process, std.testing, std.thread]
srcs: [tests/main.sakura, tests/containers/*.sakura]
- name: std.allocators.tests
type: program
runs: native
deps: [std.allocators, std.containers, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/allocators/*.sakura]
- name: std.io.tests
type: program
runs: native
deps: [std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/io/**/*.sakura]
- name: std.math.tests
type: program
runs: native
deps: [std.math, std.time, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/math/*.sakura]
- name: std.time.tests
type: program
runs: native
deps: [std.time, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/time/*.sakura]
- name: std.thread.tests
type: program
runs: native
deps: [std.thread, std.time, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/thread/*.sakura]
- name: std.process.tests
type: program
runs: native
deps: [std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/process/*.sakura]
- name: std.net.tests
type: program
runs: native
deps: [std.net, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/net/*.sakura]
- name: std.serial.tests
type: program
runs: native
deps: [std.serial, std.containers, std.json, std.yaml, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/serial/*.sakura]
- name: std.json.tests
type: program
runs: native
deps: [std.json, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/json/*.sakura]
- name: std.yaml.tests
type: program
runs: native
deps: [std.yaml, std.json, std.serial, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/yaml/*.sakura]
- name: std.xml.tests
type: program
runs: native
deps: [std.xml, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/xml/*.sakura]
- name: std.args.tests
type: program
runs: native
deps: [std.args, std.io, std.process, std.testing]
srcs: [tests/main.sakura, tests/args/*.sakura]
exports:
- std.containers
- std.allocators
- std.io
- std.math
- std.time
- std.thread
- std.process
- std.serial
- std.testing
- std.text
- std.net
- std.semver
- std.json
- std.yaml
- std.xml
- std.args
package:
lic: MIT
desc: The Sakura programming language's standard library.
auth: John Christman <sorakatadzuma@gmail.com>
url: https://git.malunal.studio/sakura/std
+169
View File
@@ -0,0 +1,169 @@
#! @file arc.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `arc`, one value on the heap that every copy owns, counted
#! atomically, for values threads share, as Rust's `Arc`; and `arc_weak`, which
#! refers to it without keeping it.
#!
#! Copies count with a relaxed add, as nothing is read through the count, and
#! close with a subtraction that releases, so what each owner did to the value
#! comes before the last owner closes it, which acquires before it does, as
#! Rust's `Arc` and C++'s `shared_ptr` do.
module std::containers;
# What an `arc` points at: the counts, then the value. The weak count holds one
# for all the owners together, as `rc_cell` does.
struct arc_cell<T> {
var owners: atomic<u64>;
var weak: atomic<u64>;
var value: T;
}
#! One value on the heap, owned by every copy, which `copy` makes, on any
#! thread, and closed where the last copy closes.
#!
#! Threads reading what they share need nothing more, but what they change
#! through `get` is guarded as any memory threads share is: an `arc<mutex<T>>`
#! or an `arc<atomic<T>>` is the usual way. An `arc` is one word, the counted
#! value's address, which is never null, so `maybe<arc<T>>` is one word too.
#! @tparam T What it holds.
pub struct arc<T> : owning, copyable, moveable {
var _at: &mut arc_cell<T>;
}
#! A reference to a value an `arc` owns that does not keep it: `lock` gives an
#! owner while any other is left.
#! @tparam T What it refers to.
pub struct arc_weak<T> : owning, copyable, moveable {
var _at: *mut arc_cell<T>;
}
#! Moves a value to the heap, with one owner.
#! @param value The value.
#! @returns Its first owner.
pub def arc<T>::new(value: T): arc<T> {
val at := allocate_for::<arc_cell<T>>(size_of::<arc_cell<T>>()) as *mut arc_cell<T>;
at[0] = arc_cell::<T> {
owners = atomic::<u64>::new(1),
weak = atomic::<u64>::new(1),
value = move(&mut value)
};
return arc::<T> { _at = through(at) };
}
#! Lends the value an `arc` owns.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def arc<T>::get(&this): &T {
return &this._at.value;
}
#! Lends the value an `arc` owns, to be changed, which threads guard as they do
#! any memory they share.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def arc<T>::get(&mut this): &mut T {
return &mut this._at.value;
}
#! How many owners share the value, which other threads may change at once.
#! @param this An owner.
#! @returns How many, this one among them.
pub def arc<T>::count(&this): u64 {
return this._at.owners.load(order::relaxed);
}
#! A reference to the value that does not keep it.
#! @param this An owner.
#! @returns The reference.
pub def arc<T>::weak(&this): arc_weak<T> {
_ = this._at.weak.fetch_add(1, order::relaxed);
return arc_weak::<T> { _at = this._at as *mut arc_cell<T> };
}
#! Makes another owner of the same value.
#! @param other An owner.
#! @returns The new owner.
pub def arc<T>::copy_of(other: &arc<T>): arc<T> {
_ = other._at.owners.fetch_add(1, order::relaxed);
return arc::<T> { _at = other._at };
}
#! Moves an owner, leaving the one moved from empty.
#! @param other The owner to move from.
#! @returns The owner it was.
pub def arc<T>::move_of(other: &mut arc<T>): arc<T> {
val made := arc::<T> { _at = other._at };
(other as *mut u64)[0] = 0;
return made;
}
#! Closes an owner: the value too where it was the last, and the memory where no
#! weak reference is left either.
#! @param this The owner, which is empty after.
pub def arc<T>::close(&mut this): void {
val at := this._at as *mut arc_cell<T>;
return if at == null;
(this as *mut u64)[0] = 0;
return if at[0].owners.fetch_sub(1, order::release) != 1;
fence(order::acquire);
close(&mut at[0].value);
arc_cell_let_go::<T>(at);
}
#! An owner of the value a weak reference refers to, where any is left.
#! @param this The weak reference.
#! @returns The new owner, or nothing where the last closed.
pub def arc_weak<T>::lock(&this): maybe<arc<T>> {
return nothing {} if this._at == null;
var count := this._at[0].owners.load(order::relaxed);
while count != 0 {
if this._at[0].owners.compare_exchange_weak(count, count + 1, order::acquire, order::relaxed) is error(found) {
count = found;
} else {
return arc::<T> { _at = through(this._at) };
}
}
return nothing {};
}
#! Makes another weak reference to the same value.
#! @param other A weak reference.
#! @returns The new one.
pub def arc_weak<T>::copy_of(other: &arc_weak<T>): arc_weak<T> {
if other._at != null {
_ = other._at[0].weak.fetch_add(1, order::relaxed);
}
return arc_weak::<T> { _at = other._at };
}
#! Moves a weak reference, leaving the one moved from empty.
#! @param other The weak reference to move from.
#! @returns The weak reference it was.
pub def arc_weak<T>::move_of(other: &mut arc_weak<T>): arc_weak<T> {
val made := arc_weak::<T> { _at = other._at };
other._at = null;
return made;
}
#! Closes a weak reference, giving back the memory where it was the last
#! reference of any kind.
#! @param this The weak reference, which is empty after.
pub def arc_weak<T>::close(&mut this): void {
val at := this._at;
return if at == null;
this._at = null;
arc_cell_let_go::<T>(at);
}
# Lets go of the weak count's one, giving back the memory where it was the last.
def arc_cell_let_go<T>(at: *mut arc_cell<T>): void {
if at[0].weak.fetch_sub(1, order::release) == 1 {
fence(order::acquire);
raw_release(at as *mut u8);
}
}
+531
View File
@@ -0,0 +1,531 @@
#! @file chain.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `chain` container. Chains are a structured
#! container that stores each element in a node of its own, linked to the nodes
#! before and after it.
module std::containers;
#! A `chain` is a structured data container, doubly linked, that stores each of
#! its elements in a node of its own.
#!
#! They are useful where elements are added and removed at either end, and where
#! an element must never move once it is added, since each keeps its own node
#! until it is removed. Reaching an element by index walks the chain from
#! whichever end is nearer.
#! @tparam T The type of its elements.
pub struct chain<T>
: owning
, hashable
, indexable<u64, T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _hed: *mut chain<T>::node;
var _tal: *mut chain<T>::node;
var _len: u64;
}
#! An element of a chain, with the nodes before and after it.
struct chain<T>::node {
var value: T;
var prev: *mut chain<T>::node;
var next: *mut chain<T>::node;
}
#! Walks the elements of a chain from its front, giving a reference that reads
#! each in turn, which is what `iter(&this)` lends and `for x` and `for &x`
#! walk.
pub struct chain<T>::cursor : sized_iterator<&T>, backward_iterator<&T> {
var _at: *mut chain<T>::node;
var _end: *mut chain<T>::node;
var _left: u64;
}
#! Gives the next element of the chain.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def chain<T>::cursor::next(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &(*here).value;
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def chain<T>::cursor::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the cursor has left, from the back of the chain.
#! @param this The cursor to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def chain<T>::cursor::next_back(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._end;
this._end = (*here).prev;
this._left = this._left - 1;
return &(*here).value;
}
#! Walks the elements of a chain from its front, giving a reference that writes
#! each in turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
pub struct chain<T>::mut_cursor : sized_iterator<&mut T>, backward_iterator<&mut T> {
var _at: *mut chain<T>::node;
var _end: *mut chain<T>::node;
var _left: u64;
}
#! Gives the next element of the chain, to be written.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def chain<T>::mut_cursor::next(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &mut (*here).value;
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def chain<T>::mut_cursor::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the cursor has left, from the back of the chain, to
#! be written.
#! @param this The cursor to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def chain<T>::mut_cursor::next_back(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._end;
this._end = (*here).prev;
this._left = this._left - 1;
return &mut (*here).value;
}
#! Provides read only access to the length of a chain.
#! @param this The chain to get the length of.
#! @returns The length of the chain.
pub val chain<T>::length: u64 {
get => this._len;
}
#! Indicates if a chain is empty.
#! @param this The chain to check.
#! @returns Whether the chain is empty.
pub val chain<T>::is_empty: bool {
get => this._len == 0;
}
#! Creates a new chain with no allocator.
#! @returns The created chain container.
#! @remarks Will use the built in `raw_allocate` and `raw_release` for memory
#! management.
pub def chain<T>::new(): chain<T> {
return chain::<T>::new(nothing{});
}
#! Creates a new chain with an optional allocator.
#! @param alloc The optional allocator for the nodes of the chain.
#! @returns The created chain container, which holds no elements yet.
pub def chain<T>::new(alloc: maybe<&mut allocator>): chain<T> {
return chain::<T> { _alc = alloc, _hed = null, _tal = null, _len = 0 };
}
#! Creates a copy of the provided chain.
#! @param other The chain to copy.
#! @returns The copy, which owns its own nodes and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def chain<T>::copy_of(other: &chain<T>): chain<T> {
var made := chain::<T>::new(other._alc);
var at := other._hed;
while at != null {
made.push_back(copy::<T>(&(*at).value));
at = (*at).next;
}
return made;
}
#! Creates a new chain by moving the nodes of another chain into it.
#! @param other The chain to move elements from, which holds none after.
#! @returns The moved chain, which takes the nodes and allocator with it.
#! @remarks Nothing is copied and no element is touched: the nodes move as they
#! stand, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def chain<T>::move_of(other: &mut chain<T>): chain<T> {
val made: chain<T> = chain {
_alc = other._alc,
_hed = other._hed,
_tal = other._tal,
_len = other._len
};
other._hed = null;
other._tal = null;
other._len = 0;
return made;
}
#! Gets the element at the provided index, walking from the nearer end.
#! @param this The chain to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def chain<T>::at(&this, index: u64): &T {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
return &(*this.node_at(index)).value;
}
#! Gets the element at the provided index, walking from the nearer end.
#! @param this The chain to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def chain<T>::at(&mut this, index: u64): &mut T {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
return &mut (*this.node_at(index)).value;
}
#! Gets the element at an index, if the chain holds one there, for an index
#! that may be past the end in a program that is right.
#! @param this The chain to read.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def chain<T>::get(&this, index: u64): maybe<&T> {
return nothing {} if index >= this._len;
return &(*this.node_at(index)).value;
}
#! Gets the element at an index to write it, if the chain holds one there.
#! @param this The chain to write.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def chain<T>::get(&mut this, index: u64): maybe<&mut T> {
return nothing {} if index >= this._len;
return &mut (*this.node_at(index)).value;
}
#! Gets the element at the front of a chain.
#! @param this The chain to get the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def chain<T>::front(&this): &T {
if const checking() {
if this._len == 0 {
fault("The chain is empty.");
}
}
return &(*this._hed).value;
}
#! Gets the element at the front of a chain.
#! @param this The chain to get the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def chain<T>::front(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The chain is empty.");
}
}
return &mut (*this._hed).value;
}
#! Gets the element at the back of a chain.
#! @param this The chain to get the back of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def chain<T>::back(&this): &T {
if const checking() {
if this._len == 0 {
fault("The chain is empty.");
}
}
return &(*this._tal).value;
}
#! Gets the element at the back of a chain.
#! @param this The chain to get the back of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def chain<T>::back(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The chain is empty.");
}
}
return &mut (*this._tal).value;
}
#! Pushes a new element onto the front of a chain.
#! @param this The chain to push the value onto.
#! @param value The value to push onto the chain.
#! @remarks An allocator that gives no more memory stops the program.
pub def chain<T>::push_front(&mut this, value: T): void {
this.link(null, this._hed, move(value));
}
#! Pushes a new element onto the back of a chain.
#! @param this The chain to push the value onto.
#! @param value The value to push onto the chain.
#! @remarks An allocator that gives no more memory stops the program.
pub def chain<T>::push_back(&mut this, value: T): void {
this.link(this._tal, null, move(value));
}
#! Pops the element off the front of a chain.
#! @param this The chain to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def chain<T>::pop_front(&mut this): void {
if const checking() {
if this._len == 0 {
fault("The chain is empty.");
}
}
this.unlink(this._hed);
}
#! Pops the element off the back of a chain.
#! @param this The chain to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def chain<T>::pop_back(&mut this): void {
if const checking() {
if this._len == 0 {
fault("The chain is empty.");
}
}
this.unlink(this._tal);
}
#! Adds an element at an index, after the elements before it.
#! @param this The chain to insert into.
#! @param index Where the element goes, from `0` to `length`, where `length`
#! appends. An index past that stops a checked program.
#! @param value The element to insert.
#! @remarks An allocator that gives no more memory stops the program.
pub def chain<T>::insert_at(&mut this, index: u64, value: T): void {
if const checking() {
if index > this._len {
past_end(index, this._len);
}
}
if index == this._len {
this.push_back(move(value));
return;
}
val next := this.node_at(index);
this.link((*next).prev, next, move(value));
}
#! Removes the element at an index.
#! @param this The chain to remove from.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @remarks The element is closed where it closes, or holds what does.
pub def chain<T>::remove_at(&mut this, index: u64): void {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
this.unlink(this.node_at(index));
}
#! Removes the first element equal to the one given.
#! @param this The chain to remove from.
#! @param elem The element to look for.
#! @returns Whether an element equalled it and was removed.
#! @remarks The element is closed where it closes, or holds what does.
pub def chain<T>::remove(&mut this, elem: &T): bool {
var at := this._hed;
while at != null {
if equals::<T>(&(*at).value, elem) {
this.unlink(at);
return true;
}
at = (*at).next;
}
return false;
}
#! Tells whether the chain holds an element equal to the one given.
#! @param this The chain to search.
#! @param elem The element to look for.
#! @returns Whether any element equals it.
pub def chain<T>::contains(&this, elem: &T): bool {
var at := this._hed;
while at != null {
return true if equals::<T>(&(*at).value, elem);
at = (*at).next;
}
return false;
}
#! Removes all elements from a chain, disposing their nodes.
#! @param this The chain to clear.
#! @remarks Elements that close, or hold what does, are closed.
pub def chain<T>::clear(&mut this): void {
var at := this._hed;
while at != null {
val next := (*at).next;
this.release(at);
at = next;
}
this._hed = null;
this._tal = null;
this._len = 0;
}
#! Removes all elements of a chain, disposing their nodes.
#! @param this The chain to close.
pub def chain<T>::close(&mut this): void {
this.clear();
}
#! Compares one chain to another by equality.
#! @param this The chain to compare against.
#! @param other The chain to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def chain<T>::equals(&this, other: &chain<T>): bool {
if this._len != other._len {
return false;
}
var mine := this._hed;
var theirs := other._hed;
while mine != null {
return false if !equals::<T>(&(*mine).value, &(*theirs).value);
mine = (*mine).next;
theirs = (*theirs).next;
}
return true;
}
#! Lends a cursor that reads the elements from the front of the chain, which
#! `for x in c` walks.
#! @param this The chain to walk.
#! @returns The cursor, which is only good until the chain changes or closes.
pub def chain<T>::iter(&this): chain<T>::cursor {
return chain::<T>::cursor { _at = this._hed, _end = this._tal, _left = this._len };
}
#! Lends a cursor that writes the elements where they are, from the front of the
#! chain, which `for &mut x in c` walks.
#! @param this The chain to walk.
#! @returns The cursor, which is only good until the chain changes or closes.
pub def chain<T>::iter(&mut this): chain<T>::mut_cursor {
return chain::<T>::mut_cursor { _at = this._hed, _end = this._tal, _left = this._len };
}
#! Hashes the provided chain.
#! @param this The chain to hash.
#! @returns The hashed value of the chain.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def chain<T>::hash(&this): u64 {
var code := this._len;
var at := this._hed;
while at != null {
code = mix(code, hash::<T>(&(*at).value));
at = (*at).next;
}
return code;
}
# The node at an index, which is below the length, walked to from the nearer end.
def chain<T>::node_at(&this, index: u64): *mut chain<T>::node {
if index < this._len / 2 {
var at := this._hed;
for _ in 0..index {
at = (*at).next;
}
return at;
}
var at := this._tal;
for _ in 0..(this._len - 1 - index) {
at = (*at).prev;
}
return at;
}
def chain<T>::link(
&mut this,
prev: *mut chain<T>::node,
next: *mut chain<T>::node,
value: T
): void {
# An allocator that gives no memory stops the program, as `acquire` does.
val made := acquire::<chain<T>::node>(this._alc, 1);
(*made).value = move(value);
(*made).prev = prev;
(*made).next = next;
if prev == null {
this._hed = made;
} else {
(*prev).next = made;
}
if next == null {
this._tal = made;
} else {
(*next).prev = made;
}
this._len++;
}
def chain<T>::unlink(&mut this, node: *mut chain<T>::node): void {
if (*node).prev == null {
this._hed = (*node).next;
} else {
(*(*node).prev).next = (*node).next;
}
if (*node).next == null {
this._tal = (*node).prev;
} else {
(*(*node).next).prev = (*node).prev;
}
this.release(node);
this._len--;
}
def chain<T>::release(&mut this, node: *mut chain<T>::node): void {
close(&mut (*node).value);
dispose::<chain<T>::node>(this._alc, node, 1);
}
+501
View File
@@ -0,0 +1,501 @@
#! @file deque.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `deque` container. Deques are a structured
#! container where data is pushed and popped at either end.
module std::containers;
#! A `deque` is a structured data container, a double-ended queue, that stores
#! its content in order and is pushed and popped at either end.
#!
#! They are useful wherever work is taken from both ends, such as undo
#! histories, sliding windows, and work-stealing schedulers, and wherever a
#! queue must also be indexed.
#!
#! Its elements live in one block used as a ring: the front is at `_hed`, and
#! each element after it is at the next index, wrapping to the start of the
#! block.
#! @tparam T The type of its elements.
pub struct deque<T>
: owning
, hashable
, indexable<u64, T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _dat: *mut T;
var _hed: u64;
var _len: u64;
var _cap: u64;
}
#! Provides read only access to the length of a deque.
#! @param this The deque to get the length of.
#! @returns The length of the deque.
pub val deque<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a deque.
#! @param this The deque to get the capacity of.
#! @returns The capacity of the deque.
pub val deque<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a deque is empty.
#! @param this The deque to check.
#! @returns Whether the deque is empty.
pub val deque<T>::is_empty: bool {
get => this._len == 0;
}
#! Indicates if a deque is full.
#! @param this The deque to check.
#! @returns Whether the deque is full.
pub val deque<T>::is_full: bool {
get => this._len == this._cap;
}
#! Creates a new deque with no allocator and a default size.
#! @returns The created deque container.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def deque<T>::new(): deque<T> {
return deque::<T>::new(4, nothing{});
}
#! Creates a new deque with an optional allocator and a default size.
#! @param alloc The optional allocator for the memory backing of the deque.
#! @returns The created deque container.
pub def deque<T>::new(alloc: maybe<&mut allocator>): deque<T> {
return deque::<T>::new(4, alloc);
}
#! Creates a new deque with an optional allocator and a provided size.
#! @param size The initial capacity of the deque, which may be none.
#! @param alloc The optional allocator for the memory backing of the deque.
#! @returns The created deque container, which holds no elements yet.
pub def deque<T>::new(size: u64, alloc: maybe<&mut allocator>): deque<T> {
var made: deque<T> = deque {
_alc = alloc,
_dat = null,
_hed = 0,
_len = 0,
_cap = 0
};
made.reserve(size);
return made;
}
#! Creates a copy of the provided deque.
#! @param other The deque to copy.
#! @returns The copy, which owns its own memory and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def deque<T>::copy_of(other: &deque<T>): deque<T> {
var made := deque::<T>::new(other._len, other._alc);
for index in 0..other._len {
made.push_back(copy::<T>(&other._dat[other.slot(index)]));
}
return made;
}
#! Creates a new deque by moving the data of another deque into it.
#! @param other The deque to move elements from, which holds none after.
#! @returns The moved deque, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no element is touched: the memory moves as it
#! stands, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def deque<T>::move_of(other: &mut deque<T>): deque<T> {
val made: deque<T> = deque {
_alc = other._alc,
_dat = other._dat,
_hed = other._hed,
_len = other._len,
_cap = other._cap
};
other._dat = null;
other._hed = 0;
other._len = 0;
other._cap = 0;
return made;
}
#! Gets the element at the provided index, counted from the front.
#! @param this The deque to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def deque<T>::at(&this, index: u64): &T {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
return &this._dat[this.slot(index)];
}
#! Gets the element at the provided index, counted from the front.
#! @param this The deque to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def deque<T>::at(&mut this, index: u64): &mut T {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
return &mut this._dat[this.slot(index)];
}
#! Gets the element at an index, if the deque holds one there, for an index
#! that may be past the end in a program that is right.
#! @param this The deque to read.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def deque<T>::get(&this, index: u64): maybe<&T> {
return nothing {} if index >= this._len;
return &this._dat[this.slot(index)];
}
#! Gets the element at an index to write it, if the deque holds one there.
#! @param this The deque to write.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def deque<T>::get(&mut this, index: u64): maybe<&mut T> {
return nothing {} if index >= this._len;
return &mut this._dat[this.slot(index)];
}
#! Gets the element at the front of a deque.
#! @param this The deque to get the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def deque<T>::front(&this): &T {
if const checking() {
if this._len == 0 {
fault("The deque is empty.");
}
}
return &this._dat[this._hed];
}
#! Gets the element at the front of a deque.
#! @param this The deque to get the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def deque<T>::front(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The deque is empty.");
}
}
return &mut this._dat[this._hed];
}
#! Gets the element at the back of a deque.
#! @param this The deque to get the back of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def deque<T>::back(&this): &T {
if const checking() {
if this._len == 0 {
fault("The deque is empty.");
}
}
return &this._dat[this.slot(this._len - 1)];
}
#! Gets the element at the back of a deque.
#! @param this The deque to get the back of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def deque<T>::back(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The deque is empty.");
}
}
return &mut this._dat[this.slot(this._len - 1)];
}
#! Pushes a new element onto the front of a deque.
#! @param this The deque to push the value onto.
#! @param value The value to push onto the deque.
#! @remarks An allocator that gives no more memory stops the program.
pub def deque<T>::push_front(&mut this, value: T): void {
if this.is_full {
this.grow();
}
this._hed = (this._hed + this._cap - 1) % this._cap;
this._dat[this._hed] = move(value);
this._len++;
}
#! Pushes a new element onto the back of a deque.
#! @param this The deque to push the value onto.
#! @param value The value to push onto the deque.
#! @remarks An allocator that gives no more memory stops the program.
pub def deque<T>::push_back(&mut this, value: T): void {
if this.is_full {
this.grow();
}
this._dat[this.slot(this._len)] = move(value);
this._len++;
}
#! Pops the element off the front of a deque.
#! @param this The deque to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def deque<T>::pop_front(&mut this): void {
if const checking() {
if this._len == 0 {
fault("The deque is empty.");
}
}
this.release(this._hed);
this._hed = (this._hed + 1) % this._cap;
this._len--;
}
#! Pops the element off the back of a deque.
#! @param this The deque to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def deque<T>::pop_back(&mut this): void {
if const checking() {
if this._len == 0 {
fault("The deque is empty.");
}
}
this.release(this.slot(this._len - 1));
this._len--;
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the deque provided.
#! @param this The deque to reserve elements for.
#! @param count The number of elements to reserve for a deque.
pub def deque<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes all elements from a deque.
#! @param this The deque to clear.
#! @remarks Elements that close, or hold what does, are closed. The backing data
#! is kept but not disposed.
pub def deque<T>::clear(&mut this): void {
for index in 0..this._len {
this.release(this.slot(index));
}
this._hed = 0;
this._len = 0;
}
#! Removes all elements of a deque then disposes the backing memory.
#! @param this The deque to close.
pub def deque<T>::close(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[this.slot(index)]);
}
}
this._hed = 0;
this._len = 0;
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = null;
this._cap = 0;
}
#! Compares one deque to another by equality.
#! @param this The deque to compare against.
#! @param other The deque to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def deque<T>::equals(&this, other: &deque<T>): bool {
if this._len != other._len {
return false;
}
for index in 0..this._len {
return false if !equals::<T>(
&this._dat[this.slot(index)],
&other._dat[other.slot(index)]
);
}
return true;
}
#! Walks the elements of a deque from its front, giving a reference that reads
#! each in turn, which is what `iter(&this)` lends and `for x` and `for &x`
#! walk.
pub struct deque<T>::cursor : sized_iterator<&T>, backward_iterator<&T> {
var _dat: *mut T;
var _at: u64;
var _cap: u64;
var _left: u64;
}
#! Gives the next element of the deque.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def deque<T>::cursor::next(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (here + 1) % this._cap;
this._left = this._left - 1;
return &this._dat[here];
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def deque<T>::cursor::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the cursor has left, from the back of the deque.
#! @param this The cursor to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def deque<T>::cursor::next_back(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &this._dat[(this._at + this._left) % this._cap];
}
#! Walks the elements of a deque from its front, giving a reference that writes
#! each in turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
pub struct deque<T>::mut_cursor : sized_iterator<&mut T>, backward_iterator<&mut T> {
var _dat: *mut T;
var _at: u64;
var _cap: u64;
var _left: u64;
}
#! Gives the next element of the deque, to be written.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def deque<T>::mut_cursor::next(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (here + 1) % this._cap;
this._left = this._left - 1;
return &mut this._dat[here];
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def deque<T>::mut_cursor::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the cursor has left, from the back of the deque, to
#! be written.
#! @param this The cursor to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def deque<T>::mut_cursor::next_back(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &mut this._dat[(this._at + this._left) % this._cap];
}
#! Lends a cursor that reads the elements from the front of the deque, which
#! `for x in d` walks.
#! @param this The deque to walk.
#! @returns The cursor, which is only good until the deque changes or closes.
pub def deque<T>::iter(&this): deque<T>::cursor {
return deque::<T>::cursor { _dat = this._dat, _at = this._hed, _cap = this._cap, _left = this._len };
}
#! Lends a cursor that writes the elements where they are, from the front of the
#! deque, which `for &mut x in d` walks.
#! @param this The deque to walk.
#! @returns The cursor, which is only good until the deque changes or closes.
pub def deque<T>::iter(&mut this): deque<T>::mut_cursor {
return deque::<T>::mut_cursor { _dat = this._dat, _at = this._hed, _cap = this._cap, _left = this._len };
}
#! Hashes the provided deque.
#! @param this The deque to hash.
#! @returns The hashed value of the deque.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def deque<T>::hash(&this): u64 {
var code := this._len;
for index in 0..this._len {
code = mix(code, hash::<T>(&this._dat[this.slot(index)]));
}
return code;
}
def deque<T>::slot(&this, index: u64): u64 {
return (this._hed + index) % this._cap;
}
def deque<T>::release(&mut this, slot: u64): void {
close(&mut this._dat[slot]);
# The slot is emptied where writing over it would close what it held.
if const T is closeable {
memset((this._dat + slot) as *mut u8, 0, bytes_of::<T>(1));
}
}
# Gives the deque room for more elements, doubling it.
def deque<T>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the deque room for a number of elements, where it has less, with them
# from its first slot. An allocator that gives no memory stops the program, as
# `acquire` does.
def deque<T>::grow(&mut this, size: u64): void {
if size <= this._cap {
return;
}
val block := acquire::<T>(this._alc, size);
val first := this._cap - this._hed;
val lead := this._len < first ? this._len : first;
memcpy(block as *mut u8, (this._dat + this._hed) as *mut u8, bytes_of::<T>(lead));
memcpy((block + lead) as *mut u8, this._dat as *mut u8, bytes_of::<T>(this._len - lead));
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = block;
this._hed = 0;
this._cap = size;
}
+657
View File
@@ -0,0 +1,657 @@
#! @file dict.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `dict` container. Dictionaries are an unordered
#! container that stores each value by a key, finding it by the hash of that key.
module std::containers;
#! A `dict` is an unordered data container that stores values by key, holding
#! one value for each key.
#!
#! They are useful wherever something is looked up by name or by some other
#! value, such as symbol tables, caches, and counting occurrences.
#!
#! Its entries live in one block, and it has a bucket for each of them. A bucket
#! holds the first entry whose key hashes to it, one past its index so that zero
#! is an empty bucket, and an entry holds the next of its bucket as `next`. The
#! entries holding no key are chained the same way from `_fre`, and `-1` ends
#! either chain. Entries keep their places as the dictionary grows, so only its
#! buckets are made again.
#! @tparam K The type of its keys, which are `hashable` and `equatable`.
#! @tparam V The type of its values.
pub struct dict<K, V>
: owning
, hashable
, indexable<K, V>
, iterable<dict<K, V>::entry>
, extendable<pair<K, V>>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _bkt: *mut i64;
var _ent: *mut dict<K, V>::entry;
var _len: u64;
var _cap: u64;
var _fre: i64;
}
#! A key and its value, with the hash the key is found by and the next entry of
#! its bucket, or of the free chain. Iterating a dictionary gives a reference to
#! each, which reads its `key` and `value`.
pub struct dict<K, V>::entry {
#! The key, which no other entry of the dictionary holds.
pub var key: K;
#! The value the key holds.
pub var value: V;
#! The key's hash, kept so the entry is found and moved without hashing again.
pub var hash: u64;
#! The index of the next entry of its bucket, or of the free chain, or `-1`.
pub var next: i64;
}
#! Provides read only access to the length of a dictionary.
#! @param this The dictionary to get the length of.
#! @returns The number of keys it holds a value for.
pub val dict<K, V>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a dictionary.
#! @param this The dictionary to get the capacity of.
#! @returns The number of keys it has room for before it grows.
pub val dict<K, V>::capacity: u64 {
get => this._cap;
}
#! Indicates if a dictionary is empty.
#! @param this The dictionary to check.
#! @returns Whether the dictionary holds no keys.
pub val dict<K, V>::is_empty: bool {
get => this._len == 0;
}
#! Indicates if a dictionary is full.
#! @param this The dictionary to check.
#! @returns Whether the next new key makes it grow.
pub val dict<K, V>::is_full: bool {
get => this._len == this._cap;
}
#! Creates a new dictionary with no allocator, which takes memory once something
#! is added.
#! @returns The created dictionary, which holds no keys yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def dict<K, V>::new(): dict<K, V> {
return dict::<K, V>::new(nothing{});
}
#! Creates a new dictionary with an optional allocator, which takes memory once
#! something is added.
#! @param alloc The optional allocator for the memory backing of the
#! dictionary.
#! @returns The created dictionary, which holds no keys yet.
pub def dict<K, V>::new(alloc: maybe<&mut allocator>): dict<K, V> {
return dict::<K, V> { _alc = alloc, _bkt = null, _ent = null, _len = 0, _cap = 0, _fre = -1 };
}
#! Creates a new dictionary with an optional allocator and room for some keys.
#! @param size The number of keys to make room for, which may be none.
#! @param alloc The optional allocator for the memory backing of the
#! dictionary.
#! @returns The created dictionary, which holds no keys yet.
pub def dict<K, V>::new(size: u64, alloc: maybe<&mut allocator>): dict<K, V> {
var made := dict::<K, V>::new(alloc);
made.reserve(size);
return made;
}
#! Builds a dictionary holding copies of another's keys and values, with its
#! allocator.
#! @param other The dictionary to copy from.
#! @returns The copy, which owns its own memory, keys, and values.
#! @remarks Keys and values are copied by `copyable` where they provide one, so
#! a key or value owning memory is copied rather than shared.
pub def dict<K, V>::copy_of(other: &dict<K, V>): dict<K, V> {
var made := dict::<K, V>::new(other._cap, other._alc);
for home in 0..other._cap {
var at := other._bkt[home] - 1;
while at >= 0 {
val held := &other._ent[at as u64];
made.set(copy::<K>(&held.key), copy::<V>(&held.value));
at = held.next;
}
}
return made;
}
#! Creates a new dictionary by moving the data of another dictionary into it.
#! @param other The dictionary to move from, which holds nothing after.
#! @returns The moved dictionary, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no entry is touched: the memory moves as it
#! stands, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def dict<K, V>::move_of(other: &mut dict<K, V>): dict<K, V> {
val made: dict<K, V> = dict {
_alc = other._alc,
_bkt = other._bkt,
_ent = other._ent,
_len = other._len,
_cap = other._cap,
_fre = other._fre
};
other._bkt = null;
other._ent = null;
other._len = 0;
other._cap = 0;
other._fre = -1;
return made;
}
#! Gets the value of a key the dictionary holds.
#! @param this The dictionary to get the value from.
#! @param key The key of the value, which the dictionary must hold, or else a
#! checked program stops.
#! @returns The value of the key.
pub def dict<K, V>::at(&this, key: K): &V {
val found := this.find(&key);
if const checking() {
if found < 0 {
fault("The dictionary does not hold the key.");
}
}
return &this._ent[found as u64].value;
}
#! Gets the value of a key the dictionary holds.
#! @param this The dictionary to get the value from.
#! @param key The key of the value, which the dictionary must hold, or else a
#! checked program stops.
#! @returns The value of the key.
pub def dict<K, V>::at(&mut this, key: K): &mut V {
val found := this.find(&key);
if const checking() {
if found < 0 {
fault("The dictionary does not hold the key.");
}
}
return &mut this._ent[found as u64].value;
}
#! Gets the value of a key, if the dictionary holds one.
#! @param this The dictionary to get the value from.
#! @param key The key of the value.
#! @returns The value of the key, or `none` where it holds none.
pub def dict<K, V>::get(&this, key: &K): maybe<&V> {
val found := this.find(key);
if found < 0 {
return nothing {};
}
return &this._ent[found as u64].value;
}
#! Gets the value of a key, if the dictionary holds one.
#! @param this The dictionary to get the value from.
#! @param key The key of the value.
#! @returns The value of the key, or `none` where it holds none.
pub def dict<K, V>::get(&mut this, key: &K): maybe<&mut V> {
val found := this.find(key);
if found < 0 {
return nothing {};
}
return &mut this._ent[found as u64].value;
}
#! Gets a copy of the value of a key, or another value where the dictionary
#! holds none for it.
#! @param this The dictionary to get the value from.
#! @param key The key of the value.
#! @param fallback The value given where the dictionary holds none for the
#! key.
#! @returns A copy of the value of the key, or else `fallback`.
#! @remarks The value is copied by `copyable` where it provides one, as `copy`
#! copies it.
pub def dict<K, V>::get_or(&this, key: &K, fallback: V): V {
val found := this.find(key);
if found < 0 {
return fallback;
}
return copy::<V>(&this._ent[found as u64].value);
}
#! Sets the value of a key the dictionary does not hold yet.
#! @param this The dictionary to set the value in.
#! @param key The key to set the value of.
#! @param value The value to store for the key.
#! @returns Whether the key was new and took the value. A key the dictionary
#! already holds keeps the value it has.
#! @remarks An allocator that gives no more memory stops the program.
pub def dict<K, V>::insert(&mut this, key: K, value: V): bool {
if this.find(&key) >= 0 {
return false;
}
this.add(move(key), move(value));
return true;
}
#! Sets the value of a key.
#! @param this The dictionary to set the value in.
#! @param key The key to set the value of.
#! @param value The value to store for the key.
#! @remarks A key the dictionary already holds takes the new value, and one it
#! does not takes an entry of its own, which grows the dictionary when
#! it is full. An allocator that gives no more memory stops the
#! program.
pub def dict<K, V>::set(&mut this, key: K, value: V): void {
val found := this.find(&key);
if found >= 0 {
this._ent[found as u64].value = move(value);
return;
}
this.add(move(key), move(value));
}
# Gives a key the dictionary does not hold an entry of its own, growing it when
# it is full.
def dict<K, V>::add(&mut this, key: K, value: V): void {
if this._fre < 0 {
this.grow();
}
val slot := this._fre as u64;
val code := hash::<K>(&key);
val home := dict::<K, V>::home(code, this._cap);
this._fre = this._ent[slot].next;
this._ent[slot] = dict::<K, V>::entry {
key = move(key),
value = move(value),
hash = code,
next = this._bkt[home] - 1
};
this._bkt[home] = slot as i64 + 1;
this._len++;
}
#! Tells whether the dictionary holds a value for a key.
#! @param this The dictionary to search.
#! @param key The key to look for.
#! @returns Whether the key has a value in it.
pub def dict<K, V>::contains(&this, key: &K): bool {
return this.find(key) >= 0;
}
#! Removes the value of a key, if the dictionary holds one.
#! @param this The dictionary to remove from.
#! @param key The key of the value to remove.
#! @returns Whether the key had a value that was removed.
#! @remarks The key and value are closed where they close, or hold what does,
#! and the entry goes back on the free chain for the next key.
pub def dict<K, V>::remove(&mut this, key: &K): bool {
if this._len == 0 {
return false;
}
val code := hash::<K>(key);
val home := dict::<K, V>::home(code, this._cap);
var prev := -1 as i64;
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
val next := this._ent[here].next;
if this._ent[here].hash != code || !equals::<K>(&this._ent[here].key, key) {
prev = at;
at = next;
continue;
}
if prev < 0 {
this._bkt[home] = next + 1;
} else {
this._ent[prev as u64].next = next;
}
this.release(here);
this._ent[here].next = this._fre;
this._fre = at;
this._len--;
return true;
}
return false;
}
#! Reserves room for a number of keys, so that setting that many grows the
#! dictionary no further.
#! @param this The dictionary to reserve room in.
#! @param count The number of keys to make room for.
pub def dict<K, V>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes every key and value from a dictionary.
#! @param this The dictionary to clear.
#! @remarks Keys and values that close, or hold what does, are closed. The
#! backing memory is kept for the keys set after.
pub def dict<K, V>::clear(&mut this): void {
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
at = this._ent[here].next;
this.release(here);
}
}
memset(this._bkt as *mut u8, 0, bytes_of::<i64>(this._cap));
this._fre = -1;
this._len = 0;
this.free(0, this._cap);
}
#! Removes every key and value of a dictionary, then disposes the backing
#! memory.
#! @param this The dictionary to close.
#! @remarks The memory is given back as it stands, so the keys and values are
#! closed where they close, or hold what does, but the entries are not
#! emptied.
pub def dict<K, V>::close(&mut this): void {
if const K is closeable || V is closeable {
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
at = this._ent[here].next;
this.close_entry(here);
}
}
}
this._len = 0;
if this._bkt != null {
dispose::<i64>(this._alc, this._bkt, this._cap);
dispose::<dict<K, V>::entry>(this._alc, this._ent, this._cap);
}
this._bkt = null;
this._ent = null;
this._cap = 0;
this._fre = -1;
}
#! Compares one dictionary to another for equality.
#! @param this The dictionary to compare against.
#! @param other The dictionary to compare with.
#! @returns Whether both hold the same keys, each with an equal value.
pub def dict<K, V>::equals(&this, other: &dict<K, V>): bool {
if this._len != other._len {
return false;
}
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
val found := other.find(&held.key);
return false if found < 0 || !equals::<V>(
&other._ent[found as u64].value,
&held.value
);
at = held.next;
}
}
return true;
}
#! Walks the entries of a dictionary, giving a reference that reads each in
#! turn, which is what `iter` lends and `for e in d` walks. Entries come in no
#! particular order, and each key once.
pub struct dict<K, V>::cursor : sized_iterator<&dict<K, V>::entry> {
var _bkt: *mut i64;
var _ent: *mut dict<K, V>::entry;
var _cap: u64;
var _bucket: u64;
var _at: i64;
var _left: u64;
}
#! Gives the next entry of the dictionary.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next entry; otherwise, `nothing`.
pub def dict<K, V>::cursor::next(&mut this): maybe<&dict<K, V>::entry> {
# Every entry holding a key is in the chain of its bucket, and nothing else is.
while this._at < 0 {
if this._bucket >= this._cap {
return nothing {};
}
this._at = this._bkt[this._bucket] - 1;
this._bucket++;
}
val here := this._at as u64;
this._at = this._ent[here].next;
this._left = this._left - 1;
return &this._ent[here];
}
#! How many entries the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def dict<K, V>::cursor::remaining(&this): u64 {
return this._left;
}
#! Lends a cursor that reads the entries of the dictionary, which `for e in d`
#! walks. Values are changed through `d[key]`, since a key never changes.
#! @param this The dictionary to walk.
#! @returns The cursor, which is only good until the dictionary changes or
#! closes.
pub def dict<K, V>::iter(&this): dict<K, V>::cursor {
return dict::<K, V>::cursor { _bkt = this._bkt, _ent = this._ent, _cap = this._cap, _bucket = 0, _at = -1, _left = this._len };
}
#! Makes a dictionary of the keys and values an iterator gives as pairs, each
#! key's last value kept.
#! @tparam I The iterator.
#! @param from The iterator, walked to its end.
#! @returns The dictionary.
pub def dict<K, V>::from<I>(from: I): dict<K, V> where I: iterator<pair<K, V>> {
var made := dict::<K, V>::new();
if const I is sized_iterator<pair<K, V>> {
made.reserve(from.remaining());
}
while from.next() is some(entry) {
made.set(move(&mut entry.first), move(&mut entry.second));
}
return made;
}
#! Gives a key a value, as `set` does, from a pair of them, so a dictionary is
#! what an iterator's `into` appends pairs to.
#! @param this The dictionary.
#! @param entry The key, first, and its value.
pub def dict<K, V>::append(&mut this, entry: pair<K, V>): void {
this.set(move(&mut entry.first), move(&mut entry.second));
}
#! Lends a cursor over the keys, in the order `iter` gives the entries.
#! @param this The dictionary to walk.
#! @returns The cursor, which is only good until the dictionary changes or
#! closes.
pub def dict<K, V>::keys(&this): dict<K, V>::key_cursor {
return dict::<K, V>::key_cursor { _from = this.iter() };
}
#! Lends a cursor over the values, in the order `iter` gives the entries.
#! @param this The dictionary to walk.
#! @returns The cursor, which is only good until the dictionary changes or
#! closes.
pub def dict<K, V>::values(&this): dict<K, V>::value_cursor {
return dict::<K, V>::value_cursor { _from = this.iter() };
}
#! Walks the keys of a dictionary, giving a reference that reads each in turn.
pub struct dict<K, V>::key_cursor : sized_iterator<&K> {
var _from: dict<K, V>::cursor;
}
#! Gives the next key.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the key; otherwise, `nothing`.
pub def dict<K, V>::key_cursor::next(&mut this): maybe<&K> {
if this._from.next() is some(&entry) {
return &entry.key;
}
return nothing {};
}
#! How many keys the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def dict<K, V>::key_cursor::remaining(&this): u64 {
return this._from.remaining();
}
#! Walks the values of a dictionary, giving a reference that reads each in turn.
pub struct dict<K, V>::value_cursor : sized_iterator<&V> {
var _from: dict<K, V>::cursor;
}
#! Gives the next value.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the value; otherwise, `nothing`.
pub def dict<K, V>::value_cursor::next(&mut this): maybe<&V> {
if this._from.next() is some(&entry) {
return &entry.value;
}
return nothing {};
}
#! How many values the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def dict<K, V>::value_cursor::remaining(&this): u64 {
return this._from.remaining();
}
#! Hashes the dictionary provided.
#! @param this The dictionary to hash.
#! @returns The hash code of the dictionary, which dictionaries holding the same
#! keys share however their entries are arranged.
#! @remarks Only the keys are hashed, and they are added rather than combined in
#! order, since two equal dictionaries may hold them in different
#! places.
pub def dict<K, V>::hash(&this): u64 {
var code := 0u;
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
code += mix(held.hash, 0x9E3779B97F4A7C15);
at = held.next;
}
}
return mix(code, this._len);
}
def dict<K, V>::find(&this, key: &K): i64 {
if this._len == 0 {
return -1;
}
val code := hash::<K>(key);
var at := this._bkt[dict::<K, V>::home(code, this._cap)] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
return at if held.hash == code && equals::<K>(&held.key, key);
at = held.next;
}
return -1;
}
# The bucket of a hash among a power of two of them. The hash is spread first, so
# that keys differing only in their high bits, as pairs packed into one integer
# do, and integers, which are their own hash, still fall in buckets of their own.
def dict<K, V>::home(code: u64, size: u64): u64 {
return (((code ^ (code >> 32)) * 0x9E3779B97F4A7C15) >> 32) & (size - 1);
}
def dict<K, V>::release(&mut this, index: u64): void {
this.close_entry(index);
# The entry is emptied where setting another key in it would close what it held.
if const K is closeable || V is closeable {
memset((this._ent + index) as *mut u8, 0, bytes_of::<dict<K, V>::entry>(1));
}
}
def dict<K, V>::close_entry(&mut this, index: u64): void {
close(&mut this._ent[index].key);
close(&mut this._ent[index].value);
}
def dict<K, V>::free(&mut this, from: u64, to: u64): void {
var index := to;
while index > from {
index--;
this._ent[index].next = this._fre;
this._fre = index as i64;
}
}
# Gives the dictionary room for more keys, doubling it.
def dict<K, V>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the dictionary room for a number of keys, where it has less. An allocator
# that gives no memory stops the program, as `acquire` and `resize` do.
def dict<K, V>::grow(&mut this, wanted: u64): void {
if wanted <= this._cap {
return;
}
# There is a power of two of buckets, which `home` masks a hash to.
var size: u64 = 4;
while size < wanted {
size *= 2;
}
# A bucket holding 0 holds no key.
val buckets := acquire::<i64>(this._alc, size);
memset(buckets as *mut u8, 0, bytes_of::<i64>(size));
val entries := this._ent == null
? acquire::<dict<K, V>::entry>(this._alc, size)
: resize::<dict<K, V>::entry>(this._alc, this._ent, this._cap, size);
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
val moved := dict::<K, V>::home(entries[here].hash, size);
at = entries[here].next;
entries[here].next = buckets[moved] - 1;
buckets[moved] = here as i64 + 1;
}
}
if this._bkt != null {
dispose::<i64>(this._alc, this._bkt, this._cap);
}
val from := this._cap;
this._bkt = buckets;
this._ent = entries;
this._cap = size;
this.free(from, size);
}
+21
View File
@@ -0,0 +1,21 @@
#! @file faults.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the fault std's containers stop with where they are asked for an
#! element they do not hold, which no switch leaves out, as `core`'s own
#! containers have.
module std::containers;
# Stops the program where one of std's containers is asked for an element past
# its end, as indexing a view outside its length does. A container calls it
# only where its check fails, so that where the check holds, it costs a compare,
# and the call is no more than its two numbers, which keeps what calls it short
# enough to be emitted where it is called. Where the check is, and what called
# it, the report of the stop names.
def past_end(index: u64, length: u64): void {
fault($"Index {index} is out of bounds: the length is {length}.");
}
+230
View File
@@ -0,0 +1,230 @@
#! @file groups.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `groups` container. Groups hold elements
#! gathered by a key numbered from zero, those of each key one after another, so
#! that the elements of a key are a view.
module std::containers;
#! A `groups` holds elements gathered by key, those of each key one after
#! another in one block, so that the elements of a key are a view of it.
#!
#! They are useful wherever items are listed by what they belong to, such as
#! the reads of each value, the edges into each block, or the members of each
#! scope, which a vector for each key would scatter over the heap.
#!
#! Groups are filled in two passes, as compressed sparse rows are: the first
#! counts the elements of each key, `seal` works out where those of each key
#! begin, and the second puts each element in its place. The elements of a key
#! keep the order they were put in. The keys are numbered from zero, up to the
#! number the groups are made or reset for.
#! @tparam T The type of the elements.
pub struct groups<T>
: owning
, moveable
{
var _first: vector<u64>; # Where the elements of each key begin, then where the last end: zeros until sealed.
var _place: vector<u64>; # How many elements each key has until sealed, then where the next of each goes.
var _items: vector<T>;
var _sealed: bool;
}
#! Provides read only access to how many keys the groups have.
#! @param this The groups.
#! @returns The number of keys, each of which has a group, empty or not.
pub val groups<T>::keys: u64 {
get => this._first.length == 0 ? 0 : this._first.length - 1;
}
#! Provides read only access to how many elements the groups hold together.
#! @param this The groups.
#! @returns The number of elements, which is how many were counted once the
#! groups are sealed, and 0 before.
pub val groups<T>::size: u64 {
get => this._items.length;
}
#! Indicates whether the groups are sealed, so that elements are put rather
#! than counted.
#! @param this The groups.
#! @returns Whether `seal` was called since they were made or reset.
pub val groups<T>::is_sealed: bool {
get => this._sealed;
}
#! Creates groups for a number of keys, with no allocator, ready to count.
#! @param keys The number of keys.
#! @returns The created groups, each empty.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def groups<T>::new(keys: u64): groups<T> {
return groups::<T>::new(keys, nothing{});
}
#! Creates groups for a number of keys, with an optional allocator, ready to
#! count.
#! @param keys The number of keys.
#! @param alloc The optional allocator for the memory backing of the groups.
#! @returns The created groups, each empty.
pub def groups<T>::new(keys: u64, alloc: maybe<&mut allocator>): groups<T> {
var made := groups::<T> {
_first = vector::<u64>::new(alloc),
_place = vector::<u64>::new(alloc),
_items = vector::<T>::new(alloc),
_sealed = false
};
made._first.resize(keys + 1);
made._place.resize(keys);
return made;
}
#! Creates new groups by moving the data of others into them.
#! @param other The groups to move from, which have no keys after.
#! @returns The moved groups, which take the memory and allocator with them.
pub def groups<T>::move_of(other: &mut groups<T>): groups<T> {
val made := groups::<T> {
_first = move(&mut other._first),
_place = move(&mut other._place),
_items = move(&mut other._items),
_sealed = other._sealed
};
other._first.resize(1);
other._sealed = false;
return made;
}
#! Empties the groups and gives them a number of keys, ready to count again,
#! keeping the memory.
#! @param this The groups to reset.
#! @param keys The number of keys.
#! @remarks Elements are closed where they close, or hold what does.
pub def groups<T>::reset(&mut this, keys: u64): void {
this._items.clear();
this._place.clear();
this._place.resize(keys);
this._first.clear();
this._first.resize(keys + 1);
this._sealed = false;
}
#! Counts an element of a key, which is put once the groups are sealed.
#! @param this The groups, which are not sealed, or else the program stops.
#! @param key The key, below `keys`, past which a checked program stops.
pub def groups<T>::count(&mut this, key: u64): void {
this.count(key, 1);
}
#! Counts a number of elements of a key, which are put once the groups are
#! sealed.
#! @param this The groups, which are not sealed, or else the program stops.
#! @param key The key, below `keys`, past which a checked program stops.
#! @param many How many elements.
pub def groups<T>::count(&mut this, key: u64, many: u64): void {
if this._sealed {
fault("The groups are counted after they were sealed.");
}
this.check(key);
this._place.data[key] += many;
}
#! Works out where the elements of each key begin, from those counted, so that
#! they can be put.
#! @param this The groups, which are not sealed, or else the program stops.
#! @remarks Every key's elements are made room for at once, zeroed until they
#! are put. An allocator that gives no more memory stops the program.
pub def groups<T>::seal(&mut this): void {
if this._sealed {
fault("The groups are sealed a second time.");
}
val keys := this._first.length - 1;
val first := this._first.data;
val place := this._place.data;
for key in 0..keys {
first[key + 1] = first[key] + place[key];
place[key] = first[key];
}
this._items.resize(first[keys]);
this._sealed = true;
}
#! Puts an element of a key in its place, after those of the key put before it.
#! @param this The groups, which are sealed, or else a checked program stops.
#! @param key The key, below `keys`, past which a checked program stops, with
#! an element counted that is not put yet, or else a checked
#! program stops.
#! @param item The element.
#! @remarks Each check stops a checked program as indexing past an end does,
#! which keeps `put` short enough to be written where it is called.
pub def groups<T>::put(&mut this, key: u64, item: T): void {
if const checking() {
if key >= this._place.length {
past_end(key, this._place.length);
}
}
# Groups not sealed end every key at zero, so no element fits there.
val at := this._place.data[key];
val end := this._first.data[key + 1];
if const checking() {
if at >= end {
past_end(at, end);
}
}
this._items.data[at] = move(item);
this._place.data[key] = at + 1;
}
#! How many elements a key has.
#! @param this The groups.
#! @param key The key, below `keys`, past which a checked program stops.
#! @returns The number of its elements: those counted, before the groups are
#! sealed, and those made room for after.
pub def groups<T>::length(&this, key: u64): u64 {
this.check(key);
if !this._sealed {
return this._place.data[key];
}
return this._first.data[key + 1] - this._first.data[key];
}
#! Lends a view of the elements of a key, in the order they were put.
#! @param this The groups.
#! @param key The key, below `keys`, past which a checked program stops.
#! @returns The view, which is only good until the groups are reset or closed,
#! and whose elements not put yet are zero. Before the groups are
#! sealed, it is empty.
pub def groups<T>::of(&this, key: u64): span<T> {
# Groups not sealed begin and end every key at zero, so its view is empty.
val next := key + 1;
if const checking() {
if next >= this._first.length {
past_end(key, this._first.length - 1);
}
}
val start := this._first.data[key];
return span::<T>::over(this._items.data + start, this._first.data[next] - start);
}
#! Removes every element and every key, and gives back the memory the groups
#! hold.
#! @param this The groups to close.
#! @remarks Elements are closed where they close, or hold what does.
pub def groups<T>::close(&mut this): void {
this._items.close();
this._place.close();
this._first.close();
this._sealed = false;
}
# Stops the program where a key is not one of the groups'.
def groups<T>::check(&this, key: u64): void {
if const checking() {
if key + 1 >= this._first.length {
past_end(key, this.keys);
}
}
}
+565
View File
@@ -0,0 +1,565 @@
#! @file hashset.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `hashset` container. Hash sets are an unordered
#! container that holds each value once, finding it by its hash.
module std::containers;
#! A `hashset` is an unordered data container that holds values, each of them
#! once.
#!
#! They are useful wherever what matters of a value is whether it is held, such
#! as the names already seen, the nodes already visited, and the members two
#! groups have in common.
#!
#! It is laid out as a dictionary is, holding values rather than keys. Its
#! entries live in one block, and it has a bucket for each of them. A bucket
#! holds the first entry whose value hashes to it, one past its index so that
#! zero is an empty bucket, and an entry holds the next of its bucket as `next`.
#! The entries holding no value are chained the same way from `_fre`, and `-1`
#! ends either chain. Entries keep their places as the set grows, so only its
#! buckets are made again.
#! @tparam T The type of its values, which are `hashable` and `equatable`.
pub struct hashset<T>
: owning
, hashable
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _bkt: *mut i64;
var _ent: *mut hashset<T>::entry;
var _len: u64;
var _cap: u64;
var _fre: i64;
}
#! A value of a set, with the hash it is found by and the next entry of its
#! bucket, or of the free chain.
struct hashset<T>::entry {
var value: T;
var hash: u64;
var next: i64;
}
#! Provides read only access to the length of a set.
#! @param this The set to get the length of.
#! @returns The number of values it holds.
pub val hashset<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a set.
#! @param this The set to get the capacity of.
#! @returns The number of values it has room for before it grows.
pub val hashset<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a set is empty.
#! @param this The set to check.
#! @returns Whether the set holds no values.
pub val hashset<T>::is_empty: bool {
get => this._len == 0;
}
#! Indicates if a set is full.
#! @param this The set to check.
#! @returns Whether the next new value makes it grow.
pub val hashset<T>::is_full: bool {
get => this._len == this._cap;
}
#! Creates a new set with no allocator, which takes memory once something is
#! added.
#! @returns The created set, which holds no values yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def hashset<T>::new(): hashset<T> {
return hashset::<T>::new(nothing{});
}
#! Creates a new set with an optional allocator, which takes memory once
#! something is added.
#! @param alloc The optional allocator for the memory backing of the set.
#! @returns The created set, which holds no values yet.
pub def hashset<T>::new(alloc: maybe<&mut allocator>): hashset<T> {
return hashset::<T> { _alc = alloc, _bkt = null, _ent = null, _len = 0, _cap = 0, _fre = -1 };
}
#! Creates a new set with an optional allocator and room for some values.
#! @param size The number of values to make room for, which may be none.
#! @param alloc The optional allocator for the memory backing of the set.
#! @returns The created set, which holds no values yet.
pub def hashset<T>::new(size: u64, alloc: maybe<&mut allocator>): hashset<T> {
var made := hashset::<T>::new(alloc);
made.reserve(size);
return made;
}
#! Builds a set holding copies of another's values, with its allocator.
#! @param other The set to copy from.
#! @returns The copy, which owns its own memory and values.
#! @remarks Values are copied by `copyable` where they provide one, so a value
#! owning memory is copied rather than shared.
pub def hashset<T>::copy_of(other: &hashset<T>): hashset<T> {
var made := hashset::<T>::new(other._cap, other._alc);
for home in 0..other._cap {
var at := other._bkt[home] - 1;
while at >= 0 {
val held := &other._ent[at as u64];
made.add(copy::<T>(&held.value), held.hash);
at = held.next;
}
}
return made;
}
#! Creates a new set by moving the data of another set into it.
#! @param other The set to move from, which holds nothing after.
#! @returns The moved set, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no entry is touched: the memory moves as it
#! stands, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def hashset<T>::move_of(other: &mut hashset<T>): hashset<T> {
val made: hashset<T> = hashset {
_alc = other._alc,
_bkt = other._bkt,
_ent = other._ent,
_len = other._len,
_cap = other._cap,
_fre = other._fre
};
other._bkt = null;
other._ent = null;
other._len = 0;
other._cap = 0;
other._fre = -1;
return made;
}
#! Adds a value the set does not hold yet.
#! @param this The set to add the value to.
#! @param value The value to add.
#! @returns Whether the value was new and was added. A value the set already
#! holds an equal of is closed, and the one it holds kept.
#! @remarks A new value takes an entry of its own, which grows the set when it
#! is full. An allocator that gives no more memory stops the program.
pub def hashset<T>::insert(&mut this, value: T): bool {
val code := hash::<T>(&value);
if this.find(&value, code) >= 0 {
return false;
}
this.add(move(value), code);
return true;
}
#! Tells whether the set holds a value.
#! @param this The set to search.
#! @param value The value to look for.
#! @returns Whether the set holds a value equal to it.
pub def hashset<T>::contains(&this, value: &T): bool {
return this.find(value, hash::<T>(value)) >= 0;
}
#! Gets the value the set holds that equals the one given, if it holds one.
#! @param this The set to get the value from.
#! @param value The value to look for.
#! @returns The value the set holds, or `none` where it holds none equal to it.
#! @remarks The value held is the set's own, which equals the one given but may
#! be another, as two `string`s holding the same text are, so a set
#! can keep one of each value for whatever asks for it.
pub def hashset<T>::get(&this, value: &T): maybe<&T> {
val found := this.find(value, hash::<T>(value));
if found < 0 {
return nothing {};
}
return &this._ent[found as u64].value;
}
#! Removes a value, if the set holds one equal to it.
#! @param this The set to remove from.
#! @param value The value to remove.
#! @returns Whether the set held the value and it was removed.
#! @remarks The value is closed where it closes, or holds what does, and the
#! entry goes back on the free chain for the next value.
pub def hashset<T>::remove(&mut this, value: &T): bool {
if this._len == 0 {
return false;
}
val code := hash::<T>(value);
val home := hashset::<T>::home(code, this._cap);
var prev := -1 as i64;
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
if held.hash == code && equals::<T>(&held.value, value) {
this.unlink(home, prev, at as u64);
return true;
}
prev = at;
at = held.next;
}
return false;
}
#! Adds a copy of each value of another set that this one does not hold, so that
#! it holds what either held.
#! @param this The set to add to.
#! @param other The set whose values are added.
#! @remarks Values are copied by `copyable` where they provide one, and the
#! other set is left as it was.
pub def hashset<T>::union_with(&mut this, other: &hashset<T>): void {
for home in 0..other._cap {
var at := other._bkt[home] - 1;
while at >= 0 {
val held := &other._ent[at as u64];
if this.find(&held.value, held.hash) < 0 {
this.add(copy::<T>(&held.value), held.hash);
}
at = held.next;
}
}
}
#! Removes each value another set does not hold, so that the set holds what both
#! held.
#! @param this The set to remove from.
#! @param other The set whose values are kept.
#! @remarks The values removed are closed where they close, or hold what does.
pub def hashset<T>::intersect_with(&mut this, other: &hashset<T>): void {
this.keep(other, true);
}
#! Removes each value another set holds, so that the set holds what only it held.
#! @param this The set to remove from.
#! @param other The set whose values are removed.
#! @remarks The values removed are closed where they close, or hold what does.
pub def hashset<T>::subtract(&mut this, other: &hashset<T>): void {
this.keep(other, false);
}
#! Tells whether another set holds every value of this one.
#! @param this The set whose values are looked for.
#! @param other The set to look in.
#! @returns Whether each value of this set is in the other, which an empty set's
#! are of any set.
pub def hashset<T>::is_subset_of(&this, other: &hashset<T>): bool {
if this._len > other._len {
return false;
}
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
return false if other.find(&held.value, held.hash) < 0;
at = held.next;
}
}
return true;
}
#! Tells whether the set holds no value another holds.
#! @param this The set to compare against.
#! @param other The set to compare with.
#! @returns Whether the two hold no value in common.
#! @remarks The values of the smaller set are looked for in the larger.
pub def hashset<T>::is_disjoint_from(&this, other: &hashset<T>): bool {
if this._len > other._len {
return other.is_disjoint_from(this);
}
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
return false if other.find(&held.value, held.hash) >= 0;
at = held.next;
}
}
return true;
}
#! Reserves room for a number of values, so that adding that many grows the set
#! no further.
#! @param this The set to reserve room in.
#! @param count The number of values to make room for.
pub def hashset<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes every value from a set.
#! @param this The set to clear.
#! @remarks Values that close, or hold what does, are closed. The backing memory
#! is kept for the values added after.
pub def hashset<T>::clear(&mut this): void {
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
at = this._ent[here].next;
this.release(here);
}
}
memset(this._bkt as *mut u8, 0, bytes_of::<i64>(this._cap));
this._fre = -1;
this._len = 0;
this.free(0, this._cap);
}
#! Removes every value of a set, then disposes the backing memory.
#! @param this The set to close.
#! @remarks The memory is given back as it stands, so the values are closed
#! where they close, or hold what does, but the entries are not
#! emptied.
pub def hashset<T>::close(&mut this): void {
if const T is closeable {
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
at = this._ent[here].next;
close(&mut this._ent[here].value);
}
}
}
this._len = 0;
if this._bkt != null {
dispose::<i64>(this._alc, this._bkt, this._cap);
dispose::<hashset<T>::entry>(this._alc, this._ent, this._cap);
}
this._bkt = null;
this._ent = null;
this._cap = 0;
this._fre = -1;
}
#! Compares one set to another for equality.
#! @param this The set to compare against.
#! @param other The set to compare with.
#! @returns Whether both hold the same values, however they are arranged.
pub def hashset<T>::equals(&this, other: &hashset<T>): bool {
return this._len == other._len && this.is_subset_of(other);
}
#! Walks the values of a set, giving a reference that reads each in turn, which
#! is what `iter` lends and `for x in s` walks. Values come in no particular
#! order, and each once.
pub struct hashset<T>::cursor : sized_iterator<&T> {
var _bkt: *mut i64;
var _ent: *mut hashset<T>::entry;
var _cap: u64;
var _bucket: u64;
var _at: i64;
var _left: u64;
}
#! Gives the next value of the set.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next value; otherwise, `nothing`.
pub def hashset<T>::cursor::next(&mut this): maybe<&T> {
# Every entry holding a value is in the chain of its bucket, and nothing else is.
while this._at < 0 {
if this._bucket >= this._cap {
return nothing {};
}
this._at = this._bkt[this._bucket] - 1;
this._bucket++;
}
val here := this._at as u64;
this._at = this._ent[here].next;
this._left = this._left - 1;
return &this._ent[here].value;
}
#! How many values the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def hashset<T>::cursor::remaining(&this): u64 {
return this._left;
}
#! Lends a cursor that reads the values of the set, which `for x in s` walks.
#! There is none that writes them, since a value changed where it is would no
#! longer be found by its hash.
#! @param this The set to walk.
#! @returns The cursor, which is only good until the set changes or closes.
pub def hashset<T>::iter(&this): hashset<T>::cursor {
return hashset::<T>::cursor { _bkt = this._bkt, _ent = this._ent, _cap = this._cap, _bucket = 0, _at = -1, _left = this._len };
}
#! Hashes the set provided.
#! @param this The set to hash.
#! @returns The hash code of the set, which sets holding the same values share
#! however their entries are arranged.
#! @remarks The values' hashes are added rather than combined in order, since
#! two equal sets may hold them in different places.
pub def hashset<T>::hash(&this): u64 {
var code := 0u;
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
code += mix(held.hash, 0x9E3779B97F4A7C15);
at = held.next;
}
}
return mix(code, this._len);
}
# The entry holding a value of a hash, or -1 where the set holds none.
def hashset<T>::find(&this, value: &T, code: u64): i64 {
if this._len == 0 {
return -1;
}
var at := this._bkt[hashset::<T>::home(code, this._cap)] - 1;
while at >= 0 {
val held := &this._ent[at as u64];
return at if held.hash == code && equals::<T>(&held.value, value);
at = held.next;
}
return -1;
}
# Gives a value of a hash, which the set does not hold, an entry of its own,
# growing the set when it is full.
def hashset<T>::add(&mut this, value: T, code: u64): void {
if this._fre < 0 {
this.grow();
}
val slot := this._fre as u64;
val home := hashset::<T>::home(code, this._cap);
this._fre = this._ent[slot].next;
this._ent[slot] = hashset::<T>::entry {
value = move(value),
hash = code,
next = this._bkt[home] - 1
};
this._bkt[home] = slot as i64 + 1;
this._len++;
}
# Takes an entry out of the chain of its bucket, after the entry before it there,
# or -1 where it is first, closes its value, and puts it on the free chain.
def hashset<T>::unlink(&mut this, home: u64, prev: i64, here: u64): void {
val next := this._ent[here].next;
if prev < 0 {
this._bkt[home] = next + 1;
} else {
this._ent[prev as u64].next = next;
}
this.release(here);
this._ent[here].next = this._fre;
this._fre = here as i64;
this._len--;
}
# Removes each value whose being held by another set is not what is kept: those
# it holds are kept where `held` is true, and those it does not where it is false.
# The other may be this set, since each entry is looked for before it is removed.
def hashset<T>::keep(&mut this, other: &hashset<T>, held: bool): void {
for home in 0..this._cap {
var prev := -1 as i64;
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
val next := this._ent[here].next;
if (other.find(&this._ent[here].value, this._ent[here].hash) >= 0) == held {
prev = at;
} else {
this.unlink(home, prev, here);
}
at = next;
}
}
}
# The bucket of a hash among a power of two of them, spread as a dictionary's is.
def hashset<T>::home(code: u64, size: u64): u64 {
return (((code ^ (code >> 32)) * 0x9E3779B97F4A7C15) >> 32) & (size - 1);
}
def hashset<T>::release(&mut this, index: u64): void {
close(&mut this._ent[index].value);
# The entry is emptied where adding another value in it would close what it held.
if const T is closeable {
memset((this._ent + index) as *mut u8, 0, bytes_of::<hashset<T>::entry>(1));
}
}
def hashset<T>::free(&mut this, from: u64, to: u64): void {
var index := to;
while index > from {
index--;
this._ent[index].next = this._fre;
this._fre = index as i64;
}
}
# Gives the set room for more values, doubling it.
def hashset<T>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the set room for a number of values, where it has less. An allocator that
# gives no memory stops the program, as `acquire` and `resize` do.
def hashset<T>::grow(&mut this, wanted: u64): void {
if wanted <= this._cap {
return;
}
# There is a power of two of buckets, which `home` masks a hash to.
var size: u64 = 4;
while size < wanted {
size *= 2;
}
# A bucket holding 0 holds no value.
val buckets := acquire::<i64>(this._alc, size);
memset(buckets as *mut u8, 0, bytes_of::<i64>(size));
val entries := this._ent == null
? acquire::<hashset<T>::entry>(this._alc, size)
: resize::<hashset<T>::entry>(this._alc, this._ent, this._cap, size);
for home in 0..this._cap {
var at := this._bkt[home] - 1;
while at >= 0 {
val here := at as u64;
val moved := hashset::<T>::home(entries[here].hash, size);
at = entries[here].next;
entries[here].next = buckets[moved] - 1;
buckets[moved] = here as i64 + 1;
}
}
if this._bkt != null {
dispose::<i64>(this._alc, this._bkt, this._cap);
}
val from := this._cap;
this._bkt = buckets;
this._ent = entries;
this._cap = size;
this.free(from, size);
}
+198
View File
@@ -0,0 +1,198 @@
#! @file heap.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `heap` container. Heaps keep the least of the
#! values they hold at hand, adding a value and taking the least each in time
#! that grows with the logarithm of how many there are.
module std::containers;
#! A `heap` holds values so that the least of them, by the order `<` gives, is
#! always first, which `peek` reads and `pop` removes.
#!
#! They are useful wherever the next of many things to do is the least of them,
#! such as the soonest event, the cheapest path found so far, or the interval
#! that begins first.
#!
#! Its values are held in one vector as a binary tree, each no greater than the
#! two below it: those below the value at index `i` are at `2i + 1` and `2i + 2`.
#! Values equal to each other come out in no particular order.
#! @tparam T The type of its values, which are `ordered`.
pub struct heap<T>
: owning
, copyable
, moveable
{
var _val: vector<T>;
}
#! Provides read only access to the length of a heap.
#! @param this The heap to get the length of.
#! @returns The number of values it holds.
pub val heap<T>::length: u64 {
get => this._val.length;
}
#! Indicates if a heap is empty.
#! @param this The heap to check.
#! @returns Whether the heap holds no values.
pub val heap<T>::is_empty: bool {
get => this._val.length == 0;
}
#! Creates a new heap with no allocator, which takes memory once something is
#! pushed.
#! @returns The created heap, which holds no values yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def heap<T>::new(): heap<T> {
return heap::<T>::new(nothing{});
}
#! Creates a new heap with an optional allocator, which takes memory once
#! something is pushed.
#! @param alloc The optional allocator for the memory backing of the heap.
#! @returns The created heap, which holds no values yet.
pub def heap<T>::new(alloc: maybe<&mut allocator>): heap<T> {
if const !(T is ordered) {
compile_error("A heap keeps its least value first, by the order `<` gives, so its values are `ordered`.");
}
return heap::<T> { _val = vector::<T>::new(alloc) };
}
#! Creates a new heap with an optional allocator and room for some values.
#! @param size The number of values to make room for, which may be none.
#! @param alloc The optional allocator for the memory backing of the heap.
#! @returns The created heap, which holds no values yet.
pub def heap<T>::new(size: u64, alloc: maybe<&mut allocator>): heap<T> {
var made := heap::<T>::new(alloc);
made._val.reserve(size);
return made;
}
#! Builds a heap holding copies of another's values, with its allocator.
#! @param other The heap to copy from.
#! @returns The copy, which owns its own memory and values.
#! @remarks Values are copied by `copyable` where they provide one.
pub def heap<T>::copy_of(other: &heap<T>): heap<T> {
return heap::<T> { _val = vector::<T>::copy_of(&other._val) };
}
#! Creates a new heap by moving the data of another heap into it.
#! @param other The heap to move from, which holds nothing after.
#! @returns The moved heap, which takes the memory and allocator with it.
pub def heap<T>::move_of(other: &mut heap<T>): heap<T> {
return heap::<T> { _val = move(&mut other._val) };
}
#! Adds a value.
#! @param this The heap to add the value to.
#! @param value The value to add.
#! @remarks The value rises past each value above it that is greater. An
#! allocator that gives no more memory stops the program.
pub def heap<T>::push(&mut this, value: T): void {
if const !(T is ordered) {
compile_error("A heap keeps its least value first, by the order `<` gives, so its values are `ordered`.");
}
this._val.append(move(value));
var at := this._val.length - 1;
val data := this._val.data;
while at > 0 {
val parent := (at - 1) / 2;
break if data[parent] <= data[at];
heap::<T>::swap(data, parent, at);
at = parent;
}
}
#! Reads the least value.
#! @param this The heap to read, which holds a value, or else a checked
#! program stops.
#! @returns The least value, which is only good until the heap changes or
#! closes.
pub def heap<T>::peek(&this): &T {
if const checking() {
if this._val.length == 0 {
past_end(0, 0);
}
}
return &this._val.data[0];
}
#! Removes the least value.
#! @param this The heap to remove from, which holds a value, or else a checked
#! program stops.
#! @remarks The value is closed where it closes, or holds what does, and not
#! given back, so read it with `peek` first. The last value takes its
#! place and sinks past each value below it that is less.
pub def heap<T>::pop(&mut this): void {
if const !(T is ordered) {
compile_error("A heap keeps its least value first, by the order `<` gives, so its values are `ordered`.");
}
if const checking() {
if this._val.length == 0 {
past_end(0, 0);
}
}
val data := this._val.data;
val last := this._val.length - 1;
heap::<T>::swap(data, 0, last);
this._val.truncate();
val count := this._val.length;
var at: u64 = 0;
while 2 * at + 1 < count {
var child := 2 * at + 1;
if child + 1 < count && data[child + 1] < data[child] {
child++;
}
break if data[at] <= data[child];
heap::<T>::swap(data, at, child);
at = child;
}
}
#! Lends a view of the values, in the order the heap holds them, which is not
#! the order they come out in.
#! @param this The heap to view.
#! @returns The view, which is only good until the heap changes or closes.
pub def heap<T>::view(&this): span<T> {
return this._val.view();
}
#! Removes every value, keeping the memory the heap holds them in.
#! @param this The heap to empty.
#! @remarks Values are closed where they close, or hold what does.
pub def heap<T>::clear(&mut this): void {
this._val.clear();
}
#! Removes every value and gives back the memory the heap holds.
#! @param this The heap to close.
#! @remarks Values are closed where they close, or hold what does.
pub def heap<T>::close(&mut this): void {
this._val.close();
}
# Swaps two values byte for byte, so that neither is closed or copied.
def heap<T>::swap(data: *mut T, first: u64, second: u64): void {
return if first == second;
if const !(T is closeable) {
val held: T = data[first];
data[first] = data[second];
data[second] = held;
return;
}
val a := (data + first) as *mut u8;
val b := (data + second) as *mut u8;
for at in 0..size_of::<T>() {
val held: u8 = a[at];
a[at] = b[at];
b[at] = held;
}
}
+401
View File
@@ -0,0 +1,401 @@
#! @file interner.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for an `interner` container. Interners give each
#! value an ID, the same for equal values, counting up in the order values are
#! first given.
module std::containers;
#! An `interner` gives each distinct value an ID of its own, a `u32` counted up
#! from zero in the order the values are first given, and keeps one copy of
#! each, which its ID reads back.
#!
#! They are useful wherever values are compared or kept many times over, such
#! as the names a compiler reads and the strings a file writes once each: two
#! values are equal exactly where their IDs are, and an ID is a small number
#! wherever the value would be large.
#!
#! Nothing is removed but by `clear`, so an ID is good for as long as the
#! interner is. Its values are held one after another, by ID, and a table of
#! slots finds a value's ID by its hash. The table is open, a power of two of
#! slots at least twice as many as the values, and a value is in the first slot
#! from where its hash begins that is free or holds it. A slot is 0, or one more
#! than an ID with the high half of the value's hash above it, which most values
#! that differ are told apart by without being compared.
#! @tparam T The type of its values, which are `hashable` and `equatable`.
pub struct interner<T>
: owning
, hashable
, indexable<u32, T>
, viewable<T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _val: vector<T>;
var _slt: *mut u64;
var _cap: u64;
}
#! Provides read only access to the length of an interner.
#! @param this The interner to get the length of.
#! @returns The number of values it holds, which is one more than the newest's
#! ID.
pub val interner<T>::length: u64 {
get => this._val.length;
}
#! Indicates if an interner is empty.
#! @param this The interner to check.
#! @returns Whether the interner holds no values.
pub val interner<T>::is_empty: bool {
get => this._val.length == 0;
}
#! Creates a new interner with no allocator, which takes memory once something
#! is interned.
#! @returns The created interner, which holds no values yet.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def interner<T>::new(): interner<T> {
return interner::<T>::new(nothing{});
}
#! Creates a new interner with an optional allocator, which takes memory once
#! something is interned.
#! @param alloc The optional allocator for the memory backing of the
#! interner.
#! @returns The created interner, which holds no values yet.
pub def interner<T>::new(alloc: maybe<&mut allocator>): interner<T> {
return interner::<T> { _alc = alloc, _val = vector::<T>::new(alloc), _slt = null, _cap = 0 };
}
#! Creates a new interner with an optional allocator and room for some values.
#! @param size The number of values to make room for, which may be none.
#! @param alloc The optional allocator for the memory backing of the
#! interner.
#! @returns The created interner, which holds no values yet.
pub def interner<T>::new(size: u64, alloc: maybe<&mut allocator>): interner<T> {
var made := interner::<T>::new(alloc);
made.reserve(size);
return made;
}
#! Builds an interner holding copies of another's values, each with the same
#! ID, with its allocator.
#! @param other The interner to copy from.
#! @returns The copy, which owns its own memory and values.
#! @remarks Values are copied by `copyable` where they provide one, so a value
#! owning memory is copied rather than shared. The slots are copied as
#! they are, since a copy hashes as what it copies does.
pub def interner<T>::copy_of(other: &interner<T>): interner<T> {
var made := interner::<T> {
_alc = other._alc,
_val = vector::<T>::copy_of(&other._val),
_slt = null,
_cap = other._cap
};
if other._slt != null {
made._slt = acquire::<u64>(other._alc, other._cap);
memcpy(made._slt as *mut u8, other._slt as *u8, bytes_of::<u64>(other._cap));
}
return made;
}
#! Creates a new interner by moving the data of another interner into it.
#! @param other The interner to move from, which holds nothing after.
#! @returns The moved interner, which takes the memory and allocator with it.
#! @remarks Nothing is copied: the memory moves as it stands, and the other is
#! left empty rather than dead, so closing it afterwards is harmless.
pub def interner<T>::move_of(other: &mut interner<T>): interner<T> {
val made: interner<T> = interner {
_alc = other._alc,
_val = move(&mut other._val),
_slt = other._slt,
_cap = other._cap
};
other._slt = null;
other._cap = 0;
return made;
}
#! Gives the ID of a value, adding the value where the interner holds none
#! equal to it.
#! @param this The interner to intern the value in.
#! @param value The value to intern.
#! @returns The ID of the value equal to it the interner holds, or else the new
#! ID it is given, one more than the newest's.
#! @remarks A value equal to one held is closed, and the one held kept. A new
#! value grows the interner where it needs room, and an allocator that
#! gives no more memory stops the program, as does a new value past
#! the last ID a `u32` holds.
pub def interner<T>::intern(&mut this, value: T): u32 {
if this._cap == 0 {
this.rehash(8);
}
val code := interner::<T>::spread(hash::<T>(&value));
val at := this.slot_of(&value, code);
val held := this._slt[at];
if held != 0 {
return ((held & 0xFFFFFFFF) - 1) as u32;
}
return this.add(move(value), code, at);
}
#! Gives the ID of the value whose view equals a view, making the value from the
#! view where the interner holds none, so that the view is copied only where it
#! is new, as a `strview` is into a `string`.
#! @tparam U The type of the elements of the view.
#! @param this The interner to intern the value in.
#! @param view The view of the value to intern.
#! @returns The ID of the value viewed as it, or else the new ID of the value
#! made from it, one more than the newest's.
#! @remarks The values are `viewable`, are made by a `from` taking the view and
#! the interner's allocator, as `string::from` is, and must hash as
#! their views do, as a `string` hashes as its text. A new value grows
#! the interner as `intern` does.
pub def interner<T>::intern_view<U>(&mut this, view: span<U>): u32 {
if const !(T is viewable<U>) || !(T is interner_made<U>) {
compile_error("`intern_view` finds values by their views and makes them from those views, so they are `viewable` as the view given, with a `from` taking it and an allocator.");
}
if this._cap == 0 {
this.rehash(8);
}
val code := interner::<T>::spread(view.hash());
val mask := this._cap - 1;
var at := code & mask;
while true {
val held := this._slt[at];
break if held == 0;
if (held >> 32) == (code >> 32) {
val id := (held & 0xFFFFFFFF) - 1;
return id as u32 if this._val.data[id].view() == view;
}
at = (at + 1) & mask;
}
return this.add(T::from(view, this._alc), code, at);
}
# A value made from a view of its elements and an allocator, as a `string` is
# from a `strview`, which `intern_view` makes what it does not hold of.
trait interner_made<U> {
def from(view: span<U>, alloc: maybe<&mut allocator>): self;
}
#! Gives the ID of a value, if the interner holds one equal to it.
#! @param this The interner to search.
#! @param value The value to look for.
#! @returns The ID of the value equal to it, or `none` where it holds none.
pub def interner<T>::find(&this, value: &T): maybe<u32> {
if this._cap == 0 {
return nothing {};
}
val held := this._slt[this.slot_of(value, interner::<T>::spread(hash::<T>(value)))];
if held == 0 {
return nothing {};
}
return ((held & 0xFFFFFFFF) - 1) as u32;
}
#! Gives the ID of the value whose view equals a view, if the interner holds
#! one, without making a value to look for, as a `string` would be made to look
#! for a `strview`.
#! @tparam U The type of the elements of the view.
#! @param this The interner to search.
#! @param view The view to look for.
#! @returns The ID of the value viewed as it, or `none` where it holds none.
#! @remarks The values are `viewable`, and must hash as their views do, as a
#! `string` hashes as its text, or this finds none of them. A value
#! that is to be interned where it is not found is interned at once
#! by `intern_view`.
pub def interner<T>::find_view<U>(&this, view: span<U>): maybe<u32> {
if const !(T is viewable<U>) {
compile_error("`find_view` finds values by their views, so they are `viewable` as the view given.");
}
if this._cap == 0 {
return nothing {};
}
val code := interner::<T>::spread(view.hash());
val mask := this._cap - 1;
var at := code & mask;
while true {
val held := this._slt[at];
break if held == 0;
if (held >> 32) == (code >> 32) {
val id := (held & 0xFFFFFFFF) - 1;
return id as u32 if this._val.data[id].view() == view;
}
at = (at + 1) & mask;
}
return nothing {};
}
#! Tells whether the interner holds a value.
#! @param this The interner to search.
#! @param value The value to look for.
#! @returns Whether it holds a value equal to it.
pub def interner<T>::contains(&this, value: &T): bool {
return this.find(value) is some;
}
#! Reads the value of an ID, which `i[id]` calls.
#! @param this The interner to read.
#! @param id The ID, below `length`, past which a checked program stops.
#! @returns The value, which is only good until the interner grows or closes.
#! There is none that writes it, since a value changed where it is
#! would no longer be found by its hash.
pub def interner<T>::at(&this, id: u32): &T {
return this._val.at(id as u64);
}
#! Lends a view of the values, by ID, without copying them.
#! @param this The interner to view.
#! @returns A view of its values, the value of each ID at that index, which is
#! only good until the interner grows or closes.
pub def interner<T>::view(&this): span<T> {
return this._val.view();
}
#! Reserves room for a number of values, so that interning that many new ones
#! grows the interner no further.
#! @param this The interner to reserve room in.
#! @param count The number of values to make room for.
pub def interner<T>::reserve(&mut this, count: u64): void {
this._val.reserve(count);
var size: u64 = this._cap != 0 ? this._cap : 8;
while size < count * 2 {
size *= 2;
}
if size > this._cap {
this.rehash(size);
}
}
#! Removes every value from an interner, so that the next value interned is
#! given the ID 0 again.
#! @param this The interner to clear.
#! @remarks Values that close, or hold what does, are closed. The backing memory
#! is kept for the values interned after.
pub def interner<T>::clear(&mut this): void {
this._val.clear();
if this._slt != null {
memset(this._slt as *mut u8, 0, bytes_of::<u64>(this._cap));
}
}
#! Removes every value of an interner, then disposes the backing memory.
#! @param this The interner to close.
#! @remarks Values that close, or hold what does, are closed.
pub def interner<T>::close(&mut this): void {
this._val.close();
if this._slt != null {
dispose::<u64>(this._alc, this._slt, this._cap);
}
this._slt = null;
this._cap = 0;
}
#! Compares one interner to another for equality.
#! @param this The interner to compare against.
#! @param other The interner to compare with.
#! @returns Whether both hold equal values, each with the same ID.
pub def interner<T>::equals(&this, other: &interner<T>): bool {
return this._val.equals(&other._val);
}
#! What `iter(&this)` lends, which reads the values by ID.
pub type interner<T>::cursor = span<T>::cursor;
#! Lends a cursor that reads the values in the order of their IDs, which `for x
#! in i` walks.
#! @param this The interner to walk.
#! @returns The cursor, which is only good until the interner grows or closes.
pub def interner<T>::iter(&this): span<T>::cursor {
return this._val.iter();
}
#! Hashes the values, in the order of their IDs.
#! @param this The interner to hash.
#! @returns The hash code, which interners holding equal values with the same
#! IDs share.
pub def interner<T>::hash(&this): u64 {
return this._val.hash();
}
# The slot holding the ID of a value of a hash, or the free slot it would be in.
# There is always one free, as the slots are at least twice as many as the values.
def interner<T>::slot_of(&this, value: &T, code: u64): u64 {
val mask := this._cap - 1;
var at := code & mask;
while true {
val held := this._slt[at];
break if held == 0;
if (held >> 32) == (code >> 32) && equals::<T>(&this._val.data[(held & 0xFFFFFFFF) - 1], value) {
break;
}
at = (at + 1) & mask;
}
return at;
}
# Holds a value of a hash, which the interner holds none equal to, giving it the
# next ID in the free slot found for it, then grows the slots where the values
# are more than half of them.
def interner<T>::add(&mut this, value: T, code: u64, at: u64): u32 {
val id := this._val.length;
if id >= 0xFFFFFFFF {
fault("The interner has no ID left for a new value.");
}
this._val.append(move(value));
this._slt[at] = (code & 0xFFFFFFFF00000000u) | (id + 1);
if this._val.length * 2 > this._cap {
this.rehash(this._cap * 2);
}
return id as u32;
}
# Makes the slots again, a power of two of them at least twice the values,
# putting each value's ID in its slot again. An allocator that gives no memory
# stops the program, as `acquire` does.
def interner<T>::rehash(&mut this, size: u64): void {
val slots := acquire::<u64>(this._alc, size);
memset(slots as *mut u8, 0, bytes_of::<u64>(size));
val mask := size - 1;
for id in 0..this._val.length {
val code := interner::<T>::spread(hash::<T>(&this._val.data[id]));
var at := code & mask;
while slots[at] != 0 {
at = (at + 1) & mask;
}
slots[at] = (code & 0xFFFFFFFF00000000u) | (id + 1);
}
if this._slt != null {
dispose::<u64>(this._alc, this._slt, this._cap);
}
this._slt = slots;
this._cap = size;
}
# Spreads a hash, so that its low bits say where it begins in the slots and its
# high half tells it from others there, however the values hash, as integers
# hash as themselves.
def interner<T>::spread(code: u64): u64 {
var bits := (code ^ (code >> 31)) * 0xBF58476D1CE4E5B9u;
return bits ^ (bits >> 29);
}
+501
View File
@@ -0,0 +1,501 @@
#! @file list.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `list` container. Lists are a structured
#! container that stores each element in a node of its own, linked to the next.
module std::containers;
#! A `list` is a structured data container, singly linked, that stores each of
#! its elements in a node of its own.
#!
#! They are useful where elements are added and removed at the front, and where
#! an element must never move once it is added, since each keeps its own node
#! until it is removed. Reaching an element by index walks the list from the
#! front.
#!
#! It holds its first and last nodes, so pushing onto either end takes the same
#! time however long it is, but only the front is popped without walking.
#! @tparam T The type of its elements.
pub struct list<T>
: owning
, hashable
, indexable<u64, T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _hed: *mut list<T>::node;
var _tal: *mut list<T>::node;
var _len: u64;
}
#! An element of a list, with the node after it.
struct list<T>::node {
var value: T;
var next: *mut list<T>::node;
}
#! Walks the elements of a list from its front, giving a reference that reads
#! each in turn, which is what `iter(&this)` lends and `for x` and `for &x`
#! walk.
pub struct list<T>::cursor : sized_iterator<&T> {
var _at: *mut list<T>::node;
var _left: u64;
}
#! Gives the next element of the list.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def list<T>::cursor::next(&mut this): maybe<&T> {
if this._at == null {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &(*here).value;
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def list<T>::cursor::remaining(&this): u64 {
return this._left;
}
#! Walks the elements of a list from its front, giving a reference that writes
#! each in turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
pub struct list<T>::mut_cursor : sized_iterator<&mut T> {
var _at: *mut list<T>::node;
var _left: u64;
}
#! Gives the next element of the list, to be written.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def list<T>::mut_cursor::next(&mut this): maybe<&mut T> {
if this._at == null {
return nothing {};
}
val here := this._at;
this._at = (*here).next;
this._left = this._left - 1;
return &mut (*here).value;
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def list<T>::mut_cursor::remaining(&this): u64 {
return this._left;
}
#! Provides read only access to the length of a list.
#! @param this The list to get the length of.
#! @returns The length of the list.
pub val list<T>::length: u64 {
get => this._len;
}
#! Indicates if a list is empty.
#! @param this The list to check.
#! @returns Whether the list is empty.
pub val list<T>::is_empty: bool {
get => this._len == 0;
}
#! Creates a new list with no allocator.
#! @returns The created list container.
#! @remarks Will use the built in `raw_allocate` and `raw_release` for memory
#! management.
pub def list<T>::new(): list<T> {
return list::<T>::new(nothing{});
}
#! Creates a new list with an optional allocator.
#! @param alloc The optional allocator for the nodes of the list.
#! @returns The created list container, which holds no elements yet.
pub def list<T>::new(alloc: maybe<&mut allocator>): list<T> {
return list::<T> { _alc = alloc, _hed = null, _tal = null, _len = 0 };
}
#! Creates a copy of the provided list.
#! @param other The list to copy.
#! @returns The copy, which owns its own nodes and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def list<T>::copy_of(other: &list<T>): list<T> {
var made := list::<T>::new(other._alc);
var at := other._hed;
while at != null {
made.push_back(copy::<T>(&(*at).value));
at = (*at).next;
}
return made;
}
#! Creates a new list by moving the nodes of another list into it.
#! @param other The list to move elements from, which holds none after.
#! @returns The moved list, which takes the nodes and allocator with it.
#! @remarks Nothing is copied and no element is touched: the nodes move as they
#! stand, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def list<T>::move_of(other: &mut list<T>): list<T> {
val made: list<T> = list {
_alc = other._alc,
_hed = other._hed,
_tal = other._tal,
_len = other._len
};
other._hed = null;
other._tal = null;
other._len = 0;
return made;
}
#! Gets the element at the provided index, walking from the front.
#! @param this The list to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def list<T>::at(&this, index: u64): &T {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
return &(*this.node_at(index)).value;
}
#! Gets the element at the provided index, walking from the front.
#! @param this The list to get the element of.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @returns The element at the given index.
pub def list<T>::at(&mut this, index: u64): &mut T {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
return &mut (*this.node_at(index)).value;
}
#! Gets the element at an index, if the list holds one there, for an index
#! that may be past the end in a program that is right.
#! @param this The list to read.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def list<T>::get(&this, index: u64): maybe<&T> {
return nothing {} if index >= this._len;
return &(*this.node_at(index)).value;
}
#! Gets the element at an index to write it, if the list holds one there.
#! @param this The list to write.
#! @param index The index of the element.
#! @returns Maybe the element; otherwise, `nothing`.
pub def list<T>::get(&mut this, index: u64): maybe<&mut T> {
return nothing {} if index >= this._len;
return &mut (*this.node_at(index)).value;
}
#! Gets the element at the front of a list.
#! @param this The list to get the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def list<T>::front(&this): &T {
if const checking() {
if this._len == 0 {
fault("The list is empty.");
}
}
return &(*this._hed).value;
}
#! Gets the element at the front of a list.
#! @param this The list to get the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def list<T>::front(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The list is empty.");
}
}
return &mut (*this._hed).value;
}
#! Gets the element at the back of a list.
#! @param this The list to get the back of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def list<T>::back(&this): &T {
if const checking() {
if this._len == 0 {
fault("The list is empty.");
}
}
return &(*this._tal).value;
}
#! Gets the element at the back of a list.
#! @param this The list to get the back of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def list<T>::back(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The list is empty.");
}
}
return &mut (*this._tal).value;
}
#! Pushes a new element onto the front of a list.
#! @param this The list to push the value onto.
#! @param value The value to push onto the list.
#! @remarks An allocator that gives no more memory stops the program.
pub def list<T>::push_front(&mut this, value: T): void {
val made := this.make(move(value));
(*made).next = this._hed;
this._hed = made;
if this._tal == null {
this._tal = made;
}
this._len++;
}
#! Pushes a new element onto the back of a list.
#! @param this The list to push the value onto.
#! @param value The value to push onto the list.
#! @remarks An allocator that gives no more memory stops the program.
pub def list<T>::push_back(&mut this, value: T): void {
val made := this.make(move(value));
if this._tal == null {
this._hed = made;
} else {
(*this._tal).next = made;
}
this._tal = made;
this._len++;
}
#! Pops the element off the front of a list.
#! @param this The list to pop the value off of, which stops a checked program
#! where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def list<T>::pop_front(&mut this): void {
if const checking() {
if this._len == 0 {
fault("The list is empty.");
}
}
val gone := this._hed;
this._hed = (*gone).next;
if this._hed == null {
this._tal = null;
}
this.release(gone);
this._len--;
}
#! Adds an element at an index, after the elements before it.
#! @param this The list to insert into.
#! @param index Where the element goes, from `0` to `length`, where `length`
#! appends. An index past that stops a checked program.
#! @param value The element to insert.
#! @remarks An allocator that gives no more memory stops the program.
pub def list<T>::insert_at(&mut this, index: u64, value: T): void {
if const checking() {
if index > this._len {
past_end(index, this._len);
}
}
if index == 0 {
this.push_front(move(value));
return;
}
if index == this._len {
this.push_back(move(value));
return;
}
val made := this.make(move(value));
val prev := this.node_at(index - 1);
(*made).next = (*prev).next;
(*prev).next = made;
this._len++;
}
#! Removes the element at an index.
#! @param this The list to remove from.
#! @param index The index of the element, below `length`, past which a checked
#! program stops.
#! @remarks The element is closed where it closes, or holds what does.
pub def list<T>::remove_at(&mut this, index: u64): void {
if const checking() {
if index >= this._len {
past_end(index, this._len);
}
}
if index == 0 {
this.pop_front();
return;
}
this.unlink(this.node_at(index - 1));
}
#! Removes the first element equal to the one given.
#! @param this The list to remove from.
#! @param elem The element to look for.
#! @returns Whether an element equalled it and was removed.
#! @remarks The element is closed where it closes, or holds what does.
pub def list<T>::remove(&mut this, elem: &T): bool {
if this._len == 0 {
return false;
}
if equals::<T>(&(*this._hed).value, elem) {
this.pop_front();
return true;
}
var prev := this._hed;
while (*prev).next != null {
if equals::<T>(&(*(*prev).next).value, elem) {
this.unlink(prev);
return true;
}
prev = (*prev).next;
}
return false;
}
#! Tells whether the list holds an element equal to the one given.
#! @param this The list to search.
#! @param elem The element to look for.
#! @returns Whether any element equals it.
pub def list<T>::contains(&this, elem: &T): bool {
var at := this._hed;
while at != null {
return true if equals::<T>(&(*at).value, elem);
at = (*at).next;
}
return false;
}
#! Removes all elements from a list, disposing their nodes.
#! @param this The list to clear.
#! @remarks Elements that close, or hold what does, are closed.
pub def list<T>::clear(&mut this): void {
var at := this._hed;
while at != null {
val next := (*at).next;
this.release(at);
at = next;
}
this._hed = null;
this._tal = null;
this._len = 0;
}
#! Removes all elements of a list, disposing their nodes.
#! @param this The list to close.
pub def list<T>::close(&mut this): void {
this.clear();
}
#! Compares one list to another by equality.
#! @param this The list to compare against.
#! @param other The list to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def list<T>::equals(&this, other: &list<T>): bool {
if this._len != other._len {
return false;
}
var mine := this._hed;
var theirs := other._hed;
while mine != null {
return false if !equals::<T>(&(*mine).value, &(*theirs).value);
mine = (*mine).next;
theirs = (*theirs).next;
}
return true;
}
#! Lends a cursor that reads the elements from the front of the list, which
#! `for x in l` walks.
#! @param this The list to walk.
#! @returns The cursor, which is only good until the list changes or closes.
pub def list<T>::iter(&this): list<T>::cursor {
return list::<T>::cursor { _at = this._hed, _left = this._len };
}
#! Lends a cursor that writes the elements where they are, from the front of the
#! list, which `for &mut x in l` walks.
#! @param this The list to walk.
#! @returns The cursor, which is only good until the list changes or closes.
pub def list<T>::iter(&mut this): list<T>::mut_cursor {
return list::<T>::mut_cursor { _at = this._hed, _left = this._len };
}
#! Hashes the provided list.
#! @param this The list to hash.
#! @returns The hashed value of the list.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def list<T>::hash(&this): u64 {
var code := this._len;
var at := this._hed;
while at != null {
code = mix(code, hash::<T>(&(*at).value));
at = (*at).next;
}
return code;
}
# The node at an index, which is below the length.
def list<T>::node_at(&this, index: u64): *mut list<T>::node {
var at := this._hed;
for _ in 0..index {
at = (*at).next;
}
return at;
}
# A node holding the value, from the list's allocator, which stops the program
# where it gives no memory, as `acquire` does.
def list<T>::make(&mut this, value: T): *mut list<T>::node {
val made := acquire::<list<T>::node>(this._alc, 1);
(*made).value = move(value);
(*made).next = null;
return made;
}
def list<T>::unlink(&mut this, prev: *mut list<T>::node): void {
val gone := (*prev).next;
(*prev).next = (*gone).next;
if gone == this._tal {
this._tal = prev;
}
this.release(gone);
this._len--;
}
def list<T>::release(&mut this, node: *mut list<T>::node): void {
close(&mut (*node).value);
dispose::<list<T>::node>(this._alc, node, 1);
}
+400
View File
@@ -0,0 +1,400 @@
#! @file queue.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `queue` container. Queues are a structured
#! container where data is pushed onto the back and popped off the front, in a
#! first-in-first-out (FIFO) manner.
module std::containers;
#! A `queue` is a structured data container that stores its content in a first-
#! in-first-out (FIFO) manner.
#!
#! They are useful wherever work is handled in the order it arrives, such as
#! event loops, breadth-first searches, and buffers between a producer and a
#! consumer.
#!
#! Its elements live in one block used as a ring: the front is at `_hed`, and
#! each element after it is at the next index, wrapping to the start of the
#! block.
#! @tparam T The type of its elements.
pub struct queue<T>
: owning
, hashable
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _dat: *mut T;
var _hed: u64;
var _len: u64;
var _cap: u64;
}
#! Provides read only access to the length of a queue.
#! @param this The queue to get the length of.
#! @returns The length of the queue.
pub val queue<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a queue.
#! @param this The queue to get the capacity of.
#! @returns The capacity of the queue.
pub val queue<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a queue is empty.
#! @param this The queue to check.
#! @returns Whether the queue is empty.
pub val queue<T>::is_empty: bool {
get => this._len == 0;
}
#! Indicates if a queue is full.
#! @param this The queue to check.
#! @returns Whether the queue is full.
pub val queue<T>::is_full: bool {
get => this._len == this._cap;
}
#! Creates a new queue with no allocator and a default size.
#! @returns The created queue container.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def queue<T>::new(): queue<T> {
return queue::<T>::new(4, nothing{});
}
#! Creates a new queue with an optional allocator and a default size.
#! @param alloc The optional allocator for the memory backing of the queue.
#! @returns The created queue container.
pub def queue<T>::new(alloc: maybe<&mut allocator>): queue<T> {
return queue::<T>::new(4, alloc);
}
#! Creates a new queue with an optional allocator and a provided size.
#! @param size The initial capacity of the queue, which may be none.
#! @param alloc The optional allocator for the memory backing of the queue.
#! @returns The created queue container, which holds no elements yet.
pub def queue<T>::new(size: u64, alloc: maybe<&mut allocator>): queue<T> {
var made: queue<T> = queue {
_alc = alloc,
_dat = null,
_hed = 0,
_len = 0,
_cap = 0
};
made.reserve(size);
return made;
}
#! Creates a copy of the provided queue.
#! @param other The queue to copy.
#! @returns The copy, which owns its own memory and its own elements.
#! @remarks Each element is copied by `copyable` where it provides one, so an
#! element owning memory is copied rather than shared.
pub def queue<T>::copy_of(other: &queue<T>): queue<T> {
var made := queue::<T>::new(other._len, other._alc);
for index in 0..other._len {
made.push(copy::<T>(&other._dat[other.slot(index)]));
}
return made;
}
#! Creates a new queue by moving the data of another queue into it.
#! @param other The queue to move elements from, which holds none after.
#! @returns The moved queue, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no element is touched: the memory moves as it
#! stands, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def queue<T>::move_of(other: &mut queue<T>): queue<T> {
val made: queue<T> = queue {
_alc = other._alc,
_dat = other._dat,
_hed = other._hed,
_len = other._len,
_cap = other._cap
};
other._dat = null;
other._hed = 0;
other._len = 0;
other._cap = 0;
return made;
}
#! Pushes a new element onto the back of a queue.
#! @param this The queue to push the value onto.
#! @param value The value to push onto the queue.
#! @remarks An allocator that gives no more memory stops the program.
pub def queue<T>::push(&mut this, value: T): void {
if this.is_full {
this.grow();
}
this._dat[this.slot(this._len)] = move(value);
this._len++;
}
#! Pops the element off the front of a queue.
#! @param this The queue to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def queue<T>::pop(&mut this): void {
if const checking() {
if this._len == 0 {
fault("The queue is empty.");
}
}
this.release(this._hed);
this._hed = (this._hed + 1) % this._cap;
this._len--;
}
#! Peeks the element at the front of a queue without removing it.
#! @param this The queue to peek the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def queue<T>::peek(&this): &T {
if const checking() {
if this._len == 0 {
fault("The queue is empty.");
}
}
return &this._dat[this._hed];
}
#! Peeks the element at the front of a queue without removing it.
#! @param this The queue to peek the front of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def queue<T>::peek(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The queue is empty.");
}
}
return &mut this._dat[this._hed];
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the queue provided.
#! @param this The queue to reserve elements for.
#! @param count The number of elements to reserve for a queue.
pub def queue<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Removes all elements from a queue.
#! @param this The queue to clear.
#! @remarks Elements that close, or hold what does, are closed. The backing data
#! is kept but not disposed.
pub def queue<T>::clear(&mut this): void {
for index in 0..this._len {
this.release(this.slot(index));
}
this._hed = 0;
this._len = 0;
}
#! Removes all elements of a queue then disposes the backing memory.
#! @param this The queue to close.
pub def queue<T>::close(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[this.slot(index)]);
}
}
this._hed = 0;
this._len = 0;
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = null;
this._cap = 0;
}
#! Compares one queue to another by equality.
#! @param this The queue to compare against.
#! @param other The queue to compare with.
#! @returns Whether both hold equal elements, in the same order.
pub def queue<T>::equals(&this, other: &queue<T>): bool {
if this._len != other._len {
return false;
}
for index in 0..this._len {
return false if !equals::<T>(
&this._dat[this.slot(index)],
&other._dat[other.slot(index)]
);
}
return true;
}
#! Walks the elements of a queue from its front, giving a reference that reads
#! each in turn, which is what `iter(&this)` lends and `for x` and `for &x`
#! walk.
pub struct queue<T>::cursor : sized_iterator<&T>, backward_iterator<&T> {
var _dat: *mut T;
var _at: u64;
var _cap: u64;
var _left: u64;
}
#! Gives the next element of the queue.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def queue<T>::cursor::next(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (here + 1) % this._cap;
this._left = this._left - 1;
return &this._dat[here];
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def queue<T>::cursor::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the cursor has left, from the back of the queue.
#! @param this The cursor to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def queue<T>::cursor::next_back(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &this._dat[(this._at + this._left) % this._cap];
}
#! Walks the elements of a queue from its front, giving a reference that writes
#! each in turn, which is what `iter(&mut this)` lends and `for &mut x` walks.
pub struct queue<T>::mut_cursor : sized_iterator<&mut T>, backward_iterator<&mut T> {
var _dat: *mut T;
var _at: u64;
var _cap: u64;
var _left: u64;
}
#! Gives the next element of the queue, to be written.
#! @param this The cursor to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def queue<T>::mut_cursor::next(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = (here + 1) % this._cap;
this._left = this._left - 1;
return &mut this._dat[here];
}
#! How many elements the cursor has left to give.
#! @param this The cursor.
#! @returns How many.
pub def queue<T>::mut_cursor::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the cursor has left, from the back of the queue, to
#! be written.
#! @param this The cursor to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def queue<T>::mut_cursor::next_back(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &mut this._dat[(this._at + this._left) % this._cap];
}
#! Lends a cursor that reads the elements from the front of the queue, which
#! `for x in q` walks.
#! @param this The queue to walk.
#! @returns The cursor, which is only good until the queue changes or closes.
pub def queue<T>::iter(&this): queue<T>::cursor {
return queue::<T>::cursor { _dat = this._dat, _at = this._hed, _cap = this._cap, _left = this._len };
}
#! Lends a cursor that writes the elements where they are, from the front of the
#! queue, which `for &mut x in q` walks.
#! @param this The queue to walk.
#! @returns The cursor, which is only good until the queue changes or closes.
pub def queue<T>::iter(&mut this): queue<T>::mut_cursor {
return queue::<T>::mut_cursor { _dat = this._dat, _at = this._hed, _cap = this._cap, _left = this._len };
}
#! Hashes the provided queue.
#! @param this The queue to hash.
#! @returns The hashed value of the queue.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def queue<T>::hash(&this): u64 {
var code := this._len;
for index in 0..this._len {
code = mix(code, hash::<T>(&this._dat[this.slot(index)]));
}
return code;
}
def queue<T>::slot(&this, index: u64): u64 {
return (this._hed + index) % this._cap;
}
def queue<T>::release(&mut this, slot: u64): void {
close(&mut this._dat[slot]);
# The slot is emptied where writing over it would close what it held.
if const T is closeable {
memset((this._dat + slot) as *mut u8, 0, bytes_of::<T>(1));
}
}
# Gives the queue room for more elements, doubling it.
def queue<T>::grow(&mut this): void {
this.grow(
this._cap != 0
? this._cap * 2
: 4
);
}
# Gives the queue room for a number of elements, where it has less, with them
# from its first slot. An allocator that gives no memory stops the program, as
# `acquire` does.
def queue<T>::grow(&mut this, size: u64): void {
if size <= this._cap {
return;
}
val block := acquire::<T>(this._alc, size);
val first := this._cap - this._hed;
val lead := this._len < first ? this._len : first;
memcpy(block as *mut u8, (this._dat + this._hed) as *mut u8, bytes_of::<T>(lead));
memcpy((block + lead) as *mut u8, this._dat as *mut u8, bytes_of::<T>(this._len - lead));
if this._dat != null {
dispose::<T>(this._alc, this._dat, this._cap);
}
this._dat = block;
this._hed = 0;
this._cap = size;
}
+167
View File
@@ -0,0 +1,167 @@
#! @file rc.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `rc`, one value on the heap that every copy owns, counted plainly,
#! for values one thread shares, as Rust's `Rc`; and `rc_weak`, which refers to
#! it without keeping it. `arc` counts atomically, for values threads share.
#!
#! Each copy counts one more owner, and the last to close closes the value.
#! Counting plainly costs an add, where counting atomically costs a locked add:
#! fourteen times as long for a copy alone, and half again as long for a list
#! walked with a counted cursor, measured as `docs/performance.md` says.
module std::containers;
# Allocates a block a counted value is written into: zeroed where the value
# closes, since writing it closes what the block held, as `box` allocates.
def allocate_for<T>(size: u64): *mut u8 {
if const T is closeable {
return raw_allocate_zeroed(size);
}
return raw_allocate(size);
}
# What an `rc` points at: the counts, then the value. The weak count holds one
# for all the owners together, so the last owner to close and the last weak
# reference to close agree on which gives the memory back.
struct rc_cell<T> {
var owners: u64;
var weak: u64;
var value: T;
}
#! One value on the heap, owned by every copy, which `copy` makes, and closed
#! where the last copy closes. Copies count plainly, so threads never share
#! one; `arc` is for that.
#!
#! An `rc` is one word, the counted value's address, which is never null, so
#! `maybe<rc<T>>` is one word too. Moving one moves the address and leaves the
#! one moved from empty, closing nothing.
#! @tparam T What it holds.
pub struct rc<T> : owning, copyable, moveable {
var _at: &mut rc_cell<T>;
}
#! A reference to a value an `rc` owns that does not keep it: `lock` gives an
#! owner while any other is left.
#! @tparam T What it refers to.
pub struct rc_weak<T> : owning, copyable, moveable {
var _at: *mut rc_cell<T>;
}
#! Moves a value to the heap, with one owner.
#! @param value The value.
#! @returns Its first owner.
pub def rc<T>::new(value: T): rc<T> {
val at := allocate_for::<rc_cell<T>>(size_of::<rc_cell<T>>()) as *mut rc_cell<T>;
at[0] = rc_cell::<T> { owners = 1, weak = 1, value = move(&mut value) };
return rc::<T> { _at = through(at) };
}
#! Lends the value an `rc` owns.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def rc<T>::get(&this): &T {
return &this._at.value;
}
#! Lends the value an `rc` owns, to be changed, which every copy sees.
#! @param this The owner.
#! @returns The value, good while any owner is left.
pub def rc<T>::get(&mut this): &mut T {
return &mut this._at.value;
}
#! How many owners share the value.
#! @param this An owner.
#! @returns How many, this one among them.
pub def rc<T>::count(&this): u64 {
return this._at.owners;
}
#! A reference to the value that does not keep it.
#! @param this An owner.
#! @returns The reference.
pub def rc<T>::weak(&this): rc_weak<T> {
this._at.weak++;
return rc_weak::<T> { _at = this._at as *mut rc_cell<T> };
}
#! Makes another owner of the same value.
#! @param other An owner.
#! @returns The new owner.
pub def rc<T>::copy_of(other: &rc<T>): rc<T> {
other._at.owners++;
return rc::<T> { _at = other._at };
}
#! Moves an owner, leaving the one moved from empty.
#! @param other The owner to move from.
#! @returns The owner it was.
pub def rc<T>::move_of(other: &mut rc<T>): rc<T> {
val made := rc::<T> { _at = other._at };
(other as *mut u64)[0] = 0;
return made;
}
#! Closes an owner: the value too where it was the last, and the memory where no
#! weak reference is left either.
#! @param this The owner, which is empty after.
pub def rc<T>::close(&mut this): void {
val at := this._at as *mut rc_cell<T>;
return if at == null;
(this as *mut u64)[0] = 0;
at[0].owners--;
return if at[0].owners != 0;
close(&mut at[0].value);
rc_cell_let_go::<T>(at);
}
#! An owner of the value a weak reference refers to, where any is left.
#! @param this The weak reference.
#! @returns The new owner, or nothing where the last closed.
pub def rc_weak<T>::lock(&this): maybe<rc<T>> {
return nothing {} if this._at == null || this._at[0].owners == 0;
this._at[0].owners++;
return rc::<T> { _at = through(this._at) };
}
#! Makes another weak reference to the same value.
#! @param other A weak reference.
#! @returns The new one.
pub def rc_weak<T>::copy_of(other: &rc_weak<T>): rc_weak<T> {
if other._at != null {
other._at[0].weak++;
}
return rc_weak::<T> { _at = other._at };
}
#! Moves a weak reference, leaving the one moved from empty.
#! @param other The weak reference to move from.
#! @returns The weak reference it was.
pub def rc_weak<T>::move_of(other: &mut rc_weak<T>): rc_weak<T> {
val made := rc_weak::<T> { _at = other._at };
other._at = null;
return made;
}
#! Closes a weak reference, giving back the memory where it was the last
#! reference of any kind.
#! @param this The weak reference, which is empty after.
pub def rc_weak<T>::close(&mut this): void {
val at := this._at;
return if at == null;
this._at = null;
rc_cell_let_go::<T>(at);
}
# Lets go of the weak count's one, giving back the memory where it was the last.
def rc_cell_let_go<T>(at: *mut rc_cell<T>): void {
at[0].weak--;
if at[0].weak == 0 {
raw_release(at as *mut u8);
}
}
+209
View File
@@ -0,0 +1,209 @@
#! @file runs.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `runs` container. Runs hold many short lists,
#! each a run of elements one after another in one block, named by an ID.
module std::containers;
#! A `runs` holds many lists of elements, each a run of them one after another
#! in one block, which a `u32` ID names.
#!
#! They are useful wherever many short lists are made and kept, such as the
#! parts of each type, the parameters of each function, or the children of each
#! node, which a vector each would scatter over the heap.
#!
#! The elements of every run are held in one vector, in the order the runs were
#! made, and where each run begins in another. A run is made by adding a view of
#! its elements, or by pushing them one at a time and then ending it. Runs are
#! never changed, and none is removed but by `rewind` and `clear`, so an ID is
#! good for as long as its run is. ID 0 is the empty run, which every empty view
#! added is given.
#! @tparam T The type of the elements.
pub struct runs<T>
: owning
, copyable
, moveable
{
var _items: vector<T>;
var _start: vector<u64>;
}
#! Provides read only access to how many runs there are.
#! @param this The runs to count.
#! @returns The number of runs, the empty one included, which is one more than
#! the newest's ID.
pub val runs<T>::count: u64 {
get => this._start.length - 1;
}
#! Provides read only access to how many elements the runs hold together.
#! @param this The runs to count the elements of.
#! @returns The number of elements, those of a run still being pushed included.
pub val runs<T>::size: u64 {
get => this._items.length;
}
#! Creates new runs with no allocator, holding only the empty run.
#! @returns The created runs.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def runs<T>::new(): runs<T> {
return runs::<T>::new(nothing{});
}
#! Creates new runs with an optional allocator, holding only the empty run.
#! @param alloc The optional allocator for the memory backing of the runs.
#! @returns The created runs.
pub def runs<T>::new(alloc: maybe<&mut allocator>): runs<T> {
var made := runs::<T> { _items = vector::<T>::new(alloc), _start = vector::<u64>::new(alloc) };
made._start.resize(2);
return made;
}
#! Builds runs holding copies of another's, each with the same ID, with its
#! allocator.
#! @param other The runs to copy from.
#! @returns The copy, which owns its own memory and elements.
#! @remarks Elements are copied by `copyable` where they provide one.
pub def runs<T>::copy_of(other: &runs<T>): runs<T> {
return runs::<T> { _items = vector::<T>::copy_of(&other._items), _start = vector::<u64>::copy_of(&other._start) };
}
#! Creates new runs by moving the data of others into them.
#! @param other The runs to move from, which hold nothing after, not even the
#! empty run, until they are cleared.
#! @returns The moved runs, which take the memory and allocator with them.
pub def runs<T>::move_of(other: &mut runs<T>): runs<T> {
return runs::<T> { _items = move(&mut other._items), _start = move(&mut other._start) };
}
#! Adds a run of copies of elements.
#! @param this The runs to add to.
#! @param items The elements of the run, in order.
#! @returns The run's ID, or 0, the empty run's, where there are no elements.
#! @remarks Elements are copied as a vector's `extend` copies them. Elements
#! pushed and not yet ended begin the run. An allocator that gives no
#! more memory stops the program.
pub def runs<T>::add(&mut this, items: span<T>): u32 {
this._items.extend(items);
return this.end();
}
#! Adds an element to the run being made, which `end` ends.
#! @param this The runs to add to.
#! @param item The element, which follows those pushed before it.
pub def runs<T>::push(&mut this, item: T): void {
this._items.append(move(item));
}
#! Ends the run being made, of the elements pushed since the last run ended.
#! @param this The runs to end the run of.
#! @returns The run's ID, or 0, the empty run's, where none was pushed.
pub def runs<T>::end(&mut this): u32 {
val open := this._start.data[this._start.length - 1];
return 0 if this._items.length == open;
val id := this._start.length - 1;
this._start.append(this._items.length);
return id as u32;
}
#! How many elements a run holds.
#! @param this The runs.
#! @param id The run's ID, below `count`, past which a checked program
#! stops.
#! @returns The number of its elements.
pub def runs<T>::length(&this, id: u32): u64 {
if const checking() {
if id as u64 + 1 >= this._start.length {
past_end(id as u64, this._start.length - 1);
}
}
return this._start.data[id as u64 + 1] - this._start.data[id];
}
#! Reads an element of a run.
#! @param this The runs.
#! @param id The run's ID, below `count`, past which a checked program
#! stops.
#! @param index The element's place in the run, below its length, past which a
#! checked program stops.
#! @returns The element, which is only good until the runs grow or close.
pub def runs<T>::at(&this, id: u32, index: u64): &T {
if const checking() {
if id as u64 + 1 >= this._start.length {
past_end(id as u64, this._start.length - 1);
}
}
val start := this._start.data[id];
val length := this._start.data[id as u64 + 1] - start;
if const checking() {
if index >= length {
past_end(index, length);
}
}
return &this._items.data[start + index];
}
#! Lends a view of a run's elements.
#! @param this The runs.
#! @param id The run's ID, below `count`, past which a checked program
#! stops.
#! @returns The view, which is only good until the runs grow or close, so a loop
#! that adds runs while it walks one reads it by `at` instead.
pub def runs<T>::view(&this, id: u32): span<T> {
val next := id as u64 + 1;
if const checking() {
if next >= this._start.length {
past_end(id as u64, this._start.length - 1);
}
}
val start := this._start.data[id];
return span::<T>::over(this._items.data + start, this._start.data[next] - start);
}
#! Removes the runs from an ID on, so that the next run made is given it.
#! @param this The runs to remove from.
#! @param count How many runs to keep, from 1, which keeps only the empty one,
#! to `count`, which keeps them all.
#! @remarks Elements removed are closed where they close, or hold what does, and
#! so are those pushed and not yet ended.
pub def runs<T>::rewind(&mut this, count: u64): void {
if const checking() {
if count == 0 || count > this.count {
past_end(count, this.count + 1);
}
}
this._items.resize(this._start.data[count]);
this._start.resize(count + 1);
}
#! Removes every run but the empty one, keeping the memory.
#! @param this The runs to empty.
#! @remarks Elements are closed where they close, or hold what does.
pub def runs<T>::clear(&mut this): void {
this._items.clear();
this._start.clear();
this._start.resize(2);
}
#! Removes every run and gives back the memory the runs hold.
#! @param this The runs to close.
#! @remarks Elements are closed where they close, or hold what does. Closed runs
#! hold not even the empty run, until they are cleared.
pub def runs<T>::close(&mut this): void {
this._items.close();
this._start.close();
}
# Stops the program where an ID names no run.
def runs<T>::check(&this, id: u32): void {
if const checking() {
if id as u64 + 1 >= this._start.length {
past_end(id as u64, this._start.length - 1);
}
}
}
+338
View File
@@ -0,0 +1,338 @@
#! @file stack.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Defines an implementation for a `stack` container. Stacks are a structured
#! container where data is pushed and popped from the memory region in a last-
#! in-first-out (LIFO) manner.
module std::containers;
#! A `stack` is a structured data container that stores its content in a last-
#! in-first-out (LIFO) manner.
#!
#! They are useful in situations where data needs to be tracked in that exact
#! LIFO manner. Situations like that often include things like lexers, parsers,
#! GUI layers, etc.
#! @tparam T The type of its elements.
pub struct stack<T>
: owning
, hashable
, sliceable<T>
, viewable<T>
, iterable<T>
, copyable
, moveable
, equatable
{
var _alc: maybe<&mut allocator>;
var _dat: *mut T;
var _len: u64;
var _cap: u64;
}
#! Provides read only access to the length of a stack.
#! @param this The stack to get the length of.
#! @returns The length of the stack.
pub val stack<T>::length: u64 {
get => this._len;
}
#! Provides read only access to the capacity of a stack.
#! @param this The stack to get the capacity of.
#! @returns The capacity of the stack.
pub val stack<T>::capacity: u64 {
get => this._cap;
}
#! Indicates if a stack is empty.
#! @param this The stack to check.
#! @returns Whether the stack is empty.
pub val stack<T>::is_empty: bool {
get => this._len == 0;
}
#! Indicates if a stack is full.
#! @param this The stack to check.
#! @returns Whether the stack is full.
pub val stack<T>::is_full: bool {
get => this._len == this._cap;
}
#! Creates a new stack with no allocator, which takes memory once something is
#! added.
#! @returns The created stack container.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def stack<T>::new(): stack<T> {
return stack::<T>::new(nothing{});
}
#! Creates a new stack with an optional allocator, which takes memory once
#! something is added.
#! @param alloc The optional allocator for the memory backing of the stack.
#! @returns The created stack container.
pub def stack<T>::new(alloc: maybe<&mut allocator>): stack<T> {
return stack::<T> { _alc = alloc, _dat = null, _len = 0, _cap = 0 };
}
#! Creates a new stack with an optional allocator and a provided size.
#! @param size The initial capacity of the stack.
#! @param alloc The optional allocator for the memory backing of the stack.
#! @returns The created stack container.
pub def stack<T>::new(size: u64, alloc: maybe<&mut allocator>): stack<T> {
var made := stack::<T>::new(alloc);
made.reserve(size);
return made;
}
#! Creates a copy of the provided stack.
#! @param other The stack to copy.
#! @returns The created stack container.
pub def stack<T>::copy_of(other: &stack<T>): stack<T> {
var made := stack::<T>::new(other._len, other._alc);
for index in 0..other._len {
made.push(copy::<T>(&other._dat[index]));
}
return made;
}
#! Creates a new stack by moving the data of another stack into it.
#! @param other The stack to move elements from, which holds none after.
#! @returns The moved stack, which takes the memory and allocator with it.
#! @remarks Nothing is copied and no element is touched: the memory moves as it
#! stands, and the other is left empty rather than dead, so closing it
#! afterwards is harmless.
pub def stack<T>::move_of(other: &mut stack<T>): stack<T> {
val made: stack<T> = stack {
_alc = other._alc,
_dat = other._dat,
_len = other._len,
_cap = other._cap
};
other._dat = null;
other._len = 0;
other._cap = 0;
return made;
}
#! Creates a slice of the data of a stack container.
#! @param this The stack container to slice.
#! @returns A slice of the elements of the provided stack container.
pub def stack<T>::slice(&mut this): slice<T> {
return slice::<T>::over(this._dat, this._len);
}
#! Creates a view of the data of a stack container.
#! @param this The stack container to view.
#! @returns A span of the elements of the provided stack container.
pub def stack<T>::view(&this): span<T> {
return span::<T>::over(this._dat, this._len);
}
#! Pushes a new element onto a stack.
#! @param this The stack to push the value onto.
#! @param value The value to push onto a stack.
#! @remarks An allocator that gives no more memory stops the program.
pub def stack<T>::push(&mut this, value: T): void {
if this.is_full {
this.grow();
}
this._dat[this._len++] = move(value);
}
#! Pops an old value off of a stack.
#! @param this The stack to pop the value off of, which stops a checked
#! program where it is empty.
#! @remarks The value is closed where it closes, or holds what does.
pub def stack<T>::pop(&mut this): void {
if const checking() {
if this._len == 0 {
fault("The stack is empty.");
}
}
close(&mut this._dat[this._len - 1]);
# The slot is emptied where pushing would close what it held.
if const T is closeable {
memset((this._dat + (this._len - 1)) as *mut u8, 0, bytes_of::<T>(1));
}
this._len--;
}
#! Peeks the element on top of a stack without removing it.
#! @param this The stack to peek the top of, which stops a checked program
#! where it is empty.
#! @returns A reference to an immutable element.
pub def stack<T>::peek(&this): &T {
if const checking() {
if this._len == 0 {
fault("The stack is empty.");
}
}
return &this._dat[this._len - 1];
}
#! Peeks the element on top of a stack without removing it.
#! @param this The stack to peek the top of, which stops a checked program
#! where it is empty.
#! @returns A reference to a mutable element.
pub def stack<T>::peek(&mut this): &mut T {
if const checking() {
if this._len == 0 {
fault("The stack is empty.");
}
}
return &mut this._dat[this._len - 1];
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the stack provided.
#! @param this The stack to reserve elements for.
#! @param count The number of elements to reserve for a stack.
#! @remarks A stack with room for that many already is left as it is, so this
#! never shrinks it.
pub def stack<T>::reserve(&mut this, count: u64): void {
this.grow(count);
}
#! Reserves an amount of memory for the number of elements requested for the
#! backing memory of the stack provided, then makes those new elements
#! available.
#! @param this The stack to resize.
#! @param count The number of elements to resize a stack to.
#! @remarks New elements are zeroed. Elements past a smaller count are removed,
#! and closed where they close, or hold what does. An allocator that
#! gives no more memory stops the program.
pub def stack<T>::resize(&mut this, count: u64): void {
# Growing doubles at least, so resizing a little at a time copies little.
if count > this._cap {
this.grow(count > this._cap * 2 ? count : this._cap * 2);
}
if count < this._len {
if const T is closeable {
for index in count..this._len {
close(&mut this._dat[index]);
}
}
# The slots past the length are kept empty where pushing would close them.
if const T is closeable {
memset((this._dat + count) as *mut u8, 0, bytes_of::<T>(this._len - count));
}
}
else {
memset((this._dat + this._len) as *mut u8, 0, bytes_of::<T>(count - this._len));
}
this._len = count;
}
#! Removes all elements from a stack.
#! @param this The stack to clear.
#! @remarks Elements that close, or hold what does, are closed. Once all are
#! closed, the backing data will be cleared but not disposed.
pub def stack<T>::clear(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[index]);
}
}
if const T is closeable {
memset(this._dat as *mut u8, 0, bytes_of::<T>(this._len));
}
this._len = 0;
}
#! Removes all elements of a stack then disposes the backing memory.
#! @param this The stack to close.
pub def stack<T>::close(&mut this): void {
if const T is closeable {
for index in 0..this._len {
close(&mut this._dat[index]);
}
}
dispose::<T>(this._alc, this._dat, this._cap);
this._dat = null;
this._len = 0;
this._cap = 0;
}
#! Compares one stack to another by equality.
#! @param this The stack to compare against.
#! @param other The stack to compare with.
#! @returns Whether the stacks are equal by value.
pub def stack<T>::equals(&this, other: &stack<T>): bool {
if this._len != other._len {
return false;
}
for index in 0..this._len {
return false if !equals::<T>(
&this._dat[index],
&other._dat[index]
);
}
return true;
}
#! What `iter(&this)` lends, which reads the elements from the bottom of the
#! stack.
pub type stack<T>::cursor = span<T>::cursor;
#! What `iter(&mut this)` lends, which writes the elements where the stack holds
#! them.
pub type stack<T>::mut_cursor = slice<T>::mut_cursor;
#! Lends a cursor that reads the elements from the bottom of the stack to its
#! top, which `for x in s` walks.
#! @param this The stack to walk.
#! @returns The cursor, which is only good until the stack grows, shrinks, or
#! closes.
pub def stack<T>::iter(&this): span<T>::cursor {
return this.view().iter();
}
#! Lends a cursor that writes the elements where they are, from the bottom of
#! the stack to its top, which `for &mut x in s` walks.
#! @param this The stack to walk.
#! @returns The cursor, which is only good until the stack grows, shrinks, or
#! closes.
pub def stack<T>::iter(&mut this): slice<T>::mut_cursor {
var whole := this.slice();
return whole.iter();
}
#! Hashes the provided stack.
#! @param this The stack to hash.
#! @returns The hashed value of the stack.
#! @remarks Elements are hashed by their `hash`, so they are `hashable`.
pub def stack<T>::hash(&this): u64 {
var code := this._len;
for index in 0..this._len {
code = mix(code, hash(this._dat[index]));
}
return code;
}
# Gives the stack room for more elements, doubling it.
def stack<T>::grow(&mut this): void {
this.grow(this._cap == 0 ? 4 : this._cap * 2);
}
# Gives the stack room for a number of elements, where it has less. An allocator
# that gives no memory stops the program, as `acquire` and `resize` do.
def stack<T>::grow(&mut this, size: u64): void {
if size <= this._cap {
return;
}
this._dat = this._dat == null
? acquire::<T>(this._alc, size)
: resize::<T>(this._alc, this._dat, this._cap, size);
this._cap = size;
}
+284
View File
@@ -0,0 +1,284 @@
#! @file byte_writer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `byte_writer`, the stream that writes to memory: it lays out bytes
#! one after another, as a file or a block of machine code is laid out, and is
#! `writable`, so whatever writes a stream writes one.
import system;
module std::io;
#! A `byte_writer` holds bytes written one after another: integers least
#! significant byte first, as x86-64 stores them, views of bytes, zeros up to an
#! alignment, and words written over places already written, such as a length
#! known only once what it counts is written.
#!
#! They are useful wherever a binary format is made, such as an object file, a
#! table of debugging information, or machine code.
#! @remarks Integers are written as the processor stores them, so the bytes are
#! least significant first only where it is, as x86-64 is.
pub struct byte_writer
: owning
, moveable
, writable
{
var _dat: vector<u8>;
}
#! Provides read only access to how many bytes are written.
#! @param this The writer.
#! @returns The number of bytes, which is where the next one goes.
pub val byte_writer::length: u64 {
get => this._dat.length;
}
#! Creates a writer with no allocator, holding no bytes.
#! @returns The created writer.
#! @remarks Will use the built in `raw_allocate`, `raw_release` and `raw_resize`
#! for memory management.
pub def byte_writer::new(): byte_writer {
return byte_writer::new(nothing{});
}
#! Creates a writer with an optional allocator, holding no bytes.
#! @param alloc The optional allocator for the memory backing of the writer.
#! @returns The created writer.
pub def byte_writer::new(alloc: maybe<&mut allocator>): byte_writer {
return byte_writer { _dat = vector::<u8>::new(alloc) };
}
#! Creates a writer by moving the bytes of another into it.
#! @param other The writer to move from, which holds nothing after.
#! @returns The moved writer, which takes the memory and allocator with it.
pub def byte_writer::move_of(other: &mut byte_writer): byte_writer {
return byte_writer { _dat = move(&mut other._dat) };
}
#! Lends a view of the bytes written.
#! @param this The writer.
#! @returns The view, which is only good until the writer grows or closes.
pub def byte_writer::view(&this): span<u8> {
return this._dat.view();
}
#! Lends a view of the bytes written that writes them where they are.
#! @param this The writer.
#! @returns The view, which is only good until the writer grows or closes.
pub def byte_writer::slice(&mut this): slice<u8> {
return this._dat.slice();
}
#! Makes room for bytes after the last, giving where they begin, for the caller
#! to write.
#! @param this The writer.
#! @param count How many bytes.
#! @returns Where the first of them is, which is only good until the writer
#! grows or closes.
#! @remarks An allocator that gives no more memory stops the program.
pub def byte_writer::room(&mut this, count: u64): *mut u8 {
val at := this._dat.length;
this._dat.resize(at + count);
return this._dat.data + at;
}
#! Adds a byte.
#! @param this The writer.
#! @param value The byte.
pub def byte_writer::byte(&mut this, value: u8): void {
this._dat.append(value);
}
#! Adds a 16-bit word, least significant byte first.
#! @param this The writer.
#! @param value The word, of which the low 16 bits are written.
pub def byte_writer::u16(&mut this, value: u64): void {
*(this.room(2) as *mut u16) = value as u16;
}
#! Adds a 32-bit word, least significant byte first.
#! @param this The writer.
#! @param value The word, of which the low 32 bits are written.
pub def byte_writer::u32(&mut this, value: u64): void {
*(this.room(4) as *mut u32) = (value & 0xFFFFFFFF) as u32;
}
#! Adds a 64-bit word, least significant byte first.
#! @param this The writer.
#! @param value The word.
pub def byte_writer::u64(&mut this, value: u64): void {
*(this.room(8) as *mut u64) = value;
}
#! Adds bytes.
#! @param this The writer.
#! @param data The bytes.
pub def byte_writer::put(&mut this, data: span<u8>): void {
return if data.length == 0;
memcpy(this.room(data.length), data.data, data.length);
}
#! Writes bytes after the last, as a stream is written, so a byte writer is
#! given where anything `writable` is wanted.
#! @param this The writer.
#! @param data The bytes to write.
#! @returns Nothing, since a writer always takes them: an allocator that gives
#! no more memory stops the program.
pub def byte_writer::write(&mut this, data: span<u8>): result<void, io_error> {
this.put(data);
return;
}
#! Adds bytes, then a zero after them, as C ends its strings.
#! @param this The writer.
#! @param text The bytes, which hold no zero of their own where the result is
#! to be read as one string.
pub def byte_writer::put_terminated(&mut this, text: span<u8>): void {
this.put(text);
this._dat.append(0);
}
#! Adds zeros.
#! @param this The writer.
#! @param count How many.
pub def byte_writer::zeros(&mut this, count: u64): void {
this._dat.resize(this._dat.length + count);
}
#! Adds zeros until the length is a multiple of an alignment.
#! @param this The writer.
#! @param align The alignment, which is not zero.
#! @returns The length after, which is where what is aligned begins.
pub def byte_writer::align_to(&mut this, align: u64): u64 {
val over := this._dat.length % align;
if over != 0 {
this.zeros(align - over);
}
return this._dat.length;
}
#! Adds a 32-bit length that is not known yet, as zero, to be written by
#! `end_length` once what it counts is.
#! @param this The writer.
#! @returns Where the length is, which `end_length` is given.
pub def byte_writer::begin_length(&mut this): u64 {
val at := this._dat.length;
this.u32(0);
return at;
}
#! Writes a length `begin_length` began: how many bytes follow it.
#! @param this The writer.
#! @param at Where the length is, as `begin_length` gave it.
pub def byte_writer::end_length(&mut this, at: u64): void {
this.set_u32(at, this._dat.length - at - 4);
}
#! Writes a byte over the one at a place.
#! @param this The writer.
#! @param at The place, below the length, past which a checked program
#! stops.
#! @param value The byte.
pub def byte_writer::set_byte(&mut this, at: u64, value: u8): void {
this._dat[at] = value;
}
#! Writes a 16-bit word over the two bytes at a place.
#! @param this The writer.
#! @param at The place, whose bytes are written, or else a checked program
#! stops.
#! @param value The word, of which the low 16 bits are written.
pub def byte_writer::set_u16(&mut this, at: u64, value: u64): void {
*(this.place(at, 2) as *mut u16) = value as u16;
}
#! Writes a 32-bit word over the four bytes at a place.
#! @param this The writer.
#! @param at The place, whose bytes are written, or else a checked program
#! stops.
#! @param value The word, of which the low 32 bits are written.
pub def byte_writer::set_u32(&mut this, at: u64, value: u64): void {
*(this.place(at, 4) as *mut u32) = (value & 0xFFFFFFFF) as u32;
}
#! Writes a 64-bit word over the eight bytes at a place.
#! @param this The writer.
#! @param at The place, whose bytes are written, or else a checked program
#! stops.
#! @param value The word.
pub def byte_writer::set_u64(&mut this, at: u64, value: u64): void {
*(this.place(at, 8) as *mut u64) = value;
}
#! Reads the byte at a place.
#! @param this The writer.
#! @param at The place, below the length, past which a checked program
#! stops.
#! @returns The byte.
pub def byte_writer::get_byte(&this, at: u64): u8 {
return this._dat[at];
}
#! Reads the 32-bit word at a place.
#! @param this The writer.
#! @param at The place, whose bytes are written, or else a checked program
#! stops.
#! @returns The word.
pub def byte_writer::get_u32(&this, at: u64): u32 {
return *(this.place(at, 4) as *u32);
}
#! Reads the 64-bit word at a place.
#! @param this The writer.
#! @param at The place, whose bytes are written, or else a checked program
#! stops.
#! @returns The word.
pub def byte_writer::get_u64(&this, at: u64): u64 {
return *(this.place(at, 8) as *u64);
}
#! Removes the bytes from a place on, so that what is written next goes there,
#! as code made again shorter is.
#! @param this The writer.
#! @param length How many bytes to keep, no more than the length, or else a
#! checked program stops.
#! @remarks The memory is kept for the bytes written after.
pub def byte_writer::rewind(&mut this, length: u64): void {
if const checking() {
if length > this._dat.length {
past_end(length, this._dat.length);
}
}
this._dat.resize(length);
}
#! Removes every byte, keeping the memory.
#! @param this The writer to empty.
pub def byte_writer::clear(&mut this): void {
this._dat.clear();
}
#! Removes every byte and gives back the memory the writer holds.
#! @param this The writer to close.
pub def byte_writer::close(&mut this): void {
this._dat.close();
}
# Where bytes written before begin, stopping the program where they reach past
# the length, as indexing them one at a time would.
def byte_writer::place(&this, at: u64, size: u64): *mut u8 {
if const checking() {
if at + size > this._dat.length {
past_end(at + size - 1, this._dat.length);
}
}
return this._dat.data + at;
}
# Stops the program where a writer is asked for bytes past its end, as indexing
# a view outside its length does. It's called only where the check fails, so
# that where the check holds, it costs a compare.
def past_end(index: u64, length: u64): void {
fault($"Index {index} is out of bounds: the length is {length}.");
}
+165
View File
@@ -0,0 +1,165 @@
#! @file console.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `console`, the standard input, output, and error the program was
#! given, and `print` and `println`, which write text to the standard output.
import system;
module std::io;
# `std::io` is written once, for every system, over `system`, which is the only
# layer that knows which system it runs on. It takes and gives `path`s, keeps what
# is open in values that close themselves, and reports what fails as an
# `io_error`, inside a `result`.
#! One of the standard streams the program was given, its input, output, or
#! error, which it reads or writes but does not own, so nothing closes it.
#!
#! The reader `input()` lends, and the writers `output()` and `error_output()`
#! lend, are over one each, so closing one of them closes nothing of the
#! console, and the next call lends it again. Only `std::io` makes one.
pub struct console : readable, writable {
var _handle: system::fd;
}
#! Reads what has arrived on the console's handle, waiting only where nothing
#! has.
#! @param this The console to read.
#! @param into Where the bytes read are written.
#! @returns How many bytes were read, which is zero only at the end of the
#! input.
pub def console::read(&mut this, into: slice<u8>): result<u64, io_error> {
val count := this._handle.read(into.data, into.length);
if count < 0 {
return system::error_of(count);
}
return count as u64;
}
#! Writes all of some bytes to the console's handle, at once.
#! @param this The console to write.
#! @param data The bytes to write.
#! @returns Why they could not all be written, where they could not.
pub def console::write(&mut this, data: span<u8>): result<void, io_error> {
return write_all(this._handle, data);
}
#! Writes text to the standard output, through `output()`, and flushes it, so
#! the text and anything given to `output()` before it are written when this
#! returns.
#! @param text The text to write, which may be a literal, a view of one, or
#! the text a `string` owns, since a string lends a view of
#! itself.
pub def print(text: strview): void {
hold_console(&mut output_held);
val out := &mut output();
_ = out.write(text);
_ = out.flush();
let_go_console(&mut output_held);
}
#! Writes text and a new line to the standard output, through `output()`, which
#! writes them both once the line ends.
#! @param text The text to write.
pub def println(text: strview): void {
hold_console(&mut output_held);
val out := &mut output();
_ = out.write(text);
_ = out.write("\n");
let_go_console(&mut output_held);
}
#! Holds the standard output for the thread calling, so what it writes there
#! through the guard, line after line, mixes with no other thread's, as `print`
#! and `println` hold it for each call. Another thread printing waits until the
#! guard closes; this one writes through the guard, not `print` or `println`,
#! while it holds it.
#! @returns The guard, lending the writer `output()` lends.
pub def output_locked(): console_guard {
hold_console(&mut output_held);
return console_guard { _word = (&mut output_held) as *mut atomic<u32> };
}
#! Holds the standard error for the thread calling, as `output_locked` holds
#! the standard output.
#! @returns The guard, lending the writer `error_output()` lends.
pub def error_output_locked(): console_guard {
hold_console(&mut error_held);
return console_guard { _word = (&mut error_held) as *mut atomic<u32>, _error = true };
}
#! Holds the standard output or error for one thread, and lets go of it where it
#! closes.
@nodiscard
pub struct console_guard : owning {
var _word: *mut atomic<u32>;
var _error: bool = false;
}
#! The writer held.
#! @param this The guard.
#! @returns The writer.
pub def console_guard::writer(&mut this): &mut writer<console> {
return this._error ? error_output() : output();
}
#! Lets go of what the guard holds.
#! @param this The guard, which holds nothing after.
pub def console_guard::close(&mut this): void {
if this._word != null {
if this._error {
_ = error_output().flush();
}
let_go_console(&mut this._word[0]);
this._word = null;
}
}
# The locks of the standard output, error, and input, each taken for a call
# writing or reading it, so lines two threads write never mix: 0 where no thread
# holds it, 1 where one does, and 2 where others may wait.
var output_held: atomic<u32>;
var error_held: atomic<u32>;
var input_held: atomic<u32>;
def hold_console(word: &mut atomic<u32>): void {
if word.exchange(1) != 0 {
while word.exchange(2) != 0 {
_ = system::futex_wait((word as *mut atomic<u32>) as *mut u32, 2, -1);
}
}
}
def let_go_console(word: &mut atomic<u32>): void {
if word.exchange(0) == 2 {
_ = system::futex_wake((word as *mut atomic<u32>) as *mut u32, 1);
}
}
# Writes every byte of the data to a handle, giving the failure that stopped it,
# where one did.
def write_all(handle: system::fd, data: span<u8>): result<void, io_error> {
var total := 0u;
while total < data.length {
val count := handle.write(data.data + total, data.length - total);
if count < 0 {
return system::error_of(count);
}
if count == 0 {
return io_error::other;
}
total += count as u64;
}
return;
}
# What an operation of `system` that gives only whether it failed gave.
def outcome(code: i64): result<void, io_error> {
if code < 0 {
return system::error_of(code);
}
return;
}
+207
View File
@@ -0,0 +1,207 @@
#! @file directories.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `directory`, a directory being read one name at a time,
#! `list_directory`, which reads every name at once, what makes directories, and
#! the working directory: finding it, changing it, and making a path absolute
#! against it.
import system;
module std::io;
#! A directory being read, one name at a time, which is closed where its scope
#! ends.
#!
#! `for entry in listing` walks the names it holds, in no particular order,
#! leaving out `.` and `..`. Each entry's name is only good until the next is
#! read, so a name to keep is copied, or joined onto the directory's path.
#! Reading that fails partway stops the walk early, and `error` says why.
pub struct directory : owning, moveable {
var _stream: system::dir_stream;
var _error: maybe<io_error>;
}
#! A name a directory holds, as `directory::next` gives it.
pub struct directory::entry {
pub var name: strview; #! Only good until the next entry is read, or the directory closes.
pub var kind: file_kind; #! What the name is itself, so a link is a `link` wherever it leads.
}
#! Why reading the directory stopped before its end, where it did.
#! @param this The directory to ask.
#! @returns The failure, or `nothing` where none has happened.
pub val directory::error: maybe<io_error> {
get => this._error;
}
#! Opens a directory to read the names it holds.
#! @param at The path of the directory.
#! @returns The open directory, or why it could not be opened.
pub def directory::open(at: &path): result<directory, io_error> {
var made: directory;
val status := system::opendir(at.view(), &mut made._stream);
if status < 0 {
return system::error_of(status);
}
return move(made);
}
#! Reads the next name the directory holds.
#! @param this The directory to read.
#! @returns The next entry, or `nothing` once there are no more, or reading
#! failed.
pub def directory::next(&mut this): maybe<directory::entry> {
var found: system::dir_entry;
val status := this._stream.next(&mut found);
if status < 0 {
this._error = system::error_of(status);
return nothing{};
}
if status == 0 {
return nothing{};
}
return directory::entry { name = found.name, kind = found.kind };
}
#! Creates a directory by taking another's place in reading, which leaves the
#! other closed.
#! @param other The directory to move from.
#! @returns The directory, which closes where its scope ends.
pub def directory::move_of(other: &mut directory): directory {
return directory { _stream = move(other._stream), _error = other._error };
}
#! Stops reading the directory. Closing one that is not open does nothing.
#! @param this The directory to close.
pub def directory::close(&mut this): void {
this._stream.close();
}
#! Gives the path of everything a directory holds.
#! @param at The path of the directory.
#! @param alloc The optional allocator for the paths and the list of them.
#! @returns The path of each name the directory holds, joined onto `at`, in no
#! particular order, or why the directory could not be read. A name no
#! path can hold, as one with `\` on Linux, fails with
#! `io_error::invalid`; a `directory` gives every name as it is.
pub def list_directory(
at: &path,
alloc: maybe<&mut allocator> = nothing{}
): result<vector<path>, io_error> {
var listing := directory::open(at) else (e) { return e; };
var found := vector::<path>::new(alloc);
while listing.next() is some(each) {
var parsed := path::parse(each.name, alloc);
if parsed is not value(&name) {
return io_error::invalid;
}
found.append(at.joined(name, alloc));
}
if listing.error is some(why) {
return why;
}
return move(found);
}
#! Makes a directory.
#! @param at The path of the directory, whose parent must already exist.
#! @param mode The permissions to give it, less what the system's mask takes
#! away.
#! @returns Why it could not be made, where it could not.
pub def create_directory(
at: &path,
mode: permissions = permissions::default_directory
): result<void, io_error> {
return outcome(system::mkdir(at.view(), mode));
}
#! Makes a directory, and every directory above it that is missing.
#! @param at The path of the directory.
#! @param mode The permissions to give each directory made, less the mask.
#! @returns Why they could not be made, where they could not. A directory that
#! already exists is not a failure, but anything else at the path is.
pub def create_directories(
at: &path,
mode: permissions = permissions::default_directory
): result<void, io_error> {
val made := system::mkdir(at.view(), mode);
if made == 0 {
return;
}
val why := system::error_of(made);
if why != io_error::not_found {
return directory_at(at, why);
}
# A directory above it is missing too, so those are made first.
var above := at.parent();
if above is not some(&parent) {
return why;
}
create_directories(parent, mode) else (e) { return e; };
val again := system::mkdir(at.view(), mode);
if again == 0 {
return;
}
return directory_at(at, system::error_of(again));
}
#! Gives the working directory, which relative paths are taken from.
#! @param alloc The optional allocator for the path.
#! @returns The absolute path of the working directory, or why it could not be
#! found.
pub def working_directory(alloc: maybe<&mut allocator> = nothing{}): result<path, io_error> {
var text: u8[system::path_limit];
val length := system::getcwd((&mut text) as *mut u8, system::path_limit);
if length < 0 {
return system::error_of(length);
}
var parsed := path::parse(strview::over((&text) as *u8, length as u64), alloc);
if parsed is not value(&mut found) {
return io_error::invalid;
}
return move(found);
}
#! Sets the working directory, which relative paths are taken from.
#! @param at The path of the directory.
#! @returns Why it could not be set, where it could not.
pub def set_working_directory(at: &path): result<void, io_error> {
return outcome(system::chdir(at.view()));
}
#! Makes a path absolute, resolving it against the working directory.
#! @param at The path to make absolute.
#! @returns The path resolved as `path::resolve` does, from its text, with the
#! working directory as the base where it is relative, or why the
#! working directory could not be found.
pub def absolute(at: &path): result<path, io_error> {
if at.is_absolute {
return at.resolve(at);
}
val here := working_directory(at._text.alloc) else (e) { return e; };
return at.resolve(here);
}
# Whether a failure to make a directory leaves one there anyway, as when it was
# already there. Succeeds where a directory is at the path, and gives the failure
# otherwise.
def directory_at(at: &path, why: io_error): result<void, io_error> {
if why != io_error::already_exists {
return why;
}
val found := info(at) else { return why; };
if found.kind != file_kind::directory {
return why;
}
return;
}
+190
View File
@@ -0,0 +1,190 @@
#! @file file.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `file`, a file the program has open, which reads, writes, and seeks,
#! and closes where its scope ends.
import system;
module std::io;
#! A file the program has open, which it reads and writes through, and which is
#! closed where its scope ends.
#!
#! A file is opened by `file::open` or `file::create`, which give why where they
#! cannot. It cannot be copied, since only one value may close it, but it can be
#! moved. Its zero value is not open, and using one that is not open fails with
#! `io_error::invalid`.
pub struct file : owning, moveable, readable, writable, seekable {
var _handle: system::fd;
var _open: bool;
}
#! The system's handle of the file, for what `system` does that a file does
#! not.
#! @param this The file to read the handle of.
#! @returns The handle, which is only good while the file is open.
pub val file::handle: system::fd {
get => this._handle;
}
#! Whether the file is open.
#! @param this The file to check.
#! @returns Whether it was opened, and has not been closed or moved from.
pub val file::is_open: bool {
get => this._open;
}
#! Opens the file at a path.
#! @param at The path of the file to open.
#! @param flags How to open it, which is for reading unless they say
#! otherwise.
#! @param mode The permissions a file made by `open_flags::create` is given,
#! less what the system's mask takes away.
#! @returns The open file, or why it could not be opened.
pub def file::open(
at: &path,
flags: open_flags = open_flags::read,
mode: permissions = permissions::default_file
): result<file, io_error> {
val handle := system::open(at.view(), flags, mode);
if handle < 0 {
return system::error_of(handle);
}
return file { _handle = handle, _open = true };
}
#! Opens the file at a path for writing, emptied, making it where there is none.
#! @param at The path of the file to write.
#! @param mode The permissions a file this makes is given, less the mask.
#! @returns The open file, or why it could not be opened.
pub def file::create(at: &path, mode: permissions = permissions::default_file): result<file, io_error> {
return file::open(at, open_flags::write | open_flags::create | open_flags::truncate, mode);
}
#! Creates a file by taking another's handle, which leaves the other not open.
#! @param other The file to move from.
#! @returns The file, which closes the handle where its scope ends.
pub def file::move_of(other: &mut file): file {
val made: file = file { _handle = other._handle, _open = other._open };
other._open = false;
return made;
}
#! Closes the file. Closing a file that is not open does nothing.
#! @param this The file to close.
pub def file::close(&mut this): void {
if !this._open {
return;
}
this._handle.close();
this._open = false;
}
#! Reads from the file, where its position is, and moves the position past what
#! was read.
#! @param this The file to read.
#! @param into Where the bytes read are written.
#! @returns How many bytes were read, which may be fewer than there is room for,
#! and is zero only at the end of the file.
pub def file::read(&mut this, into: slice<u8>): result<u64, io_error> {
if !this._open {
return io_error::invalid;
}
val count := this._handle.read(into.data, into.length);
if count < 0 {
return system::error_of(count);
}
return count as u64;
}
#! Reads the rest of the file, from its position to its end.
#! @param this The file to read.
#! @param alloc The optional allocator for the text to be held in.
#! @returns The bytes read, or why they could not be.
pub def file::read_all(&mut this, alloc: maybe<&mut allocator> = nothing{}): result<string, io_error> {
if !this._open {
return io_error::invalid;
}
# What the system says the file holds is only a hint, so the text grows to hold
# whatever is actually read.
var made := string::new(alloc);
var info: file_info;
if this._handle.stat(&mut info) == 0 {
made.reserve(info.size);
}
var chunk: u8[4096];
while true {
val count := this._handle.read((&mut chunk) as *mut u8, 4096);
if count < 0 {
return system::error_of(count);
}
if count == 0 {
break;
}
made.append(span::<u8>::over((&chunk) as *u8, count as u64));
}
return move(made);
}
#! Writes all of some bytes to the file, where its position is, and moves the
#! position past them.
#! @param this The file to write.
#! @param data The bytes to write.
#! @returns Why they could not all be written, where they could not.
pub def file::write(&mut this, data: span<u8>): result<void, io_error> {
if !this._open {
return io_error::invalid;
}
return write_all(this._handle, data);
}
#! Moves the position in the file that reads and writes happen at.
#! @param this The file to seek in.
#! @param offset The offset to move to.
#! @param from Where the offset is measured from.
#! @returns The new position, from the start of the file.
pub def file::seek(&mut this, offset: i64, from: whence = whence::start): result<u64, io_error> {
if !this._open {
return io_error::invalid;
}
val position := this._handle.seek(offset, from);
if position < 0 {
return system::error_of(position);
}
return position as u64;
}
#! Describes the file.
#! @param this The file to describe.
#! @returns What is known of it, or why it could not be described.
pub def file::info(&this): result<file_info, io_error> {
if !this._open {
return io_error::invalid;
}
var out: file_info;
val status := this._handle.stat(&mut out);
if status < 0 {
return system::error_of(status);
}
return out;
}
#! Sets who may do what with the file.
#! @param this The file whose permissions to set.
#! @param mode The permissions to give it.
#! @returns Why they could not be set, where they could not.
pub def file::set_permissions(&mut this, mode: permissions): result<void, io_error> {
if !this._open {
return io_error::invalid;
}
return outcome(this._handle.chmod(mode));
}
+81
View File
@@ -0,0 +1,81 @@
#! @file files.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what is done to a file by its path, without holding it open: reading
#! or writing the whole of it, describing it, whether anything is there,
#! removing and renaming it, and changing who may use it.
import system;
module std::io;
#! Reads the whole of a file.
#! @param at The path of the file to read.
#! @param alloc The optional allocator for the text to be held in.
#! @returns The contents of the file, or why it could not be read.
pub def read_file(at: &path, alloc: maybe<&mut allocator> = nothing{}): result<string, io_error> {
var opened := file::open(at) else (e) { return e; };
return opened.read_all(alloc);
}
#! Replaces the contents of a file, making it where there is none.
#! @param at The path of the file to write.
#! @param data The bytes to write.
#! @returns Why they could not all be written, where they could not.
pub def write_file(at: &path, data: span<u8>): result<void, io_error> {
var opened := file::create(at) else (e) { return e; };
return opened.write(data);
}
#! Describes the file at a path.
#! @param at The path of the file to describe.
#! @param follow Whether a link the path ends in is followed to what it leads
#! to, rather than described itself.
#! @returns What is known of the file, or why it could not be described.
pub def info(at: &path, follow: bool = true): result<file_info, io_error> {
var out: file_info;
val status := follow
? system::stat(at.view(), &mut out)
: system::lstat(at.view(), &mut out);
if status < 0 {
return system::error_of(status);
}
return out;
}
#! Tells whether anything is at a path, following a link the path ends in.
#! @param at The path to look at.
#! @returns Whether the file it names could be described.
pub def exists(at: &path): bool {
return info(at) is value;
}
#! Removes the file, link, or empty directory at a path. A link is removed
#! itself, not what it leads to.
#! @param at The path of what to remove.
#! @returns Why it could not be removed, where it could not.
pub def remove(at: &path): result<void, io_error> {
val found := info(at, false) else (e) { return e; };
if found.kind == file_kind::directory {
return outcome(system::rmdir(at.view()));
}
return outcome(system::unlink(at.view()));
}
#! Moves a file or directory to another path, replacing a file already there.
#! @param from The path of what to move.
#! @param to Where to move it, on the same device.
#! @returns Why it could not be moved, where it could not.
pub def rename(from: &path, to: &path): result<void, io_error> {
return outcome(system::rename(from.view(), to.view()));
}
#! Sets who may do what with the file at a path.
#! @param at The path of the file.
#! @param mode The permissions to give it.
#! @returns Why they could not be set, where they could not.
pub def set_permissions(at: &path, mode: permissions): result<void, io_error> {
return outcome(system::chmod(at.view(), mode));
}
+20
View File
@@ -0,0 +1,20 @@
#! @file flushable.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the flushable trait, which a stream holding bytes back implements.
import system;
module std::io;
#! A stream that holds back what it is given, and passes it on when flushed.
#!
#! Only what holds bytes back is flushable: a string, or a file, passes on what
#! it is given at once, and has nothing to flush.
pub trait flushable {
#! Passes on everything held.
#! @param this The stream to flush.
#! @returns Why it could not all be passed on, where it could not.
def flush(&mut this): result<void, io_error>;
}
+55
View File
@@ -0,0 +1,55 @@
# std::io::glob
`std::io::glob` reads globs, paths written with wildcards as
`src/**/*.sakura`, and matches paths against them or finds the files they name.
`*` matches any run of characters within a name, `?` any one, `[abc]` and
`[a-z]` one of a set, `[!abc]` one not in it, `**` as a whole name any number of
whole names, and `{a,b}` either. `\` takes away what the next character means.
`/` separates names on every system, Windows included, and a name starting with
`.` is matched only by one written so, unless the options say otherwise. Cases
are told apart on Linux and folded elsewhere, unless the options say otherwise.
`pattern::find` walks no further than a glob's names need, never follows a link
`**` would descend, and gives what it finds in the order of their bytes, as a
shell does. blossom expands a target's `srcs` with it.
It's a module within `std::io`, whose paths it matches, so the library `std.io`
holds it, and it sees `std::io`'s names without importing it.
## Using it
Require the standard library in your blossomfile, and name `std.io`, the library
holding it, among a target's `deps`:
```yaml
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
targets:
- name: app
type: program
deps: [std.io]
```
```sakura
import std::io;
import std::io::glob;
def main(): void {
val sources := glob::pattern::parse("src/**/*.sakura") else (_) { return; };
val root := path::parse(".") else (_) { return; };
val found := sources.find(&root) else (_) { return; };
for &each in found {
io::println(each.view());
}
}
```
## Testing
From the standard library's root, `blossom test --only std.io` runs them with the
rest of `std::io`'s, or:
```sh
sakurac run --lib std=. tests/main.sakura tests/io/*.sakura tests/io/glob/*.sakura
```
+161
View File
@@ -0,0 +1,161 @@
#! @file find.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `pattern::find`, which walks the file system for the paths a glob
#! matches, and `search_error`, which says why it stopped.
import system;
module std::io::glob;
#! Why a search stopped: a directory it had to read couldn't be.
pub struct search_error {
pub var why: io_error; #! What the system said.
pub var at: path; #! The directory.
}
#! Describes why the search stopped.
#! @param this The error.
#! @returns A sentence naming the directory and what the system said.
pub def search_error::describe(&this): string {
return $"`{this.at.view()}` could not be read: {this.why}";
}
#! Finds every path the glob matches, walking from a directory.
#!
#! A name written as it is, as `src` in `src/*.sakura`, is joined on rather
#! than looked for, so whether it matches another case is the file system's,
#! and only the directories a wildcard is matched in are read. `**` reads every
#! directory below where it starts, but those reached through a link, so a link
#! never leads it around in a circle. A file only reached through a link is
#! found by naming the link, as `*` or as written.
#! @param this The pattern.
#! @param from The directory a glob without a root starts from, as `.`.
#! @returns Each path that exists and whose text the pattern `matches`, joined
#! onto `from` where the glob has no root, in order by their bytes, as
#! `sort` orders them where its locale is `C`, each once, or why a directory couldn't be read. A directory that
#! isn't there, or a name that isn't a directory, is passed over, as
#! is a link leading around in a circle, and a name no `path` can
#! hold, as one with `\` on Linux.
pub def pattern::find(&this, from: &path): result<vector<path>, search_error> {
var found := vector::<path>::new();
for c in 0..this._choices.length {
val each := this._choices[c];
var root := path::parse(each.rooted == 0 ? "." : this._bytes.substr(each.root, each.rooted)) else (_) { continue; };
var walked := this.walk(&each, each.rooted == 0 ? from : &root, each.start, 0, &mut found);
if walked is error(&mut why) {
return move(why);
}
}
found.sort_by(before);
var kept := vector::<path>::new();
for k in 0..found.length {
continue if kept.length != 0 && kept.last().equals(&found[k]);
kept.append(move(found[k]));
}
return move(kept);
}
# Adds each path that the segments of a choice from one on match, below a
# directory a number of names were matched to reach.
def pattern::walk(
&this,
each: &choice,
dir: &path,
s: u64,
depth: u64,
found: &mut vector<path>
): result<void, search_error> {
val end := each.start + each.length;
if s == end {
# A choice of no names but a root, or `.`, matches where it starts, and
# `**` alone doesn't.
if (depth != 0 || each.length == 0) && is_there(dir, each.directories) {
found.append(path::copy_of(dir));
}
return;
}
val seg := this._segments[s];
val last := s + 1 == end;
if seg.kind == segment_kind::literal {
# A name no path can hold, as one with `\` on Linux, names nothing.
var name := path::parse(this._bytes.substr(seg.start, seg.length)) else (_) { return; };
var next := dir.join(&name);
if last {
if is_there(&next, each.directories) {
found.append(move(next));
}
return;
}
return this.walk(each, &next, s + 1, depth + 1, found);
}
if seg.kind == segment_kind::deep {
var walked := this.walk(each, dir, s + 1, depth, found);
return move(walked) if walked is error;
}
var listing := io::directory::open(dir) else (why) { return passed(why, dir); };
while listing.next() is some(entry) {
continue if !this.fits_name(&seg, entry.name);
var name := path::parse(entry.name) else (_) { continue; };
var next := dir.join(&name);
val kind := entry.kind;
# `**` takes in a directory, and ends with anything else where it's last.
if seg.kind == segment_kind::deep {
if kind == file_kind::directory {
var walked := this.walk(each, &next, s, depth + 1, found);
return move(walked) if walked is error;
} else if last && (!each.directories || is_there(&next, true)) {
found.append(move(next));
}
continue;
}
if last {
if !each.directories || kind == file_kind::directory || (kind == file_kind::link && is_there(&next, true)) {
found.append(move(next));
}
} else if kind == file_kind::directory || kind == file_kind::link {
var walked := this.walk(each, &next, s + 1, depth + 1, found);
return move(walked) if walked is error;
}
}
if listing.error is some(why) {
return passed(why, dir);
}
return;
}
# Whether anything is at a path, a link included wherever it leads, or where
# only directories are asked for, whether a directory is, through any links.
def is_there(at: &path, directories: bool): bool {
if directories {
return match io::info(at) {
value(&found) => found.kind == file_kind::directory,
error(_) => false,
};
}
return io::info(at, false) is value;
}
# Passes over a directory that couldn't be read because it isn't one, or isn't
# there, or a link leads around in a circle, and stops the search otherwise.
def passed(why: io_error, at: &path): result<void, search_error> {
if why == io_error::not_found || why == io_error::not_a_directory || why == io_error::link_loop {
return;
}
return search_error { why = why, at = path::copy_of(at) };
}
# Whether a path comes before another, by their bytes, as `a`, `a-b`, `a/b`,
# which keeps a directory's paths together, and orders them as a shell's `*`
# and `sort` do.
def before(a: &path, b: &path): bool {
return a.view().compare(b.view()) < 0;
}
+132
View File
@@ -0,0 +1,132 @@
#! @file glob.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what a glob is read with, the mistakes a glob's text can hold, and
#! `escape`, which makes text a glob matching only itself.
#!
#! A glob is a path written with wildcards, as `src/**/*.sakura`, which
#! `pattern::parse` reads and `pattern::matches` and `pattern::find` match:
#!
#! - `*` matches any run of characters within a name, or none;
#! - `?` matches any one character;
#! - `[abc]` matches one of the characters it holds, `[a-z]` one in the range,
#! and `[!abc]` or `[^abc]` one it doesn't hold. A `]` first is one of them,
#! as is a `-` first or last;
#! - `**`, as a whole name, matches any number of whole names, none included,
#! so `src/**/*.sakura` matches `src/main.sakura` and `src/a/b/main.sakura`;
#! elsewhere it is `*`;
#! - `{a,b}` matches either, and may hold anything, `/` and other braces
#! included, so `{src,test}/*.sakura` is two globs;
#! - `\` takes away what the next character means, as `\*` matches a `*`. It
#! can't make `/` part of a name, as no name holds one;
#! - `/` separates names on every system, Windows included, and a glob
#! starting with one, or on Windows with a drive's, as `C:/`, starts at that
#! root. A glob ending in one matches directories only.
#!
#! A character is a code point of UTF-8, or a byte where the text isn't UTF-8.
#! A name starting with `.` is matched only by a name of the glob starting with
#! `.` as written, unless the options say otherwise, so `*` leaves out hidden
#! files and `**` the directories that hold them. Neither ever matches `.` or
#! `..`, which only a glob's `.` and `..` match.
#!
#! `std::io::glob` is a module within `std::io`, whose paths it matches, and so
#! sees its names without importing it. It is a module of its own so that its
#! `error`, `options`, `describe`, and `escape` are seen only where it is
#! imported.
module std::io::glob;
when os == linux {
#! Whether letters match in either case unless the options say otherwise: on
#! Linux they don't, as its file systems tell cases apart.
pub const folds_case_by_default: bool = false;
}
else {
#! Whether letters match in either case unless the options say otherwise: on
#! Windows and macOS they do, as their file systems don't tell cases apart.
pub const folds_case_by_default: bool = true;
}
#! How a glob is read and matched.
pub struct options {
#! Whether `*`, `?`, a set, and `**` match a name starting with `.`, which
#! otherwise only a name of the glob starting with `.` matches.
pub var hidden: bool = false;
#! Whether letters match in either case, as `*.TXT` matches `notes.txt`. Only
#! ASCII letters fold.
pub var folds_case: bool = folds_case_by_default;
}
#! The kinds of mistake a glob's text can hold.
pub enum error_kind: u8 {
empty, #! The text is empty.
trailing_escape, #! The text ends in a `\`, which escapes nothing.
unclosed_set, #! A `[` has no `]` after it.
unclosed_brace, #! A `{` has no `}` after it.
unopened_brace, #! A `}` has no `{` before it.
too_many_choices, #! The braces make more globs than `choice_limit`.
}
#! The most globs the braces of one may make, as `{a,b}{c,d}` makes four.
pub const choice_limit: u64 = 1024;
#! A mistake in a glob's text, and where it is.
pub struct error {
pub var kind: error_kind; #! What the mistake is.
pub var offset: u64; #! The byte of the text it is at.
}
#! Describes the mistake.
#! @param this The mistake.
#! @returns A sentence saying what it is and where.
pub def error::describe(&this): string {
return $"{describe(this.kind)} (at byte {this.offset})";
}
#! Describes a kind of mistake.
#! @param kind The kind.
#! @returns A sentence saying what it is.
pub def describe(kind: error_kind): strview {
return match kind {
empty => "A glob can't be empty: `.` names where a search starts.",
trailing_escape => "The glob ends in a `\\`, which escapes nothing.",
unclosed_set => "A `[` has no `]` closing it.",
unclosed_brace => "A `{` has no `}` closing it.",
unopened_brace => "A `}` has no `{` opening it.",
too_many_choices => "The braces make more than 1024 globs.",
};
}
#! Makes text into a glob matching only itself, by escaping each character
#! that would mean something else, as `notes[1].txt` becomes `notes\[1\].txt`.
#! @param text The text, as a name or a path.
#! @param alloc The optional allocator for the glob's text.
#! @returns The glob. On Windows, where `\` separates names too, each is
#! written as `/`, so a path's text is a glob naming that path.
pub def escape(text: strview, alloc: maybe<&mut allocator> = nothing{}): string {
var made := string::new(alloc);
made.reserve(text.length);
for at in 0..text.length {
val byte := text[at];
when os == windows {
if byte == '\\' {
made.push('/');
continue;
}
}
if is_special(byte) {
made.push('\\');
}
made.push(byte);
}
return made;
}
# Whether a byte means something in a glob other than itself, somewhere.
def is_special(byte: u8): bool {
return byte == '*' || byte == '?' || byte == '[' || byte == ']' || byte == '{' || byte == '}'
|| byte == ',' || byte == '\\';
}
+678
View File
@@ -0,0 +1,678 @@
#! @file pattern.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `pattern`, a glob read into the pieces that match it, and how the
#! text of a path is matched against one.
module std::io::glob;
#! A glob, read into what each of its names matches.
#!
#! Braces are taken out as it is read, so a pattern is one or more choices,
#! each a root and a list of segments: a name as written, a name matched by its
#! pieces, or `**`. Every segment, piece, and set is held in a flat array of the
#! pattern's, by index, as are the bytes of the names and pieces as written.
pub struct pattern {
var _text: string; #! The glob, as given.
var _options: options;
var _bytes: string; #! The bytes of every name and text piece, and every root, escapes taken out.
var _pieces: vector<piece>;
var _ranges: vector<bounds>; #! The characters of every set.
var _segments: vector<segment>;
var _choices: vector<choice>;
}
# What a piece of a name matches.
enum piece_kind: u8 {
text, #! Its bytes, as written.
one, #! Any one character.
any, #! Any run of characters, or none.
set, #! One character within any of its ranges.
unset, #! One character within none of its ranges.
}
# A piece of a name: what it matches, and where its bytes or ranges are.
struct piece {
var kind: piece_kind;
var start: u64; #! Its first byte in `_bytes`, or its first range in `_ranges`.
var length: u64; #! How many bytes or ranges it has.
}
# The characters from one to another, both included, which a set holds.
struct bounds {
var low: u32;
var high: u32;
}
# What a segment of a choice matches.
enum segment_kind: u8 {
literal, #! One name, as written: its bytes are in `_bytes`.
wild, #! One name its pieces match: they are in `_pieces`.
deep, #! Any number of whole names, none included, as `**` does.
}
# A segment of a choice: what it matches, and where its bytes or pieces are.
struct segment {
var kind: segment_kind;
var start: u64; #! Its first byte or piece.
var length: u64; #! How many bytes or pieces it has.
var dotted: bool; #! Whether it starts with `.` as written, so it may match a hidden name.
}
# One of the globs a pattern's braces make: where it starts, and its segments.
struct choice {
var start: u64; #! Its first segment in `_segments`.
var length: u64; #! How many segments it has.
var root: u64; #! Its root's first byte in `_bytes`.
var rooted: u64; #! How many bytes its root has: none, as `/`, or as `C:/`.
var directories: bool; #! Whether it ended in `/`, so only directories match.
}
# A character of text, and how many bytes it takes.
struct rune {
var value: u32;
var width: u64;
}
#! Reads a glob.
#! @param text The glob, as `src/**/*.sakura`.
#! @param settings How it is read and matched.
#! @param alloc The optional allocator for what the pattern holds.
#! @returns The pattern, or the first mistake the text holds.
pub def pattern::parse(
text: strview,
settings: options = options {},
alloc: maybe<&mut allocator> = nothing{}
): result<pattern, error> {
if text.length == 0 {
return error { kind = error_kind::empty, offset = 0 };
}
if mistake_in(text) is some(found) {
return found;
}
var choices := vector::<string>::new(alloc);
if !expand(text, &mut choices, alloc) {
return error { kind = error_kind::too_many_choices, offset = 0 };
}
var made := pattern {
_text = string::from(text, alloc),
_options = settings,
_bytes = string::new(alloc),
_pieces = vector::<piece>::new(alloc),
_ranges = vector::<bounds>::new(alloc),
_segments = vector::<segment>::new(alloc),
_choices = vector::<choice>::new(alloc)
};
for &each in choices {
made.add_choice(each.view());
}
return move(made);
}
#! The glob the pattern was read from.
#! @param this The pattern.
#! @returns The glob's text, as given.
pub val pattern::text: strview {
get => this._text.view();
}
#! Whether the glob has no wildcards or braces, so it names one path, which
#! matches only itself.
#! @param this The pattern.
#! @returns Whether every name of its one choice is written as it is.
pub val pattern::is_literal: bool {
get {
return false if this._choices.length != 1;
val only := this._choices[0];
for s in only.start..(only.start + only.length) {
return false if this._segments[s].kind != segment_kind::literal;
}
return true;
}
}
#! Whether the glob ends in `/`, so only directories match it.
#! @param this The pattern.
#! @returns Whether any of its choices does.
pub val pattern::directories: bool {
get {
for c in 0..this._choices.length {
return true if this._choices[c].directories;
}
return false;
}
}
#! Tells whether the text of a path matches the glob, from the text alone.
#! @param this The pattern.
#! @param text The path, as `src/main.sakura`. A name of `.`, and a `/` more
#! than one between names, are passed over, as a path's normal
#! form does. On Windows, `\` separates names too.
#! @returns Whether any of the pattern's choices matches it. A glob ending in
#! `/` matches only text ending in one, which says it is a directory,
#! and text that is only a root, or `.`, is matched only by a glob
#! naming it, as `**` doesn't.
pub def pattern::matches(&this, text: strview): bool {
var at := 0u;
var root := strview::empty();
if text.length > 0 && is_delim(text[0]) {
root = "/";
at = 1;
}
when os == windows {
if text.length > 2 && text[0].is_alpha && text[1] == ':' && is_delim(text[2]) {
root = text.substr(0, 2);
at = 3;
}
}
var names := vector::<strview>::new();
var from := at;
while at <= text.length {
if at < text.length && !is_delim(text[at]) {
at++;
continue;
}
val name := text.substr(from, at - from);
if name.length != 0 && name != "." {
names.append(name);
}
at++;
from = at;
}
val directory := text.length > 0 && is_delim(text[text.length - 1]);
for c in 0..this._choices.length {
val each := this._choices[c];
continue if each.directories && !directory;
continue if !this.same_root(&each, root);
return true if this.fits(&each, names.view());
}
return false;
}
# Whether a byte separates the names of a path's text.
def is_delim(byte: u8): bool {
when os == windows {
return byte == '/' || byte == '\\';
}
return byte == '/';
}
# Whether text's root is a choice's, which is empty, `/`, or a drive's: `C:` in
# the text, and `C:/` in the choice.
def pattern::same_root(&this, each: &choice, root: strview): bool {
if each.rooted == 0 || root.length == 0 {
return each.rooted == 0 && root.length == 0;
}
val mine := this._bytes.substr(each.root, each.rooted);
if root == "/" {
return mine == "/";
}
return mine.length == 3 && mine[0].to_lower == root[0].to_lower;
}
# Whether a choice's segments match the names, one each, but for `**`, which
# matches any number of them.
def pattern::fits(&this, each: &choice, names: span<strview>): bool {
if names.length == 0 {
return each.length == 0;
}
# Without `**`, each segment matches the name in its place.
var deep := false;
for s in each.start..(each.start + each.length) {
deep = deep || this._segments[s].kind == segment_kind::deep;
}
if !deep {
return false if each.length != names.length;
for k in 0..names.length {
return false if !this.fits_name(&this._segments[each.start + k], names[k]);
}
return true;
}
# With it, whether the segments from each on match the names from each on,
# worked out from the last of both back, in a row of `names.length + 1` for
# each segment, so every segment is matched against every name at most once.
val row := names.length + 1;
var ends := vector::<bool>::new();
ends.resize((each.length + 1) * row, false);
ends.set(each.length * row + names.length, true);
var s := each.length;
while s > 0 {
s--;
val seg := this._segments[each.start + s];
var n := row;
while n > 0 {
n--;
var fits := false;
if seg.kind == segment_kind::deep {
fits = ends[(s + 1) * row + n] || (n < names.length && this.covers(names[n]) && ends[s * row + n + 1]);
} else {
fits = n < names.length && ends[(s + 1) * row + n + 1] && this.fits_name(&seg, names[n]);
}
ends.set(s * row + n, fits);
}
}
return ends[0];
}
# Whether a segment matches one name, which for `**` is whether it may cover it.
def pattern::fits_name(&this, seg: &segment, name: strview): bool {
return match seg.kind {
literal => this.same(this._bytes.substr(seg.start, seg.length), name),
deep => this.covers(name),
wild => this.wild_fits(seg, name),
};
}
# Whether `**` may cover a name: any but `.`, `..`, and a hidden one, unless the
# options let it.
def pattern::covers(&this, name: strview): bool {
return false if name == "." || name == "..";
return this._options.hidden || name.length == 0 || name[0] != '.';
}
# Whether the pieces of a segment match a name, letting the last `*` seen take
# a character more each time what follows it doesn't fit, as `*` matches any run.
def pattern::wild_fits(&this, seg: &segment, name: strview): bool {
return false if name == "." || name == "..";
if !this._options.hidden && name.length > 0 && name[0] == '.' && !seg.dotted {
return false;
}
val end := seg.start + seg.length;
var p := seg.start;
var t := 0u;
var starred := false;
var star := 0u; # The piece after the last `*`.
var resume := 0u; # Where the text goes on from after what that `*` took.
while true {
if p < end {
val each := this._pieces[p];
if each.kind == piece_kind::any {
p++;
return true if p == end;
starred = true;
star = p;
resume = t;
continue;
}
if t < name.length {
val taken := this.taken(&each, name, t);
if taken != 0 {
p++;
t += taken;
continue;
}
}
} else if t == name.length {
return true;
}
return false if !starred || resume >= name.length;
resume += rune_at(name, resume).width;
t = resume;
p = star;
}
return false;
}
# How many bytes of a name a piece other than `*` takes where it starts at a
# byte, or zero where it doesn't fit there.
def pattern::taken(&this, each: &piece, name: strview, at: u64): u64 {
if each.kind == piece_kind::text {
return 0 if name.length - at < each.length;
val fits := this.same(this._bytes.substr(each.start, each.length), name.substr(at, each.length));
return fits ? each.length : 0;
}
val read := rune_at(name, at);
if each.kind == piece_kind::one {
return read.width;
}
var within := this.within(each, read.value);
if this._options.folds_case && !within {
within = this.within(each, other_case(read.value));
}
return within == (each.kind == piece_kind::set) ? read.width : 0;
}
# Whether a character is within any of a set's ranges.
def pattern::within(&this, each: &piece, value: u32): bool {
for r in each.start..(each.start + each.length) {
val range := this._ranges[r];
return true if value >= range.low && value <= range.high;
}
return false;
}
# Whether two runs of bytes are the same, in either case where the options fold
# it.
def pattern::same(&this, a: strview, b: strview): bool {
return false if a.length != b.length;
if !this._options.folds_case {
return a == b;
}
for k in 0..a.length {
return false if a[k].to_lower != b[k].to_lower;
}
return true;
}
# An ASCII letter in the other case, and anything else as it is.
def other_case(value: u32): u32 {
if value >= ('a' as u32) && value <= ('z' as u32) {
return value - 32;
}
if value >= ('A' as u32) && value <= ('Z' as u32) {
return value + 32;
}
return value;
}
# The character text holds at a byte. A byte starting no character of UTF-8, or
# one too short, too long, or past U+10FFFF, is a character of its own, U+FFFD.
def rune_at(text: strview, at: u64): rune {
val lead := text[at];
if lead < 0x80 {
return rune { value = lead as u32, width = 1 };
}
var width: u64 = 0;
var value: u32 = 0;
var least: u32 = 0;
if (lead & 0xE0) == 0xC0 {
width = 2;
value = (lead & 0x1F) as u32;
least = 0x80;
} else if (lead & 0xF0) == 0xE0 {
width = 3;
value = (lead & 0x0F) as u32;
least = 0x800;
} else if (lead & 0xF8) == 0xF0 {
width = 4;
value = (lead & 0x07) as u32;
least = 0x10000;
}
val malformed := rune { value = 0xFFFD, width = 1 };
return malformed if width == 0 || at + width > text.length;
for k in 1..width {
val byte := text[at + k];
return malformed if (byte & 0xC0) != 0x80;
value = (value << 6) | (byte & 0x3F) as u32;
}
if value < least || value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF) {
return malformed;
}
return rune { value = value, width = width };
}
# The first mistake in a glob's text, where it holds one: an escape ending it,
# or a set or brace left open, or a brace closed that wasn't opened.
def mistake_in(text: strview): maybe<error> {
var open := vector::<u64>::new(); # Where each brace still open is.
var at := 0u;
while at < text.length {
val byte := text[at];
if byte == '\\' {
return error { kind = error_kind::trailing_escape, offset = at } if at + 1 == text.length;
at += 2;
continue;
}
if byte == '[' {
val end := set_end(text, at);
return error { kind = error_kind::unclosed_set, offset = at } if end is none;
at = end.some + 1;
continue;
}
if byte == '{' {
open.append(at);
} else if byte == '}' {
return error { kind = error_kind::unopened_brace, offset = at } if open.length == 0;
open.remove_at(open.length - 1);
}
at++;
}
if open.length != 0 {
return error { kind = error_kind::unclosed_brace, offset = open[open.length - 1] };
}
return nothing{};
}
# Where the `]` closing the set opened at a byte is: after a `!` or `^` and a
# `]` first, which are the set's, and passing over escaped characters.
def set_end(text: strview, at: u64): maybe<u64> {
var k := at + 1;
if k < text.length && (text[k] == '!' || text[k] == '^') {
k++;
}
if k < text.length && text[k] == ']' {
k++;
}
while k < text.length {
return k if text[k] == ']';
k += text[k] == '\\' ? 2 : 1;
}
return nothing{};
}
# Adds each glob a glob's braces make, in order, as `a{b,c}d` makes `abd` and
# `acd`, giving whether there were no more than `choice_limit`. The text holds
# no mistakes.
def expand(text: strview, into: &mut vector<string>, alloc: maybe<&mut allocator>): bool {
# The first brace outside a set.
var open := text.length;
var at := 0u;
while at < text.length {
val byte := text[at];
if byte == '\\' {
at += 2;
continue;
}
if byte == '[' {
at = set_end(text, at).some + 1;
continue;
}
if byte == '{' {
open = at;
break;
}
at++;
}
if open == text.length {
into.append(string::from(text, alloc));
return into.length <= choice_limit;
}
# Each choice it holds, between it, the commas within it but not within a
# brace it holds, and the brace closing it.
var cuts := vector::<u64>::new();
var depth := 0u;
cuts.append(open);
at = open + 1;
while true {
val byte := text[at];
if byte == '\\' {
at += 2;
continue;
}
if byte == '[' {
at = set_end(text, at).some + 1;
continue;
}
if byte == '{' {
depth++;
} else if byte == '}' {
if depth == 0 {
cuts.append(at);
break;
}
depth--;
} else if byte == ',' && depth == 0 {
cuts.append(at);
}
at++;
}
val close := cuts[cuts.length - 1];
val after := text.substr(close + 1, text.length - close - 1);
for k in 0..(cuts.length - 1) {
var joined := string::from(text.substr(0, open), alloc);
joined.append(text.substr(cuts[k] + 1, cuts[k + 1] - cuts[k] - 1));
joined.append(after);
return false if !expand(joined.view(), into, alloc);
}
return true;
}
# Reads one glob without braces into a choice: its root, then a segment for
# each name, passing over empty names and `.`, and taking `**` after `**` as
# one.
def pattern::add_choice(&mut this, text: strview): void {
var made := choice { start = this._segments.length, root = this._bytes.length };
var at := 0u;
if text.length > 0 && text[0] == '/' {
this._bytes.push('/');
at = 1;
}
when os == windows {
if text.length > 2 && text[0].is_alpha && text[1] == ':' && text[2] == '/' {
this._bytes.append(text.substr(0, 3));
at = 3;
}
}
made.rooted = this._bytes.length - made.root;
made.directories = text.length > at && text[text.length - 1] == '/';
var from := at; # Where the name being read starts.
var first := this._pieces.length;
while true {
val ends := at == text.length || text[at] == '/' || (text[at] == '\\' && text[at + 1] == '/');
if ends {
this.add_segment(text.substr(from, at - from), first, made.start);
break if at == text.length;
at += text[at] == '\\' ? 2 : 1;
from = at;
first = this._pieces.length;
continue;
}
val byte := text[at];
if byte == '\\' {
this.add_text(text.substr(at + 1, 1), first);
at += 2;
} else if byte == '*' {
val last := this._pieces.length;
if last == first || this._pieces[last - 1].kind != piece_kind::any {
this._pieces.append(piece { kind = piece_kind::any });
}
at++;
} else if byte == '?' {
this._pieces.append(piece { kind = piece_kind::one });
at++;
} else if byte == '[' {
val end := set_end(text, at).some;
this.add_set(text, at, end);
at = end + 1;
} else {
this.add_text(text.substr(at, 1), first);
at++;
}
}
made.length = this._segments.length - made.start;
this._choices.append(made);
}
# Adds bytes matched as written to the name being read, whose pieces start at
# one, onto its last piece where that is text too.
def pattern::add_text(&mut this, bytes: strview, first: u64): void {
val last := this._pieces.length;
if last > first {
val prior := this._pieces[last - 1];
if prior.kind == piece_kind::text && prior.start + prior.length == this._bytes.length {
this._pieces.at(last - 1).length += bytes.length;
this._bytes.append(bytes);
return;
}
}
this._pieces.append(piece { kind = piece_kind::text, start = this._bytes.length, length = bytes.length });
this._bytes.append(bytes);
}
# Adds the set from its `[` to its `]`: each character, or range of them, it
# holds, and whether it matches those or the rest.
def pattern::add_set(&mut this, text: strview, open: u64, close: u64): void {
var made := piece { kind = piece_kind::set, start = this._ranges.length };
var at := open + 1;
if text[at] == '!' || text[at] == '^' {
made.kind = piece_kind::unset;
at++;
}
while at < close {
val low := item_at(text, at);
at += low.width;
if at + 1 < close && text[at] == '-' {
val high := item_at(text, at + 1);
at += 1 + high.width;
this._ranges.append(bounds { low = low.value, high = high.value });
} else {
this._ranges.append(bounds { low = low.value, high = low.value });
}
}
made.length = this._ranges.length - made.start;
this._pieces.append(made);
}
# The character a set holds at a byte, escaped or not, with the bytes it takes.
def item_at(text: strview, at: u64): rune {
if text[at] == '\\' {
val escaped := rune_at(text, at + 1);
return rune { value = escaped.value, width = escaped.width + 1 };
}
return rune_at(text, at);
}
# Ends the name being read, whose pieces start at one, as a segment of the
# choice whose segments start at another: a name as written where its pieces
# are all text, `**` where it is only that, and its pieces otherwise. An empty
# name and `.` add none, nor does `**` after `**`.
def pattern::add_segment(&mut this, written: strview, first: u64, opened: u64): void {
val count := this._pieces.length - first;
if written.length == 0 || written == "." {
this._pieces.resize(first);
return;
}
if written == "**" {
this._pieces.resize(first);
val segments := this._segments.length;
if segments > opened && this._segments[segments - 1].kind == segment_kind::deep {
return;
}
this._segments.append(segment { kind = segment_kind::deep });
return;
}
if count == 1 && this._pieces[first].kind == piece_kind::text {
val only := this._pieces[first];
this._pieces.resize(first);
this._segments.append(segment { kind = segment_kind::literal, start = only.start, length = only.length });
return;
}
val lead := this._pieces[first];
this._segments.append(segment {
kind = segment_kind::wild,
start = first,
length = count,
dotted = lead.kind == piece_kind::text && this._bytes[lead.start] == '.'
});
}
+708
View File
@@ -0,0 +1,708 @@
#! @file path.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains paths, which `std::io` takes and gives for every file it names, and
#! the ways of making one from another: taking its parent, joining, resolving, and
#! making one relative to another. Nothing here reads the file system, so `..` is
#! worked out from the text alone; `std::io` is what asks the system.
#! `std::net`'s `uri::from_path` and `uri::to_path` turn a path into a `file`
#! URI and back.
import system;
module std::io;
# I hate Windows :)
when os == windows {
pub const path_delim: u8 = '\\';
pub const path_invalid_chars: strview = "<>:\"/\\|?*";
} else when os == linux {
pub const path_delim: u8 = '/';
pub const path_invalid_chars: strview = "\\";
} else when os == macos {
pub const path_delim: u8 = '/';
pub const path_invalid_chars: strview = ":\\";
}
#! A path (or filepath, pathname, or similar) is a string that uniquely
#! identifies an item in a hierarchical file system. Generally, a path is
#! composed of directory names, special format specifiers, and optionally a
#! filename, all separated by delimiters.
#!
#! A path can be either relative or absolute. A relative path is one in relation
#! to another, most often the working directory. An absolute path indicates a
#! location regardless of the current directory; that is, it specifies all path
#! components starting from the file system's root, and does not depend on
#! context like a relative path does.
#!
#! A parsed path holds its text in a normal form: its root, then its segments
#! joined by one `path_delim` each. Repeated delimiters and `.` segments are
#! dropped, as is a delimiter at the end, and a relative path left with nothing
#! is `.`. A `..` segment is kept, since what it leads back to depends on links
#! the file system holds; `resolve` is what works `..` out, from the text alone.
#! So two paths are equal when their normal forms are.
#!
#! Paths made from other paths take memory from the same allocator as the path
#! they are made from.
#!
#! @sa https://en.wikipedia.org/wiki/Path_(computing)
pub struct path
: owning
, hashable
, equatable
, copyable
, moveable
{
var _text: string;
var _root: u64;
}
#! The number of bytes the path holds.
#! @param this The path to measure.
#! @returns How many bytes of text it holds, which is no more than its capacity.
pub val path::length: u64 {
get => this._text.length;
}
#! Whether the path is empty.
#! @param this The path to measure.
#! @returns If the path is empty or populated.
pub val path::empty: bool {
get => this.length == 0;
}
#! Provides read only access to the root of a path, which is where it starts
#! from before its first segment.
#! @param this The path to get the root of.
#! @returns A view of the root, such as `/`, `C:\`, `C:`, `\`, or
#! `\\server\share\`, which is empty for a relative path.
pub val path::root: strview {
get => this.view().substr(0, this._root);
}
#! Indicates if a path is absolute, naming the same place whatever the working
#! directory is.
#! @param this The path to check.
#! @returns Whether the path is absolute.
#! @remarks On Windows, `C:foo` is relative to the working directory of drive
#! `C:`, and `\foo` to the root of the working directory's drive, so
#! neither is absolute; only a root ending in a delimiter after a
#! drive or share is.
pub val path::is_absolute: bool {
get {
if !this.is_rooted() {
return false;
}
when os == windows {
return this._root > 1;
}
return true;
}
}
#! Indicates if a path is a directory.
#! @param this The path to check.
#! @returns Whether the path is a directory.
pub val path::is_directory: bool {
get {
return match info(this) {
value(&i) => i.kind == file_kind::directory,
error(_) => false
};
}
}
#! Provides read only access to the name a path ends with.
#! @param this The path to get the name of.
#! @returns A view of the last segment, which is empty where the path is only a
#! root, or is `.` or ends in `..`.
pub val path::name: strview {
get {
val text := this.view();
val start := this.last_start();
val name := text.substr(start, text.length - start);
return name == ".."
? strview::empty()
: name;
}
}
#! Provides read only access to the name a path ends with, without its
#! extension.
#! @param this The path to get the stem of.
#! @returns A view of the name before its last `.`, or the whole name where it
#! has no extension.
pub val path::stem: strview {
get {
val name := this.name;
val dot := path::dot_of(name);
return dot != 0
? name.substr(0, dot)
: name;
}
}
#! Provides read only access to the extension of the name a path ends with.
#! @param this The path to get the extension of.
#! @returns A view of the name after its last `.`, without the `.`, which is
#! empty where it has none. A name starting with its only `.`, such as
#! `.profile`, has no extension.
pub val path::extension: strview {
get {
val name := this.name;
val dot := path::dot_of(name);
return dot != 0
? name.substr(dot + 1, name.length - dot - 1)
: strview::empty();
}
}
#! Creates an empty path.
#! @returns The created path.
pub def path::new(): path {
return path {};
}
#! Parses text as a path, in the form of the platform checked for.
#! @param text The text to parse, such as `/usr/lib`, `../notes.txt`, or on
#! Windows `C:\Users` or `\\server\share\file`.
#! @param alloc The optional allocator for the text the path holds.
#! @returns The path, in its normal form, or why the text is not one.
#! @remarks On Windows, `/` also separates segments, and is written as `\`, and
#! a drive's letter is written in upper case.
pub def path::parse(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): result<path, failure> {
if text.is_empty() {
return failure { message = $"a path cannot be empty" };
}
var made := path { _text = string::new(alloc), _root = 0 };
made._text.reserve(text.length);
val start := path::read_root(text, &mut made._text);
if start is none {
return failure { message = $"`{text}` does not name both a server and a share" };
}
made._root = made._text.length;
var at := start.some;
while at < text.length {
if path::is_delim(text[at]) {
at++;
continue;
}
var end := at;
while end < text.length && !path::is_delim(text[end]) {
end++;
}
val part := text.substr(at, end - at);
at = end;
if part == "." {
continue;
}
val bad := path::invalid_in(part);
if bad is some {
return failure {
message = $"`{text}` holds `{part.substr(bad.some, 1)}`, which a path cannot"
};
}
if made._text.length > made._root {
made._text.push(path_delim);
}
made._text.append(part);
}
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Creates a copy of the provided path.
#! @param other The path to copy.
#! @returns The copy, which owns its own text, with the other's allocator.
pub def path::copy_of(other: &path): path {
return path {
_text = string::copy_of(&other._text),
_root = other._root
};
}
#! Creates a new path by moving the text of another path into it.
#! @param other The path to move from, which holds no text after.
#! @returns The moved path, which takes the text and allocator with it.
pub def path::move_of(other: &mut path): path {
val made: path = path {
_text = string::move_of(&mut other._text),
_root = other._root
};
other._root = 0;
return made;
}
#! Views the text of a path, in its normal form.
#! @param this The path to view.
#! @returns A view of its text, which is only good until the path closes.
pub def path::view(&this): strview {
return this._text.view();
}
#! Views each segment of a path after its root, in turn.
#! @param this The path to split.
#! @returns The segments, in order, each viewing into the path's text, so they
#! are only good for as long as it is. A path that is only a root, or
#! is `.`, has none.
pub def path::segments(&this): splits {
if this.is_dot() || this._text.length == this._root {
return splits::empty();
}
val rest := this.view().substr(this._root, this._text.length - this._root);
return rest.split(path_delim);
}
# TODO: Move this to being a property.
#! Makes the path of the directory holding what a path names, from its text.
#! @param this The path to take the parent of.
#! @returns The path without its last segment, which is `.` where only one
#! segment of a relative path was left. A path ending in `..` has
#! another `..` added instead, since dropping it would lead down rather
#! than up. A path that is only a root, or is `.`, has no parent.
pub def path::parent(&this): maybe<path> {
val text := this.view();
if this.is_dot() || text.length == this._root {
return nothing{};
}
var made := this.blank();
val start := this.last_start();
made._root = this._root;
if text.substr(start, text.length - start) == ".." {
made._text.append(text);
made._text.push(path_delim);
made._text.append("..");
return move(made);
}
# The delimiter before the last segment goes with it, unless it ends the root.
val end := start > this._root ? start - 1 : start;
made._text.append(text.substr(0, end));
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Joins another path onto the end of this one.
#! @param this The path to start from.
#! @param other The path to follow from there.
#! @returns The joined path. Where the other is absolute it is the other alone,
#! since it names the same place from anywhere, and where either is `.`
#! it is the other one.
#! @remarks On Windows, a path starting at a root without a drive, as `\foo`, is
#! joined onto this one's drive or share. A path on a drive without a
#! root, as `C:foo`, is joined onto this one where it is on the same
#! drive, and is taken alone where it is not.
pub def path::join(&this, other: &path): path {
return this.joined(other, this._text.alloc);
}
#! Joins a path, given as text, onto the end of this one, as `join` of the path
#! the text is does.
#!
#! The text is taken to be one the program wrote, as `dir.join("lib")`, so text
#! that is not a path is a mistake in the program, and stops it. Text from
#! outside the program is parsed by `path::parse`, which says why it is not a
#! path, and the path it gives is joined instead.
#! @param this The path to start from.
#! @param text The text of the path to follow from there, such as `lib` or
#! `../include`.
#! @returns The joined path.
pub def path::join(&this, text: strview): path {
var parsed := path::parse(text, this._text.alloc);
if parsed is value(&other) {
return this.joined(other, this._text.alloc);
}
system::fd::stderr.put($"sakura: `{text}` is not a path, so it cannot be joined onto one\n");
system::abort();
return this.blank();
}
#! Resolves a path against a base, from the text alone: joins it onto the base,
#! then has each `..` take away the segment before it.
#! @param this The path to resolve, which is taken as it is where absolute.
#! @param base The path that a relative one is taken from, as the working
#! directory is by `std::io::absolute`.
#! @returns The resolved path, which holds no `..` after another segment, and
#! none at all where it has a root, since nothing is above a root.
#! @remarks Where the file system holds links, `..` after one leads back from
#! what the link leads to, which this does not ask the system about.
pub def path::resolve(&this, base: &path): path {
val joined := base.joined(this, this._text.alloc);
var parts := vector::<strview>::new();
for part in joined.segments() {
if part != ".." {
parts.append(part);
continue;
}
if parts.length > 0 && parts.at(parts.length - 1) != ".." {
parts.remove_at(parts.length - 1);
continue;
}
if !joined.is_rooted() {
parts.append(part);
}
}
var made := this.blank();
made._text.append(joined.root);
made._root = joined._root;
for i in 0..parts.length {
if i > 0 {
made._text.push(path_delim);
}
made._text.append(parts.at(i));
}
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Makes the path that leads from a base to this one, from the text alone.
#! @param this The path to lead to.
#! @param base The path to lead from.
#! @returns A relative path, which `base.join` turns back into this one, as
#! `../lib/std` from `/usr/share` to `/usr/lib/std`, and `.` where the
#! two are the same. There is none where their roots differ, as one
#! being absolute and the other relative, or where the base has a `..`
#! past what they share, since what that leads back from is unknown.
pub def path::relative_to(&this, base: &path): maybe<path> {
if this.root != base.root {
return nothing{};
}
val mine := this.segments().to_vector();
val theirs := base.segments().to_vector();
var shared := 0u;
while shared < mine.length && shared < theirs.length {
val a: strview = mine.at(shared);
val b: strview = theirs.at(shared);
if a != b {
break;
}
shared++;
}
for i in shared..theirs.length {
if theirs.at(i) == ".." {
return nothing{};
}
}
var made := this.blank();
for _ in shared..theirs.length {
made.push_segment("..");
}
for i in shared..mine.length {
made.push_segment(mine.at(i));
}
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Tells whether a path is a base or lies within it, by whole segments, so
#! `/usr/lib` starts with `/usr` but not with `/us`.
#! @param this The path to check.
#! @param base The path it may start with.
#! @returns Whether the base's root and segments begin this path. Every relative
#! path starts with `.`.
pub def path::starts_with(&this, base: &path): bool {
if this._root != base._root || this.root != base.root {
return false;
}
if base.is_dot() || base._text.length == base._root {
return true;
}
val mine := this.view();
val theirs := base.view();
if !mine.starts_with(theirs) {
return false;
}
return mine.length == theirs.length || mine[theirs.length] == path_delim;
}
#! Makes a path naming something else in the same directory.
#! @param this The path whose name to replace.
#! @param name The name to give it instead, which is one segment.
#! @returns The path with the name replaced, or why it cannot be: the path has
#! no name to replace, or the name is empty, `.`, `..`, or holds a
#! delimiter or something else a path cannot.
pub def path::with_name(&this, name: strview): result<path, failure> {
if this.name.is_empty() {
return failure { message = $"`{this.view()}` has no name to replace" };
}
if name.is_empty() || name == "." || name == ".." {
return failure { message = $"`{name}` is not a name" };
}
val bad := path::invalid_in(name);
if bad is some {
return failure { message = $"`{name}` holds `{name.substr(bad.some, 1)}`, which a name cannot" };
}
var made := this.blank();
made._text.append(this.view().substr(0, this.last_start()));
made._text.append(name);
made._root = this._root;
return move(made);
}
#! Makes a path whose name has another extension, as `main.o` from
#! `main.sakura`.
#! @param this The path whose extension to replace.
#! @param extension The extension, without its `.`, or empty to take the
#! extension away.
#! @returns The path with the extension replaced, or added where the name had
#! none, or why it cannot be: the path has no name, or the extension
#! holds a delimiter or something else a path cannot.
pub def path::with_extension(&this, extension: strview): result<path, failure> {
if this.name.is_empty() {
return failure { message = $"`{this.view()}` has no name to give an extension" };
}
val bad := path::invalid_in(extension);
if bad is some {
return failure {
message = $"`{extension}` holds `{extension.substr(bad.some, 1)}`, which a name cannot"
};
}
var made := this.blank();
made._text.append(this.view().substr(0, this.last_start()));
made._text.append(this.stem);
if !extension.is_empty() {
made._text.push('.');
made._text.append(extension);
}
made._root = this._root;
return move(made);
}
#! Gives back the memory holding the text of a path.
#! @param this The path to close.
pub def path::close(&mut this): void {
this._text.close();
this._root = 0;
}
#! Compares one path to another by equality.
#! @param this The path to compare against.
#! @param other The path to compare with.
#! @returns Whether both have the same normal form.
pub def path::equals(&this, other: &path): bool {
return this._text.equals(&other._text);
}
#! Hashes the provided path.
#! @param this The path to hash.
#! @returns The hash code of its normal form, which equal paths share.
pub def path::hash(&this): u64 {
return this._text.hash();
}
# Joins another path onto the end of this one, as `join` does, into memory from
# the allocator given.
def path::joined(&this, other: &path, alloc: maybe<&mut allocator>): path {
var made := path { _text = string::new(alloc), _root = 0 };
when os == windows {
if other._root > 0 && !other.is_absolute {
return this.joined_on_drive(other, alloc);
}
}
if other.is_absolute || this.is_dot() {
made._text.append(other.view());
made._root = other._root;
return move(made);
}
made._text.append(this.view());
made._root = this._root;
if !other.is_dot() {
if this._text.length > this._root {
made._text.push(path_delim);
}
made._text.append(other.view());
}
return move(made);
}
# Joins a Windows path that starts at a root without a drive, as `\foo`, or on a
# drive without a root, as `C:foo`, onto the end of this one.
def path::joined_on_drive(&this, other: &path, alloc: maybe<&mut allocator>): path {
var made := path { _text = string::new(alloc), _root = 0 };
val root := this.root;
# `\foo` keeps this path's drive or share: its root, less the delimiter ending it.
if other._root == 1 {
val drive := root.length > 1 && path::is_delim(root[root.length - 1])
? root.substr(0, root.length - 1)
: root;
val keeps := drive.length > 1 ? drive : strview::empty();
made._text.append(keeps);
made._text.append(other.view());
made._root = keeps.length + 1;
return move(made);
}
# `C:foo` follows on from this path where it is on drive `C:`, and stands alone
# where it is not.
if root.length >= 2 && root[0] == other.view()[0] && root[1] == ':' {
made._text.append(this.view());
made._root = this._root;
if other._text.length > other._root {
if this._text.length > this._root {
made._text.push(path_delim);
}
made._text.append(other.view().substr(other._root, other._text.length - other._root));
}
return move(made);
}
made._text.append(other.view());
made._root = other._root;
return move(made);
}
# A path with no text yet, whose memory comes from the same allocator as this one.
def path::blank(&this): path {
return path { _text = string::new(this._text.alloc), _root = 0 };
}
# Adds a segment to the end of a path being made, after a delimiter where the path
# already holds something past its root.
def path::push_segment(&mut this, part: strview): void {
if this._text.length > this._root {
this._text.push(path_delim);
}
this._text.append(part);
}
# Whether the path is `.`, the relative path with nothing in it.
def path::is_dot(&this): bool {
return this._root == 0 && this.view() == ".";
}
# Whether the path's root ends in a delimiter, so nothing is above it.
def path::is_rooted(&this): bool {
return this._root > 0 && this.view()[this._root - 1] == path_delim;
}
# Where the last segment begins, or the end of the text where there is none.
def path::last_start(&this): u64 {
val text := this.view();
if this.is_dot() {
return text.length;
}
var at := text.length;
while at > this._root && text[at - 1] != path_delim {
at--;
}
return at;
}
def path::is_delim(byte: u8): bool {
when os == windows {
return byte == '/' || byte == '\\';
}
return byte == path_delim;
}
# Writes the root the text starts with into the path's text, in normal form, and
# gives the index after it, or `nothing` where it starts as a share without
# naming one.
def path::read_root(text: strview, into: &mut string): maybe<u64> {
var at := 0u;
when os == windows {
if text.length >= 2 && path::is_delim(text[0]) && path::is_delim(text[1]) {
return path::read_share(text, into);
}
if text.length >= 2 && text[0].is_alpha && text[1] == ':' {
into.push(text[0].to_upper);
into.push(':');
at = 2;
if at == text.length || !path::is_delim(text[at]) {
return at;
}
}
}
if at < text.length && path::is_delim(text[at]) {
into.push(path_delim);
}
while at < text.length && path::is_delim(text[at]) {
at++;
}
return at;
}
# Writes a Windows share, as `\\server\share\`, into the path's text, and gives
# the index after it, or `nothing` where either name is missing.
def path::read_share(text: strview, into: &mut string): maybe<u64> {
var at := 2u;
into.push(path_delim);
into.push(path_delim);
for _ in 0..2 {
val start := at;
while at < text.length && !path::is_delim(text[at]) {
at++;
}
if at == start {
return nothing{};
}
into.append(text.substr(start, at - start));
into.push(path_delim);
while at < text.length && path::is_delim(text[at]) {
at++;
}
}
return at;
}
# Gives the index of the first byte of a segment that no path can hold, which is
# a zero byte, a delimiter, or one of `path_invalid_chars`.
def path::invalid_in(part: strview): maybe<u64> {
for index in 0..part.length {
val byte := part[index];
if byte == 0 || path::is_delim(byte) || path_invalid_chars.contains(&byte) {
return index;
}
}
return nothing{};
}
# Gives the index of the `.` before the extension of a name, or `0` where it has
# none, since a name starting with its only `.` is hidden rather than extended.
def path::dot_of(name: strview): u64 {
var at := name.length;
while at > 1 {
at--;
if name[at] == '.' {
return at;
}
}
return 0;
}
+46
View File
@@ -0,0 +1,46 @@
#! @file pipe.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `pipe`, the two ends of a pipe, each a `file`: what is written to
#! one is read from the other, as when a program talks with one it started.
import system;
module std::io;
#! The two ends of a pipe, each a `file` that closes where its scope ends: what
#! is written to one is read from the other.
#!
#! A program it starts inherits neither end, unless it is given one, as
#! `std::process` gives a child its streams. Reading the reading end ends once
#! every copy of the writing end is closed. Writing to the writing end once
#! nothing reads fails with `io_error::broken_pipe`, rather than stopping the
#! program, as `pipe::open` says.
pub struct pipe {
pub var reading: file; #! The end that is read.
pub var writing: file; #! The end that is written.
}
#! Makes a pipe.
#!
#! The first pipe the program makes has a write to a pipe nothing reads fail
#! with `io_error::broken_pipe`, rather than stopping the program, where the
#! program has not said otherwise of `system::signal::pipe` itself. Writing
#! to the program's own output or error once nothing reads it still stops the
#! program, quietly, as it would have before.
#! @returns The pipe, or why it could not be made.
pub def pipe::open(): result<pipe, io_error> {
var reading: system::fd = 0;
var writing: system::fd = 0;
val made := system::pipe(&mut reading, &mut writing);
if made < 0 {
return system::error_of(made);
}
return pipe {
reading = file { _handle = reading, _open = true },
writing = file { _handle = writing, _open = true }
};
}
+38
View File
@@ -0,0 +1,38 @@
#! @file readable.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the readable trait, which anything bytes are read from implements: a
#! file, the console, a reader, or a view of text.
import system;
module std::io;
#! Anything bytes are read from.
#!
#! A reference that writes, `&mut` one, is readable where what it refers to is,
#! so a generic given `&mut f` reads `f` without owning it, and `&mut readable`
#! reads whatever it refers to. One that only reads is not, since reading moves
#! where the next read starts.
pub trait readable {
#! Reads what has arrived, waiting only where nothing has.
#! @param this The stream to read.
#! @param into Where the bytes read are written.
#! @returns How many bytes were read, which may be fewer than there is room
#! for, and is zero only at the end, or why nothing could be read.
def read(&mut this, into: slice<u8>): result<u64, io_error>;
}
#! Reads bytes from the front of the view, which then views only what is left,
#! so a view of text is read as any stream is. A copy of the view reads the text
#! again.
#! @param this The view to read from, which shrinks by what is read.
#! @param into Where the bytes read are written.
#! @returns How many bytes were read, which is zero once the view is empty.
pub def strview::read(&mut this, into: slice<u8>): result<u64, io_error> {
val count := into.length < this.length ? into.length : this.length;
memcpy(into.data, this.data, count);
this = this.substr(count, this.length - count);
return count;
}
+318
View File
@@ -0,0 +1,318 @@
#! @file reader.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `reader`, which reads any stream through a buffer a line or a number
#! of bytes at a time, the standard input's reader, and `lines`, which walks
#! what a reader reads line by line.
import system;
module std::io;
# Bytes a reader asks what it reads for at a time.
const reader_bytes: u64 = 16384;
#! Reads any stream through a buffer, a line or a number of bytes at a time, and
#! is closed where its scope ends.
#!
#! A reader is made by `reader_of`, which owns or borrows what it reads as it is
#! given it: `reader_of(move(f))` owns the file `f` and closes it,
#! `reader_of(&mut f)` borrows it and closes nothing of it, and
#! `reader_of("text")` reads a view of text.
#!
#! The standard input is read through `io::input()`, which every part of the
#! program shares, so what one part leaves in its buffer the next part reads.
#!
#! Each read waits only for what it needs: a line waits for its line break, and
#! `read` gives whatever has arrived, so a reader serves a program that talks
#! with another as it goes, as a language server does.
#!
#! A wait that a signal the program handles ends fails with
#! `io_error::interrupted`, and leaves what was read of a line or of the bytes
#! asked for in the reader, so the next read carries on from it.
#! @tparam S The stream it reads, held by value where it owns it, or as `&mut`
#! where it borrows it.
pub struct reader<S> : owning, readable where S: readable {
var _source: S;
var _open: bool; #! Whether it reads, which one moved from, closed, or never made does not.
var _buffer: *mut u8; #! Null until the first read.
var _start: u64; #! The first byte of the buffer not yet read.
var _end: u64; #! The end of what the buffer holds.
var _tied: bool; #! Whether the standard output is flushed before waiting.
var _error: maybe<io_error>;
}
# The standard input, as `input()` lends it.
var standard_input: reader<console>;
#! Lends the reader of the standard input, which every part of the program
#! shares. It flushes `output()` before it waits for anything to arrive, so a
#! prompt written there shows first.
#! @returns The reader, which is never closed by the program ending.
pub def input(): &mut reader<console> {
standard_input._source._handle = system::fd::stdin;
standard_input._open = true;
standard_input._tied = true;
return &mut standard_input;
}
#! Reads the next line of the standard input, as `input().read_line` does.
#! @param alloc The optional allocator for the line to be held in.
#! @returns The line, without its line break, or `nothing` once the input has
#! ended or could not be read.
pub def read_line(alloc: maybe<&mut allocator> = nothing{}): maybe<string> {
hold_console(&mut input_held);
var line := input().read_line(alloc);
let_go_console(&mut input_held);
return move(&mut line);
}
#! Makes a reader of a stream, which owns what it is given: a stream given by
#! value, as `move(f)` or a temporary, is the reader's, and closed where it
#! closes, while one given by reference, as `&mut f`, is only borrowed.
#! @tparam S The stream to read, as it is given.
#! @param source The stream to read, from where it is.
#! @returns The reader.
pub def reader_of<S>(source: S): reader<S> where S: readable {
return reader::<S> { _source = move(source), _open = true };
}
#! Gives back the reader's buffer, and closes what it reads where it owns it.
#! Closing the reader of the standard input leaves the input open, and `input()`
#! lends it again. A reader that is closed, moved from, or never made reads
#! nothing, failing with `io_error::invalid`.
#! @param this The reader to close.
pub def reader<S>::close(&mut this): void {
raw_release(this._buffer);
this._buffer = null;
this._start = 0;
this._end = 0;
if !this._open {
return;
}
this._open = false;
close(&mut this._source);
}
#! Why the last read gave less than it was asked for, where it was a failure
#! rather than the end of the input.
#! @param this The reader to ask.
#! @returns The failure, or `nothing` where the last read did not fail.
pub val reader<S>::error: maybe<io_error> {
get => this._error;
}
#! Reads the next line, waiting until its line break has arrived.
#! @param this The reader to read.
#! @param alloc The optional allocator for the line to be held in.
#! @returns The line, without the `\n` that ends it or a `\r` before that, or
#! `nothing` once the input has ended, or could not be read, as `error`
#! then says. A last line without a line break is still a line.
pub def reader<S>::read_line(&mut this, alloc: maybe<&mut allocator> = nothing{}): maybe<string> {
this._error = nothing{};
var line := string::new(alloc);
var took: bool = false;
while true {
if this._start == this._end && !this.fill() {
if this.interrupted() {
this.put_back(line.view());
return nothing{};
}
if !took {
return nothing{};
}
return move(line);
}
took = true;
val waiting := strview::over(this._buffer + this._start, this._end - this._start);
var at := this._end;
if waiting.index_of(&'\n') is some(found) {
at = this._start + found;
}
line.append(strview::over(this._buffer + this._start, at - this._start));
if at == this._end {
this._start = this._end;
continue;
}
this._start = at + 1;
if line.length > 0 && line[line.length - 1] == '\r' {
line.resize(line.length - 1);
}
return move(line);
}
return nothing{};
}
#! Lends the lines the reader reads, each as `read_line` gives it, so a loop
#! walks them: `for line in input.lines()` closes each line where its pass ends.
#! @param this The reader to read.
#! @param alloc The optional allocator for the lines to be held in.
#! @returns The lines, which end where the input does, or where reading fails,
#! as the reader's `error` then says.
pub def reader<S>::lines(&mut this, alloc: maybe<&mut allocator> = nothing{}): lines<S> {
return lines::<S> { _from = this, _alloc = alloc };
}
#! Reads whatever has arrived, waiting only where nothing has.
#! @param this The reader to read.
#! @param into Where the bytes read are written.
#! @returns How many bytes were read, which is zero only at the end of the
#! input.
pub def reader<S>::read(&mut this, into: slice<u8>): result<u64, io_error> {
this._error = nothing{};
if into.length == 0 {
return 0u;
}
if !this._open {
return io_error::invalid;
}
# What is too large for the buffer to be worth passing through goes straight
# where it is wanted.
if this._start == this._end && into.length >= reader_bytes {
if this._tied {
_ = output().flush();
}
return this._source.read(into);
}
if this._start == this._end && !this.fill() {
if this._error is some(why) {
return why;
}
return 0u;
}
return this.take(into.data, into.length);
}
#! Reads an exact number of bytes, waiting until they have all arrived.
#! @param this The reader to read.
#! @param count How many bytes to read.
#! @param alloc The optional allocator for the bytes to be held in.
#! @returns The bytes, or why they could not all be read, which is
#! `io_error::unexpected_end` where the input ended first.
pub def reader<S>::read_exactly(
&mut this,
count: u64,
alloc: maybe<&mut allocator> = nothing{}
): result<string, io_error> {
this._error = nothing{};
var made := string::new(alloc);
made.reserve(count);
while made.length < count {
if this._start == this._end && !this.fill() {
if this.interrupted() {
this.put_back(made.view());
}
if this._error is some(why) {
return why;
}
return io_error::unexpected_end;
}
val left := count - made.length;
val have := this._end - this._start;
val take := left < have ? left : have;
made.append(span::<u8>::over(this._buffer + this._start, take));
this._start += take;
}
return move(made);
}
#! Reads the rest of the input, until it ends.
#! @param this The reader to read.
#! @param alloc The optional allocator for the bytes to be held in.
#! @returns The bytes, or why they could not all be read.
pub def reader<S>::read_all(&mut this, alloc: maybe<&mut allocator> = nothing{}): result<string, io_error> {
this._error = nothing{};
var made := string::new(alloc);
while true {
if this._start == this._end && !this.fill() {
if this.interrupted() {
this.put_back(made.view());
}
if this._error is some(why) {
return why;
}
return move(made);
}
made.append(span::<u8>::over(this._buffer + this._start, this._end - this._start));
this._start = this._end;
}
return move(made);
}
# Reads what has arrived into the buffer, which is empty, giving whether anything
# had, and keeping the failure where reading failed.
def reader<S>::fill(&mut this): bool {
if !this._open {
this._error = io_error::invalid;
return false;
}
if this._buffer == null {
this._buffer = raw_allocate(reader_bytes);
}
if this._tied {
_ = output().flush();
}
val count := this._source.read(slice::<u8>::over(this._buffer, reader_bytes)) else (why) {
this._error = why;
return false;
};
this._start = 0;
this._end = count;
return count > 0;
}
# Whether the last read failed because a signal the program handles ended its
# wait.
def reader<S>::interrupted(&this): bool {
if this._error is some(why) {
return why == io_error::interrupted;
}
return false;
}
# Puts bytes taken from the buffer back in it, which holds nothing more, so the
# next read finds them first, growing it where they are more than it holds.
def reader<S>::put_back(&mut this, bytes: span<u8>): void {
if bytes.length > reader_bytes {
this._buffer = raw_resize(this._buffer, bytes.length);
}
memcpy(this._buffer, bytes.data, bytes.length);
this._start = 0;
this._end = bytes.length;
}
# Copies as much of what the buffer holds as fits, giving how much that was.
def reader<S>::take(&mut this, into: *mut u8, length: u64): u64 {
val have := this._end - this._start;
val count := length < have ? length : have;
memcpy(into, this._buffer + this._start, count);
this._start += count;
return count;
}
#! The lines a reader reads, as `reader::lines` lends them, each a `string` the
#! loop walking them owns.
#! @tparam S The stream the reader walked reads.
pub struct lines<S> : iterator<string> where S: readable {
var _from: &mut reader<S>;
var _alloc: maybe<&mut allocator>;
}
#! Reads the next line.
#! @param this The lines to advance.
#! @returns The line, or `nothing` once the reader has none left.
pub def lines<S>::next(&mut this): maybe<string> {
return this._from.read_line(this._alloc);
}
+20
View File
@@ -0,0 +1,20 @@
#! @file seekable.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the seekable trait, which a stream whose position can be moved
#! implements, as a file does.
import system;
module std::io;
#! A stream whose position, where the next read or write happens, can be moved.
pub trait seekable {
#! Moves the position.
#! @param this The stream whose position to move.
#! @param offset The offset to move to.
#! @param from Where the offset is measured from.
#! @returns The new position, from the start, or why it could not be moved.
def seek(&mut this, offset: i64, from: whence): result<u64, io_error>;
}
+72
View File
@@ -0,0 +1,72 @@
#! @file streams.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `copy_all` and `read_all`, which use any stream while they run: one
#! copies a stream to its end into another, the other reads one to its end into
#! a `string`.
import system;
module std::io;
# These only use a stream while they run, so they borrow it as a trait reference:
# what keeps a stream, as a reader or writer does, is generic over it instead.
# Bytes copied at a time.
const copy_bytes: u64 = 16384;
#! Copies everything a stream has left into another, until it ends.
#! @param from The stream to read, to its end.
#! @param to The stream to write, which is not flushed: whoever made it does
#! that.
#! @returns How many bytes were copied, or why reading or writing failed.
pub def copy_all(from: &mut readable, to: &mut writable): result<u64, io_error> {
val chunk := raw_allocate(copy_bytes);
var total := 0u;
while true {
val count := from.read(slice::<u8>::over(chunk, copy_bytes)) else (why) {
raw_release(chunk);
return why;
};
if count == 0 {
break;
}
to.write(span::<u8>::over(chunk as *u8, count)) else (why) {
raw_release(chunk);
return why;
};
total += count;
}
raw_release(chunk);
return total;
}
#! Reads everything a stream has left, until it ends.
#! @param from The stream to read.
#! @param alloc The optional allocator for the bytes to be held in.
#! @returns The bytes, or why they could not all be read.
pub def read_all(from: &mut readable, alloc: maybe<&mut allocator> = nothing{}): result<string, io_error> {
var made := string::new(alloc);
made.reserve(copy_bytes);
while true {
if made.length == made.capacity {
made.reserve(made.capacity * 2);
}
# The read fills the room made, which is then cut back to what it read.
val had := made.length;
made.resize(made.capacity);
val count := from.read(made.slice()[had:]) else (why) {
return why;
};
made.resize(had + count);
if count == 0 {
break;
}
}
return move(made);
}
+39
View File
@@ -0,0 +1,39 @@
#! @file writable.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the writable trait, which anything bytes are written to implements: a
#! file, the console, a writer, or a string.
import system;
module std::io;
#! Anything bytes are written to.
#!
#! A write writes all of what it is given, or gives why it could not, so a
#! caller never writes the rest again. Something that holds bytes back before
#! passing them on is also `flushable`, and whoever made it flushes it: code
#! given a `&mut writable` only writes.
#!
#! A reference that writes, `&mut` one, is writable where what it refers to is,
#! so a generic given `&mut s` writes `s` without owning it.
pub trait writable {
#! Writes all of some bytes.
#! @param this The stream to write.
#! @param data The bytes to write.
#! @returns Why they could not all be written, where they could not.
def write(&mut this, data: span<u8>): result<void, io_error>;
}
#! Writes bytes after the last, as a stream is written, so a string is given
#! where anything `writable` is wanted, as a test gives one to collect what is
#! written.
#! @param this The string to write to.
#! @param data The bytes to write.
#! @returns Nothing, since a string always takes them: an allocator that gives
#! no more memory stops the program.
pub def string::write(&mut this, data: span<u8>): result<void, io_error> {
this.append(data);
return;
}
+208
View File
@@ -0,0 +1,208 @@
#! @file writer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `writer`, which holds what it is given and writes it to any stream
#! in larger pieces, and the standard output's and standard error's writers.
import system;
module std::io;
# Bytes a writer holds before it writes them.
const writer_bytes: u64 = 16384;
# When a writer writes what it holds, besides when it fills, is flushed, or closes.
enum writer_flushing: u8 {
when_full, #! Any writer `writer_of` makes.
at_lines, #! The standard output's: once it is given a line break.
at_writes, #! The standard error's: after every write.
}
#! Writes any stream through a buffer, and is closed where its scope ends,
#! writing what it still holds first.
#!
#! A writer is made by `writer_of`, which owns or borrows what it writes as it
#! is given it: `writer_of(move(f))` owns the file `f` and closes it, while
#! `writer_of(&mut f)` and `writer_of(&mut text)` borrow what they write to and
#! close nothing of it. It writes what it holds only once its buffer fills, it
#! is flushed, or it closes, which saves asking the system to write each piece.
#!
#! The standard output is written through `io::output()`, and the standard error
#! through `io::error_output()`, which every part of the program shares, as
#! `print` does. The standard output's writer writes what it holds once it is
#! given a line break, and the standard error's after every write.
#!
#! Neither shared writer is closed when the program ends, so text given to
#! `io::output()` after its last line break is written only once it is flushed,
#! or once `print` writes, since `print` flushes every time. Reading the
#! standard input flushes it too, so a prompt shows before the program waits for
#! an answer.
#! @tparam S The stream it writes, held by value where it owns it, or as `&mut`
#! where it borrows it.
pub struct writer<S> : owning, writable, flushable where S: writable {
pub var _sink: S; #! The stream written, which std's tests read.
var _open: bool; #! Whether it writes, which one moved from, closed, or never made does not.
var _buffer: *mut u8; #! Null until the first write.
var _length: u64; #! How much of the buffer is held, yet to be written.
var _flush: writer_flushing;
var _error: maybe<io_error>;
}
# The standard output and error, as `output()` and `error_output()` lend them.
var standard_output: writer<console>;
var standard_error: writer<console>;
#! Lends the writer of the standard output, which every part of the program
#! shares, and which writes what it holds once it is given a line break.
#! @returns The writer, which is never closed by the program ending.
pub def output(): &mut writer<console> {
standard_output._sink._handle = system::fd::stdout;
standard_output._open = true;
standard_output._flush = writer_flushing::at_lines;
return &mut standard_output;
}
#! Lends the writer of the standard error, which every part of the program
#! shares, and which writes what it is given at once.
#! @returns The writer, which is never closed by the program ending.
pub def error_output(): &mut writer<console> {
standard_error._sink._handle = system::fd::stderr;
standard_error._open = true;
standard_error._flush = writer_flushing::at_writes;
return &mut standard_error;
}
#! Makes a writer of a stream, which owns what it is given: a stream given by
#! value, as `move(f)` or a temporary, is the writer's, and closed where it
#! closes, while one given by reference, as `&mut f`, is only borrowed.
#! @tparam S The stream to write, as it is given.
#! @param sink The stream to write, from where it is.
#! @returns The writer.
pub def writer_of<S>(sink: S): writer<S> where S: writable {
return writer::<S> { _sink = move(sink), _open = true };
}
#! Writes what the writer holds, gives back its buffer, and closes what it
#! writes where it owns it. Closing the writer of the standard output or error
#! leaves it open, and `output()` or `error_output()` lends it again. A writer
#! that is closed, moved from, or never made writes nothing, failing with
#! `io_error::invalid`.
#! @param this The writer to close.
#! @remarks Closing cannot say whether what the writer held was written, and
#! keeps the failure in `error`, so a program that needs to know
#! flushes first.
pub def writer<S>::close(&mut this): void {
_ = this.flush();
raw_release(this._buffer);
this._buffer = null;
this._length = 0;
if !this._open {
return;
}
this._open = false;
close(&mut this._sink);
}
#! Why the last time the writer wrote what it held failed, where it did.
#! @param this The writer to ask.
#! @returns The failure, or `nothing` where the last write did not fail.
pub val writer<S>::error: maybe<io_error> {
get => this._error;
}
#! Gives the writer bytes to write, which it holds until it writes them.
#! @param this The writer to give them to.
#! @param data The bytes to write, which may be a literal, a view of one, or
#! the text a `string` lends.
#! @returns Why what the writer held could not be written, where writing it to
#! make room, or because a line ended, failed.
pub def writer<S>::write(&mut this, data: span<u8>): result<void, io_error> {
if !this._open {
return io_error::invalid;
}
if data.length == 0 {
return;
}
if this._length + data.length > writer_bytes {
this.pass() else (e) { return e; };
# What is too large for the buffer to be worth passing through goes straight
# to what the writer writes.
if data.length >= writer_bytes {
return this.wrote(this._sink.write(data));
}
}
if this._buffer == null {
this._buffer = raw_allocate(writer_bytes);
}
memcpy(this._buffer + this._length, data.data, data.length);
this._length += data.length;
if this._flush == writer_flushing::at_writes {
return this.pass();
}
if this._flush == writer_flushing::at_lines && holds_line_break(data) {
return this.pass();
}
return;
}
#! Gives the writer text, then a line break, to write.
#! @param this The writer to give them to.
#! @param text The text to write before the line break.
#! @returns Why what the writer held could not be written, where it could not.
pub def writer<S>::write_line(&mut this, text: strview): result<void, io_error> {
this.write(text) else (e) { return e; };
return this.write("\n");
}
#! Writes everything the writer holds, then flushes what it writes to, where
#! that holds bytes back too, so writers stacked on one another flush all the
#! way down.
#! @param this The writer to flush.
#! @returns Why it could not all be written, where it could not, in which case
#! what was held is let go of, rather than written again by the next
#! flush.
pub def writer<S>::flush(&mut this): result<void, io_error> {
this.pass() else (e) { return e; };
if const S is flushable {
if this._open {
return this.wrote(this._sink.flush());
}
}
return;
}
# Writes everything the writer holds to what it writes, without flushing that.
def writer<S>::pass(&mut this): result<void, io_error> {
this._error = nothing{};
if this._length == 0 {
return;
}
val count := this._length;
this._length = 0;
return this.wrote(this._sink.write(span::<u8>::over(this._buffer as *u8, count)));
}
# Keeps the failure of a write, where it failed, and gives it back.
def writer<S>::wrote(&mut this, outcome: result<void, io_error>): result<void, io_error> {
if outcome is error(why) {
this._error = why;
}
return outcome;
}
# Whether some bytes hold a line break.
def holds_line_break(data: span<u8>): bool {
for byte in data {
if byte == '\n' {
return true;
}
}
return false;
}
+53
View File
@@ -0,0 +1,53 @@
# std::json
`std::json` reads and writes JSON for Sakura, strictly, as RFC 8259 writes it:
any value may stand alone, text must be UTF-8, and comments, trailing commas,
`NaN`, `Infinity`, and single quotes are errors. `json::parse` reads text into a
`json::document`, which holds every value of it, `json::reader` gives one token
at a time, and `json::writer` writes JSON as it is given it. A value whose type
marks its fields with `@serial` is written as JSON and read back by those marks,
over `std::serial`.
## Using it
Require the standard library in your blossomfile, and name the module among a
target's `deps`, with the other modules of std it reads:
```yaml
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
targets:
- name: app
type: program
deps: [std.json, std.io]
```
```sakura
import std::io;
import std::json;
def main(): void {
val read := json::parse("{\"name\": \"sakura\", \"stars\": 5}") else (_) {
io::println("That isn't JSON.");
return;
};
if read.root.get("name") is some(name) {
if name.as_text() is value(text) {
io::println(text);
}
}
}
```
## Testing
From the standard library's root, where the conformance test finds its suite,
`blossom test --only std.json` runs them, or:
```sh
sakurac run --lib std=. tests/main.sakura tests/json/*.sakura
```
The conformance test reads each file of JSONTestSuite's `test_parsing`, in
`tests/json/parsing`, whose license is beside it.
+652
View File
@@ -0,0 +1,652 @@
#! @file document.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the parsed document, which holds every value of JSON text as a flat
#! array of nodes, and `json::value`, which reads one of them.
module std::json;
#! The kinds of JSON values.
pub enum kind: u8 {
empty, #! `null`.
boolean, #! `true` or `false`.
number, #! A number.
text, #! A string.
array, #! A list of values, in order.
object, #! Members, each a key and a value.
}
# What a node is: the kinds of values, then a member's name.
enum node_kind: u8 {
empty,
boolean,
number,
text,
array,
object,
key,
}
# One value of a document, or a member's name, in 16 bytes.
#
# A value's nodes follow it, so an array's elements follow it in order, and an
# object's members do, each as its key and then its value. A container's `length`
# is how many elements or members it holds, and its `next` is the index just past
# everything it holds, so a value is skipped in one step. A string's `start` is
# where its opening quote is, and its text follows that for `length` bytes, unless
# it holds escapes: then its decoded text is in the document's buffer, from `next`.
struct node {
var kind: node_kind;
var flag: u8; #! Whether a string holds escapes, or a boolean is true.
var spare: u16;
var start: u32; #! The byte of the text the value begins at.
var length: u32;
var next: u32;
}
#! JSON text read whole, every value of it held as a node of a flat array.
#!
#! A document views the text it was parsed from, which must outlive it, and the
#! values it gives view the document, so they are good only while it lives. A
#! string holding escapes is decoded once, as the document is parsed, so reading
#! any string allocates nothing.
pub struct document : serial::decoder, moveable {
var _text: strview;
var _nodes: vector<node>;
var _decoded: string; #! The text of each string that holds escapes, decoded.
}
#! A value of a document, by its place in it. It is good only while the document
#! lives and stays where it is.
#!
#! A value writes itself through any format, as `serial::encode` writes a typed
#! value, so a document's values are written again whole.
pub struct value : serial::encodable {
var _document: *document;
var _at: u32;
}
#! A member of an object, as `value::members` gives each.
pub struct member {
pub var key: strview; #! The member's key, still escaped where it holds escapes.
pub var value: value; #! Its value.
}
#! Reads JSON text whole into a document.
#! @param text The text, which must outlive the document and every value of
#! it.
#! @param depth How deep values may nest before parsing fails with `too_deep`.
#! @param alloc An optional allocator for the document to take memory from.
#! @returns The document, or why the text is not JSON, with where it fails.
pub def parse(text: strview, depth: u32 = default_depth, alloc: maybe<&mut allocator> = nothing {}): result<document, error> {
if text.length > 0xFFFFFFFFu {
return error { kind = error_kind::too_long };
}
var made := document {
_text = text,
_nodes = vector::<node>::new(alloc),
_decoded = string::new(alloc)
};
# The open objects and arrays, by their nodes.
var open := vector::<u32>::new(alloc);
var tokens := reader::new(text, depth);
while tokens.next() is some(read) {
val at := read.offset as u32;
match read.kind {
begin_object => {
made.count_in(&open);
open.append(made._nodes.length as u32);
made._nodes.append(node { kind = node_kind::object, start = at });
}
begin_array => {
made.count_in(&open);
open.append(made._nodes.length as u32);
made._nodes.append(node { kind = node_kind::array, start = at });
}
end_object, end_array => {
val closing: u32 = open.at(open.length - 1);
made._nodes.at(closing as u64).next = made._nodes.length as u32;
open.remove_at(open.length - 1);
}
key => {
val holder: u32 = open.at(open.length - 1);
made._nodes.at(holder as u64).length++;
made.add_string(node_kind::key, &read);
}
text => {
made.count_in(&open);
made.add_string(node_kind::text, &read);
}
number => {
made.count_in(&open);
made._nodes.append(node { kind = node_kind::number, start = at, length = read.view.length as u32 });
}
boolean => {
made.count_in(&open);
made._nodes.append(node { kind = node_kind::boolean, flag = read.truth ? 1 : 0, start = at });
}
empty => {
made.count_in(&open);
made._nodes.append(node { kind = node_kind::empty, start = at });
}
}
}
if tokens.error is some(failed) {
return failed;
}
return move(made);
}
#! Creates a document by taking another's nodes and decoded text, which leaves
#! the other holding nothing.
#! @param other The document to move from.
#! @returns The document, which views the same text.
pub def document::move_of(other: &mut document): document {
return document {
_text = other._text,
_nodes = move(other._nodes),
_decoded = move(other._decoded)
};
}
#! The value the text holds, which holds the rest.
#! @param this The document to read.
#! @returns The value.
pub val document::root: value {
get => value { _document = this as *document, _at = 0 };
}
#! The text the document was parsed from.
#! @param this The document to ask.
#! @returns The text.
pub val document::text: strview {
get => this._text;
}
#! What kind of value the value is.
#! @param this The value to ask.
#! @returns Its kind.
pub val value::kind: kind {
get => (*this._document).kind_at(this._at);
}
#! Whether the value is `null`.
#! @param this The value to ask.
#! @returns Whether it is.
pub val value::is_null: bool {
get => this.kind == kind::empty;
}
#! How many elements an array holds, or members an object holds, repeats
#! included.
#! @param this The value to measure.
#! @returns The count, which is 0 for any other value.
pub val value::length: u64 {
get => (*this._document).count(this._at);
}
#! Where the value begins in the text, by its line and its column.
#! @param this The value to place.
#! @returns Where it is.
pub val value::place: serial::place {
get => (*this._document).place(this._at);
}
#! Finds the first member of an object with a name.
#! @param this The object to look in, which an object is searched member by
#! member.
#! @param key The name to look for, as it is decoded.
#! @returns The member's value, or `nothing` where the value is not an object or
#! has no member of the name.
pub def value::get(&this, key: strview): maybe<value> {
val found := (*this._document).member(this._at, key) else { return nothing {}; };
return value { _document = this._document, _at = found };
}
#! Iterates over the values of every member of an object with a name, in the
#! order they are written, since a name may be given more than once.
#! @param this The object to look in.
#! @param key The name to look for, as it is decoded.
#! @returns An iterator over the values, which gives none where the value is not
#! an object.
pub def value::get_all(&this, key: strview): value::match_cursor {
val count := (*this._document).count(this._at);
val first: u32 = count == 0 ? 0 : this._at + 1;
return value::match_cursor { _document = this._document, _at = first, _left = count, _key = key };
}
#! Finds an element of an array by its index.
#! @param this The array to look in.
#! @param index The element's index, counted from 0.
#! @returns The element, or `nothing` where the value is not an array or is
#! shorter.
pub def value::at(&this, index: u64): maybe<value> {
if this.kind != kind::array || index >= this.length {
return nothing {};
}
return value { _document = this._document, _at = (*this._document).element(this._at, index) };
}
#! Iterates over the elements of an array, in order.
#! @param this The array to walk.
#! @returns An iterator over them, which gives none where the value is not an
#! array.
pub def value::elements(&this): value::element_cursor {
if this.kind != kind::array {
return value::element_cursor { _document = this._document };
}
return value::element_cursor { _document = this._document, _at = this._at + 1, _left = this.length };
}
#! Iterates over the members of an object, in the order they are written,
#! repeats included.
#! @param this The object to walk.
#! @returns An iterator over them, which gives none where the value is not an
#! object.
pub def value::members(&this): value::member_cursor {
if this.kind != kind::object {
return value::member_cursor { _document = this._document };
}
return value::member_cursor { _document = this._document, _at = this._at + 1, _left = this.length };
}
#! Reads a boolean.
#! @param this The value to read.
#! @returns Its truth, or `wrong_kind` where it is not a boolean.
pub def value::as_bool(&this): result<bool, error> {
return (*this._document).as_bool(this._at) else (e) { return error::from(&e); };
}
#! Reads a number as a signed integer, exactly.
#! @param this The value to read.
#! @returns The integer, or `wrong_kind` where it is not a number without a
#! fraction, or `out_of_range` where it does not fit.
pub def value::as_i64(&this): result<i64, error> {
return (*this._document).as_i64(this._at) else (e) { return error::from(&e); };
}
#! Reads a number as an unsigned integer, exactly.
#! @param this The value to read.
#! @returns The integer, or `wrong_kind` where it is not a number without a
#! fraction, or `out_of_range` where it is negative or does not fit.
pub def value::as_u64(&this): result<u64, error> {
return (*this._document).as_u64(this._at) else (e) { return error::from(&e); };
}
#! Reads a number as the nearest 64-bit float.
#! @param this The value to read.
#! @returns The float, or `wrong_kind` where it is not a number, or
#! `out_of_range` where it is too large for 64 bits.
pub def value::as_f64(&this): result<f64, error> {
return (*this._document).as_f64(this._at) else (e) { return error::from(&e); };
}
#! Reads a string, decoded.
#! @param this The value to read.
#! @returns A view of its text, good while the document lives, or `wrong_kind`
#! where it is not a string.
pub def value::as_text(&this): result<strview, error> {
return (*this._document).as_text(this._at) else (e) { return error::from(&e); };
}
#! Writes the value and everything it holds through a format. A number is
#! written as an integer where it is one that fits, and as the nearest float
#! otherwise.
#! @param this The value to write.
#! @param out The format to write it through.
pub def value::encode(&this, out: &mut serial::encoder): void {
match this.kind {
empty => out.empty();
boolean => out.boolean((*this._document).node_at(this._at).flag != 0);
text => out.text((*this._document).text_at(this._at));
number => this.encode_number(out);
array => {
out.begin_array(this.length);
for item in this.elements() {
item.encode(out);
}
out.end_array();
}
object => {
out.begin_object(this.length);
for each in this.members() {
out.member(each.key);
each.value.encode(out);
}
out.end_object();
}
}
}
# Writes a number as an integer where it is one that fits, and otherwise as the
# nearest float, or as nothing where it is too large for one, keeping the failure.
def value::encode_number(&this, out: &mut serial::encoder): void {
# Read once as an integer, since asking for one that is not makes an error, and
# working out where it is reads the text up to it.
val read := serial::integral_of((*this._document).number_at(this._at));
val limit: u64 = read.negative ? 0x8000000000000000u : 0x7FFFFFFFFFFFFFFFu;
if read.whole && read.fits && read.magnitude <= limit {
out.signed(read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64);
return;
}
if read.whole && read.fits && !read.negative {
out.unsigned(read.magnitude);
return;
}
match (*this._document).as_f64(this._at) {
value(real) => out.real(real);
error(_) => {
out.fail(serial::error_kind::out_of_range);
out.empty();
}
}
}
#! An iterator over an array's elements.
pub struct value::element_cursor : iterator<value> {
var _document: *document;
var _at: u32;
var _left: u64;
}
#! Gives the next element of the array.
#! @param this The cursor to advance.
#! @returns The next element, or `nothing` once there are no more.
pub def value::element_cursor::next(&mut this): maybe<value> {
if this._left == 0 {
return nothing {};
}
val made := value { _document = this._document, _at = this._at };
this._at = (*this._document).after(this._at);
this._left--;
return made;
}
#! An iterator over an object's members.
pub struct value::member_cursor : iterator<member> {
var _document: *document;
var _at: u32; #! The next member's key.
var _left: u64;
}
#! Gives the next member of the object, in the order the text writes them.
#! @param this The cursor to advance.
#! @returns The next member, or `nothing` once there are no more.
pub def value::member_cursor::next(&mut this): maybe<member> {
if this._left == 0 {
return nothing {};
}
val made := member {
key = (*this._document).text_at(this._at),
value = value { _document = this._document, _at = this._at + 1 }
};
this._at = (*this._document).after(this._at + 1);
this._left--;
return made;
}
#! An iterator over the values of an object's members of one name.
pub struct value::match_cursor : iterator<value> {
var _document: *document;
var _at: u32; #! The next member's key.
var _left: u64;
var _key: strview;
}
#! Gives the value of the next member of the name.
#! @param this The cursor to advance.
#! @returns The next value, or `nothing` once no member left has the name.
pub def value::match_cursor::next(&mut this): maybe<value> {
while this._left > 0 {
val key := this._at;
this._at = (*this._document).after(key + 1);
this._left--;
if (*this._document).text_at(key) == this._key {
return value { _document = this._document, _at = key + 1 };
}
}
return nothing {};
}
#! What kind of value a node is.
#! @param this The document to read.
#! @param at The value's index.
#! @returns Its kind.
pub def document::kind_of(&this, at: u32): serial::kind {
return (this.kind_at(at) as u8) as serial::kind;
}
#! Finds the value of the first member of an object with a name.
#! @param this The document to read.
#! @param at The object's index.
#! @param name The name to look for, as it is decoded.
#! @returns The member's value's index, or `nothing` where there is none of the
#! name or the value is not an object.
pub def document::member(&this, at: u32, name: strview): maybe<u32> {
if this.node_at(at).kind != node_kind::object {
return nothing {};
}
var key := at + 1;
for _ in 0..this.node_at(at).length as u64 {
if this.text_at(key) == name {
return key + 1;
}
key = this.after(key + 1);
}
return nothing {};
}
#! How many elements an array holds, or members an object holds, repeats
#! included.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The count, which is 0 for any other value.
pub def document::count(&this, at: u32): u64 {
val held := this.node_at(at);
if held.kind != node_kind::array && held.kind != node_kind::object {
return 0;
}
return held.length as u64;
}
#! The name of the member of an object whose value is given.
#! @param this The document to read.
#! @param value The member's value's index.
#! @returns The name, decoded.
pub def document::name_of(&this, value: u32): strview {
return this.text_at(value - 1);
}
#! The element of an array, or the value of a member of an object, after
#! another.
#! @param this The document to read.
#! @param at The array's or object's index.
#! @param previous The element or value before, which must not be the last.
#! @returns The value's index.
pub def document::next_element(&this, at: u32, previous: u32): u32 {
val next := this.after(previous);
return this.node_at(at).kind == node_kind::object ? next + 1 : next;
}
#! An element of an array, or the value of a member of an object, by its index.
#! @param this The document to read.
#! @param at The array's or object's index.
#! @param index Which element or member, which must be less than the count.
#! @returns The value's index.
pub def document::element(&this, at: u32, index: u64): u32 {
val object := this.node_at(at).kind == node_kind::object;
var held := object ? at + 2 : at + 1;
for _ in 0..index {
held = this.after(held);
if object {
held++;
}
}
return held;
}
#! Reads a string's text, decoded.
#! @param this The document to read.
#! @param at The value's index.
#! @returns A view of the text, or `wrong_kind` where the value is not a string.
pub def document::as_text(&this, at: u32): result<strview, serial::error> {
if this.node_at(at).kind != node_kind::text {
return this.wrong(at);
}
return this.text_at(at);
}
#! Reads a value as a signed integer, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The integer, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is not an integer `i64` holds.
pub def document::as_i64(&this, at: u32): result<i64, serial::error> {
val read := this.integral_at(at) else (e) { return e; };
val limit: u64 = read.negative ? 0x8000000000000000u : 0x7FFFFFFFFFFFFFFFu;
if !read.fits || read.magnitude > limit {
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
}
return read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64;
}
#! Reads a value as an unsigned integer, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The integer, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is not an integer `u64` holds.
pub def document::as_u64(&this, at: u32): result<u64, serial::error> {
val read := this.integral_at(at) else (e) { return e; };
if !read.fits || (read.negative && read.magnitude != 0) {
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
}
return read.magnitude;
}
#! Reads a value as a real number, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The number, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is too large for an `f64`.
pub def document::as_f64(&this, at: u32): result<f64, serial::error> {
if this.node_at(at).kind != node_kind::number {
return this.wrong(at);
}
match real::parse::<f64>(this.number_at(at)) {
value(read) => return read;
error(&_) => return serial::error::at(
serial::error_kind::out_of_range, this.place(at));
}
return 0.0;
}
#! Reads a value as `true` or `false`, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The value, or `wrong_kind` where it is not a boolean.
pub def document::as_bool(&this, at: u32): result<bool, serial::error> {
val held := this.node_at(at);
if held.kind != node_kind::boolean {
return this.wrong(at);
}
return held.flag != 0;
}
#! Where a value begins in the text, by its line and its column.
#! @param this The document to read.
#! @param at The value's index.
#! @returns Where it is.
pub def document::place(&this, at: u32): serial::place {
return serial::place_of(this._text, this.node_at(at).start as u64);
}
# Counts a value as an element of the innermost open array; an object counts its
# members by their keys.
def document::count_in(&mut this, open: &vector<u32>): void {
if open.length == 0 {
return;
}
val holder: u32 = open.at(open.length - 1);
if this._nodes.at(holder as u64).kind == node_kind::array {
this._nodes.at(holder as u64).length++;
}
}
# Adds a string or key, decoding its escapes into the buffer where it holds any.
def document::add_string(&mut this, kind: node_kind, read: &token): void {
if !read.escaped {
this._nodes.append(node { kind = kind, start = read.offset as u32, length = read.view.length as u32 });
return;
}
val from := this._decoded.length;
unescape(read.view, &mut this._decoded);
this._nodes.append(node {
kind = kind,
flag = 1,
start = read.offset as u32,
length = (this._decoded.length - from) as u32,
next = from as u32
});
}
def document::node_at(&this, at: u32): &node {
return this._nodes.at(at as u64);
}
def document::kind_at(&this, at: u32): kind {
val held := this.node_at(at).kind;
return held == node_kind::key ? kind::text : (held as u8) as kind;
}
# The index just past a value and everything it holds.
def document::after(&this, at: u32): u32 {
val held := this.node_at(at);
if held.kind == node_kind::array || held.kind == node_kind::object {
return held.next;
}
return at + 1;
}
# A string's or key's text, decoded.
def document::text_at(&this, at: u32): strview {
val held := this.node_at(at);
if held.flag != 0 {
return this._decoded.substr(held.next as u64, held.length as u64);
}
return this._text.substr(held.start as u64 + 1, held.length as u64);
}
# A number's text.
def document::number_at(&this, at: u32): strview {
val held := this.node_at(at);
return this._text.substr(held.start as u64, held.length as u64);
}
# A number read as an integer exactly, or why it is not one.
def document::integral_at(&this, at: u32): result<serial::integral, serial::error> {
if this.node_at(at).kind != node_kind::number {
return this.wrong(at);
}
val read := serial::integral_of(this.number_at(at));
if !read.whole {
return this.wrong(at);
}
return read;
}
def document::wrong(&this, at: u32): serial::error {
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
}
+180
View File
@@ -0,0 +1,180 @@
#! @file json.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains JSON's errors, and the functions that write a value as JSON and read
#! one back by what `@serial` marks of its type, over `std::serial`.
#!
#! JSON is read strictly, as RFC 8259 writes it: any value may stand alone, text
#! must be UTF-8, and comments, trailing commas, `NaN`, `Infinity`, and single
#! quotes are errors. `json::parse` reads text into a `json::document`, which holds
#! every value of it, `json::reader` gives one token at a time, and `json::writer`
#! writes JSON as it is given it.
import std::io;
module std::json;
#! Why JSON could not be read or written.
pub enum error_kind: u8 {
unexpected_end, #! The text ends before the value does.
unexpected_byte, #! A byte stands where JSON allows none of its kind.
invalid_escape, #! A string holds an escape JSON has not, or half a surrogate pair.
invalid_utf8, #! Text is not UTF-8.
invalid_number, #! A number breaks JSON's grammar, as `01`, `1.`, or `.5` do.
too_deep, #! Values nest deeper than the limit the text was read with.
too_long, #! The text is longer than the 4 GiB a document holds.
trailing_text, #! Something follows the value.
not_finite, #! A number written is infinite or NaN, which JSON cannot hold.
not_written, #! The stream the text was passed on to failed, as its own error says.
# What `std::serial` finds reading and writing typed values, as its own kinds say.
wrong_kind, #! A value is of another kind than the type asked for, as text for a number.
missing_member, #! An object lacks a member for a field that is not a `maybe`.
unknown_member, #! An object has a member no field takes, which only strict reading refuses.
repeated_member, #! An object has a member twice, which only strict reading refuses.
out_of_range, #! A number does not fit the type asked for, or a name is no member's.
not_serial, #! A value holds an enum member or union field that is not `@serial`.
}
#! Why JSON could not be read or written, and where in the text.
#!
#! An error is plain data, so `else (e)` names it. One from writing has no
#! place, and is at line 0.
pub struct error {
pub var kind: error_kind; #! What went wrong.
pub var offset: u64; #! The byte of the text the error is at.
pub var line: u32; #! Counted from 1.
pub var column: u32; #! The byte within the line, counted from 1.
}
#! Says what the error is, in a sentence, after where it is.
#! @param this The error to describe.
#! @returns The description, as `1:5: The text ends before the value does.`
pub def error::describe(&this): string {
if this.line == 0 {
return string::from(describe(this.kind), nothing {});
}
return $"{this.line}:{this.column}: {describe(this.kind)}";
}
#! Says what a kind of error is, in a sentence.
#! @param kind The kind to describe.
#! @returns The sentence.
pub def describe(kind: error_kind): strview {
return match kind {
unexpected_end => "The text ends before the value does.",
unexpected_byte => "A byte stands where JSON allows none of its kind.",
invalid_escape => "A string holds an escape JSON does not have, or half of a surrogate pair.",
invalid_utf8 => "The text is not UTF-8.",
invalid_number => "A number does not follow JSON's grammar.",
too_deep => "Values nest deeper than the limit the text is read with.",
too_long => "The text is longer than the 4 GiB a document holds.",
trailing_text => "Something follows the value.",
not_finite => "A number is infinite or NaN, which JSON cannot hold.",
not_written => "The stream the text was written to failed, as its own error says.",
wrong_kind => serial::describe(serial::error_kind::wrong_kind),
missing_member => serial::describe(serial::error_kind::missing_member),
unknown_member => serial::describe(serial::error_kind::unknown_member),
repeated_member => serial::describe(serial::error_kind::repeated_member),
out_of_range => serial::describe(serial::error_kind::out_of_range),
not_serial => serial::describe(serial::error_kind::not_serial),
};
}
#! The error JSON gives for one `std::serial` gives, at the same place.
#! @param problem The error reading or writing a typed value gave.
#! @returns The error.
pub def error::from(problem: &serial::error): error {
return error {
kind = of_serial(problem.kind),
offset = problem.offset,
line = problem.line,
column = problem.column
};
}
# The kind of JSON's error for a kind of `std::serial`'s.
def of_serial(kind: serial::error_kind): error_kind {
return match kind {
wrong_kind => error_kind::wrong_kind,
missing_member => error_kind::missing_member,
unknown_member => error_kind::unknown_member,
repeated_member => error_kind::repeated_member,
out_of_range => error_kind::out_of_range,
not_serial => error_kind::not_serial,
};
}
# An error of a kind at a byte of the text.
def error_at(kind: error_kind, text: strview, offset: u64): error {
val at := serial::place_of(text, offset);
return error { kind = kind, offset = offset, line = at.line, column = at.column };
}
#! Writes a typed value through a writer, by what `@serial` marks of its type,
#! or the form of its own the type gives, among whatever else the writer is
#! given.
#! @tparam T The type of the value.
#! @param value The value to write.
#! @param out The writer to write it with.
pub def encode<T>(value: &T, out: &mut writer): void {
serial::encode(value, out);
}
#! Writes a typed value as JSON text, by what `@serial` marks of its type.
#! @tparam T The type of the value.
#! @param value The value to write.
#! @param indent Spaces for each level of nesting, or 0 to write it on one
#! line.
#! @param alloc An optional allocator for the text to take memory from.
#! @returns The text, or the first failure in the value, as a number JSON cannot
#! hold, or an enum member or union field that is not marked.
pub def to_text<T>(value: &T, indent: u32 = 0, alloc: maybe<&mut allocator> = nothing {}): result<string, error> {
var out := writer::indented(indent, alloc);
serial::encode(value, &mut out);
_ = out.finish() else (e) { return e; };
return move(out._text);
}
#! Writes a typed value as JSON text into a stream, by what `@serial` marks of
#! its type, passing the text on as it goes rather than holding it all.
#! @tparam T The type of the value.
#! @param value The value to write.
#! @param out The stream to write to, which is not flushed: whoever made it
#! does that.
#! @param indent Spaces for each level of nesting, or 0 to write it on one
#! line.
#! @returns Nothing, or the first failure in the value, or `not_written` where
#! the stream failed, as its own error then says.
pub def write_to<T>(value: &T, out: &mut writable, indent: u32 = 0): result<void, error> {
var w := writer::to(out, indent);
serial::encode(value, &mut w);
_ = w.finish() else (e) { return e; };
return;
}
#! Reads a typed value from a value of a document, by what `@serial` marks of
#! its type, or the form of its own the type gives.
#! @tparam T The type to read.
#! @param from The value to read.
#! @param given How strictly to read: strictly, a member no field takes, and a
#! member written more than once, are errors.
#! @returns The value, or why it could not be read, at the value that failed.
pub def decode<T>(from: value, given: serial::options = serial::options {}): result<T, error> where T: zeroable {
var made := serial::decode::<T>(&from._document[0], from._at, given) else (e) { return error::from(&e); };
return move(made);
}
#! Reads a typed value from JSON text, by what `@serial` marks of its type.
#! @tparam T The type to read.
#! @param text The text to read.
#! @param given How strictly to read.
#! @returns The value, or why the text is not JSON, or could not be read as the
#! type.
pub def from_text<T>(text: strview, given: serial::options = serial::options {}): result<T, error> where T: zeroable {
val read := parse(text) else (e) { return e; };
var made := decode::<T>(read.root, given) else (e) { return e; };
return move(made);
}
+480
View File
@@ -0,0 +1,480 @@
#! @file reader.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the pull reader, which reads JSON one token at a time, checking it as
#! it goes, without building anything.
import core::swar;
module std::json;
#! The nesting a reader allows when it is given no other limit.
pub const default_depth: u32 = 512;
#! What a token is.
pub enum token_kind: u8 {
begin_object, #! `{`, which begins an object.
end_object, #! `}`, which ends one.
begin_array, #! `[`, which begins an array.
end_array, #! `]`, which ends one.
key, #! A member's name, whose value is the next token.
text, #! A string.
number, #! A number, whose text is its view.
boolean, #! `true` or `false`, which `truth` says.
empty, #! `null`.
}
#! A piece of JSON a reader gives.
pub struct token {
pub var kind: token_kind; #! What the token is.
pub var escaped: bool; #! Whether a key's or text's view holds escapes, which `unescape` decodes.
pub var truth: bool; #! A boolean's value.
pub var view: strview; #! A key's or text's text between its quotes, a number's text, or the literal.
pub var offset: u64; #! The byte of the text the token begins at.
}
# What a reader looks for next.
enum reading: u8 {
value, #! A value: the first, or one after `:` or after `,` within an array.
first_element, #! A value or `]`, after `[`.
first_member, #! A key or `}`, after `{`.
member, #! A key, after `,` within an object.
colon, #! The `:` after a key.
after, #! A `,` or the end of what holds the value just read.
done, #! Nothing but whitespace, after the whole value.
failed, #! Nothing: the reader has stopped at an error.
}
#! Reads JSON one token at a time, checking it as it goes: commas, colons,
#! nesting, escapes, UTF-8, and the grammar of numbers. It stops at the first
#! error, which `error` then gives.
#!
#! A reader views the text it reads, and so do its tokens, so the text outlives
#! them. It allocates nothing unless its limit lets values nest past 512 levels.
pub struct reader {
var _text: strview;
var _at: u64;
var _state: reading;
var _depth: u32;
var _limit: u32;
var _stack: u64[8]; #! A bit for each of the first 512 open values, set for an object.
var _deeper: vector<u64>; #! The bits of those past 512.
var _error: maybe<error>;
}
#! Makes a reader of JSON text.
#! @param text The text to read, which must outlive the reader and its
#! tokens.
#! @param depth How deep values may nest before reading fails with `too_deep`.
#! @returns The reader, at the start of the text.
pub def reader::new(text: strview, depth: u32 = default_depth): reader {
return reader { _text = text, _limit = depth };
}
#! Why reading stopped before the end of the text, where it did.
#! @param this The reader to ask.
#! @returns The error, or `nothing` where none has been met.
pub val reader::error: maybe<error> {
get => this._error;
}
#! How deep the reader is among open objects and arrays.
#! @param this The reader to ask.
#! @returns The number of them that are open.
pub val reader::depth: u32 {
get => this._depth;
}
#! Reads the next token.
#! @param this The reader to read with.
#! @returns The token, or `nothing` at the end of the text or at an error, which
#! `error` tells apart.
pub def reader::next(&mut this): maybe<token> {
while true {
this.skip_space();
match this._state {
value => return this.read_value();
first_element => {
if this.peek() != ']' {
return this.read_value();
}
return this.close(token_kind::end_array);
}
first_member => {
if this.peek() == '}' {
return this.close(token_kind::end_object);
}
return this.read_key();
}
member => return this.read_key();
colon => {
if this.peek() != ':' {
return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
this._at++;
this._state = reading::value;
}
after => {
if this._depth == 0 {
this._state = reading::done;
continue;
}
val byte := this.peek();
if byte == ',' {
this._at++;
this._state = this.in_object() ? reading::member : reading::value;
continue;
}
if byte == '}' && this.in_object() {
return this.close(token_kind::end_object);
}
if byte == ']' && !this.in_object() {
return this.close(token_kind::end_array);
}
return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
done => {
if this.at_end() {
return nothing {};
}
return this.fail(error_kind::trailing_text, this._at);
}
failed => return nothing {};
}
}
return nothing {};
}
#! Reads past the value whose first token is next, however much it holds, as
#! after a key whose value is not wanted.
#! @param this The reader to read with.
#! @returns Whether the value was read whole, which it is not at an error.
pub def reader::skip(&mut this): bool {
val outer := this._depth;
while this.next() is some(read) {
if read.kind == token_kind::key {
continue;
}
if this._depth == outer {
return true;
}
}
return false;
}
# Reads a value: an object or array opening, a string, a number, or a literal.
def reader::read_value(&mut this): maybe<token> {
if this.at_end() {
return this.fail(error_kind::unexpected_end, this._at);
}
val start := this._at;
match this._text[start] {
'{' => return this.open(token_kind::begin_object, true);
'[' => return this.open(token_kind::begin_array, false);
'"' => return this.read_string(token_kind::text);
't' => return this.read_literal("true", token_kind::boolean, true);
'f' => return this.read_literal("false", token_kind::boolean, false);
'n' => return this.read_literal("null", token_kind::empty, false);
else => {
val byte := this._text[start];
if byte != '-' && !byte.is_digit {
return this.fail(error_kind::unexpected_byte, start);
}
return this.read_number();
}
}
return nothing {};
}
# Reads a key, and the `:` after it is looked for next.
def reader::read_key(&mut this): maybe<token> {
if this.peek() != '"' {
return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
val read := this.read_string(token_kind::key);
if read is some(_) {
this._state = reading::colon;
}
return read;
}
# Reads a string from its opening quote, checking its escapes and its UTF-8, and
# that it holds no control characters, which JSON writes as escapes.
def reader::read_string(&mut this, kind: token_kind): maybe<token> {
val start := this._at;
var index := start + 1;
var escaped := false;
while true {
index = plain_run(this._text, index);
if index >= this._text.length {
return this.fail(error_kind::unexpected_end, index);
}
val byte := this._text[index];
if byte == '"' {
break;
}
if byte == '\\' {
val end := escape_end(this._text, index);
if end == 0 {
return this.fail(error_kind::invalid_escape, index);
}
escaped = true;
index = end;
continue;
}
if byte < 0x20 {
return this.fail(error_kind::unexpected_byte, index);
}
if byte < 0x80 {
index++;
continue;
}
val count := serial::utf8_length(this._text, index);
if count == 0 {
return this.fail(error_kind::invalid_utf8, index);
}
index += count;
}
this._at = index + 1;
this._state = reading::after;
return token { kind = kind, escaped = escaped, view = this._text.substr(start + 1, index - start - 1), offset = start };
}
# Reads a number, which must end where a value may: at whitespace, a `,`, a closing
# bracket, or the end of the text, so `01` and `1x` are errors of the number.
def reader::read_number(&mut this): maybe<token> {
val start := this._at;
val end := number_end(this._text, start);
if end == start || (end < this._text.length && !ends_value(this._text[end])) {
return this.fail(error_kind::invalid_number, start);
}
this._at = end;
this._state = reading::after;
return token { kind = token_kind::number, view = this._text.substr(start, end - start), offset = start };
}
# Reads `true`, `false`, or `null`.
def reader::read_literal(&mut this, word: strview, kind: token_kind, truth: bool): maybe<token> {
val start := this._at;
val found := this._text.substr(start, word.length);
if found != word {
# Text that ends partway through the word ends early, and anything else is wrong.
val cut := found.length < word.length && word.starts_with(found);
return this.fail(cut ? error_kind::unexpected_end : error_kind::unexpected_byte, start);
}
this._at += word.length;
this._state = reading::after;
return token { kind = kind, truth = truth, view = found, offset = start };
}
# Opens an object or array, nesting one level deeper.
def reader::open(&mut this, kind: token_kind, object: bool): maybe<token> {
val start := this._at;
if this._depth >= this._limit {
return this.fail(error_kind::too_deep, start);
}
this.mark(this._depth, object);
this._depth++;
this._at++;
this._state = object ? reading::first_member : reading::first_element;
return token { kind = kind, view = this._text.substr(start, 1), offset = start };
}
# Closes the innermost object or array, at its closing bracket.
def reader::close(&mut this, kind: token_kind): maybe<token> {
val start := this._at;
this._depth--;
this._at++;
this._state = reading::after;
return token { kind = kind, view = this._text.substr(start, 1), offset = start };
}
# Records whether the value open at a level is an object.
def reader::mark(&mut this, level: u32, object: bool): void {
val bit: u64 = 1u << (level % 64) as u64;
if level < 512 {
val word := (level / 64) as u64;
this._stack[word] = object ? this._stack[word] | bit : this._stack[word] & ~bit;
return;
}
val word := ((level - 512) / 64) as u64;
while this._deeper.length <= word {
this._deeper.append(0);
}
val held := this._deeper.at(word);
this._deeper.set(word, object ? held | bit : held & ~bit);
}
# Whether the innermost open value is an object.
def reader::in_object(&this): bool {
val level := this._depth - 1;
val bit: u64 = 1u << (level % 64) as u64;
if level < 512 {
return (this._stack[(level / 64) as u64] & bit) != 0;
}
return (this._deeper.at(((level - 512) / 64) as u64) & bit) != 0;
}
# Stops at an error, which `error` then gives.
def reader::fail(&mut this, kind: error_kind, offset: u64): maybe<token> {
this._error = error_at(kind, this._text, offset);
this._state = reading::failed;
return nothing {};
}
# Moves past the whitespace JSON allows between tokens.
def reader::skip_space(&mut this): void {
this._at = space_run(this._text, this._at);
while this._at < this._text.length {
val byte := this._text[this._at];
if byte != ' ' && byte != '\n' && byte != '\r' && byte != '\t' {
return;
}
this._at++;
}
}
# Past the bytes of a string from a place that need no looking at alone: none
# of `"`, `\`, a control character, or a byte past ASCII, which as an `i8` is
# below zero, so one comparison finds both. Sixteen at a time where vectors are
# held in registers, then eight at a time as words, the last few read without
# passing the end.
def plain_run(text: strview, from: u64): u64 {
var at := from;
if lanes_held() {
val quote := u8x16::splat('"');
val slash := u8x16::splat('\\');
val below := i8x16::splat(0x20);
while at + 16 <= text.length {
val chunk := u8x16::load(text, at);
val stops := chunk.equal(&quote).bits() | chunk.equal(&slash).bits() | chunk.bits::<i8, 16>().less(&below).bits();
return at + trailing_zeros(stops) as u64 if stops != 0;
at += 16;
}
}
val data := text.data;
while at + 8 <= text.length {
val stops := plain_stops(swar::load(data + at));
return at + stops.first() if stops.any();
at += 8;
}
if at < text.length {
val stops: swar::mask8 = plain_stops(swar::load_last(data + at, text.length - at)) & swar::mask8::leading(text.length - at);
return at + stops.first() if stops.any();
}
return text.length;
}
# The bytes of a word a string's plain run stops at.
def plain_stops(word: swar::bytes8): swar::mask8 {
return word.equal('"') | word.equal('\\') | word.below(0x20) | (word & 0x8080808080808080);
}
# Past the whitespace from a place, sixteen bytes at a time where vectors are
# held in registers, then eight at a time as words where the first byte is
# whitespace, as where lines are indented, and none otherwise.
def space_run(text: strview, from: u64): u64 {
var at := from;
if lanes_held() {
val blank := u8x16::splat(' ');
val newline := u8x16::splat('\n');
val ret := u8x16::splat('\r');
val tab := u8x16::splat('\t');
while at + 16 <= text.length {
val chunk := u8x16::load(text, at);
val spaces := chunk.equal(&blank).bits() | chunk.equal(&newline).bits() | chunk.equal(&ret).bits()
| chunk.equal(&tab).bits();
return at + trailing_zeros(~spaces) as u64 if spaces != 0xFFFF;
at += 16;
}
}
return at if at >= text.length || !is_json_space(text[at]);
val data := text.data;
while at + 8 <= text.length {
val word := swar::load(data + at);
val other: swar::mask8 = ~(word.equal(' ') | word.equal('\n') | word.equal('\r') | word.equal('\t')) & 0x8080808080808080;
return at + other.first() if other.any();
at += 8;
}
return at;
}
# Whether a byte is whitespace JSON allows between tokens.
def is_json_space(byte: u8): bool {
return byte == ' ' || byte == '\n' || byte == '\r' || byte == '\t';
}
# The byte the reader is at, or 0 at the end of the text.
def reader::peek(&this): u8 {
return this.at_end() ? 0 : this._text[this._at];
}
def reader::at_end(&this): bool {
return this._at >= this._text.length;
}
# Whether a byte may follow a value: whitespace, a `,`, or a closing bracket.
def ends_value(byte: u8): bool {
return byte == ' ' || byte == '\n' || byte == '\r' || byte == '\t' || byte == ',' || byte == ']' || byte == '}';
}
# Where the escape beginning at `at` ends, or 0 where it is not one JSON has: one of
# `\" \\ \/ \b \f \n \r \t`, or `\u` and four hexadecimal digits, where a surrogate
# is the first of a pair written as two escapes.
def escape_end(text: strview, at: u64): u64 {
if at + 1 >= text.length {
return 0;
}
val marker := text[at + 1];
if marker == '"' || marker == '\\' || marker == '/' || marker == 'b' || marker == 'f'
|| marker == 'n' || marker == 'r' || marker == 't' {
return at + 2;
}
if marker != 'u' || !hex_at(text, at + 2) {
return 0;
}
val code := hex_value(text, at + 2);
if code >= 0xDC00 && code <= 0xDFFF {
return 0;
}
if code < 0xD800 || code > 0xDBFF {
return at + 6;
}
# A high surrogate is followed by a low one.
if at + 7 >= text.length || text[at + 6] != '\\' || text[at + 7] != 'u' || !hex_at(text, at + 8) {
return 0;
}
val low := hex_value(text, at + 8);
if low < 0xDC00 || low > 0xDFFF {
return 0;
}
return at + 12;
}
# Whether four hexadecimal digits begin at `at`.
def hex_at(text: strview, at: u64): bool {
if at + 4 > text.length {
return false;
}
for index in 0u..4u {
if !text[at + index].is_hex {
return false;
}
}
return true;
}
+194
View File
@@ -0,0 +1,194 @@
#! @file text.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what JSON's text is made of: UTF-8, the escapes of strings, and the
#! grammar of numbers and what they read as, which the reader, the document, and
#! the writer share.
module std::json;
# The digits a `\u` escape is written with.
const hex_digits: strview = "0123456789abcdef";
#! Writes text with JSON's escapes, as it stands between the quotes of a string:
#! `"`, `\`, and the control characters escaped, and everything else as it is.
#! @param text The text to escape.
#! @param into The string to append to.
#! @param lossy Whether each byte that breaks UTF-8 is written as the escape of
#! U+FFFD, `\ufffd`, so the whole text is written, rather than the
#! text being cut short at the first.
#! @returns Whether the text is UTF-8, which JSON's text must be. Text that is
#! not is appended only as far as its first byte that breaks UTF-8,
#! unless the escape is lossy.
pub def escape(text: strview, into: &mut string, lossy: bool = false): bool {
var run: u64 = 0; # Where the bytes written as they are begin.
var at: u64 = 0;
var whole: bool = true;
while at < text.length {
val byte := text[at];
if byte >= 0x80 {
val count := serial::utf8_length(text, at);
if count != 0 {
at += count;
continue;
}
into.append(text.substr(run, at - run));
if !lossy {
return false;
}
into.append("\\ufffd");
whole = false;
at++;
run = at;
continue;
}
if byte >= 0x20 && byte != '"' && byte != '\\' {
at++;
continue;
}
into.append(text.substr(run, at - run));
escape_byte(byte, into);
at++;
run = at;
}
into.append(text.substr(run, at - run));
return whole;
}
#! Decodes the escapes of a string's text as JSON writes them, where the text is
#! as it stands between the quotes, as a reader's token views it.
#! @param raw The text, whose escapes the reader has checked.
#! @param into The string to append the decoded text to.
pub def unescape(raw: strview, into: &mut string): void {
var run: u64 = 0;
var at: u64 = 0;
while at < raw.length {
if raw[at] != '\\' {
at++;
continue;
}
into.append(raw.substr(run, at - run));
val marker := raw[at + 1];
at += 2;
run = at;
if marker != 'u' {
into.push(unescaped(marker));
continue;
}
# A surrogate pair is two escapes, which are one character together.
var code := hex_value(raw, at);
at += 4;
if code >= 0xD800 && code <= 0xDBFF {
code = 0x10000 + ((code - 0xD800) << 10) + (hex_value(raw, at + 2) - 0xDC00);
at += 6;
}
serial::append_utf8(code, into);
run = at;
}
into.append(raw.substr(run, at - run));
}
#! Whether text is UTF-8: no overlong forms, no surrogates, nothing past
#! U+10FFFF, and nothing cut short.
#! @param text The text to check.
#! @returns Whether it is UTF-8.
pub def is_utf8(text: strview): bool {
return serial::is_utf8(text);
}
# Where the number beginning at `at` ends, following JSON's grammar,
# `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`, or `at` where none begins there
# or it breaks the grammar.
def number_end(text: strview, at: u64): u64 {
var index := at;
if index < text.length && text[index] == '-' {
index++;
}
if index >= text.length {
return at;
}
if text[index] == '0' {
index++;
} else if text[index] >= '1' && text[index] <= '9' {
index = digits_end(text, index);
} else {
return at;
}
if index < text.length && text[index] == '.' {
val digits := index + 1;
index = digits_end(text, digits);
if index == digits {
return at;
}
}
if index < text.length && (text[index] == 'e' || text[index] == 'E') {
index++;
if index < text.length && (text[index] == '+' || text[index] == '-') {
index++;
}
val digits := index;
index = digits_end(text, digits);
if index == digits {
return at;
}
}
return index;
}
# Where a run of decimal digits beginning at `at` ends.
def digits_end(text: strview, at: u64): u64 {
var index := at;
while index < text.length && text[index].is_digit {
index++;
}
return index;
}
# Appends the escape JSON writes for a byte it does not write as it is.
def escape_byte(byte: u8, into: &mut string): void {
into.push('\\');
match byte {
'"' => into.push('"');
'\\' => into.push('\\');
'\n' => into.push('n');
'\r' => into.push('r');
'\t' => into.push('t');
0x08 => into.push('b');
0x0C => into.push('f');
else => {
into.append("u00");
into.push(hex_digits[(byte >> 4) as u64]);
into.push(hex_digits[(byte & 0x0F) as u64]);
}
}
}
# The byte a one-letter escape stands for, as `n` for a line break.
def unescaped(marker: u8): u8 {
return match marker {
'b' => 0x08,
'f' => 0x0C,
'n' => '\n',
'r' => '\r',
't' => '\t',
else => marker,
};
}
# The number four hexadecimal digits beginning at `at` write.
def hex_value(text: strview, at: u64): u64 {
var made: u64 = 0;
for index in 0u..4u {
made = made * 16 + text[at + index].digit_value;
}
return made;
}
+401
View File
@@ -0,0 +1,401 @@
#! @file writer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the writer, which writes JSON as it is given it, without building a
#! tree first.
import std::io;
module std::json;
# How much text a writer passing its text on holds before it does.
const pass_bytes: u64 = 16384;
# What each open object or array of a writer records.
const level_object: u8 = 1; # It is an object.
const level_held: u8 = 2; # It holds something already, so a comma comes before the next.
const level_named: u8 = 4; # A member's name is written, and its value is next.
#! Writes JSON into a string it owns, as it is given it: commas, colons,
#! escapes, and indentation are its own.
#!
#! A writer made by `writer::to` passes its text on to a stream instead,
#! whenever it holds 16 KB and when it finishes, so a large document is never
#! held whole. It borrows the stream, which the caller flushes and closes.
#!
#! Misuse stops the program, as indexing past an array does, since it is a
#! mistake in the program rather than in its data: a member outside an object, a
#! value within an object without its member's name, ending an array where an
#! object is open, a second value after the first, or finishing with something
#! still open.
#!
#! A failure in the data is kept, so it is checked once, when the writer
#! finishes: a number that is infinite or NaN, or text that is not UTF-8, is
#! written as `null` in its place, and the first such failure is what `finish`
#! gives. A writer `set_lossy` makes lossy writes text that is not UTF-8 instead,
#! with U+FFFD in place of each byte that breaks it, as a server must that sends
#! whatever a file holds.
#!
#! The writer is a `serial::encoder`, so `json::encode` and `serial::encode`
#! write typed values through it, among what it is given by hand, and `raw`
#! writes JSON already written, as it is.
pub struct writer : serial::encoder, moveable {
pub var _text: string; #! The text written so far, which std's tests read.
var _indent: u32; #! Spaces for each level of nesting, or 0 to write everything on one line.
var _levels: vector<u8>; #! Each open object or array, outermost first.
var _written: bool; #! Whether the value is begun, after which there is no other.
var _failure: maybe<error_kind>;
var _out: maybe<&mut writable>; #! Where the text is passed on, for a writer `to` makes.
var _pass_at: u64; #! How much text is held before it is passed on, or 0 for never.
var _lossy: bool; #! Whether text that is not UTF-8 is written with U+FFFD in place of what breaks it.
}
#! Makes a writer that writes everything on one line.
#! @param alloc An optional allocator for the writer to take memory from.
#! @returns The writer, which holds no text yet.
pub def writer::new(alloc: maybe<&mut allocator> = nothing {}): writer {
return writer { _text = string::new(alloc), _levels = vector::<u8>::new(alloc) };
}
#! Makes a writer that writes each element and member on a line of its own.
#! @param width How many spaces each level of nesting is indented by.
#! @param alloc An optional allocator for the writer to take memory from.
#! @returns The writer, which holds no text yet.
pub def writer::indented(width: u32, alloc: maybe<&mut allocator> = nothing {}): writer {
return writer { _text = string::new(alloc), _indent = width, _levels = vector::<u8>::new(alloc) };
}
#! Makes a writer that passes what it writes on to a stream, whenever it holds
#! 16 KB and when it finishes, rather than holding it all.
#! @param out The stream to write to, which the writer borrows, and which
#! whoever made it flushes and closes.
#! @param indent Spaces for each level of nesting, or 0 to write everything on
#! one line.
#! @param alloc An optional allocator for the writer to take memory from.
#! @returns The writer.
pub def writer::to(out: &mut writable, indent: u32 = 0, alloc: maybe<&mut allocator> = nothing {}): writer {
return writer {
_text = string::new(alloc),
_indent = indent,
_levels = vector::<u8>::new(alloc),
_out = out,
_pass_at = pass_bytes
};
}
#! Creates a writer by taking another's text and what it has open, which leaves
#! the other holding nothing.
#! @param other The writer to move from.
#! @returns The writer.
pub def writer::move_of(other: &mut writer): writer {
val made := writer {
_text = move(other._text),
_indent = other._indent,
_levels = move(other._levels),
_written = other._written,
_failure = other._failure,
_out = other._out,
_pass_at = other._pass_at,
_lossy = other._lossy
};
other._written = false;
other._failure = nothing {};
other._out = nothing {};
other._pass_at = 0;
return made;
}
#! Gives the text written, once the value is written whole. A writer `to` a
#! stream passes on what it still holds, and gives an empty view.
#! @param this The writer to finish.
#! @returns A view of the text, good until the writer is written to, cleared, or
#! closed, or the first failure in the data, which has no place, or
#! `not_written` where the stream failed.
pub def writer::finish(&mut this): result<strview, error> {
expects(this._written && this._levels.length == 0,
"A writer finishes once its value is written whole, with nothing left open.");
if this._pass_at != 0 {
this.pass();
}
if this._failure is some(kind) {
return error { kind = kind };
}
return this._text.view();
}
#! Empties the writer to write another value, keeping its memory, and whether it
#! is lossy.
#! @param this The writer to empty.
pub def writer::clear(&mut this): void {
this._text.clear();
this._levels.clear();
this._written = false;
this._failure = nothing {};
}
#! Makes the writer lossy, or strict again. A lossy writer writes text that is
#! not UTF-8, in strings and members' names alike, with the escape of U+FFFD,
#! `\ufffd`, in place of each byte that breaks UTF-8, rather than writing `null`
#! and keeping the failure, so what it writes is JSON whatever it is given.
#! @param this The writer to change.
#! @param lossy Whether it is lossy.
pub def writer::set_lossy(&mut this, lossy: bool): void {
this._lossy = lossy;
}
#! Begins an object, whose members are each written as `member` and a value.
#! @param this The writer to write with.
pub def writer::begin_object(&mut this): void {
this.begin(level_object, '{');
}
#! Begins an object, as `serial::encode` does, knowing how many members it
#! holds.
#! @param this The writer to write with.
#! @param count How many members the object holds, which JSON need not know.
pub def writer::begin_object(&mut this, count: u64): void {
this.begin(level_object, '{');
}
#! Writes the name of the member whose value is written next.
#! @param this The writer to write with, within an object.
#! @param name The name, which is escaped.
pub def writer::member(&mut this, name: strview): void {
expects(this._levels.length > 0 && (this.top() & level_object) != 0,
"A member is written only within an object.");
expects((this.top() & level_named) == 0, "A member's value is written before the next member.");
val top := this.top();
if (top & level_held) != 0 {
this._text.push(',');
}
this._levels.set(this._levels.length - 1, top | level_held | level_named);
this.newline(this._levels.length);
this._text.push('"');
val before := this._text.length;
if !escape(name, &mut this._text, this._lossy) && !this._lossy {
this._text.resize(before);
this.keep(error_kind::invalid_utf8);
}
this._text.append(this._indent > 0 ? "\": " : "\":");
}
#! Ends the innermost object.
#! @param this The writer to write with.
pub def writer::end_object(&mut this): void {
expects(this._levels.length > 0 && (this.top() & level_object) != 0,
"An object is ended only where one is open innermost.");
expects((this.top() & level_named) == 0, "A member's value is written before the object ends.");
this.end('}');
}
#! Begins an array.
#! @param this The writer to write with.
pub def writer::begin_array(&mut this): void {
this.begin(0, '[');
}
#! Begins an array, as `serial::encode` does, knowing how many elements it
#! holds.
#! @param this The writer to write with.
#! @param count How many elements the array holds, which JSON need not know.
pub def writer::begin_array(&mut this, count: u64): void {
this.begin(0, '[');
}
#! Ends the innermost array.
#! @param this The writer to write with.
pub def writer::end_array(&mut this): void {
expects(this._levels.length > 0 && (this.top() & level_object) == 0,
"An array is ended only where one is open innermost.");
this.end(']');
}
#! Writes a string.
#! @param this The writer to write with.
#! @param value The text, which is escaped, and must be UTF-8 unless the
#! writer is lossy.
pub def writer::text(&mut this, value: strview): void {
this.before_value();
val before := this._text.length;
this._text.push('"');
if !escape(value, &mut this._text, this._lossy) && !this._lossy {
this._text.resize(before);
this._text.append("null");
this.keep(error_kind::invalid_utf8);
return;
}
this._text.push('"');
}
#! Writes a signed integer.
#! @param this The writer to write with.
#! @param value The integer.
pub def writer::signed(&mut this, value: i64): void {
this.before_value();
if value < 0 {
this._text.push('-');
this.digits(0u - value as u64);
return;
}
this.digits(value as u64);
}
#! Writes an unsigned integer.
#! @param this The writer to write with.
#! @param value The integer.
pub def writer::unsigned(&mut this, value: u64): void {
this.before_value();
this.digits(value);
}
#! Writes a float, as the shortest text that reads back as it.
#! @param this The writer to write with.
#! @param value The float, which must be finite.
pub def writer::real(&mut this, value: f64): void {
this.before_value();
if !(value - value == 0.0) {
this._text.append("null");
this.keep(error_kind::not_finite);
return;
}
val written := $"{value}";
this._text.append(written.view());
}
#! Writes `true` or `false`.
#! @param this The writer to write with.
#! @param value The truth to write.
pub def writer::boolean(&mut this, value: bool): void {
this.before_value();
this._text.append(value ? "true" : "false");
}
#! Writes `null`.
#! @param this The writer to write with.
pub def writer::empty(&mut this): void {
this.before_value();
this._text.append("null");
}
#! Writes JSON text already written, as it is, as a value: one written by
#! another writer, or by another program, which is written again without being
#! read.
#! @param this The writer to write with.
#! @param json The text, which must be one whole JSON value, since the writer
#! does not read it, and which keeps its own spacing, however the
#! writer indents.
pub def writer::raw(&mut this, json: strview): void {
this.before_value();
this._text.append(json);
}
#! Keeps a failure `serial::encode` finds, as the writer keeps its own, to give
#! it when it finishes.
#! @param this The writer to keep it.
#! @param kind The failure.
pub def writer::fail(&mut this, kind: serial::error_kind): void {
this.keep(of_serial(kind));
}
# Begins an object or array, as a value.
def writer::begin(&mut this, level: u8, bracket: u8): void {
this.before_value();
this._text.push(bracket);
this._levels.append(level);
}
# Passes the text on to the stream, where the writer passes it on and holds enough.
def writer::passes(&mut this): void {
if this._pass_at != 0 && this._text.length >= this._pass_at {
this.pass();
}
}
# Passes everything held on to the stream, and lets go of it. Once the stream has
# failed, what is written is let go of without being passed on.
def writer::pass(&mut this): void {
if this._out is some(out) {
if out.write(this._text.view()) is error(_) {
this._out = nothing {};
this.keep(error_kind::not_written);
}
}
this._text.clear();
}
# Ends the innermost object or array, closing it on a line of its own where it
# holds anything and the writer indents.
def writer::end(&mut this, bracket: u8): void {
this.passes();
val held := (this.top() & level_held) != 0;
this._levels.remove_at(this._levels.length - 1);
if held {
this.newline(this._levels.length);
}
this._text.push(bracket);
}
# Readies a value: within an array, after a comma where one comes, and within an
# object, after its member's name.
def writer::before_value(&mut this): void {
this.passes();
if this._levels.length == 0 {
expects(!this._written, "A writer writes one value; an array holds more than one.");
this._written = true;
return;
}
val top := this.top();
if (top & level_object) != 0 {
expects((top & level_named) != 0, "A value within an object follows its member's name.");
this._levels.set(this._levels.length - 1, top & ~level_named);
return;
}
if (top & level_held) != 0 {
this._text.push(',');
}
this._levels.set(this._levels.length - 1, top | level_held);
this.newline(this._levels.length);
}
# Begins a line indented for a depth, where the writer indents.
def writer::newline(&mut this, depth: u64): void {
if this._indent == 0 {
return;
}
this._text.push('\n');
for _ in 0..depth * (this._indent as u64) {
this._text.push(' ');
}
}
# Writes an integer's digits.
def writer::digits(&mut this, magnitude: u64): void {
var buffer: u8[20];
var at: u64 = 20;
var left := magnitude;
while true {
at--;
buffer[at] = '0' + (left % 10) as u8;
left /= 10;
if left == 0 {
break;
}
}
this._text.append(strview::over(&buffer[at] as *u8, 20 - at));
}
def writer::top(&this): u8 {
return this._levels.at(this._levels.length - 1);
}
# Keeps the first failure in the data.
def writer::keep(&mut this, kind: error_kind): void {
if this._failure is none {
this._failure = kind;
}
}
+150
View File
@@ -0,0 +1,150 @@
#! @file bits.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains a real's bits, as IEEE 754 lays them out, and what they say of it:
#! whether it is not a number, infinite, finite, or subnormal, and its sign.
#! Also the pieces of a double's bits the functions of this module are written
#! with, as the C they are ported from reads them.
module std::math;
#! The bits of an `f64`: its sign, then 11 bits of exponent, then 52 of
#! significand.
#! @param x The real.
#! @returns Its bits.
pub def bits_of(x: f64): u64 {
var held := x;
return ((&mut held) as *mut u64)[0];
}
#! The bits of an `f32`: its sign, then 8 bits of exponent, then 23 of
#! significand.
#! @param x The real.
#! @returns Its bits.
pub def bits_of(x: f32): u32 {
var held := x;
return ((&mut held) as *mut u32)[0];
}
#! The `f64` some bits are.
#! @param bits The bits, as `bits_of` gives them.
#! @returns The real.
pub def real_of_bits(bits: u64): f64 {
var held := bits;
return ((&mut held) as *mut f64)[0];
}
#! The `f32` some bits are.
#! @param bits The bits, as `bits_of` gives them.
#! @returns The real.
pub def real_of_bits(bits: u32): f32 {
var held := bits;
return ((&mut held) as *mut f32)[0];
}
#! Whether a real is not a number, which is the only value unequal to itself.
#! @tparam T The type of real.
#! @param x The real.
#! @returns Whether it is NaN.
pub def is_nan<T>(x: T): bool where T: real {
return x != x;
}
#! Whether a real is infinite, of either sign.
#! @tparam T The type of real.
#! @param x The real.
#! @returns Whether it is.
pub def is_infinite<T>(x: T): bool where T: real {
return (bits_of(x as f64) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
}
#! Whether a real is finite: neither infinite nor NaN.
#! @tparam T The type of real.
#! @param x The real.
#! @returns Whether it is.
pub def is_finite<T>(x: T): bool where T: real {
return (bits_of(x as f64) & 0x7FF0000000000000) != 0x7FF0000000000000;
}
#! Whether a real is subnormal: not zero, but closer to it than the least normal
#! value of its type, so it holds fewer bits of precision.
#! @tparam T The type of real.
#! @param x The real.
#! @returns Whether it is.
pub def is_subnormal<T>(x: T): bool where T: real {
if const size_of::<T>() == 4 {
val bits := bits_of(x as f32);
return (bits & 0x7F800000) == 0 && (bits & 0x007FFFFF) != 0;
}
val bits := bits_of(x as f64);
return (bits & 0x7FF0000000000000) == 0 && (bits & 0x000FFFFFFFFFFFFF) != 0;
}
#! Whether a real's sign bit is set, as it is for `-0` and some NaNs, which no
#! comparison with zero says.
#! @tparam T The type of real.
#! @param x The real.
#! @returns Whether it is.
pub def sign_bit<T>(x: T): bool where T: real {
return (bits_of(x as f64) >> 63) != 0;
}
# The pieces of a double's bits.
# The top 12 bits of a double: its sign and exponent.
def top12(x: f64): u32 {
return (bits_of(x) >> 52) as u32;
}
# The high 32 bits of a double: its sign, exponent, and 20 bits of significand.
def high_word(x: f64): u32 {
return (bits_of(x) >> 32) as u32;
}
# The low 32 bits of a double, of its significand.
def low_word(x: f64): u32 {
return (bits_of(x) & 0xFFFFFFFF) as u32;
}
# The double of a high and a low word.
def of_words(high: u32, low: u32): f64 {
return real_of_bits(((high as u64) << 32) | low as u64);
}
# The double with its high word replaced.
def with_high_word(x: f64, high: u32): f64 {
return real_of_bits(((high as u64) << 32) | (bits_of(x) & 0xFFFFFFFF));
}
# The double with its low word replaced.
def with_low_word(x: f64, low: u32): f64 {
return real_of_bits((bits_of(x) & 0xFFFFFFFF00000000) | low as u64);
}
# What a function gives where its result is past what a double holds, as musl's
# `__math_oflow`, `__math_uflow`, `__math_invalid`, and `__math_divzero` make
# them: an infinity, a zero, NaN, or an infinity from dividing by zero, each of
# the sign asked for.
def overflowed(sign: u32): f64 {
val y: f64 = 3.105036184601418e+231;
return (sign != 0 ? -y : y) * y;
}
def underflowed(sign: u32): f64 {
val y: f64 = 1.2882297539194267e-231;
return (sign != 0 ? -y : y) * y;
}
def invalid(x: f64): f64 {
return (x - x) / (x - x);
}
def divided_by_zero(sign: u32): f64 {
return (sign != 0 ? -1.0 : 1.0) / 0.0;
}
+74
View File
@@ -0,0 +1,74 @@
#! @file constants.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the constants of real numbers: those of mathematics, as `f64`s, which
#! `as f32` gives the nearest `f32` of, and those of each type of real, its
#! largest and least values, epsilon, infinity, and not a number.
module std::math;
#! π, the ratio of a circle's circumference to its diameter.
pub const pi: f64 = 3.141592653589793;
#! τ, which is 2π, the angle of a whole turn in radians.
pub const tau: f64 = 6.283185307179586;
#! e, the base of the natural logarithm.
pub const e: f64 = 2.718281828459045;
#! The square root of 2.
pub const sqrt_2: f64 = 1.4142135623730951;
#! The natural logarithm of 2.
pub const ln_2: f64 = 0.6931471805599453;
#! The natural logarithm of 10.
pub const ln_10: f64 = 2.302585092994046;
#! The largest finite value of a type of real.
#! @tparam T The type of real.
#! @returns About 3.4e38 for `f32`, and 1.8e308 for `f64`.
pub def largest<T>(): T where T: real {
if const size_of::<T>() == 4 {
return 3.4028234663852886e38 as T;
}
return 1.7976931348623157e308 as T;
}
#! The least positive normal value of a type of real. Those closer to zero are
#! subnormal, and hold fewer bits of precision.
#! @tparam T The type of real.
#! @returns About 1.2e-38 for `f32`, and 2.2e-308 for `f64`.
pub def smallest<T>(): T where T: real {
if const size_of::<T>() == 4 {
return 1.1754943508222875e-38 as T;
}
return 2.2250738585072014e-308 as T;
}
#! The difference between 1 and the next value of a type of real.
#! @tparam T The type of real.
#! @returns 2^-23 for `f32`, and 2^-52 for `f64`.
pub def epsilon<T>(): T where T: real {
if const size_of::<T>() == 4 {
return 1.1920928955078125e-07 as T;
}
return 2.220446049250313e-16 as T;
}
#! Positive infinity, of a type of real.
#! @tparam T The type of real.
#! @returns Infinity; its negation is negative infinity.
pub def infinity<T>(): T where T: real {
return real_of_bits(0x7FF0000000000000u) as T;
}
#! Not a number, of a type of real: a quiet NaN, of positive sign.
#! @tparam T The type of real.
#! @returns NaN, which is unequal to everything, itself included.
pub def nan<T>(): T where T: real {
return real_of_bits(0x7FF8000000000000u) as T;
}
+483
View File
@@ -0,0 +1,483 @@
#! @file exact.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the operations of real numbers IEEE 754 defines to the bit: square
#! roots, rounding to integers, absolute values, signs, fused multiplying and
#! adding, and the least and greatest of two values. Each gives the one result
#! the standard says, in the virtual machine, in an executable, and while
#! compiling.
#!
#! An `f32` is worked in `f64` and rounded back, which gives its exact result
#! too: a double holds more than twice a float's bits, so its square root
#! rounds once, and a float's integer neighbours are floats. Only `fma` needs
#! more, as musl's `fmaf` does.
#!
#! Rounding is ported from musl 1.2.5, which is Copyright © 2005-2020 Rich
#! Felker, et al., under the MIT license. `fma_single` is from FreeBSD's
#! s_fmaf.c, by way of musl, which says:
#!
#! Copyright (c) 2005-2011 David Schultz <das@FreeBSD.ORG>
#! All rights reserved.
#!
#! Redistribution and use in source and binary forms, with or without
#! modification, are permitted provided that the following conditions
#! are met:
#! 1. Redistributions of source code must retain the above copyright
#! notice, this list of conditions and the following disclaimer.
#! 2. Redistributions in binary form must reproduce the above copyright
#! notice, this list of conditions and the following disclaimer in the
#! documentation and/or other materials provided with the distribution.
#!
#! THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
#! ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#! ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
#! FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
#! OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
#! HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
#! OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#! SUCH DAMAGE.
import core::intrinsics;
module std::math;
#! The square root of a real, correctly rounded.
#! @tparam T The type of real.
#! @param x The real.
#! @returns Its square root: `-0` for `-0`, infinity for infinity, and NaN for
#! what is below zero or NaN.
pub def sqrt<T>(x: T): T where T: real {
return square_root(x as f64) as T;
}
#! The greatest integer not above a real.
#! @tparam T The type of real.
#! @param x The real.
#! @returns The integer, as a real: `-0` stays `-0`, and infinities and NaN
#! are themselves.
pub def floor<T>(x: T): T where T: real {
return floor_double(x as f64) as T;
}
#! The least integer not below a real.
#! @tparam T The type of real.
#! @param x The real.
#! @returns The integer, as a real: what is above -1 and below 0 gives `-0`.
pub def ceil<T>(x: T): T where T: real {
return ceil_double(x as f64) as T;
}
#! A real's integer part, toward zero.
#! @tparam T The type of real.
#! @param x The real.
#! @returns The integer, as a real, of the real's sign.
pub def trunc<T>(x: T): T where T: real {
return trunc_double(x as f64) as T;
}
#! The integer nearest a real, halves away from zero, so 2.5 gives 3 and -2.5
#! gives -3.
#! @tparam T The type of real.
#! @param x The real.
#! @returns The integer, as a real, of the real's sign.
pub def round<T>(x: T): T where T: real {
return round_double(x as f64) as T;
}
#! The integer nearest a real, halves to the even one, so 2.5 gives 2 and 3.5
#! gives 4, as IEEE 754 rounds by default.
#! @tparam T The type of real.
#! @param x The real.
#! @returns The integer, as a real, of the real's sign.
pub def round_even<T>(x: T): T where T: real {
return round_even_double(x as f64) as T;
}
#! A value's distance from zero, of a type that negates and is ordered: a
#! number, or a `duration`. A real's sign bit is cleared, so `-0` gives `0`, and
#! NaN a NaN. The most negative integer of a type has no positive, and gives
#! itself.
#! @tparam T The type.
#! @param x The value.
#! @returns Its absolute value.
pub def abs<T>(x: T): T where T: negatable, ordered {
if const T is real {
if const size_of::<T>() == 4 {
return real_of_bits(bits_of(x as f32) & 0x7FFFFFFF) as T;
}
return real_of_bits(bits_of(x as f64) & 0x7FFFFFFFFFFFFFFF) as T;
}
return x < -x ? -x : x;
}
#! A real with the magnitude of one and the sign of another, NaN included.
#! @tparam T The type of real.
#! @param x The real giving the magnitude.
#! @param sign The real giving the sign.
#! @returns The real.
pub def copysign<T>(x: T, sign: T): T where T: real {
if const size_of::<T>() == 4 {
return real_of_bits((bits_of(x as f32) & 0x7FFFFFFF) | (bits_of(sign as f32) & 0x80000000)) as T;
}
return real_of_bits((bits_of(x as f64) & 0x7FFFFFFFFFFFFFFF) | (bits_of(sign as f64) & 0x8000000000000000)) as T;
}
#! `x * y + z`, rounded once rather than after the multiply too.
#! @tparam T The type of real.
#! @param x The first factor.
#! @param y The second factor.
#! @param z What the product is added to.
#! @returns The sum, correctly rounded.
pub def fma<T>(x: T, y: T, z: T): T where T: real {
if const size_of::<T>() == 4 {
return fma_single(x as f32, y as f32, z as f32) as T;
}
return fma_double(x as f64, y as f64, z as f64) as T;
}
#! The lesser of two values. Of reals, this is IEEE 754's `minimum`: NaN where
#! either is NaN, and `-0` below `0`. Of others, `a` where they are equal.
#! @tparam T The type.
#! @param a One value.
#! @param b The other.
#! @returns The lesser.
pub def min<T>(a: T, b: T): T where T: ordered {
if const T is real {
return a + b if a != a || b != b;
if a == b {
return sign_bit(a) ? a : b;
}
}
return b < a ? b : a;
}
#! The greater of two values. Of reals, this is IEEE 754's `maximum`: NaN where
#! either is NaN, and `0` above `-0`. Of others, `a` where they are equal.
#! @tparam T The type.
#! @param a One value.
#! @param b The other.
#! @returns The greater.
pub def max<T>(a: T, b: T): T where T: ordered {
if const T is real {
return a + b if a != a || b != b;
if a == b {
return sign_bit(a) ? b : a;
}
}
return a < b ? b : a;
}
#! A value held between two others, as `max(low, min(x, high))`: `low` where it
#! is below, `high` where it is above, and itself between. Of reals, NaN gives
#! NaN. Where `low` is above `high`, it gives `low`.
#! @tparam T The type.
#! @param x The value.
#! @param low The least it may be.
#! @param high The greatest it may be.
#! @returns The value held.
pub def clamp<T>(x: T, low: T, high: T): T where T: ordered {
return max(low, min(x, high));
}
# Doubles.
# 2^52, past which every double is an integer, and which adding and taking away
# rounds a smaller one to an integer.
const to_integer: f64 = 4503599627370496.0;
def floor_double(x: f64): f64 {
val bits := bits_of(x);
val e := (bits >> 52) & 0x7FF;
return x if e >= 0x3FF + 52 || x == 0;
# y is the integer nearest x, less x.
val y := (bits >> 63) != 0 ? x - to_integer + to_integer - x : x + to_integer - to_integer - x;
if e <= 0x3FF - 1 {
return (bits >> 63) != 0 ? -1.0 : 0.0;
}
return x + y - 1.0 if y > 0;
return x + y;
}
def ceil_double(x: f64): f64 {
val bits := bits_of(x);
val e := (bits >> 52) & 0x7FF;
return x if e >= 0x3FF + 52 || x == 0;
val y := (bits >> 63) != 0 ? x - to_integer + to_integer - x : x + to_integer - to_integer - x;
if e <= 0x3FF - 1 {
return (bits >> 63) != 0 ? -0.0 : 1.0;
}
return x + y + 1.0 if y < 0;
return x + y;
}
def trunc_double(x: f64): f64 {
val bits := bits_of(x);
var e := (((bits >> 52) & 0x7FF) as i64) - 0x3FF + 12;
return x if e >= 52 + 12;
if e < 12 {
e = 1;
}
val m := 0xFFFFFFFFFFFFFFFFu >> (e as u64);
return x if (bits & m) == 0;
return real_of_bits(bits & ~m);
}
def round_double(x: f64): f64 {
val bits := bits_of(x);
val e := (bits >> 52) & 0x7FF;
return x if e >= 0x3FF + 52;
val negative := (bits >> 63) != 0;
val a := negative ? -x : x;
if e < 0x3FF - 1 {
return 0.0 * x;
}
var y := a + to_integer - to_integer - a;
if y > 0.5 {
y = y + a - 1.0;
} else if y <= -0.5 {
y = y + a + 1.0;
} else {
y = y + a;
}
return negative ? -y : y;
}
def round_even_double(x: f64): f64 {
val bits := bits_of(x);
val e := (bits >> 52) & 0x7FF;
return x if e >= 0x3FF + 52;
val negative := (bits >> 63) != 0;
val y := negative ? x - to_integer + to_integer : x + to_integer - to_integer;
if y == 0 {
return negative ? -0.0 : 0.0;
}
return y;
}
# x times 2^n, rounded once: musl's `scalbn`.
def scalbn(x: f64, power: i32): f64 {
var n := power;
var y := x;
if n > 1023 {
y *= 8.98846567431158e307;
n -= 1023;
if n > 1023 {
y *= 8.98846567431158e307;
n -= 1023;
if n > 1023 {
n = 1023;
}
}
} else if n < -1022 {
# The last n is below -53, so a subnormal result rounds once.
y *= 2.2250738585072014e-308 * 9007199254740992.0;
n += 1022 - 53;
if n < -1022 {
y *= 2.2250738585072014e-308 * 9007199254740992.0;
n += 1022 - 53;
if n < -1022 {
n = -1022;
}
}
}
return y * real_of_bits(((0x3FF + n) as u64) << 52);
}
# Fused multiplying and adding, of doubles, from musl's fma.c: the product is
# held exactly in 128 bits, the sum is formed in them, and the result is rounded
# once converting to a double.
# A double as its significand, shifted so its top 10 bits and its last are 0,
# its exponent, and its sign.
struct fma_part {
var m: u64;
var e: i32;
var sign: i32;
}
# Exponents from this one up are of zero, infinity, or NaN.
const zero_inf_nan: i32 = 0x7FF - 0x3FF - 52 - 1;
def fma_normalize(x: f64): fma_part {
var ix := bits_of(x);
var e := (ix >> 52) as i32;
val sign := e & 0x800;
e &= 0x7FF;
if e == 0 {
ix = bits_of(x * 9223372036854775808.0);
e = ((ix >> 52) & 0x7FF) as i32;
e = e != 0 ? e - 63 : 0x800;
}
ix &= (1u << 52) - 1;
ix |= 1u << 52;
ix <<= 1;
e -= 0x3FF + 52 + 1;
return fma_part { m = ix, e = e, sign = sign };
}
# 1 where a word is not zero, as C's `!!`.
def any_of(word: u64): u64 {
return word != 0 ? 1 : 0;
}
def fma_double(x: f64, y: f64, z: f64): f64 {
val nx := fma_normalize(x);
val ny := fma_normalize(y);
val nz := fma_normalize(z);
return x * y + z if nx.e >= zero_inf_nan || ny.e >= zero_inf_nan;
if nz.e >= zero_inf_nan {
return x * y + z if nz.e > zero_inf_nan;
return z;
}
# r = x * y, of 128 bits.
val xlo := nx.m & 0xFFFFFFFF;
val xhi := nx.m >> 32;
val ylo := ny.m & 0xFFFFFFFF;
val yhi := ny.m >> 32;
val t1 := xlo * ylo;
val t2 := xlo * yhi + xhi * ylo;
val t3 := xhi * yhi;
var rlo := t1 + (t2 << 32);
var rhi := t3 + (t2 >> 32) + (t1 > rlo ? 1u : 0u);
# The exponents aligned: z shifted left by kz and r right by kr, where kz + kr
# is d, and e is then e + kr.
var zlo: u64 = 0;
var zhi: u64 = 0;
var e := nx.e + ny.e;
var d := nz.e - e;
if d > 0 {
if d < 64 {
zlo = nz.m << (d as u64);
zhi = nz.m >> ((64 - d) as u64);
} else {
zlo = 0;
zhi = nz.m;
e = nz.e - 64;
d -= 64;
if d == 0 {
} else if d < 64 {
rlo = (rhi << ((64 - d) as u64)) | (rlo >> (d as u64)) | any_of(rlo << ((64 - d) as u64));
rhi = rhi >> (d as u64);
} else {
rlo = 1;
rhi = 0;
}
}
} else {
zhi = 0;
d = -d;
if d == 0 {
zlo = nz.m;
} else if d < 64 {
zlo = (nz.m >> (d as u64)) | any_of(nz.m << ((64 - d) as u64));
} else {
zlo = 1;
}
}
# The sum.
var sign := nx.sign ^ ny.sign;
val same_sign := (sign ^ nz.sign) == 0;
var nonzero := true;
if same_sign {
rlo += zlo;
rhi += zhi + (rlo < zlo ? 1u : 0u);
} else {
val t := rlo;
rlo -= zlo;
rhi = rhi - zhi - (t < rlo ? 1u : 0u);
if (rhi >> 63) != 0 {
rlo = 0 - rlo;
rhi = (0 - rhi) - any_of(rlo);
sign = sign != 0 ? 0 : 1;
}
nonzero = rhi != 0;
}
# rhi is the top 63 bits of the result, its last bit sticky.
if nonzero {
e += 64;
d = (leading_zeros(rhi) as i32) - 1;
rhi = (rhi << (d as u64)) | (rlo >> ((64 - d) as u64)) | any_of(rlo << (d as u64));
} else if rlo != 0 {
d = (leading_zeros(rlo) as i32) - 1;
if d < 0 {
rhi = (rlo >> 1) | (rlo & 1);
} else {
rhi = rlo << (d as u64);
}
} else {
# An exact zero, of the sign the operations give it.
return x * y + z;
}
e -= d;
# The double, from |r| in [2^62, 2^63].
var i := rhi as i64;
if sign != 0 {
i = -i;
}
var r := i as f64;
if e < -1022 - 62 {
# Subnormal before rounding.
if e == -1022 - 63 {
var c: f64 = 9223372036854775808.0;
if sign != 0 {
c = -c;
}
if r == c {
# The least normal value, after rounding.
return sign != 0 ? -2.2250738585072014e-308 : 2.2250738585072014e-308;
}
# A bit is lost scaling, so another top bit is added to round once, at
# converting, where it is inexact.
if (rhi << 53) != 0 {
i = ((rhi >> 1) | (rhi & 1) | (1u << 62)) as i64;
if sign != 0 {
i = -i;
}
r = i as f64;
r = 2.0 * r - c;
}
} else {
# Rounded once, scaling.
i = (((rhi >> 10) | any_of(rhi << 54)) << 10) as i64;
if sign != 0 {
i = -i;
}
r = i as f64;
}
}
return scalbn(r, e);
}
# Fused multiplying and adding, of floats, from FreeBSD's s_fmaf.c: the product
# is exact in a double, and so is the sum but where it rounds to a halfway point
# between two floats, which the error then moves off.
def fma_single(x: f32, y: f32, z: f32): f32 {
val xy := (x as f64) * (y as f64);
val wide := z as f64;
val result := xy + wide;
var bits := bits_of(result);
val e := (bits >> 52) & 0x7FF;
if (bits & 0x1FFFFFFF) != 0x10000000 || e == 0x7FF || (result - xy == wide && result - wide == xy) {
return result as f32;
}
val negative := (bits >> 63) != 0;
val error := negative == (wide > xy) ? xy - result + wide : wide - result + xy;
if negative == (error < 0) {
bits++;
} else {
bits--;
}
return real_of_bits(bits) as f32;
}
+263
View File
@@ -0,0 +1,263 @@
#! @file exp.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the exponential functions: e^x and 2^x.
#!
#! Ported from musl 1.2.5, whose `exp` and `exp2` are from Arm's
#! optimized-routines, which says:
#!
#! Copyright (c) 2018, Arm Limited.
#! SPDX-License-Identifier: MIT
#!
#! Each is within 0.52 ulp of the true value for `f64`. An `f32` is worked in
#! `f64` and rounded once more.
module std::math;
#! e raised to a power.
#! @tparam T The type of real.
#! @param x The power.
#! @returns e^x: infinity past about 709.78, and 0 below about -745.13.
pub def exp<T>(x: T): T where T: real {
return exp_double(x as f64) as T;
}
#! 2 raised to a power.
#! @tparam T The type of real.
#! @param x The power.
#! @returns 2^x: infinity from 1024 on, and 0 below -1075.
pub def exp2<T>(x: T): T where T: real {
return exp2_double(x as f64) as T;
}
# The data `exp`, `exp2`, and `pow` share, from musl's exp_data.c.
# How many entries the table has, a power of 2: 2^7.
const exp_size: u64 = 128;
# N / ln 2.
const exp_inverse_ln2_n: f64 = 184.6649652337873;
# -ln 2 / N, as a high part and a low part.
const exp_negative_ln2_high_n: f64 = -0.005415212348111709;
const exp_negative_ln2_low_n: f64 = -1.2864023111638346e-14;
# 1.5 * 2^52, which adding rounds to an integer.
const exp_shift: f64 = 6755399441055744.0;
# The polynomial of e^r, for r near 0: its last four coefficients.
const exp_c2: f64 = 0.49999999999996786;
const exp_c3: f64 = 0.16666666666665886;
const exp_c4: f64 = 0.0416666808410674;
const exp_c5: f64 = 0.008333335853059549;
# 1.5 * 2^52 / N, which adding rounds to a multiple of 1 / N.
const exp2_shift: f64 = 52776558133248.0;
# The polynomial of 2^r, for r near 0.
const exp2_c1: f64 = 0.6931471805599453;
const exp2_c2: f64 = 0.24022650695909065;
const exp2_c3: f64 = 0.0555041086686087;
const exp2_c4: f64 = 0.009618131975721055;
const exp2_c5: f64 = 0.0013332074570119598;
# 2^(k / N) is about H[k] * (1 + T[k]) for each k from 0 to N: the bits of T[k],
# then those of H[k] less (k << 52) / N.
const exp_table: u64[256] = [
0x0000000000000000, 0x3ff0000000000000, 0x3c9b3b4f1a88bf6e, 0x3feff63da9fb3335,
0xbc7160139cd8dc5d, 0x3fefec9a3e778061, 0xbc905e7a108766d1, 0x3fefe315e86e7f85,
0x3c8cd2523567f613, 0x3fefd9b0d3158574, 0xbc8bce8023f98efa, 0x3fefd06b29ddf6de,
0x3c60f74e61e6c861, 0x3fefc74518759bc8, 0x3c90a3e45b33d399, 0x3fefbe3ecac6f383,
0x3c979aa65d837b6d, 0x3fefb5586cf9890f, 0x3c8eb51a92fdeffc, 0x3fefac922b7247f7,
0x3c3ebe3d702f9cd1, 0x3fefa3ec32d3d1a2, 0xbc6a033489906e0b, 0x3fef9b66affed31b,
0xbc9556522a2fbd0e, 0x3fef9301d0125b51, 0xbc5080ef8c4eea55, 0x3fef8abdc06c31cc,
0xbc91c923b9d5f416, 0x3fef829aaea92de0, 0x3c80d3e3e95c55af, 0x3fef7a98c8a58e51,
0xbc801b15eaa59348, 0x3fef72b83c7d517b, 0xbc8f1ff055de323d, 0x3fef6af9388c8dea,
0x3c8b898c3f1353bf, 0x3fef635beb6fcb75, 0xbc96d99c7611eb26, 0x3fef5be084045cd4,
0x3c9aecf73e3a2f60, 0x3fef54873168b9aa, 0xbc8fe782cb86389d, 0x3fef4d5022fcd91d,
0x3c8a6f4144a6c38d, 0x3fef463b88628cd6, 0x3c807a05b0e4047d, 0x3fef3f49917ddc96,
0x3c968efde3a8a894, 0x3fef387a6e756238, 0x3c875e18f274487d, 0x3fef31ce4fb2a63f,
0x3c80472b981fe7f2, 0x3fef2b4565e27cdd, 0xbc96b87b3f71085e, 0x3fef24dfe1f56381,
0x3c82f7e16d09ab31, 0x3fef1e9df51fdee1, 0xbc3d219b1a6fbffa, 0x3fef187fd0dad990,
0x3c8b3782720c0ab4, 0x3fef1285a6e4030b, 0x3c6e149289cecb8f, 0x3fef0cafa93e2f56,
0x3c834d754db0abb6, 0x3fef06fe0a31b715, 0x3c864201e2ac744c, 0x3fef0170fc4cd831,
0x3c8fdd395dd3f84a, 0x3feefc08b26416ff, 0xbc86a3803b8e5b04, 0x3feef6c55f929ff1,
0xbc924aedcc4b5068, 0x3feef1a7373aa9cb, 0xbc9907f81b512d8e, 0x3feeecae6d05d866,
0xbc71d1e83e9436d2, 0x3feee7db34e59ff7, 0xbc991919b3ce1b15, 0x3feee32dc313a8e5,
0x3c859f48a72a4c6d, 0x3feedea64c123422, 0xbc9312607a28698a, 0x3feeda4504ac801c,
0xbc58a78f4817895b, 0x3feed60a21f72e2a, 0xbc7c2c9b67499a1b, 0x3feed1f5d950a897,
0x3c4363ed60c2ac11, 0x3feece086061892d, 0x3c9666093b0664ef, 0x3feeca41ed1d0057,
0x3c6ecce1daa10379, 0x3feec6a2b5c13cd0, 0x3c93ff8e3f0f1230, 0x3feec32af0d7d3de,
0x3c7690cebb7aafb0, 0x3feebfdad5362a27, 0x3c931dbdeb54e077, 0x3feebcb299fddd0d,
0xbc8f94340071a38e, 0x3feeb9b2769d2ca7, 0xbc87deccdc93a349, 0x3feeb6daa2cf6642,
0xbc78dec6bd0f385f, 0x3feeb42b569d4f82, 0xbc861246ec7b5cf6, 0x3feeb1a4ca5d920f,
0x3c93350518fdd78e, 0x3feeaf4736b527da, 0x3c7b98b72f8a9b05, 0x3feead12d497c7fd,
0x3c9063e1e21c5409, 0x3feeab07dd485429, 0x3c34c7855019c6ea, 0x3feea9268a5946b7,
0x3c9432e62b64c035, 0x3feea76f15ad2148, 0xbc8ce44a6199769f, 0x3feea5e1b976dc09,
0xbc8c33c53bef4da8, 0x3feea47eb03a5585, 0xbc845378892be9ae, 0x3feea34634ccc320,
0xbc93cedd78565858, 0x3feea23882552225, 0x3c5710aa807e1964, 0x3feea155d44ca973,
0xbc93b3efbf5e2228, 0x3feea09e667f3bcd, 0xbc6a12ad8734b982, 0x3feea012750bdabf,
0xbc6367efb86da9ee, 0x3fee9fb23c651a2f, 0xbc80dc3d54e08851, 0x3fee9f7df9519484,
0xbc781f647e5a3ecf, 0x3fee9f75e8ec5f74, 0xbc86ee4ac08b7db0, 0x3fee9f9a48a58174,
0xbc8619321e55e68a, 0x3fee9feb564267c9, 0x3c909ccb5e09d4d3, 0x3feea0694fde5d3f,
0xbc7b32dcb94da51d, 0x3feea11473eb0187, 0x3c94ecfd5467c06b, 0x3feea1ed0130c132,
0x3c65ebe1abd66c55, 0x3feea2f336cf4e62, 0xbc88a1c52fb3cf42, 0x3feea427543e1a12,
0xbc9369b6f13b3734, 0x3feea589994cce13, 0xbc805e843a19ff1e, 0x3feea71a4623c7ad,
0xbc94d450d872576e, 0x3feea8d99b4492ed, 0x3c90ad675b0e8a00, 0x3feeaac7d98a6699,
0x3c8db72fc1f0eab4, 0x3feeace5422aa0db, 0xbc65b6609cc5e7ff, 0x3feeaf3216b5448c,
0x3c7bf68359f35f44, 0x3feeb1ae99157736, 0xbc93091fa71e3d83, 0x3feeb45b0b91ffc6,
0xbc5da9b88b6c1e29, 0x3feeb737b0cdc5e5, 0xbc6c23f97c90b959, 0x3feeba44cbc8520f,
0xbc92434322f4f9aa, 0x3feebd829fde4e50, 0xbc85ca6cd7668e4b, 0x3feec0f170ca07ba,
0x3c71affc2b91ce27, 0x3feec49182a3f090, 0x3c6dd235e10a73bb, 0x3feec86319e32323,
0xbc87c50422622263, 0x3feecc667b5de565, 0x3c8b1c86e3e231d5, 0x3feed09bec4a2d33,
0xbc91bbd1d3bcbb15, 0x3feed503b23e255d, 0x3c90cc319cee31d2, 0x3feed99e1330b358,
0x3c8469846e735ab3, 0x3feede6b5579fdbf, 0xbc82dfcd978e9db4, 0x3feee36bbfd3f37a,
0x3c8c1a7792cb3387, 0x3feee89f995ad3ad, 0xbc907b8f4ad1d9fa, 0x3feeee07298db666,
0xbc55c3d956dcaeba, 0x3feef3a2b84f15fb, 0xbc90a40e3da6f640, 0x3feef9728de5593a,
0xbc68d6f438ad9334, 0x3feeff76f2fb5e47, 0xbc91eee26b588a35, 0x3fef05b030a1064a,
0x3c74ffd70a5fddcd, 0x3fef0c1e904bc1d2, 0xbc91bdfbfa9298ac, 0x3fef12c25bd71e09,
0x3c736eae30af0cb3, 0x3fef199bdd85529c, 0x3c8ee3325c9ffd94, 0x3fef20ab5fffd07a,
0x3c84e08fd10959ac, 0x3fef27f12e57d14b, 0x3c63cdaf384e1a67, 0x3fef2f6d9406e7b5,
0x3c676b2c6c921968, 0x3fef3720dcef9069, 0xbc808a1883ccb5d2, 0x3fef3f0b555dc3fa,
0xbc8fad5d3ffffa6f, 0x3fef472d4a07897c, 0xbc900dae3875a949, 0x3fef4f87080d89f2,
0x3c74a385a63d07a7, 0x3fef5818dcfba487, 0xbc82919e2040220f, 0x3fef60e316c98398,
0x3c8e5a50d5c192ac, 0x3fef69e603db3285, 0x3c843a59ac016b4b, 0x3fef7321f301b460,
0xbc82d52107b43e1f, 0x3fef7c97337b9b5f, 0xbc892ab93b470dc9, 0x3fef864614f5a129,
0x3c74b604603a88d3, 0x3fef902ee78b3ff6, 0x3c83c5ec519d7271, 0x3fef9a51fbc74c83,
0xbc8ff7128fd391f0, 0x3fefa4afa2a490da, 0xbc8dae98e223747d, 0x3fefaf482d8e67f1,
0x3c8ec3bc41aa2008, 0x3fefba1bee615a27, 0x3c842b94c3a9eb32, 0x3fefc52b376bba97,
0x3c8a64a931d185ee, 0x3fefd0765b6e4540, 0xbc8e37bae43be3ed, 0x3fefdbfdad9cbe14,
0x3c77893b4d91cd9d, 0x3fefe7c1819e90d8, 0x3c5305c14160cc89, 0x3feff3c22b8f71f1,
];
# e^x and 2^x, from musl's exp.c and exp2.c.
# Where scale * (1 + tmp) may overflow or underflow on the way. The bits of
# scale are `sbits`, whose exponent may have overflowed into the sign, and `ki`
# is the k reducing the argument: above zero the result may overflow, and below
# it underflow.
def exp_special(tmp: f64, scale_bits: u64, ki: u64): f64 {
var sbits := scale_bits;
if (ki & 0x80000000) == 0 {
# k above zero, where the scale's exponent may have overflowed by 460.
sbits -= 1009u << 52;
val scale := real_of_bits(sbits);
return 5.486124068793689e+303 * (scale + scale * tmp);
}
# k below zero, where the subnormals need care.
sbits += 1022u << 52;
val scale := real_of_bits(sbits);
var y := scale + scale * tmp;
if y < 1.0 {
# Rounded to the precision it ends with before scaling into the subnormals,
# so it rounds once.
var lo := scale - y + scale * tmp;
val hi := 1.0 + y;
lo = 1.0 - hi + y + lo;
y = (hi + lo) - 1.0;
if y == 0.0 {
y = 0.0;
}
}
return 2.2250738585072014e-308 * y;
}
def exp_double(x: f64): f64 {
var abstop := top12(x) & 0x7FF;
if abstop - 0x3C9 >= 0x408 - 0x3C9 {
# Below 2^-54, where e^x is 1 + x.
return 1.0 + x if abstop - 0x3C9 >= 0x80000000;
if abstop >= 0x409 {
return 0.0 if bits_of(x) == 0xFFF0000000000000;
return 1.0 + x if abstop >= 0x7FF;
return (bits_of(x) >> 63) != 0 ? underflowed(0) : overflowed(0);
}
# A large x, which `exp_special` works out.
abstop = 0;
}
# e^x is 2^(k / N) * e^r, where x is k ln 2 / N + r, k is an integer, and r
# is within ln 2 / 2N of 0.
val z := exp_inverse_ln2_n * x;
var kd := z + exp_shift;
val ki := bits_of(kd);
kd -= exp_shift;
val r := x + kd * exp_negative_ln2_high_n + kd * exp_negative_ln2_low_n;
# 2^(k / N) is about scale * (1 + tail).
val index := 2 * (ki % exp_size);
val top := ki << (52 - 7);
val tail := real_of_bits(exp_table[index]);
val sbits := exp_table[index + 1] + top;
# e^x is about scale + scale * (tail + e^r - 1).
val r2 := r * r;
val tmp := tail + r + r2 * (exp_c2 + r * exp_c3) + r2 * r2 * (exp_c4 + r * exp_c5);
return exp_special(tmp, sbits, ki) if abstop == 0;
val scale := real_of_bits(sbits);
return scale + scale * tmp;
}
# As `exp_special`, for 2^x, whose scale's exponent may overflow by only 1.
def exp2_special(tmp: f64, scale_bits: u64, ki: u64): f64 {
var sbits := scale_bits;
if (ki & 0x80000000) == 0 {
sbits -= 1u << 52;
val scale := real_of_bits(sbits);
return 2.0 * (scale + scale * tmp);
}
sbits += 1022u << 52;
val scale := real_of_bits(sbits);
var y := scale + scale * tmp;
if y < 1.0 {
var lo := scale - y + scale * tmp;
val hi := 1.0 + y;
lo = 1.0 - hi + y + lo;
y = (hi + lo) - 1.0;
if y == 0.0 {
y = 0.0;
}
}
return 2.2250738585072014e-308 * y;
}
def exp2_double(x: f64): f64 {
var abstop := top12(x) & 0x7FF;
if abstop - 0x3C9 >= 0x408 - 0x3C9 {
return 1.0 + x if abstop - 0x3C9 >= 0x80000000;
if abstop >= 0x409 {
return 0.0 if bits_of(x) == 0xFFF0000000000000;
return 1.0 + x if abstop >= 0x7FF;
if (bits_of(x) >> 63) == 0 {
return overflowed(0);
}
# At -1075 and below.
if bits_of(x) >= 0xC090CC0000000000 {
return underflowed(0);
}
}
# Past 928 either way.
if 2 * bits_of(x) > 2 * 0x408D000000000000u {
abstop = 0;
}
}
# 2^x is 2^(k / N) * 2^r, where x is k / N + r, k is an integer, and r is
# within 1 / 2N of 0.
var kd := x + exp2_shift;
val ki := bits_of(kd);
kd -= exp2_shift;
val r := x - kd;
val index := 2 * (ki % exp_size);
val top := ki << (52 - 7);
val tail := real_of_bits(exp_table[index]);
val sbits := exp_table[index + 1] + top;
val r2 := r * r;
val tmp := tail + r * exp2_c1 + r2 * (exp2_c2 + r * exp2_c3) + r2 * r2 * (exp2_c4 + r * exp2_c5);
return exp2_special(tmp, sbits, ki) if abstop == 0;
val scale := real_of_bits(sbits);
return scale + scale * tmp;
}
+210
View File
@@ -0,0 +1,210 @@
#! @file expm1.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains e^x - 1 and ln(1 + x), which keep their precision where x is near
#! 0, as `exp(x) - 1` and `log(1 + x)` lose it.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `expm1` and `log1p` are from FreeBSD's s_expm1.c
#! and s_log1p.c, which say:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunPro, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! Each is within 1 ulp of the true value for `f64`. An `f32` is worked in
#! `f64` and rounded once more.
module std::math;
#! e raised to a power, less 1, which is precise where the power is near 0.
#! @tparam T The type of real.
#! @param x The power.
#! @returns e^x - 1: x itself near 0, infinity past about 709.78, and -1 below
#! about -37.43 and for negative infinity.
pub def expm1<T>(x: T): T where T: real {
return expm1_double(x as f64) as T;
}
#! The natural logarithm of 1 more than a real, which is precise where the real
#! is near 0.
#! @tparam T The type of real.
#! @param x The real.
#! @returns ln(1 + x): x itself near 0, negative infinity at -1, and NaN below
#! -1.
pub def log1p<T>(x: T): T where T: real {
return log1p_double(x as f64) as T;
}
# The constants of `expm1` and `log1p`.
# Past this, about 709.78, e^x - 1 overflows.
const expm1_overflow: f64 = 709.782712893384;
# ln 2, as a high part, whose last 32 bits are 0 so that multiplying it by a
# small integer is exact, and a low part. `log1p` has them too.
const expm1_ln2_high: f64 = 0.6931471803691238;
const expm1_ln2_low: f64 = 1.9082149292705877e-10;
# 1 / ln 2.
const expm1_inverse_ln2: f64 = 1.4426950408889634;
# The rational function of r near 0: the coefficients of its polynomial in
# (r^2) / 2, each the nth scaled by 2^n.
const expm1_q1: f64 = -0.03333333333333313;
const expm1_q2: f64 = 0.0015873015872548146;
const expm1_q3: f64 = -7.93650757867488e-05;
const expm1_q4: f64 = 4.008217827329362e-06;
const expm1_q5: f64 = -2.0109921818362437e-07;
# The polynomial of ln(1 + f), in s^2 where s is f / (2 + f).
const log1p_lg1: f64 = 0.6666666666666735;
const log1p_lg2: f64 = 0.3999999999940942;
const log1p_lg3: f64 = 0.2857142874366239;
const log1p_lg4: f64 = 0.22222198432149784;
const log1p_lg5: f64 = 0.1818357216161805;
const log1p_lg6: f64 = 0.15313837699209373;
const log1p_lg7: f64 = 0.14798198605116586;
# e^x - 1, from musl's expm1.c.
def expm1_double(argument: f64): f64 {
var x := argument;
val hx := high_word(x) & 0x7FFFFFFF;
val negative := (bits_of(x) >> 63) != 0;
# |x| at least 56 ln 2, where e^x - 1 is -1 below 0 and may overflow above,
# or infinite, or NaN.
if hx >= 0x4043687A {
return x if x != x;
return -1.0 if negative;
return x * 8.98846567431158e307 if x > expm1_overflow;
}
# x is k ln 2 + r, where r is at most ln 2 / 2 from 0, as hi - lo, and c is
# what rounding r lost.
var k: i32 = 0;
var c := 0.0;
if hx > 0x3FD62E42 {
# |x| above ln 2 / 2.
var hi := 0.0;
var lo := 0.0;
if hx < 0x3FF0A2B2 {
# And below 3 ln 2 / 2, where k is 1 or -1.
if !negative {
hi = x - expm1_ln2_high;
lo = expm1_ln2_low;
k = 1;
} else {
hi = x + expm1_ln2_high;
lo = -expm1_ln2_low;
k = -1;
}
} else {
k = (expm1_inverse_ln2 * x + (negative ? -0.5 : 0.5)) as i32;
val t := k as f64;
# Exact, as the high part's last bits are 0.
hi = x - t * expm1_ln2_high;
lo = t * expm1_ln2_low;
}
x = hi - lo;
c = (hi - x) - lo;
} else if hx < 0x3C900000 {
# |x| below 2^-54, where e^x - 1 is x.
return x;
}
# e^r - 1 is r - e, by a rational function of r^2 / 2.
val hfx := 0.5 * x;
val hxs := x * hfx;
val r1 := 1.0 + hxs * (expm1_q1 + hxs * (expm1_q2 + hxs * (expm1_q3 + hxs * (expm1_q4 + hxs * expm1_q5))));
val t := 3.0 - r1 * hfx;
var e := hxs * ((r1 - t) / (6.0 - x * t));
return x - (x * e - hxs) if k == 0;
# c corrected for, e^x is about 2^k (r - e + 1).
e = x * (e - c) - c;
e -= hxs;
return 0.5 * (x - e) - 0.5 if k == -1;
if k == 1 {
return -2.0 * (e - (x + 0.5)) if x < -0.25;
return 1.0 + 2.0 * (x - e);
}
val twopk := real_of_bits(((0x3FF + k) as u64) << 52);
if k < 0 || k > 56 {
# k below 0 or past 56, where 2^k (r - e + 1) - 1 is near enough.
var y := x - e + 1.0;
if k == 1024 {
# 2^k overflows, so it is 2 * 2^1023.
y = y * 2.0 * 8.98846567431158e307;
} else {
y = y * twopk;
}
return y - 1.0;
}
# Else 2^k (r - e + (1 - 2^-k)), the 1 taken away before scaling.
val twomk := real_of_bits(((0x3FF - k) as u64) << 52);
return (x - e + (1.0 - twomk)) * twopk if k < 20;
return (x - (e + twomk) + 1.0) * twopk;
}
# ln(1 + x), from musl's log1p.c.
def log1p_double(x: f64): f64 {
val hx := high_word(x);
# 1 + x is 2^k (1 + f), where 1 + f is from sqrt(2) / 2 to sqrt 2, and c
# corrects for 1 + x being rounded.
var k: i32 = 1;
var c := 0.0;
var f := 0.0;
if hx < 0x3FDA827A || (hx >> 31) != 0 {
# 1 + x below sqrt 2, a little over.
if hx >= 0xBFF00000 {
# x at most -1, or NaN of the sign bit.
return x / 0.0 if x == -1.0;
return (x - x) / 0.0;
}
# |x| below 2^-53, where ln(1 + x) is x.
return x if (hx << 1) < (0x3CA00000 << 1);
if hx <= 0xBFD2BEC4 {
# 1 + x from sqrt(2) / 2, a little under, where x is f itself.
k = 0;
c = 0.0;
f = x;
}
} else if hx >= 0x7FF00000 {
# Infinite, or NaN.
return x;
}
if k != 0 {
var u := 1.0 + x;
var hu := high_word(u);
hu += 0x3FF00000 - 0x3FE6A09E;
k = ((hu >> 20) as i32) - 0x3FF;
# ln(1 + x) - ln u is about c / u, which is too small to count past 2^54.
if k < 54 {
c = k >= 2 ? 1.0 - (u - x) : x - (u - 1.0);
c /= u;
} else {
c = 0.0;
}
# u scaled into [sqrt(2) / 2, sqrt 2].
hu = (hu & 0x000FFFFF) + 0x3FE6A09E;
u = with_high_word(u, hu);
f = u - 1.0;
}
val hfsq := 0.5 * f * f;
val s := f / (2.0 + f);
val z := s * s;
val w := z * z;
val t1 := w * (log1p_lg2 + w * (log1p_lg4 + w * log1p_lg6));
val t2 := z * (log1p_lg1 + w * (log1p_lg3 + w * (log1p_lg5 + w * log1p_lg7)));
val r := t2 + t1;
val dk := k as f64;
return s * (hfsq + r) + (dk * expm1_ln2_low + c) - hfsq + f + dk * expm1_ln2_high;
}
+217
View File
@@ -0,0 +1,217 @@
#! @file hyperbolic.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the hyperbolic functions, sinh, cosh, and tanh, and their inverses,
#! asinh, acosh, and atanh.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license.
#!
#! Each is within 2 ulp of the true value for `f64`, and `cosh` within 1: `tanh`
#! comes nearest 2, near 0.2, and `acosh` near 1. An `f32` is worked in `f64`
#! and rounded once more.
import core::intrinsics;
module std::math;
#! The hyperbolic sine of a real, (e^x - e^-x) / 2.
#! @tparam T The type of real.
#! @param x The real.
#! @returns sinh x, of x's sign: x itself near 0, and infinity past about
#! 710.48.
pub def sinh<T>(x: T): T where T: real {
return sinh_double(x as f64) as T;
}
#! The hyperbolic cosine of a real, (e^x + e^-x) / 2.
#! @tparam T The type of real.
#! @param x The real.
#! @returns cosh x, at least 1: 1 near 0, and infinity past about 710.48 either
#! way.
pub def cosh<T>(x: T): T where T: real {
return cosh_double(x as f64) as T;
}
#! The hyperbolic tangent of a real, sinh x / cosh x.
#! @tparam T The type of real.
#! @param x The real.
#! @returns tanh x, of x's sign: x itself near 0, and 1 past about 19.06, and
#! -1 below about -19.06, infinities included.
pub def tanh<T>(x: T): T where T: real {
return tanh_double(x as f64) as T;
}
#! The inverse hyperbolic sine of a real, the y whose sinh is x.
#! @tparam T The type of real.
#! @param x The real.
#! @returns asinh x, of x's sign: x itself near 0, and infinities themselves.
pub def asinh<T>(x: T): T where T: real {
return asinh_double(x as f64) as T;
}
#! The inverse hyperbolic cosine of a real, the y from 0 up whose cosh is x.
#! @tparam T The type of real.
#! @param x The real, at least 1.
#! @returns acosh x: 0 at 1, infinity for infinity, and NaN below 1.
pub def acosh<T>(x: T): T where T: real {
return acosh_double(x as f64) as T;
}
#! The inverse hyperbolic tangent of a real, the y whose tanh is x.
#! @tparam T The type of real.
#! @param x The real, from -1 to 1.
#! @returns atanh x, of x's sign: x itself near 0, infinity of x's sign at 1
#! and -1, and NaN beyond them.
pub def atanh<T>(x: T): T where T: real {
return atanh_double(x as f64) as T;
}
# A sign times e^x / 2, for x from about ln(DBL_MAX) up, where e^x overflows,
# from musl's __expo2.c: e^(x - k ln 2) times 2^(k - 1). k is odd, so 2^(k - 1)
# is the square of a scale, which multiplies twice as the square overflows,
# and k ln 2 is a double with little relative error.
const hyperbolic_k: i32 = 2043;
const hyperbolic_k_ln2: f64 = 1416.0996898839683;
def hyperbolic_expo2(x: f64, sign: f64): f64 {
val scale := of_words(((0x3FF + hyperbolic_k / 2) as u32) << 20, 0);
return exp_double(x - hyperbolic_k_ln2) * (sign * scale) * scale;
}
# sinh x, from musl's sinh.c, of e^|x| - 1.
def sinh_double(x: f64): f64 {
var h := 0.5;
if (bits_of(x) >> 63) != 0 {
h = -h;
}
val absx := real_of_bits(bits_of(x) & 0x7FFFFFFFFFFFFFFF);
val w := high_word(absx);
# |x| below ln(DBL_MAX).
if w < 0x40862E42 {
val t := expm1_double(absx);
if w < 0x3FF00000 {
# Below 2^-26, sinh x is x.
return x if w < 0x3FF00000 - (26 << 20);
return h * (2.0 * t - t * t / (t + 1.0));
}
return h * (t + t / (t + 1.0));
}
# |x| above ln(DBL_MAX), or NaN.
return hyperbolic_expo2(absx, 2.0 * h);
}
# cosh x, from musl's cosh.c.
def cosh_double(argument: f64): f64 {
val x := real_of_bits(bits_of(argument) & 0x7FFFFFFFFFFFFFFF);
val w := high_word(x);
# |x| below ln 2, by e^|x| - 1.
if w < 0x3FE62E42 {
# Below 2^-26, cosh x is 1.
return 1.0 if w < 0x3FF00000 - (26 << 20);
val t := expm1_double(x);
return 1.0 + t * t / (2.0 * (1.0 + t));
}
# Below ln(DBL_MAX), by e^|x|.
if w < 0x40862E42 {
val t := exp_double(x);
return 0.5 * (t + 1.0 / t);
}
# Above ln(DBL_MAX), or NaN.
return hyperbolic_expo2(x, 1.0);
}
# tanh x, from musl's tanh.c, of e^2|x| - 1.
def tanh_double(argument: f64): f64 {
val negative := (bits_of(argument) >> 63) != 0;
val x := real_of_bits(bits_of(argument) & 0x7FFFFFFFFFFFFFFF);
val w := high_word(x);
var t := 0.0;
if w > 0x3FE193EA {
# |x| above ln(3) / 2, about 0.5493, or NaN.
if w > 0x40340000 {
# Above 20, where tanh x is 1, or NaN, which this keeps.
t = 1.0 - 0.0 / x;
} else {
t = expm1_double(2.0 * x);
t = 1.0 - 2.0 / (t + 2.0);
}
} else if w > 0x3FD058AE {
# Above ln(5/3) / 2, about 0.2554.
t = expm1_double(2.0 * x);
t = t / (t + 2.0);
} else if w >= 0x00100000 {
# Normal.
t = expm1_double(-2.0 * x);
t = -t / (t + 2.0);
} else {
# Subnormal, where tanh x is x.
t = x;
}
return negative ? -t : t;
}
# asinh x, from musl's asinh.c: ln(|x| + sqrt(x^2 + 1)), of x's sign.
def asinh_double(argument: f64): f64 {
val bits := bits_of(argument);
val e := (bits >> 52) & 0x7FF;
val negative := (bits >> 63) != 0;
var x := real_of_bits(bits & 0x7FFFFFFFFFFFFFFF);
if e >= 0x3FF + 26 {
# |x| at least 2^26, infinite, or NaN, where it is ln 2|x|.
x = log_double(x) + ln_2;
} else if e >= 0x3FF + 1 {
# At least 2.
x = log_double(2.0 * x + 1.0 / (square_root(x * x + 1.0) + x));
} else if e >= 0x3FF - 26 {
# At least 2^-26.
x = log1p_double(x + x * x / (square_root(x * x + 1.0) + 1.0));
}
# Below 2^-26, asinh x is x.
return negative ? -x : x;
}
# acosh x, from musl's acosh.c: ln(x + sqrt(x^2 - 1)).
def acosh_double(x: f64): f64 {
# Below 1, NaN. musl leaves this to the functions it calls, which give it but
# for some x from -2^26 to -2, where they give a number; the NaN is the one
# they give elsewhere.
return invalid(x) if x < 1.0;
val e := (bits_of(x) >> 52) & 0x7FF;
# Below 2.
return log1p_double(x - 1.0 + square_root((x - 1.0) * (x - 1.0) + 2.0 * (x - 1.0))) if e < 0x3FF + 1;
# Below 2^26.
return log_double(2.0 * x - 1.0 / (x + square_root(x * x - 1.0))) if e < 0x3FF + 26;
# At least 2^26, or NaN, where it is ln 2x.
return log_double(x) + ln_2;
}
# atanh x, from musl's atanh.c: ln((1 + x) / (1 - x)) / 2, of x's sign.
def atanh_double(argument: f64): f64 {
val bits := bits_of(argument);
val e := (bits >> 52) & 0x7FF;
val negative := (bits >> 63) != 0;
var y := real_of_bits(bits & 0x7FFFFFFFFFFFFFFF);
if e < 0x3FF - 1 {
# |x| below 1/2, and below 2^-32, where atanh x is x.
if e >= 0x3FF - 32 {
y = 0.5 * log1p_double(2.0 * y + 2.0 * y * y / (1.0 - y));
}
} else {
# Divided first, so it doesn't overflow.
y = 0.5 * log1p_double(2.0 * (y / (1.0 - y)));
}
return negative ? -y : y;
}
+293
View File
@@ -0,0 +1,293 @@
#! @file integers.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the operations of integers processors give but the operators do not:
#! rotating; adding, subtracting, and multiplying with a check or with
#! saturation; powers, greatest common divisors, square roots, and dividing
#! toward negative infinity. Each works for every integer type, signed or
#! unsigned, of any width. Counting bits and swapping bytes are `core`'s.
import core::intrinsics;
module std::math;
#! An integer's bits turned toward its top, those leaving the top coming back in
#! at the bottom.
#! @tparam T The type of integer.
#! @param x The integer.
#! @param by How many places, of which only the remainder dividing by the
#! type's width counts.
#! @returns The integer turned.
pub def rotate_left<T>(x: T, by: u32): T where T: integer {
val width := size_of::<T>() * 8;
val n := by as u64 % width;
return x if n == 0;
val mask := width_mask::<T>();
val bits := x as u64 & mask;
return (((bits << n) | (bits >> (width - n))) & mask) as T;
}
#! An integer's bits turned toward its bottom, those leaving the bottom coming
#! back in at the top.
#! @tparam T The type of integer.
#! @param x The integer.
#! @param by How many places, of which only the remainder dividing by the
#! type's width counts.
#! @returns The integer turned.
pub def rotate_right<T>(x: T, by: u32): T where T: integer {
val width := size_of::<T>() * 8;
val n := by as u64 % width;
return x if n == 0;
return rotate_left(x, (width - n) as u32);
}
#! `a + b`, where it fits the type.
#! @tparam T The type of integer.
#! @param a One integer.
#! @param b The other.
#! @returns The sum, or `nothing` where it overflows.
pub def checked_add<T>(a: T, b: T): maybe<T> where T: integer {
val sum := a + b;
if is_signed::<T>() {
return nothing {} if (a < 0) == (b < 0) && (sum < 0) != (a < 0);
return sum;
}
return nothing {} if sum < a;
return sum;
}
#! `a - b`, where it fits the type.
#! @tparam T The type of integer.
#! @param a The integer subtracted from.
#! @param b The integer subtracted.
#! @returns The difference, or `nothing` where it overflows.
pub def checked_sub<T>(a: T, b: T): maybe<T> where T: integer {
val difference := a - b;
if is_signed::<T>() {
return nothing {} if (a < 0) != (b < 0) && (difference < 0) != (a < 0);
return difference;
}
return nothing {} if a < b;
return difference;
}
#! `a * b`, where it fits the type.
#! @tparam T The type of integer.
#! @param a One integer.
#! @param b The other.
#! @returns The product, or `nothing` where it overflows.
pub def checked_mul<T>(a: T, b: T): maybe<T> where T: integer {
return 0 as T if a == 0;
# -1 times the most negative integer is the one product dividing back cannot
# check, since that division overflows too.
if is_signed::<T>() && a == ~(0 as T) {
return nothing {} if b == least_of::<T>();
return -b;
}
# The product wrapped, which divides back to `b` only where it did not wrap.
val product := a * b;
return nothing {} if product / a != b;
return product;
}
#! An integer raised to a power, where it fits the type.
#! @tparam T The type of integer.
#! @param x The integer.
#! @param exponent The power.
#! @returns x^exponent, 1 where the power is 0, or `nothing` where it overflows.
pub def checked_pow<T>(x: T, exponent: u32): maybe<T> where T: integer {
var result := 1 as T;
var base := x;
var left := exponent;
while left != 0 {
if (left & 1) != 0 {
result = checked_mul(result, base) else { return nothing {}; };
}
left >>= 1;
if left != 0 {
base = checked_mul(base, base) else { return nothing {}; };
}
}
return result;
}
#! `a + b`, held at the type's greatest or least value where it would pass it.
#! @tparam T The type of integer.
#! @param a One integer.
#! @param b The other.
#! @returns The sum, saturated.
pub def saturating_add<T>(a: T, b: T): T where T: integer {
if checked_add(a, b) is some(sum) {
return sum;
}
return is_signed::<T>() && b < 0 ? least_of::<T>() : greatest_of::<T>();
}
#! `a - b`, held at the type's greatest or least value where it would pass it.
#! @tparam T The type of integer.
#! @param a The integer subtracted from.
#! @param b The integer subtracted.
#! @returns The difference, saturated.
pub def saturating_sub<T>(a: T, b: T): T where T: integer {
if checked_sub(a, b) is some(difference) {
return difference;
}
return is_signed::<T>() && b < 0 ? greatest_of::<T>() : least_of::<T>();
}
#! `a * b`, held at the type's greatest or least value where it would pass it.
#! @tparam T The type of integer.
#! @param a One integer.
#! @param b The other.
#! @returns The product, saturated.
pub def saturating_mul<T>(a: T, b: T): T where T: integer {
if checked_mul(a, b) is some(product) {
return product;
}
return is_signed::<T>() && (a < 0) != (b < 0) ? least_of::<T>() : greatest_of::<T>();
}
#! An integer raised to a power, wrapping where it overflows, as `*` does.
#! @tparam T The type of integer.
#! @param x The integer.
#! @param exponent The power.
#! @returns x^exponent, as the type holds it; 1 where the power is 0.
pub def int_pow<T>(x: T, exponent: u32): T where T: integer {
var result := 1 as T;
var base := x;
var left := exponent;
while left != 0 {
if (left & 1) != 0 {
result = result * base;
}
left >>= 1;
if left != 0 {
base = base * base;
}
}
return result;
}
#! The greatest common divisor of two integers: the greatest integer dividing
#! both, whatever their signs.
#! @tparam T The type of integer.
#! @param a One integer.
#! @param b The other.
#! @returns The divisor, never below zero, and 0 where both are 0. Where it is
#! the magnitude of a signed type's most negative integer, which the
#! type cannot hold, it wraps to that integer.
pub def gcd<T>(a: T, b: T): T where T: integer {
return word_gcd(magnitude_of(a), magnitude_of(b)) as T;
}
#! The least common multiple of two integers: the least integer above zero both
#! divide.
#! @tparam T The type of integer.
#! @param a One integer.
#! @param b The other.
#! @returns The multiple, never below zero, and 0 where either is 0. It wraps
#! where the type cannot hold it, as `*` does.
pub def lcm<T>(a: T, b: T): T where T: integer {
val x := magnitude_of(a);
val y := magnitude_of(b);
return 0 as T if x == 0 || y == 0;
return ((x / word_gcd(x, y)) * y) as T;
}
#! The integer square root: the greatest integer whose square is not above an
#! integer.
#! @tparam T The type of integer.
#! @param x The integer.
#! @returns The root, and 0 below zero.
pub def isqrt<T>(x: T): T where T: integer {
return 0 as T if x <= 0;
val n := x as u64 & width_mask::<T>();
# The root of the nearest double is within one or two of the root.
var root := square_root(n as f64) as u64;
while root > 0 && root > n / root {
root--;
}
while root + 1 <= n / (root + 1) {
root++;
}
return root as T;
}
#! `a / b`, rounded toward negative infinity rather than toward zero, so -7 / 2
#! gives -4 where `/` gives -3. Of unsigned integers, it is `/`.
#! @tparam T The type of integer.
#! @param a The dividend.
#! @param b The divisor, which stops the program where it is zero, as `/`
#! does.
#! @returns The quotient.
pub def div_floor<T>(a: T, b: T): T where T: integer {
val quotient := a / b;
if is_signed::<T>() && quotient * b != a && (a < 0) != (b < 0) {
return quotient - 1;
}
return quotient;
}
#! What is left dividing toward negative infinity, which has the divisor's sign,
#! so -7 and 2 give 1 where `%` gives -1. `div_floor(a, b) * b + rem_floor(a, b)`
#! is `a`. Of unsigned integers, it is `%`.
#! @tparam T The type of integer.
#! @param a The dividend.
#! @param b The divisor, which stops the program where it is zero, as `%`
#! does.
#! @returns The remainder.
pub def rem_floor<T>(a: T, b: T): T where T: integer {
val rest := a % b;
if is_signed::<T>() && rest != 0 && (rest < 0) != (b < 0) {
return rest + b;
}
return rest;
}
# What the functions above know of a type of integer.
# The bits of a type, low ones set, as a word.
def width_mask<T>(): u64 where T: integer {
if const size_of::<T>() == 8 {
return 0xFFFFFFFFFFFFFFFFu;
}
return (1u << (size_of::<T>() * 8)) - 1;
}
# Whether a type of integer is signed, as its every bit set is below zero.
def is_signed<T>(): bool where T: integer {
return ~(0 as T) < 0;
}
# The greatest value of a type of integer.
def greatest_of<T>(): T where T: integer {
return is_signed::<T>() ? (width_mask::<T>() >> 1) as T : ~(0 as T);
}
# The least value of a type of integer.
def least_of<T>(): T where T: integer {
return is_signed::<T>() ? (1u << (size_of::<T>() * 8 - 1)) as T : 0 as T;
}
# An integer's distance from zero, as a word, which holds it whatever its type.
def magnitude_of<T>(x: T): u64 where T: integer {
if is_signed::<T>() && x < 0 {
return 0 - (x as i64) as u64;
}
return x as u64 & width_mask::<T>();
}
# Euclid's greatest common divisor, of words.
def word_gcd(a: u64, b: u64): u64 {
var x := a;
var y := b;
while y != 0 {
val rest := x % y;
x = y;
y = rest;
}
return x;
}
+314
View File
@@ -0,0 +1,314 @@
#! @file inverse.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the inverse trigonometric functions: the arcsine, the arccosine,
#! and the arctangent, of one real and of a point's two coordinates.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `asin`, `acos`, `atan`, and `atan2` are from
#! FreeBSD's e_asin.c, e_acos.c, s_atan.c, and e_atan2.c, of Sun's fdlibm, by
#! way of musl. e_asin.c, e_acos.c, and e_atan2.c say:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunSoft, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! and s_atan.c says:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunPro, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! For `f64`, `asin`, `acos`, and `atan` are within 0.9 ulp of the true value,
#! and `atan2` within about 1.5 ulp, since it rounds y / x before taking its
#! arctangent. An `f32` is worked in `f64` and rounded once more.
import core::intrinsics;
module std::math;
#! The arcsine of a real: the angle, in radians, whose sine it is.
#! @tparam T The type of real.
#! @param x The sine, from -1 to 1.
#! @returns The angle, from -pi/2 to pi/2: `-0` for `-0`, and NaN past 1
#! either way or for NaN.
pub def asin<T>(x: T): T where T: real {
return asin_double(x as f64) as T;
}
#! The arccosine of a real: the angle, in radians, whose cosine it is.
#! @tparam T The type of real.
#! @param x The cosine, from -1 to 1.
#! @returns The angle, from 0 to pi: 0 for 1, pi for -1, and NaN past 1 either
#! way or for NaN.
pub def acos<T>(x: T): T where T: real {
return acos_double(x as f64) as T;
}
#! The arctangent of a real: the angle, in radians, whose tangent it is.
#! @tparam T The type of real.
#! @param x The tangent.
#! @returns The angle, from -pi/2 to pi/2: `-0` for `-0`, pi/2 for infinity,
#! -pi/2 for negative infinity, and NaN for NaN.
pub def atan<T>(x: T): T where T: real {
return atan_double(x as f64) as T;
}
#! The angle, in radians, from the positive x axis to the point (x, y): the
#! arctangent of y / x, in the quadrant of the point.
#! @tparam T The type of real.
#! @param y The point's y coordinate.
#! @param x The point's x coordinate.
#! @returns The angle, from -pi to pi, of the sign of y, zeros included. A
#! `±0` y gives `±0` where x is `0` or above, and `±pi` where x is
#! `-0` or below. A zero x, or an infinite y, gives `±pi/2` otherwise,
#! and an infinite x `±0` or `±pi`, or `±pi/4` or `±3pi/4` where y is
#! infinite too. NaN where either is NaN.
pub def atan2<T>(y: T, x: T): T where T: real {
return atan2_double(y as f64, x as f64) as T;
}
# The data `asin` and `acos` share, from musl's asin.c and acos.c.
# pi/2, as a high part and a low part.
const inverse_pio2_high: f64 = 1.5707963267948966;
const inverse_pio2_low: f64 = 6.123233995736766e-17;
# A rational function near (asin(x) - x) / x^3, of x^2, on [0, 0.5]: the
# coefficients of its numerator and of its denominator.
const inverse_p0: f64 = 0.16666666666666666;
const inverse_p1: f64 = -0.3255658186224009;
const inverse_p2: f64 = 0.20121253213486293;
const inverse_p3: f64 = -0.04005553450067941;
const inverse_p4: f64 = 0.0007915349942898145;
const inverse_p5: f64 = 3.479331075960212e-05;
const inverse_q1: f64 = -2.403394911734414;
const inverse_q2: f64 = 2.0209457602335057;
const inverse_q3: f64 = -0.6882839716054533;
const inverse_q4: f64 = 0.07703815055590194;
# The rational function, of z = x^2.
def inverse_rational(z: f64): f64 {
val p := z * (inverse_p0 + z * (inverse_p1 + z * (inverse_p2 + z * (inverse_p3 + z * (inverse_p4 + z * inverse_p5)))));
val q := 1.0 + z * (inverse_q1 + z * (inverse_q2 + z * (inverse_q3 + z * inverse_q4)));
return p / q;
}
# The arcsine, from musl's asin.c.
def asin_double(x: f64): f64 {
val hx := high_word(x);
val ix := hx & 0x7FFFFFFF;
# At 1 and past it either way, or NaN: asin(±1) is ±pi/2.
if ix >= 0x3FF00000 {
return x * inverse_pio2_high if ((ix - 0x3FF00000) | low_word(x)) == 0;
return 0.0 / (x - x);
}
# Below 0.5, asin(x) is x + x^3 R(x^2), and x itself below 2^-26.
if ix < 0x3FE00000 {
return x if ix < 0x3E500000 && ix >= 0x00100000;
return x + x * inverse_rational(x * x);
}
# From 0.5 to 1, asin(x) is pi/2 - 2 asin(s), where s is sqrt((1 - |x|) / 2)
# and its arcsine is s + s z R(z) for z = s^2.
val z := (1.0 - abs(x)) * 0.5;
val s := square_root(z);
val r := inverse_rational(z);
var y: f64 = 0;
if ix >= 0x3FEF3333 {
# Above 0.975.
y = inverse_pio2_high - (2.0 * (s + s * r) - inverse_pio2_low);
} else {
# f + c is s, where f is s with its low word cleared.
val f := with_low_word(s, 0);
val c := (z - f * f) / (s + f);
y = 0.5 * inverse_pio2_high - (2.0 * s * r - (inverse_pio2_low - 2.0 * c) - (0.5 * inverse_pio2_high - 2.0 * f));
}
return (hx >> 31) != 0 ? -y : y;
}
# The arccosine, from musl's acos.c.
def acos_double(x: f64): f64 {
val hx := high_word(x);
val ix := hx & 0x7FFFFFFF;
# At 1 and past it either way, or NaN: acos(1) is 0 and acos(-1) is pi.
if ix >= 0x3FF00000 {
if ((ix - 0x3FF00000) | low_word(x)) == 0 {
return 2.0 * inverse_pio2_high if (hx >> 31) != 0;
return 0.0;
}
return 0.0 / (x - x);
}
# Below 0.5, acos(x) is pi/2 - asin(x), and pi/2 itself below 2^-57.
if ix < 0x3FE00000 {
return inverse_pio2_high if ix <= 0x3C600000;
return inverse_pio2_high - (x - (inverse_pio2_low - x * inverse_rational(x * x)));
}
# Below -0.5, acos(x) is pi - 2 asin(s), where s is sqrt((1 + x) / 2).
if (hx >> 31) != 0 {
val z := (1.0 + x) * 0.5;
val s := square_root(z);
val w := inverse_rational(z) * s - inverse_pio2_low;
return 2.0 * (inverse_pio2_high - (s + w));
}
# Above 0.5, acos(x) is 2 asin(s), where s is sqrt((1 - x) / 2), worked as
# df + c, where df is s with its low word cleared.
val z := (1.0 - x) * 0.5;
val s := square_root(z);
val df := with_low_word(s, 0);
val c := (z - df * df) / (s + df);
val w := inverse_rational(z) * s + c;
return 2.0 * (df + w);
}
# The data of `atan`, from musl's atan.c.
# atan(0.5), atan(1), atan(1.5), and atan(infinity), as high parts and low
# parts.
const atan_high: f64[4] = [
0.4636476090008061, 0.7853981633974483, 0.982793723247329, 1.5707963267948966,
];
const atan_low: f64[4] = [
2.2698777452961687e-17, 3.061616997868383e-17, 1.3903311031230998e-17,
6.123233995736766e-17,
];
# The polynomial of (x - atan(x)) / x^3, of x^2, on [0, 7/16].
const atan_t: f64[11] = [
0.3333333333333293, -0.19999999999876483, 0.14285714272503466,
-0.11111110405462356, 0.09090887133436507, -0.0769187620504483,
0.06661073137387531, -0.058335701337905735, 0.049768779946159324,
-0.036531572744216916, 0.016285820115365782,
];
# The arctangent, from musl's atan.c.
def atan_double(x: f64): f64 {
var ix := high_word(x);
val sign := ix >> 31;
ix &= 0x7FFFFFFF;
# From 2^66 up, atan(x) is ±pi/2, or NaN.
if ix >= 0x44100000 {
return x if x != x;
val z := atan_high[3];
return sign != 0 ? -z : z;
}
# |x| is reduced to t, near one of 0, 0.5, 1, 1.5, and infinity, whose
# arctangent is id's of atan_high and atan_low.
var t := x;
var id: i32 = -1;
if ix < 0x3FDC0000 {
# Below 7/16, and x itself below 2^-27.
return x if ix < 0x3E400000;
} else {
t = abs(x);
if ix < 0x3FF30000 {
if ix < 0x3FE60000 {
# From 7/16 to 11/16.
id = 0;
t = (2.0 * t - 1.0) / (2.0 + t);
} else {
# From 11/16 to 19/16.
id = 1;
t = (t - 1.0) / (t + 1.0);
}
} else {
if ix < 0x40038000 {
# From 19/16 to 39/16.
id = 2;
t = (t - 1.5) / (1.0 + 1.5 * t);
} else {
# From 39/16 to 2^66.
id = 3;
t = -1.0 / t;
}
}
}
# The polynomial, of its odd and even terms apart.
val z := t * t;
val w := z * z;
val s1 := z * (atan_t[0] + w * (atan_t[2] + w * (atan_t[4] + w * (atan_t[6] + w * (atan_t[8] + w * atan_t[10])))));
val s2 := w * (atan_t[1] + w * (atan_t[3] + w * (atan_t[5] + w * (atan_t[7] + w * atan_t[9]))));
return t - t * (s1 + s2) if id < 0;
val k := id as u64;
val y := atan_high[k] - (t * (s1 + s2) - atan_low[k] - t);
return sign != 0 ? -y : y;
}
# The data of `atan2`, from musl's atan2.c: pi, as a high part and a low part.
const atan_pi: f64 = 3.141592653589793;
const atan_pi_low: f64 = 1.2246467991473532e-16;
# The arctangent of y / x, in the point's quadrant, from musl's atan2.c.
def atan2_double(y: f64, x: f64): f64 {
return x + y if x != x || y != y;
var ix := high_word(x);
val lx := low_word(x);
var iy := high_word(y);
val ly := low_word(y);
# atan2(y, 1) is atan(y).
return atan_double(y) if ((ix - 0x3FF00000) | lx) == 0;
# Twice x's sign and y's.
val m := ((iy >> 31) & 1) | ((ix >> 30) & 2);
ix &= 0x7FFFFFFF;
iy &= 0x7FFFFFFF;
# y is zero: ±0 where x's sign is clear, and ±pi where it is set.
if (iy | ly) == 0 {
return y if m < 2;
return m == 2 ? atan_pi : -atan_pi;
}
# x is zero: ±pi/2.
if (ix | lx) == 0 {
return (m & 1) != 0 ? -atan_pi / 2.0 : atan_pi / 2.0;
}
# x is infinite.
if ix == 0x7FF00000 {
if iy == 0x7FF00000 {
return atan_pi / 4.0 if m == 0;
return -atan_pi / 4.0 if m == 1;
return 3.0 * atan_pi / 4.0 if m == 2;
return -3.0 * atan_pi / 4.0;
}
return 0.0 if m == 0;
return -0.0 if m == 1;
return atan_pi if m == 2;
return -atan_pi;
}
# |y / x| is above 2^64, or y is infinite: ±pi/2.
if ix + 0x04000000 < iy || iy == 0x7FF00000 {
return (m & 1) != 0 ? -atan_pi / 2.0 : atan_pi / 2.0;
}
# atan(|y / x|), taken as 0 where it is below 2^-64 and x is negative, so it
# does not underflow.
var z: f64 = 0;
if (m & 2) == 0 || iy + 0x04000000 >= ix {
z = atan_double(abs(y / x));
}
return z if m == 0;
return -z if m == 1;
return atan_pi - (z - atan_pi_low) if m == 2;
return (z - atan_pi_low) - atan_pi;
}
+179
View File
@@ -0,0 +1,179 @@
#! @file lanes.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the functions of reals as methods of `simd`, lane by lane: square
#! roots, rounding to integers, and fused multiplying and adding. Each gives in
#! every lane what the function of the same name gives of one real, worked with
#! the processor's vector instructions where it has them, as `simd`'s own
#! methods are.
import core::intrinsics;
module std::math;
#! Each real lane's square root, correctly rounded, as `sqrt` gives it.
#! @param this The vector.
#! @returns The vector.
pub def simd<L[N]>::sqrt(&this): simd<L[N]> {
var made: simd<L[N]>;
if const L is real {
if !lanes_done::<L, lanes_sqrt, N>((&mut made) as *mut u8, this as *u8, null, null, 16, 16) {
var r: L[N] = this.lanes();
for i in 0..N {
r[i] = sqrt(r[i]);
}
made = simd::<L[N]>::of(r);
}
} else {
compile_error("`sqrt` takes real lanes, and these are integers.");
}
return made;
}
#! Each real lane's greatest integer not above it, as `floor` gives it.
#! @param this The vector.
#! @returns The vector.
pub def simd<L[N]>::floor(&this): simd<L[N]> {
var made: simd<L[N]>;
if const L is real {
if !lanes_done::<L, lanes_floor, N>((&mut made) as *mut u8, this as *u8, null, null, 16, 16) {
var r: L[N] = this.lanes();
for i in 0..N {
r[i] = floor(r[i]);
}
made = simd::<L[N]>::of(r);
}
} else {
compile_error("`floor` takes real lanes, and these are integers.");
}
return made;
}
#! Each real lane's least integer not below it, as `ceil` gives it.
#! @param this The vector.
#! @returns The vector.
pub def simd<L[N]>::ceil(&this): simd<L[N]> {
var made: simd<L[N]>;
if const L is real {
if !lanes_done::<L, lanes_ceil, N>((&mut made) as *mut u8, this as *u8, null, null, 16, 16) {
var r: L[N] = this.lanes();
for i in 0..N {
r[i] = ceil(r[i]);
}
made = simd::<L[N]>::of(r);
}
} else {
compile_error("`ceil` takes real lanes, and these are integers.");
}
return made;
}
#! Each real lane's integer part, toward zero, as `trunc` gives it.
#! @param this The vector.
#! @returns The vector.
pub def simd<L[N]>::trunc(&this): simd<L[N]> {
var made: simd<L[N]>;
if const L is real {
if !lanes_done::<L, lanes_trunc, N>((&mut made) as *mut u8, this as *u8, null, null, 16, 16) {
var r: L[N] = this.lanes();
for i in 0..N {
r[i] = trunc(r[i]);
}
made = simd::<L[N]>::of(r);
}
} else {
compile_error("`trunc` takes real lanes, and these are integers.");
}
return made;
}
#! Each real lane's nearest integer, halves away from zero, as `round` gives
#! it, which no instruction rounds, so a lane at a time.
#! @param this The vector.
#! @returns The vector.
pub def simd<L[N]>::round(&this): simd<L[N]> {
var made: simd<L[N]>;
if const L is real {
var r: L[N] = this.lanes();
for i in 0..N {
r[i] = round(r[i]);
}
made = simd::<L[N]>::of(r);
} else {
compile_error("`round` takes real lanes, and these are integers.");
}
return made;
}
#! Each real lane's nearest integer, halves to the even one, as `round_even`
#! gives it.
#! @param this The vector.
#! @returns The vector.
pub def simd<L[N]>::round_even(&this): simd<L[N]> {
var made: simd<L[N]>;
if const L is real {
if !lanes_done::<L, lanes_round_even, N>((&mut made) as *mut u8, this as *u8, null, null, 16, 16) {
var r: L[N] = this.lanes();
for i in 0..N {
r[i] = round_even(r[i]);
}
made = simd::<L[N]>::of(r);
}
} else {
compile_error("`round_even` takes real lanes, and these are integers.");
}
return made;
}
#! `a * b + c`, lane by lane: of reals rounded once, as `fma` gives it, and of
#! integers wrapping.
#! @param this The first factors.
#! @param times The second.
#! @param plus What the products are added to.
#! @returns The vector.
pub def simd<L[N]>::fma(&this, times: &simd<L[N]>, plus: &simd<L[N]>): simd<L[N]> {
var made: simd<L[N]>;
if !lanes_done::<L, lanes_fma, N>((&mut made) as *mut u8, this as *u8, times as *u8, plus as *u8, 16, 16) {
val a: L[N] = this.lanes();
val b: L[N] = times.lanes();
var r: L[N] = plus.lanes();
for i in 0..N {
if const L is real {
r[i] = fma(a[i], b[i], r[i]);
} else {
r[i] = a[i] * b[i] + r[i];
}
}
made = simd::<L[N]>::of(r);
}
return made;
}
# Works an operation out with the vector instructions of the processor running
# the program, where it has them, as `simd`'s own methods do: the whole vector
# at once, or 32 bytes a half at a time where it has them only for 16. Where it
# gives false, the caller works the lanes one at a time.
def lanes_done<L, const OP: u32, const N: u64>(into: *mut u8, a: *u8, b: *u8, c: *u8, a_half: u64, b_half: u64): bool {
if lanes_have::<L, OP, N>() {
lanes_apply::<L, OP, N>(into, a, b, c);
return true;
}
if const N * size_of::<L>() == 32 {
if lanes_have::<L, OP, N / 2>() {
lanes_apply::<L, OP, N / 2>(into, a, b, c);
lanes_apply::<L, OP, N / 2>(into + 16, a + a_half, b == null ? b : b + b_half, c == null ? c : c + 16);
return true;
}
}
return false;
}
# The operations on lanes of these functions, as the compiler numbers them.
const lanes_sqrt: u32 = 13;
const lanes_floor: u32 = 14;
const lanes_ceil: u32 = 15;
const lanes_trunc: u32 = 16;
const lanes_round_even: u32 = 17;
const lanes_fma: u32 = 25;
+289
View File
@@ -0,0 +1,289 @@
#! @file log.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the natural logarithm.
#!
#! Ported from musl 1.2.5, whose `log` is from Arm's optimized-routines, which
#! says:
#!
#! Copyright (c) 2018, Arm Limited.
#! SPDX-License-Identifier: MIT
#!
#! It is within 0.52 ulp of the true value for `f64`. An `f32` is worked in
#! `f64` and rounded once more.
module std::math;
#! The natural logarithm of a real, the power e is raised to to give it.
#! @tparam T The type of real.
#! @param x The real.
#! @returns ln x: negative infinity for zero, and NaN below zero.
pub def log<T>(x: T): T where T: real {
return log_double(x as f64) as T;
}
# The data of `log`, from musl's log_data.c.
# ln 2, as a high part and a low part.
const log_ln2_high: f64 = 0.6931471805598903;
const log_ln2_low: f64 = 5.497923018708371e-14;
# The polynomial of ln(1 + r) for r within 2^-4 of 0, from its second
# coefficient.
const log_b: f64[11] = [
-0.5, 0.3333333333333352, -0.24999999999998432,
0.19999999999320328, -0.16666666669929706, 0.14285715076560868,
-0.12499997863982555, 0.11110712032936046, -0.10000486757818193,
0.09181994006195467, -0.08328363062289341,
];
# The polynomial of ln(1 + r) - r for r within 1/2N of 0, from its second
# coefficient.
const log_a: f64[5] = [
-0.5000000000000001, 0.33333333331825593, -0.2499999999622955,
0.20000304511814496, -0.16667054827627667,
];
# For each of N subintervals of [0.6875, 1.375), 1/c and ln c, for a c near its
# middle.
const log_table: f64[256] = [
1.4504249240398293, -0.3718565645633589, 1.442253508327276,
-0.36620682668944937, 1.4341736174350004, -0.3605888069791945,
1.426183816329995, -0.3550022171419869, 1.4182825527052965,
-0.34944666968829097, 1.4104682921759335, -0.3439217713603284,
1.4027396147468003, -0.3384271921261188, 1.3950954438932313,
-0.332962831494342, 1.3875338232485754, -0.32752794345742586,
1.3800539211058593, -0.32212257167088865, 1.3726542695419708,
-0.3167462884799761, 1.3653332798446802, -0.3113985598928366,
1.358090204587874, -0.3060794515165526, 1.3509234892132138,
-0.300788424667644, 1.3438320840699889, -0.2955252968476998,
1.3368146974742003, -0.29028969275850613, 1.329870114677736,
-0.2850812793277555, 1.322997339161106, -0.27989987391470095,
1.316195352741367, -0.27474526621870154, 1.3094628125672239,
-0.2696169863701243, 1.3027990455471041, -0.26451506180308115,
1.2962024229438942, -0.2594387762767383, 1.2896726275815547,
-0.2543884090981692, 1.2832080305745537, -0.24936321635129843,
1.276807885983376, -0.24436312405975968, 1.2704714060687552,
-0.23938801747897287, 1.2641976054949482, -0.23443761696705678,
1.257985357514882, -0.22951151871518505, 1.2518337750655457,
-0.2246094963439873, 1.2457421919097305, -0.21973149037705753,
1.2397094966625508, -0.2148770752847895, 1.2337348463589233,
-0.210046029103637, 1.2278176973028803, -0.20523836373934046,
1.2219570190618474, -0.20045368751368642, 1.2161519732977757,
-0.1956917537758045, 1.2104018095009725, -0.19095237845203883,
1.204705805718973, -0.18623539250290833, 1.1990631185441964,
-0.18154051731551135, 1.1934733004462308, -0.1768677957431919,
1.1879350812847385, -0.17221657406412305, 1.1824481322833125,
-0.16758697765942543, 1.1770114976921955, -0.16297859687290384,
1.1716248121809465, -0.15839151377804228, 1.1662869231674715,
-0.15382513241456763, 1.1609977486762766, -0.14927976358922024,
1.1557563220795803, -0.14475495398119165, 1.1505619105480347,
-0.14025044090817573, 1.1454138888505974, -0.1357660466685502,
1.140311877374656, -0.1313018016355727, 1.1352550225747513,
-0.12685731518763532, 1.1302429094831266, -0.1224325737671279,
1.1252747693068048, -0.11802724521862729, 1.1203501571039876,
-0.11364127671663482, 1.1154683327680124, -0.10927434611278386,
1.1106291463292157, -0.10492665324943573, 1.1058315813301596,
-0.10059761422644442, 1.1010752177696026, -0.09628717309055901,
1.0963597137952512, -0.09199534069557558, 1.0916844827550398,
-0.08772190036688698, 1.0870487291277784, -0.08346643613867855,
1.082452357388312, -0.07922916827544668, 1.0778948225025884,
-0.0750099004750382, 1.0733751731601076, -0.07080805133352897,
1.068893585073351, -0.06662408085151128, 1.0644491706655506,
-0.06245745471915143, 1.0600414846328305, -0.0583080438042316,
1.0556701316181605, -0.05417576112313327, 1.051334750556926,
-0.050060547896805474, 1.0470347288442157, -0.045962101199052086,
1.0427699229652954, -0.04188056008865715, 1.0385395013738175,
-0.03781540056183985, 1.034343418940345, -0.03376684757915882,
1.0301811073173315, -0.029734619131772888, 1.026052043621297,
-0.025718470239212365, 1.0219561082336197, -0.021718543925430822,
1.0178926505784922, -0.01773446126981071, 1.0138614436244586,
-0.013766252464051831, 1.0098620186501341, -0.009813706322574944,
1.0058938559734134, -0.005876555150052809, 1.00195696235014,
-0.0019550499938532084, 0.9961089923088509, 0.0038985973556009412,
0.9884170338185201, 0.011650571286395461, 0.9808429191005297,
0.019342955478919066, 0.9733840169987446, 0.0269766014846482,
0.9660377568876556, 0.034552359728422744, 0.9588014945307369,
0.04207121767183253, 0.9516728569073111, 0.049533940950141186,
0.9446494635965822, 0.056941358295944156, 0.9377288993026223,
0.06429439168346107, 0.9309091073790681, 0.0715936354946507,
0.924187681612722, 0.07884010933776153, 0.9175626765599192,
0.08603438905970506, 0.9110320403624034, 0.09317721180013905,
0.9045935839762024, 0.10026951462748457, 0.8982456375922825,
0.10731170956330516, 0.8919860966782501, 0.11430473320717738,
0.8858131121185129, 0.12124928503033061, 0.879725075760676,
0.12814583422959913, 0.8737201372634685, 0.1349951636851756,
0.8677966405782273, 0.1417978768189414, 0.8619528050060739,
0.14855476039031146, 0.8561872354420692, 0.1552661937658968,
0.8504983927816893, 0.16193275688146969, 0.8448844572790304,
0.16855539792220497, 0.8393442741575965, 0.1751343179947753,
0.8338762249349438, 0.1816702989864325, 0.8284789320557778,
0.18816387146023317, 0.8231510800065832, 0.1946155228479256,
0.8178913903778707, 0.20102572579389744, 0.8126984007245374,
0.2073952090795501, 0.8075710029460227, 0.21372429840596396,
0.8025078881160415, 0.2200135945981856, 0.7975077379364331,
0.22626374162859975, 0.792569604966373, 0.23247494747693054,
0.7876923641254114, 0.23864766620658884, 0.7828746724940998,
0.24478265647405806, 0.7781155388790811, 0.25088025827324145,
0.7734139557869777, 0.2569408552510595, 0.7687687179914933,
0.26296511155101143, 0.7641790698041854, 0.2689531327189343,
0.7596438763692399, 0.27490553924610595, 0.7551621951078668,
0.2808227248478943, 0.7507331780216866, 0.286704979267256,
0.7463557196361751, 0.29255295645509705, 0.7420289364869653,
0.2983670386142876, 0.7377521537065876, 0.30414734587282055,
0.7335242966002608, 0.30989455774829366, 0.729344777457841,
0.31560871301871884,
];
# The same c, as a double and the rest.
const log_table2: f64[256] = [
0.6894531274426304, 2.60290652810535e-17, 0.6933593811533166,
5.1607448519931415e-17, 0.6972656502972674, 5.290672414887869e-17,
0.7011718886092148, 7.801030634806013e-18, 0.7050781228976939,
-2.471355337688684e-17, 0.7089843887644558, -4.6413389636862956e-17,
0.7128906815542553, 3.3387408065940366e-17, 0.7167968359278303,
-2.6454587338050098e-17, 0.7207031520563163, 2.4284096334522285e-17,
0.7246093683054673, 4.85782435031982e-17, 0.7285155644718035,
-1.3014776598894487e-17, 0.7324219036935506, -1.0402317671225898e-17,
0.73632811474659, 3.078291427467431e-17, 0.7402343715130797,
-1.4304998976623033e-17, 0.7441405900738403, -2.8625955785571303e-17,
0.7480468324364, 5.1609093535635645e-17, 0.7519531335902885,
4.423423949536319e-17, 0.7558594189116706, -4.683016762099508e-17,
0.7597656365502305, 4.466742007514772e-17, 0.7636719350887737,
-4.8134498775190266e-17, 0.767578087670501, -4.3371015350542286e-17,
0.7714844396979536, -2.515644472251707e-17, 0.7753905747966752,
-4.163636184961329e-17, 0.7792968686084766, 3.3837161384165165e-17,
0.783203182701066, 4.379206565056758e-17, 0.7871094109030913,
2.7322930976146396e-17, 0.7910155783031153, -5.463661225364046e-17,
0.7949218121071572, -1.4320502634189868e-17, 0.7988281031542229,
-4.0766731402809024e-17, 0.8027343109146796, -4.0338264352540086e-17,
0.8066405901480322, 1.7241428071650815e-18, 0.8105469363625933,
-4.5534218930924523e-17, 0.8144531571720115, 1.821216920589142e-17,
0.8183593894061396, 4.9864288025894273e-17, 0.8222656559018297,
4.335990416726689e-17, 0.8261719308006343, -5.422001471661127e-17,
0.830078177803083, -5.333603728929035e-17, 0.8339844538076674,
-1.1270648442682386e-17, 0.8378905498984414, -3.165126734800398e-17,
0.8417968420618669, 1.1286283062565865e-17, 0.8457030568173808,
5.643595964448442e-18, 0.8496093725173733, -2.1687834632368187e-17,
0.8535155534462677, -2.2548234217914977e-17, 0.8574219432077146,
4.683260556353139e-17, 0.8613281129443706, 2.5148296884122795e-17,
0.8652342893532053, -8.672187570949467e-18, 0.8691405397938828,
-1.2576268285559751e-17, 0.8730468608194392, -2.9930851265148e-17,
0.8769530685783117, 4.814801507681644e-17, 0.8808593488818101,
-9.10549533611022e-18, 0.8847655593409667, -3.512414651620766e-17,
0.888671840226208, 3.555261815374023e-17, 0.8925780870017613,
1.692380503540994e-17, 0.8964844367374554, -1.0837881791715702e-17,
0.9003905608862683, 5.2900545724138363e-17, 0.9042968358682077,
5.3330721088784517e-17, 0.9082031671057441, 1.8640040753232978e-17,
0.9121093993305497, 4.467972832054075e-17, 0.9160155849026457,
-5.216213419585033e-18, 0.9199219622862499, -2.7324731032846873e-17,
0.9238281880717143, -1.7769263393434193e-17, 0.9277343012727929,
4.943363080817441e-17, 0.9316407021562788, 4.164434042024055e-17,
0.935546825207466, 1.3011820859795741e-17, 0.9394530312562943,
-2.7332907838481398e-17, 0.9433593066844669, 2.342133170803292e-17,
0.9472655994038329, 1.6478717480487438e-17, 0.9511718313032721,
-5.19608290131499e-18, 0.9550781578218178, -3.5565573220579e-17,
0.9589843147339043, 2.0816772146458738e-17, 0.9628906735633685,
-3.471962826146841e-18, 0.9667968893972092, -3.68646834472642e-17,
0.9707031054025779, -3.4674108076868834e-18, 0.9746094325494931,
4.598152624774392e-17, 0.9785156054582722, 4.553145752392568e-17,
0.9824218687812282, -7.811259169418978e-18, 0.9863280690752917,
2.0375615178047467e-17, 0.9902342909546034, -1.344597043422914e-17,
0.9941406780264008, 1.51853723695054e-17, 0.9980468598715558,
-1.301926039598001e-17, 1.0039062067717412, -4.596120641744973e-17,
1.0117187035281372, -8.152405002665349e-17, 1.0195312424919558,
8.239927014757811e-17, 1.0273437641634193, 3.122851005327045e-17,
1.0351562274561221, -1.3010212611128995e-17, 1.0429687539123276,
-5.984116688633458e-17, 1.0507812561238108, 2.860923854822335e-17,
1.0585937308350133, -1.9962944508904598e-17, 1.0664062936992642,
5.291469130309099e-17, 1.0742187309945372, 1.0321575006732523e-16,
1.082031301537134, 9.021194373419119e-17, 1.0898438063644336,
5.202798992357953e-17, 1.0976562356711468, 5.898318482500785e-17,
1.1054688179463226, 8.846377690653252e-17, 1.113281220803328,
-9.529455965212574e-18, 1.1210937073167315, 6.765080709377787e-17,
1.1289062967338532, 1.0929327370933015e-16, 1.1367187631150848,
6.938570551230516e-17, 1.1445312490244826, 1.908841015045148e-17,
1.1523437096203593, 2.7744504138979832e-17, 1.1601563266482477,
-1.5621964097491672e-17, 1.1679688257483505, -6.4191661495975e-17,
1.1757811754697645, -4.336465165059268e-17, 1.183593793665613,
-3.8159292551356396e-17, 1.1914062331617676, -2.94933042768015e-17,
1.1992187450577771, -6.244142916351348e-17, 1.2070312971249755,
7.458644622627413e-17, 1.2148438169965134, 2.7760519266147807e-17,
1.222656225220801, -7.025106921079665e-17, 1.2304687681290862,
3.7292622364618835e-17, 1.2382812116234925, 2.2558949940652082e-17,
1.2460936706149877, 8.499368944400665e-17, 1.2539063289686938,
1.039515474644361e-17, 1.2617188367227732, 3.297262223275499e-17,
1.2695311590462317, 4.509883253594155e-17, 1.277343660657941,
-7.546987371769545e-17, 1.2851561882963496, 9.454295598818184e-17,
1.2929686521915196, -7.28545609119749e-17, 1.3007813359167737,
-8.934357651462802e-17, 1.3085938093753886, 8.15257059458102e-17,
1.3164063202609564, 6.946341460765881e-18, 1.3242188320313901,
-7.892731380721676e-17, 1.3320311786874468, -4.3384657500713545e-17,
1.3398436880573092, 9.627577954598792e-17, 1.3476563390295309,
4.2492400590204517e-17, 1.3554687641043626, -1.0843419551446047e-16,
1.3632813590971713, -8.50172782472025e-17, 1.3710936595522603,
-7.110627206162922e-17,
];
# ln x, from musl's log.c.
def log_double(x: f64): f64 {
var ix := bits_of(x);
val top := (ix >> 48) as u32;
# Near 1, within -2^-4 and 1.03515625 * 2^-4, where the polynomial alone is
# near enough.
if ix - 0x3FEE000000000000 < 0x3FF1090000000000 - 0x3FEE000000000000 {
return 0.0 if ix == 0x3FF0000000000000;
val r := x - 1.0;
val r2 := r * r;
val r3 := r * r2;
var y := r3 * (log_b[1] + r * log_b[2] + r2 * log_b[3]
+ r3 * (log_b[4] + r * log_b[5] + r2 * log_b[6]
+ r3 * (log_b[7] + r * log_b[8] + r2 * log_b[9] + r3 * log_b[10])));
var w := r * 134217728.0;
val rhi := r + w - w;
val rlo := r - rhi;
w = rhi * rhi * log_b[0];
val hi := r + w;
var lo := r - hi + w;
lo += log_b[0] * rlo * (rhi + r);
y += lo;
y += hi;
return y;
}
if top - 0x0010 >= 0x7FF0 - 0x0010 {
# Below 2^-1022, infinite, or NaN.
return divided_by_zero(1) if ix * 2 == 0;
return x if ix == 0x7FF0000000000000;
return invalid(x) if (top & 0x8000) != 0 || (top & 0x7FF0) == 0x7FF0;
# A subnormal, made normal.
ix = bits_of(x * 4503599627370496.0);
ix -= 52u << 52;
}
# x is 2^k z, where z is in [0.6875, 1.375) and exact, and falls in the ith
# subinterval, whose c is near its middle.
val tmp := ix - 0x3FE6000000000000;
val i := (tmp >> (52 - 7)) % 128;
val k := (tmp as i64) >> 52;
val iz := ix - (tmp & (0xFFFu << 52));
val invc := log_table[2 * i];
val logc := log_table[2 * i + 1];
val z := real_of_bits(iz);
# ln x is ln(1 + (z/c - 1)) + ln c + k ln 2, where r is about z/c - 1.
val r := (z - log_table2[2 * i] - log_table2[2 * i + 1]) * invc;
val kd := k as f64;
# hi + lo is r + ln c + k ln 2.
val w := kd * log_ln2_high + logc;
val hi := w + r;
val lo := w - hi + r + kd * log_ln2_low;
# ln x is lo + (ln(1 + r) - r) + hi.
val r2 := r * r;
return lo + r2 * log_a[0] + r * r2 * (log_a[1] + r * log_a[2] + r2 * (log_a[3] + r * log_a[4])) + hi;
}
+104
View File
@@ -0,0 +1,104 @@
#! @file log10.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the base 10 logarithm.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `log10` is from FreeBSD's e_log10.c, which says:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunSoft, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! It is within 1 ulp of the true value for `f64`. An `f32` is worked in `f64`
#! and rounded once more.
module std::math;
#! The base 10 logarithm of a real, the power 10 is raised to to give it.
#! @tparam T The type of real.
#! @param x The real.
#! @returns log10 x: 0 for 1, negative infinity for zero, infinity for
#! infinity, and NaN below zero.
pub def log10<T>(x: T): T where T: real {
return log10_double(x as f64) as T;
}
# The data of `log10`, from musl's log10.c.
# 1 / ln 10, as a high part of 33 bits and a low part.
const log10_inverse_ln10_high: f64 = 0.4342944818781689;
const log10_inverse_ln10_low: f64 = 2.5082946711645275e-11;
# log10 2, as a high part and a low part.
const log10_log10_2_high: f64 = 0.30102999566361177;
const log10_log10_2_low: f64 = 3.694239077158931e-13;
# The polynomial of (ln(1 + f) - f + f^2 / 2) / s, in s^2, where s is
# f / (2 + f): its coefficients from s^2's.
const log10_lg1: f64 = 0.6666666666666735;
const log10_lg2: f64 = 0.3999999999940942;
const log10_lg3: f64 = 0.2857142874366239;
const log10_lg4: f64 = 0.22222198432149784;
const log10_lg5: f64 = 0.1818357216161805;
const log10_lg6: f64 = 0.15313837699209373;
const log10_lg7: f64 = 0.14798198605116586;
# log10 x, from musl's log10.c.
def log10_double(x: f64): f64 {
var v := x;
var hx := high_word(v);
var k: i32 = 0;
if hx < 0x00100000 || (hx >> 31) != 0 {
# Zero, below zero, or subnormal.
return -1.0 / (v * v) if (bits_of(v) << 1) == 0;
return (v - v) / 0.0 if (hx >> 31) != 0;
# A subnormal, scaled up by 2^54.
k -= 54;
v *= 18014398509481984.0;
hx = high_word(v);
} else if hx >= 0x7FF00000 {
return v;
} else if hx == 0x3FF00000 && (bits_of(v) << 32) == 0 {
return 0.0;
}
# x is 2^k (1 + f), where 1 + f is in [sqrt(2) / 2, sqrt(2)).
hx += 0x3FF00000 - 0x3FE6A09E;
k += ((hx >> 20) as i32) - 0x3FF;
hx = (hx & 0x000FFFFF) + 0x3FE6A09E;
v = with_high_word(v, hx);
val f := v - 1.0;
val hfsq := 0.5 * f * f;
val s := f / (2.0 + f);
val z := s * s;
var w := z * z;
val t1 := w * (log10_lg2 + w * (log10_lg4 + w * log10_lg6));
val t2 := z * (log10_lg1 + w * (log10_lg3 + w * (log10_lg5 + w * log10_lg7)));
val r := t2 + t1;
# hi + lo is f - hfsq + s * (hfsq + r), about ln(1 + f), hi of 32 bits.
val hi := real_of_bits(bits_of(f - hfsq) & 0xFFFFFFFF00000000);
val lo := f - hi - hfsq + s * (hfsq + r);
# high + low is log10(1 + f) + k log10 2.
var high := hi * log10_inverse_ln10_high;
val dk := k as f64;
val y := dk * log10_log10_2_high;
var low := dk * log10_log10_2_low + (lo + hi) * log10_inverse_ln10_low + lo * log10_inverse_ln10_high;
# y added in extra precision.
w = y + high;
low += (y - w) + high;
high = w;
return low + high;
}
+213
View File
@@ -0,0 +1,213 @@
#! @file log2.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the base 2 logarithm.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `log2` is from Arm's optimized-routines, which
#! says:
#!
#! Copyright (c) 2018, Arm Limited.
#! SPDX-License-Identifier: MIT
#!
#! It is within 0.55 ulp of the true value for `f64`. An `f32` is worked in
#! `f64` and rounded once more.
module std::math;
#! The base 2 logarithm of a real, the power 2 is raised to to give it.
#! @tparam T The type of real.
#! @param x The real.
#! @returns log2 x: exact at powers of 2, negative infinity for zero, infinity
#! for infinity, and NaN below zero.
pub def log2<T>(x: T): T where T: real {
return log2_double(x as f64) as T;
}
# The data of `log2`, from musl's log2_data.c.
# 1 / ln 2, as a high part of 33 bits and a low part.
const log2_inverse_ln2_high: f64 = 1.4426950407214463;
const log2_inverse_ln2_low: f64 = 1.6751713164886512e-10;
# The polynomial of log2(1 + r) for r within 2^-7 of 0, from its second
# coefficient, the first being 1 / ln 2.
const log2_a: f64[6] = [
-0.7213475204444882, 0.4808983469629985, -0.36067375954075914,
0.2885390073180969, -0.2404693555628422, 0.2061202382173603,
];
# The polynomial of log2(1 + r) for r near 0, within -0.0424 and 0.0443, from
# its second coefficient.
const log2_b: f64[10] = [
-0.7213475204444817, 0.48089834696298744, -0.360673760222145,
0.2885390081805197, -0.24044917405728863, 0.2060992861022954,
-0.18033596705327856, 0.1603032746063156, -0.14483316576701266,
0.13046826811283835,
];
# For each of N subintervals of [0.6875, 1.375), 1/c and log2 c, for a c near
# its middle.
const log2_table: f64[128] = [
1.4463276106642393, -0.5323943771486483, 1.4301675812282968,
-0.516184206053822, 1.4143648676229383, -0.5001543441974263,
1.3989068970611538, -0.4842999484799293, 1.3837838957784339,
-0.46861865624623533, 1.368983882697786, -0.4531054615783887,
1.3544972916324536, -0.43775750882059583, 1.3403139676437443,
-0.4225709906127122, 1.3264249304188642, -0.40754302793970965,
1.3128203652112156, -0.3926695240384106, 1.299492412370217,
-0.3779482100565019, 1.28643198385998, -0.36337518101890964,
1.2736319291846832, -0.3489484089425332, 1.2610838968062879,
-0.33466425780738973, 1.248780314313572, -0.3205197000629596,
1.2367150450059063, -0.3065131231801388, 1.2248804968401878,
-0.2926410022678283, 1.2132702353497795, -0.2789009220805383,
1.2018780785715362, -0.2652905529862437, 1.190697765061355,
-0.2518072602367738, 1.1797235410550593, -0.23844881494437686,
1.1689498986205256, -0.22521309705462045, 1.158371137408455,
-0.21209756102439314, 1.1479820146386086, -0.1991000395789797,
1.1377775576851088, -0.18621852970682085, 1.127753150630225,
-0.17345131655361, 1.1179037012282074, -0.16079591649577196,
1.1082251967632821, -0.14825107384353942, 1.098712461056607,
-0.13581387465410444, 1.0893619091634283, -0.12348332762257996,
1.0801689912316736, -0.11125703807351783, 1.071129489697672,
-0.09913289918449664, 1.0622406576750423, -0.08711065531497297,
1.0534977607927976, -0.07518724771330199, 1.044897877982342,
-0.06336194888240243, 1.0364370289499079, -0.0516324649456692,
1.0281122132034575, -0.039997735929773626, 1.0199202450036955,
-0.028456341769015125, 1.0118577522306755, -0.017006489068080555,
1.003921649236766, -0.005646678981520381, 0.9922480467550775,
0.011227277611396858, 0.9770993366178549, 0.033422853921138085,
0.9624059787315814, 0.05528248992573026, 0.9481480598286369,
0.07681573143713649, 0.9343065931261065, 0.09803204623631245,
0.9208633936884979, 0.11894094059630334, 0.9078013641840602,
0.13955143862290242, 0.8951048181512927, 0.15987146080919956,
0.882758574260473, 0.17990916589428707, 0.8707481902241709,
0.19967252559081317, 0.8590602881746972, 0.2191687127685782,
0.8476822044336688, 0.23840459427242422, 0.8366013284053287,
0.25738780610663525, 0.8258064913621258, 0.27612433583180973,
0.8152865101579193, 0.2946209507022104, 0.8050314363208223,
0.31288297359969874, 0.7950310492640542, 0.33091689015759584,
0.7852760432487271, 0.3487282100279572, 0.7757575660314712,
0.36632223233368677, 0.7664670566588946, 0.383704309808536,
0.7573965608078645, 0.4008792246509074, 0.7485380168514022,
0.41785250494945103, 0.7398844213755009, 0.4346281724315304,
0.7314286113178112, 0.45121103315341315,
];
# The same c, as a double and the rest.
const log2_table2: f64[128] = [
0.6914062848739648, 4.339971893418182e-17, 0.6992187580850853,
7.805593338712074e-18, 0.7070311366547563, 3.20843320369626e-17,
0.7148438556567389, 4.336491946473985e-17, 0.7226561915128084,
4.681890319761607e-17, 0.730468789763508, -1.647126642147294e-17,
0.7382812842650944, 2.0846837208642192e-17, 0.7460938437864584,
-7.82131795361932e-18, 0.7539062159244969, -3.470987810015201e-17,
0.761718835645205, 1.2996798345429576e-17, 0.7695312342578777,
-5.2071007285622585e-17, 0.7773438569208053, -4.513636731226183e-17,
0.7851561955110148, -2.0797044446832382e-17, 0.7929686538163826,
-1.9947626198727574e-17, 0.8007813612514213, 1.472064871061342e-17,
0.8085937047812207, 5.290804109377209e-17, 0.816406173973453,
-1.129659587857177e-17, 0.8242186867064328, 3.901543738154691e-17,
0.8320311501051142, -3.212482853127187e-17, 0.8398436860662717,
5.220081794706035e-18, 0.8476562221566525, -5.37416378988278e-17,
0.8554686571084844, 4.291992377471359e-18, 0.8632811779454657,
1.7319616935225806e-17, 0.8710937865301015, 1.8251073579011692e-17,
0.8789064200163806, 1.2113671810693101e-17, 0.8867188705623812,
-2.431195196496269e-17, 0.894531433164887, -2.258952781769403e-17,
0.9023436779100781, 4.3322028821617186e-17, 0.9101562378188762,
-5.2414676705491076e-18, 0.9179685755379005, -2.3432856904274634e-17,
0.9257810658494647, 3.9914341909758727e-17, 0.9335939394986237,
-1.8218382846902827e-17, 0.9414062555172099, 4.423669374431538e-17,
0.9492189136192009, -2.6059674623550364e-17, 0.9570313243730211,
-4.947019261946595e-17, 0.9648439529540691, -5.4644837229582306e-17,
0.9726564738338594, -5.4656321533328614e-17, 0.9804688208697894,
-1.782581090537996e-18, 0.98828120632121, -5.2277711573086786e-18,
0.9960936700192217, 4.1586638841164565e-17, 1.007812515499802,
9.540912389137736e-17, 1.0234373952820537, 3.985821704561347e-17,
1.0390625391978199, -5.179495640960355e-18, 1.0546875982436061,
-6.074512782488841e-17, 1.07031247275489, -4.853656019321416e-17,
1.0859374005459401, -1.0233609026899023e-16, 1.101562565835984,
9.714504510281668e-17, 1.1171875960464082, -5.728631491659617e-17,
1.1328125595809087, -4.3353271744463366e-17, 1.1484376438870962,
5.029455257812864e-17, 1.1640626551656426, -1.3886091944776072e-17,
1.179687381390876, 9.535864385063222e-17, 1.19531246968748,
2.5970710873556995e-17, 1.2109374417129501, -1.0412863482435496e-16,
1.2265626715770166, 1.903080930681457e-17, 1.2421875157698543,
9.884933154288451e-17, 1.2578125104996614, 2.605028401046449e-17,
1.273437549250769, 3.128070230699857e-17, 1.2890625161616944,
-4.506460293510891e-17, 1.3046875156762752, -2.0874781900380847e-17,
1.3203123063212308, 8.50535702424751e-17, 1.3359374907988373,
-3.99657459893118e-17, 1.351562448282023, 4.1576596545784e-17,
1.3671874254389709, -6.072295450780066e-17,
];
# log2 x, from musl's log2.c.
def log2_double(x: f64): f64 {
var ix := bits_of(x);
val top := (ix >> 48) as u32;
# Near 1, within 1 - 0x1.5b51p-5 and 1 + 0x1.6ab2p-5, where the polynomial
# alone is near enough.
if ix - 0x3FEEA4AF00000000 < 0x3FF0B55900000000 - 0x3FEEA4AF00000000 {
return 0.0 if ix == 0x3FF0000000000000;
val r := x - 1.0;
# r / ln 2 as hi + lo, r split so the high part's product is exact.
val rhi := real_of_bits(bits_of(r) & 0xFFFFFFFF00000000);
val rlo := r - rhi;
val hi := rhi * log2_inverse_ln2_high;
var lo := rlo * log2_inverse_ln2_high + r * log2_inverse_ln2_low;
val r2 := r * r;
val r4 := r2 * r2;
val p := r2 * (log2_b[0] + r * log2_b[1]);
var y := hi + p;
lo += hi - y + p;
lo += r4 * (log2_b[2] + r * log2_b[3] + r2 * (log2_b[4] + r * log2_b[5])
+ r4 * (log2_b[6] + r * log2_b[7] + r2 * (log2_b[8] + r * log2_b[9])));
y += lo;
return y;
}
if top - 0x0010 >= 0x7FF0 - 0x0010 {
# Below 2^-1022, infinite, or NaN.
return divided_by_zero(1) if ix * 2 == 0;
return x if ix == 0x7FF0000000000000;
return invalid(x) if (top & 0x8000) != 0 || (top & 0x7FF0) == 0x7FF0;
# A subnormal, made normal.
ix = bits_of(x * 4503599627370496.0);
ix -= 52u << 52;
}
# x is 2^k z, where z is in [0.6875, 1.375) and exact, and falls in the ith
# subinterval, whose c is near its middle.
val tmp := ix - 0x3FE6000000000000;
val i := (tmp >> (52 - 6)) % 64;
val k := (tmp as i64) >> 52;
val iz := ix - (tmp & (0xFFFu << 52));
val invc := log2_table[2 * i];
val logc := log2_table[2 * i + 1];
val z := real_of_bits(iz);
val kd := k as f64;
# log2 x is log2(1 + (z/c - 1)) + log2 c + k, where r is about z/c - 1, and
# r / ln 2 is t1 + t2.
val r := (z - log2_table2[2 * i] - log2_table2[2 * i + 1]) * invc;
val rhi := real_of_bits(bits_of(r) & 0xFFFFFFFF00000000);
val rlo := r - rhi;
val t1 := rhi * log2_inverse_ln2_high;
val t2 := rlo * log2_inverse_ln2_high + r * log2_inverse_ln2_low;
# hi + lo is r / ln 2 + log2 c + k.
val t3 := kd + logc;
val hi := t3 + t1;
val lo := t3 - hi + t1 + t2;
# log2(1 + r) is r / ln 2 + r^2 p.
val r2 := r * r;
val r4 := r2 * r2;
val p := log2_a[0] + r * log2_a[1] + r2 * (log2_a[2] + r * log2_a[3]) + r4 * (log2_a[4] + r * log2_a[5]);
return lo + r2 * p + hi;
}
+384
View File
@@ -0,0 +1,384 @@
#! @file pow.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains a real raised to a real power.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `pow` is from Arm's optimized-routines, which
#! says:
#!
#! Copyright (c) 2018, Arm Limited.
#! SPDX-License-Identifier: MIT
#!
#! It is within 0.55 ulp of the true value for `f64`. An `f32` is worked in
#! `f64` and rounded once more.
module std::math;
#! A real raised to a power, as C's `pow`.
#! @tparam T The type of real.
#! @param x The base.
#! @param y The power.
#! @returns x^y: 1 where y is zero or x is 1, even with NaN; NaN where x is
#! finite and below zero and y is not an integer; infinity, of x's
#! sign where y is an odd integer, for a zero x and y below zero; and
#! infinity or 0 past what the type holds.
pub def pow<T>(x: T, y: T): T where T: real {
return pow_double(x as f64, y as f64) as T;
}
# The data of the logarithm `pow` works with, from musl's pow_data.c. Its ln 2
# halves are those of `log`.
# The polynomial of ln(1 + r) for r within 0.0056 of 0, from its second
# coefficient, each scaled to undo the factors of -1/2 it is evaluated with.
const pow_a: f64[7] = [
-0.5, -0.6666666666666679, 0.5000000000000007,
0.7999999995323976, -0.6666666663487739, -1.142909628459501,
1.0000415263675542,
];
# For each of N subintervals of [0.7057, 1.4114), 1/c, and ln c as a multiple
# of 2^-43 and the rest, for a c near its middle whose 1/c has few bits, so
# z/c - 1 is exact.
const pow_table: f64[384] = [
1.4140625, -0.3464667673462145, 5.929407345889625e-15,
1.40625, -0.34092658697056777, -2.544157440035963e-14,
1.3984375, -0.3353555419211034, -3.443525940775045e-14,
1.390625, -0.3297532863724655, -2.500123826022799e-15,
1.3828125, -0.32411946865420305, -8.929337133850617e-15,
1.375, -0.31845373111855224, 1.7625431312172662e-14,
1.3671875, -0.31275571000389846, 1.5688303180062087e-15,
1.359375, -0.3070250352949415, 2.9655274673691784e-14,
1.3515625, -0.3012613305781997, 3.7923164802093147e-14,
1.34375, -0.2954642128938758, 3.993416384387844e-14,
1.3359375, -0.28963329258306203, 1.9352855826489123e-14,
1.3359375, -0.28963329258306203, 1.9352855826489123e-14,
1.328125, -0.28376817313062475, -1.9852665484979036e-14,
1.3203125, -0.27786845100342816, -2.814323765595281e-14,
1.3125, -0.2719337154836694, 2.7643769993528702e-14,
1.3046875, -0.2659635484970977, -4.025092402293806e-14,
1.296875, -0.25995752443691345, -1.2621729398885316e-14,
1.2890625, -0.25391520998095984, -3.600176732637335e-15,
1.2890625, -0.25391520998095984, -3.600176732637335e-15,
1.28125, -0.2478361639045943, 1.3029797173308663e-14,
1.2734375, -0.2417199368871934, 4.8230289429940886e-14,
1.265625, -0.23556607131274632, -2.0592242769647135e-14,
1.2578125, -0.22937410106487732, 3.149265065191484e-14,
1.25, -0.22314355131425145, 4.169796584527195e-14,
1.25, -0.22314355131425145, 4.169796584527195e-14,
1.2421875, -0.21687393830063684, 2.2477465222466186e-14,
1.234375, -0.21056476910735, 3.6507188831790577e-16,
1.2265625, -0.2042155414286526, -3.827767260205414e-14,
1.2265625, -0.2042155414286526, -3.827767260205414e-14,
1.21875, -0.19782574332987224, -4.7641388950792196e-14,
1.2109375, -0.19139485299967873, 4.9278276214647115e-14,
1.203125, -0.18492233849406148, 4.9485167661250996e-14,
1.203125, -0.18492233849406148, 4.9485167661250996e-14,
1.1953125, -0.1784076574728033, -1.5003333854266542e-14,
1.1875, -0.17185025692663203, -2.7194441649495324e-14,
1.1875, -0.17185025692663203, -2.7194441649495324e-14,
1.1796875, -0.1652495728952772, -2.99659267292569e-14,
1.171875, -0.15860503017665906, 2.0472357800461955e-14,
1.171875, -0.15860503017665906, 2.0472357800461955e-14,
1.1640625, -0.15191604202584585, 3.879296723063646e-15,
1.15625, -0.1451820098444614, -3.6506824353335045e-14,
1.1484375, -0.13840232285906495, -5.4183331379008994e-14,
1.1484375, -0.13840232285906495, -5.4183331379008994e-14,
1.140625, -0.131576357788731, 1.1729485484531301e-14,
1.140625, -0.131576357788731, 1.1729485484531301e-14,
1.1328125, -0.12470347850091912, -3.811763084710266e-14,
1.125, -0.11778303565643, 4.654729747598445e-14,
1.125, -0.11778303565643, 4.654729747598445e-14,
1.1171875, -0.11081436634026431, -2.5799991283069902e-14,
1.109375, -0.10379679368168127, 3.7700471749674615e-14,
1.109375, -0.10379679368168127, 3.7700471749674615e-14,
1.1015625, -0.09672962645856842, 1.7306161136093256e-14,
1.1015625, -0.09672962645856842, 1.7306161136093256e-14,
1.09375, -0.089612158689647, -4.012913552726574e-14,
1.0859375, -0.08244366921110213, 2.7541708360737882e-14,
1.0859375, -0.08244366921110213, 2.7541708360737882e-14,
1.078125, -0.07522342123763792, 5.0396178134370583e-14,
1.078125, -0.07522342123763792, 5.0396178134370583e-14,
1.0703125, -0.06795066190852594, 1.8195060030168815e-14,
1.0625, -0.06062462181648698, 5.213620639136504e-14,
1.0625, -0.06062462181648698, 5.213620639136504e-14,
1.0546875, -0.053244514518837605, 2.532168943117445e-14,
1.0546875, -0.053244514518837605, 2.532168943117445e-14,
1.046875, -0.045809536031242715, -5.148849572685811e-14,
1.046875, -0.045809536031242715, -5.148849572685811e-14,
1.0390625, -0.038318864302141264, 4.6652946995830086e-15,
1.0390625, -0.038318864302141264, 4.6652946995830086e-15,
1.03125, -0.03077165866670839, -4.529814257790929e-14,
1.03125, -0.03077165866670839, -4.529814257790929e-14,
1.0234375, -0.023167059281490765, -4.361324067851568e-14,
1.015625, -0.015504186535963527, -1.7274567499706107e-15,
1.015625, -0.015504186535963527, -1.7274567499706107e-15,
1.0078125, -0.0077821404420319595, -2.298941004620351e-14,
1.0078125, -0.0077821404420319595, -2.298941004620351e-14,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
0.9921875, 0.007843177461040796, -1.4902732911301337e-14,
0.984375, 0.01574835696817445, -3.527980389655325e-14,
0.9765625, 0.023716526617363343, -4.730054772033249e-14,
0.96875, 0.03174869831457272, 7.580310369375161e-15,
0.9609375, 0.039845908547249564, -4.9893776716773285e-14,
0.953125, 0.048009219186383234, -2.262629393030674e-14,
0.9453125, 0.056239718322899535, -2.345674491018699e-14,
0.94140625, 0.06038051098892083, -1.3352588834854848e-14,
0.93359375, 0.06871389254808946, -3.765296820388875e-14,
0.92578125, 0.07711730334438016, 5.1128335719851986e-14,
0.91796875, 0.08559193033545398, -5.046674438470119e-14,
0.9140625, 0.08985632912185793, 3.1218748807418837e-15,
0.90625, 0.09844007281321865, 3.3871241029241416e-14,
0.8984375, 0.10709813555638448, -1.7376727386423858e-14,
0.89453125, 0.11145544092528326, 3.957125899799804e-14,
0.88671875, 0.12022742699821265, -5.2849453521890294e-14,
0.8828125, 0.12464244520731427, -3.767012502308738e-14,
0.875, 0.13353139262449076, 3.1859736349078334e-14,
0.87109375, 0.13800567301939282, 5.0900642926060466e-14,
0.86328125, 0.14701474296180095, 8.710783796122478e-15,
0.859375, 0.15154989812720032, 6.157896229122976e-16,
0.8515625, 0.16068238169043525, 3.821577743916796e-14,
0.84765625, 0.16528009093906348, 3.9440046718453496e-14,
0.83984375, 0.17453941635187675, 2.2924522154618074e-14,
0.8359375, 0.17920142945774842, -3.742530094732263e-14,
0.83203125, 0.18388527877016259, -2.5223102140407338e-14,
0.82421875, 0.1933193110035063, -1.0320443688698849e-14,
0.8203125, 0.19806991376208316, 1.0634128304268335e-14,
0.8125, 0.20763936477828793, -4.3425422595242564e-14,
0.80859375, 0.21245865121420593, -1.2527395755711364e-14,
0.8046875, 0.21730127569003344, -5.204008743405884e-14,
0.80078125, 0.22216746534115828, -3.979844515951702e-15,
0.79296875, 0.2319714654378231, -4.7955860343296286e-14,
0.7890625, 0.2369097470783572, 5.015686013791602e-16,
0.78515625, 0.24187253642048745, -7.252318953240293e-16,
0.78125, 0.2468600779315011, 2.4688324156011588e-14,
0.7734375, 0.2569104137850218, 5.465121253624792e-15,
0.76953125, 0.26197371574153294, 4.102651071698446e-14,
0.765625, 0.2670627852490952, -4.996736502345936e-14,
0.76171875, 0.27217788591576664, 4.903580708156347e-14,
0.7578125, 0.27731928541618345, 5.089628039500759e-14,
0.75390625, 0.28248725557466514, 1.1782016386565151e-14,
0.74609375, 0.29290401643288533, 4.727452940514406e-14,
0.7421875, 0.29815337231912054, -4.4204083338755686e-14,
0.73828125, 0.3034304294199046, 1.548345993498083e-14,
0.734375, 0.30873548164959175, 2.1522127491642888e-14,
0.73046875, 0.3140688276249648, 1.1054030169005386e-14,
0.7265625, 0.31943077076641657, -5.534326352070679e-14,
0.72265625, 0.3248216194012912, -5.351646604259541e-14,
0.71875, 0.33024168687052224, 5.4612144489920215e-14,
0.71484375, 0.3356912916381134, 2.8136969901227338e-14,
0.7109375, 0.3411707574027787, -1.156568624616423e-14,
];
# The sign bias, which `pow_exp` adds to the exponent of its scale to negate
# the result.
const pow_sign_bias: u32 = 0x800 << 7;
# ln x, as a double and about 15 bits more. ix is the bits of x, whose exponent
# is below zero where x is subnormal.
struct pow_sum {
var hi: f64;
var lo: f64;
}
def pow_log(ix: u64): pow_sum {
# x is 2^k z, where z is in [0.7057, 1.4114) and exact, and falls in the ith
# subinterval, whose c is near its middle.
val tmp := ix - 0x3FE6955500000000;
val i := (tmp >> (52 - 7)) % 128;
val k := (tmp as i64) >> 52;
val iz := ix - (tmp & (0xFFFu << 52));
val z := real_of_bits(iz);
val kd := k as f64;
# ln x is k ln 2 + ln c + ln(1 + (z/c - 1)).
val invc := pow_table[3 * i];
val logc := pow_table[3 * i + 1];
val logctail := pow_table[3 * i + 2];
# r is z/c - 1, as rhi + rlo, of z split so rhi, rlo, and rhi^2 are exact.
val zhi := real_of_bits((iz + (1u << 31)) & 0xFFFFFFFF00000000);
val zlo := z - zhi;
val rhi := zhi * invc - 1.0;
val rlo := zlo * invc;
val r := rhi + rlo;
# k ln 2 + ln c + r.
val t1 := kd * log_ln2_high + logc;
val t2 := t1 + r;
val lo1 := kd * log_ln2_low + logctail;
val lo2 := t1 - t2 + r;
# k ln 2 + ln c + r - r^2 / 2, the last as arhi2 + lo3.
val ar := pow_a[0] * r;
val ar2 := r * ar;
val ar3 := r * ar2;
val arhi := pow_a[0] * rhi;
val arhi2 := rhi * arhi;
val hi := t2 + arhi2;
val lo3 := rlo * (ar + arhi);
val lo4 := t2 - hi + arhi2;
# ln(1 + r) - r + r^2 / 2.
val p := ar3 * (pow_a[1] + r * pow_a[2] + ar2 * (pow_a[3] + r * pow_a[4] + ar2 * (pow_a[5] + r * pow_a[6])));
val lo := lo1 + lo2 + lo3 + lo4 + p;
val y := hi + lo;
return pow_sum { hi = y, lo = hi - y + lo };
}
# As `exp_special`, where the result may be negative.
def pow_special(tmp: f64, scale_bits: u64, ki: u64): f64 {
var sbits := scale_bits;
if (ki & 0x80000000) == 0 {
# k above zero, where the scale's exponent may have overflowed by 460.
sbits -= 1009u << 52;
val scale := real_of_bits(sbits);
return 5.486124068793689e+303 * (scale + scale * tmp);
}
# k below zero, where the subnormals need care.
sbits += 1022u << 52;
val scale := real_of_bits(sbits);
var y := scale + scale * tmp;
if abs(y) < 1.0 {
# Rounded to the precision it ends with before scaling into the subnormals,
# so it rounds once.
val one := y < 0.0 ? -1.0 : 1.0;
var lo := scale - y + scale * tmp;
val hi := one + y;
lo = one - hi + y + lo;
y = (hi + lo) - one;
if y == 0.0 {
# A zero of the scale's sign.
y = real_of_bits(sbits & 0x8000000000000000);
}
}
return 2.2250738585072014e-308 * y;
}
# e^(x + xtail), negated where sign_bias is `pow_sign_bias`, as `exp_double`
# works it, xtail being within 2^-8 / N of 0 and of x.
def pow_exp(x: f64, xtail: f64, sign_bias: u32): f64 {
var abstop := top12(x) & 0x7FF;
if abstop - 0x3C9 >= 0x408 - 0x3C9 {
if abstop - 0x3C9 >= 0x80000000 {
# Below 2^-54, where e^x is 1 + x.
val one := 1.0 + x;
return sign_bias != 0 ? -one : one;
}
if abstop >= 0x409 {
return (bits_of(x) >> 63) != 0 ? underflowed(sign_bias) : overflowed(sign_bias);
}
# A large x, which `pow_special` works out.
abstop = 0;
}
# e^x is 2^(k / N) * e^r, where x is k ln 2 / N + r, k is an integer, and r
# is within ln 2 / 2N of 0.
val z := exp_inverse_ln2_n * x;
var kd := z + exp_shift;
val ki := bits_of(kd);
kd -= exp_shift;
var r := x + kd * exp_negative_ln2_high_n + kd * exp_negative_ln2_low_n;
r += xtail;
# 2^(k / N) is about scale * (1 + tail), the sign bias negating scale.
val index := 2 * (ki % exp_size);
val top := (ki + (sign_bias as u64)) << (52 - 7);
val tail := real_of_bits(exp_table[index]);
val sbits := exp_table[index + 1] + top;
# e^x is about scale + scale * (tail + e^r - 1).
val r2 := r * r;
val tmp := tail + r + r2 * (exp_c2 + r * exp_c3) + r2 * r2 * (exp_c4 + r * exp_c5);
return pow_special(tmp, sbits, ki) if abstop == 0;
val scale := real_of_bits(sbits);
return scale + scale * tmp;
}
# Whether the bits of a finite real other than zero are of an integer: 0 where
# they are not, 1 where it is odd, and 2 where it is even.
def pow_check_integer(iy: u64): i32 {
val e := ((iy >> 52) & 0x7FF) as i32;
return 0 if e < 0x3FF;
return 2 if e > 0x3FF + 52;
return 0 if (iy & ((1u << ((0x3FF + 52 - e) as u64)) - 1)) != 0;
return 1 if (iy & (1u << ((0x3FF + 52 - e) as u64))) != 0;
return 2;
}
# Whether bits are of zero, infinity, or NaN.
def pow_zero_inf_nan(i: u64): bool {
return 2 * i - 1 >= 2 * 0x7FF0000000000000u - 1;
}
# x^y, from musl's pow.c.
def pow_double(x: f64, y: f64): f64 {
var sign_bias: u32 = 0;
var ix := bits_of(x);
val iy := bits_of(y);
var topx := top12(x);
val topy := top12(y);
if topx - 0x001 >= 0x7FF - 0x001 || (topy & 0x7FF) - 0x3BE >= 0x43E - 0x3BE {
# x below 2^-1022 (or below zero), infinite, or NaN; or |y| below 2^-65,
# from 2^63 up, or NaN. Past 2^63, x^y is infinity or 0, and below 2^-65,
# it is 1 within an ulp.
if pow_zero_inf_nan(iy) {
return 1.0 if 2 * iy == 0;
return 1.0 if ix == 0x3FF0000000000000;
return x + y if 2 * ix > 2 * 0x7FF0000000000000u || 2 * iy > 2 * 0x7FF0000000000000u;
return 1.0 if 2 * ix == 2 * 0x3FF0000000000000u;
# |x| below 1 and y infinity, or |x| above 1 and y negative infinity.
return 0.0 if (2 * ix < 2 * 0x3FF0000000000000u) == ((iy >> 63) == 0);
return y * y;
}
if pow_zero_inf_nan(ix) {
var x2 := x * x;
if (ix >> 63) != 0 && pow_check_integer(iy) == 1 {
x2 = -x2;
}
return (iy >> 63) != 0 ? 1.0 / x2 : x2;
}
# x and y finite, and not zero.
if (ix >> 63) != 0 {
# x below zero.
val yint := pow_check_integer(iy);
return invalid(x) if yint == 0;
if yint == 1 {
sign_bias = pow_sign_bias;
}
ix &= 0x7FFFFFFFFFFFFFFF;
topx &= 0x7FF;
}
if (topy & 0x7FF) - 0x3BE >= 0x43E - 0x3BE {
# y is not odd here, being so large or so small.
return 1.0 if ix == 0x3FF0000000000000;
if (topy & 0x7FF) < 0x3BE {
# |y| below 2^-65, where x^y is about 1 + y ln x.
return ix > 0x3FF0000000000000 ? 1.0 + y : 1.0 - y;
}
return (ix > 0x3FF0000000000000) == (topy < 0x800) ? overflowed(0) : underflowed(0);
}
if topx == 0 {
# A subnormal x, made normal with an exponent below zero.
ix = bits_of(x * 4503599627370496.0);
ix &= 0x7FFFFFFFFFFFFFFF;
ix -= 52u << 52;
}
}
# x^y is e^(y ln x), y ln x worked as ehi + elo, from halves of y and ln x
# whose products are exact.
val ln := pow_log(ix);
val yhi := real_of_bits(iy & 0xFFFFFFFFF8000000);
val ylo := y - yhi;
val lhi := real_of_bits(bits_of(ln.hi) & 0xFFFFFFFFF8000000);
val llo := ln.hi - lhi + ln.lo;
val ehi := yhi * lhi;
val elo := ylo * lhi + y * llo;
return pow_exp(ehi, elo, sign_bias);
}
+417
View File
@@ -0,0 +1,417 @@
#! @file reduce.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the reduction of a double by multiples of π/2, which the
#! trigonometric functions work from: x less n·π/2, as two doubles whose sum
#! holds it to well past a double's precision, and n. Arguments up to 2^20·π/2
#! are reduced with π/2 in three parts of 33 bits; larger ones with as many bits
#! of 2/π as their exponent needs, so the largest double reduces as well as 1e7.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `__rem_pio2` and `__rem_pio2_large` are from
#! FreeBSD's e_rem_pio2.c, optimized by Bruce D. Evans, and k_rem_pio2.c, which
#! say:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunSoft, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
module std::math;
# A double reduced by n multiples of π/2: x - n·π/2 is about hi + lo, where hi
# is the sum rounded and within about π/4 of 0.
struct reduce_result {
var n: i32;
var hi: f64;
var lo: f64;
}
# The constants of the reduction, from musl's __rem_pio2.c.
# 1.5 * 2^52, which adding and taking away rounds a smaller double to an
# integer.
const reduce_to_integer: f64 = 6755399441055744.0;
# π/4.
const reduce_pio4: f64 = 0.7853981633974483;
# 2/π, to 53 bits.
const reduce_inverse_pio2: f64 = 0.6366197723675814;
# π/2 in three parts of 33 bits, each with what is left of π/2 after it and
# those before it.
const reduce_pio2_1: f64 = 1.5707963267341256;
const reduce_pio2_1_tail: f64 = 6.077100506506192e-11;
const reduce_pio2_2: f64 = 6.077100506303966e-11;
const reduce_pio2_2_tail: f64 = 2.0222662487959506e-21;
const reduce_pio2_3: f64 = 2.0222662487111665e-21;
const reduce_pio2_3_tail: f64 = 8.4784276603689e-32;
# x less n·π/2, from musl's __rem_pio2.c. The caller handles |x| up to about
# π/4, which needs no reducing. Infinity and NaN give NaN, with n 0.
def reduce_pio2(x: f64): reduce_result {
val bits := bits_of(x);
val sign := (bits >> 63) != 0;
val ix := ((bits >> 32) as u32) & 0x7FFFFFFF;
# Up to 9π/4, x is less 1, 2, 3, or 4 times π/2, but near π/2, π, 3π/2, and
# 2π, where too many bits cancel, and the medium case reduces it.
var near := false;
if ix <= 0x400F6A7A {
if (ix & 0xFFFFF) == 0x921FB {
near = true;
} else if ix <= 0x4002D97C {
return reduce_pio2_small(x, sign ? -1 : 1);
} else {
return reduce_pio2_small(x, sign ? -2 : 2);
}
} else if ix <= 0x401C463B {
if ix <= 0x4015FDBC {
if ix == 0x4012D97C {
near = true;
} else {
return reduce_pio2_small(x, sign ? -3 : 3);
}
} else {
if ix == 0x401921FB {
near = true;
} else {
return reduce_pio2_small(x, sign ? -4 : 4);
}
}
}
return reduce_pio2_medium(x, ix) if near || ix < 0x413921FB;
# Infinity and NaN.
if ix >= 0x7FF00000 {
val nan := x - x;
return reduce_result { n = 0, hi = nan, lo = nan };
}
# |x| as 2^e0 times three pieces of 24 bits, the first with its top bit set,
# less those that are zero at the end.
val z0 := real_of_bits((bits & 0x000FFFFFFFFFFFFF) | ((0x3FF + 23) << 52));
var tx: f64[3];
var z := z0;
var i: i32 = 0;
while i < 2 {
tx[i] = (z as i32) as f64;
z = (z - tx[i]) * 16777216.0;
i++;
}
tx[2] = z;
while tx[i] == 0.0 {
i--;
}
val large := reduce_pio2_large(tx, (ix >> 20) as i32 - (0x3FF + 23), i + 1);
if sign {
return reduce_result { n = -large.n, hi = -large.hi, lo = -large.lo };
}
return large;
}
# x less k·π/2, for k from -4 to 4 that is not near x / (π/2): a subtraction
# of the first part, which cancels to about 85 bits, then its tail. musl writes
# x + |k|·π/2 for k below 0, which rounds the same.
def reduce_pio2_small(x: f64, k: i32): reduce_result {
val m := k as f64;
val z := x - m * reduce_pio2_1;
val hi := z - m * reduce_pio2_1_tail;
val lo := (z - hi) - m * reduce_pio2_1_tail;
return reduce_result { n = k, hi = hi, lo = lo };
}
# x less n·π/2 for |x| below 2^20·π/2, where n is x / (π/2) rounded: the first
# part of π/2 and its tail, then the second and third where so many bits cancel
# that the tail isn't enough.
def reduce_pio2_medium(x: f64, ix: u32): reduce_result {
var fn := x * reduce_inverse_pio2 + reduce_to_integer - reduce_to_integer;
var n := fn as i32;
var r := x - fn * reduce_pio2_1;
var w := fn * reduce_pio2_1_tail;
# Only a rounding mode other than the nearest makes n off by 1.
if r - w < -reduce_pio4 {
n--;
fn--;
r = x - fn * reduce_pio2_1;
w = fn * reduce_pio2_1_tail;
} else if r - w > reduce_pio4 {
n++;
fn++;
r = x - fn * reduce_pio2_1;
w = fn * reduce_pio2_1_tail;
}
var hi := r - w;
val ex := (ix >> 20) as i32;
var ey := ((bits_of(hi) >> 52) & 0x7FF) as i32;
if ex - ey > 16 {
# Good to 118 bits.
var t := r;
w = fn * reduce_pio2_2;
r = t - w;
w = fn * reduce_pio2_2_tail - ((t - r) - w);
hi = r - w;
ey = ((bits_of(hi) >> 52) & 0x7FF) as i32;
if ex - ey > 49 {
# Good to 151 bits, which is enough for every double.
t = r;
w = fn * reduce_pio2_3;
r = t - w;
w = fn * reduce_pio2_3_tail - ((t - r) - w);
hi = r - w;
}
}
val lo := (r - hi) - w;
return reduce_result { n = n, hi = hi, lo = lo };
}
# The reduction of large doubles, from musl's __rem_pio2_large.c, at the
# precision of a double: x·(2/π) is formed in pieces of 24 bits, from only the
# bits of 2/π that reach its last three integer bits and its fraction, so it
# takes as long for 1e300 as for 1e7.
# The bits of 2/π after the point, 24 to an entry: entry i is the bits from
# 24i + 1 to 24i + 24, so it is worth `reduce_2_over_pi[i]` · 2^(-24(i + 1)).
# These are as many as a double's exponent can need; musl holds more for long
# doubles.
const reduce_2_over_pi: i32[66] = [
0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62,
0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A,
0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129,
0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41,
0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8,
0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF,
0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5,
0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08,
0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3,
0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880,
0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B,
];
# π/2 in pieces of 24 bits, as many as a double needs.
const reduce_pio2_pieces: f64[5] = [
1.570796251296997, 7.549789415861596e-08, 5.390302529957765e-15,
3.282003415807913e-22, 1.270655753080676e-29,
];
# 2^24 and 2^-24.
const reduce_two_24: f64 = 16777216.0;
const reduce_two_minus_24: f64 = 5.9604644775390625e-08;
# One less than how many pieces of the product are formed at first, for
# doubles: musl's jk. Two more than would seem needed, so the test for bits
# lost to cancelling works.
const reduce_pieces: i32 = 4;
# The positive x[0]·2^e0 + x[1]·2^(e0 - 24) + ..., of `count` pieces of 24
# bits each, less n·π/2, where n is returned modulo 8.
def reduce_pio2_large(x: f64[3], e0: i32, count: i32): reduce_result {
var iq: i32[20];
var f: f64[20];
var fq: f64[20];
var q: f64[20];
val jk := reduce_pieces;
val jp := jk;
# jv is the first piece of 2/π needed: those before it make a multiple of 8
# of x·(2/π). q0 is the exponent of q[0].
val jx := count - 1;
var jv := (e0 - 3) / 24;
if jv < 0 {
jv = 0;
}
var q0 := e0 - 24 * (jv + 1);
# f[0] to f[jx + jk] are the pieces of 2/π from jv - jx to jv + jk.
var j := jv - jx;
val m := jx + jk;
var i: i32 = 0;
while i <= m {
f[i] = j < 0 ? 0.0 : reduce_2_over_pi[j] as f64;
i++;
j++;
}
# q[0] to q[jk], the pieces of the product.
var fw: f64 = 0.0;
i = 0;
while i <= jk {
fw = 0.0;
j = 0;
while j <= jx {
fw += x[j] * f[jx + i - j];
j++;
}
q[i] = fw;
i++;
}
var jz := jk;
var z: f64 = 0.0;
var n: i32 = 0;
var ih: i32 = 0;
var k: i32 = 0;
while true {
# q[] into iq[], 24 bits each, from the last.
i = 0;
j = jz;
z = q[jz];
while j > 0 {
fw = ((reduce_two_minus_24 * z) as i32) as f64;
iq[i] = (z - reduce_two_24 * fw) as i32;
z = q[j - 1] + fw;
i++;
j--;
}
# n is the integer part, modulo 8, and z the fraction.
z = scalbn(z, q0);
z -= 8.0 * floor_double(z * 0.125);
n = z as i32;
z -= n as f64;
ih = 0;
if q0 > 0 {
# The last bits of the integer are in iq[jz - 1].
i = iq[jz - 1] >> ((24 - q0) as u64);
n += i;
iq[jz - 1] -= i << ((24 - q0) as u64);
ih = iq[jz - 1] >> ((23 - q0) as u64);
} else if q0 == 0 {
ih = iq[jz - 1] >> 23;
} else if z >= 0.5 {
ih = 2;
}
# At a half or more, the fraction is 1 less it, and n one more, so the
# result is negative.
if ih > 0 {
n += 1;
var carry: i32 = 0;
i = 0;
while i < jz {
j = iq[i];
if carry == 0 {
if j != 0 {
carry = 1;
iq[i] = 0x1000000 - j;
}
} else {
iq[i] = 0xFFFFFF - j;
}
i++;
}
if q0 == 1 {
iq[jz - 1] &= 0x7FFFFF;
} else if q0 == 2 {
iq[jz - 1] &= 0x3FFFFF;
}
if ih == 2 {
z = 1.0 - z;
if carry != 0 {
z -= scalbn(1.0, q0);
}
}
}
# Where the fraction's leading bits all cancelled, more pieces of 2/π are
# taken, and it is worked again.
if z == 0.0 {
j = 0;
i = jz - 1;
while i >= jk {
j |= iq[i];
i--;
}
if j == 0 {
k = 1;
while iq[jk - k] == 0 {
k++;
}
i = jz + 1;
while i <= jz + k {
f[jx + i] = reduce_2_over_pi[jv + i] as f64;
fw = 0.0;
j = 0;
while j <= jx {
fw += x[j] * f[jx + i - j];
j++;
}
q[i] = fw;
i++;
}
jz += k;
continue;
}
}
break;
}
# The pieces of the fraction, less those that are zero at the end.
if z == 0.0 {
jz -= 1;
q0 -= 24;
while iq[jz] == 0 {
jz--;
q0 -= 24;
}
} else {
z = scalbn(z, -q0);
if z >= reduce_two_24 {
fw = ((reduce_two_minus_24 * z) as i32) as f64;
iq[jz] = (z - reduce_two_24 * fw) as i32;
jz += 1;
q0 += 24;
iq[jz] = fw as i32;
} else {
iq[jz] = z as i32;
}
}
# The pieces as doubles.
fw = scalbn(1.0, q0);
i = jz;
while i >= 0 {
q[i] = fw * (iq[i] as f64);
fw *= reduce_two_minus_24;
i--;
}
# The fraction times π/2.
i = jz;
while i >= 0 {
fw = 0.0;
k = 0;
while k <= jp && k <= jz - i {
fw += reduce_pio2_pieces[k] * q[i + k];
k++;
}
fq[jz - i] = fw;
i--;
}
# The sum as two doubles.
fw = 0.0;
i = jz;
while i >= 0 {
fw += fq[i];
i--;
}
val hi := ih == 0 ? fw : -fw;
fw = fq[0] - fw;
i = 1;
while i <= jz {
fw += fq[i];
i++;
}
val lo := ih == 0 ? fw : -fw;
return reduce_result { n = n & 7, hi = hi, lo = lo };
}
+163
View File
@@ -0,0 +1,163 @@
#! @file roots.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the roots besides the square root: the cube root, and the square
#! root of a sum of squares, a point's distance from the origin, worked without
#! overflowing or underflowing.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `cbrt` is from FreeBSD's s_cbrt.c, of Sun's
#! fdlibm, by way of musl, which says:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunPro, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! Optimized by Bruce D. Evans.
#!
#! For `f64`, `cbrt` is within 0.67 ulp of the true value, and `hypot` within
#! 1 ulp. An `f32` is worked in `f64` and rounded once more.
import core::intrinsics;
module std::math;
#! The cube root of a real, the real whose cube it is.
#! @tparam T The type of real.
#! @param x The real.
#! @returns Its cube root, of its sign: `±0` for `±0`, `±infinity` for
#! `±infinity`, and NaN for NaN.
pub def cbrt<T>(x: T): T where T: real {
return cbrt_double(x as f64) as T;
}
#! The square root of the sum of two reals' squares, which is the length of the
#! hypotenuse of a right triangle whose legs they are, or a point's distance
#! from the origin. It does not overflow or underflow where the squares would.
#! @tparam T The type of real.
#! @param x One real.
#! @param y The other.
#! @returns The root: infinity where either is infinite, even with NaN, NaN
#! where either is NaN otherwise, and infinity past what `T` holds.
pub def hypot<T>(x: T, y: T): T where T: real {
return hypot_double(x as f64, y as f64) as T;
}
# The data of `cbrt`, from musl's cbrt.c.
# Added to a third of the high word, these give a cube root to about 5 bits:
# (1023 - 1023/3 - 0.03306235651) * 2^20, and that less 54/3 * 2^20, for a
# subnormal scaled by 2^54.
const cbrt_b1: u32 = 715094163;
const cbrt_b2: u32 = 696219795;
# A polynomial within 2^-23.5 of 1 / cbrt(r), for r within 1/10 of 1.
const cbrt_p0: f64 = 1.87595182427177;
const cbrt_p1: f64 = -1.8849797954337717;
const cbrt_p2: f64 = 1.6214297201053545;
const cbrt_p3: f64 = -0.758397934778766;
const cbrt_p4: f64 = 0.14599619288661245;
# The cube root, from musl's cbrt.c.
def cbrt_double(x: f64): f64 {
var hx := high_word(x) & 0x7FFFFFFF;
# Infinities and NaN are their own.
return x + x if hx >= 0x7FF00000;
# t is the cube root to 5 bits: a third of the bits less the exponent's bias,
# which the B's add back, of the sign of x.
var bits := bits_of(x);
if hx < 0x00100000 {
# Zero, its own root, or a subnormal, scaled by 2^54 to be normal.
bits = bits_of(x * 1.8014398509481984e+16);
hx = ((bits >> 32) as u32) & 0x7FFFFFFF;
return x if hx == 0;
hx = hx / 3 + cbrt_b2;
} else {
hx = hx / 3 + cbrt_b1;
}
bits &= 1u << 63;
bits |= (hx as u64) << 32;
var t := real_of_bits(bits);
# To 23 bits: cbrt(x) is t cbrt(x / t^3), and that about P(t^3 / x).
var r := (t * t) * (t / x);
t = t * ((cbrt_p0 + r * (cbrt_p1 + r * cbrt_p2)) + ((r * r) * r) * (cbrt_p3 + r * cbrt_p4));
# Rounded away from zero to 23 bits, so its square is exact.
t = real_of_bits((bits_of(t) + 0x80000000) & 0xFFFFFFFFC0000000);
# A step of Newton's method, to 53 bits.
val s := t * t;
r = x / s;
val w := t + t;
r = (r - t) / (w + r);
t = t + t * r;
return t;
}
# A double's square as a high part and a low part, whose sum is exact.
struct hypot_square {
var hi: f64;
var lo: f64;
}
# 2^27 + 1, which splits a double into halves of 26 bits.
const hypot_split: f64 = 134217729.0;
# The square of a double, from musl's hypot.c's `sq`: x is split into xh + xl,
# so the square's error is worked exactly.
def hypot_squared(x: f64): hypot_square {
val xc := x * hypot_split;
val xh := x - xc + xc;
val xl := x - xh;
val hi := x * x;
val lo := xh * xh - hi + 2.0 * xh * xl + xl * xl;
return hypot_square { hi = hi, lo = lo };
}
# sqrt(x^2 + y^2), from musl's hypot.c.
def hypot_double(x: f64, y: f64): f64 {
# |x| >= |y|, as the bits of each.
var ux := bits_of(x) & 0x7FFFFFFFFFFFFFFF;
var uy := bits_of(y) & 0x7FFFFFFFFFFFFFFF;
if ux < uy {
val ut: u64 = ux;
ux = uy;
uy = ut;
}
val ex := (ux >> 52) as i32;
val ey := (uy >> 52) as i32;
var a := real_of_bits(ux);
var b := real_of_bits(uy);
# Infinity where either is infinite, NaN included, and NaN where either is
# NaN otherwise.
return b if ey == 0x7FF;
return a if ex == 0x7FF || uy == 0;
# b is too small to change a: a + b rounds as a + b^2 / 2a would.
return a + b if ex - ey > 64;
# Scaled by 2^-700 or 2^700, so neither square overflows and the low parts do
# not underflow.
var z: f64 = 1;
if ex > 0x3FF + 510 {
z = 5.260135901548374e+210;
a *= 1.90109156629516e-211;
b *= 1.90109156629516e-211;
} else if ey < 0x3FF - 450 {
z = 1.90109156629516e-211;
a *= 5.260135901548374e+210;
b *= 5.260135901548374e+210;
}
val sa := hypot_squared(a);
val sb := hypot_squared(b);
return z * square_root(sb.lo + sa.lo + sb.hi + sa.hi);
}
+222
View File
@@ -0,0 +1,222 @@
#! @file trig.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the trigonometric functions: sine, cosine, and tangent, of an angle
#! in radians. Each reduces its argument by multiples of π/2 to within about
#! π/4 of 0, with `reduce_pio2`, exactly however large it is, and works the
#! reduced angle with a polynomial.
#!
#! Ported from musl 1.2.5, which is Copyright © 2005-2020 Rich Felker, et al.,
#! under the MIT license. Its `sin`, `cos`, and `tan` are from FreeBSD's
#! s_sin.c, s_cos.c, and s_tan.c, which say:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunPro, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! Its kernels `__sin` and `__cos` are from k_sin.c and k_cos.c, which say:
#!
#! Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
#!
#! Developed at SunSoft, a Sun Microsystems, Inc. business.
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! And `__tan` is from k_tan.c, which says:
#!
#! Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
#!
#! Permission to use, copy, modify, and distribute this
#! software is freely granted, provided that this notice
#! is preserved.
#!
#! Each is within 1 ulp of the true value for `f64`. An `f32` is worked in
#! `f64` and rounded once more.
module std::math;
#! The sine of an angle.
#! @tparam T The type of real.
#! @param x The angle, in radians.
#! @returns sin x, from -1 to 1: `-0` for `-0`, and NaN for infinity and NaN.
pub def sin<T>(x: T): T where T: real {
return sin_double(x as f64) as T;
}
#! The cosine of an angle.
#! @tparam T The type of real.
#! @param x The angle, in radians.
#! @returns cos x, from -1 to 1: 1 for `±0`, and NaN for infinity and NaN.
pub def cos<T>(x: T): T where T: real {
return cos_double(x as f64) as T;
}
#! The tangent of an angle.
#! @tparam T The type of real.
#! @param x The angle, in radians.
#! @returns tan x: `-0` for `-0`, and NaN for infinity and NaN. No double is an
#! odd multiple of π/2, so it is always finite, at most about 2.1e18
#! in magnitude.
pub def tan<T>(x: T): T where T: real {
return tan_double(x as f64) as T;
}
# sin x, cos x, and tan x, from musl's sin.c, cos.c, and tan.c. Each reduces x
# to y = x - n·π/2, and as n modulo 4 is 0, 1, 2, or 3, sin x is sin y, cos y,
# -sin y, or -cos y; cos x is cos y, -sin y, -cos y, or sin y; and tan x is
# tan y or -1 / tan y.
def sin_double(x: f64): f64 {
val ix := high_word(x) & 0x7FFFFFFF;
# Up to about π/4, where x needs no reducing, and below 2^-26, where sin x
# rounds to x.
if ix <= 0x3FE921FB {
return x if ix < 0x3E500000;
return trig_sin_kernel(x, 0.0, false);
}
# Infinity and NaN.
return x - x if ix >= 0x7FF00000;
val y := reduce_pio2(x);
val n := y.n & 3;
return trig_sin_kernel(y.hi, y.lo, true) if n == 0;
return trig_cos_kernel(y.hi, y.lo) if n == 1;
return -trig_sin_kernel(y.hi, y.lo, true) if n == 2;
return -trig_cos_kernel(y.hi, y.lo);
}
def cos_double(x: f64): f64 {
val ix := high_word(x) & 0x7FFFFFFF;
# Up to about π/4, and below 2^-27·√2, where cos x rounds to 1.
if ix <= 0x3FE921FB {
return 1.0 if ix < 0x3E46A09E;
return trig_cos_kernel(x, 0.0);
}
return x - x if ix >= 0x7FF00000;
val y := reduce_pio2(x);
val n := y.n & 3;
return trig_cos_kernel(y.hi, y.lo) if n == 0;
return -trig_sin_kernel(y.hi, y.lo, true) if n == 1;
return -trig_cos_kernel(y.hi, y.lo) if n == 2;
return trig_sin_kernel(y.hi, y.lo, true);
}
def tan_double(x: f64): f64 {
val ix := high_word(x) & 0x7FFFFFFF;
# Up to about π/4, and below 2^-27, where tan x rounds to x.
if ix <= 0x3FE921FB {
return x if ix < 0x3E400000;
return trig_tan_kernel(x, 0.0, false);
}
return x - x if ix >= 0x7FF00000;
val y := reduce_pio2(x);
return trig_tan_kernel(y.hi, y.lo, (y.n & 1) != 0);
}
# The kernels, from musl's __sin.c, __cos.c, and __tan.c: each of x + y, where
# |x + y| is at most about π/4 and y is below half an ulp of x.
# sin x = x + S1·x^3 + ... + S6·x^13, within 2^-58, on [0, π/4].
const trig_s1: f64 = -0.16666666666666632;
const trig_s2: f64 = 0.00833333333332249;
const trig_s3: f64 = -0.0001984126982985795;
const trig_s4: f64 = 2.7557313707070068e-06;
const trig_s5: f64 = -2.5050760253406863e-08;
const trig_s6: f64 = 1.58969099521155e-10;
# sin(x + y), where y is taken as 0 unless `tail` is. Its polynomial doesn't
# keep the sign of `-0`, which callers return themselves.
def trig_sin_kernel(x: f64, y: f64, tail: bool): f64 {
val z := x * x;
val w := z * z;
val r := trig_s2 + z * (trig_s3 + z * trig_s4) + z * w * (trig_s5 + z * trig_s6);
val v := z * x;
return x + v * (trig_s1 + z * r) if !tail;
# sin(x + y) is about sin x + (1 - x^2/2)·y.
return x - ((z * (0.5 * y - v * r) - y) - v * trig_s1);
}
# cos x = 1 - x^2/2 + C1·x^4 + ... + C6·x^14, within 2^-58, on [0, π/4].
const trig_c1: f64 = 0.0416666666666666;
const trig_c2: f64 = -0.001388888888887411;
const trig_c3: f64 = 2.480158728947673e-05;
const trig_c4: f64 = -2.7557314351390663e-07;
const trig_c5: f64 = 2.087572321298175e-09;
const trig_c6: f64 = -1.1359647557788195e-11;
# cos(x + y). It is about w + ((1 - w - x^2/2) + (r - x·y)), where w is
# 1 - x^2/2 rounded, and the first term in parentheses is what that rounding
# lost, and the second the rest of the polynomial and the tail's part, as
# cos(x + y) is about cos x - x·y.
def trig_cos_kernel(x: f64, y: f64): f64 {
val z := x * x;
var w := z * z;
val r := z * (trig_c1 + z * (trig_c2 + z * trig_c3)) + w * w * (trig_c4 + z * (trig_c5 + z * trig_c6));
val hz := 0.5 * z;
w = 1.0 - hz;
return w + (((1.0 - w) - hz) + (z * r - x * y));
}
# tan x = x + T[0]·x^3 + ... + T[12]·x^27, within 2^-59.2, on [0, 0.67434].
const trig_t: f64[13] = [
0.3333333333333341, 0.13333333333320124, 0.05396825397622605,
0.021869488294859542, 0.0088632398235993, 0.0035920791075913124,
0.0014562094543252903, 0.0005880412408202641, 0.0002464631348184699,
7.817944429395571e-05, 7.140724913826082e-05, -1.8558637485527546e-05,
2.590730518636337e-05,
];
# π/4, as a high part and a low part.
const trig_pio4: f64 = 0.7853981633974483;
const trig_pio4_low: f64 = 3.061616997868383e-17;
# tan(x + y), or -1 / tan(x + y) where `odd` is. Its polynomial doesn't keep the
# sign of `-0`, which callers return themselves.
def trig_tan_kernel(x0: f64, y0: f64, odd: bool): f64 {
var x := x0;
var y := y0;
val hx := high_word(x);
# From about 0.6744 up, tan x is worked as tan(π/4 - x'), where x' is
# π/4 - |x|, which is (1 - tan x') / (1 + tan x').
val big := (hx & 0x7FFFFFFF) >= 0x3FE59428;
val sign := (hx >> 31) != 0;
if big {
if sign {
x = -x;
y = -y;
}
x = (trig_pio4 - x) + (trig_pio4_low - y);
y = 0.0;
}
val z := x * x;
var w := z * z;
# x^5 times the polynomial's terms from T[1], in two halves: the odd ones in
# w = x^4, and the even ones, times z = x^2.
var r := trig_t[1] + w * (trig_t[3] + w * (trig_t[5] + w * (trig_t[7] + w * (trig_t[9] + w * trig_t[11]))));
var v := z * (trig_t[2] + w * (trig_t[4] + w * (trig_t[6] + w * (trig_t[8] + w * (trig_t[10] + w * trig_t[12])))));
var s := z * x;
# tan(x + y) is about tan x + (1 + x^2)·y.
r = y + z * (s * (r + v) + y) + s * trig_t[0];
w = x + r;
if big {
s = odd ? -1.0 : 1.0;
v = s - 2.0 * (x + (r - w * w / (w + s)));
return sign ? -v : v;
}
return w if !odd;
# -1 / (x + r), which dividing alone would give within 2 ulp: w0 + v is x + r,
# and a0 is -1 / w, each with its low word cleared, so the products are exact.
val w0 := with_low_word(w, 0);
v = r - (w0 - x);
val a := -1.0 / w;
val a0 := with_low_word(a, 0);
return a0 + a * (1.0 + a0 * w0 + a0 * v);
}
+109
View File
@@ -0,0 +1,109 @@
#! @file paths.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains turning a path into a `file` URI and back, `std::io`'s paths being
#! read here so that `std::io` reads nothing of URIs.
import std::io;
module std::net;
#! Makes the `file` URI of an absolute path, as
#! `file:///usr/lib/my%20notes.txt`.
#! @param at The path, which must be absolute.
#! @param alloc The optional allocator for the text the URI holds.
#! @returns The URI, with each byte of the path but its delimiters and the
#! unreserved bytes percent-encoded, or why there is none.
#! @remarks On Windows, `C:\Users` is `file:///C:/Users`, and `\\server\share\x`
#! is `file://server/share/x`.
pub def uri::from_path(at: &path, alloc: maybe<&mut allocator> = nothing{}): result<uri, failure> {
if !at.is_absolute {
return failure { message = $"`{at.view()}` is relative, and only an absolute path has a `file` URI" };
}
var made := string::new(alloc);
made.append("file://");
when os == windows {
uri::windows_uri(at.view(), &mut made);
return uri::split(move(made));
}
for byte in at.view() {
uri::encode_byte(byte, "/", &mut made);
}
return uri::split(move(made));
}
#! Makes the path a `file` URI names.
#! @param this The URI, whose scheme must be `file`.
#! @param alloc The optional allocator for the text the path holds.
#! @returns The path, decoded from the URI's, or why there is none: the URI
#! names another scheme, or a file on another machine, or a path no
#! path here can be. A query or fragment is left out.
#! @remarks On Windows, a URI naming a machine other than `localhost` names a
#! path on its share, as `file://server/share/x` names
#! `\\server\share\x`.
pub def uri::to_path(&this, alloc: maybe<&mut allocator> = nothing{}): result<path, failure> {
if !uri::same_letters(this.scheme, "file") {
return failure { message = $"`{this.view()}` is not a `file` URI" };
}
var decoded := uri::decode(this.path, alloc);
if decoded is not value(&text) {
return failure { message = $"`{this.view()}` has a `%` that two hexadecimal digits do not follow" };
}
val host := this.host;
when os == windows {
return uri::windows_path(host, text.view(), alloc);
}
if !host.is_empty() && !uri::same_letters(host, "localhost") {
return failure { message = $"`{this.view()}` names a file on `{host}`, which no path here can" };
}
return path::parse(text.view(), alloc);
}
# The Windows path a `file` URI names, from its host and decoded path:
# `\\host\share\x` for a host other than `localhost`, and `C:\x` for `/C:/x`.
def uri::windows_path(host: strview, text: strview, alloc: maybe<&mut allocator>): result<path, failure> {
if !host.is_empty() && !uri::same_letters(host, "localhost") {
var share := string::new(alloc);
share.append("\\\\");
share.append(host);
share.append(text);
return path::parse(share.view(), alloc);
}
if text.length >= 3 && text[0] == '/' && text[1].is_alpha && text[2] == ':' {
return path::parse(text.substr(1, text.length - 1), alloc);
}
return path::parse(text, alloc);
}
# Writes what follows `file://` in the URI of an absolute Windows path: the host
# and share of `\\host\share\x` as `host/share/x`, and `C:\x` as `/C:/x`.
def uri::windows_uri(text: strview, into: &mut string): void {
var at := 2u;
if text.starts_with("\\\\") {
while at < text.length && text[at] != '\\' {
uri::encode_byte(text[at], "", into);
at++;
}
} else {
into.push('/');
into.push(text[0]);
into.push(':');
}
while at < text.length {
val byte := text[at];
at++;
if byte == '\\' {
into.push('/');
continue;
}
uri::encode_byte(byte, "", into);
}
}
+986
View File
@@ -0,0 +1,986 @@
#! @file uri.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains URIs, as RFC 3986 defines them: reading one from text, its parts,
#! resolving one against another, its normal form, and percent-encoding.
#! `std::io` turns a `file` URI into a `path` and back.
import std::containers;
module std::net;
# The bytes that separate parts within a component, which a URI holds as they are.
const uri_sub_delims: strview = "!$&'()*+,;=";
const uri_hex_digits: strview = "0123456789ABCDEF";
#! A Uniform Resource Identifier (URI): a sequence of characters naming a
#! resource, such as a web page, a service, an email address, a phone number, a
#! book, a real-world object such as a person or a place, or a concept.
#!
#! A URI is written `scheme:` then, after `//`, an authority of user
#! information, a host, and a port, then a path, a query after `?`, and a
#! fragment after `#`:
#!
#! https://user@example.com:8080/docs/index.html?lang=en#intro
#!
#! Every part but the path may be left out, and a URI without a scheme is a
#! relative reference, as `../images/logo.png`, which `resolve` turns into a
#! whole URI against a base.
#!
#! A URI holds its text as it was written, and its parts are views of it, still
#! percent-encoded, as `%20` for a space; `uri::decode` gives what they hold.
#! Two URIs are equal when their text is. `normalized` gives the form in which
#! two URIs naming the same resource by their syntax are equal.
#!
#! @sa https://www.rfc-editor.org/rfc/rfc3986
pub struct uri
: owning
, hashable
, equatable
, copyable
, moveable
{
var _text: string;
var _scheme: u64; #! Where what follows the scheme's `:` begins, or 0 where there is none.
var _host: u64; #! Where the host begins, after `//` and any user information and `@`.
var _port: u64; #! Where the host ends: the `:` before a port, or the end of the authority.
var _path: u64; #! Where the path begins, which ends the authority.
var _query: u64; #! Where the path ends: the `?` before a query, or the `#`, or the end.
var _fragment: u64; #! Where the query ends: the `#` before a fragment, or the end.
}
#! A parameter of a query written as `name=value`, as `uri::parameters` gives
#! it.
pub struct uri::parameter {
pub var name: strview; #! As written, still percent-encoded.
pub var value: strview; #! As written, still percent-encoded, and empty where there is no `=`.
}
#! The scheme a URI starts with, which says how to read the rest.
#! @param this The URI to read.
#! @returns A view of the scheme, as `https`, without its `:`, which is empty
#! for a relative reference.
pub val uri::scheme: strview {
get {
return this._scheme == 0
? strview::empty()
: this.view().substr(0, this._scheme - 1);
}
}
#! Whether a URI has a scheme, and so names a resource without a base to resolve
#! it against.
#! @param this The URI to check.
#! @returns Whether it has a scheme, rather than being a relative reference.
pub val uri::is_absolute: bool {
get => this._scheme != 0;
}
#! The authority of a URI, which follows `//`.
#! @param this The URI to read.
#! @returns A view of the user information, host, and port, as `user@host:8080`,
#! or `nothing` where the URI has no `//`.
pub val uri::authority: maybe<strview> {
get {
if !this.has_authority() {
return nothing{};
}
return this.view().substr(this._scheme + 2, this._path - this._scheme - 2);
}
}
#! The user information of a URI's authority, before its `@`.
#! @param this The URI to read.
#! @returns A view of it, as `user:password`, or `nothing` where there is no
#! `@`.
pub val uri::userinfo: maybe<strview> {
get {
if !this.has_authority() || this._host == this._scheme + 2 {
return nothing{};
}
return this.view().substr(this._scheme + 2, this._host - this._scheme - 3);
}
}
#! The user a URI's user information names.
#! @param this The URI to read.
#! @returns A view of the user information before its first `:`, which is empty
#! where there is none.
pub val uri::user: strview {
get {
if this.userinfo is not some(info) {
return strview::empty();
}
return info.substr(0, uri::colon_in(info));
}
}
#! The password a URI's user information holds, which RFC 3986 advises against
#! writing in a URI at all.
#! @param this The URI to read.
#! @returns A view of the user information after its first `:`, or `nothing`
#! where it has none.
pub val uri::password: maybe<strview> {
get {
if this.userinfo is not some(info) {
return nothing{};
}
val colon := uri::colon_in(info);
if colon == info.length {
return nothing{};
}
return info.substr(colon + 1, info.length - colon - 1);
}
}
#! The host a URI's authority names.
#! @param this The URI to read.
#! @returns A view of the host, as `example.com` or `127.0.0.1`, or an IPv6
#! address without the brackets around it, as `::1`. It is empty where
#! the URI has no authority, or names none.
pub val uri::host: strview {
get {
val host := this.view().substr(this._host, this._port - this._host);
if host.length >= 2 && host[0] == '[' && host[host.length - 1] == ']' {
return host.substr(1, host.length - 2);
}
return host;
}
}
#! The port a URI's authority names.
#! @param this The URI to read.
#! @returns The port, or `nothing` where there is none, or its `:` has no digits
#! after it, which leaves the scheme's own.
pub val uri::port: maybe<u16> {
get {
if this._port >= this._path {
return nothing{};
}
val digits := this.view().substr(this._port + 1, this._path - this._port - 1);
if digits.is_empty() {
return nothing{};
}
var value := 0u;
for byte in digits {
value = value * 10 + byte.digit_value;
}
return value as u16;
}
}
#! The path of a URI, which every URI has, though it may be empty.
#! @param this The URI to read.
#! @returns A view of the path, as `/docs/index.html`, still percent-encoded.
pub val uri::path: strview {
get => this.view().substr(this._path, this._query - this._path);
}
#! The query of a URI, after its `?`.
#! @param this The URI to read.
#! @returns A view of the query, as `lang=en&page=2`, still percent-encoded, or
#! `nothing` where there is no `?`.
pub val uri::query: maybe<strview> {
get {
if this._query == this._fragment {
return nothing{};
}
return this.view().substr(this._query + 1, this._fragment - this._query - 1);
}
}
#! The fragment of a URI, after its `#`, which names a part of the resource.
#! @param this The URI to read.
#! @returns A view of the fragment, still percent-encoded, or `nothing` where
#! there is no `#`.
pub val uri::fragment: maybe<strview> {
get {
if this._fragment == this._text.length {
return nothing{};
}
return this.view().substr(this._fragment + 1, this._text.length - this._fragment - 1);
}
}
#! Reads text as a URI or a relative reference.
#! @param text The text to read, as `https://example.com/a?b#c`, `../d`, or
#! `#e`. Empty text is a reference to the document it is in.
#! @param alloc The optional allocator for the text the URI holds.
#! @returns The URI, or why the text is not one. Bytes a part cannot hold, such
#! as a space, must already be percent-encoded, as `uri::encode` does.
pub def uri::parse(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): result<uri, failure> {
var made := uri { _text = string::from(text, alloc) };
made.locate();
var message := made.problem();
if message.length > 0 {
return failure { message = move(message) };
}
return move(made);
}
#! Percent-encodes text, so that a URI can hold it within one of its parts.
#! @param text The text to encode.
#! @param keep The bytes to keep as they are, besides the unreserved letters,
#! digits, `-`, `.`, `_`, and `~`, as `/` to encode a path.
#! @param alloc The optional allocator for the encoded text.
#! @returns The text, with every other byte written as `%` and two upper-case
#! hexadecimal digits, as a space is `%20`.
pub def uri::encode(
text: strview,
keep: strview = "",
alloc: maybe<&mut allocator> = nothing{}
): string {
var made := string::new(alloc);
made.reserve(text.length);
for byte in text {
uri::encode_byte(byte, keep, &mut made);
}
return made;
}
#! Decodes percent-encoded text, as a part of a URI holds it.
#! @param text The text to decode, as `my%20notes`.
#! @param alloc The optional allocator for the decoded text.
#! @returns The text, with each `%` and the two hexadecimal digits after it
#! written as the byte they are, or why it cannot be decoded. A `+` is
#! left as it is, since only forms write a space as one.
pub def uri::decode(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): result<string, failure> {
var made := string::new(alloc);
if !uri::decode_into(text, &mut made, false) {
return failure { message = $"`{text}` has a `%` that two hexadecimal digits do not follow" };
}
return move(made);
}
#! Decodes percent-encoded text as `decode` does, but leniently, as editors and
#! browsers read what they are given: a `%` that two hexadecimal digits do not
#! follow is kept as it is.
#! @param text The text to decode, as `100%25 of my%20notes`.
#! @param alloc The optional allocator for the decoded text.
#! @returns The text, with each `%` and the two hexadecimal digits after it
#! written as the byte they are, and everything else as it is.
pub def uri::decode_lenient(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): string {
var made := string::new(alloc);
uri::decode_into(text, &mut made, true);
return made;
}
#! Creates a copy of the provided URI.
#! @param other The URI to copy.
#! @returns The copy, which owns its own text, with the other's allocator.
pub def uri::copy_of(other: &uri): uri {
return uri {
_text = string::copy_of(&other._text),
_scheme = other._scheme,
_host = other._host,
_port = other._port,
_path = other._path,
_query = other._query,
_fragment = other._fragment
};
}
#! Creates a new URI by moving the text of another into it.
#! @param other The URI to move from, which is empty after.
#! @returns The moved URI, which takes the text and allocator with it.
pub def uri::move_of(other: &mut uri): uri {
val made: uri = uri {
_text = string::move_of(&mut other._text),
_scheme = other._scheme,
_host = other._host,
_port = other._port,
_path = other._path,
_query = other._query,
_fragment = other._fragment
};
other.locate();
return made;
}
#! Views the text of a URI, as it was written.
#! @param this The URI to view.
#! @returns A view of its text, which is only good until the URI closes.
pub def uri::view(&this): strview {
return this._text.view();
}
#! Views each segment of a URI's path, between its `/`s, in turn.
#! @param this The URI to split.
#! @returns The segments, still percent-encoded, each viewing into the URI's
#! text. A `/` the path starts with is left out, so `/a/b` holds `a`
#! and `b`, and one it ends with leaves an empty segment last. An empty
#! path has none.
pub def uri::segments(&this): splits {
var path := this.path;
if path.is_empty() {
return splits::empty();
}
if path[0] == '/' {
path = path.substr(1, path.length - 1);
}
return path.split('/');
}
#! Views each parameter of a URI's query, as `name=value` pairs separated by
#! `&`, which is how forms and most programs write a query.
#! @param this The URI to read.
#! @param alloc The allocator for the list that will be created.
#! @returns The parameters, in order, each viewing into the URI's text. Empty
#! pairs, as in `a=1&&b=2`, are left out.
pub def uri::parameters(&this, alloc: maybe<&mut allocator> = nothing{}): vector<uri::parameter> {
var found := vector::<uri::parameter>::new(alloc);
if this.query is not some(query) {
return found;
}
var start := 0u;
while start <= query.length {
var end := start;
while end < query.length && query[end] != '&' {
end++;
}
val pair := query.substr(start, end - start);
start = end + 1;
if pair.is_empty() {
continue;
}
var equal := 0u;
while equal < pair.length && pair[equal] != '=' {
equal++;
}
found.append(uri::parameter {
name = pair.substr(0, equal),
value = equal < pair.length
? pair.substr(equal + 1, pair.length - equal - 1)
: strview::empty()
});
}
return found;
}
#! Finds the value of the first parameter of a URI's query with a name.
#! @param this The URI to read.
#! @param name The name to look for, as it is written in the query.
#! @returns A view of the value, still percent-encoded, or `nothing` where no
#! parameter has the name.
pub def uri::query_value(&this, name: strview): maybe<strview> {
for &each in this.parameters() {
if each.name == name {
return each.value;
}
}
return nothing{};
}
#! Resolves a reference against a base, as RFC 3986 does in section 5.2: a whole
#! URI is taken as it is, and anything it leaves out is taken from the base,
#! with a relative path following on from the base's.
#! @param this The reference to resolve, as `../c?d` or `#e`.
#! @param base The URI it is relative to, which has a scheme.
#! @returns The resolved URI, whose path holds no `.` or `..` segments, as
#! `http://a/b/c?d` from `../c?d` against `http://a/b/x/y`.
pub def uri::resolve(&this, base: &uri): uri {
var made := string::new(this._text.alloc);
if this.is_absolute || this.has_authority() {
made.append(this.is_absolute ? this.scheme_part() : base.scheme_part());
made.append(this.authority_part());
uri::remove_dots(this.path, &mut made);
made.append(this.query_part());
} else {
made.append(base.scheme_part());
made.append(base.authority_part());
this.merge_onto(base, &mut made);
}
made.append(this.fragment_part());
return uri::split(move(made));
}
#! Makes the normal form of a URI, as RFC 3986 does in section 6.2.2, in which
#! two URIs that name the same resource by their syntax alone are equal.
#! @param this The URI to normalize.
#! @returns The URI with its scheme and host in lower case, each
#! percent-encoding of an unreserved byte decoded and the rest in upper
#! case, and, where it has a scheme, no `.` or `..` segments. A `:`
#! without a port is left out.
pub def uri::normalized(&this): uri {
val text := this.view();
var made := string::new(this._text.alloc);
for byte in this.scheme_part() {
made.push(byte.to_lower);
}
if this.has_authority() {
made.append("//");
if this.userinfo is some(info) {
uri::normalize_into(info, &mut made, false);
made.push('@');
}
uri::normalize_into(text.substr(this._host, this._port - this._host), &mut made, true);
if this._port + 1 < this._path {
made.append(text.substr(this._port, this._path - this._port));
}
}
if this.is_absolute {
var path := string::new(nothing{});
uri::normalize_into(this.path, &mut path, false);
uri::remove_dots(path.view(), &mut made);
} else {
uri::normalize_into(this.path, &mut made, false);
}
if this.query is some(query) {
made.push('?');
uri::normalize_into(query, &mut made, false);
}
if this.fragment is some(fragment) {
made.push('#');
uri::normalize_into(fragment, &mut made, false);
}
return uri::split(move(made));
}
#! Gives back the memory holding the text of a URI.
#! @param this The URI to close.
pub def uri::close(&mut this): void {
this._text.close();
this.locate();
}
#! Compares one URI to another by equality.
#! @param this The URI to compare against.
#! @param other The URI to compare with.
#! @returns Whether both have the same text. Compare their `normalized` forms to
#! ask whether they name the same resource.
pub def uri::equals(&this, other: &uri): bool {
return this._text.equals(&other._text);
}
#! Hashes the provided URI.
#! @param this The URI to hash.
#! @returns The hash code of its text, which equal URIs share.
pub def uri::hash(&this): u64 {
return this._text.hash();
}
# Makes a URI of text that is known to be one, as what `resolve` and `normalized`
# write is, finding where its parts are.
def uri::split(text: string): uri {
var made := uri { _text = move(text) };
made.locate();
return made;
}
# Finds where each part of the text begins and ends, as RFC 3986 does in its
# appendix B, without asking whether the parts are what they should be.
def uri::locate(&mut this): void {
val text := this._text.view();
val n := text.length;
var at := 0u;
while at < n && text[at] != ':' && text[at] != '/' && text[at] != '?' && text[at] != '#' {
at++;
}
this._scheme = at < n && text[at] == ':' ? at + 1 : 0;
at = this._scheme;
this._host = at;
this._port = at;
if at + 1 < n && text[at] == '/' && text[at + 1] == '/' {
at += 2;
var end := at;
while end < n && text[end] != '/' && text[end] != '?' && text[end] != '#' {
end++;
}
# The user information ends at the last `@`, and a port follows the first `:`
# after the host, which is after the `]` of an address in brackets.
var host := at;
for k in at..end {
if text[k] == '@' {
host = k + 1;
}
}
var port := host;
if port < end && text[port] == '[' {
while port < end && text[port] != ']' {
port++;
}
}
while port < end && text[port] != ':' {
port++;
}
this._host = host;
this._port = port;
at = end;
}
this._path = at;
while at < n && text[at] != '?' && text[at] != '#' {
at++;
}
this._query = at;
if at < n && text[at] == '?' {
while at < n && text[at] != '#' {
at++;
}
}
this._fragment = at;
}
# Why the parts `locate` found are not what RFC 3986 lets them be, or nothing
# where they are.
def uri::problem(&this): string {
val text := this.view();
if this._scheme > 0 {
val scheme := text.substr(0, this._scheme - 1);
if scheme.is_empty() {
return $"`{text}` has a `:` where a scheme should end, but no scheme before it";
}
if !scheme[0].is_alpha {
return $"`{scheme}` is not a scheme, which starts with a letter";
}
for byte in scheme {
if !byte.is_alnum && byte != '+' && byte != '-' && byte != '.' {
return $"`{scheme}` is not a scheme, which only letters, digits, `+`, `-`, and `.` make";
}
}
}
if this.has_authority() {
var why := this.authority_problem();
if why.length > 0 {
return move(why);
}
}
val path := this.path;
val bad := uri::invalid_in(path, ":@/");
if bad is some {
return uri::holds(text, path, bad.some, "path");
}
if this.query is some(query) {
val wrong := uri::invalid_in(query, ":@/?");
if wrong is some {
return uri::holds(text, query, wrong.some, "query");
}
}
if this.fragment is some(fragment) {
val wrong := uri::invalid_in(fragment, ":@/?");
if wrong is some {
return uri::holds(text, fragment, wrong.some, "fragment");
}
}
return "";
}
# Why the user information, host, or port of the authority is not what they may
# be, or nothing where they are.
def uri::authority_problem(&this): string {
val text := this.view();
if this.userinfo is some(info) {
val bad := uri::invalid_in(info, ":");
if bad is some {
return uri::holds(text, info, bad.some, "user information");
}
}
val host := text.substr(this._host, this._port - this._host);
if host.length > 0 && host[0] == '[' {
if host.length < 2 || host[host.length - 1] != ']' {
return $"`{text}` opens an address with `[` but does not close it with `]`";
}
val inside := host.substr(1, host.length - 2);
if !uri::is_ip_literal(inside) {
return $"`{inside}` is not an IPv6 address";
}
} else {
val bad := uri::invalid_in(host, "");
if bad is some {
return uri::holds(text, host, bad.some, "host");
}
}
if this._port >= this._path {
return "";
}
val digits := text.substr(this._port + 1, this._path - this._port - 1);
var value := 0u;
for byte in digits {
if !byte.is_digit {
return $"`{digits}` is not a port, which only digits make";
}
value = value * 10 + byte.digit_value;
if value > 65535 {
return $"`{digits}` is past 65535, the highest port";
}
}
return "";
}
# Says which byte of a part a URI cannot hold as it is.
def uri::holds(text: strview, part: strview, at: u64, name: strview): string {
if part[at] == '%' {
return $"`{text}` has a `%` in its {name} that two hexadecimal digits do not follow";
}
return $"`{text}` holds `{part.substr(at, 1)}` in its {name}, which a URI holds only percent-encoded";
}
# Gives the index of the first byte of a part that it cannot hold, where only
# unreserved bytes, percent-encodings, sub-delimiters, and `allowed` may be.
def uri::invalid_in(part: strview, allowed: strview): maybe<u64> {
var at := 0u;
while at < part.length {
val byte := part[at];
if byte == '%' {
if at + 2 >= part.length || !part[at + 1].is_hex || !part[at + 2].is_hex {
return at;
}
at += 3;
continue;
}
if !uri::is_unreserved(byte) && !uri::is_sub_delim(byte) && !allowed.contains(&byte) {
return at;
}
at++;
}
return nothing{};
}
def uri::is_unreserved(byte: u8): bool {
return byte.is_alnum || byte == '-' || byte == '.' || byte == '_' || byte == '~';
}
def uri::is_sub_delim(byte: u8): bool {
return uri_sub_delims.contains(&byte);
}
# Whether what is between the brackets of a host is an IPv6 address, or a future
# form of address, which starts with `v`.
def uri::is_ip_literal(text: strview): bool {
if text.length > 0 && (text[0] == 'v' || text[0] == 'V') {
return uri::is_ip_future(text);
}
return uri::is_ipv6(text);
}
# `v`, its version in hexadecimal, `.`, then unreserved bytes, sub-delimiters,
# and `:`.
def uri::is_ip_future(text: strview): bool {
var at := 1u;
while at < text.length && text[at].is_hex {
at++;
}
if at == 1 || at + 1 >= text.length || text[at] != '.' {
return false;
}
at++;
while at < text.length {
val byte := text[at];
if !uri::is_unreserved(byte) && !uri::is_sub_delim(byte) && byte != ':' {
return false;
}
at++;
}
return true;
}
# Eight groups of up to four hexadecimal digits separated by `:`, where `::` may
# stand for one or more groups of zeros once, and an IPv4 address may stand for
# the last two.
def uri::is_ipv6(text: strview): bool {
var groups := 0u;
var elided: bool = false;
var at := 0u;
if text.starts_with("::") {
elided = true;
at = 2;
if at == text.length {
return true;
}
}
while true {
val start := at;
while at < text.length && text[at].is_hex && at - start < 5 {
at++;
}
if at < text.length && text[at] == '.' {
if !uri::is_ipv4(text.substr(start, text.length - start)) {
return false;
}
groups += 2;
break;
}
val digits := at - start;
if digits == 0 || digits > 4 {
return false;
}
groups++;
if at == text.length {
break;
}
if text[at] != ':' {
return false;
}
at++;
if at < text.length && text[at] == ':' {
if elided {
return false;
}
elided = true;
at++;
if at == text.length {
break;
}
continue;
}
if at == text.length {
return false;
}
}
return elided ? groups < 8 : groups == 8;
}
# Four numbers from 0 to 255 separated by `.`, none written with a leading zero.
def uri::is_ipv4(text: strview): bool {
var parts := 0u;
var at := 0u;
while parts < 4 {
val start := at;
var value := 0u;
while at < text.length && text[at].is_digit && at - start < 4 {
value = value * 10 + text[at].digit_value;
at++;
}
val digits := at - start;
if digits == 0 || digits > 3 || value > 255 || (digits > 1 && text[start] == '0') {
return false;
}
parts++;
if parts == 4 {
break;
}
if at >= text.length || text[at] != '.' {
return false;
}
at++;
}
return at == text.length;
}
# Whether a URI has an authority, which `//` starts.
def uri::has_authority(&this): bool {
val text := this.view();
return this._path >= this._scheme + 2 && text[this._scheme] == '/' && text[this._scheme + 1] == '/';
}
# The scheme with its `:`, or nothing for a relative reference.
def uri::scheme_part(&this): strview {
return this.view().substr(0, this._scheme);
}
# The authority with the `//` before it, or nothing where there is none.
def uri::authority_part(&this): strview {
return this.view().substr(this._scheme, this._path - this._scheme);
}
# The query with the `?` before it, or nothing where there is none.
def uri::query_part(&this): strview {
return this.view().substr(this._query, this._fragment - this._query);
}
# The fragment with the `#` before it, or nothing where there is none.
def uri::fragment_part(&this): strview {
return this.view().substr(this._fragment, this._text.length - this._fragment);
}
# Writes the path and query of a reference without a scheme or authority,
# resolved against a base, as RFC 3986 does in section 5.2.2.
def uri::merge_onto(&this, base: &uri, into: &mut string): void {
val path := this.path;
if path.is_empty() {
into.append(base.path);
into.append(this.query is some ? this.query_part() : base.query_part());
return;
}
if path[0] == '/' {
uri::remove_dots(path, into);
into.append(this.query_part());
return;
}
# A relative path follows the base's up to its last `/`, or follows `/` where the
# base has an authority and no path.
var merged := string::new(nothing{});
val held := base.path;
if base.has_authority() && held.is_empty() {
merged.push('/');
} else {
var slash := held.length;
while slash > 0 && held[slash - 1] != '/' {
slash--;
}
merged.append(held.substr(0, slash));
}
merged.append(path);
uri::remove_dots(merged.view(), into);
into.append(this.query_part());
}
# Writes a path without its `.` and `..` segments, each `..` taking the segment
# before it away, as RFC 3986 does in section 5.2.4.
def uri::remove_dots(path: strview, into: &mut string): void {
val floor := into.length;
var at := 0u;
while at < path.length {
val rest := path.substr(at, path.length - at);
if rest.starts_with("../") {
at += 3;
continue;
}
if rest.starts_with("./") || rest.starts_with("/./") {
at += 2;
continue;
}
if rest == "/." {
into.push('/');
return;
}
if rest.starts_with("/../") {
uri::drop_segment(into, floor);
at += 3;
continue;
}
if rest == "/.." {
uri::drop_segment(into, floor);
into.push('/');
return;
}
if rest == "." || rest == ".." {
return;
}
var end := path[at] == '/' ? at + 1 : at;
while end < path.length && path[end] != '/' {
end++;
}
into.append(path.substr(at, end - at));
at = end;
}
}
# Takes the last segment of the path being written away, with the `/` before it,
# never reaching back before `floor`, where the path began.
def uri::drop_segment(into: &mut string, floor: u64): void {
var at := into.length;
while at > floor && into[at - 1] != '/' {
at--;
}
if at > floor {
at--;
}
into.resize(at);
}
# Writes a part in its normal form: each percent-encoding of an unreserved byte
# decoded, the rest with upper-case digits, and, where `lower` is set, every letter
# in lower case, as a host is written.
def uri::normalize_into(part: strview, into: &mut string, lower: bool): void {
var at := 0u;
while at < part.length {
val byte := part[at];
if byte != '%' || at + 2 >= part.length {
into.push(lower ? byte.to_lower : byte);
at++;
continue;
}
val decoded := (part[at + 1].digit_value * 16 + part[at + 2].digit_value) as u8;
if !uri::is_unreserved(decoded) {
into.push('%');
into.push(part[at + 1].to_upper);
into.push(part[at + 2].to_upper);
at += 3;
continue;
}
into.push(lower ? decoded.to_lower : decoded);
at += 3;
}
}
# Writes a byte as it is where it is unreserved or kept, and percent-encoded
# otherwise.
# Decodes percent-encoded text into a string, giving whether each `%` is
# followed by two hexadecimal digits. Where one is not, a lenient decoding keeps
# the `%` as it is and goes on, and any other stops.
def uri::decode_into(text: strview, into: &mut string, lenient: bool): bool {
into.reserve(text.length);
var at := 0u;
while at < text.length {
val byte := text[at];
if byte == '%' && at + 2 < text.length && text[at + 1].is_hex && text[at + 2].is_hex {
into.push((text[at + 1].digit_value * 16 + text[at + 2].digit_value) as u8);
at += 3;
continue;
}
if byte == '%' && !lenient {
return false;
}
into.push(byte);
at++;
}
return true;
}
def uri::encode_byte(byte: u8, keep: strview, into: &mut string): void {
if uri::is_unreserved(byte) || keep.contains(&byte) {
into.push(byte);
return;
}
into.push('%');
into.push(uri_hex_digits[byte >> 4]);
into.push(uri_hex_digits[byte & 15]);
}
# Where the first `:` of user information is, or its end.
def uri::colon_in(info: strview): u64 {
var at := 0u;
while at < info.length && info[at] != ':' {
at++;
}
return at;
}
# Whether two texts hold the same letters, whatever their case.
def uri::same_letters(a: strview, b: strview): bool {
if a.length != b.length {
return false;
}
for i in 0..a.length {
if a[i].to_lower != b[i].to_lower {
return false;
}
}
return true;
}
+184
View File
@@ -0,0 +1,184 @@
#! @file child.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `child`, a program that a command started, which is talked to
#! through its pipes, and waited for where it closes; `status`, how one stopped;
#! and `captured`, how one stopped with everything it wrote.
import std::io;
import system;
module std::process;
#! How a child stopped, which compares equal to another only where both say the
#! same.
#!
#! Windows stops a program by a signal only where `child::kill` stopped it,
#! which is `kill`, numbered 9, or where the console's Ctrl-C did, which is
#! `interrupt`, numbered 2; every other way it stops is an exit.
pub union status : equatable {
pub var exited: i32; #! It exited, with this status.
pub var signaled: i32; #! A signal stopped it, by the system's number.
}
#! Whether two statuses say the same.
#! @param this The status.
#! @param other The status to compare it with.
#! @returns Whether both are exits, or both signals, of the same number.
pub def status::equals(&this, other: &status): bool {
if this is exited(a) && other is exited(b) {
return a == b;
}
if this is signaled(a) && other is signaled(b) {
return a == b;
}
return false;
}
#! Whether the child exited with zero, which says it did what it was asked to.
#! @param this The status to read.
#! @returns Whether it exited, with zero.
pub val status::succeeded: bool {
get {
if this is exited(code) {
return code == 0;
}
return false;
}
}
#! A program that a command started, which runs beside this one, and which is
#! waited for where it closes.
#!
#! Each standard stream the command piped is an open `io::file` of the child,
#! which the program writes to or reads, and the rest are not open. Each may be
#! borrowed, as `io::reader_of(child.output())` borrows the output, or taken
#! over, as `io::reader_of(move(child.output()))` takes it, leaving the child a
#! file that is not open.
#!
#! A child cannot be copied, since only one value may wait for it, but it can be
#! moved. One moved from holds no program, and waits for nothing.
pub struct child : owning {
var _id: i64;
# Whether it is yet to be waited for, which one moved from is not, and how it
# stopped, once it has.
var _running: bool;
var _status: status;
var _input: io::file;
var _output: io::file;
var _error: io::file;
}
#! The number the system knows the child by.
#! @param this The child to read the number of.
#! @returns The number, which is zero for one moved from.
pub val child::id: u64 {
get => this._id as u64;
}
#! The pipe the child reads its standard input from, which is open where the
#! command piped it. Closing it ends the child's input.
#! @param this The child.
#! @returns The pipe's end the program writes.
pub def child::input(&mut this): &mut io::file {
return &mut this._input;
}
#! The pipe the child writes its standard output to, which is open where the
#! command piped it.
#! @param this The child.
#! @returns The pipe's end the program reads.
pub def child::output(&mut this): &mut io::file {
return &mut this._output;
}
#! The pipe the child writes its standard error to, which is open where the
#! command piped it.
#! @param this The child.
#! @returns The pipe's end the program reads.
pub def child::error(&mut this): &mut io::file {
return &mut this._error;
}
#! Waits for the child to stop. Its input is closed first, so a child reading
#! its input to the end can finish.
#! @param this The child to wait for.
#! @returns How it stopped, which waiting again gives again, or why it could not
#! be waited for: `io_error::invalid` for a child moved from, and
#! `io_error::interrupted` where a signal the program handles ended the
#! wait, after which it can be waited for again.
pub def child::wait(&mut this): result<status, io_error> {
this._input.close();
if !this._running {
if this._id == 0 {
return io_error::invalid;
}
return this._status;
}
var stopped: system::process_status;
val waited := system::wait(this._id, &mut stopped);
if waited < 0 {
return system::error_of(waited);
}
this._running = false;
this._status = stopped.exited ? status { exited = stopped.code } : status { signaled = stopped.signal };
return this._status;
}
#! Stops the child at once, which it cannot put off. Once the child has been
#! waited for, this does nothing, since the system may then have given its
#! number to another program.
#! @param this The child to stop.
#! @returns Nothing, or why it could not be stopped.
pub def child::kill(&mut this): result<void, io_error> {
if !this._running {
return;
}
val sent := system::kill(this._id, system::signal::kill);
if sent < 0 {
return system::error_of(sent);
}
return;
}
#! Closes the child's pipes, then waits for it to stop, as many times as a
#! signal ends the wait. A child that has been waited for, or moved from, is not
#! waited for again.
#! @param this The child to close.
pub def child::close(&mut this): void {
this._input.close();
this._output.close();
this._error.close();
while this._running {
if this.wait() is error(why) && why != io_error::interrupted {
return;
}
}
}
#! What `command::capture` gives: how the child stopped, and everything it
#! wrote.
pub struct captured {
pub var status: status; #! How the child stopped.
pub var output: string; #! What it wrote to its standard output.
pub var error: string; #! What it wrote to its standard error.
}
#! A variable of the environment the program started with.
#! @param name The name of the variable, as `PATH`, which Windows reads
#! whatever the case of its letters, as `Path`.
#! @returns Its value, which views memory that lasts as long as the program, or
#! `nothing` where the program started without it.
pub def variable(name: strview): maybe<strview> {
for each in system::environment() {
if each.length > name.length && each[name.length] == '=' && same_name(each.substr(0, name.length), name) {
return each.substr(name.length + 1, each.length - name.length - 1);
}
}
return nothing{};
}
+606
View File
@@ -0,0 +1,606 @@
#! @file command.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `std::process`, which starts other programs, and `command`, a
#! program to start with its arguments, directory, variables, and standard
#! streams, which starts it as a `child` to talk to, runs it to its end, or
#! captures everything it writes.
#!
#! `std::process` is written once over `system`, which starts a program the
#! way each system does, so it is the same everywhere.
import std::io;
import system;
module std::process;
# Bytes read from a child's output at a time, while capturing it.
const capture_bytes: u64 = 16384;
#! Where one of a started program's standard streams goes.
pub enum stdio: u8 {
inherit, #! The program's own.
piped, #! A pipe, whose other end the child gives the program.
none, #! Nothing: reading it ends at once, and writing goes nowhere.
}
#! A program to start, and what it is given, which can start any number of
#! children, each the same way.
#!
#! The program is found as it is started: a name without a `/` in the
#! directories of the `PATH` the child will have, as a shell finds it, and one
#! with a `/` where it says, from where the child runs. Its first argument is
#! the name as it is given here, and the arguments added follow.
#!
#! On Windows, a name holding a `\` too, or beginning with a drive, as `C:`, is
#! where it says. The directories of `PATH` are split at `;`, and a name ending
#! in none of the endings `PATHEXT` lists, as `.EXE` and `.CMD`, is tried with
#! each of them in turn, as the system's shell tries it. The names of variables
#! are the same whatever the case of their letters, as `Path` is `PATH`.
#!
#! A command owns all it gives a child. A file given to it, as by `output_to`,
#! goes to the first child it starts, and starting that child closes the
#! program's copy, so the child alone holds it.
pub struct command {
var _program: string;
var _arguments: vector<string>;
var _directory: string;
var _variables: vector<setting>;
var _cleared: bool;
var _streams: stdio[3];
var _set_input: bool;
var _files: io::file[3];
}
# A variable a command sets, or removes where `value` is `nothing`.
struct setting {
var name: string;
var value: maybe<string>;
}
#! Makes a command to start a program, with no arguments, in the program's own
#! directory, with the program's own variables and standard streams.
#! @param program The program's name, as `cc`, or its path, as `./build.sh`.
#! @returns The command.
pub def command::new(program: strview): command {
return command {
_program = string::from(program, nothing{}),
_arguments = vector::<string>::new(),
_directory = string::new(nothing{}),
_variables = vector::<setting>::new()
};
}
#! Adds an argument, after those added before.
#! @param this The command.
#! @param text The argument, which the program is given as it is, without
#! being split or quoted.
pub def command::argument(&mut this, text: strview): void {
this._arguments.append(string::from(text, nothing{}));
}
#! Adds arguments, after those added before.
#! @param this The command.
#! @param texts The arguments, in order.
pub def command::arguments(&mut this, texts: span<strview>): void {
for text in texts {
this._arguments.append(string::from(text, nothing{}));
}
}
#! Sets the directory the program runs in, which is the program's own unless
#! this is set.
#! @param this The command.
#! @param at The directory.
pub def command::directory(&mut this, at: &path): void {
this._directory.clear();
this._directory.append(at.view());
}
#! Gives the program a variable, in place of any of the name it would have.
#! @param this The command.
#! @param name The name of the variable, which holds no `=`.
#! @param value Its value.
pub def command::set_variable(&mut this, name: strview, value: strview): void {
this.change(name, string::from(value, nothing{}));
}
#! Starts the program without a variable it would have.
#! @param this The command.
#! @param name The name of the variable.
pub def command::remove_variable(&mut this, name: strview): void {
this.change(name, nothing{});
}
#! Starts the program with none of the program's variables, and only those set
#! after this.
#! @param this The command.
pub def command::clear_variables(&mut this): void {
this._variables.clear();
this._cleared = true;
}
#! Sets where the program's standard input comes from, which is the program's
#! own unless this is set.
#! @param this The command.
#! @param how Where it comes from.
pub def command::input(&mut this, how: stdio): void {
this.stream(0, how);
this._set_input = true;
}
#! Sets where the program's standard output goes, which is the program's own
#! unless this is set.
#! @param this The command.
#! @param how Where it goes.
pub def command::output(&mut this, how: stdio): void {
this.stream(1, how);
}
#! Sets where the program's standard error goes, which is the program's own
#! unless this is set.
#! @param this The command.
#! @param how Where it goes.
pub def command::error(&mut this, how: stdio): void {
this.stream(2, how);
}
#! Gives the program a file to read as its standard input, taking it over.
#! @param this The command.
#! @param file The file, which goes to the first child started.
pub def command::input_from(&mut this, file: io::file): void {
this._files[0] = move(file);
this._set_input = true;
}
#! Gives the program a file to write its standard output to, taking it over.
#! @param this The command.
#! @param file The file, which goes to the first child started.
pub def command::output_to(&mut this, file: io::file): void {
this._files[1] = move(file);
}
#! Gives the program a file to write its standard error to, taking it over.
#! @param this The command.
#! @param file The file, which goes to the first child started.
pub def command::error_to(&mut this, file: io::file): void {
this._files[2] = move(file);
}
#! Starts the program, which runs beside this one.
#!
#! What the program has written to `io::output()` and `io::error_output()` is
#! flushed first, where the child writes to the same place, so it comes before
#! what the child writes. A child that reads the program's input does not see
#! what `io::input()` has already read.
#! @param this The command.
#! @returns The child, running, or why it could not be started:
#! `io_error::not_found` where the program is not found, which is
#! known before anything starts, `io_error::permission_denied` where it
#! may not be run, and `io_error::invalid` where a text the command
#! holds has a zero in it, or a variable's name is empty or holds `=`.
pub def command::spawn(&mut this): result<child, io_error> {
return this.start(false);
}
#! Starts the program, and waits for it to stop.
#! @param this The command.
#! @returns How it stopped, or why it could not be started, as `spawn` says.
pub def command::run(&mut this): result<status, io_error> {
var started := this.start(false) else (why) { return why; };
return started.wait();
}
#! Starts the program, and keeps everything it writes to its standard output
#! and error until it stops. Both are read as they arrive, so a program that
#! fills one while this waits on the other cannot stop both. The program is
#! given nothing to read, unless its input was set.
#! @param this The command.
#! @returns How the program stopped, with what it wrote, which is what it gives
#! for a program that failed too, or why it could not be started, as
#! `spawn` says, or read.
pub def command::capture(&mut this): result<captured, io_error> {
var started := this.start(true) else (why) { return why; };
started._input.close();
var output := string::new(nothing{});
var error := string::new(nothing{});
val buffer := raw_allocate(capture_bytes);
val read := read_both(&mut started, &mut output, &mut error, buffer);
raw_release(buffer);
if read is some(why) {
return why;
}
val stopped := started.wait() else (why) { return why; };
return captured { status = stopped, output = move(output), error = move(error) };
}
# Reads both outputs of a child as they arrive, until both end, giving why where
# reading failed.
def read_both(started: &mut child, output: &mut string, error: &mut string, buffer: *mut u8): maybe<io_error> {
var handles: system::fd[2];
var ready: bool[2];
while started._output.is_open || started._error.is_open {
handles[0] = started._output.is_open ? started._output.handle : -1;
handles[1] = started._error.is_open ? started._error.handle : -1;
val polled := system::poll(span::<system::fd>::over((&handles) as *system::fd, 2), slice::<bool>::over((&mut ready) as *mut bool, 2));
if polled < 0 {
return system::error_of(polled);
}
if ready[0] && read_into(&mut started._output, output, buffer) is some(why) {
return why;
}
if ready[1] && read_into(&mut started._error, error, buffer) is some(why) {
return why;
}
}
return nothing{};
}
# Reads what has arrived on a pipe into text, closing the pipe where it has
# ended, and giving why where reading failed.
def read_into(from: &mut io::file, into: &mut string, buffer: *mut u8): maybe<io_error> {
val count := from.read(slice::<u8>::over(buffer, capture_bytes)) else (why) { return why; };
if count == 0 {
from.close();
return nothing{};
}
into.append(span::<u8>::over(buffer as *u8, count));
return nothing{};
}
# Sets where a stream goes, giving up a file given for it before.
def command::stream(&mut this, which: u64, how: stdio): void {
this._files[which].close();
this._streams[which] = how;
}
# Records a variable set, or removed where `value` is `nothing`, in place of
# what was recorded of the name before.
def command::change(&mut this, name: strview, value: maybe<string>): void {
for &mut each in this._variables {
if same_name(each.name.view(), name) {
each.value = move(value);
return;
}
}
this._variables.append(setting { name = string::from(name, nothing{}), value = move(value) });
}
# What the command records of a variable, where it records anything.
def command::setting_of(&this, name: strview): maybe<&setting> {
for &each in this._variables {
if same_name(each.name.view(), name) {
return each;
}
}
return nothing{};
}
# Starts the program, with its streams as they are set, or with its output and
# error piped and its input empty unless set, where `capturing`.
def command::start(&mut this, capturing: bool): result<child, io_error> {
var found := this.find() else (why) { return why; };
var variables := this.environment() else (why) { return why; };
var arguments := vector::<strview>::new();
arguments.append(this._program.view());
for &each in this._arguments {
arguments.append(each.view());
}
var views := vector::<strview>::new();
for &each in variables {
views.append(each.view());
}
# What the program has written comes first, where the child writes there too.
if this.inherits(1, capturing) || this.inherits(2, capturing) {
_ = io::output().flush();
_ = io::error_output().flush();
}
# Each stream is the child's end of a pipe, the device that holds nothing, or
# a file given, which all close once the child has started, as each of its
# own; or it is the program's own, which is no file.
var made := child {};
var given: io::file[3];
for which in 0u..3u {
if this.connect(which, capturing, &mut given[which], &mut made) is error(why) {
return why;
}
}
val request := system::spawn_request {
program = found.view(),
arguments = arguments.view(),
environment = views.view(),
directory = this._directory.view(),
input = given[0].is_open ? given[0].handle : 0,
output = given[1].is_open ? given[1].handle : 1,
error = given[2].is_open ? given[2].handle : 2
};
val id := system::spawn(&request);
if id < 0 {
return system::error_of(id);
}
made._id = id;
made._running = true;
return move(made);
}
# Whether a stream goes where the program's own does.
def command::inherits(&this, which: u64, capturing: bool): bool {
return !this.uses_file(which, capturing) && this.choice(which, capturing) == stdio::inherit;
}
# Whether a stream goes to the file given for it, which capturing passes over
# for the outputs.
def command::uses_file(&this, which: u64, capturing: bool): bool {
return this._files[which].is_open && !(capturing && which != 0);
}
# Where a stream goes, where it goes to no file: capturing pipes both outputs,
# and gives the child nothing to read unless its input was set.
def command::choice(&this, which: u64, capturing: bool): stdio {
if capturing && which != 0 {
return stdio::piped;
}
if capturing && !this._set_input {
return stdio::none;
}
return this._streams[which];
}
# Gives the child what a stream goes to, as a file, which is not open where the
# stream is the program's own, keeping the program's end of a pipe in the child.
def command::connect(
&mut this,
which: u64,
capturing: bool,
given: &mut io::file,
made: &mut child
): result<void, io_error> {
if this.uses_file(which, capturing) {
given = move(this._files[which]);
return;
}
val how := this.choice(which, capturing);
if how == stdio::inherit {
return;
}
if how == stdio::none {
var device := path::parse(system::null_device) else (_) { return io_error::invalid; };
val flags := which == 0 ? open_flags::read : open_flags::write;
given = io::file::open(&device, flags) else (why) { return why; };
return;
}
var ends := io::pipe::open() else (why) { return why; };
if which == 0 {
given = move(ends.reading);
made._input = move(ends.writing);
return;
}
given = move(ends.writing);
if which == 1 {
made._output = move(ends.reading);
return;
}
made._error = move(ends.reading);
return;
}
# The variables the child gets, each as `NAME=value`: the program's, with the
# command's changes, or only those set where the command cleared them.
def command::environment(&this): result<vector<string>, io_error> {
var made := vector::<string>::new();
if !this._cleared {
for each in system::environment() {
var name_length := 0u;
while name_length < each.length && each[name_length] != '=' {
name_length++;
}
if this.setting_of(each.substr(0, name_length)) is some(_) {
continue;
}
made.append(string::from(each, nothing{}));
}
}
for &each in this._variables {
if each.name.length == 0 || contains(each.name.view(), '=') {
return io_error::invalid;
}
if each.value is some(&value) {
var text := string::copy_of(&each.name);
text.append("=");
text.append(value.view());
made.append(move(text));
}
}
return move(made);
}
# The path of the program to start: as given, where the name holds a `/`, and
# otherwise the first in the directories of the `PATH` the child will have that
# is a file anyone may run. Windows finds it as `found` says.
def command::find(&this): result<string, io_error> {
val name := this._program.view();
if name.length == 0 {
return io_error::invalid;
}
when os == windows {
return this.found(name);
}
if contains(name, '/') {
return string::from(name, nothing{});
}
val search := this.search_path();
for directory in search.split(':') {
var candidate := string::from(directory.length == 0 ? "." : directory, nothing{});
candidate.append("/");
candidate.append(name);
if this.runnable(candidate.view()) {
return move(candidate);
}
}
return io_error::not_found;
}
# The `PATH` the child will have, which is the command's own where it set one,
# and otherwise the program's.
def command::search_path(&this): strview {
if this.setting_of("PATH") is some(&set) && set.value is some(&value) {
return value.view();
}
return variable("PATH") else { return "/usr/local/bin:/usr/bin:/bin"; };
}
# Whether a path, from where the child runs, is a file anyone may run.
def command::runnable(&this, candidate: strview): bool {
var at := string::new(nothing{});
var rooted := candidate.starts_with("/");
when os == windows {
rooted = rooted || candidate.starts_with("\\") || (candidate.length > 1 && candidate[1] == ':');
}
if this._directory.length != 0 && !rooted {
at.append(this._directory.view());
at.append("/");
}
at.append(candidate);
var info: file_info;
return system::stat(at.view(), &mut info) == 0 && info.kind == file_kind::regular
&& (info.permissions & 0o111) != 0;
}
when os == windows {
# The path of the program to start, as Windows finds it: as given, where the
# name holds a `/` or `\`, or begins with a drive, and otherwise the first in
# the directories of the `PATH` the child will have that is a program. A name
# ending in none of the endings `PATHEXT` lists is tried with each in turn,
# where it is given as a path too, since the system adds none itself.
def command::found(&this, name: strview): result<string, io_error> {
val endings := this.endings();
val ended := this.has_ending(name, &endings);
if contains(name, '/') || contains(name, '\\') || (name.length > 1 && name[1] == ':') {
for ending in endings.split(';') {
if !ended && ending.length != 0 {
var candidate := string::from(name, nothing{});
candidate.append(ending);
if this.runnable(candidate.view()) {
return move(candidate);
}
}
}
return string::from(name, nothing{});
}
val search := this.directories();
for listed in search.split(';') {
# A directory may be written within quotes, as one holding a `;` must be.
var directory := listed.trim();
if directory.length >= 2 && directory[0] == '"' && directory[directory.length - 1] == '"' {
directory = directory.substr(1, directory.length - 2);
}
if directory.length == 0 {
continue;
}
var at := string::from(directory, nothing{});
if !directory.ends_with("\\") && !directory.ends_with("/") {
at.append("\\");
}
at.append(name);
if ended && this.runnable(at.view()) {
return move(at);
}
for ending in endings.split(';') {
if !ended && ending.length != 0 {
var candidate := string::copy_of(&at);
candidate.append(ending);
if this.runnable(candidate.view()) {
return move(candidate);
}
}
}
}
return io_error::not_found;
}
# The endings that make a name a program's, as the `PATHEXT` the child will
# have lists them, between `;`, or those the system's shell takes where it
# lists none.
def command::endings(&this): string {
if this.setting_of("PATHEXT") is some(&set) && set.value is some(&value) {
return string::copy_of(value);
}
val listed := variable("PATHEXT") else { return string::from(".COM;.EXE;.BAT;.CMD", nothing{}); };
return string::from(listed, nothing{});
}
# Whether a name ends in one of the endings, compared whatever their case.
def command::has_ending(&this, name: strview, endings: &string): bool {
for ending in endings.split(';') {
if ending.length != 0 && name.length > ending.length
&& same_name(name.substr(name.length - ending.length, ending.length), ending) {
return true;
}
}
return false;
}
# The directories the child will have in its `PATH`, which is the command's
# own where it set one, and otherwise the program's, or, where neither has
# one, those of the system, where the program has `SystemRoot`.
def command::directories(&this): string {
if this.setting_of("PATH") is some(&set) && set.value is some(&value) {
return string::copy_of(value);
}
if variable("PATH") is some(listed) {
return string::from(listed, nothing{});
}
val root := variable("SystemRoot") else { return string::new(nothing{}); };
var made := string::from(root, nothing{});
made.append("\\System32;");
made.append(root);
return made;
}
# Whether two names of variables are the same, as Windows has them: whatever
# the case of their letters.
def same_name(a: strview, b: strview): bool {
if a.length != b.length {
return false;
}
for i in 0..a.length {
if a[i].to_upper != b[i].to_upper {
return false;
}
}
return true;
}
}
else {
# Whether two names of variables are the same.
def same_name(a: strview, b: strview): bool {
return a == b;
}
}
# Whether text holds a byte.
def contains(text: strview, wanted: u8): bool {
for i in 0..text.length {
if text[i] == wanted {
return true;
}
}
return false;
}
+57
View File
@@ -0,0 +1,57 @@
#! @file version.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#!
module std::semver;
#! Represents a semantic version.
pub struct version {
pub var major: u32;
pub var minor: u32;
pub var patch: u32;
pub var preview: string;
pub var build: string;
}
pub struct version::error {
}
pub enum version::error_kind {
}
# pub def version::parse(
# verstr: strview,
# alloc: maybe<&mut allocator> = nothing{}
# ): result<version, version::error> {
# return version {
# major = version::parse_number(verstr) else (e) { return e; },
# minor = version::parse_number(verstr) else (e) { return e; },
# patch = version::parse_number(verstr) else (e) { return e; },
# preview = version::parse_preview(verstr, alloc) else (e) { return e; },
# build = version::parse_build(verstr, alloc) else (e) { return e; }
# };
# }
# def version::parse_number(
# verstr: &mut strview
# ): result<u32, version::error> {
# }
# def version::parse_preview(
# verstr: &mut strview,
# alloc: maybe<&mut allocator>
# ): result<string, version::error> {
# }
# def version::parse_build(
# verstr: &mut strview,
# alloc: maybe<&mut allocator>
# ): result<string, version::error> {
# }
+277
View File
@@ -0,0 +1,277 @@
#! @file serial.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what writing and reading values knows apart from any format: the
#! `@serial` attribute a program marks its types and fields with, the traits a
#! format implements to be written and read through, and the traits a type with a
#! form of its own implements. `serial::encode` and `serial::decode` walk a value
#! by what is marked, so JSON, and any other format, read the marks the same way.
module std::serial;
#! Marks a type to be written and read, and each of its fields, enum members,
#! and union fields that are. A field left unmarked is never written, and
#! reading leaves it at its default, or else its zero value.
#!
#! The marks are also what lets `serial::encode` and `serial::decode` see a type
#! private to the program, since reflection gives a module what carries an
#! attribute it declares. So a type is marked, and each field written, even
#! where it is `pub`.
@usage{ on = target::structs | target::unions | target::enums | target::fields | target::members }
pub struct serial : attribute {
pub val name: strview = ""; #! The name written in place of the declaration's, where it is not empty.
}
#! How strictly `serial::decode` reads.
pub struct options {
pub val strict: bool = false; #! Whether a member no field takes, and a member written twice, are errors.
}
#! The kinds of values every format writes and reads.
pub enum kind: u8 {
empty, #! Nothing: JSON's `null`.
boolean, #! `true` or `false`.
number, #! A number, integer or real.
text, #! Text.
array, #! A list of values, in order.
object, #! Members, each a name and a value.
}
#! Why a value could not be written or read, whatever the format.
pub enum error_kind: u8 {
wrong_kind, #! A value is of another kind than the type asked for, as text for a number.
missing_member, #! An object lacks a member for a field that is not a `maybe`.
unknown_member, #! An object has a member no field takes, which only strict reading refuses.
repeated_member, #! An object has a member twice, which only strict reading refuses.
out_of_range, #! A number does not fit the type asked for, or a name is no member's.
not_serial, #! A value holds an enum member or union field that is not `@serial`.
}
#! Where a value was read, from the start of the text it was read from.
pub struct place {
pub var offset: u64; #! The byte the value begins at.
pub var line: u32; #! Counted from 1.
pub var column: u32; #! The byte within the line, counted from 1.
}
#! Why a value could not be read or written, and where it was read.
#!
#! An error is plain data, so `else (e)` names it.
pub struct error {
pub var kind: error_kind; #! What went wrong.
pub var offset: u64; #! The byte the value that failed begins at.
pub var line: u32; #! Its line, counted from 1.
pub var column: u32; #! The byte within the line, counted from 1.
}
#! Makes an error of a kind, at a place.
#! @param kind The kind of error.
#! @param at Where the value that failed was read.
#! @returns The error.
pub def error::at(kind: error_kind, at: place): error {
return error { kind = kind, offset = at.offset, line = at.line, column = at.column };
}
#! Says what the error is, in a sentence, after where it is.
#! @param this The error to describe.
#! @returns The description, as `3:14: An object lacks a member a field needs.`
pub def error::describe(&this): string {
return $"{this.line}:{this.column}: {describe(this.kind)}";
}
#! Says what a kind of error is, in a sentence.
#! @param kind The kind to describe.
#! @returns The sentence.
pub def describe(kind: error_kind): strview {
return match kind {
wrong_kind => "The value is not of the kind the type asks for.",
missing_member => "An object lacks a member that a field needs.",
unknown_member => "An object has a member that no field takes.",
repeated_member => "An object has a member more than once.",
out_of_range => "The value does not fit the type asked for.",
not_serial => "The value holds an enum member or union field that is not `@serial`.",
};
}
#! What a format writes values through, as `json::writer` does.
#!
#! A format keeps the first failure in the data, such as a number it cannot
#! hold, or one `fail` reports, and gives it when it finishes, so each value
#! needs no check. Misuse, such as ending an array where an object is open, is
#! the program's mistake and stops it.
pub trait encoder {
#! Begins an object, whose members are each written as `member` and then a
#! value.
#! @param this The format to write through.
#! @param count How many members it has, which a format writing their count
#! ahead uses.
def begin_object(&mut this, count: u64): void;
#! Writes the name of the member whose value is written next.
#! @param this The format to write through.
#! @param name The member's name.
def member(&mut this, name: strview): void;
#! Ends the object begun last.
#! @param this The format to write through.
def end_object(&mut this): void;
#! Begins an array, whose elements are each written as a value.
#! @param this The format to write through.
#! @param count How many elements it has, which a format writing their count
#! ahead uses.
def begin_array(&mut this, count: u64): void;
#! Ends the array begun last.
#! @param this The format to write through.
def end_array(&mut this): void;
#! Writes text as a value.
#! @param this The format to write through.
#! @param value The text, as UTF-8.
def text(&mut this, value: strview): void;
#! Writes a signed integer as a value.
#! @param this The format to write through.
#! @param value The integer.
def signed(&mut this, value: i64): void;
#! Writes an unsigned integer as a value.
#! @param this The format to write through.
#! @param value The integer.
def unsigned(&mut this, value: u64): void;
#! Writes a real number as a value.
#! @param this The format to write through.
#! @param value The number, which a format that holds no infinity or NaN
#! keeps as a failure.
def real(&mut this, value: f64): void;
#! Writes `true` or `false` as a value.
#! @param this The format to write through.
#! @param value The value.
def boolean(&mut this, value: bool): void;
#! Writes nothing as a value: JSON's `null`.
#! @param this The format to write through.
def empty(&mut this): void;
#! Keeps a failure the walk finds, where the format keeps its own, so it is
#! given when the format finishes.
#! @param this The format to write through.
#! @param kind What went wrong.
def fail(&mut this, kind: error_kind): void;
}
#! A document a format has read, as `json::document` is, whose values are known
#! by their indices in it. It names no `self`, so a form of a type's own takes
#! it as a `&decoder`.
pub trait decoder {
#! The kind of a value.
#! @param this The document to read.
#! @param at The index of the value.
#! @returns Its kind.
def kind_of(&this, at: u32): kind;
#! Finds the first member of an object by its name.
#! @param this The document to read.
#! @param at The index of the object.
#! @param name The name to look for.
#! @returns The index of its value, or `nothing` where the object has no
#! member of the name.
def member(&this, at: u32, name: strview): maybe<u32>;
#! How many members an object has, repeats included, or how many elements an
#! array has.
#! @param this The document to read.
#! @param at The index of the object or array.
#! @returns The count, which is zero for any other kind.
def count(&this, at: u32): u64;
#! An element of an array, or the value of a member of an object, by its
#! position.
#! @param this The document to read.
#! @param at The index of the array or object.
#! @param index Its position, below `count`.
#! @returns The index of the value.
def element(&this, at: u32, index: u64): u32;
#! The element of an array, or the value of a member of an object, after
#! another, so walking them in order counts none from the first.
#! @param this The document to read.
#! @param at The index of the array or object.
#! @param previous The index of the value before it.
#! @returns The index of the value after it.
def next_element(&this, at: u32, previous: u32): u32;
#! The name of the member of an object whose value is given.
#! @param this The document to read.
#! @param value The index of the member's value.
#! @returns The member's name, decoded.
def name_of(&this, value: u32): strview;
#! Reads a value as text.
#! @param this The document to read.
#! @param at The index of the value.
#! @returns The text, decoded, or `wrong_kind` where the value is not text.
def as_text(&this, at: u32): result<strview, error>;
#! Reads a value as a signed integer.
#! @param this The document to read.
#! @param at The index of the value.
#! @returns The integer, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is not an integer `i64` holds.
def as_i64(&this, at: u32): result<i64, error>;
#! Reads a value as an unsigned integer.
#! @param this The document to read.
#! @param at The index of the value.
#! @returns The integer, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is not an integer `u64` holds.
def as_u64(&this, at: u32): result<u64, error>;
#! Reads a value as a real number.
#! @param this The document to read.
#! @param at The index of the value.
#! @returns The number, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is too large for an `f64`.
def as_f64(&this, at: u32): result<f64, error>;
#! Reads a value as `true` or `false`.
#! @param this The document to read.
#! @param at The index of the value.
#! @returns The value, or `wrong_kind` where it is not a boolean.
def as_bool(&this, at: u32): result<bool, error>;
#! Where a value was read, for an error about it.
#! @param this The document to read.
#! @param at The index of the value.
#! @returns Its place in the text.
def place(&this, at: u32): place;
}
#! A type that writes itself, in place of what `serial::encode` would write of
#! it. It writes what it holds through `serial::encode`, so its parts are
#! written by their own forms.
pub trait encodable {
#! Writes the value through a format.
#! @param this The value to write.
#! @param out The format to write through.
def encode(&this, out: &mut encoder): void;
}
#! A type that reads itself, in place of what `serial::decode` would read into
#! it. It reads what it holds through `serial::decode`, giving it the options it
#! is given, so its parts are read by their own forms, as strictly.
pub trait decodable {
#! Reads a value of the type from a document.
#! @param from The document to read.
#! @param at The index of the value in it.
#! @param given How strictly to read, which the value's parts are read with
#! too.
#! @returns The value, or why it could not be read.
def decode(from: &decoder, at: u32, given: options): result<self, error>;
}
+251
View File
@@ -0,0 +1,251 @@
#! @file text.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what reading and writing text formats share, whatever the format:
#! checking and appending UTF-8, reading a number's text as an integer exactly, and
#! finding where a byte of the text is by its line and column.
import core::swar;
module std::serial;
# The most an exponent is read as, past which a number is zero or too large for
# any type anyway.
const exponent_limit: u64 = 100000;
#! Whether text is UTF-8: no overlong forms, no surrogates, nothing past
#! U+10FFFF, and nothing cut short.
#! @param text The text to check.
#! @returns Whether it is UTF-8.
pub def is_utf8(text: strview): bool {
val data := text.data;
var at: u64 = 0;
while at < text.length {
if text[at] < 0x80 {
# ASCII, which is passed a word at a time to the next byte past it.
at++;
while at + 8 <= text.length {
val wide: swar::mask8 = swar::load(data + at) & 0x8080808080808080;
if wide.any() {
at += wide.first();
break;
}
at += 8;
}
continue;
}
val count := utf8_length(text, at);
if count == 0 {
return false;
}
at += count;
}
return true;
}
#! The length of the UTF-8 sequence beginning at a byte, or 0 where the bytes
#! there are not one: overlong, a surrogate, past U+10FFFF, or cut short.
#! @param text The text to read.
#! @param at Where the sequence begins, which must be within the text.
#! @returns How many bytes it takes, from 1 to 4, or 0.
pub def utf8_length(text: strview, at: u64): u64 {
val lead := text[at];
if lead < 0x80 {
return 1;
}
# The second byte is narrowed where the lead alone would allow an overlong form, a
# surrogate, or a character past U+10FFFF.
var count: u64 = 0;
var low: u8 = 0x80;
var high: u8 = 0xBF;
if lead >= 0xC2 && lead <= 0xDF {
count = 2;
} else if lead == 0xE0 {
count = 3;
low = 0xA0;
} else if lead == 0xED {
count = 3;
high = 0x9F;
} else if lead >= 0xE1 && lead <= 0xEF {
count = 3;
} else if lead == 0xF0 {
count = 4;
low = 0x90;
} else if lead == 0xF4 {
count = 4;
high = 0x8F;
} else if lead >= 0xF1 && lead <= 0xF3 {
count = 4;
} else {
return 0;
}
if at + count > text.length || text[at + 1] < low || text[at + 1] > high {
return 0;
}
for index in 2..count {
val byte := text[at + index];
if byte < 0x80 || byte > 0xBF {
return 0;
}
}
return count;
}
#! Where a byte of the text is, by its line and its column, counting a line
#! break as `\n`, `\r\n`, or a `\r` alone.
#! @param text The text the byte is in.
#! @param offset The byte, which is at most the text's length.
#! @returns Where it is: its line counted from 1, and its column, the byte
#! within the line, counted from 1.
pub def place_of(text: strview, offset: u64): place {
var line: u32 = 1;
var begun: u64 = 0;
val end := offset < text.length ? offset : text.length;
for index in 0..end {
val byte := text[index];
if byte == '\n' || (byte == '\r' && (index + 1 >= text.length || text[index + 1] != '\n')) {
line++;
begun = index + 1;
}
}
return place { offset = offset, line = line, column = (offset - begun + 1) as u32 };
}
# Where a run of decimal digits beginning at `at` ends.
def digits_end(text: strview, at: u64): u64 {
var index := at;
while index < text.length && text[index].is_digit {
index++;
}
return index;
}
#! What a number's text is as an integer: its magnitude and sign, and whether it
#! is one and fits in 64 bits.
pub struct integral {
pub var magnitude: u64; #! The integer's magnitude, where it fits.
pub var negative: bool; #! Whether it is below zero.
pub var whole: bool; #! Whether it has no fraction, as `1.50` has and `1.5e1` has not.
pub var fits: bool; #! Whether its magnitude fits in 64 bits.
}
#! Reads a decimal number's text as an integer exactly, as
#! `[-+]?[0-9]*(\.[0-9]*)?([eE][-+]?[0-9]+)?` writes it, so `1.5e1` is 15.
#! @param text The number's text, which follows that grammar and holds a
#! digit.
#! @returns Its magnitude and sign, whether it is whole, and whether it fits.
pub def integral_of(text: strview): integral {
var made := integral { whole = true, fits = true };
var at: u64 = 0;
if text[0] == '-' || text[0] == '+' {
made.negative = text[0] == '-';
at = 1;
}
# The digits, with where the fraction among them begins, and the exponent.
val start := at;
at = digits_end(text, at);
val integers := at - start;
var fraction := at;
var fractions: u64 = 0;
if at < text.length && text[at] == '.' {
fraction = at + 1;
at = digits_end(text, fraction);
fractions = at - fraction;
}
var exponent: u64 = 0;
var lowered: bool = false;
if at < text.length {
at++;
if text[at] == '+' || text[at] == '-' {
lowered = text[at] == '-';
at++;
}
while at < text.length {
exponent = exponent * 10 + text[at].digit_value;
if exponent > exponent_limit {
exponent = exponent_limit;
}
at++;
}
}
# The value is the digits times ten to the exponent, less one for each digit of
# the fraction, so that many digits from the end are the fraction where it is
# negative, and that many zeros follow where it is not.
var kept := integers + fractions;
var shift: u64 = 0;
if lowered || exponent < fractions {
val dropped := lowered ? exponent + fractions : fractions - exponent;
if dropped > kept {
made.whole = !any_but_zero(text, start, integers, fraction, fractions, 0, kept);
return made;
}
made.whole = !any_but_zero(text, start, integers, fraction, fractions, kept - dropped, kept);
kept -= dropped;
} else {
shift = exponent - fractions;
}
for index in 0..kept {
val digit := digit_at(text, start, integers, fraction, index);
if made.magnitude > (0xFFFFFFFFFFFFFFFFu - digit) / 10 {
made.fits = false;
return made;
}
made.magnitude = made.magnitude * 10 + digit;
}
if made.magnitude == 0 {
return made;
}
for _ in 0..shift {
if made.magnitude > 0xFFFFFFFFFFFFFFFFu / 10 {
made.fits = false;
return made;
}
made.magnitude *= 10;
}
return made;
}
# The digit at an index among a number's digits, those of its integer part then
# those of its fraction.
def digit_at(text: strview, start: u64, integers: u64, fraction: u64, index: u64): u64 {
return index < integers ? text[start + index].digit_value : text[fraction + index - integers].digit_value;
}
# Whether any digit from `from` to `to` among a number's digits is not zero.
def any_but_zero(text: strview, start: u64, integers: u64, fraction: u64, fractions: u64, from: u64, to: u64): bool {
for index in from..to {
if digit_at(text, start, integers, fraction, index) != 0 {
return true;
}
}
return false;
}
#! Appends a character as UTF-8.
#! @param code The character, which must be no more than U+10FFFF.
#! @param into The string to append to.
pub def append_utf8(code: u64, into: &mut string): void {
if code < 0x80 {
into.push(code as u8);
} else if code < 0x800 {
into.push((0xC0 | (code >> 6)) as u8);
into.push((0x80 | (code & 0x3F)) as u8);
} else if code < 0x10000 {
into.push((0xE0 | (code >> 12)) as u8);
into.push((0x80 | ((code >> 6) & 0x3F)) as u8);
into.push((0x80 | (code & 0x3F)) as u8);
} else {
into.push((0xF0 | (code >> 18)) as u8);
into.push((0x80 | ((code >> 12) & 0x3F)) as u8);
into.push((0x80 | ((code >> 6) & 0x3F)) as u8);
into.push((0x80 | (code & 0x3F)) as u8);
}
}
+428
View File
@@ -0,0 +1,428 @@
#! @file walk.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `serial::encode` and `serial::decode`, which walk a value by what
#! `@serial` marks of its type, and the forms of the types std gives: numbers,
#! `bool`, strings, views, `maybe`, vectors, sets, and dictionaries keyed by
#! text.
import std::containers;
module std::serial;
# A type whose value is left out where it is missing, as `maybe` is, rather than
# the missing member being an error.
trait vacant {
def vacant(): self;
}
# A key read from a member's name, as a dictionary's `string` keys are.
trait named {
def from(text: strview, alloc: maybe<&mut allocator>): self;
}
#! Writes a value through a format.
#!
#! A type of its own form, one implementing `encodable`, writes itself, as std's
#! numbers, strings, and containers do. Otherwise the type must be `@serial`:
#! - a struct is written as an object of its marked fields, named as they are or
#! by the `name` of their marks;
#! - an enum as the name of its member, which must be marked;
#! - a union as an object of one member, the marked field it holds.
#! A value holding an unmarked member or field is written as nothing, and the
#! format keeps `not_serial` as its failure.
#! @tparam T The type of the value.
#! @param value The value to write.
#! @param out The format to write it through.
pub def encode<T>(value: &T, out: &mut encoder): void {
if const T is encodable {
value.encode(out);
return;
}
if const attached::<serial>(decl_of::<T>()).length == 0 {
compile_error("The type is not `@serial`, so it is not written. Mark it, and each field to write, with `@serial`.");
}
if const decl_of::<T>().kind == target::enums {
for const member in members_of(decl_of::<T>()) {
if const member.kind == target::members && attached::<serial>(member).length > 0 {
if value == value_of(member) {
out.text(attached::<serial>(member)[0].name.length > 0 ? attached::<serial>(member)[0].name : member.name);
return;
}
}
}
out.fail(error_kind::not_serial);
out.empty();
return;
}
if const decl_of::<T>().kind == target::unions {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
if value is (field) {
out.begin_object(1);
out.member(attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name);
encode(&value.(field), out);
out.end_object();
return;
}
}
}
out.fail(error_kind::not_serial);
out.empty();
return;
}
var count: u64 = 0;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
count++;
}
}
out.begin_object(count);
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
out.member(attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name);
encode(&value.(field), out);
}
}
out.end_object();
}
#! Reads a value a format has read.
#!
#! A type of its own form, one implementing `decodable`, reads itself, as std's
#! numbers, strings, and containers do. Otherwise the type must be `@serial`,
#! and is read as `encode` writes it. A struct starts at its zero value, with
#! its fields at their defaults, and each marked field is read from its member,
#! so a field left unmarked keeps its default.
#!
#! A member missing for a marked field is a `missing_member` error, unless the
#! field is a `maybe`, which is then `none`. A member no field takes is ignored,
#! and so is a member written again after its first, unless the options are
#! strict.
#! @tparam T The type to read, which is `zeroable`, so a field left unread
#! has a value.
#! @param from The document the format read.
#! @param at The value to read, by its index in the document.
#! @param given How strictly to read.
#! @returns The value, or why it could not be read, at the value that failed.
pub def decode<T>(from: &decoder, at: u32, given: options = options {}): result<T, error> where T: zeroable {
if const T is decodable {
return T::decode(from, at, given);
}
if const attached::<serial>(decl_of::<T>()).length == 0 {
compile_error("The type is not `@serial`, so it is not read. Mark it, and each field to read, with `@serial`.");
}
if const decl_of::<T>().kind == target::enums {
val written := from.as_text(at) else (e) { return e; };
for const member in members_of(decl_of::<T>()) {
if const member.kind == target::members && attached::<serial>(member).length > 0 {
val name: strview = attached::<serial>(member)[0].name.length > 0 ? attached::<serial>(member)[0].name : member.name;
if written == name {
return value_of(member);
}
}
}
return error::at(error_kind::out_of_range, from.place(at));
}
if const decl_of::<T>().kind == target::unions {
if from.kind_of(at) != kind::object || from.count(at) != 1 {
return error::at(error_kind::wrong_kind, from.place(at));
}
val inner := from.element(at, 0);
val written := from.name_of(inner);
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
val name: strview = attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name;
if written == name {
var read := decode::<type_of(field)>(from, inner, given) else (e) { return e; };
var made: T;
made.(field) = move(read);
return move(made);
}
}
}
return error::at(error_kind::out_of_range, from.place(inner));
}
if from.kind_of(at) != kind::object {
return error::at(error_kind::wrong_kind, from.place(at));
}
var made: T;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
val name: strview = attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name;
if from.member(at, name) is some(found) {
var read := decode::<type_of(field)>(from, found, given) else (e) { return e; };
made.(field) = move(read);
} else {
if const !(type_of(field) is vacant) {
return error::at(error_kind::missing_member, from.place(at));
}
}
}
}
# Strictly, every member is one a field takes, and is the first of its name.
if given.strict {
var item: u32 = 0;
for index in 0..from.count(at) {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
val written := from.name_of(item);
var known := false;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
val name: strview = attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name;
known = known || written == name;
}
}
if !known {
return error::at(error_kind::unknown_member, from.place(item));
}
val first := from.member(at, written) else { continue; };
if first != item {
return error::at(error_kind::repeated_member, from.place(item));
}
}
}
return move(made);
}
def i8::encode(&this, out: &mut encoder): void { out.signed(this as i64); }
def i16::encode(&this, out: &mut encoder): void { out.signed(this as i64); }
def i32::encode(&this, out: &mut encoder): void { out.signed(this as i64); }
def i64::encode(&this, out: &mut encoder): void { out.signed(this); }
def u8::encode(&this, out: &mut encoder): void { out.unsigned(this as u64); }
def u16::encode(&this, out: &mut encoder): void { out.unsigned(this as u64); }
def u32::encode(&this, out: &mut encoder): void { out.unsigned(this as u64); }
def u64::encode(&this, out: &mut encoder): void { out.unsigned(this); }
def f32::encode(&this, out: &mut encoder): void { out.real(this as f64); }
def f64::encode(&this, out: &mut encoder): void { out.real(this); }
def bool::encode(&this, out: &mut encoder): void { out.boolean(this); }
def i8::decode(from: &decoder, at: u32, given: options): result<i8, error> {
val read := signed_within(from, at, -128, 127) else (e) { return e; };
return read as i8;
}
def i16::decode(from: &decoder, at: u32, given: options): result<i16, error> {
val read := signed_within(from, at, -32768, 32767) else (e) { return e; };
return read as i16;
}
def i32::decode(from: &decoder, at: u32, given: options): result<i32, error> {
val read := signed_within(from, at, -2147483648, 2147483647) else (e) { return e; };
return read as i32;
}
def i64::decode(from: &decoder, at: u32, given: options): result<i64, error> {
return from.as_i64(at);
}
def u8::decode(from: &decoder, at: u32, given: options): result<u8, error> {
val read := unsigned_within(from, at, 255) else (e) { return e; };
return read as u8;
}
def u16::decode(from: &decoder, at: u32, given: options): result<u16, error> {
val read := unsigned_within(from, at, 65535) else (e) { return e; };
return read as u16;
}
def u32::decode(from: &decoder, at: u32, given: options): result<u32, error> {
val read := unsigned_within(from, at, 4294967295) else (e) { return e; };
return read as u32;
}
def u64::decode(from: &decoder, at: u32, given: options): result<u64, error> {
return from.as_u64(at);
}
def f32::decode(from: &decoder, at: u32, given: options): result<f32, error> {
val read := from.as_f64(at) else (e) { return e; };
if read > 3.4028234663852886e38 || read < -3.4028234663852886e38 {
return error::at(error_kind::out_of_range, from.place(at));
}
return read as f32;
}
def f64::decode(from: &decoder, at: u32, given: options): result<f64, error> {
return from.as_f64(at);
}
def bool::decode(from: &decoder, at: u32, given: options): result<bool, error> {
return from.as_bool(at);
}
def string::encode(&this, out: &mut encoder): void {
out.text(this.view());
}
def string::decode(from: &decoder, at: u32, given: options): result<string, error> {
val read := from.as_text(at) else (e) { return e; };
return string::from(read, nothing {});
}
# A view of one-byte integers is text, and any other view an array, since a view of
# text cannot be told apart from one of bytes by its type.
def span<T>::encode(&this, out: &mut encoder): void {
if const size_of::<T>() == 1 && T is integer {
out.text(strview::over(this.data as *u8, this.length));
return;
}
out.begin_array(this.length);
for &item in this {
encode(item, out);
}
out.end_array();
}
def maybe<T>::encode(&this, out: &mut encoder): void {
match this {
some(&held) => encode(held, out);
none => out.empty();
}
}
def maybe<T>::decode(from: &decoder, at: u32, given: options): result<maybe<T>, error> {
if const !(T is zeroable) {
compile_error("What a `maybe` holds is read from its zero value, so it is `zeroable`.");
}
if from.kind_of(at) == kind::empty {
return maybe::<T>::vacant();
}
var read := decode::<T>(from, at, given) else (e) { return e; };
var made: maybe<T> = move(read);
return move(made);
}
def maybe<T>::vacant(): maybe<T> {
return nothing {};
}
def vector<T>::encode(&this, out: &mut encoder): void {
out.begin_array(this.length);
for &item in this {
encode(item, out);
}
out.end_array();
}
def vector<T>::decode(from: &decoder, at: u32, given: options): result<vector<T>, error> {
if const !(T is zeroable) {
compile_error("A vector's elements are each read from their zero value, so they are `zeroable`.");
}
if from.kind_of(at) != kind::array {
return error::at(error_kind::wrong_kind, from.place(at));
}
val count := from.count(at);
var made := vector::<T>::new(count, nothing {});
var item: u32 = 0;
for index in 0..count {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
var read := decode::<T>(from, item, given) else (e) { return e; };
made.append(move(read));
}
return move(made);
}
# A dictionary is an object, so its keys are text.
def dict<K, V>::encode(&this, out: &mut encoder): void {
if const !(K is viewable<u8>) {
compile_error("A dictionary is written as an object, whose members are named, so its keys are text.");
}
out.begin_object(this.length);
for &entry in this {
out.member(entry.key.view());
encode(&entry.value, out);
}
out.end_object();
}
def dict<K, V>::decode(from: &decoder, at: u32, given: options): result<dict<K, V>, error> {
if const !(K is named) {
compile_error("A dictionary is read from an object, whose members are named, so its keys are `string`s.");
}
if const !(V is zeroable) {
compile_error("A dictionary's values are each read from their zero value, so they are `zeroable`.");
}
if from.kind_of(at) != kind::object {
return error::at(error_kind::wrong_kind, from.place(at));
}
# A member written again is read from its first, as a struct's is.
val count := from.count(at);
var made := dict::<K, V>::new(count, nothing {});
var item: u32 = 0;
for index in 0..count {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
var key := K::from(from.name_of(item), nothing {});
if made.get(&key) is some(_) {
if given.strict {
return error::at(error_kind::repeated_member, from.place(item));
}
continue;
}
var read := decode::<V>(from, item, given) else (e) { return e; };
made.set(move(key), move(read));
}
return move(made);
}
# A set is an array of its values, in no particular order.
def hashset<T>::encode(&this, out: &mut encoder): void {
out.begin_array(this.length);
for &item in this {
encode(item, out);
}
out.end_array();
}
# A value written twice is held once, as a set holds every value.
def hashset<T>::decode(from: &decoder, at: u32, given: options): result<hashset<T>, error> {
if const !(T is zeroable) {
compile_error("A set's values are each read from their zero value, so they are `zeroable`.");
}
if from.kind_of(at) != kind::array {
return error::at(error_kind::wrong_kind, from.place(at));
}
val count := from.count(at);
var made := hashset::<T>::new(count, nothing {});
var item: u32 = 0;
for index in 0..count {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
var read := decode::<T>(from, item, given) else (e) { return e; };
made.insert(move(read));
}
return move(made);
}
# A signed integer read exactly, within bounds.
def signed_within(from: &decoder, at: u32, low: i64, high: i64): result<i64, error> {
val read := from.as_i64(at) else (e) { return e; };
if read < low || read > high {
return error::at(error_kind::out_of_range, from.place(at));
}
return read;
}
# An unsigned integer read exactly, within a bound.
def unsigned_within(from: &decoder, at: u32, high: u64): result<u64, error> {
val read := from.as_u64(at) else (e) { return e; };
if read > high {
return error::at(error_kind::out_of_range, from.place(at));
}
return read;
}
+312
View File
@@ -0,0 +1,312 @@
#! @file testing.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the test runner: the `test` attribute marking what it runs, the
#! `fixture` trait for what a test is given ready, and the `tester` a test
#! checks with, whose `run` runs every test of the program, each in a copy of
#! the program of its own.
import std::io;
import system;
module std::testing;
#! Marks a function, or a constant holding one, as a test that `tester::run`
#! runs.
#!
#! A test is a `def(t: &mut tester): void`. It may also take a fixture after the
#! tester, as `def(t: &mut tester, dir: temp_dir): void`, which the runner sets
#! up for it and which closes where the test returns. A generic test is marked
#! through a constant holding an instance, as `@test const sorts_i64 :=
#! sorts::<i64>;`.
@usage{ on = target::functions | target::constants }
pub struct test : attribute {
#! What the report calls the test, which is its path when this is empty.
pub val name: strview = "";
#! Whether the test is left out, which the report counts.
pub val skip: bool = false;
}
#! What a test is given ready, as its parameter after the tester.
#!
#! The runner makes it with `setup` before the test runs, and a fixture that is
#! `owning` is closed where the test returns, however it returns.
#! @tparam T The type of the fixture, which is the type implementing it.
pub trait fixture<T> {
#! Makes the fixture, before the test taking it runs.
#! @param t The tester of the test, which a fixture that cannot be made
#! checks with.
#! @returns The fixture.
def setup(t: &mut tester): T;
}
#! What a test checks with, which counts what it checked and what failed.
pub struct tester {
pub val name: strview; #! What the report calls the test.
pub var checks: u64; #! How many checks it has made.
pub var failed: u64; #! How many of those failed.
}
#! Checks a condition, reporting it with where it is written and the values its
#! operands held when it does not hold, and going on either way.
#!
#! It gives whether the condition held, so a check that the rest of the test
#! needs is a guard: `if !t.expects(p != null) { return; }`.
#! @param this The tester of the test, which counts the check.
#! @param cond The condition to check.
#! @param text The condition as it is written, which the compiler fills in.
#! @param got What its operands held, which the compiler fills in.
#! @param at Where it is written, which the compiler fills in.
#! @returns Whether the condition held.
pub def tester::expects(
&mut this,
cond: bool,
text: strview = source_of(cond),
got: string = cond ? string::new(nothing {}) : values_of(cond),
at: site = call_site()
): bool {
this.checks++;
return true if cond;
this.failed++;
val held := got.view();
val why := held.length != 0 ? $" with {held}" : "";
println($" {at.path}({at.line}:{at.column}): \"{text}\"{why}");
return false;
}
#! Makes the fixture a test takes, which the runner does before the test runs.
#! @tparam F The type of the fixture.
#! @param t The tester of the test.
#! @returns The fixture, which `setup` made.
pub def tester::prepare<F>(t: &mut tester): F where F: fixture<F> {
return F::setup(t);
}
#! Runs every test of the program, one after another, each in a copy of the
#! program of its own, so that one that faults, as by indexing past the end of
#! an array, fails alone and the rest still run. Each is reported as it
#! finishes, then how many passed, failed, and were skipped.
#!
#! The arguments may say `--only TEXT`, which runs the tests whose name holds
#! the text, and `--here`, which runs them in this program rather than in copies
#! of it, as a debugger wants, so the first fault stops them all.
#!
#! Windows cannot copy a program as it runs, so there each copy is the program
#! started again, with the same command line, and with `SAKURA_TEST_ONE` naming
#! the test it runs, which it runs alone, reporting nothing, then stops. What the
#! program does before calling this, each copy does again.
#! @param args The arguments the program was given.
#! @returns The status to stop with: zero when no test failed.
pub def tester::run(args: span<strview>): i32 {
var tally := tester::tally { only = "", here = false };
tally.read(args);
when os == windows {
alone = alone_named();
}
for const d in declarations() {
if const attached::<test>(d).length == 0 { continue; }
if const d.generic {
compile_error(
"""
A test is not generic; mark a constant holding an instance, as
`@test const sorts_i64 := sorts::<i64>;`.
""",
d.at
);
}
val marked := attached::<test>(d)[0];
val name := marked.name.length != 0 ? marked.name : d.path;
continue if !tally.wants(name);
if marked.skip {
tally.skip(name);
continue;
}
tally.begin(name);
val child := tally.here ? 0 : copy_running(name);
if child < 0 {
tally.ended(name, false, "a copy of the program could not be started");
continue;
}
if child == 0 {
var t := tester { name = name };
if const value_of(d) is def(&mut tester): void {
value_of(d)(&mut t);
}
else if const d.kind == target::functions && params_of(d).length == 2 {
if const !(value_of(d) is def(&mut tester, type_of(params_of(d)[1])): void) {
compile_error("A test takes the tester first, as `def(t: &mut tester, f: F): void`.", d.at);
}
if const type_of(params_of(d)[1]) is not fixture<type_of(params_of(d)[1])> {
compile_error("What a test takes after the tester is a fixture, which implements `fixture<F>`.", d.at);
}
value_of(d)(&mut t, tester::prepare::<type_of(params_of(d)[1])>(&mut t));
}
else {
compile_error("A test is a `def(t: &mut tester): void`, or also takes a fixture after the tester.", d.at);
}
if !tally.here {
exit(t.failed == 0 ? 0 : 1);
}
tally.ended(name, t.failed == 0, "");
continue;
}
tally.waited(name, child);
}
return tally.finish();
}
# What the runner counts and was asked, and how it reports each test.
struct tester::tally {
val only: strview;
val here: bool;
var passed: u64;
var failed: u64;
var skipped: u64;
}
def tester::tally::read(&mut this, args: span<strview>): void {
for i in 0..args.length {
if args[i] == "--here" {
this = tester::tally { only = this.only, here = true };
}
else if args[i] == "--only" && i + 1 < args.length {
this = tester::tally { only = args[i + 1], here = this.here };
}
}
}
# Whether a test's name holds the text `--only` asked for, which every name holds
# when it asked for none. A copy of the program on Windows wants only the test
# it runs.
def tester::tally::wants(&this, name: strview): bool {
when os == windows {
if alone.length != 0 {
return name == alone;
}
}
if this.only.length == 0 {
return true;
}
if this.only.length > name.length {
return false;
}
for at in 0..name.length - this.only.length + 1 {
var same := true;
for i in 0..this.only.length {
if name[at + i] != this.only[i] {
same = false;
break;
}
}
if same {
return true;
}
}
return false;
}
def tester::tally::begin(&this, name: strview): void {
when os == windows {
return if alone.length != 0;
}
println($"[ RUN ] {name}");
}
def tester::tally::skip(&mut this, name: strview): void {
this.skipped++;
println($"[ SKIP ] {name}");
}
def tester::tally::ended(&mut this, name: strview, passed: bool, why: strview): void {
if passed {
this.passed++;
println($"[ OK ] {name}");
return;
}
this.failed++;
if why.length == 0 {
println($"[ FAIL ] {name}");
return;
}
println($"[ FAIL ] {name}: {why}");
}
# Waits for the copy running a test, which passed when it exited with zero.
def tester::tally::waited(&mut this, name: strview, child: i64): void {
var status: process_status;
var result := wait(child, &mut status);
while result < 0 && error_of(result) == io_error::interrupted {
result = wait(child, &mut status);
}
if result < 0 {
this.ended(name, false, "the copy running it could not be waited for");
return;
}
if !status.exited {
this.ended(name, false, $"stopped by signal {status.signal}".view());
return;
}
if status.code == 0 {
this.ended(name, true, "");
return;
}
this.ended(name, false, status.code == 1 ? "" : $"exited with {status.code}".view());
}
def tester::tally::finish(&this): i32 {
# A copy of the program on Windows stops as its test ends, so one that gets
# here found no test of the name it was given.
when os == windows {
if alone.length != 0 {
fd::stderr.put($"no test is named `{alone}`\n");
return 2;
}
}
println($"{this.passed} passed, {this.failed} failed, {this.skipped} skipped");
return this.failed == 0 ? 0 : 1;
}
when os == windows {
# The variable naming the test a copy of the program runs alone.
val alone_variable: strview = "SAKURA_TEST_ONE";
# The test this program runs alone, where it is a copy of the program started
# for it, or nothing.
var alone: strview;
# The test the variable names, or nothing where the program has none.
def alone_named(): strview {
for each in environment() {
if each.length > alone_variable.length && each[alone_variable.length] == '='
&& each.starts_with(alone_variable) {
return each.substr(alone_variable.length + 1, each.length - alone_variable.length - 1);
}
}
return "";
}
# Starts the copy of the program a test runs in, giving its number, or zero
# in a copy, which runs its test itself.
def copy_running(name: strview): i64 {
if alone.length != 0 {
return 0;
}
return respawn($"{alone_variable}={name}".view(), fd::stdin, fd::stdout, fd::stderr);
}
}
else {
# Starts the copy of the program a test runs in, giving its number, or zero
# in the copy.
def copy_running(name: strview): i64 {
return fork();
}
}
+221
View File
@@ -0,0 +1,221 @@
# Tests of the allocators: an arena hands out blocks one after another, grows the
# last where it is, and frees them all at once, by reset, rewind, or close; the
# containers keep their memory in one; and nodes linked by reference live in one.
# A pool hands out blocks of one size, those given back first, makes and unmakes
# values in them, and holds a list's nodes.
import std::allocators;
import std::containers;
import std::testing;
@test def arenas_hand_out_blocks_one_after_another(t: &mut tester): void {
var a := arena::new(1024);
val first := a.acquire(10, 1);
val second := a.acquire(10, 1);
val third := a.acquire(8, 8);
t.expects(second == first + 10 && third == first + 24 && (third as u64) % 8 == 0);
# A block too large for what is left of a chunk starts another, and one larger
# than a chunk has a chunk of its own.
val big := a.acquire(5000, 16);
t.expects(big != null && (big as u64) % 16 == 0);
for i in 0..5000u { big[i] = (i % 251) as u8; }
val after := a.acquire(16, 16);
t.expects(after != null && big[4999] == (4999 % 251) as u8);
}
@test def arenas_grow_and_give_back_the_last_block_where_it_is(t: &mut tester): void {
var a := arena::new(1024);
val block := a.acquire(16, 8);
block[0] = 7;
val grown := a.resize(block, 16, 64, 8);
t.expects(grown == block && grown[0] == 7);
# A block that is not the last is copied.
val other := a.acquire(16, 8);
val moved := a.resize(grown, 64, 128, 8);
t.expects(moved != grown && moved[0] == 7);
# The last block given back is where the next begins.
a.dispose(moved, 128);
t.expects(a.acquire(32, 8) == moved);
a.dispose(other, 16);
t.expects(a.acquire(8, 8) != other);
}
@test def arenas_free_what_they_handed_out_by_reset_and_rewind(t: &mut tester): void {
var a := arena::new(512);
val first := a.acquire(100, 16);
for _ in 0..20u { a.acquire(100, 16); }
a.reset();
t.expects(a.acquire(100, 16) == first);
val point := a.mark();
val kept := a.acquire(64, 16);
for _ in 0..20u { a.acquire(200, 16); }
a.rewind(point);
t.expects(a.acquire(64, 16) == kept);
}
@test def arenas_over_a_buffer_hand_it_out_first(t: &mut tester): void {
var bytes: u8[1024];
var a := arena::over(bytes[:]);
val low := (&bytes) as *u8 as u64;
val made := a.acquire(100, 8) as u64;
t.expects(made >= low && made + 100 <= low + 1024);
# Once it is full, blocks come from the heap.
val more := a.acquire(2000, 8) as u64;
t.expects(more + 2000 <= low || more >= low + 1024);
}
@test def containers_keep_their_memory_in_an_arena(t: &mut tester): void {
var a := arena::new();
val alloc: maybe<&mut allocator> = &mut a;
var numbers := vector::<u64>::new(alloc);
for i in 0..1000u { numbers.append(i * 3); }
var total: u64 = 0;
for &n in numbers { total += n; }
t.expects(numbers.length == 1000 && total == 1498500);
var names := dict::<u64, u64>::new(alloc);
for i in 0..500u { names.set(i, i + 1); }
t.expects(names.length == 500 && names[499] == 500);
var text := string::new(alloc);
for _ in 0..100u { text.append("ab"); }
t.expects(text.length == 200 && text[199] == 'b' as u8);
var nested := vector::<vector<u32>>::new(alloc);
for i in 0..50u {
var inner := vector::<u32>::new(alloc);
inner.append(i as u32);
nested.append(move(inner));
}
t.expects(nested.length == 50 && nested[49][0] == 49);
}
struct arena_node {
var value: u64;
var next: maybe<&arena_node>;
}
@test def an_arena_holds_nodes_linked_by_reference(t: &mut tester): void {
var a := arena::new();
val alloc: maybe<&mut allocator> = &mut a;
# Nodes made in an arena live until it rewinds past them, so they link to one
# another by reference, and are given back together.
val point := a.mark();
var front: maybe<&arena_node> = nothing {};
for i in 0..500u {
val made := acquire::<arena_node>(alloc, 1);
made[0] = arena_node { value = i, next = front };
front = through(made);
}
var sum: u64 = 0;
var count: u64 = 0;
while front is some(&each) {
sum += each.value;
count++;
front = each.next;
}
t.expects(count == 500 && sum == 124750);
a.rewind(point);
}
@test def pools_hand_out_the_blocks_given_back_first(t: &mut tester): void {
var p := pool::new(24, 8);
t.expects(p.block_size() == 24);
val a := p.acquire(24, 8);
val b := p.acquire(16, 8);
val c := p.acquire(24, 8);
t.expects(a != null && b == a + 24 && c == b + 24 && p.count() == 3);
# A block given back is the next handed out, the last given back first.
p.dispose(b, 16);
p.dispose(a, 24);
t.expects(p.count() == 1 && p.acquire(24, 8) == a && p.acquire(24, 8) == b);
# Of a size or alignment larger than its blocks, it hands out nothing.
t.expects(p.acquire(25, 8) == null && p.acquire(8, 16) == null && p.count() == 3);
val aligned := pool::new(20, 16);
t.expects(aligned.block_size() == 32);
}
@test def pools_hand_out_their_chunks_again_once_reset(t: &mut tester): void {
# More blocks than a chunk holds take more chunks, each carved in turn, and a
# pool reset carves them again from the first.
var p := pool::new(64, 8);
val first := p.acquire(64, 8);
for _ in 0..3000u {
_ = p.acquire(64, 8);
}
t.expects(p.count() == 3001);
p.reset();
t.expects(p.count() == 0 && p.acquire(64, 8) == first);
for _ in 0..3000u {
_ = p.acquire(64, 8);
}
t.expects(p.count() == 3001);
}
# The values of the pooled values closed, from any test.
var pooled_closed: u64;
struct pooled : owning {
var value: u64;
}
def pooled::close(&mut this): void {
pooled_closed += this.value;
}
@test def pools_make_values_and_close_them_as_they_are_unmade(t: &mut tester): void {
var p := pool::of::<pooled>();
pooled_closed = 0;
var made := vector::<*mut pooled>::new();
for i in 1..101u {
made.append(p.make(pooled { value = i }));
}
t.expects(p.count() == 100 && made[41][0].value == 42);
# The odd values, 1 to 99, are unmade, then the rest.
for i in 0..made.length {
if i % 2 == 0 {
p.unmake(made[i]);
}
}
t.expects(pooled_closed == 2500 && p.count() == 50);
for i in 0..made.length {
if i % 2 == 1 {
p.unmake(made[i]);
}
}
t.expects(pooled_closed == 5050 && p.count() == 0);
}
@test def lists_keep_their_nodes_in_a_pool(t: &mut tester): void {
# A list asks for one node at a time, each within the pool's blocks, and gives
# each back as it is removed.
var p := pool::new(64, 8);
val alloc: maybe<&mut allocator> = &mut p;
{
var numbers := list::<u64>::new(alloc);
for i in 0..1000u {
numbers.push_back(i);
}
t.expects(p.count() == 1000);
for _ in 0..400u {
numbers.pop_front();
}
var total: u64 = 0;
for &n in numbers {
total += n;
}
t.expects(p.count() == 600 && total == 419700);
}
t.expects(p.count() == 0);
}
+585
View File
@@ -0,0 +1,585 @@
# Tests of `std::args`: every form of the syntax, each error and where it is,
# the values std's types read, repeats, positional arguments, subcommands, the
# help text, and the mistakes in marks that stop the program. The commands are
# private to the program, so the walk sees them only by the consent its marks
# give.
import std::args;
import std::io;
import std::testing;
@command{ name = "flags", help = "Reads switches and numbers." }
struct cli_flags {
@option{ short = 'v', help = "Says more." }
var verbose: bool;
@option{ short = 'q' }
var quiet: bool;
@option{ short = 'n', value = "N", help = "How many." }
var count: i64 = 3;
@option{ name = "level", short = 'l' }
var depth: i64;
@option{ help = "Does nothing." }
var dry_run: bool;
@argument{ value = "WORD", help = "The words." }
var words: vector<strview>;
var untouched: i64 = 99;
}
enum cli_colour: u8 {
@choice red,
@choice{ name = "GREEN", help = "As grass is." } green,
@choice light_blue,
unmarked,
}
struct cli_heat : args::value {
var degrees: f64;
}
def cli_heat::from_argument(text: strview): result<cli_heat, strview> {
if text.length < 2 || text[text.length - 1] != 'C' {
return "is not a temperature, as `21C`";
}
return match real::parse::<f64>(text.substr(0, text.length - 1)) {
value(v) => cli_heat { degrees = v },
error(_) => "is not a temperature, as `21C`",
};
}
@command{ name = "values" }
struct cli_values {
@option var tiny: u8;
@option var signed: i8;
@option var wide: i64;
@option var huge: u64;
@option var ratio: f64;
@option var small: f32;
@option var named: string;
@option var file: path;
@option var colour: cli_colour = cli_colour::red;
@option var heat: maybe<cli_heat>;
@option var hues: vector<cli_colour>;
}
@command{ name = "repeats" }
struct cli_repeats {
@option{ short = 'I', value = "DIR" }
var include: vector<strview>;
@option{ short = 'v', count = true }
var verbosity: u32;
@option{ short = 'n' }
var number: i32;
}
@command{ name = "places" }
struct cli_places {
@argument{ value = "FIRST" }
var first: strview;
@argument{ value = "MIDDLE" }
var middle: vector<i64>;
@argument{ value = "LAST" }
var last: strview;
@argument{ value = "MAYBE" }
var maybe_one: maybe<strview>;
}
@command{ name = "passes" }
struct cli_passes {
@option{ short = 'x' }
var exact: bool;
@argument{ value = "FILE" }
var files: vector<strview>;
@argument{ value = "ARGUMENT", rest = true, help = "What is passed on." }
var passed: vector<strview>;
}
@command{ name = "needs" }
struct cli_needs {
@option{ short = 'o', value = "OUTPUT", required = true, help = "Where it goes." }
var output: strview;
@argument{ value = "INPUT" }
var input: strview;
}
@command{ name = "host" }
struct cli_host {
@option{ short = 'h', value = "NAME", help = "The host." }
var host: strview;
}
@command{ name = "git", help = "Keeps versions.", version = "git 2.0" }
union cli_git {
@command{ help = "Names other copies." }
var remote: cli_remote;
@command
var status: cli_status;
}
@command{ help = "Lists, adds, and removes other copies." }
struct cli_remote {
@option{ short = 'v', help = "Shows each one's address." }
var verbose: bool;
@argument
var action: cli_remote_action;
}
@command
union cli_remote_action {
@command{ help = "Adds one." }
var add: cli_remote_add;
@command{ name = "rm", help = "Removes one." }
var remove: cli_remote_remove;
}
@command
struct cli_remote_add {
@option{ help = "Fetches it at once." }
var fetch: bool;
@argument{ value = "NAME" }
var name: strview;
@argument{ value = "URL" }
var url: strview;
}
@command
struct cli_remote_remove {
@argument{ value = "NAME" }
var name: strview;
}
@command{ help = "Shows what changed." }
struct cli_status {
@option{ short = 's' }
var short_form: bool;
}
@command{ name = "make" }
struct cli_make {
@option{ short = 'C', value = "DIR" }
var directory: strview;
@argument{ value = "FILE" }
var file: strview;
@argument
var step: cli_make_step;
}
@command
union cli_make_step {
@command var build: cli_make_build;
@command var clean: cli_status;
}
@command
struct cli_make_build {
@option{ short = 'j' }
var jobs: u8 = 1;
}
# Options several commands share, as a group, which holds a group of its own.
@group
struct cli_shared {
@option{ short = 'O', value = "LEVEL", help = "How much to optimize." }
var level: u8 = 2;
@option{ short = 'v', help = "Says more." }
var verbose: bool;
@group
var library: cli_library;
}
@group
struct cli_library {
@option{ name = "std", value = "DIR", required = true, help = "Where the library is." }
var directory: strview;
@option{ short = 'I', value = "DIR" }
var include: vector<strview>;
}
@command{ name = "grouped", help = "Builds with the options it shares." }
struct cli_grouped {
@option{ short = 'o', value = "OUTPUT", help = "Where it goes." }
var output: strview;
@group
var shared: cli_shared;
@option{ short = 'j', value = "N", help = "How many at once." }
var jobs: u32 = 1;
@argument{ value = "FILE", help = "The files." }
var files: vector<strview>;
}
# The commands whose marks are mistaken, which stop the program once read.
@command struct cli_two_longs { @option var level: i64; @option{ name = "level" } var depth: i64; }
@command struct cli_two_shorts { @option{ short = 'x' } var one: bool; @option{ short = 'x' } var two: bool; }
@command struct cli_bad_short { @option{ short = '!' } var bang: bool; }
@command struct cli_bad_count { @option{ count = true } var noise: strview; }
@command struct cli_bad_rest { @argument{ rest = true } var after: strview; }
@command struct cli_two_rests { @argument{ rest = true } var one: vector<strview>; @argument{ rest = true } var two: vector<strview>; }
@command struct cli_late_command { @argument var step: cli_make_step; @argument var after: strview; }
@command struct cli_many_before { @argument var files: vector<strview>; @argument var step: cli_make_step; }
@command union cli_two_commands { @command var one: cli_status; @command{ name = "one" } var two: cli_status; }
@command struct cli_group_short { @option{ short = 'v' } var loud: bool; @group var shared: cli_shared; }
@command struct cli_group_long { @group var shared: cli_shared; @option{ name = "std" } var other: strview; }
# The error reading the arguments into a command gives, or one of no kind
# where they are read.
def cli_error_of<T>(given: span<strview>): args::error where T: zeroable {
var read := args::parse::<T>(given) else (wrong) { return wrong; };
return args::error { kind = args::error_kind::help_asked, at = 9999 };
}
# The arguments read into flags, or flags of a count of -1 where they are not.
def cli_flags_of(given: span<strview>): cli_flags {
var read := args::parse::<cli_flags>(given) else (_) { return cli_flags { count = -1 }; };
return move(read);
}
@test def options_are_read_by_long_and_short_names(t: &mut tester): void {
t.expects(cli_flags_of(["--count", "4"]).count == 4);
t.expects(cli_flags_of(["--count=5"]).count == 5);
t.expects(cli_flags_of(["-n", "6"]).count == 6);
t.expects(cli_flags_of(["-n7"]).count == 7);
t.expects(cli_flags_of(["--level", "2"]).depth == 2);
t.expects(cli_flags_of(["-l", "8"]).depth == 8);
val plain := cli_flags_of([]);
t.expects(plain.count == 3 && plain.depth == 0 && !plain.verbose && plain.words.length == 0 && plain.untouched == 99);
# Switches written together, the last of them taking a value.
val together := cli_flags_of(["-vq"]);
t.expects(together.verbose && together.quiet);
val valued := cli_flags_of(["-vn9"]);
t.expects(valued.verbose && !valued.quiet && valued.count == 9);
val spaced := cli_flags_of(["-qvn", "10"]);
t.expects(spaced.verbose && spaced.quiet && spaced.count == 10);
# A field's `_` is written `-`, and the last of an option written is kept.
t.expects(cli_flags_of(["--dry-run"]).dry_run);
t.expects(cli_error_of::<cli_flags>(["--dry_run"]).kind == args::error_kind::unknown_option);
t.expects(cli_flags_of(["-n", "1", "--count", "2", "-n3"]).count == 3);
}
@test def values_may_begin_with_a_dash_and_positional_arguments_may_be_dashes(t: &mut tester): void {
t.expects(cli_flags_of(["--level", "-5"]).depth == -5);
t.expects(cli_flags_of(["-n", "-12"]).count == -12);
t.expects(cli_flags_of(["--level=-6"]).depth == -6);
# Options come between positional arguments, which a lone `-` is, and `-` then
# a digit, where no short name is a digit.
val mixed := cli_flags_of(["one", "-v", "-", "-5", "two"]);
t.expects(mixed.verbose && mixed.words.length == 4);
t.expects(mixed.words[0] == "one" && mixed.words[1] == "-" && mixed.words[2] == "-5" && mixed.words[3] == "two");
# After `--`, everything is positional.
val ended := cli_flags_of(["a", "--", "-v", "--count", "b"]);
t.expects(!ended.verbose && ended.count == 3 && ended.words.length == 4 && ended.words[1] == "-v");
# `--name=` gives an empty value, which no number is.
val empty := cli_error_of::<cli_flags>(["--count="]);
t.expects(empty.kind == args::error_kind::invalid_value && empty.text.length == 0);
}
@test def each_error_says_where_it_is(t: &mut tester): void {
val unknown := cli_error_of::<cli_flags>(["-v", "--colour", "red"]);
t.expects(unknown.kind == args::error_kind::unknown_option && unknown.at == 1 && unknown.text == "--colour");
val unknown_short := cli_error_of::<cli_flags>(["-vz"]);
t.expects(unknown_short.kind == args::error_kind::unknown_option && unknown_short.at == 0 && unknown_short.name == "-z");
val missing := cli_error_of::<cli_flags>(["-v", "--count"]);
t.expects(missing.kind == args::error_kind::missing_value && missing.at == 2 && missing.name == "--count");
val missing_short := cli_error_of::<cli_flags>(["-vn"]);
t.expects(missing_short.kind == args::error_kind::missing_value && missing_short.at == 1 && missing_short.name == "-n");
val invalid := cli_error_of::<cli_flags>(["--count", "ten"]);
t.expects(invalid.kind == args::error_kind::invalid_value && invalid.at == 1 && invalid.text == "ten");
t.expects(invalid.name == "--count" && invalid.reason == "is not a whole number");
val attached := cli_error_of::<cli_flags>(["-nx1"]);
t.expects(attached.kind == args::error_kind::invalid_value && attached.at == 0 && attached.text == "x1" && attached.name == "-n");
val switched := cli_error_of::<cli_flags>(["--verbose=yes"]);
t.expects(switched.kind == args::error_kind::switch_given_value && switched.text == "yes" && switched.name == "--verbose");
val required := cli_error_of::<cli_needs>(["in"]);
t.expects(required.kind == args::error_kind::missing_option && required.at == 1 && required.name == "--output");
val argument := cli_error_of::<cli_needs>(["-o", "out"]);
t.expects(argument.kind == args::error_kind::missing_argument && argument.at == 2 && argument.name == "INPUT");
val extra := cli_error_of::<cli_needs>(["-o", "out", "in", "more"]);
t.expects(extra.kind == args::error_kind::unexpected_argument && extra.at == 3 && extra.text == "more");
val command := cli_error_of::<cli_git>(["stats"]);
t.expects(command.kind == args::error_kind::unknown_command && command.at == 0 && command.text == "stats");
val no_command := cli_error_of::<cli_git>([]);
t.expects(no_command.kind == args::error_kind::missing_command && no_command.at == 0);
val deeper := cli_error_of::<cli_git>(["remote", "-v"]);
t.expects(deeper.kind == args::error_kind::missing_command && deeper.at == 2);
val helped := cli_error_of::<cli_flags>(["-v", "--help"]);
t.expects(helped.kind == args::error_kind::help_asked && helped.at == 1);
t.expects(cli_error_of::<cli_flags>(["-vh"]).kind == args::error_kind::help_asked);
t.expects(cli_error_of::<cli_git>(["--version"]).kind == args::error_kind::version_asked);
t.expects(cli_error_of::<cli_flags>(["--version"]).kind == args::error_kind::unknown_option);
}
@test def errors_say_what_went_wrong(t: &mut tester): void {
t.expects(cli_error_of::<cli_values>(["--tiny", "300"]).describe().view() == "`--tiny 300`: 300 is not between 0 and 255.");
t.expects(cli_error_of::<cli_flags>(["--colour"]).describe().view() == "`--colour` is not an option.");
t.expects(cli_error_of::<cli_flags>(["--count"]).describe().view() == "`--count` needs a value.");
t.expects(cli_error_of::<cli_flags>(["-q=1"]).describe().view() == "`-q=1` is not an option.");
t.expects(cli_error_of::<cli_flags>(["--quiet=1"]).describe().view() == "`--quiet` takes no value, but is given `1`.");
t.expects(cli_error_of::<cli_needs>(["in"]).describe().view() == "`--output` is required.");
t.expects(cli_error_of::<cli_needs>(["-o", "out"]).describe().view() == "INPUT is missing.");
t.expects(cli_error_of::<cli_places>(["a", "x", "b"]).describe().view() == "MIDDLE `x` is not a whole number.");
t.expects(cli_error_of::<cli_needs>(["-o", "o", "a", "b"]).describe().view() == "`b` is more than the arguments taken.");
t.expects(cli_error_of::<cli_git>(["stats"]).describe().view() == "`stats` is not a command.");
t.expects(cli_error_of::<cli_git>([]).describe().view() == "A command is needed.");
}
@test def numbers_are_read_within_their_ranges(t: &mut tester): void {
val read := args::parse::<cli_values>([
"--tiny", "255", "--signed=-128", "--wide", "-9223372036854775808", "--huge", "18446744073709551615",
"--ratio", "2.5", "--small", "-0.25"
]) else (_) { t.expects(false); return; };
t.expects(read.tiny == 255 && read.signed == -128 && read.wide == -9223372036854775807 - 1);
t.expects(read.huge == 18446744073709551615 && read.ratio == 2.5 && read.small == -0.25);
# A prefix and `_` between digits are read as the language reads them.
val prefixed := args::parse::<cli_values>(["--wide", "0x1_0", "--tiny", "0b11", "--huge", "1_000"]) else (_) { t.expects(false); return; };
t.expects(prefixed.wide == 16 && prefixed.tiny == 3 && prefixed.huge == 1000);
t.expects(cli_error_of::<cli_values>(["--tiny", "256"]).reason == "is not between 0 and 255");
t.expects(cli_error_of::<cli_values>(["--tiny", "-1"]).reason == "is not between 0 and 255");
t.expects(cli_error_of::<cli_values>(["--signed", "-129"]).reason == "is not between -128 and 127");
t.expects(cli_error_of::<cli_values>(["--signed", "128"]).reason == "is not between -128 and 127");
t.expects(cli_error_of::<cli_values>(["--wide", "9223372036854775808"]).kind == args::error_kind::invalid_value);
t.expects(cli_error_of::<cli_values>(["--huge", "18446744073709551616"]).reason == "is not a whole number");
t.expects(cli_error_of::<cli_values>(["--tiny", "0x"]).reason == "is not a whole number");
t.expects(cli_error_of::<cli_values>(["--ratio", "much"]).reason == "is not a number");
t.expects(cli_error_of::<cli_values>(["--small", "1e39"]).reason == "is too large");
}
@test def text_paths_enums_and_a_programs_own_values_are_read(t: &mut tester): void {
val read := args::parse::<cli_values>([
"--named", "anything", "--file", "a/b", "--colour", "light-blue", "--heat", "21.5C"
]) else (_) { t.expects(false); return; };
t.expects(read.named.view() == "anything");
t.expects(read.file.view() == path::parse("a/b").value.view());
t.expects(read.colour == cli_colour::light_blue);
t.expects(read.heat is some(&heat) && heat.degrees == 21.5);
t.expects(args::parse::<cli_values>([]).value.heat is none);
# A member is read by the `name` its mark gives, and an unmarked one not at all.
t.expects(args::parse::<cli_values>(["--colour", "GREEN"]).value.colour == cli_colour::green);
t.expects(cli_error_of::<cli_values>(["--colour", "green"]).reason == "is not one of the choices");
t.expects(cli_error_of::<cli_values>(["--colour", "unmarked"]).kind == args::error_kind::invalid_value);
t.expects(cli_error_of::<cli_values>(["--heat", "hot"]).reason == "is not a temperature, as `21C`");
t.expects(cli_error_of::<cli_values>(["--file", ""]).reason == "is not a path");
val listed := args::parse::<cli_values>(["--hues", "red", "--hues", "GREEN"]) else (_) { t.expects(false); return; };
t.expects(listed.hues.length == 2 && listed.hues[0] == cli_colour::red && listed.hues[1] == cli_colour::green);
}
@test def options_repeat_into_vectors_and_counts(t: &mut tester): void {
val read := args::parse::<cli_repeats>(["-I", "a", "-vvv", "--include=b", "-Ic", "-v"]) else (_) { t.expects(false); return; };
t.expects(read.include.length == 3 && read.include[0] == "a" && read.include[1] == "b" && read.include[2] == "c");
t.expects(read.verbosity == 4);
t.expects(args::parse::<cli_repeats>(["--verbosity", "--verbosity"]).value.verbosity == 2);
t.expects(cli_error_of::<cli_repeats>(["--verbosity=2"]).kind == args::error_kind::switch_given_value);
# A count is no switch to the short names written with it: `-vn5` counts once.
val counted := args::parse::<cli_repeats>(["-vn5"]) else (_) { t.expects(false); return; };
t.expects(counted.verbosity == 1 && counted.number == 5);
}
@test def positional_arguments_go_to_their_fields_in_turn(t: &mut tester): void {
# A vector takes what is left over once the single fields after it have theirs.
val read := args::parse::<cli_places>(["a", "1", "2", "3", "z"]) else (_) { t.expects(false); return; };
t.expects(read.first == "a" && read.middle.length == 3 && read.middle[2] == 3 && read.last == "z" && read.maybe_one is none);
val fewest := args::parse::<cli_places>(["a", "z"]) else (_) { t.expects(false); return; };
t.expects(fewest.first == "a" && fewest.middle.length == 0 && fewest.last == "z");
t.expects(cli_error_of::<cli_places>(["a"]).name == "LAST");
# What follows `--` goes to the field taking the rest, and only there.
val passed := args::parse::<cli_passes>(["x.sakura", "-x", "y.sakura", "--", "-x", "--", "z"]) else (_) { t.expects(false); return; };
t.expects(passed.exact && passed.files.length == 2 && passed.files[1] == "y.sakura");
t.expects(passed.passed.length == 3 && passed.passed[0] == "-x" && passed.passed[1] == "--" && passed.passed[2] == "z");
val none_passed := args::parse::<cli_passes>(["a"]) else (_) { t.expects(false); return; };
t.expects(none_passed.files.length == 1 && none_passed.passed.length == 0);
}
@test def subcommands_read_their_own_options_two_deep(t: &mut tester): void {
val read := args::parse::<cli_git>(["remote", "-v", "add", "--fetch", "origin", "https://x"]) else (_) { t.expects(false); return; };
match read {
remote(&r) => {
t.expects(r.verbose);
match r.action {
add(&a) => t.expects(a.fetch && a.name == "origin" && a.url == "https://x");
remove(&_) => t.expects(false);
}
}
status(&_) => t.expects(false);
}
val removed := args::parse::<cli_git>(["remote", "rm", "old"]) else (_) { t.expects(false); return; };
t.expects(removed is remote(&r) && r.action is remove(&gone) && gone.name == "old" && !r.verbose);
t.expects(args::parse::<cli_git>(["status", "-s"]).value is status(&s) && s.short_form);
# A command's own options come before its subcommand's word, and the
# positional arguments before it each take one.
val made := args::parse::<cli_make>(["-C", "src", "rules.mk", "build", "-j", "8"]) else (_) { t.expects(false); return; };
t.expects(made.directory == "src" && made.file == "rules.mk" && made.step is build(&b) && b.jobs == 8);
t.expects(cli_error_of::<cli_make>(["rules.mk", "build", "-C", "x"]).kind == args::error_kind::unknown_option);
t.expects(cli_error_of::<cli_make>(["rules.mk"]).kind == args::error_kind::missing_command);
}
@test def the_help_text_is_written_from_the_marks(t: &mut tester): void {
t.expects(args::help::<cli_flags>().view() == """
usage: flags [options] WORD...
Reads switches and numbers.
arguments:
WORD... The words.
options:
-v, --verbose Says more.
-q, --quiet
-n, --count N How many. Default: 3.
-l, --level LEVEL Default: 0.
--dry-run Does nothing.
-h, --help Shows this help.
""");
# The arguments reach a subcommand, whose help is given, and its usage.
t.expects(args::help::<cli_git>(["remote", "add", "--help"]).view() == """
usage: git remote add [options] NAME URL
Adds one.
arguments:
NAME
URL
options:
--fetch Fetches it at once.
-h, --help Shows this help.
""");
t.expects(args::usage::<cli_git>(["remote"]).view() == "usage: git remote [options] COMMAND ...");
t.expects(args::help::<cli_git>(["--help"]).view() == """
usage: git [options] COMMAND ...
Keeps versions.
commands:
remote Names other copies.
status Shows what changed.
options:
-h, --help Shows this help.
--version Shows the version.
""");
t.expects(args::help::<cli_values>([]).view() == """
usage: values [options]
options:
--tiny TINY Default: 0.
--signed SIGNED Default: 0.
--wide WIDE Default: 0.
--huge HUGE Default: 0.
--ratio RATIO Default: 0.
--small SMALL Default: 0.
--named NAMED
--file FILE
--colour COLOUR Default: red.
red
GREEN As grass is.
light-blue
--heat HEAT
--hues HUES
red
GREEN As grass is.
light-blue
-h, --help Shows this help.
""");
t.expects(args::usage::<cli_passes>().view() == "usage: passes [options] FILE... [-- ARGUMENT...]");
t.expects(args::usage::<cli_places>().view() == "usage: places [options] FIRST MIDDLE... LAST [MAYBE]");
}
@test def help_is_left_to_a_field_taking_its_name(t: &mut tester): void {
val read := args::parse::<cli_host>(["-h", "example.org"]) else (_) { t.expects(false); return; };
t.expects(read.host == "example.org");
t.expects(cli_error_of::<cli_host>(["--help"]).kind == args::error_kind::help_asked);
t.expects(args::help::<cli_host>().view() == """
usage: host [options]
options:
-h, --host NAME The host.
--help Shows this help.
""");
}
@test def parse_or_exit_stops_with_the_status_of_what_it_says(t: &mut tester): void {
t.expects(!stops(def() { _ = args::parse_or_exit::<cli_flags>(["--help"]); }));
t.expects(!stops(def() { _ = args::parse_or_exit::<cli_git>(["--version"]); }));
t.expects(stops(def() { _ = args::parse_or_exit::<cli_flags>(["--count", "x"]); }));
t.expects(!stops(def() { _ = args::parse_or_exit::<cli_flags>(["-v"]); }));
}
@test def mistaken_marks_stop_the_program_however_it_is_run(t: &mut tester): void {
t.expects(stops(def() { _ = args::parse::<cli_two_longs>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_two_shorts>(["--help"]); }));
t.expects(stops(def() { _ = args::parse::<cli_bad_short>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_bad_count>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_bad_rest>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_two_rests>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_late_command>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_many_before>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_two_commands>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_group_short>([]); }));
t.expects(stops(def() { _ = args::parse::<cli_group_long>([]); }));
t.expects(!stops(def() { _ = args::parse::<cli_flags>([]); }));
}
@test def groups_are_read_as_if_declared_in_place(t: &mut tester): void {
val read := args::parse::<cli_grouped>([
"-o", "out", "-O1", "--verbose", "--std", "lib", "-Ia", "--include", "b", "-j", "4", "x", "y"
]) else (_) { t.expects(false); return; };
t.expects(read.output == "out" && read.shared.level == 1 && read.shared.verbose && read.jobs == 4);
t.expects(read.shared.library.directory == "lib" && read.shared.library.include.length == 2);
t.expects(read.shared.library.include[1] == "b" && read.files.length == 2 && read.files[1] == "y");
# A group's fields keep their defaults, and its short names are written
# together with the command's own.
val plain := args::parse::<cli_grouped>(["--std=lib"]) else (_) { t.expects(false); return; };
t.expects(plain.shared.level == 2 && !plain.shared.verbose && plain.jobs == 1 && plain.output.length == 0);
val together := args::parse::<cli_grouped>(["--std", "lib", "-vj2", "-vO3"]) else (_) { t.expects(false); return; };
t.expects(together.shared.verbose && together.jobs == 2 && together.shared.level == 3);
# Errors name a group's options as they name the command's own.
val required := cli_error_of::<cli_grouped>(["x"]);
t.expects(required.kind == args::error_kind::missing_option && required.name == "--std");
val invalid := cli_error_of::<cli_grouped>(["--std", "lib", "-O", "300"]);
t.expects(invalid.kind == args::error_kind::invalid_value && invalid.name == "-O" && invalid.text == "300");
val switched := cli_error_of::<cli_grouped>(["--std", "lib", "--verbose=yes"]);
t.expects(switched.kind == args::error_kind::switch_given_value && switched.name == "--verbose");
t.expects(cli_error_of::<cli_grouped>(["--std", "lib", "--shared"]).kind == args::error_kind::unknown_option);
}
@test def groups_are_shown_in_place_in_the_help_text(t: &mut tester): void {
t.expects(args::help::<cli_grouped>().view() == """
usage: grouped [options] FILE...
Builds with the options it shares.
arguments:
FILE... The files.
options:
-o, --output OUTPUT Where it goes.
-O, --level LEVEL How much to optimize. Default: 2.
-v, --verbose Says more.
--std DIR Where the library is. Required.
-I, --include DIR
-j, --jobs N How many at once. Default: 1.
-h, --help Shows this help.
""");
}
+367
View File
@@ -0,0 +1,367 @@
# Tests of the containers: what they check of what they are asked for, what they
# close of their elements, and what they do where an allocator gives no memory,
# with the helpers of std they lean on.
import std::containers;
import std::io;
import system;
import std::testing;
# How many counters have been closed, which only those holding a count are.
var closed: u64 = 0;
struct counter : owning, hashable, ordered {
var n: u64;
}
def counter::close(&mut this): void {
if this.n != 0 {
closed++;
this.n = 0;
}
}
def counter::hash(&this): u64 { return this.n; }
def counter::equals(&this, other: &counter): bool { return this.n == other.n; }
def counter::compare(&this, other: &counter): i64 { return this.n as i64 - other.n as i64; }
# A value that is not closeable itself, but holds one that is.
struct holder {
var c: counter;
}
def held(n: u64): holder {
return holder { c = counter { n = n } };
}
@test def containers_stop_at_an_index_past_their_end(t: &mut tester): void {
t.expects(!stops(def() { var v := vector::<i64>::new(); v.append(1); val x := v[0]; v.set(0, 2); v.insert_at(1, 3); v.remove_at(1); }));
t.expects(!stops(def() { var i := interner::<i64>::new(); i.intern(1); val x := i[0]; }));
# Only a program that checks stops at these, which one that does not reads
# past what the container holds.
if const checking() {
t.expects(stops(def() { var v := vector::<i64>::new(); v.append(1); val x := v[1]; }));
t.expects(stops(def() { var v := vector::<i64>::new(); v.append(1); v[3] = 2; }));
t.expects(stops(def() { var v := vector::<i64>::new(); v.set(0, 1); }));
t.expects(stops(def() { var v := vector::<i64>::new(); v.insert_at(1, 1); }));
t.expects(stops(def() { var v := vector::<i64>::new(); v.append(1); v.remove_at(1); }));
t.expects(stops(def() { val s := string::from("ab", nothing {}); val b := s[2]; }));
t.expects(stops(def() { val xs: i64[2] = [1, 2]; val view: span<i64> = xs[0:2]; val x := view.at(2); }));
t.expects(stops(def() { var xs: i64[2] = [1, 2]; var view: slice<i64> = xs[0:2]; view.at(2) = 3; }));
t.expects(stops(def() { var d := deque::<i64>::new(); d.push_back(1); val x := d[1]; }));
t.expects(stops(def() { var l := list::<i64>::new(); l.push_back(1); val x := l[1]; }));
t.expects(stops(def() { var l := list::<i64>::new(); l.insert_at(1, 1); }));
t.expects(stops(def() { var l := list::<i64>::new(); l.push_back(1); l.remove_at(1); }));
t.expects(stops(def() { var c := chain::<i64>::new(); c.push_back(1); val x := c[1]; }));
t.expects(stops(def() { var c := chain::<i64>::new(); c.insert_at(1, 1); }));
t.expects(stops(def() { var c := chain::<i64>::new(); c.push_back(1); c.remove_at(1); }));
t.expects(stops(def() { var r := runs::<i64>::new(); val x := r.length(1); }));
t.expects(stops(def() { var r := runs::<i64>::new(); val id := r.add([1, 2]); val x := r.at(id, 2); }));
t.expects(stops(def() { var g := groups::<i64>::new(2); g.count(2); }));
t.expects(stops(def() { var w := byte_writer::new(); w.u16(1); w.set_u32(0, 5); }));
t.expects(stops(def() { var i := interner::<i64>::new(); i.intern(1); val x := i[1]; }));
}
}
@test def containers_stop_where_they_hold_nothing_asked_for(t: &mut tester): void {
t.expects(!stops(def() { var s := stack::<i64>::new(); s.push(1); val x := s.peek(); s.pop(); }));
t.expects(stops(def() { var g := groups::<i64>::new(1); g.seal(); g.count(0); }));
t.expects(!stops(def() { var g := groups::<i64>::new(1); val x := g.of(0); }));
t.expects(!stops(def() { var d := dict::<i64, i64>::new(); d.set(1, 2); val x := d[1]; }));
# Only a program that checks stops at these, which one that does not reads
# past what the container holds.
if const checking() {
t.expects(stops(def() { var s := stack::<i64>::new(); s.pop(); }));
t.expects(stops(def() { val s := stack::<i64>::new(); val x := s.peek(); }));
t.expects(stops(def() { var q := queue::<i64>::new(); q.pop(); }));
t.expects(stops(def() { val q := queue::<i64>::new(); val x := q.peek(); }));
t.expects(stops(def() { var d := deque::<i64>::new(); d.pop_front(); }));
t.expects(stops(def() { var d := deque::<i64>::new(); d.pop_back(); }));
t.expects(stops(def() { val d := deque::<i64>::new(); val x := d.front(); }));
t.expects(stops(def() { val d := deque::<i64>::new(); val x := d.back(); }));
t.expects(stops(def() { var l := list::<i64>::new(); l.pop_front(); }));
t.expects(stops(def() { val l := list::<i64>::new(); val x := l.front(); }));
t.expects(stops(def() { val l := list::<i64>::new(); val x := l.back(); }));
t.expects(stops(def() { var c := chain::<i64>::new(); c.pop_front(); }));
t.expects(stops(def() { var c := chain::<i64>::new(); c.pop_back(); }));
t.expects(stops(def() { val c := chain::<i64>::new(); val x := c.front(); }));
t.expects(stops(def() { val c := chain::<i64>::new(); val x := c.back(); }));
t.expects(stops(def() { val v := vector::<i64>::new(); val x := v.first(); }));
t.expects(stops(def() { val v := vector::<i64>::new(); val x := v.last(); }));
t.expects(stops(def() { var v := vector::<i64>::new(); v.truncate(); }));
t.expects(stops(def() { val h := heap::<i64>::new(); val x := h.peek(); }));
t.expects(stops(def() { var h := heap::<i64>::new(); h.pop(); }));
t.expects(stops(def() { var g := groups::<i64>::new(1); g.count(0); g.seal(); g.put(0, 1); g.put(0, 2); }));
t.expects(stops(def() { var g := groups::<i64>::new(1); g.count(0); g.put(0, 1); }));
t.expects(stops(def() { var w := byte_writer::new(); w.byte(1); w.rewind(2); }));
t.expects(stops(def() { var d := dict::<i64, i64>::new(); d.set(1, 2); val x := d[5]; }));
}
}
# The element `get` gives, or -1 where it gives none.
def got<T>(found: maybe<&T>): i64 where T: integer {
if found is some(element) {
return element as i64;
}
return -1;
}
@test def containers_give_an_element_or_nothing_by_get(t: &mut tester): void {
var v := vector::<i64>::new();
v.append(4);
v.append(5);
val read := &v;
t.expects(got(read.get(1)) == 5 && got(read.get(2)) == -1);
if v.get(0) is some(&mut first) {
first = 6;
}
t.expects(v[0] == 6 && v.get(2) is none);
val s := string::from("ab", nothing {});
t.expects(got(s.get(1)) == 'b' as i64 && got(s.get(2)) == -1);
val xs: i64[3] = [1, 2, 3];
val part: span<i64> = xs[1:2];
t.expects(got(part.get(1)) == 3 && got(part.get(2)) == -1);
var ys: i64[3] = [1, 2, 3];
var place: slice<i64> = ys[1:2];
if place.get(1) is some(&mut last) {
last = 9;
}
t.expects(ys[2] == 9 && place.get(2) is none);
var d := deque::<i64>::new();
d.push_back(7);
var l := list::<i64>::new();
l.push_back(8);
var c := chain::<i64>::new();
c.push_back(9);
val dr := &d;
val lr := &l;
val cr := &c;
t.expects(got(dr.get(0)) == 7 && got(dr.get(1)) == -1);
t.expects(got(lr.get(0)) == 8 && got(lr.get(1)) == -1);
t.expects(got(cr.get(0)) == 9 && got(cr.get(1)) == -1);
}
@test def containers_close_what_their_elements_hold(t: &mut tester): void {
# A value holding what closes is closed as a local holding it is.
var lone := held(1);
closed = 0;
close(&mut lone);
t.expects(closed == 1 && lone.c.n == 0);
closed = 0;
var v := vector::<holder>::new();
v.append(held(1)); v.append(held(2)); v.append(held(3)); v.append(held(4));
v.remove_at(0);
t.expects(closed == 1);
v.resize(2);
t.expects(closed == 2);
v.clear();
t.expects(closed == 4);
v.append(held(5));
v.close();
t.expects(closed == 5);
closed = 0;
var s := stack::<holder>::new();
s.push(held(1)); s.push(held(2)); s.push(held(3));
s.pop();
s.resize(1);
s.clear();
t.expects(closed == 3);
closed = 0;
var q := queue::<holder>::new();
q.push(held(1)); q.push(held(2));
q.pop();
q.clear();
var d := deque::<holder>::new();
d.push_back(held(1)); d.push_front(held(2)); d.push_back(held(3));
d.pop_front();
d.pop_back();
d.clear();
t.expects(closed == 5);
closed = 0;
var l := list::<holder>::new();
l.push_back(held(1)); l.push_back(held(2)); l.push_back(held(3));
l.pop_front();
l.remove_at(1);
l.clear();
var c := chain::<holder>::new();
c.push_back(held(1)); c.push_back(held(2)); c.push_back(held(3));
c.pop_back();
c.remove_at(0);
c.clear();
t.expects(closed == 6);
closed = 0;
var m := dict::<i64, holder>::new();
m.set(1, held(1)); m.set(2, held(2)); m.set(3, held(3));
m.set(1, held(4));
t.expects(closed == 1);
t.expects(m.remove(&2));
m.clear();
t.expects(closed == 4);
}
# An interner closes a value it is given that equals one it holds, keeping the
# first, and gives that one's ID; what it holds it closes where it is cleared, and
# it numbers from 0 again after.
@test def sets_close_the_values_they_let_go(t: &mut tester): void {
closed = 0;
var s := hashset::<counter>::new();
for n in 1..7 { t.expects(s.insert(counter { n = n as u64 })); }
t.expects(!s.insert(counter { n = 1 }) && s.length == 6 && closed == 1);
val two := counter { n = 2 };
t.expects(s.remove(&two) && !s.remove(&two) && closed == 2);
var odd := hashset::<counter>::new();
for n in 0..4 { odd.insert(counter { n = (2 * n + 1) as u64 }); }
s.intersect_with(&odd);
t.expects(s.length == 3 && closed == 4);
s.subtract(&odd);
t.expects(s.is_empty && closed == 7);
for n in 10..13 { s.insert(counter { n = n as u64 }); }
s.clear();
t.expects(closed == 10 && odd.length == 4);
var words := hashset::<string>::new();
words.insert(string::from("one", nothing {}));
words.insert(string::from("two", nothing {}));
var more := hashset::<string>::new();
more.insert(string::from("two", nothing {}));
more.insert(string::from("three", nothing {}));
var copied := hashset::<string>::copy_of(&words);
copied.union_with(&more);
more.close();
words.close();
val three := string::from("three", nothing {});
t.expects(copied.length == 3 && copied.contains(&three) && copied.get(&three).some.view() == "three");
}
@test def interners_keep_the_first_of_equal_values(t: &mut tester): void {
closed = 0;
var i := interner::<counter>::new();
t.expects(i.intern(counter { n = 5 }) == 0 && i.intern(counter { n = 6 }) == 1);
t.expects(i.intern(counter { n = 5 }) == 0 && closed == 1 && i.length == 2);
val six := counter { n = 6 };
t.expects(i.find(&six).some == 1 && i[1].n == 6 && i.contains(&six));
i.clear();
t.expects(closed == 3 && i.is_empty && i.find(&six) is none);
t.expects(i.intern(counter { n = 7 }) == 0);
# Text is found, and interned, by its view, and copied only where it is new.
var words := interner::<string>::new();
var ids := vector::<u32>::new();
for w in "a b a c b".split(' ' as u8) {
ids.append(words.intern_view(w));
}
val b: strview = "b";
val d: strview = "d";
t.expects(ids.length == 5 && ids[0] == 0 && ids[1] == 1 && ids[2] == 0 && ids[3] == 2 && ids[4] == 1);
t.expects(words.length == 3 && words.find_view(b).some == 1 && words.find_view(d) is none && words[2].view() == "c");
var copied := interner::<string>::copy_of(&words);
words.close();
t.expects(copied.length == 3 && copied.find_view(b).some == 1 && copied[0].view() == "a");
}
# A heap gives its least value first, and closes each value it removes.
@test def heaps_give_their_least_value_first(t: &mut tester): void {
closed = 0;
var h := heap::<counter>::new();
val given: u64[6] = [5, 2, 8, 1, 9, 3];
for i in 0..6 { h.push(counter { n = given[i] }); }
var order := vector::<u64>::new();
while !h.is_empty {
order.append(h.peek().n);
h.pop();
}
t.expects(order.length == 6 && order[0] == 1 && order[1] == 2 && order[2] == 3 && order[5] == 9 && closed == 6);
var words := heap::<u64>::new(4, nothing {});
for i in 0..100 { words.push(((i * 37) % 101) as u64); }
var last: u64 = 0;
var rising := true;
while !words.is_empty {
rising = rising && words.peek() >= last;
last = words.peek();
words.pop();
}
t.expects(rising);
}
# Runs are named by IDs from 1, the empty one 0, and rewound to drop the newest.
@test def runs_hold_lists_named_by_ids(t: &mut tester): void {
var r := runs::<u32>::new();
val a := r.add([1, 2, 3]);
r.push(7);
r.push(8);
val b := r.end();
t.expects(a == 1 && b == 2 && r.end() == 0 && r.add(span::<u32>::empty()) == 0 && r.count == 3);
t.expects(r.length(a) == 3 && r.at(b, 0) == 7 && r.view(a)[2] == 3 && r.length(0) == 0 && r.size == 5);
r.rewind(2);
t.expects(r.count == 2 && r.add([4]) == 2 && r.at(2, 0) == 4);
val copied := runs::<u32>::copy_of(&r);
r.clear();
t.expects(r.count == 1 && copied.count == 3 && copied.view(1)[1] == 2);
closed = 0;
var held := runs::<counter>::new();
held.push(counter { n = 1 });
held.push(counter { n = 2 });
val id := held.end();
held.push(counter { n = 3 });
held.rewind(1);
t.expects(id == 1 && closed == 3 && held.count == 1);
}
# Groups put each element after those of its key put before it, once counted.
@test def groups_gather_elements_by_key(t: &mut tester): void {
var g := groups::<u32>::new(4);
val keys: u32[6] = [3, 0, 3, 1, 3, 0];
for i in 0..6 { g.count(keys[i]); }
g.seal();
for i in 0..6 { g.put(keys[i], i as u32); }
t.expects(g.keys == 4 && g.size == 6 && g.length(3) == 3 && g.length(2) == 0);
t.expects(g.of(3)[0] == 0 && g.of(3)[1] == 2 && g.of(3)[2] == 4 && g.of(0)[1] == 5 && g.of(1)[0] == 3);
g.reset(2);
g.count(1, 2);
t.expects(!g.is_sealed && g.length(1) == 2 && g.keys == 2 && g.of(1).length == 0);
g.seal();
g.put(1, 9);
t.expects(g.of(1)[0] == 9 && g.of(1).length == 2);
}
# An allocator that never has memory to give.
struct starved : allocator {}
def starved::acquire(&mut this, size: u64, align: u64): *mut u8 { return null; }
def starved::dispose(&mut this, addr: *mut u8, size: u64): void {}
def starved::resize(&mut this, addr: *mut u8, old: u64, size: u64, align: u64): *mut u8 { return null; }
# Each container is given an allocator with nothing to give, named as the
# `maybe<&mut allocator>` the overloads of `new` take.
@test def an_allocator_that_gives_no_memory_stops_the_program(t: &mut tester): void {
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var v := vector::<i64>::new(alloc); v.append(1); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var s := string::new(alloc); s.push('x' as u8); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var d := dict::<i64, i64>::new(alloc); d.set(1, 2); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var h := hashset::<i64>::new(alloc); h.insert(1); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var i := interner::<i64>::new(alloc); i.intern(1); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var h := heap::<i64>::new(alloc); h.push(1); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var r := runs::<i64>::new(alloc); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var g := groups::<i64>::new(4, alloc); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var w := byte_writer::new(alloc); w.byte(1); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var l := list::<i64>::new(alloc); l.push_back(1); }));
t.expects(stops(def() { var none := starved {}; val alloc: maybe<&mut allocator> = &mut none; var q := queue::<i64>::new(alloc); q.push(1); }));
}
+86
View File
@@ -0,0 +1,86 @@
# Tests of the owners shared by every copy: `rc`, counted plainly, and `arc`,
# counted atomically, with the weak references that do not keep their values.
# Each closes what it holds exactly once, where its last owner closes.
import std::containers;
import std::testing;
import std::thread;
# How many values the tests gave owners have been closed, from any thread.
var owned_closed: atomic<u64>;
struct owned : owning {
var mark: u64;
}
def owned::close(&mut this): void {
if this.mark != 0 {
_ = owned_closed.fetch_add(1);
this.mark = 0;
}
}
@test def counted_owners_and_maybe_owners_are_one_word(t: &mut tester): void {
t.expects(size_of::<rc<owned>>() == 8 && size_of::<maybe<rc<owned>>>() == 8);
t.expects(size_of::<arc<owned>>() == 8 && size_of::<maybe<arc<owned>>>() == 8);
}
@test def rc_copies_share_one_value_the_last_closes(t: &mut tester): void {
val before := owned_closed.load();
var first := rc::<owned>::new(owned { mark = 1 });
var weak := first.weak();
{
var second := copy(&first);
second.get().mark = 5;
t.expects(first.count() == 2 && first.get().mark == 5);
}
t.expects(first.count() == 1 && owned_closed.load() == before);
if weak.lock() is some(&locked) {
t.expects(locked.count() == 2 && locked.get().mark == 5);
} else {
t.expects(false);
}
var weaker := copy(&weak);
first.close();
t.expects(owned_closed.load() == before + 1);
t.expects(!(weak.lock() is some) && !(weaker.lock() is some));
# Moving an owner moves the count's claim with it.
var moved_from := rc::<owned>::new(owned { mark = 7 });
var moved_to := move(&mut moved_from);
moved_from.close();
t.expects(moved_to.count() == 1 && owned_closed.load() == before + 1);
moved_to.close();
t.expects(owned_closed.load() == before + 2);
}
@test def arc_copies_are_counted_from_many_threads(t: &mut tester): void {
val before := owned_closed.load();
var shared := arc::<owned>::new(owned { mark = 9 });
val weak := shared.weak();
val from: &arc<owned> = &shared;
var workers := vector::<thread::handle<void>>::new();
for _ in 0..4u {
var started := thread::spawn(def() {
for _ in 0..2000u {
val held := copy(from);
if held.get().mark != 9 { return; }
}
}) else (e) { t.expects(false); return; };
workers.append(move(&mut started));
}
for i in 0..workers.length {
workers[i].join();
}
t.expects(shared.count() == 1 && owned_closed.load() == before);
var last := copy(&shared);
shared.close();
t.expects(last.count() == 1 && owned_closed.load() == before);
if weak.lock() is some(&locked) {
t.expects(locked.get().mark == 9);
}
last.close();
t.expects(owned_closed.load() == before + 1 && !(weak.lock() is some));
}
+29
View File
@@ -0,0 +1,29 @@
# Tests of the containers: what they check of what they are asked for, what they
# close of their elements, and what they do where an allocator gives no memory,
# with the helpers of std they lean on.
import std::io;
import system;
import std::testing;
# A byte writer lays words out least significant byte first, and writes over
# what it wrote, as a length known only after what it counts.
@test def byte_writers_lay_out_words_and_lengths(t: &mut tester): void {
var w := byte_writer::new();
w.byte(0xAA);
val at := w.begin_length();
w.u16(0x0201);
w.u64(0x0807060504030201);
w.put_terminated("hi");
w.end_length(at);
t.expects(w.get_u32(at) == 13 && w.get_byte(5) == 0x01 && w.get_byte(6) == 0x02 && w.length == 18);
t.expects(w.align_to(8) == 24 && w.get_byte(23) == 0 && w.get_u64(7) == 0x0807060504030201);
w.set_u16(1, 0xBEEF);
w.set_byte(0, 1);
t.expects(w.view()[1] == 0xEF && w.view()[2] == 0xBE && w.get_byte(0) == 1);
w.zeros(3);
t.expects(w.length == 27 && pair_high(pair_key(5, 6)) == 5 && pair_low(pair_key(5, 6)) == 6);
w.rewind(5);
w.byte(9);
t.expects(w.length == 6 && w.get_byte(5) == 9 && w.get_u32(1) == 0xBEEF);
}
+247
View File
@@ -0,0 +1,247 @@
# Tests of finding what a glob matches in a tree of files: wildcards, `**`,
# braces, hidden names, links, roots, directories, repeats, and directories
# that can't be read. Every path is listed relative to the tree, with `/`
# between names.
import std::io;
import std::process;
import system;
import std::io::glob;
import std::testing;
# A tree of files of a test's own, removed with all it holds where the test
# returns:
#
# a.sakura b.txt .hidden.sakura 名前.sakura Upper.SAKURA src-old.txt
# docs/
# src/main.sakura src/notes.txt src/util/text.sakura src/util/deep/x.sakura
# src/.git/config.sakura
# test/t.sakura
#
# and on Linux, `link`, a link to `src`, and `loop`, a link to itself.
struct tree : fixture<tree>, owning {
var at: path;
}
def tree::setup(t: &mut tester): tree {
var made := tree { at = made_directory() };
for dir in ["docs", "src", "src/util", "src/util/deep", "src/.git", "test"] {
val at := made.at.join(dir);
_ = io::create_directory(&at);
}
for file in [
"a.sakura", "b.txt", ".hidden.sakura", "名前.sakura", "Upper.SAKURA", "src-old.txt", "src/main.sakura", "src/notes.txt",
"src/util/text.sakura", "src/util/deep/x.sakura", "src/.git/config.sakura", "test/t.sakura"
] {
val at := made.at.join(file);
_ = io::write_file(&at, "");
}
when os == linux {
var link := process::command::new("ln");
link.directory(&made.at);
link.arguments(["-s", "src", "link"]);
_ = link.run();
var loop := process::command::new("ln");
loop.directory(&made.at);
loop.arguments(["-s", "loop", "loop"]);
_ = loop.run();
}
return made;
}
def tree::close(&mut this): void {
when os == windows {
var removing := process::command::new("cmd");
removing.arguments(["/d", "/c", "rmdir", "/s", "/q", this.at.view()]);
_ = removing.run();
return;
}
var remove := process::command::new("rm");
remove.arguments(["-rf", this.at.view()]);
_ = remove.run();
}
# Makes a directory no other run has, by making it only where nothing is.
def made_directory(): path {
# Windows keeps its temporary files where `TEMP` says.
when os == windows {
for n in 0..10000 {
val named := path::parse($"{temporary()}\\sakura-glob-{n}") else (_) { break; };
var at := io::absolute(&named) else (_) { break; };
if io::create_directory(&at) is error(_) {
continue;
}
return move(at);
}
}
for n in 0..10000 {
var at := path::parse($"/tmp/sakura-glob-{n}") else (_) { break; };
if io::create_directory(&at) is error(_) {
continue;
}
return move(at);
}
system::abort();
return path::new();
}
# A path's text with `/` between its names, as Windows writes `\`.
def forward(text: strview): string {
var made := string::from(text, nothing {});
for k in 0..made.length {
if made[k] == '\\' {
made[k] = '/';
}
}
return made;
}
# What a glob finds in a tree, read with the options, which by default tell
# cases apart on every system: each path relative to the tree, with a space
# between them, or why it stopped.
def found(planted: &tree, text: strview, settings: glob::options = glob::options { folds_case = false }): string {
val made := glob::pattern::parse(text, settings) else (e) { return e.describe(); };
var listed := string::new(nothing {});
var got := made.find(&planted.at);
match got {
value(&paths) => {
for &each in paths {
if listed.length != 0 {
listed.push(' ');
}
if each.relative_to(&planted.at) is some(&relative) {
listed.append(forward(relative.view()).view());
} else {
listed.append(forward(each.view()).view());
}
}
}
error(&why) => listed.append(why.describe().view());
}
return listed;
}
@test def wildcards_find_the_names_of_a_directory(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "*.sakura") == "a.sakura 名前.sakura");
t.expects(found(&planted, "*.sakura", glob::options { folds_case = true }) == "Upper.SAKURA a.sakura 名前.sakura");
t.expects(found(&planted, "?.*") == "a.sakura b.txt");
t.expects(found(&planted, "[ab].*") == "a.sakura b.txt");
t.expects(found(&planted, ".*") == ".hidden.sakura");
}
@test def two_stars_find_every_directory_below(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "**/*.sakura") == "a.sakura src/main.sakura src/util/deep/x.sakura src/util/text.sakura test/t.sakura 名前.sakura");
t.expects(found(&planted, "src/**") == "src src/main.sakura src/notes.txt src/util src/util/deep src/util/deep/x.sakura src/util/text.sakura");
# In order by their bytes, as a shell orders them.
t.expects(found(&planted, "**/*.txt") == "b.txt src-old.txt src/notes.txt");
t.expects(found(&planted, "**/deep") == "src/util/deep");
t.expects(found(&planted, "**/util/**/*.sakura") == "src/util/deep/x.sakura src/util/text.sakura");
val hidden := glob::options { hidden = true, folds_case = false };
t.expects(found(&planted, "**/*.sakura", hidden) == ".hidden.sakura a.sakura src/.git/config.sakura src/main.sakura src/util/deep/x.sakura src/util/text.sakura test/t.sakura 名前.sakura");
}
@test def braces_find_each_once(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "{src,test}/*.sakura") == "src/main.sakura test/t.sakura");
t.expects(found(&planted, "{src/**/x.sakura,**/deep/*.sakura}") == "src/util/deep/x.sakura");
t.expects(found(&planted, "{a,b}.*") == "a.sakura b.txt");
}
@test def names_as_written_are_joined_on(t: &mut tester, planted: tree): void {
t.expects(found(&planted, "a.sakura") == "a.sakura");
t.expects(found(&planted, "src/util/text.sakura") == "src/util/text.sakura");
t.expects(found(&planted, "nothing.sakura") == "" && found(&planted, "missing/*.sakura") == "");
t.expects(found(&planted, "a.sakura/*") == "" && found(&planted, "b.txt/**") == "b.txt");
t.expects(found(&planted, ".") == "." && found(&planted, "src/../test/*") == "src/../test/t.sakura");
}
@test def a_slash_last_finds_directories(t: &mut tester, planted: tree): void {
when os == linux {
t.expects(found(&planted, "*/") == "docs link src test");
t.expects(found(&planted, "**/") == "docs link src src/util src/util/deep test");
} else {
t.expects(found(&planted, "*/") == "docs src test");
t.expects(found(&planted, "**/") == "docs src src/util src/util/deep test");
}
t.expects(found(&planted, "src/*/") == "src/util" && found(&planted, "a.sakura/") == "");
}
@test def links_are_followed_where_named_but_not_by_two_stars(t: &mut tester, planted: tree): void {
when os != linux {
return;
}
t.expects(found(&planted, "*/main.sakura") == "link/main.sakura src/main.sakura");
t.expects(found(&planted, "link/**/*.sakura") == "link/main.sakura link/util/deep/x.sakura link/util/text.sakura");
t.expects(found(&planted, "l*") == "link loop");
t.expects(found(&planted, "**/main.sakura") == "src/main.sakura");
# A link leading around in a circle is passed over.
t.expects(found(&planted, "loop/*") == "" && found(&planted, "*/x") == "");
}
@test def a_glob_from_a_root_finds_from_there(t: &mut tester, planted: tree): void {
var rooted := glob::escape(planted.at.view());
rooted.append("/src/*.sakura");
t.expects(found(&planted, rooted.view()) == "src/main.sakura");
val made := glob::pattern::parse(rooted.view()) else (_) { t.expects(false); return; };
val elsewhere := path::parse("elsewhere") else (_) { t.expects(false); return; };
var got := made.find(&elsewhere);
if got is value(&paths) {
t.expects(paths.length == 1 && paths[0].is_absolute);
} else {
t.expects(false);
}
}
@test def a_directory_that_cannot_be_read_stops_the_search(t: &mut tester, planted: tree): void {
when os != linux {
return;
}
val locked := planted.at.join("locked");
_ = io::create_directory(&locked);
val inside := locked.join("inside.sakura");
_ = io::write_file(&inside, "");
_ = io::set_permissions(&locked, 0);
# Where it can be read anyway, as by the superuser, there's nothing to test.
if io::directory::open(&locked) is error(_) {
t.expects(found(&planted, "locked/*") == $"`{locked.view()}` could not be read: permission_denied");
t.expects(found(&planted, "**/*.sakura").starts_with("`"));
t.expects(found(&planted, "*.txt") == "b.txt src-old.txt");
}
_ = io::set_permissions(&locked, 0o755);
}
# Every path of the tree, but through links, relative to it, as `**` finds them
# with hidden names.
def everything(planted: &tree): vector<string> {
var all := vector::<string>::new();
val made := glob::pattern::parse("**", glob::options { hidden = true, folds_case = false }) else (_) { return all; };
var got := made.find(&planted.at);
if got is value(&paths) {
for &each in paths {
if each.relative_to(&planted.at) is some(&relative) {
all.append(forward(relative.view()));
}
}
}
return all;
}
@test def what_is_found_is_what_matches(t: &mut tester, planted: tree): void {
val all := everything(&planted);
t.expects(all.length > 15);
for text in ["**/*.sakura", "src/**", "**/util/*", "*.txt", "{src,test}/**/*.sakura", "**/[a-m]*", "?.sakura", "**/.*/*"] {
val made := glob::pattern::parse(text, glob::options { folds_case = false }) else (_) { t.expects(false); continue; };
var matched := string::new(nothing {});
for &each in all {
continue if !made.matches(each.view());
if matched.length != 0 {
matched.push(' ');
}
matched.append(each.view());
}
t.expects(found(&planted, text).view() == matched.view(), text);
}
}
+166
View File
@@ -0,0 +1,166 @@
# Tests of reading globs and matching text against them: each wildcard, sets,
# `**`, braces, escapes, hidden names, case, roots, directories, the mistakes a
# glob can hold, and `escape`.
import std::io::glob;
import std::testing;
# Whether a glob matches text, read with the options, which by default tell
# cases apart on every system.
def fits(text: strview, path: strview, settings: glob::options = glob::options { folds_case = false }): bool {
val made := glob::pattern::parse(text, settings) else (_) { return false; };
return made.matches(path);
}
# Whether reading a glob fails with a kind of mistake, at a byte.
def fails_with(text: strview, kind: glob::error_kind, offset: u64): bool {
match glob::pattern::parse(text) {
value(&_) => return false;
error(e) => return e.kind == kind && e.offset == offset;
}
return false;
}
@test def a_star_matches_any_run_within_a_name(t: &mut tester): void {
t.expects(fits("*.c", "a.c") && fits("*.c", "abc.c") && fits("*", "x"));
t.expects(!fits("*.c", "a.h") && !fits("*.c", "dir/a.c"));
t.expects(fits("a*", "a") && fits("*a*b*c", "xaybzc") && fits("*a*b*c", "abc"));
t.expects(!fits("*a*b*c", "acb") && !fits("a*b", "a/b"));
# Stars take back what they took, but only the last seen needs to.
t.expects(!fits("a*a*a*a*b", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
t.expects(fits("*?", "a") && !fits("*?", ""));
# More than two stars, or two within a name, are one.
t.expects(fits("a***b", "axyzb") && fits("a**b", "axyzb") && !fits("a**b", "ax/yb"));
}
@test def a_question_mark_matches_one_character(t: &mut tester): void {
t.expects(fits("?.c", "a.c") && !fits("?.c", "ab.c") && !fits("?.c", ".c"));
# A character is a code point, of however many bytes.
t.expects(fits("?", "é") && fits("?", "日") && fits("?", "😀") && !fits("??", "é"));
t.expects(fits("a?c", "a日c") && fits("*?本", "日本"));
# A star takes whole characters, never half of one.
t.expects(!fits("*\xA9", "é") && !fits("*\xA9", "\xC3\xC3\xA9") && fits("*\xA9", "a\xA9"));
# A byte that starts none is one of its own.
t.expects(fits("?", "\xFF") && fits("a?b", "a\xFFb") && !fits("?", "\xFF\xFF"));
}
@test def a_set_matches_one_character_of_its_own(t: &mut tester): void {
t.expects(fits("[abc].c", "b.c") && !fits("[abc].c", "d.c"));
t.expects(fits("[a-c]x", "bx") && !fits("[a-c]x", "dx"));
t.expects(fits("[!a-c]x", "dx") && !fits("[!a-c]x", "ax") && fits("[^a]x", "bx"));
# A `]` first is one, as is a `-` first or last.
t.expects(fits("[]]x", "]x") && fits("[!]]x", "ax") && !fits("[!]]x", "]x"));
t.expects(fits("[a-]x", "-x") && fits("[-a]x", "-x") && !fits("[a-]x", "bx"));
# Escapes and characters of more than a byte.
t.expects(fits("[\\]]", "]") && fits("[\\!a]", "!"));
t.expects(fits("[é-ë]", "ê") && !fits("[é-ë]", "e") && fits("[日本]", "本"));
# A set never matches the `.` starting a hidden name.
t.expects(!fits("[.]x", ".x") && fits("[.]x", ".x", glob::options { hidden = true, folds_case = false }));
}
@test def two_stars_match_any_number_of_names(t: &mut tester): void {
t.expects(fits("src/**/*.sakura", "src/a.sakura") && fits("src/**/*.sakura", "src/a/b/c.sakura"));
t.expects(!fits("src/**/*.sakura", "lib/a.sakura") && !fits("src/**/*.sakura", "src/.git/a.sakura"));
t.expects(fits("**", "a") && fits("**", "a/b/c") && fits("**/x", "x") && fits("**/x", "a/b/x"));
t.expects(fits("a/**", "a") && fits("a/**", "a/b/c") && !fits("a/**", "b"));
t.expects(fits("a/**/b/**/c", "a/b/c") && fits("a/**/b/**/c", "a/x/b/y/b/z/c") && !fits("a/**/b/**/c", "a/c"));
t.expects(fits("**/**/x", "x") && fits("**/**/x", "a/b/x"));
# `.` alone, or a root alone, is matched only by a glob naming it.
t.expects(!fits("**", ".") && !fits("**", "") && fits(".", ".") && fits("/", "/") && !fits("/**", "/"));
}
@test def braces_make_globs_of_their_own(t: &mut tester): void {
t.expects(fits("{src,test}/*.sakura", "src/a.sakura") && fits("{src,test}/*.sakura", "test/a.sakura"));
t.expects(!fits("{src,test}/*.sakura", "lib/a.sakura"));
t.expects(fits("a{b,{c,d}}e", "abe") && fits("a{b,{c,d}}e", "ace") && fits("a{b,{c,d}}e", "ade"));
t.expects(fits("{a,b}{c,d}", "bd") && fits("{,x}y", "y") && fits("{,x}y", "xy"));
t.expects(fits("{a/b,c}/d", "a/b/d") && fits("{a/b,c}/d", "c/d") && !fits("{a/b,c}/d", "a/d"));
t.expects(fits("x{a}", "xa") && fits("{[,]}", ",") && fits("{a\\,b,c}", "a,b"));
}
@test def escapes_match_what_they_escape(t: &mut tester): void {
t.expects(fits("\\*", "*") && !fits("\\*", "a") && fits("a\\?b", "a?b") && !fits("a\\?b", "axb"));
t.expects(fits("\\{a,b\\}", "{a,b}") && fits("\\[a]", "[a]") && fits("a\\\\b", "a\\b"));
# An escaped `/` still separates names.
t.expects(fits("a\\/b", "a/b"));
}
@test def hidden_names_are_matched_only_by_a_dot(t: &mut tester): void {
val hidden := glob::options { hidden = true, folds_case = false };
t.expects(fits(".*", ".git") && !fits("*", ".git") && fits(".git/*", ".git/config"));
t.expects(!fits("**/x", ".a/x") && fits("**/x", ".a/x", hidden) && fits("*", ".git", hidden));
# Neither `.` nor `..` is ever a wildcard's.
t.expects(!fits("*", "..", hidden) && !fits("?", ".", hidden) && !fits("**/x", "../x", hidden));
t.expects(fits("..", "..") && fits("../*.c", "../a.c"));
}
@test def letters_match_in_either_case_where_asked(t: &mut tester): void {
val folded := glob::options { folds_case = true };
t.expects(!fits("*.TXT", "a.txt") && fits("*.TXT", "a.txt", folded));
t.expects(fits("[A-C]", "b", folded) && fits("[!a-c]", "D", folded) && !fits("[!a-c]", "B", folded));
t.expects(fits("SRC/*", "src/a", folded) && !fits("SRC/*", "src/a"));
t.expects(fits("É", "É", folded) && !fits("é", "É", folded));
}
@test def roots_and_directories_are_matched_too(t: &mut tester): void {
t.expects(fits("/usr/*", "/usr/lib") && !fits("/usr/*", "usr/lib") && !fits("*", "/usr"));
t.expects(fits("*/", "src/") && !fits("*/", "src") && fits("src", "src/"));
t.expects(fits("a//b", "a/b") && fits("./a/*", "a/x") && fits("a/*", "a/./x") && fits("a/b", "a//b"));
val made := glob::pattern::parse("*/") else (_) { return; };
t.expects(made.directories && made.text == "*/");
}
@test def a_glob_without_wildcards_is_literal(t: &mut tester): void {
for text in ["src/main.sakura", "a\\*b", "/usr/lib", "."] {
val made := glob::pattern::parse(text) else (_) { t.expects(false); continue; };
t.expects(made.is_literal);
}
for text in ["src/*.c", "{a,b}", "a?", "[ab]", "**"] {
val made := glob::pattern::parse(text) else (_) { t.expects(false); continue; };
t.expects(!made.is_literal);
}
}
@test def mistakes_are_found_where_they_are(t: &mut tester): void {
t.expects(fails_with("", glob::error_kind::empty, 0));
t.expects(fails_with("a\\", glob::error_kind::trailing_escape, 1));
t.expects(fails_with("x[ab", glob::error_kind::unclosed_set, 1));
t.expects(fails_with("[]", glob::error_kind::unclosed_set, 0));
t.expects(fails_with("{a,{b}", glob::error_kind::unclosed_brace, 0));
t.expects(fails_with("a}", glob::error_kind::unopened_brace, 1));
t.expects(fails_with("{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}", glob::error_kind::too_many_choices, 0));
t.expects(!fails_with("{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}", glob::error_kind::too_many_choices, 0));
# A brace or escape within a set is the set's.
t.expects(fits("[{]", "{") && fits("[}]", "}"));
match glob::pattern::parse("a}") {
value(&_) => t.expects(false);
error(e) => t.expects(e.describe() == "A `}` has no `{` opening it. (at byte 1)");
}
}
@test def escaped_text_matches_only_itself(t: &mut tester): void {
val escaped := glob::escape("notes[1].txt");
t.expects(escaped == "notes\\[1\\].txt");
for text in ["notes[1].txt", "a*b?c", "{x,y}", "back\\slash", "]!^-"] {
val made := glob::pattern::parse(glob::escape(text)) else (_) { t.expects(false); continue; };
t.expects(made.is_literal);
when os == windows {
continue;
}
t.expects(made.matches(text));
}
}
+294
View File
@@ -0,0 +1,294 @@
# Tests of streams: what reads and writes bytes, the buffered readers and writers over
# any of them, and what owns or borrows what it reads or writes.
import std::io;
import system;
import std::testing;
# A file of a test's own, removed where the test returns.
struct scratch : fixture<scratch>, owning {
var at: path;
}
# Makes a file no other run has, by creating it only where nothing is.
def scratch::setup(t: &mut tester): scratch {
# Windows keeps its temporary files where `TEMP` says.
when os == windows {
for n in 0..10000 {
val named := path::parse($"{temporary()}\\sakura-streams-{n}.txt") else (_) { break; };
var at := io::absolute(&named) else (_) { break; };
val flags := open_flags::write | open_flags::create | open_flags::exclusive;
val made := io::file::open(&at, flags) else (_) { continue; };
return scratch { at = move(at) };
}
}
for n in 0..10000 {
var at := path::parse($"/tmp/sakura-streams-{n}.txt") else (_) { break; };
val flags := open_flags::write | open_flags::create | open_flags::exclusive;
val made := io::file::open(&at, flags) else (_) { continue; };
return scratch { at = move(at) };
}
system::abort();
return scratch {};
}
def scratch::close(&mut this): void {
_ = io::remove(&this.at);
}
# How many counted streams have been closed.
var counted_closed: u64 = 0;
# A stream that counts what is written to it and gives what it holds to read, and
# that closes, as a file does.
struct counted : readable, writable, owning {
var open: bool;
var written: u64;
var left: strview;
}
def counted::read(&mut this, into: slice<u8>): result<u64, io_error> {
if !this.open {
return io_error::invalid;
}
return this.left.read(into);
}
def counted::write(&mut this, data: span<u8>): result<void, io_error> {
if !this.open {
return io_error::invalid;
}
this.written += data.length;
return;
}
def counted::close(&mut this): void {
if this.open {
counted_closed++;
this.open = false;
}
}
# Which of the stream traits a type has, as bits: readable, writable, flushable, and
# seekable, from the lowest.
def streams_of<T>(): u8 {
var bits: u8 = 0;
if const T is readable {
bits = bits | 1;
}
if const T is writable {
bits = bits | 2;
}
if const T is flushable {
bits = bits | 4;
}
if const T is seekable {
bits = bits | 8;
}
return bits;
}
# Reads lines, and writes each with its length, through whatever is given.
def answer<S>(input: &mut io::reader<S>, out: &mut writable): void where S: readable {
for line in input.lines() {
_ = out.write($"{line.length}:{line};");
}
}
@test def streams_are_what_they_read_and_write(t: &mut tester): void {
t.expects(streams_of::<io::file>() == 11 && streams_of::<io::console>() == 3);
t.expects(streams_of::<io::reader<io::file>>() == 1 && streams_of::<io::writer<io::file>>() == 6);
t.expects(streams_of::<string>() == 2 && streams_of::<strview>() == 1);
# A reference that writes has the traits of what it refers to, and one that only
# reads has none, since reading and writing move a stream along. A pointer has none.
t.expects(streams_of::<&mut io::file>() == 11 && streams_of::<&mut io::writer<string>>() == 6);
t.expects(streams_of::<&io::file>() == 0 && streams_of::<&strview>() == 0);
t.expects(streams_of::<*mut io::file>() == 0);
}
@test def streams_copy_into_one_another(t: &mut tester, s: scratch): void {
var opened := io::file::open(&s.at, open_flags::read | open_flags::write) else (_) {
t.expects(false);
return;
};
var text: strview = "copied through a file\n";
val wrote := io::copy_all(&mut text, &mut opened) else (_) { t.expects(false); return; };
t.expects(wrote == 22 && text.length == 0);
_ = opened.seek(0);
var said := string::new(nothing {});
val read := io::copy_all(&mut opened, &mut said) else (_) { t.expects(false); return; };
t.expects(read == 22 && said.view() == "copied through a file\n");
# Arguments are referred to as the parameters ask, and a stream behind a pointer is
# given through `through`.
var again: strview = "again";
val p := (&mut said) as *mut string;
_ = io::copy_all(again, through(p));
t.expects(said.view() == "copied through a file\nagain" && again.length == 0);
var rest: strview = "all of the rest";
val all := io::read_all(&mut rest) else (_) { t.expects(false); return; };
t.expects(all.view() == "all of the rest");
}
@test def readers_read_lines_of_any_stream(t: &mut tester): void {
var input := io::reader_of("first\r\nsecond\n\nlast");
var seen := string::new(nothing {});
var count := 0u;
for line in input.lines() {
seen.append(line.view());
seen.append("|");
count++;
}
t.expects(seen.view() == "first|second||last|" && count == 4 && input.error is none);
var bytes := io::reader_of("0123456789");
val four := bytes.read_exactly(4) else (_) { t.expects(false); return; };
val rest := bytes.read_all() else (_) { t.expects(false); return; };
t.expects(four.view() == "0123" && rest.view() == "456789");
t.expects(bytes.read_exactly(1).error == io_error::unexpected_end);
# Borrowed, the view read is the caller's, which the reader moves along.
var text: strview = "a\nb\n";
{
var borrowed := io::reader_of(&mut text);
_ = borrowed.read_line();
}
t.expects(text.length == 0);
# The same function reads text in a test that reads the console in a program.
var asked := io::reader_of("2 + 2\n3 * 4\n");
var said := string::new(nothing {});
answer(&mut asked, &mut said);
t.expects(said.view() == "5:2 + 2;5:3 * 4;");
}
@test def writers_write_to_any_stream(t: &mut tester): void {
var said := string::new(nothing {});
{
var out := io::writer_of(&mut said);
_ = out.write("held ");
_ = out.write_line("then written");
t.expects(said.length == 0);
_ = out.flush();
t.expects(said.view() == "held then written\n");
_ = out.write("at close");
}
t.expects(said.view() == "held then written\nat close");
val as_trait: &mut writable = &mut said;
{
var out := io::writer_of(as_trait);
_ = out.write("!");
}
t.expects(said.view().ends_with("!"));
# What is too large to hold goes straight through, after what was held.
var big := string::new(nothing {});
var filler := string::new(nothing {});
for _ in 0..20000 {
filler.push('x');
}
{
var out := io::writer_of(&mut big);
_ = out.write("a");
_ = out.write(filler.view());
t.expects(big.length == 20001 && big[0] == 'a');
}
}
@test def writers_flush_what_they_write_to(t: &mut tester): void {
var said := string::new(nothing {});
var inner := io::writer_of(&mut said);
{
var outer := io::writer_of(&mut inner);
_ = outer.write("stacked");
t.expects(said.length == 0);
_ = outer.flush();
t.expects(said.view() == "stacked");
}
}
@test def readers_and_writers_close_what_they_own(t: &mut tester): void {
counted_closed = 0;
{
var out := io::writer_of(counted { open = true });
_ = out.write("abc");
}
t.expects(counted_closed == 1);
# Closed by hand, a writer writes what it holds and closes what it owns at once,
# and its scope ending closes nothing twice.
{
var out := io::writer_of(counted { open = true });
_ = out.write("abcd");
out.close();
t.expects(counted_closed == 2 && out._sink.written == 4);
}
t.expects(counted_closed == 2);
# Borrowing, they close nothing, by hand or not.
var kept := counted { open = true, left = "kept\n" };
{
var out := io::writer_of(&mut kept);
_ = out.write("ef");
out.close();
var input := io::reader_of(&mut kept);
val line := input.read_line() else { t.expects(false); return; };
t.expects(line.view() == "kept");
}
t.expects(counted_closed == 2 && kept.open && kept.written == 2);
# Moved from, one writes nothing and closes nothing, and the one moved to closes.
{
var a := io::writer_of(counted { open = true });
var b := move(a);
t.expects(a.write("x").error == io_error::invalid);
_ = b.write("y");
}
t.expects(counted_closed == 3);
{
var input := io::reader_of(counted { open = true, left = "read" });
val all := input.read_all() else (_) { t.expects(false); return; };
t.expects(all.view() == "read");
}
t.expects(counted_closed == 4);
# Closing the standard output closes nothing of the console, which `output()`
# lends again.
io::output().close();
var info: file_info;
val handle: system::fd = system::fd::stdout;
t.expects(handle.stat(&mut info) == 0 && io::output().write("") is value);
}
@test def readers_and_writers_take_files_over(t: &mut tester, s: scratch): void {
{
var made := io::file::create(&s.at) else (_) { t.expects(false); return; };
var out := io::writer_of(move(made));
t.expects(!made.is_open);
for i in 0..3000 {
_ = out.write($"{i % 10}");
}
_ = out.write_line("!");
t.expects(io::info(&s.at).value.size == 0);
}
t.expects(io::info(&s.at).value.size == 3002);
var opened := io::file::open(&s.at) else (_) { t.expects(false); return; };
{
var input := io::reader_of(&mut opened);
val all := input.read_all() else (_) { t.expects(false); return; };
t.expects(all.length == 3002 && all.view().ends_with("789!\n"));
}
t.expects(opened.is_open);
_ = opened.seek(0);
var input := io::reader_of(move(opened));
val first := input.read_exactly(3) else (_) { t.expects(false); return; };
t.expects(first.view() == "012" && !opened.is_open);
}
+68
View File
@@ -0,0 +1,68 @@
# JSON's conformance, by Nicolas Seriot's JSONTestSuite, whose parsing cases are in
# `tests/json/parsing` under its MIT license. Each `y_` case must be accepted, and each
# `n_` case refused. RFC 8259 leaves the `i_` cases to the parser.
import std::io;
import std::json;
import std::testing;
# The `i_` cases that are accepted: numbers too large or too small for any type,
# which reading them as one refuses, and nesting within the limit. Every other is
# refused: text that is not UTF-8, half of a surrogate pair, UTF-16, and a byte
# order mark before the value.
const accepted: span<strview> = [
"i_number_double_huge_neg_exp.json",
"i_number_huge_exp.json",
"i_number_neg_int_huge_exp.json",
"i_number_pos_double_huge_exp.json",
"i_number_real_neg_overflow.json",
"i_number_real_pos_overflow.json",
"i_number_real_underflow.json",
"i_number_too_big_neg_int.json",
"i_number_too_big_pos_int.json",
"i_number_very_big_negative_int.json",
"i_structure_500_nested_arrays.json",
];
def is_accepted(name: strview): bool {
for each in accepted {
if each == name {
return true;
}
}
return false;
}
@test def json_conforms_to_its_test_suite(t: &mut tester): void {
val folder := path::parse("tests/json/parsing") else (_) {
t.expects(false);
return;
};
var listing := io::directory::open(&folder) else (e) {
print("The suite is read from `tests/json/parsing`, so the tests run from the root of the repository.\n");
t.expects(false);
return;
};
var checked: u64 = 0;
while listing.next() is some(each) {
val name: strview = each.name;
if !name.ends_with(".json") {
continue;
}
val at := folder.join(name);
val text := io::read_file(&at) else (_) {
t.expects(false);
continue;
};
val parsed := json::parse(text.view()) is value;
val wanted := name[0] == 'y' || (name[0] == 'i' && is_accepted(name));
if parsed != wanted {
print($"{name} is {parsed ? "accepted" : "refused"}\n");
}
t.expects(parsed == wanted);
checked++;
}
t.expects(checked == 318);
}
+406
View File
@@ -0,0 +1,406 @@
# Tests of `std::json`: its text, the reader, the document, and the writer.
import std::io;
import std::json;
import std::testing;
import system;
# Whether parsing the text fails with the kind of error, at the line and column.
def fails_at(text: strview, kind: json::error_kind, line: u32, column: u32): bool {
match json::parse(text) {
value(&_) => return false;
error(e) => return e.kind == kind && e.line == line && e.column == column;
}
return false;
}
# The text a document's root is written again as, on one line.
def rewritten(text: strview): string {
val doc := json::parse(text) else (e) { return e.describe(); };
var out := json::writer::new();
json::encode(&doc.root, &mut out);
val written := out.finish() else (e) { return e.describe(); };
return string::from(written, nothing {});
}
# The bits of a float, which tell `-0` from `0` and compare exactly.
def bits(x: f64): u64 {
var copy: f64 = x;
return *(((&copy) as *f64) as *u64);
}
@test def json_escapes_text_and_checks_utf8(t: &mut tester): void {
var out := string::new(nothing {});
t.expects(json::escape("plain é \"quoted\" back\\slash\n\t\x01\x1F", &mut out));
t.expects(out.view() == "plain é \\\"quoted\\\" back\\\\slash\\n\\t\\u0001\\u001f");
var back := string::new(nothing {});
json::unescape("a\\u00e9\\ud83d\\ude00\\n\\/\\\\\\\"\\b\\f\\r\\t", &mut back);
t.expects(back.view() == "aé😀\n/\\\"\x08\x0C\r\t");
# Overlong forms, surrogates, and characters past U+10FFFF are not UTF-8.
t.expects(json::is_utf8("é😀\xEF\xBF\xBF\xF4\x8F\xBF\xBF"));
t.expects(!json::is_utf8("\xC0\x80") && !json::is_utf8("\xE0\x80\x80") && !json::is_utf8("\xED\xA0\x80"));
t.expects(!json::is_utf8("\xF4\x90\x80\x80") && !json::is_utf8("\xE2\x82") && !json::is_utf8("\x80"));
var cut := string::new(nothing {});
t.expects(!json::escape("ok\xFFno", &mut cut));
t.expects(cut.view() == "ok");
}
@test def json_reader_gives_tokens(t: &mut tester): void {
var tokens := json::reader::new(" {\"a\\n\": [1, -2.5e3, true, false, null, \"x\"]} ");
var kinds := string::new(nothing {});
while tokens.next() is some(read) {
kinds.append($"{read.kind}:{read.view} ");
}
t.expects(tokens.error is none);
t.expects(kinds.view() == "begin_object:{ key:a\\n begin_array:[ number:1 number:-2.5e3 boolean:true boolean:false empty:null text:x end_array:] end_object:} ");
# A key's escapes are left for `unescape`, and the token says it holds some.
var keyed := json::reader::new("{\"a\\n\": 1}");
_ = keyed.next();
val key := keyed.next().some;
t.expects(key.kind == json::token_kind::key && key.escaped && key.offset == 1);
# Skipping a value reads past everything it holds.
var skim := json::reader::new("{\"params\": {\"deep\": [1, [2, {}]]}, \"method\": \"m\"}");
_ = skim.next();
_ = skim.next();
t.expects(skim.skip());
t.expects(skim.next().some.view == "method" && skim.next().some.view == "m");
}
@test def json_reader_stops_at_the_first_error(t: &mut tester): void {
var tokens := json::reader::new("[1, 2,]");
var count := 0;
while tokens.next() is some(_) {
count++;
}
t.expects(count == 3);
t.expects(tokens.error.some.kind == json::error_kind::unexpected_byte && tokens.error.some.column == 7);
t.expects(tokens.next() is none);
}
@test def json_nesting_is_limited(t: &mut tester): void {
t.expects(json::parse("[[[1]]]", 3) is value);
match json::parse("[[[[1]]]]", 3) {
value(&_) => t.expects(false);
error(e) => t.expects(e.kind == json::error_kind::too_deep && e.column == 4);
}
# Past 512 levels, a reader given a higher limit keeps what is open elsewhere.
var deep := string::new(nothing {});
for _ in 0..600 { deep.append("[{\"k\":"); }
deep.append("1");
for _ in 0..600 { deep.append("}]"); }
t.expects(json::parse(deep.view()) is error);
t.expects(json::parse(deep.view(), 1200) is value);
}
@test def json_parse_errors_say_where(t: &mut tester): void {
t.expects(fails_at("", json::error_kind::unexpected_end, 1, 1));
t.expects(fails_at("{\"a\": 1,\n \"b\" 2}", json::error_kind::unexpected_byte, 2, 6));
t.expects(fails_at("[1, 2", json::error_kind::unexpected_end, 1, 6));
t.expects(fails_at("[01]", json::error_kind::invalid_number, 1, 2));
t.expects(fails_at("[1.]", json::error_kind::invalid_number, 1, 2));
t.expects(fails_at("[.5]", json::error_kind::unexpected_byte, 1, 2));
t.expects(fails_at("[-]", json::error_kind::invalid_number, 1, 2));
t.expects(fails_at("[1e]", json::error_kind::invalid_number, 1, 2));
t.expects(fails_at("[\"a\\x\"]", json::error_kind::invalid_escape, 1, 4));
t.expects(fails_at("[\"\\ud800\"]", json::error_kind::invalid_escape, 1, 3));
t.expects(fails_at("[\"\\udc00\"]", json::error_kind::invalid_escape, 1, 3));
t.expects(fails_at("[\"tab\there\"]", json::error_kind::unexpected_byte, 1, 6));
t.expects(fails_at("[\"\xC0\x80\"]", json::error_kind::invalid_utf8, 1, 3));
t.expects(fails_at("{\"a\": tru}", json::error_kind::unexpected_byte, 1, 7));
t.expects(fails_at("[nul", json::error_kind::unexpected_end, 1, 2));
t.expects(fails_at("{} {}", json::error_kind::trailing_text, 1, 4));
t.expects(fails_at("[1,]", json::error_kind::unexpected_byte, 1, 4));
t.expects(fails_at("{\"a\":1,}", json::error_kind::unexpected_byte, 1, 8));
t.expects(fails_at("NaN", json::error_kind::unexpected_byte, 1, 1));
val failed := json::parse("[1,\n x]") else (e) {
t.expects(e.describe().view() == "2:3: A byte stands where JSON allows none of its kind.");
return;
};
t.expects(false);
}
@test def json_documents_keep_every_member(t: &mut tester): void {
val doc := json::parse("{\"id\": 1, \"name\": \"a\", \"id\": 2, \"n\\u0061me\": \"b\", \"id\": 3}") else (e) {
t.expects(false);
return;
};
val root := doc.root;
t.expects(root.kind == json::kind::object && root.length == 5);
t.expects(root.get("id").some.as_i64().value == 1);
t.expects(root.get("missing") is none);
var ids: i64 = 0;
for each in root.get_all("id") {
ids = ids * 10 + each.as_i64().value;
}
t.expects(ids == 123);
# Escaped names are found by their decoded text, and every member is given in order.
var names := string::new(nothing {});
for each in root.get_all("name") {
names.append(each.as_text().value);
}
t.expects(names.view() == "ab");
var keys := string::new(nothing {});
for each in root.members() {
keys.append(each.key);
keys.push(' ');
}
t.expects(keys.view() == "id name id name id ");
}
@test def json_values_are_read_by_kind(t: &mut tester): void {
val doc := json::parse("[null, true, false, 0, \"s\", [1, 2], {\"k\": [3]}]") else (e) {
t.expects(false);
return;
};
val root := doc.root;
t.expects(root.length == 7 && root.at(7) is none && root.get("k") is none);
t.expects(root.at(0).some.is_null && root.at(1).some.as_bool().value && !root.at(2).some.as_bool().value);
t.expects(root.at(4).some.as_text().value == "s" && root.at(4).some.length == 0);
t.expects(root.at(6).some.get("k").some.at(0).some.as_u64().value == 3);
var total: i64 = 0;
for item in root.at(5).some.elements() {
total += item.as_i64().value;
}
t.expects(total == 3);
# A value of the wrong kind says where it is.
match root.at(4).some.as_i64() {
value(_) => t.expects(false);
error(e) => t.expects(e.kind == json::error_kind::wrong_kind && e.line == 1 && e.column == 24);
}
t.expects(root.at(0).some.as_bool() is error && root.as_text() is error);
t.expects(root.at(4).some.elements().next() is none && root.members().next() is none);
}
@test def json_integers_read_exactly(t: &mut tester): void {
val doc := json::parse("""
[1e3, 1.50e1, 1.5, 1e-1, -0, 0e99999, 9223372036854775807, -9223372036854775808,
9223372036854775808, 18446744073709551615, 18446744073709551616, -1, 12.000, 1e19, 1e20]
""") else (e) {
t.expects(false);
return;
};
val at := doc.root;
t.expects(at.at(0).some.as_i64().value == 1000 && at.at(1).some.as_i64().value == 15);
t.expects(at.at(2).some.as_i64().error.kind == json::error_kind::wrong_kind);
t.expects(at.at(3).some.as_i64().error.kind == json::error_kind::wrong_kind);
t.expects(at.at(4).some.as_u64().value == 0 && at.at(5).some.as_i64().value == 0);
t.expects(at.at(6).some.as_i64().value == 9223372036854775807);
t.expects(at.at(7).some.as_i64().value == -9223372036854775807 - 1);
t.expects(at.at(8).some.as_i64().error.kind == json::error_kind::out_of_range);
t.expects(at.at(8).some.as_u64().value == 9223372036854775808);
t.expects(at.at(9).some.as_u64().value == 18446744073709551615);
t.expects(at.at(10).some.as_u64().error.kind == json::error_kind::out_of_range);
t.expects(at.at(11).some.as_u64().error.kind == json::error_kind::out_of_range && at.at(11).some.as_i64().value == -1);
t.expects(at.at(12).some.as_i64().value == 12);
t.expects(at.at(13).some.as_u64().value == 10000000000000000000 && at.at(14).some.as_u64() is error);
}
@test def json_floats_read_back_exactly(t: &mut tester): void {
const written: span<f64> = [0.1, 5e-324, 2.2250738585072014e-308, 1.7976931348623157e308, 9007199254740993.0,
-0.0, 1e21, 1e-7, 123456789012345680000.0, 0.30000000000000004, 3.0, -2.5e-300];
var out := json::writer::new();
out.begin_array();
for x in written {
out.real(x);
}
out.end_array();
val text := out.finish() else (e) {
t.expects(false);
return;
};
val doc := json::parse(text) else (e) {
t.expects(false);
return;
};
for index, x in written {
t.expects(bits(doc.root.at(index).some.as_f64().value) == bits(x));
}
t.expects(doc.root.at(4).some.as_f64().value == 9007199254740992.0);
val huge := json::parse("[1e400, 1e-400]") else (e) {
t.expects(false);
return;
};
t.expects(huge.root.at(0).some.as_f64().error.kind == json::error_kind::out_of_range);
t.expects(huge.root.at(1).some.as_f64().value == 0.0);
}
@test def json_writer_writes_compactly_and_indented(t: &mut tester): void {
var out := json::writer::new();
out.begin_object();
out.member("jsonrpc"); out.text("2.0");
out.member("id"); out.unsigned(7);
out.member("result");
out.begin_array();
out.signed(-12); out.boolean(false); out.empty(); out.begin_object(); out.end_object(); out.begin_array(); out.end_array();
out.end_array();
out.end_object();
t.expects(out.finish().value == "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":[-12,false,null,{},[]]}");
var pretty := json::writer::indented(2);
pretty.begin_object();
pretty.member("a"); pretty.begin_array(); pretty.signed(1); pretty.signed(2); pretty.end_array();
pretty.member("b"); pretty.begin_object(); pretty.end_object();
pretty.end_object();
t.expects(pretty.finish().value == "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}");
# A writer is emptied to write another value.
out.clear();
out.text("again");
t.expects(out.finish().value == "\"again\"");
# The extremes of the integers write as they are.
out.clear();
out.begin_array(); out.signed(-9223372036854775807 - 1); out.unsigned(18446744073709551615); out.signed(0); out.end_array();
t.expects(out.finish().value == "[-9223372036854775808,18446744073709551615,0]");
}
# A stream that takes only so many bytes, then fails, as a full disk does.
struct refusing : writable {
var left: u64;
}
def refusing::write(&mut this, data: span<u8>): result<void, io_error> {
if data.length > this.left {
return io_error::no_space;
}
this.left -= data.length;
return;
}
# Writes a document larger than a writer holds before it passes its text on.
def write_records(out: &mut json::writer): void {
out.begin_array();
for i in 0..3000 {
out.begin_object();
out.member("n"); out.unsigned(i as u64);
out.member("name"); out.text("élément");
out.end_object();
}
out.end_array();
}
@test def json_writer_passes_its_text_to_a_stream(t: &mut tester): void {
var whole := json::writer::indented(2);
write_records(&mut whole);
val text := whole.finish() else (_) { t.expects(false); return; };
var said := string::new(nothing {});
var streamed := json::writer::to(&mut said, 2);
write_records(&mut streamed);
t.expects(said.length >= 16384 && said.length < text.length);
val rest := streamed.finish() else (_) { t.expects(false); return; };
t.expects(rest.length == 0 && said.view() == text);
# A typed value, through a writer that holds what it is given in turn.
var numbers := vector::<u64>::new();
for i in 0..5000 {
numbers.append((i * 7) as u64);
}
val expected := json::to_text(&numbers) else (_) { t.expects(false); return; };
var buffered := string::new(nothing {});
{
var out := io::writer_of(&mut buffered);
json::write_to(&numbers, &mut out) else (_) { t.expects(false); return; };
_ = out.flush();
}
t.expects(buffered.view() == expected.view() && buffered.length > 16384);
# A stream that fails is kept as its failure, and what is written after is let go.
var refused := refusing { left = 10 };
var failing := json::writer::to(&mut refused);
write_records(&mut failing);
t.expects(failing.finish().error.kind == json::error_kind::not_written && refused.left == 10);
t.expects(json::write_to(&numbers, &mut refused).error.kind == json::error_kind::not_written);
}
@test def json_writer_keeps_failures_in_the_data(t: &mut tester): void {
var out := json::writer::new();
out.begin_array();
out.real(1.0 / 0.0);
out.real(0.0 / 0.0);
out.text("ok\xFF");
out.end_array();
match out.finish() {
value(_) => t.expects(false);
error(e) => t.expects(e.kind == json::error_kind::not_finite && e.line == 0);
}
t.expects(out._text.view() == "[null,null,null]");
out.clear();
out.begin_object();
out.member("\xC0\x80");
out.signed(1);
out.end_object();
t.expects(out.finish().error.kind == json::error_kind::invalid_utf8);
t.expects(out._text.view() == "{\"\":1}");
}
@test def json_writer_writes_text_lossily_where_asked(t: &mut tester): void {
# Each byte that breaks UTF-8 is the escape of U+FFFD, a sequence cut short a
# byte at a time, and the escapes and characters around it are as ever.
var whole := string::new(nothing {});
t.expects(!json::escape("a\xC0\x80b\xE2\x82 é\x08", &mut whole, true));
t.expects(whole.view() == "a\\ufffd\\ufffdb\\ufffd\\ufffd é\\b");
var plain := string::new(nothing {});
t.expects(json::escape("é\n", &mut plain, true) && plain.view() == "é\\n");
# A lossy writer keeps no failure, in members' names or strings.
var out := json::writer::new();
out.set_lossy(true);
out.begin_object();
out.member("k\xFF");
out.text("ok\xFF");
out.end_object();
t.expects(out.finish().value == "{\"k\\ufffd\":\"ok\\ufffd\"}");
# Emptied, it stays lossy, and made strict again, it keeps the failure.
out.clear();
out.text("\xFF");
t.expects(out.finish().value == "\"\\ufffd\"");
out.clear();
out.set_lossy(false);
out.text("\xFF");
t.expects(out.finish().error.kind == json::error_kind::invalid_utf8);
}
@test def json_writer_writes_text_already_written(t: &mut tester): void {
# Text already written is a value, with the commas and names around it, and
# keeps its own spacing.
var out := json::writer::new();
out.begin_object();
out.member("jsonrpc"); out.text("2.0");
out.member("id"); out.raw("\"a\"");
out.member("result");
out.begin_array(); out.raw("{\"x\": [1, 2]}"); out.raw("null"); out.end_array();
out.end_object();
t.expects(out.finish().value == "{\"jsonrpc\":\"2.0\",\"id\":\"a\",\"result\":[{\"x\": [1, 2]},null]}");
var pretty := json::writer::indented(2);
pretty.begin_array(); pretty.raw("{\"a\":1}"); pretty.signed(2); pretty.end_array();
t.expects(pretty.finish().value == "[\n {\"a\":1},\n 2\n]");
out.clear();
out.raw("[]");
t.expects(out.finish().value == "[]");
}
@test def json_documents_are_written_again_whole(t: &mut tester): void {
val text: strview = "{\"a\":[1,-2,1.5,18446744073709551615,\"t\\u00e9\\n\",null,true,{}],\"b\":{\"c\":[]},\"a\":0}";
val once := rewritten(text);
t.expects(once.view() == "{\"a\":[1,-2,1.5,18446744073709551615,\"té\\n\",null,true,{}],\"b\":{\"c\":[]},\"a\":0}");
val twice := rewritten(once.view());
t.expects(twice.view() == once.view());
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Nicolas Seriot
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1 @@
[123.456e-789]
@@ -0,0 +1 @@
[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]
@@ -0,0 +1 @@
[-1e+9999]
@@ -0,0 +1 @@
[1.5e+9999]
@@ -0,0 +1 @@
[-123123e100000]
@@ -0,0 +1 @@
[123123e100000]
@@ -0,0 +1 @@
[123e-10000000]
@@ -0,0 +1 @@
[-123123123123123123123123123123]
@@ -0,0 +1 @@
[100000000000000000000]
@@ -0,0 +1 @@
[-237462374673276894279832749832423479823246327846]
@@ -0,0 +1 @@
{"\uDFAA":0}
@@ -0,0 +1 @@
["\uDADA"]
@@ -0,0 +1 @@
["\uD888\u1234"]
Binary file not shown.
Loaded 100 of 1625 files, more files were not shown because too many files have changed in this diff. Show more