Under heavy development. This site describes the intended 1.0 language. Current features and performance vary. Development status
Sn50SnThe SnAPI programming language
Development · Evolving reference

Standard library

Public declarations. Practical examples. The details within reach.

Sn is under heavy development. This reference includes the intended 1.0 design; features may be incomplete in the current compiler. Read the status →

322 documented API pages

std.abi

BorrowedFromTies a borrowed pointer result to one zero-based source parameter.↗BorrowedFromLibraryDeclares a borrowed pointer result tied to the loaded library lifetime.↗ExportPublishes a body-bearing public native-qualified function or initialized public module storage.↗ImportBinds a bodyless native-qualified function, linked module storage or runtime import-table field.↗NativeAbiProfileSelects the foreign-language ABI profile at a native boundary.↗NativeFieldLayoutRefines one field offset or alignment inside a profile-qualified native type.↗NativeImportModeSelects linked or runtime symbol resolution for a native import.↗NativeLayoutRefines packing and alignment of an already profile-qualified native type.↗NativeLibraryOwns a primary image, optional companion and complete inline callable table.↗NativeLoadErrorClassifies recoverable failures when loading a typed native library.↗NoAliasPromises exclusive access through one pointer argument for the call.↗NoCapturePromises that a native call does not retain one pointer argument.↗NoReturnPromises that the annotated native callable cannot return normally.↗NoUnwindPromises that foreign unwind never crosses the annotated boundary.↗NonNullPromises a nonnull direct pointer parameter, result, or pointed result.↗PointeeAlignmentPromises a nonzero power-of-two minimum pointee alignment in bytes.↗ReturnsOwnershipDeclares that a successful native call returns one owned pointer.↗SynchronousCallbackPromises that one callback is invoked only before its native call returns.↗TakesOwnershipDeclares that a successful native call consumes one owned pointer.↗

std.collections

BitSetOwns an allocator-aware, densely packed sequence of Boolean bits.↗BitSetIteratorTraverses a borrowed packed bit sequence as Boolean values.↗BuiltinHashKeyProves the canonical default logical hash/equality operations for built-in keys. Admitted keys are integers, byte, IEEE numbers, bool, char, str and String. The compiler binds exact existing standard implementations; custom owners use an explicit HashKeyPolicy instead. No runtime witness, allocation, storage or lifecycle permission is introduced. Borrowed text keys still need live backing.↗CreateHashMapCreates an empty hash map using built-in logical key hashing.↗CreateHashSetCreates an empty hash set using built-in logical key hashing.↗CreatePriorityQueueCreates an allocation-free heap with a stored safe function policy.↗DefaultKeyHashHashes a supported built-in key using logical contents, without allocation.↗DequeOwns an allocator-aware circular sequence with efficient operations at both ends.↗DequeConsumingIteratorOwns a transferred deque and yields its FIFO payloads by ownership. Construction transfers allocator/backing without allocation or element moves. Each Next pops the front in O(1) bookkeeping, immediately destroying its valid moved-from slot. Remaining items and backing clean up on cursor destruction. No borrowed payload alias escapes; serialize traversal and cursor movement.↗DequeInsertionErrorOwns an uninserted deque item and its recoverable storage failure.↗DequeIteratorTraverses borrowed circular storage as readonly element references.↗HashKeyPolicyDefines the exact safe readonly hash/equality operations for a key type.↗HashMapOwns an allocator-aware, bounded linear-probed key/value table.↗HashMapEntryOwns a key/value pair transferred out of a hash map.↗HashMapEntryViewBorrows a stored map entry with readonly key and readonly value access.↗HashMapInsertionErrorOwns both uninserted map inputs and their storage failure.↗HashMapIteratorScans borrowed map buckets as readonly entry views.↗HashPolicyStores safely callable hash/equality functions as one concrete key policy.↗HashSetOwns an allocator-aware set with immutable stored-key observations.↗HashSetInsertionErrorOwns one uninserted set key and its recoverable storage failure.↗HashSetIteratorBorrows set keys readonly in unspecified bucket order.↗IndexableDefines the exact canonical read indexing protocol used by `Base[Index]`.↗PriorityComparisonStores a safe function comparator as a concrete priority policy.↗PriorityQueueOwns an allocator-aware binary heap and one safe comparison policy.↗VectorOwns a contiguous growable sequence and its explicit allocator value.↗VectorConsumingIteratorOwns a transferred vector and yields its elements in sequence order. Construction allocates nothing and transfers backing/allocator ownership. Next moves exactly one indexed referent, preserving each valid moved-from slot for normal vector cleanup. It never shifts elements or allocates a second buffer. Traversal bookkeeping is O(1); T lifecycle costs remain explicit. Destruction releases remaining values, moved-from slots and backing normally. No element references escape. Serialize traversal and cursor movement.↗VectorInsertionErrorReturns both allocation failure and unconsumed element ownership.↗WritableDequeIteratorTraverses borrowed circular storage as writable element references.↗WritableHashMapEntryViewBorrows a stored map entry with readonly key and writable value access.↗WritableHashMapIteratorScans borrowed map buckets as writable-value entry views.↗

std.compiler

std.compiler.prelude

std.diagnostics

std.format

std.fs

AsyncDirectoryIteratorOwns consuming directory traversal and transfers independent entry owners. Successful EOF is sticky. Native step failures end traversal; pre-step cancellation/admission failures permit retry. External synchronization is required; destruction closes remaining enumeration synchronously. No raw native entry or borrowed name escapes.↗DirectoryOwns incremental native directory enumeration with explicit errors. TryOpen requires an absolute native path. ReadEntry allocates an owned filename; prior entries survive later advances and owner cleanup. Ordering/snapshot stability is target-defined. Read/close/move require external serialization; mutable task loans retain ownership until completion. Close consumes authority even on failure. Destruction closes synchronously without reporting errors. Consuming cursors transfer this resource, rather than opening a hidden second enumeration or retaining a raw borrowed libc entry. The example below selects the Linux filesystem adapter; other stream providers do not require filesystem support. It performs no filesystem mutation.↗DirectoryEntryOwns a native filename and an optional advisory type hint. Name is one relative component, not an absolute/openable path by itself. It preserves non-Unicode native units. Enumeration movement/advance/cleanup never invalidates this owner. Kind is absent when the OS does not provide a hint; even present hints are not stable metadata or a race-free access guarantee. This value allocates through Path ownership and adds no synchronization.↗DirectoryIteratorOwns consuming directory traversal and transfers independent entry owners. Successful EOF is sticky. Next yields one error item then ends, preventing repeated terminal failures. External synchronization is required; destruction closes remaining enumeration synchronously. No raw native entry or borrowed name escapes.↗ExtendedAttributeWriteModeSelects one native extended-attribute creation/update policy. These cases are semantic identities, not target flags. No implicit fallback turns CreateNew into replacement or ReplaceExisting into creation. Values own no resource and allocate nothing; ordinary shared mutation needs synchronization.↗FileOwns one safe unbuffered native file with explicit close authority. TryOpen may allocate native path storage and perform filesystem I/O. Byte I/O permits short transfers; use std.io full-transfer/buffered helpers when needed. Flush is immediate because this owner has no user-space output cache; Synchronize makes durability explicit. Every operation except IsClosed may block. Noncopy movement transfers authority and leaves the source closed. Mutable receiver loans serialize position/I/O/close; external synchronization is required between threads. Destruction closes once without flush/sync and cannot report close failure; explicit Close provides recoverable diagnostics.↗FileKindClassifies a portable filesystem object snapshot. Cases are semantic identities, not target flag bits. Operations translate at the selected private platform boundary; this enum retains no resources.↗FileMetadataOwns an availability-aware snapshot of an opened filesystem object. None means the provider did not supply that field; a present zero remains an observed value. Times use UTC wall time, not monotonic deadlines. The snapshot allocates nothing and retains no file/path lease. Concurrent changes may make fields stale immediately; sampling is not promised atomic. Public edits affect only this detached value. Shared mutation requires synchronization. This example uses the Linux filesystem adapter and assumes no native mode values, timestamp ordering or birth-time support.↗FileOpenModeSelects open access and explicit file-creation behavior. Cases are semantic identities, not target flag bits. Operations translate at the selected private platform boundary; this enum retains no resources.↗FileSystemOwns cheap selected-provider capability observation. This stateless utility owns no native resource, current directory or mutable process state. Capabilities() allocates nothing and performs no native probe. The selected package determines the result; resource calls can still fail.↗FileSystemCapabilitiesOwns the selected provider's implemented-request inventory. True means an implementation exists, never permission, object support, field presence or guaranteed success. Individual operations remain authoritative. The snapshot allocates nothing, retains no resource and performs no probing; immutable publication permits concurrent observation. It is independent of native filename representation and ordinary stream capabilities.↗FileTimestampChangeOwns a paired access/modification timestamp update. Both fields are validated before one native operation. Keep/Keep changes nothing for a live owner. This does not promise a transaction with ownership, mode or other metadata changes. Changed/Created are observed timestamps, not freely writable portable fields. Values own no external state and allocate nothing; shared mutation requires synchronization.↗FileTimestampUpdateOwns one explicit file timestamp update policy. This value retains no resource and allocates nothing. Exact times may be negative; conversion checks native representability before applying either timestamp. Now is sampled by the native operation, not enum construction. Shared mutation requires synchronization. Native precision may be coarser than nanoseconds; requested exact values are not a storage-precision guarantee.↗FileWriteErrorPreserves both primary whole-file transfer and secondary close failures. Reason retains the proven transferred byte prefix. CleanupError is populated only when close also fails after an earlier transfer failure; successful writes followed by close failure use close as Reason instead. No rollback is implied. This record owns reasons, allocates nothing and retains no file/input view.↗LinkPolicyControls final-component symbolic-link selection on path operations. NoFollow rejects non-root trailing separators as InvalidInput rather than following the intended final link as an intermediate component. No trimming or normalization occurs. Intermediate components still resolve normally. This is not sandboxing. Follow selects the target; NoFollow metadata observes the link itself while data/directory opens reject it. Native exclusive creation still rejects an existing name. Values own no resource and allocate nothing.↗PathOwns immutable native filename units with explicit fallible text conversion. Native-byte and UTF-16 constructors preserve non-Unicode filenames while rejecting NUL. TryCreate uses the selected target's UTF-8 encoder. Construction copies fallibly; movement transfers backing, and TryClone explicitly copies it. No cwd lookup, filename normalization or filesystem operation occurs. Borrowed View/text views expire on owner movement/destruction. Concurrent reads of a published unmoved owner are safe under ordinary backing/lifetime rules.↗PathEncodingIdentifies exact native filename units without claiming valid Unicode. Byte paths can contain non-UTF-8 bytes; UTF-16 paths can contain unpaired surrogates. Embedded NUL is rejected separately. Encoding is representation, not permission to use an unsupported OS adapter.↗PathErrorPortable path representation/text-conversion failure. Invalid Unicode does not invalidate an already preserved native path. Failed owned construction/conversion leaves borrowed input unchanged and releases partial allocation. No host errno or native pointer enters this API.↗PathViewBorrows immutable native filename units without retaining their owner. Native units preserve filenames independently of Unicode validity. Construction rejects NUL and adds no normalization, separator rewriting, allocation or cwd lookup. Views expire with backing mutation/move/destruction. Copying a view does not retain backing. Concurrent access needs the backing owner's contract. TryToString allocates explicitly; TryViewUtf8 validates a borrowed byte view.↗PosixAccessOwns one POSIX read/write/execute mode-bit group. This snapshot allocates nothing, retains no resource and grants no access by itself. Execute means traversal for directories. ACLs, mount policy and caller identity can alter effective access. Shared mutation requires synchronization.↗PosixAclEntryOwns one semantic POSIX permission entry without native encoding. Canonical policy order is Owner, ascending unique User IDs, OwningGroup, ascending unique Group IDs, optional Mask, Other. Owner, OwningGroup and Other occur exactly once; named identities require a Mask. The mask limits named users and owning/named groups, never Owner or Other. Entries allocate nothing, retain no file and grant no access by construction. Numeric IDs are interpreted by the selected provider/identity namespace, not resolved as names. Shared mutation requires synchronization. Policies are not Windows ACLs or promises about effective caller access; kernel/filesystem policy remains authoritative.↗PosixAclScopeSelects stored object access or directory inheritance policy. These are POSIX policy domains, not platform wire tags. Neither observes effective caller access. Default policy governs subsequently created children; it does not mutate existing children. Provider/kind support can fail explicitly.↗PosixFileMetadataOwns explicit POSIX identity, ownership and mode metadata. Numeric IDs are scoped to the provider/host namespace; no account lookup is performed. Device/Inode identify an object during its native lifetime, not a globally unique identity after deletion/reuse or across providers. This value retains no resource and allocates nothing. Shared mutation needs synchronization.↗PosixFileModeOwns the twelve POSIX permission/special bits as semantic values. Owner/Group/Other describe mode groups; they are not a Windows ACL or a check of the current caller's access. Editing this value changes no native object. It allocates nothing, owns no external state and requires synchronization for shared mutation. Special bits retain their reported platform meaning.↗PosixOwnershipChangeOwns an explicit partial POSIX numeric ownership change. None preserves an identity; Some(0) is a real native identity. Numeric values are scoped to the target host, with no name lookup or implicit current-user substitution. Values unrepresentable by the native ID or equal to its reserved sentinel are rejected before changing anything. Changes may clear special mode bits according to POSIX; this is not an ACL replacement or transaction. This value allocates nothing; shared mutation needs synchronization.↗SeekOriginSelects the reference position for a signed byte displacement. Cases are semantic identities, not target flag bits. Operations translate at the selected private platform boundary; this enum retains no resources.↗

std.libc.cstdio

std.libc.math

std.libc.stdlib

std.posix.memory

std.posix.unistd

std.io

AsyncBufferedReaderOwns a fixed-capacity byte cache and its concrete AsyncReader source. Construction allocates; subsequent cache operations do not grow storage. Mutable receiver loans remain live across suspension; external synchronization is required. Movement transfers the source and cache, leaving the old adapter closed. Destruction never performs hidden I/O.↗AsyncBufferedWriterOwns a fixed-capacity byte cache and its concrete AsyncWriter source. Construction allocates; subsequent cache operations do not grow storage. Mutable receiver loans remain live across suspension; external synchronization is required. Movement transfers the source and cache, leaving the old adapter closed. Destruction never performs hidden I/O.↗AsyncReaderDefines a structural safe mutable byte-stream operation. Reads asynchronously while source/output loans remain live through completion. Successful/failed transfer counts may not exceed the supplied byte view. Implementations document blocking, retention and cancellation; the concept introduces no box, allocation, global stream or implicit event loop.↗AsyncWriterDefines a structural safe mutable byte-stream operation. Writes asynchronously while source/input loans remain live through completion. Successful/failed transfer counts may not exceed the supplied byte view. Implementations document blocking, retention and cancellation; the concept introduces no box, allocation, global stream or implicit event loop.↗BufferedReaderOwns a fixed-capacity byte cache and its concrete Reader source. Construction allocates; subsequent cache operations do not grow storage. External synchronization is required. Movement transfers the source and cache, leaving the old adapter closed. Destruction never performs hidden I/O.↗BufferedStreamCreationErrorPreserves source ownership when a buffered adapter cannot be created. Caller owns Source and may retry with a different capacity. No stream operation occurs during construction. This record adds no synchronization.↗BufferedWriterOwns a fixed-capacity byte cache and its concrete Writer source. Construction allocates; subsequent cache operations do not grow storage. External synchronization is required. Movement transfers the source and cache, leaving the old adapter closed. Destruction never performs hidden I/O.↗IoErrorClassifies portable output and byte-stream failures.↗IoFailurePortable byte-stream failure reason, independent of host errno. Transferred-prefix counts live in IoError.Failure, not this reason. Storage preserves its portable allocator identity. Cancellation/timeout does not silently roll back an already transferred prefix.↗PrintAttempts to write one complete borrowed UTF-8 view to standard output.↗ReadBytesCollects a complete byte stream into explicit owned storage. Reserves before each read so valid partial provider progress remains owned on failure. Short reads continue until successful zero-byte EOF. Counts are checked before indexing; source failure never discards the already consumed prefix. Geometric storage growth may retain spare capacity beyond the read scratch.↗ReadBytesAsyncCollects a complete byte stream into explicit owned storage. Reserves before each read so valid partial provider progress remains owned on failure. Short reads continue until successful zero-byte EOF. Counts are checked before indexing; source failure never discards the already consumed prefix. Geometric storage growth may retain spare capacity beyond the read scratch.↗ReadExactlyCompletes a byte read through bounded sequential short operations. Stops on error, validates every reported count and preserves the already transferred prefix. Zero-length input performs no source operation. No allocation, synchronization or hidden flush is introduced.↗ReadExactlyAsyncCompletes an incremental byte transfer by awaiting one short operation at a time. Preserves exact partial error identity/counts, validates reported lengths and adds no intermediate byte buffer or implicit flush. Zero length makes no source operation. Source and byte backing loans remain live until task completion.↗ReadTextCollects and strictly decodes a complete UTF-8 stream. Validation occurs after EOF, so a Unicode sequence may span short reads. Invalid encoding and allocation/provider failures retain consumed bytes; no replacement decoding, newline conversion or locale behavior is introduced.↗ReadTextAsyncCollects and strictly decodes a complete UTF-8 stream. Validation occurs after EOF, so a Unicode sequence may span short reads. Invalid encoding and allocation/provider failures retain consumed bytes; no replacement decoding, newline conversion or locale behavior is introduced.↗ReaderDefines a structural safe mutable byte-stream operation. Reads into caller-owned writable bytes; zero successful count means EOF. Successful/failed transfer counts may not exceed the supplied byte view. Implementations document blocking, retention and cancellation; the concept introduces no box, allocation, global stream or implicit event loop.↗StreamReadErrorOwns proven consumed bytes when whole-stream collection fails. Bytes includes valid partial provider progress before failure. Reason's count equals Bytes.Length; bytes are not silently refunded to the source. Source remains caller-owned. This record adds no synchronization or decoding.↗WriteAllCompletes a byte write through bounded sequential short operations. Stops on error, validates every reported count and preserves the already transferred prefix. Zero-length input performs no source operation. No allocation, synchronization or hidden flush is introduced.↗WriteAllAsyncCompletes an incremental byte transfer by awaiting one short operation at a time. Preserves exact partial error identity/counts, validates reported lengths and adds no intermediate byte buffer or implicit flush. Zero length makes no source operation. Source and byte backing loans remain live until task completion.↗WriteTextSubmits all UTF-8 bytes without implicit downstream flushing. Text is already valid UTF-8; byte transfer preserves exact encoding and reports byte-prefix counts. No intermediate byte storage or locale conversion is added.↗WriteTextAsyncSubmits all UTF-8 bytes without implicit downstream flushing. Text is already valid UTF-8; byte transfer preserves exact encoding and reports byte-prefix counts. No intermediate byte storage or locale conversion is added.↗WriterDefines a structural safe mutable byte-stream operation. Accepts caller-owned bytes; flush propagates accepted bytes downstream. Successful/failed transfer counts may not exceed the supplied byte view. Implementations document blocking, retention and cancellation; the concept introduces no box, allocation, global stream or implicit event loop.↗

std.iteration

AllTests whether every cursor item satisfies a safe predicate.↗AnyTests whether a cursor contains a safe-predicate match.↗AsyncIterableDefines a source creating independent async traversal state. The source documents whether independent cursors replay, partition or compete for items, and whether they borrow or retain backing. The protocol promises no implicit buffering, allocation, executor, thread safety or replay semantics.↗AsyncIteratorDefines an incremental, cancellation-aware task-producing cursor. Each mutable step is awaited before the next. Some yields the exact owned or borrowed item category; none is terminal EOF. Errors retain source-specific retry policy. Borrowed items retain normal origin/suspension/invalidation rules. Structural satisfaction adds no runtime box, collection or implicit executor. A safe ordinary method returning the exact task shape also satisfies this protocol. Implementations document retention, affinity and step costs.↗BinaryCallableDefines a safe readonly reducer with an exact Copy/reference accumulator.↗BinarySearchFinds the first equal element or its lower-bound insertion position.↗BorrowingCallableWhereIteratorOwns lazy filtering state and a concrete safe predicate environment.↗BorrowingUnaryCallableDefines safe readonly invocation borrowing one retained input item.↗BorrowingWhereIteratorOwns lazy filtering state that borrows each candidate without copying it.↗CallableAllConsumes a cursor with a concrete exact-item safe predicate.↗CallableAnyConsumes a cursor with a concrete exact-item safe predicate.↗CallableBinarySearchFinds the first equal element or lower-bound insertion position with a concrete comparator.↗CallableFindConsumes a cursor with a concrete exact-item safe predicate.↗CallableFoldReduces a cursor with an owned concrete callback and Copyable seed.↗CallableMapIteratorOwns concrete mapping callback state without type erasure or allocation.↗CallableSortSorts a writable slice through one owned concrete safe comparator.↗CallableWhereIteratorOwns lazy filtering state and a concrete safe predicate environment.↗CollectibleIteratorRequires cursor items that can implicitly become destination values.↗ConsumingBinaryCallableDefines a safe readonly reducer with an exact owned accumulator with explicit consuming access.↗CountConsumes a structural cursor and counts items through its first exhaustion.↗CountAsyncConsumes an async cursor one awaited step at a time and counts its items. Stops at first EOF or error, destroys discarded owned items normally, and adds no intermediate collection. Task/callback/source costs remain explicit. Count overflow uses ordinary checked arithmetic. A nonterminating source never produces a final count without cancellation or source failure.↗EnumerateIteratorOwns lazy cursor state that attaches checked indices to each item.↗FindSearches a cursor for its first safe-predicate match.↗FoldReduces a cursor left-to-right from an explicit Copyable seed.↗IndexedItemPairs a traversal index with an exact value or reference item.↗IntegerRangeStores one compiler-constructed fixed-width integer progression.↗IteratorDefines a zero-allocation mutable cursor that yields optional items.↗MapIteratorOwns lazy mapping state with an exact safe function callback.↗NullaryCallableRequires a safe readonly zero-argument invocation with an exact result.↗ScalarIteratorTraverses one valid UTF-8 view as Unicode scalar values.↗SkipIteratorOwns a lazy cursor that discards a fixed prefix on its first advance.↗SliceIteratorTraverses a borrowed contiguous sequence as read-only element references.↗SortRearranges a writable slice in ascending comparator order without allocation.↗TakeIteratorOwns lazy cursor state that yields at most a requested number of items.↗TryCollectMaterializes a cursor into a new Vector with an explicitly owned allocator.↗TryExtendConsumes a cursor and appends converted items to an owned Vector.↗TypedAsyncIteratorNames exact async item/error types without external associated projections. Structural satisfaction preserves safe task/result/optional shape and exact item ownership/access. Mutable steps must not overlap; errors and borrowed item validity remain the concrete source's contract. No runtime box is added.↗TypedIteratorNames an exact cursor item type without external associated-type projection.↗UnaryCallableDefines one safe readonly invocation with exact input and result types.↗WhereIteratorOwns lazy filtering state that forwards exact accepted item categories.↗ZipItemPairs items delivered in order by two independent cursors.↗ZipIteratorOwns two cursors and lazily pairs items until either input ends.↗

std.layout

std.logging

AsyncLogSinkDefines one concrete safe mutable diagnostic-record sink. A sink may retain input through terminal WriteAsync completion, and retains neither message view nor record input afterward. Implementations document allocation, blocking, synchronization and failures. No runtime dictionary or global logger is created by concept satisfaction.↗AsyncLoggerOwns an explicitly supplied concrete sink and severity threshold. No global logger, clock sample, boxed sink or implicit flush is introduced. Managed task/frame allocation follows the existing task-runtime contract. Writable sink and message backing remain borrowed through terminal completion. Sink operations retain their own costs and failures. Synchronize complete logger operations when sharing mutable state; separate loggers writing to the same underlying stream also require record-level synchronization. Destruction releases owned fields without performing hidden output.↗AsyncStreamLogSinkOwns an async byte writer and emits sequential diagnostic framing. No intermediate formatting buffer is allocated. Managed task/frame allocation follows the existing runtime contract; message/source loans survive suspension. Each enabled record is `[level] message\n` in UTF-8. Message bytes, including newlines and zero bytes, are preserved: this is diagnostic output, not an escaped audit format. The writer retains its own blocking and allocation behavior. Synchronize complete records when multiple callers share output; individual short writes do not establish record atomicity. Destruction never flushes. Record failures preserve the exact accepted prefix and do not retry the record automatically, because a retry could duplicate output.↗LogLevelDefines increasing diagnostic severity and explicit suppression. Levels describe filtering, not platform event IDs or ABI discriminants. Off disables output and never emits a record. Immutable values retain no state.↗LogSinkDefines one concrete safe mutable diagnostic-record sink. A sink retains neither message view nor record input after Write returns. Implementations document allocation, blocking, synchronization and failures. No runtime dictionary or global logger is created by concept satisfaction.↗LoggerOwns an explicitly supplied concrete sink and severity threshold. No global logger, clock sample, allocation or implicit flush is introduced. Sink operations retain their own costs and failures. Synchronize complete logger operations when sharing mutable state; separate loggers writing to the same underlying stream also require record-level synchronization. Destruction releases owned fields without performing hidden output.↗StreamLogSinkOwns a concrete byte writer and emits allocation-free diagnostic framing. Each enabled record is `[level] message\n` in UTF-8. Message bytes, including newlines and zero bytes, are preserved: this is diagnostic output, not an escaped audit format. The writer retains its own blocking and allocation behavior. Synchronize complete records when multiple callers share output; individual short writes do not establish record atomicity. Destruction never flushes. Record failures preserve the exact accepted prefix and do not retry the record automatically, because a retry could duplicate output.↗

std.math

std.memory

std.meta

std.net

AddressOwns an immutable numeric IPv4 or IPv6 address without allocation. Copies own independent fixed-size bytes. Numeric construction performs no I/O, lookup or parsing. IPv4 scope is zero; IPv6 scope zero is unspecified. A nonzero scope is an explicit interface identifier interpreted by the selected adapter. Public operations never rewrite IPv4-mapped IPv6 or discard scope. Concurrent readonly access is safe while the value remains alive and is not moved/replaced. Borrowed Bytes views expire on replacement, movement or destruction.↗AddressFamilyIdentifies an exact numeric IP address representation. Families do not imply reachability, DNS policy or native sockaddr layout. IPv4-mapped IPv6 remains IPv6; values are not combinable flags.↗DatagramReceiptOwns metadata for exactly one consumed UDP packet. Count is bytes copied into the supplied buffer. IsTruncated marks discarded unread tail; count is not the original packet size. Sender is an independent numeric endpoint. An empty packet has zero count and is not stream EOF. Immutable copied metadata retains neither buffer nor socket; readonly access is thread safe while this value is not replaced/moved.↗DnsResolves an explicit host through bounded blocking dispatch into owned addresses. Copies the host synchronously before returning; no borrowed host view survives admission. May allocate copied host, task frames and result vector. Native resolver may use hosts/configuration as well as DNS, retaining ordering/duplicates. Cancellation cannot interrupt an already-running platform call; completion waits for that call before discarding results and releasing storage. No unsafe is needed.↗EndpointOwns one numeric address and host-order port without native layout assumptions. Copying creates an independent fixed-size value. Construction never resolves names, opens a socket, allocates or validates remote reachability. Port zero represents an ephemeral local binding request; connection operations validate their own remote port requirements. Concurrent readonly access is safe while the value is not replaced or moved. No borrowed external storage is retained.↗NetworkErrorPreserves a portable reason and operation-relative accepted byte prefix. Transferred is neither cumulative stream position nor original packet length. Error values own no socket or borrowed storage and are safe to copy/read.↗NetworkFailureClassifies portable networking failures independently of errno. WouldBlock/InProgress preserve socket ownership and require readiness before retry. Cancelled/TimedOut belong to async operation policy; immediate calls do not manufacture them. Packet truncation is DatagramReceipt.IsTruncated instead.↗TcpListenerOwns one nonblocking TCP acceptance socket with explicit close authority. TryListen transactionally opens/binds/listens. TryAccept attempts one acceptance without waiting; WouldBlock is not a fake empty stream. Successful streams own independent close authority and outlive this listener. Mutable receiver loans serialize operations; shared use across threads needs external synchronization. Move closes the source logically. Destruction closes once without flushing.↗TcpStreamOwns one nonblocking TCP byte stream implementing structural Reader/Writer. Reads/writes may transfer a short prefix or return WouldBlock; no implicit wait, thread or loop is introduced. Mutable loans serialize operations and close; cross-thread sharing requires external synchronization. Move transfers close authority and leaves the source closed. Destruction closes once without flush; explicit Close reports errors and consumes authority even on native failure. Flush has no userspace cache to drain and never promises peer receipt/durability.↗UdpSocketOwns one nonblocking UDP socket with exactly-once close authority. TryBind acquires native resources transactionally. Immediate SendTo/ReceiveFrom never wait for readiness and may report WouldBlock. UDP preserves packet boundaries; partial consumption is a marked receipt, never a stream fragment. Mutable receiver loans serialize activity/close; sharing across threads needs external synchronization. Move construction transfers authority and closes the source. Destruction closes without flush and cannot report native close failure. Explicit Close retires the token before native activity and can report errors.↗

std.prelude

std.process

ArgumentsOwns ordered native argument values without shell interpretation. Empty arguments remain real elements. No host argv lookup, whitespace splitting, quoting, Unicode normalization or filesystem operation occurs. Structural mutation/movement/destruction invalidates borrowed references and cursors. Concurrent immutable reading requires an unmoved owner; synchronize mutation. Native startup capture and generated entry forwarding are separate operations.↗EnvironmentOwns an explicit ordered environment snapshot with exact native-unit keys. Find/TrySet/Remove search linearly; edits do not affect the host environment. Portable edits require nonempty names without equals. Windows startup decoding may also retain native pseudo names beginning with equals. Keys remain unique by ordinal native representation. Every name and value uses the same representation. This is an explicit portable model, not a Windows host-name comparison adapter. Entries expose readonly views only, preventing mutation of lookup keys. Structural edits/movement/destruction invalidate cursors and borrowed views; replacement invalidates views of the replaced entry. Concurrent reads require a stable owner; externally synchronize edits. No I/O or hidden process lookup.↗EnvironmentEntryOwns an exact native environment name and value without changing host state. Validation belongs to Environment.TrySet so rejected entries retain both owners. Names and values are immutable through this API; movement invalidates views. Concurrent reads require stable ownership; synchronize replacement/movement.↗EnvironmentSetErrorPreserves the exact rejected environment entry and its failure identity. Caller owns this error and may explicitly move Entry to another owner. No retry, text conversion or host mutation occurs. Synchronize writable access.↗EnvironmentSetErrorReasonIdentifies portable validation/storage failures of explicit environment edits. No host environment mutation occurs; the owning error retains the rejected entry.↗ProcessCommandOwns explicit subprocess executable, cwd, arguments and environment. Constructor/move transfer backing without launching, allocating or capturing host state. Arguments include explicit argv0; empty environment means empty. No PATH search, implicit shell, quoting or Unicode normalization occurs. Native admission validates absolute paths/representation/limits at execution. Moving or destroying this command invalidates views/references into it; externally synchronize edits and synchronous execution. Async execution consumes ownership.↗ProcessErrorOwns detached portable process failure and native diagnostic identity. No resource, address or borrowed text survives in the error. Published values can be read concurrently without synchronization.↗ProcessExitOwns detached normal or abnormal direct-child terminal observation. Nonzero Code is an ordinary successful outcome. NativeReason identifies target termination without synthesizing shell-style128 offsets. No storage or child lifetime remains. Immutable observations require no synchronization.↗ProcessFailureClassifies launch/admission/control failures separately from child exit. Nonzero exit is a successful ProcessExit. Native diagnostic numbers remain in ProcessError.NativeCode. Cancellation/timeout completion follows direct-child cleanup; no wall-clock kill bound is promised.↗ProcessStreamCompletionOwns the final process outcome and all transferred stream owners. Returned even after process/stream/admission failure so captured bytes remain inspectable. Movement/destruction invalidates aliases into these fields. No child, raw callback context or borrowed native buffer remains. Readonly access follows ordinary field mutability; concurrent mutation needs synchronization.↗ProcessStreamErrorPreserves native failures or an exact stream failure with its channel. Detached owned error has no borrowed spans or native resource. Stream errors retain the original operation's proven partial transfer metadata; prior chunks remain observable in the caller-owned sink. Native cleanup completes before publication.↗ProgramInputErrorIdentifies startup snapshot description, copy and environment parsing failure. A failed decoder returns no partial payload and does not release the borrowed native snapshot. Native startup owns capture/release. Error values retain no foreign pointer, errno or unit view. Invalid Unicode is preserved until an explicit text conversion, never rejected merely by snapshot decoding.↗ProgramInputsOwns an explicit argument/environment payload for startup and embedding. Construction transfers existing owners without allocation, host lookup or I/O. No ambient argv/environment alias remains. Ordinary mutations use the nested owners' checked APIs. Moving/destroying the payload invalidates borrowed owner references and every nested view/cursor. Concurrent reads require stable ownership; externally synchronize edits. Native capture/entry forwarding is separate from constructing this portable payload.↗RunProcessExecutes one explicit command synchronously through terminal cleanup. May allocate/spawn/block. Command input backing remains borrowed only through return. No unsafe block, implicit shell or ambient argv/environment/cwd is needed. Timeout/cancellation terminate the owned group and reap the direct child before failure returns; OS uninterruptible work has no promised wall-clock kill bound.↗RunProcessWithStreamsRuns an explicit command with borrowed reader/writer stream adapters. Feeds stdin while draining stdout/stderr; selected adapters override standard stream inheritance. Handles short writes without implicit flush or allocation per chunk. Original IoError survives with its channel and partial prefix.↗RunProcessWithStreamsAsyncConsumes command and stream owners for bounded blocking execution. Keeps every owner in the task frame through dispatch, native operation and cleanup. Returns streams on failure so captured output remains inspectable. No stream aliases are formed before dispatch suspension completes.↗WindowsEnvironmentErrorIdentifies explicit native Windows environment lookup failure. Unsupported hosts never substitute approximate case folding. Values own no native pointers or operating-system state. Absence is a successful optional result, not an error.↗

std.random

std.reflection

std.sync

AsyncEventOwns manual-reset signal state without a hidden runtime or application loop. Set publishes and wakes every pending wait; observations never consume signal. Reset affects future waits, never revokes committed notifications. Published readonly borrows can operate concurrently; moving owner authority needs external synchronization. Wait explicitly blocks; WaitAsync suspends on retained native registration. No fairness promise or automatic reset exists.↗AsyncEventErrorPortable manual-reset event setup/wait/operation failures. Ready/unsignaled try observation is bool; errors never fabricate or consume signal.↗AsyncMutexOwns retained payload with suspension-backed exclusive acquisition. LockAsync does not block a worker while awaiting ownership. Guards can cross await and have no native-thread unlock affinity. Recursive acquisition can deadlock; no fairness or starvation bound is promised. Published readonly owner borrows may acquire concurrently; moving the owner needs synchronization. Guards/wait leases retain state independently of visible owner cleanup.↗AsyncMutexCreationErrorOwns the input that could not enter retained AsyncMutex storage. Cleanup destroys the input normally; explicit move enables retry without copies.↗AsyncMutexErrorPortable AsyncMutex allocation/acquisition errors with no native storage escape.↗AsyncMutexGuardRetains exclusive writable payload access across suspension and worker resume. No OS-thread affinity; cleanup returns exactly one permit before releasing state. Noncopy, move-only, not move-assignable. References expire at move/destruction; independently retaining the owner cannot authorize access after guard release.↗AtomicOwns inline scalar storage accessed atomically after publication. Atomic operations synchronize only their documented publication; they do not make unrelated payload races safe. No allocation or native runtime is required. Noncopy; move only before publication or under external synchronization. Every operation on moved storage traps. Fetch integer arithmetic wraps modulo width. Sequential consistency is default; explicit orders are validated per operation.↗AtomicIntegerAuthenticated compiler predicate admitting integer storage widths through64 including target integers. Same-named user concepts retain ordinary structural meaning; no runtime witness.↗AtomicValueAuthenticated compiler predicate admitting bool, integer widths through64, target integers and raw object pointers. Same-named user concepts retain ordinary structural meaning; no runtime witness.↗ChannelOwns a bounded FIFO with suspension-backed send/receive backpressure. Creation pre-reserves all slots. Successful send transfers one owned payload; failed send returns it in ChannelSendError. Immediate receives distinguish temporary Empty from final Closed; asynchronous receives return optional EOF. Close stops new send commits and drains committed items before EOF. Cancellation can remove pending permit waits, never duplicate a committed payload. Published readonly borrows may operate concurrently; moving/disposal requires ordinary synchronization and live-loan rules. No fairness or waiter-order guarantee. Queue operations/Close briefly contend on an internal mutex; guards never cross await. Creation allocates; ordinary successful transfers do not grow backing. Destruction closes before releasing state; pending work retains private leases. Element move/destruction costs and traps remain those of T.↗ChannelAsyncIteratorRetains one channel's private FIFO state for incremental owned receives. Independent cursors compete for queue items; they do not replay a sequence. The visible Channel remains closing authority. After it closes, retained cursors drain buffered values before EOF. One mutable step may be outstanding; cursor movement/destruction obeys its live receiver loan. Construction retains state without allocating new backing. Each step has ordinary task/provider costs, awaits outside queue guards and briefly locks only during transfer. EOF is sticky. Cancellation/provider error does not latch EOF.↗ChannelErrorPortable bounded-channel failure identity, without native handles. Closed forbids new send commits; receive drains committed items before EOF. Cancelled never owns a second copy of a committed item. Allocation occurs at creation; lock/permit errors preserve their provider's portable identity.↗ChannelReceiveImmediate receive distinguishes an owned item, open-empty and closed EOF. Empty is temporary: later sends may publish items. Closed is final and occurs only after buffered items drain. Item owns exactly one transferred payload.↗ChannelSendErrorOwns the item that did not commit to a bounded channel. Moving the error transfers its item; destroying it destroys the unsent item. No extra allocation, shared duplicate or implicit retry occurs.↗LockCreationErrorRetains the input that could not acquire lock/payload storage. Destroying this error destroys its input normally. Explicit move transfers it; no extra allocation or native owner survives failed creation.↗LockErrorPortable lock setup/acquisition errors; contention is an optional result. No native errno, lock word or pthread type enters this API. Storage failures preserve the allocator reason; other statuses describe native setup/acquisition.↗MemoryOrderPortable atomic memory ordering, validated per operation.↗MutexOwns one retained exclusive mutex and its movable payload. Creation may allocate; guards retain payload/native storage independently. Separate readonly published borrows may acquire concurrently. Mutating/moving the owner handle itself requires external synchronization. Blocking acquisition occupies the calling thread; try acquisition reports contention as an optional. Guards release on their acquiring thread and cannot cross await. No fairness, lock upgrade or recursive exclusive acquisition is promised.↗MutexGuardOwns exclusive writable lock access and retained payload lifetime. Cannot copy, cross await or transfer threads. Move transfers only within the acquiring thread; moved guards are inert. Cleanup unlocks before releasing payload storage. Every returned reference expires at unlock/move/destruction.↗RwLockOwns one retained reader/writer lock and its movable payload. Creation may allocate; guards retain payload/native storage independently. Separate readonly published borrows may acquire concurrently. Mutating/moving the owner handle itself requires external synchronization. Blocking acquisition occupies the calling thread; try acquisition reports contention as an optional. Guards release on their acquiring thread and cannot cross await. No fairness, lock upgrade or recursive exclusive acquisition is promised.↗RwReadGuardOwns shared readonly lock access and retained payload lifetime. Cannot copy, cross await or transfer threads. Move transfers only within the acquiring thread; moved guards are inert. Cleanup unlocks before releasing payload storage. Every returned reference expires at unlock/move/destruction.↗RwWriteGuardOwns exclusive writable lock access and retained payload lifetime. Cannot copy, cross await or transfer threads. Move transfers only within the acquiring thread; moved guards are inert. Cleanup unlocks before releasing payload storage. Every returned reference expires at unlock/move/destruction.↗SemaphoreOwns bounded native semaphore permits independently from the task runtime. Separate published readonly borrows may wait/release/close concurrently. Moving the owner itself requires external synchronization. Wait blocks its thread; TryWait does not wait for a permit. Release publishes protected effects before successful acquisition. Close rejects new commits and wakes blocked waits; no FIFO/starvation guarantee or automatic permit release is made.↗SemaphoreErrorPortable semaphore operation/setup failures; try contention is a bool. InvalidCount and LimitExceeded commit nothing. Closed cannot revoke already acquired permits.↗

std.task

CancellationErrorClassifies checked cancellation authority creation failure.↗CancellationSourceOwns move-only cooperative cancellation authority with independently retained tokens. Creation allocates native request/binding state. Token access allocates nothing. Destruction releases authority without requesting cancellation. Requesting is thread-safe through distinct retained references; moving the same handle needs external serialization. Tokens do not imply completion or side-effect rollback.↗CancellationTokenRetains copyable cooperative cancellation observation independently of authority. Defaults are inert. Copies and observations allocate nothing. Distinct retained tokens may be observed concurrently; move/assignment of one handle needs external serialization. Destruction never requests cancellation or waits for completion.↗DeadlineDelayWaits for the original absolute monotonic boundary without extending it by resampling.↗DelayWaits without blocking a worker, using checked relative monotonic time.↗DelayErrorClassifies checked delay validation, cancellation and native scheduling failure.↗RunBlockingAsyncOwns a safe callback and executes it after bounded blocking admission.↗RunCpuAsyncOwns a safe callback and executes it after bounded CPU admission.↗SharePromotes an explicitly moved unique operation into repeated shared observation.↗SharedTaskRetains repeated readonly observation of one asynchronous completion.↗TaskOwns one single-consumer asynchronous operation without copying its frame.↗TaskDispatchErrorClassifies bounded CPU/blocking admission and cooperative cancellation.↗TaskScopeSupplies structured ownership for child work created inside an async body. RunAsync stores the body's result, requests remaining-child cancellation and joins all terminal cleanup before publishing that result. The supplied scope cannot be copied, moved or independently constructed by user code. It borrows its entry frame; body-local borrows still require explicit joins before their own cleanup. Scope destruction releases already-drained state without blocking. Infrastructure exhaustion follows fatal panic semantics, never early return while borrowed child storage remains in use. Cancellation is cooperative.↗WhenAllJoins owned task carriers and collects values in traversal order.↗WhenAllVoidJoins owned no-value tasks without allocating result storage.↗WhenAnyWaits for one unique input completion without consuming any result.↗WhenAnyErrorClassifies completion-only wait failure without changing input ownership.↗WhenAnySharedWaits for one shared input completion without consuming any result.↗YieldCooperatively queues a continuation on the captured executor without blocking it.↗YieldErrorClassifies cooperative yield cancellation and checked executor resolution failure.↗

std.text

CharacterClassificationClassifies the fixed Unicode White_Space scalar set without locale state.↗NativeStringOwns immutable native process text units with explicit fallible text conversion. Native-byte and UTF-16 constructors preserve non-Unicode native values while rejecting NUL. TryCreate uses the selected target's UTF-8 encoder. Construction copies fallibly; movement transfers backing, and TryClone explicitly copies it. No cwd lookup, native text normalization or filesystem operation occurs. Borrowed View/text views expire on owner movement/destruction. Concurrent reads of a published unmoved owner are safe under ordinary backing/lifetime rules.↗NativeStringEncodingIdentifies exact native process text units without claiming valid Unicode. Byte native strings can contain non-UTF-8 bytes; UTF-16 native strings can contain unpaired surrogates. Embedded NUL is rejected separately. Encoding is representation, not permission to use an unsupported OS adapter.↗NativeStringErrorPortable native string representation/text-conversion failure. Invalid Unicode does not invalidate an already preserved native string. Failed owned construction/conversion leaves borrowed input unchanged and releases partial allocation. No host errno or native pointer enters this API.↗NativeStringViewBorrows immutable native process text units without retaining their owner. Native units preserve native values independently of Unicode validity. Construction rejects NUL and adds no normalization, separator rewriting, allocation or cwd lookup. Views expire with backing mutation/move/destruction. Copying a view does not retain backing. Concurrent access needs the backing owner's contract. TryToString allocates explicitly; TryViewUtf8 validates a borrowed byte view.↗NumberParserProves invariant text parsing into one exact numeric representation. Built-in integer/IEEE types bind their existing exact source parser. Custom types may provide the same static member. Parsing returns owned values and retains no text backing; syntax/range policies are explicit in ParseError. This concept grants no lifecycle permission, allocation or runtime witness.↗ParseParses invariant decimal text into the selected numeric type.↗ParseErrorDistinguishes malformed invariant numeric text from an unrepresentable value.↗ReplaceCreates an owning UTF-8 string with ordinal nonoverlapping replacements.↗SearchCompares a borrowed prefix using ordinal UTF-8 bytes.↗SegmentsTraverses exact separator-delimited text as borrowed UTF-8 views.↗StringOwns one immutable valid UTF-8 byte sequence.↗StringBuilderOwns reusable mutable UTF-8 construction storage.↗TextSegmentsOwns allocation-free traversal state for borrowed fields or lines.↗TrimRemoves leading Unicode whitespace from a borrowed UTF-8 view.↗

std.time

DeadlineDistinguishes a finite monotonic deadline from explicitly endless waiting.↗DurationStores a count in a compile-time rational seconds unit.↗DurationCountProves finite count encoding and checked duration decoding for one representation. Built-in integer/IEEE counts bind the existing allocation-free source operations. Exact mathematical magnitude is independent of native timer width; conversion applies explicit rounding and reports finite range/precision failures. No count becomes endless through this protocol. No borrowed input is retained. Lifecycle/Data eligibility remains separately required by Duration.↗DurationDestinationRequires exact target-type construction from exact integer or finite IEEE time facts.↗DurationErrorClassifies finite time representation and period-conversion failures.↗DurationIntegerLiteralsConstructs an exact integer Nanoseconds value from compiler-supplied token text.↗DurationMagnitudePreserves exact integer or finite IEEE count facts for checked time conversion.↗DurationPeriodStores a strictly positive reduced rational time period measured in seconds.↗DurationRealLiteralsConstructs a finite f64-count Nanoseconds duration from exact real token text.↗DurationRoundingSelects explicit mathematical rounding when converting finite time units.↗DurationScaleStores a positive reduced source-to-target duration count multiplier.↗DurationUnitsNames an i64-count fixed duration unit of 1/1000000000 seconds.↗InstantOwns monotonic ticks and their private compatible clock domain.↗TimeErrorClassifies sampling, domain and checked time arithmetic failures.↗TimeoutDistinguishes finite relative waiting from explicitly endless waiting.↗TimestampStores a finite UTC timestamp distinct from monotonic clock time.↗TryAddDurationsCombines mixed integer duration representations using the wider RightRep count.↗TrySubtractDurationsCombines mixed integer duration representations using the wider RightRep count.↗
Documentation snapshot: October 24, 2026 About versions ↗
Searching Development · language & standard library