The Luce Base standard library
Generated by tools/library_reference.py from src/std/; the source is the reference. A module is reached with import name and used as name.thing, or from name import thing for its bare name (§16.6). Everything here is Base over extern declarations of system libraries; where a constant or a layout differs by target it is a branch on the platform module (§19.5), checked by tests/platform and the corresponding platform-specific program tests.
platform#
Generated by the compiler from --target and the package's manifest (§19.5, Target.module_text); this file is the placeholder the checker replaces when it reads the library. os re-exports the target's constants for programs; the standard library branches on them directly.
let name: str = "arm64-macos"— The target triple, such asarm64-macos.
let macos: bool = true— Whether the target operating system is macOS.
let linux: bool = false— Whether the target operating system is Linux.
let windows: bool = false— Whether the target operating system is Windows.
let posix: bool = true— Whether the target is a POSIX system.
let arm64: bool = true— Whether the target architecture is arm64.
let x86_64: bool = false— Whether the target architecture is x86-64.
let pointer_bits: u32 = 64— The width of a pointer on the target, in bits.
let cpu_level: u32 = 1— The instruction-set level the program is compiled for (§19.5): 1 is the family's baseline.
type SocketDescriptor = i32— The native socket ABI: pointer-sized on Windows, int on POSIX.
let program: str = "app"— The package this program is built from, as its manifest names it;appoutside any package.
let program_version: str = ""— That package's version, empty when its manifest gives none.
float_text#
The fewest significant digits that read back as the value, of those the closest (Ryu: Adams, "Ryu: Fast Float-to-String Conversion", PLDI 2018), each width with its own digits, laid out as double-conversion's ToShortest: decimal notation for a decimal exponent from -6 to 14, otherwise one digit, the rest after a point, and e with the exponent. Integer arithmetic only. strings' format_f64 writes this text, and a formatted string's float field this text with a .0 after digits that have no point (base.md §14). It comes before core and needs nothing else.
func write_f64(value: f64, text: u8[]) -> usize— The shortest text ofvalueintotext, at least 32 bytes:0.1,1e15,5e-324,-0,inf,-inf,nan. Its length.
func write_f32(value: f32, text: u8[]) -> usize— The f32 counterpart of write_f64: the f32's own shortest digits (0.1for 0.1f32).
func display_f64(value: f64, text: u8[]) -> usize— A formatted string's field ofvalue(base.md §14): write_f64's text, with.0after digits that have no point or exponent (5.0,-0.0,123456789012345.0). Its length.
func display_f32(value: f32, text: u8[]) -> usize— display_f64 for an f32: its own shortest digits.
numerals#
What a formatted string's {value:spec} field does (base.md §5.5), as Python's format does it: the specification read as CPython's parse_internal_render_format_spec reads it, a number laid out as calc_number_widths and fill_number lay it out, and a float's digits made exactly and rounded half to even, as David Gay's dtoa rounds them. The text goes to a Sink piece by piece, so nothing is allocated and nothing bounds a field but the sink. The compiler reads a field's specification with read and misfit and refuses one that does not fit; the program lays the field out with lay_integer, lay_float or lay_text. It is the one implementation: Luce lays out its fields and rounds math.round with it too, wording a misfit in its own terms from misfit_of (luce src/support/number_text.lucb), and the seed carries a copy of this file. It comes after float_text and before core, and needs nothing else.
Spec (struct)#
A specification read: [[fill]align][sign][z][#][0][width][grouping][.precision][type] (§5.5). A part not written is 0, -1 or empty, so a default can still be told apart.
var fill: str— The fill scalar, as written; empty when none was.var align: u8—<,>,^or=; 0 when none was written.var sign: u8—+,-or a space; 0 when none was written.var no_negative_zero: bool—z: a negative zero, after rounding, shows as zero.var alternate: bool—#: the alternate form, a base's prefix or a point always kept.var zero: bool—0before the width: zeros fill a number after its sign.var width: i64— The least width in scalars; -1 when none was written.var grouping: u8—,or_between groups of digits; 0 when none was written.var precision: i64— The digits after the point, or the scalars a text keeps; -1 when none was written.var kind: u8— The type letter; 0 when none was written.
Reading (struct)#
A specification read from its text, and what is wrong with it: empty when nothing is.
var spec: Spec— The specification, meaningful whenproblemis empty.var problem: str— Why the text is not a specification; empty when it is one.
Category (enum)#
What a field shows: an integer, a float, or text (a str, a char, a bool).
func scalar_count(text: const u8[]) -> i64— The scalars of UTF-8text.
func read(text: str) -> Reading— Readtextas CPython's parse_internal_render_format_spec reads a specification.
Misfit (enum)#
Why a specification does not fit a value of its category, for its caller to word.
func misfit_of(spec: Spec, category: Category) -> Misfit— Whyspecdoes not fit a value ofcategory, orfits(§5.5).
func misfit(spec: Spec, category: Category) -> str— What is wrong withspecfor a value ofcategory, in Base's terms: empty when it fits (§5.5).
Sink (struct)#
Where laid-out text goes: write appends bytes to context, answering false when they did not all fit, which ends the layout.
var context: void*— What the text is written into, handed towrite.var write: func(void*, const u8[]) -> bool— Append the bytes; false when they did not all fit.
Decimal (struct)#
Digits, a virtual 0 outside [0, count): an integer's in its base, or the exact decimal digits of a float's magnitude, 0.d1d2d3... × 10^point, at most 767 significant digits for any finite f64 and no trailing zero.
var digits: u8[800]— The digits, as ASCII; the firstcountare meaningful.var count: usize— How many digits there are; 0 is zero.var point: i64— Where the point stands: beforedigits[point], a negativepointthat many zeros earlier.func at(i: i64) -> u8— The digit at virtual indexi.
func decimal_places(value: f64, places: i64) -> Decimal— The exact decimal digits of finite |value| rounded half to even toplacesafter the point (before it, for a negativeplaces), as dtoa's mode 3 makes them for Python'sround(x, places): no trailing zero, zero as0at point 1, and no digit at all, at point-places, when the rounding leaves nothing.
func lay_integer(sink: Sink, negative: bool, magnitude: u64, specification: str) -> bool— An integer field{value:spec}, its sign apart from its magnitude, laid out byspecification. Acfield of a number that names no Unicode scalar traps.
func is_scalar(negative: bool, magnitude: u64) -> bool— Whether the integer ofnegativeandmagnitudenames a Unicode scalar, as acfield's number must: from 0 to U+10FFFF, not a surrogate. A caller that must not trap asks before laying acfield out.
func encode_scalar(value: u32, buffer: u8[]) -> const u8[]— The UTF-8 of scalarvalueinbuffer, which holds four bytes.
func lay_float(sink: Sink, value: f64, single: bool, specification: str) -> bool— A float field{value:spec}laid out byspecification;singlewhen the value is anf32(or anf16), whose display is its own shortest digits. With neither a type nor a precision a field shows the value's display, where Python shows its repr.
func lay_text(sink: Sink, shown: str, specification: str) -> bool— A text field{value:spec},shownbeing its display, laid out byspecification: precision keeps that many scalars, and the width pads it (CPython's format_string_internal).
memory#
The allocators of §12, the thread's current-allocator convention, the diagnostic records of an allocation failure, and the byte copy, move, set, read and write helpers.
Allocator (interface)#
What every allocator offers: blocks of bytes at an alignment, optionally resized in place, and given back (§12.4). Zero alignment means one. A nonempty block must meet the requested alignment; an allocator may refuse an unsupported alignment. Bump allocators support every positive alignment, not only powers of two.
FixedBuffer (struct : Allocator)#
A bump allocator over a caller's bytes. Only the last block can be resized or released; everything goes away together when the buffer does.
FixedBuffer.over(buffer: u8[]) -> FixedBuffer— An allocator handing outbuffer's bytes; only the last block resizes.func allocate(size: usize, alignment: usize) -> u8[]?— Allocatesizebytes atalignment, or none when it cannot.func resize(block: u8[], size: usize) -> bool— Try to resizeblocktosizein place; whether it worked.func release(block: u8[])— Freeblock.
CAllocator (struct : Allocator)#
The C library's heap.
func allocate(size: usize, alignment: usize) -> u8[]?— Allocatesizebytes atalignment, or none when it cannot.func resize(block: u8[], size: usize) -> bool— Try to resizeblocktosizein place; whether it worked.func release(block: u8[])— Freeblock.
Arena (struct : Allocator)#
Bump allocation over a parent allocator, released all at once by reset or destroy (§12.4, §24.3). One thread at a time.
Arena.over(parent: Allocator, capacity: usize) -> Arena!— An arena ofcapacitybytes overparent, released all at once.func allocate(size: usize, alignment: usize) -> u8[]?— Allocatesizebytes atalignment, or none when it cannot.func resize(block: u8[], size: usize) -> bool— Try to resizeblocktosizein place; whether it worked.func release(block: u8[])— Freeblock.func in_use() -> usize— What has been handed out since the last reset, and what the arena holds in all.func capacity() -> usize— The arena's total capacity in bytes.func reset()— Forget every allocation; the storage is reused from its start.func destroy()— Give the storage back to the parent; the arena is empty afterwards.
PageAllocator (struct : Allocator)#
Whole pages from the host, each block its own mapping (§12.4). Safe from several threads.
func allocate(size: usize, alignment: usize) -> u8[]?— Allocatesizebytes atalignment, or none when it cannot.func resize(block: u8[], size: usize) -> bool— Try to resizeblocktosizein place; whether it worked.func release(block: u8[])— Freeblock.
func page_size() -> usize— The host's memory page size in bytes: the one queryos.page_sizeand the threads' stack sizes use too.
var diagnostic: bool—--profile diagnostic: set by the startup shim beforestartupruns.
Site (struct)#
An allocation the diagnostic profile recorded (§19.4): the block, its size, and where.
var address: void*?— The block's address, or none for a failed request.var size: usize— The requested size in bytes.var function: str— The function that requested it.var line: u32— The source line of the request.
func note_site(address: void*?, size: usize, function: str, line: u32)— Called by the compiled program after each allocation under--profile diagnostic. The record keeps the most recent 256 allocations, oldest first: once full, the oldest goes and the newest takes the last place.
func allocation_sites() -> const Site[]— The allocations recorded so far, the most recent 256 at most, oldest first. A view of the record: read it while no other thread allocates.
let exhausted: ErrorCode = ErrorCode.package(1)— Allocation failed because memory is exhausted.
let unset: ErrorCode = ErrorCode.package(2)— No allocator is current (§12.3).
var heap: Allocator— The process's C heap allocator.
func startup()— Run by the startup shim beforemain, and bythread.spawnin a new thread.
func copy[T](target: T[], source: const T[], count: usize)— Copycountelements fromsourceintotarget.
func move[T](target: T[], source: const T[], count: usize)— Copycountelements, allowingsourceandtargetto overlap.
func set(target: u8[], value: u8)— Set every byte oftargettovalue.
func read[T](address: const void*) -> T— Read aTfromaddress, which may be unaligned.
func write[T](address: void*, value: T)— Writevaluetoaddress, which may be unaligned.
func frame[T](count: usize, most: usize) -> T[]—countuninitialised elements ofTin the frame of the function that calls this, at mostmost(a constant;most * size_of(T)at most 4096 bytes), freed when that function returns (§12.7). The compiler takes the storage at the call, so this body never runs.
func allocate(size: usize, alignment: usize) -> u8[]!—sizeunwritten bytes aligned toalignment, from the current allocator: storage a structure lays out itself (§12.2), given back withfree; the diagnostic profile fills them with 0xAA (§19.4). Fails withmemory.exhausted.
func grow(block: u8[], size: usize) -> u8[]!—blockwithsizebytes: in place when the current allocator can, else a new block with the old bytes copied and the old block released. The bytes past the old ones are unwritten, 0xAA under the diagnostic profile.
os#
Its environment, working directory, identity and host (§16.6). Text comes back as str views of C storage that the system owns; copy what must outlive the next call.
func random_bytes(buffer: u8[]) -> !— Fill bytes from the operating system's cryptographic random generator. A failure is reported; weak process IDs or timestamps are never substituted.
let failed: ErrorCode = ErrorCode.package(12)— An operating-system call failed.
let arm64: bool = platform.arm64— The target, as constants a program branches on:if os.arm64:,if os.linux and os.x86_64:(§19.5); the compiler decides them from--target, so the branch a target rules out is pruned (§19.6).
let x86_64: bool = platform.x86_64— Whether the target architecture is x86-64.
let macos: bool = platform.macos— Whether the target operating system is macOS.
let linux: bool = platform.linux— Whether the target operating system is Linux.
let windows: bool = platform.windows— Whether the target operating system is Windows.
let posix: bool = platform.posix— Whether the target is a POSIX system.
let pointer_bits: u32 = platform.pointer_bits— The width of a pointer on the target, in bits.
let name: str = platform.name— The target triple.
let cpu_level: u32 = platform.cpu_level— The instruction-set level the program was compiled for (--cpu, §19.5): on x86-64, 1 to 4 for x86-64-v1 to v4; on arm64, 1 for NEON, 2 for SVE.
func cpu_level_running() -> u32— The microarchitecture level (§19.5) the CPU running this process supports.
func cpus() -> u32— The processors available to this process, at least one.
func page_size() -> usize— The host's memory page size in bytes.
func env(variable: c.str) -> str?— The value of an environment variable, or none when it is not set. Copy a view that must survive another env call on this thread or an environment mutation.
func set_env(variable: c.str, value: c.str) -> !— Set an environment variable for this process and the ones it starts.
func unset_env(variable: c.str) -> !— Remove environment variablevariable.
func cwd() -> str!— The working directory, in storage from the current allocator.
func executable() -> str!— The path of this program's executable as the loader saw it, in an allocation of the current allocator, NUL-terminated for the C calls a path goes to.
func change_dir(path: c.str) -> !— Change the process's working directory topath.
func pid() -> i32— The process identifier.
func parent_pid() -> i32— The parent process's identifier.
func hostname() -> str!— The host's name, in storage from the current allocator.
func exit(code: i32) -> never— Stop the process withcode, running no deferred work.
io#
Readers and writers over bytes, buffered wrappers, the standard output and error streams, the user's home directory, and the stream error codes.
Reader (interface)#
A borrowed byte source. A successful read returns at most the buffer length; zero for a nonempty buffer means EOF. Empty reads return zero without consuming input. Errors are distinct from EOF. The implementing object owns its lifetime.
Writer (interface)#
A borrowed byte sink (§14.4). A write may accept fewer bytes than supplied; callers needing the whole payload use write_all. Empty writes return zero. A failure may follow earlier successful writes; the view never owns the sink.
let unexpected_eof: ErrorCode = ErrorCode.package(14)— A stream ended before the expected bytes arrived.
let no_progress: ErrorCode = ErrorCode.package(15)— A stream made no progress and cannot continue.
let invalid_count: ErrorCode = ErrorCode.package(16)— A read or write was asked for an invalid count.
let invalid_buffer: ErrorCode = ErrorCode.package(17)— A read or write was given an invalid buffer.
func read_exact(source: Reader, buffer: u8[], transferred: usize*? = none) -> !— Fillbuffer, or fail at EOF or on a source error. Optionaltransferredis reset to zero on entry and updated after each successful read, including before a later failure. It must not overlap the buffer or the source's state. No call reaches the source for an empty buffer. The source remains borrowed and open.
func write_all(destination: Writer, data: const u8[], transferred: usize*? = none) -> !— Write all bytes, preserving confirmed progress throughtransferredon error. The progress pointer must not overlap the data or sink state. A zero-length successful write on nonempty input fails withno_progressinstead of spinning. This does not flush or close the borrowed sink. Empty input makes no sink call.
func copy_limit(source: Reader, destination: Writer, buffer: u8[], limit: usize, transferred: usize*? = none) -> usize!— Copy at mostlimitbytes through caller-owned scratch storage; stop earlier at EOF. Reads never consume beyond the limit.transferredcounts confirmed destination bytes, including before a failure; source consumption can be ahead by one scratch buffer if writing fails. Scratch and progress must not overlap either endpoint's state/data or each other. No allocation, flush or close occurs.
SliceReader (struct : Reader)#
A cursor over borrowed bytes. Copying the reader copies its position, not its data. The backing storage must outlive the reader and every read using it.
SliceReader.over(data: const u8[]) -> SliceReader— A reader overdata.func remaining() -> usize— The number of bytes not yet read.func read(buffer: u8[]) -> usize!— Copy up to the buffer length; zero means no bytes remain (or an empty read).
SliceWriter (struct : Writer)#
A writer into fixed borrowed storage. Copying it copies the cursor and aliases storage. Writes may be short; once full, a nonempty write fails with full.
SliceWriter.over(data: u8[]) -> SliceWriter— A writer intodata.func written() -> const u8[]— View of confirmed written bytes, borrowed from the caller's storage.func write(data: const u8[]) -> usize!— Writedata; the number of bytes written.
BufferedReader (struct : Reader)#
Buffered input over a borrowed source and nonempty caller-owned storage. Both must outlive this adapter. Storage must not overlap source state or read buffers. Construct with over; serialize access and do not use copied adapters together. Reads may prefetch beyond the requested bytes. The adapter never closes its source.
BufferedReader.over(source: Reader, storage: u8[]) -> BufferedReader!— A buffered reader oversource, usingstorage.func buffered() -> usize— Unread bytes already fetched. No source operation occurs.func read(buffer: u8[]) -> usize!— Return buffered bytes first, otherwise perform one source read. Empty reads do not call the source. EOF is not cached, allowing a growing source to resume.
BufferedWriter (struct : Writer)#
Buffered output over a borrowed sink and nonempty caller-owned storage. Both must outlive this adapter; storage must not overlap sink state or write input. Construct with over; serialize access and do not use copied adapters together. Explicitly flush before discarding the adapter. There is no implicit flush/close.
BufferedWriter.over(destination: Writer, storage: u8[]) -> BufferedWriter!— A buffered writer overdestination, usingstorage.func buffered() -> usize— Bytes accepted by this adapter but not yet confirmed by the destination.func flush() -> !— Drain this buffer, preserving the unconfirmed suffix if the sink fails. Retrying does not resend bytes confirmed by earlier successful sink writes. This neither flushes downstream buffers nor requests filesystem durability.func write(data: const u8[]) -> usize!— Accept up to the remaining capacity. A full buffer is drained before any new input is accepted; a failure accepts none of this call's input. Empty writes do not drain the buffer. Use write_all to accept an entire payload.
Location (struct)#
A compile-time source position, the value of luce.location.
var file: str— The source file of the location.var line: u32— The source line of the location.var function: str— The enclosing function of the location.
let closed: ErrorCode = ErrorCode.package(3)— The stream is closed.
let failed: ErrorCode = ErrorCode.package(24)— The underlying stream operation failed.
let would_block: ErrorCode = ErrorCode.package(28)— A non-blocking stream has no data ready.
File (struct : Writer)#
Borrowed standard output stream. Each nonempty write uses the existing libc stream and flushes only that stream, making completed output visible before a following print. The libc stream lock serializes each write with other libc users; concurrent direct descriptor writes may interleave. No stream is created or owned here. A write/flush failure can follow partial output.
func flush() -> !— Flush this C stream, without closing it or requesting filesystem durability.func write(data: const u8[]) -> usize!— Writedata; the number of bytes written.
func stdin() -> Reader— Borrowed unbuffered standard input. Reads may block; concurrent readers compete for bytes. Do not mix with buffered C stdin reads, which may have prefetched data.
func stdout() -> Writer— A writer over the process's standard output.
func stderr() -> Writer— The process's standard error stream.
func flush_stdout() -> !— Explicitly flush C stdout, including bytes written through C interop.
func flush_stderr() -> !— Explicitly flush C stderr, including bytes written through C interop.
let full: ErrorCode = ErrorCode.package(4)— A fixed writer has no room left.
FormatSink (struct : Writer)#
The sink a formatted string offers a Display value (§14.4): it appends to the buffer the compiler is filling, and fails once that buffer is full, as format then does.
func write(data: const u8[]) -> usize!— Writedata; the number of bytes written.
path (struct)#
The process's directories (§16.6): from io import path, then path.user(). Each is a str view of environment storage the system owns, or fresh storage from the current allocator where one has to be built.
path.user() -> str!— The user's home directory: USERPROFILE on Windows, HOME on POSIX.path.home() -> str!— The current user's home directory.path.temp() -> str— Where temporary files go:$TMPDIR, else/tmp.path.config() -> str!— Where configuration lives:$XDG_CONFIG_HOME, else$HOME/.config.
let io_path_failed: ErrorCode = ErrorCode.package(13)— The home directory could not be determined.
atomic#
Memory orderings for the operations of @T (§15.1).
Ordering (enum as u8)#
The memory ordering of an @T operation.
func fence(order: Ordering)— A standalone fence; the backend supplies the instruction.
time#
A monotonic clock that never goes backwards, and the wall clock as seconds since the Unix epoch, over the host's clock_gettime.
func now() -> u64— Nanoseconds from an arbitrary origin, never going backwards.
func unix() -> i64— Seconds since the Unix epoch.
func since(start: u64) -> u64— Nanoseconds elapsed sincestart, fromnow().
thread#
Spawning, joining and detaching host threads over pthreads, and on Windows over its own threads, with the running thread's identity and yielding and sleeping.
let failed: ErrorCode = ErrorCode.package(5)— A thread operation failed.
var default_stack: usize = 8388608— The stack of a thread spawned without a size: 8 MiB on every host, the main thread's on Linux, where macOS gives a new thread 512 KiB and Windows 1 MiB. A program may set it before it spawns;spawn(..., stack = n)overrides it for one thread.
var locals_start: (func() -> unit)?— What gives a new thread'slocal vars their initialisers (§6.3), run before its entry. The native backend's startup sets it when the program has such initialisers, since its thread-local storage starts zeroed; under C,_Thread_localstorage starts initialised and it stays none.
Handle (struct)#
A running thread; the zero value is no thread at all, so arrays of handles exist. On Windows the id is the thread's handle.
func join() -> !— Wait for the thread to finish.func detach()— Let the thread run on its own; its resources are reclaimed at exit.
func spawn(entry: func(void*?) -> unit, context: void*?, stack: usize = 0, name: str = "") -> Handle!— Start a thread runningentry(context).stackis its stack in bytes,default_stackwhen 0, at leastPTHREAD_STACK_MINand whole pages;nameis what the host's tools show for it, its first fifteen bytes.
func current() -> Handle— A handle to the calling thread: on Windows its pseudo-handle, which stands for whichever thread uses it and which closing leaves alone.
func is_main() -> bool— Whether this is the process's initial thread, for main-thread native resources.
func pause()— A hint to the processor inside a spin loop.
func yield()— Yield the processor to another runnable thread.
func sleep(milliseconds: u64)— Sleep for at leastmilliseconds: a signal that interrupts the sleep leaves the time remaining, which is slept again.
sync#
Blocking synchronisation over the host's futex-like wait and wake: a mutex, a condition variable, a run-once gate, and a counting semaphore. The host's sleep returns on wakes nothing here sent: Linux and macOS rarely, and Windows often when a thread waiting on an address less than 32 bytes away is woken. Every sleep below checks its own word again and sleeps again when it has not changed, so such a wake costs a context switch and is never seen by a caller.
Mutex (struct)#
A lock whose waiters sleep: zero is unlocked, so var lock: Mutex is ready to use; one is locked; two is locked with someone asleep on it. A mutual-exclusion lock; a waiter sleeps until it is free.
func lock()— Acquire the lock, blocking until it is free.func unlock()— Release the lock and wake one waiter.func try_lock() -> bool— Acquire the lock without blocking; whether it was taken.
Condition (struct)#
A sequence number waiters watch; every signal advances it and wakes. A condition variable: waiters sleep until signalled. As with every condition variable, a waiter checks its predicate in a loop around wait: a signal says that something changed, not what, and another thread may have acted on it first.
func wait(mutex: Mutex*)— Releasemutex, sleep until signalled, then reacquire it. A wake with no signal since the call is not returned; a signal or broadcast meant for another waiter may be.func wait_for(mutex: Mutex*, milliseconds: u64)—wait, giving up after aboutmilliseconds; a caller tells a timeout from a signal by checking its predicate.func signal()— Wake one waiter.func broadcast()— Wake every waiter.
Once (struct)#
Runs its function exactly once; later callers wait for the first to finish. Runs a function exactly once; later callers wait for the first.
func run(function: func() -> unit)— Runfunctionon the first call; later calls wait for it to finish.
Semaphore (struct)#
A counting semaphore whose waiters sleep. A counting semaphore whose waiters sleep.
func acquire()— Take one permit, blocking until one is available.func release()— Return one permit and wake one waiter.
Cancellation (struct)#
A one-way cancellation signal shared by reference. Zero is not requested. Keep this object alive until every waiting thread returns; do not copy or reset it while shared. Requests use release/acquire synchronization.
func request()— Request cancellation.func is_requested() -> bool— Whether cancellation was requested.
ownership#
Intrusive ownership shared by Base libraries and compiled Luce programs. Base callers retain and release explicitly; Luce inserts those operations. One header and trace protocol cover native/managed cycles on the owning thread. Runtime allocations use the system heap; an explicit allocator can be supplied to reserve when its lifetime is guaranteed by the native owner.
let immortal: u8 = 32— A literal's text: never counted, never released, never alive at the end.
Object (struct)#
The ownership header every managed object carries, before its fields.
var strong: u32— The strong reference count; the object is finalized when it reaches zero.var weak: u32— The number of weak references watching the object.var flags: u8— The collector's color and state bits (§the cycle collector).var info: Info*— The object's class description.var generation: u64— Allocation identity never repeats, even when an allocator reuses an address.var context: u64— The owning context the object belongs to.var allocation_size: usize— The size of the object's allocation in bytes.var allocator: memory.Allocator?— The allocator that made the object, when one was supplied explicitly.
Info (struct)#
What the collector and the destructor need to know about a class.
var name: str— The class name, for diagnostics and the collector.var size: usize— The object's size in bytes, its fields included.var finish: (func(Object*) -> unit)?—deinit, when the class declares one.var drop: func(Object*) -> unit— Releases the fields in reverse declaration order, tolerating unassigned ones.var trace: func(Object*, func(Object*, void*) -> unit, void*) -> unit— Visits every strong reference the object holds, fields in declaration order.var identity: (func(Object*) -> u64)? = none— An interface adapter preserves the identity of its concrete owner.var acyclic: bool = false— No object of this type can be part of a reference cycle (text, a list of numbers, a class whose fields are all such): the collector never takes one as a candidate nor walks into one, so large acyclic data costs it nothing.var disposes: bool = false—finishdisposes native state that other objects' finishes may still reach (a native object's close): in a garbage cycle it runs after everydeinit, and before the finishes of the objects this one refers to, as releasing them in turn would.
func live_count() -> usize— Allocated objects not yet finalized on the calling runtime thread.
func restore_site(saved: str)— The caller's site again, deferred by every function the compiler writes.
func stop(message: str) -> never— Stop the program withtrap: file:line:column: messageon standard error and status 1.
func stop_at_site(message: str)— A library trap on behalf of the value language: stops at its running statement when one is set, so the trap names the Luce line rather than the library's; returns otherwise, for the caller's owntrapto name its statement.
func context_id() -> u64— A unique runtime identity for this thread, independent of recycled OS thread IDs.
func enter()— Application runtime entry is separate from ordinary manual Base ownership. Generated callbacks require entry; native worker adapters establish it internally.
func require_context()— Trap when no owning context has been entered.
func check_thread(o: Object*)— Trap whenois touched from a thread other than its owner.
func check_alive(o: Object*)— Trap whenohas already been finalized.
func reserve(info: Info*, size: usize, allocator: memory.Allocator? = none) -> Object*!— Reserve unpublished storage. The caller supplies a stable descriptor before publishing the object and abandons the storage if native initialization fails.
func allocate(info: Info*) -> Object*— Allocate an object of classinfoand its header.
func allocate_sized(info: Info*, size: usize) -> Object*— Runtime wrapper/text allocation retains Luce's trap-on-exhaustion policy.
func retain(o: Object*) -> Object*— Add a strong reference tooand return it.
func release(o: Object*)— Drop a strong reference too, finalizing it when the count reaches zero. The value language's release: it stores before it releases, so the collector may run here.
func release_held(o: Object*)—releasefor a handle native code holds (interop): never runs the collector, which could trace a field the caller has released but not yet overwritten (possible_root).
func discard_unpublished(o: Object*)— Free unpublished storage without invoking the successful object's cleanup. The native initializer owns cleanup of its partially acquired resources.
func abandon(o: Object*, cause: str, cause_at: str)— Aninitthat failed: the fields assigned so far go, nodeinitruns. Likedestroy, the object leaves the collector's candidates first, so a collection the drop sets off never walks fields already released. What the fields held that refers back to the object, a closure overselfor a child holding its parent, lets go of it in the drop; a reference still held after that was published by the failedinit, which stops the program rather than leave it pointing at freed storage. The trap names theinit's own failure,causeraised atcause_at, which the publication would otherwise hide.
func identity(object: Object*) -> u64— The allocation identity, or the concrete owner's identity through an adapter.
func mark() -> usize— The current pool position, todrainback to later.
func pool_object(o: Object*) -> Object*— An owned object handed on as a temporary: released by the nextdrain.
func pool_value[T](v: T, drop: func(void*) -> unit) -> T— An owned value of any type handed on as a temporary;dropreleases what it holds.
func drain(since: usize)— Releases every temporary pooled sincemark, in the order they were pooled.
let candidate_limit: usize = 1024
func safe_point()— A point where no native code is midway through replacing a traced field, such as the top of an event loop's turn: collects when releases through native handles filled the candidates (possible_root), which they never collect themselves.
func collect()— Free the garbage: deinits first, then the native objects' disposals, then every object's fields, then the storage.
Weak (struct)#
A weak reference: it watches an object without keeping it alive.
var target: Object*?— The watched object, or none once it is gone.
func weak_make(o: Object*) -> Weak— A weak reference watchingo.
func weak_copy(w: Weak) -> Weak— A copy ofw, counting one more watcher of its object.
func weak_drop(w: Weak)— Dropw; the object's shell is freed when its last watcher goes.
func weak_get(w: Weak) -> Object*?— The object with a fresh strong reference, or none once it is dead.
func finish_run(status: i32) -> i32— Aftermain: the collector runs, and anything still alive is a defect. The exit status.
func finish_task()— A worker's end (§14): its heap is its own, and it too must leave nothing alive once its arguments and result are released; what it does leave stops the program.
strings#
Text operations over str views; what allocates says so and uses the current allocator, and says how the allocation is given back: release for a text made here, free for the borrowed-field arrays returned by split and split_by.
let invalid_separator: ErrorCode = ErrorCode.package(48)— An empty separator or needle where one is required.
let output_too_large: ErrorCode = ErrorCode.package(49)— A result exceeds the caller's byte limit.
let invalid_radix: ErrorCode = ErrorCode.package(50)— A radix outside 2 through 36.
let invalid_number: ErrorCode = ErrorCode.package(51)— The text is not a number in the given radix.
let number_out_of_range: ErrorCode = ErrorCode.package(52)— The parsed value does not fit its type.
func starts_with(text: str, prefix: str) -> bool— Whethertextbegins withprefix.
func ends_with(text: str, suffix: str) -> bool— Whethertextends withsuffix.
func find(text: str, needle: str) -> usize?— The byte offset of the first exact needle, or none. Empty needles match at zero. No allocation or UTF-8 validation occurs; embedded NUL bytes are ordinary data. The search takes linear time and constant auxiliary space.
func find_from(text: str, needle: str, start: usize) -> usize?— Search at or after a byte offset. An offset past the end returns none, including for an empty needle. This does not require a Unicode scalar boundary.
func find_last(text: str, needle: str) -> usize?— The last exact occurrence, including overlaps. Empty needles match at the end. Like find, this uses byte offsets, linear time, constant space and no allocation.
func last(text: str, byte: u8) -> usize?— The byte offset of the lastbyteintext.
func contains(text: str, needle: str) -> bool— Whetherneedleoccurs anywhere intext.
func split(text: str, separator: u8) -> str[]!—textsplit at everyseparator, as views into it; the array is an allocation of the current allocator, given back withfree.
SplitIterator (struct)#
Split a borrowed text at a nonempty byte substring. Empty fields, including the final one after a trailing separator, are preserved. Zero is an exhausted iterator. Keep text and separator storage alive and unchanged while iterating.
SplitIterator.over(text: str, separator: str, max_parts: usize = 0) -> SplitIterator!— max_parts=0 has no limit; one returns the entire input as a single field. No allocation occurs. An empty separator reports invalid_separator.func next() -> str?— The next borrowed field. An empty field is present; none means exhausted.
func split_by(text: str, separator: str, max_parts: usize = 0) -> str[]!— An allocated array of borrowed fields with SplitIterator semantics. Free the array through the allocator current on entry; its field bytes still borrow text. max_parts=0 has no limit. An empty separator reports invalid_separator.
func split_once(text: str, separator: str) -> (str, str)?— Borrow the text before and after the first separator, or none if absent. The separator is omitted. An empty separator splits at the start: (empty, text).
func split_last(text: str, separator: str) -> (str, str)?— Borrow the text before and after the last separator, including overlapping candidates. An empty separator splits at the end: (text, empty).
func trim(text: str) -> str—textwithout leading and trailing spaces, tabs, and line ends: a view.
func join(pieces: const str[], separator: str) -> str!— The pieces joined withseparatorbetween them, NUL-terminated in the current allocator;releasegives it back.
func copy(text: str) -> str!— A copy oftextin the current allocator, NUL-terminated so it may be ac.str;releasegives it back.
func copy_into(buffer: u8[], text: str) -> str— As much oftextas fits inbuffer, copied there and cut at a character's start; the result viewsbuffer. A caught failure's message is kept past its handler so, or withcopy(§11.3).
func to_upper(text: str) -> str!— ASCII case folding; other bytes pass through. NUL-terminated in the current allocator;releasegives the text back.
func to_lower(text: str) -> str!— ASCII lowercase; other bytes pass through unchanged. The result is a NUL-terminated current-allocator allocation released with release.
func release(text: str)— Give back text from join, copy, replace, to_upper or to_lower: the allocation is one byte longer than the text, its NUL.
func replace(text: str, needle: str, replacement: str, max_replacements: usize = 0, max_bytes: usize? = none) -> str!— Replace nonoverlapping byte substrings from left to right. Empty needles report invalid_separator. max_replacements=0 replaces all matches; max_bytes optionally limits result bytes excluding its terminator, reporting output_too_large before allocation. A result is always a fresh NUL-terminated current-allocator allocation, including unchanged or empty results; release gives it back. Inputs remain borrowed and unchanged and may overlap each other. No UTF-8 validation occurs.
func parse_i64(text: str, radix: u32 = 10) -> i64?— A signed integer in radix 2 through 36. ASCII letters are case-insensitive digits; prefixes are not interpreted. Optional +/- and leading zeroes are accepted. None reports an invalid radix, invalid byte, missing digit or overflow.
func parse_u64(text: str, radix: u32 = 10) -> u64?— Unsigned counterpart of parse_i64. A leading plus is accepted; every minus, including -0, is rejected. The entire input must fit u64 in the requested radix.
func format_i64(value: i64, buffer: u8[], radix: u32 = 10) -> str!— Canonical lowercase digits, with a minus only for negative values, no prefix, padding or terminator. Return a borrowed view of buffer. A 65-byte buffer always suffices. Invalid radix or insufficient capacity leaves buffer unchanged.
func format_u64(value: u64, buffer: u8[], radix: u32 = 10) -> str!— Unsigned counterpart of format_i64; at most 64 bytes are needed. io.full reports insufficient capacity and invalid_radix reports a radix outside 2 through 36.
func parse_f64(text: str) -> f64!— Parsetext, all of it, as the f64 nearest its value, ties to even: an optional sign, then digits with an optional point (1,1.5,.5,5.) and an optional exponent (eorE, an optional sign, digits), orinf,infinityornanin any case. NaN is the quiet NaN with the written sign. Fails with invalid_number whentextis not a number or goes on past one (scan_f64 says where it ends), and with number_out_of_range when it rounds past the largest finite f64; a smaller magnitude than the least subnormal is a signed zero. No locale, whitespace, underscore or hex form is read.
func parse_f32(text: str) -> f32!— The f32 counterpart of parse_f64, rounded once from the decimal (never through f64).
func scan_f64(text: const u8[]) -> (f64, usize)!— The number that startstext, read as parse_f64 reads one, and how many bytes spell it: the longest prefix that is a number (1eis the number1, one byte). A reader continues from there, and names that position when what follows is not what it expects. Fails with invalid_number when no number startstext, number_out_of_range as parse_f64 does.
func scan_f32(text: const u8[]) -> (f32, usize)!— The f32 counterpart of scan_f64.
func format_f64(value: f64, buffer: u8[]) -> str!— The shortest decimal text that parse_f64 reads back asvalue, the closest to it of those, as double-conversion's ToShortest lays it out: decimal notation for a decimal exponent from -6 to 14 (0.000001,123456789012345,1.5), otherwise one digit, the rest after a point, andewith the exponent (1e-7,1.2345e15,5e-324);-0,inf,-inf,nan(no sign, no payload). Written intobuffer(32 bytes always suffice), and a view of it; io.full when it does not fit, the buffer unchanged. Neither allocates, locale or rounding mode (float_text).
func format_f32(value: f32, buffer: u8[]) -> str!— The f32 counterpart of format_f64: the f32's own shortest digits (0.1for 0.1f32, not the digits of its f64 value).
func format(buffer: u8[], text: fmt) -> str!—textwritten intobuffer: thestrover the bytes written (§5.5). Fails withmemory.exhaustedwhen the text does not fit, the bytes that fit written. The compiler writes the text where the call is, so this body never runs.
func write_i64(sink: io.Writer, value: i64, spec: str) -> !—valuelaid out by format specificationspec(§5.5), written tosink: what a formatted string's{value:spec}field writes. Aspecthat does not read traps.
func write_u64(sink: io.Writer, value: u64, spec: str) -> !—valuelaid out by format specificationspec(§5.5), written tosink.
func write_f64(sink: io.Writer, value: f64, spec: str) -> !—valuelaid out by format specificationspec(§5.5), written tosink.
func write_f32(sink: io.Writer, value: f32, spec: str) -> !—valuelaid out by format specificationspec(§5.5), written tosink: with neither a type nor a precision, thef32's own shortest digits.
func write_text(sink: io.Writer, text: str, spec: str) -> !—textlaid out by format specificationspec(§5.5), written tosink.
func write_char(sink: io.Writer, value: char, spec: str) -> !—value, its UTF-8, laid out by format specificationspec(§5.5), written tosink.
func write_bool(sink: io.Writer, value: bool, spec: str) -> !—trueorfalselaid out by format specificationspec(§5.5), written tosink.
interop#
Explicit native ownership shared with managed consumers. Package types remain ordinary structs with init and methods; a Type declaration supplies their disposal, trace and affinity contract. Reference values are manual in Base.
let invalid: ErrorCode = ErrorCode.package(101)— The carrier or its native value is not valid.
let wrong_thread: ErrorCode = ErrorCode.package(102)— The value was touched from a thread other than its owner.
let expired: ErrorCode = ErrorCode.package(103)— The lease or scope backing the value has ended.
Type (struct [T])#
A package's constant declaration of native ownership. Dispose releases native resources and strong edges exactly once, including after an explicit close. A closeable export binds its public disposal method as the terminal operation.
let name: str— The type's name.let dispose: func(T*) -> unit— Releases the value's native resources and strong edges, exactly once.let trace: (func(const T*, func(ownership.Object*, void*) -> unit, void*) -> unit)? = none— Visits the strong references the value holds, when it holds any.let closeable: bool = false— Whether the export binds a public disposal method as its terminal operation.let main_thread: bool = false— Whether the value must live on the process's main thread.
Owner (struct [T])#
Stable shell shared by every native reference and managed alias. Its header participates directly in the shared collector; no second reference count exists.
var header: ownership.Object— The shared collector header.Owner.is_open(object: ownership.Object*) -> bool— Whether the owner has not been closed.Owner.enter(object: ownership.Object*)— Begin a native call guard, retaining the object.Owner.leave(object: ownership.Object*)— End a native call guard, disposing the owner once closed and idle.Owner.finish_owner(object: ownership.Object*)— The collector's finalizer: close the owner.Owner.drop_owner(object: ownership.Object*)— Free the owner's native storage.Owner.trace_owner(object: ownership.Object*, visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the native value's strong references.
Reservation (struct [T])#
Unpublished ownership storage. Reserve before running a native initializer; publish only after success, or cancel without running a successful finalizer.
func init(declaration: Type[T]) -> !— Reserve unpublished storage fordeclaration.func publish(native: T*, allocator: memory.Allocator? = none) -> Reference[T]— Publish the native value, yielding a reference and consuming the reservation.func cancel()— Discard the reservation without publishing.
Reference (struct [T])#
A typed reference carrier. Parameters borrow the carrier; clone acquires an additional strong reference. Publish/adopt return one owning reference, whose Base caller releases explicitly. Copying the struct does not acquire ownership.
let owner: Owner[T]*— The owner shell this reference keeps alive.func init(owner: Owner[T]*)— A reference overowner, which is already alive.Reference.adopt(native: T*, declaration: Type[T], allocator: memory.Allocator? = none) -> Reference[T]!— Adoptnativeinto a new owned reference ofdeclaration.func clone() -> Reference[T]— Another strong reference to the same value.func release()— Drop this reference's edge.func get() -> T*!— The native value, or a closed/uninitialized error.func value() -> T*— Infallible access traps; fallible adapters use get to preserve a closed error.func identity() -> u64— A stable identity for the value that never repeats.func is_closed() -> bool— Whether the value has been closed.func close()— Close the value, if its type is closeable.func lease() -> Lease!— A validity lease over the value.Reference.validate_interface(object: ownership.Object*) -> !— Validate thatobjectis a live reference of this type.func as_interface[I](native: I) -> Interface[I]— The supplied witness must point into this owner's stable native storage.func enter()— Guards are balanced by generated Luce calls or explicitly by Base callers.func leave()— End a native call guard on the value.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Every retained native edge must be visited by the package's trace callback.
WeakReference (struct [T])#
A weak carrier keeps the owner shell, never the native resource. Getting a live reference acquires one strong ownership obligation for the Base caller.
func init(reference: Reference[T])— A weak carrier watchingreference's owner.func clone() -> WeakReference[T]— Another weak carrier watching the same owner.func release()— Drop this weak carrier's edge to the owner.func get() -> Reference[T]?— A fresh strong reference to the value, or none once it is gone.
Lease (struct)#
A one-shot validity scope over an owning native object.
func clone() -> Lease— Another edge to the same lease.func release()— Drop this lease's edge.func invalidate()— Mark the scope invalid; later checks fail.func is_valid() -> bool— Whether the scope is still valid and its owner open.func check() -> !— Errorexpiredwhen the scope is no longer valid.func enter() -> !— An active invocation postpones physical disposal of its native owner. Operational closure/expiry is still visible immediately to every alias.func leave()— End a guarded invocation, releasing the owner.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the owner as a strong reference.
ViewType (struct [T])#
An explicit export of a borrowed native struct. Its complete native data is a view, never copied into ownership of the resource it describes.
let name: str— The view type's name.let mutable: bool = false— Whether the view allows mutable access.
ViewOwner (struct [T])#
The owner shell backing a checked view.
var header: ownership.Object— The shared collector header.ViewOwner.drop_view(object: ownership.Object*)— Release the view's lease when the owner is dropped.ViewOwner.trace_view(object: ownership.Object*, visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the lease's strong references.
View (struct [T])#
Manual Base carrier for a checked view. The Luce adapter shares this owner and retains it in aliases/bound methods; every operation checks its lease again.
let owner: ViewOwner[T]*— The owner shell this view shares.func init(owner: ViewOwner[T]*)— A view overowner, which is already alive.View.make(native: T, declaration: ViewType[T], lease: Lease) -> View[T]!— A view ofnative, valid whileleaseis.func clone() -> View[T]— Another strong reference to the same view.func release()— Drop this view's edge.func get() -> const T*!— A read-only pointer to the value, after checking the lease.func get_mut() -> T*!— A mutable pointer to the value, when the view is mutable.func value() -> const T*— The value, trapping if the lease has expired.func value_mut() -> T*— The mutable value, trapping when unavailable.func is_valid() -> bool— Whether the view's lease is still valid.func enter() -> !— Begin a guarded invocation, retaining the owner.func leave()— End a guarded invocation.View.validate_interface(object: ownership.Object*) -> !— Validate thatobjectis a live view of this type.View.begin_interface(object: ownership.Object*)— Begin a guarded invocation for an interface witness.View.end_interface(object: ownership.Object*)— End a guarded invocation for an interface witness.func as_interface[I](native: I) -> Interface[I]— The witness borrows this view's storage and preserves its validity lease.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the owner as a strong reference.
Interface (struct [I])#
An interface witness paired with explicit ownership and validity. A bare Base interface is only a pointer/table view; this carrier makes retention deliberate.
let owner: ownership.Object*— The retained object the witness belongs to.func init(owner: ownership.Object*, native: I,— Construction borrows. A returned carrier transfers one retained reference; use clone when the caller already owns the original reference.func clone() -> Interface[I]— Another edge to the same witness.func release()— Drop this witness's edge to the owner.func get() -> I!— The interface value, after checking that the owner is alive and valid.func value() -> I— The interface value, trapping if it is invalid.func enter() -> !— Begin a guarded invocation, retaining the owner.func leave()— End a guarded invocation, releasing the owner.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the owner as a strong reference.
Owned (struct [T])#
A native value with explicit backing storage. The value may borrow that storage; clone retains it, release ends the obligation. Plain/static values need no owner.
let value: T— The native value, which may borrow the owner's storage.let owner: ownership.Object*? = none— The object backing the value, or none for a plain value.func clone() -> Owned[T]— Another edge to the value's owner, when it has one.func release()— End this value's obligation to its owner.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the owner as a strong reference.
Outcome (struct [T])#
A callback's success value or failure text, each with an explicit owner. A Base caller can consume a failure without leaving managed error text pending anywhere. get borrows until release; it never transfers ownership of the contained value.
let code: ErrorCode— The failure code, orpackage(0)on success.Outcome.success(value: Owned[T]) -> Outcome[T]— A successful outcome carryingvalue.Outcome.failure(code: ErrorCode, message: Owned[str]) -> Outcome[T]— A failed outcome withcodeandmessage.func is_success() -> bool— Whether the outcome succeeded.func get() -> T!— The success value, or the failure as an error.func clone() -> Outcome[T]— A copy of the outcome, retaining its owned value or message.func release()— Release the outcome's owned value or message.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the outcome's strong references.
func copy_text(value: str) -> Owned[str]!— Own a copy of text from a temporary buffer or a native error before it expires.
func success_unit() -> Outcome[unit]— A successful unit outcome, for a callback that reports only success or failure. It saves every such callback from spellingOutcome[unit].success(Owned[unit](())).
func failure_unit(code: ErrorCode, message: str) -> Outcome[unit]— A failed unit outcome carryingcodeand an owned copy ofmessage, the bridge from a Base!failure to theOutcomea callback returns:expr catch failure: return interop.failure_unit(failure.code, failure.message). If copying the message itself runs out of memory, the outcome reports memory.exhausted with a static note instead of pending managed text.
Callback (struct [A, R])#
A retained callable. Copying this carrier borrows; cloning acquires an edge. Managed closures use their existing owner, so captures remain visible to ARC.
let owner: ownership.Object*— The retained object the callable belongs to.let entry: func(ownership.Object*, A) -> Outcome[R]— Adapter identity. Call through invoke to retain the owner and check affinity.func init(owner: ownership.Object*, entry: func(ownership.Object*, A) -> Outcome[R])— A callback overowner, called throughentry.func clone() -> Callback[A, R]— Another edge to the same callable.func release()— Drop this callback's edge to the owner.func invoke(argument: A) -> Outcome[R]— Call the callable withargument, retaining the owner across the call.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the owner as a strong reference.Callback.bind[T](source: Reference[T], method: func(const T*, A) -> Outcome[R]) -> Callback[A, R]!— Native methods receive stable storage under the source owner's call guard.Callback.bind_mutating[T](source: Reference[T], method: func(T*, A) -> Outcome[R]) -> Callback[A, R]!— A callback bound to a method of a nativesourcethat changes it.
Connection (struct)#
Owning registration token. Dropping its last reference disconnects; explicit disconnection remains queryable and releases its signal-state edge immediately.
func disconnect()— Remove the registration; idempotent.func is_connected() -> bool— Whether the registration is still present.
let connection_type: Type[Connection] = Type[Connection](name = "Connection",— The interop type describing aConnection.
Signal (struct [A])#
A typed, connectable signal: an owned carrier its aliases share by reference count.
func init(allocator: memory.Allocator? = none) -> !— A custom allocator must outlive the signal and its connection aliases.func clone() -> Signal[A]— Another strong reference to the same signal.func release()— Drop this signal's edge.func close()— Close the signal; further connects and emits fail.func is_closed() -> bool— Whether the signal has been closed.func trace(visit: func(ownership.Object*, void*) -> unit, context: void*)— Visit the signal state as a strong reference.func connect(callback: Callback[A, unit]) -> Reference[Connection]!— Registercallback, returning aConnectiontoken.func emit(argument: A) -> Outcome[unit]— Deliverargumentto every connected callback.
Packet (struct [T])#
A uniquely owned message outside either thread's ARC graph. Copies borrow; passing a packet into a queue transfers its release obligation. Its disposer must work on either thread and must not access thread-bound owners/allocators.
let value: T— The message value.func init(value: T, storage: void*? = none, dispose: (func(void*) -> unit)? = none)— A packet owningvalue, released throughdispose.func release()— Dispose the packet's storage.
Transfer (struct [T])#
Deep-copy policy supplied by the native library for a wire value. All borrowed members must point into the returned packet or immutable process-lifetime data. A policy must never smuggle an ARC owner, checked view or callback across threads.
let copy: func(T) -> Packet[T]!— The library's deep-copy of a wire value into a packet.Transfer.plain() -> Transfer[T]— For pointer-free scalar/record values only. Text/spans need a deep copy.
let text_transfer: Transfer[str] = Transfer[str](PacketBytes.text)— The deep-copy policy forstr.
let bytes_transfer: Transfer[const u8[]] = Transfer[const u8[]](PacketBytes.copy)— The deep-copy policy for byte spans.
Reply (struct [T])#
A reply owns its successful packet or its copied failure text. get borrows; release is required whether the caller handles success or failure.
let code: ErrorCode— The failure code, orpackage(0)on success.Reply.success(value: Packet[T]) -> Reply[T]— A successful reply carryingvalue.Reply.failure(code: ErrorCode, message: str) -> Reply[T]— A failed reply withcodeand a copiedmessage.func is_success() -> bool— Whether the reply succeeded.func get() -> T!— The success value, or the failure as an error.func release()— Release the reply's owned value or message.
WorkerEntry (struct [C, M, R])#
A named factory and its runtime hooks, with no retained source-thread state. The factory runs exactly once on the new thread and returns its local handler. Compilers supply the managed entry adapter; Base factories use native().
let context: void*?— The factory's context pointer, borrowed for the worker's life.let open: func(void*?, C) -> Outcome[Callback[M, R]]— Runs the factory on the new thread, yielding its handler or a failure.let enter: func() -> unit— The runtime hook run as the worker starts.let leave: func() -> unit— The runtime hook run as the worker ends.WorkerEntry.native(factory: func(C) -> Outcome[Callback[M, R]]) -> WorkerEntry[C, M, R]— A worker entry from a plain Base factory.
func worker_cancellation() -> sync.Cancellation*— Native operations called by a worker use this signal for interruptible socket waits. The pointer is borrowed on this worker until its factory/handler returns; it must not be retained outside the worker's lifetime or reset by application code.
let worker_closed: ErrorCode = ErrorCode.package(104)— The worker has been closed.
let worker_busy: ErrorCode = ErrorCode.package(105)— The worker's queue is full.
Worker (struct [C, M, R])#
A bounded persistent worker: a uniquely-owned handle over a thread, its queues and cancellation.
func init(entry: WorkerEntry[C, M, R], configuration: C,— Startentryon a new worker thread withconfiguration, waiting until it is ready.func send(message: M) -> !— Postmessageto the worker, blocking while its input queue is full.func try_send(message: M) -> !— Nonblocking backpressure: a full input queue returns worker_busy.func receive() -> Reply[R]!— The next reply, waiting for it. Replies preserve accepted-message order. Cancellation is terminal: queued replies are discarded by close, and blocked receivers wake with worker_closed.func try_receive() -> Reply[R]?!— The next reply if one is ready, none if not: a receive that never waits, for a caller that polls, as a UI frame does.func receive_within(milliseconds: u64) -> Reply[R]?!— The next reply, waiting at most aboutmillisecondsfor it; none when none came.func cancel()— Ask the worker to stop; cancellation is terminal and wakes blocked callers.func close()— Cancel the worker, join its thread, drain its queues, and free it.
c#
The C types (c.int, c.long, c.char, c.str, c.va_list, …) and the standard streams c.stdin(), c.stdout(), c.stderr() (§5.2, §17).