Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 00:51:45 -05:00
commit b176c3d6d1
1625 files changed
+43245

No files matched your search

+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;
}