Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Standard library

The standard library is the set of modules under the reserved std namespace. They are written in Plenty or expose existing compiler facilities, and are embedded in the compiler: importing one needs no source installation, network, Cargo, or rustc. Native compilation still requires the supported linker environment. Using std.dataframe additionally requires its separately installed optional native engine; unused imports need no engine.

A standard module must be imported. Names available without an import belong to the prelude and are specified under built-in facilities.

Modules

ModuleContentsError type
std.actorSupervised actors on one thread, each with its own heap, bounded mailbox and copied messages; a trap discards only that actor’s heap and files; timers, request-reply and restartStartError, Undelivered[M], TimerError, RequestError[M]
std.actor.netTCP for actors: a listener that starts one actor per connection with admission limits, connections with bounded buffers, back-pressure and deadlines, and nonblocking connect and lookupNetError, TimerError, BytesError
std.actor.tlsTLS for actor connections: a std.tls session over a std.actor.net connection, with plaintext back-pressure and the session in the connection actor’s heapTlsError, TimerError
std.actor.http.serverHTTP/1.1 and HTTPS on isolated connection actors, bounded request/response handlers or resumable streaming events, deadlines and drainingServerError
std.archiveTAR and ZIP readers and writers over std.io, and extraction into a new directory under explicit path, link, and size limitsArchiveError
std.atomicInline atomic integers and booleans with compile-time checked orderings, and fencesNone
std.bytesCompact owning byte buffers with checked ranges, explicit copies and validated text conversionBytesError
std.cache.lruFixed-capacity caches that evict the least recently used entry, with constant-time lookup, promotion and evictionAllocError
std.channelBounded channels, endpoints and selectionChannel/send/receive/selection errors
std.cliExplicit typed options/positionals, repeatable values, generated help and lossless path argumentsCliError
std.cli.fileinputBuffered fallible UTF-8 lines across native paths or command-line files, with stdin fallbackFileInputError
std.cli.progressTerminal-only stderr bars and spinners with counts, rates, ETA and throttled redrawsProgressError
std.collectionsOwned binary heaps ordered by < or by a stored comparatorAllocError
std.complexComplex numbers over f64 with arithmetic operators, polar form, exp, log, sqrt, pow, and a+bi displayNone
std.compressBounded gzip, zlib, DEFLATE and Brotli compression of buffers and std.io streams, and CRC-32CompressError
std.concurrentExecutors, futures and parallel operationsPool/submission/future/parallel errors
std.cryptoDigests, HMAC, BLAKE3 hashing/key derivation, constant-time comparison, AEAD encryption, Ed25519, X25519, and HKDF over std.bytesCryptoError, AdvancedError
std.csvStreaming CSV readers and writers over std.io with explicit dialects, size limits, and positioned errorsCsvError
std.dataframeOptional Polars analytical expression plans, typed nullable columns, schema inspection, grouping, and CSV/Parquet I/ODataFrameError
std.db.kvOrdered byte-key maps, atomic transactions and bounded scans over a versioned SQLite storeKvError
std.db.sqliteSQLite databases through prepared statements with typed parameters and reads, owned transactions that roll back on drop, and an explicit value-size limitDbError
std.dequeOwned generic ring buffers with constant-time removal at either endAllocError
std.diffLine, word, character, byte, and list differences as edit operations, with Myers and patience algorithms and unified-diff outputAllocError
std.encodingHex, base32/base64, MIME base64 and validated custom alphabets, plus fixed-width integer and IEEE 754 float packing with explicit byte order, over std.bytesEncodingError
std.envEnvironment variables as text or bytes, a detached snapshot, and the working directoryIoError
std.errorExplicit error mapping, operation/path context, descriptions, and standard-error reportsMapper-selected error, Context[E], AllocError
std.fmtWriter-generic value/report formatting, bounded output and fallible stringsFormatError
std.fsDirectories, metadata/walking, symbolic links and canonical paths, rooted mutation, owned temporary resources, bounded file/tree copy, metadata preservation, delete/globIoError, AllocError, WalkError, FsError, TreeCopyError
std.fs.dirsThe home directory and the XDG configuration, cache, data, and state directories, from the environmentIoError
std.fs.lockOwned Linux shared/exclusive advisory locks, nonblocking and cancellable deadline acquisitionLockError
std.fs.watchBounded Linux filesystem change batches, rename cookies, overflow and readiness waitsWatchError, WaitError
std.graphDirected and undirected graphs with node and edge data, stable handles, traversal, shortest paths, topological order, components and spanning treesAllocError, GraphError
std.httpBounded HTTP/1.1 message heads and streamed Content-Length, chunked, and close-delimited bodies over std.io streamsHttpError
std.http.decoderResumable bounded HTTP/1.x request framing over caller-supplied bytes, without I/OHttpError
std.http.bodyBounded request bodies for handlers: URL-encoded forms, JSON, and multipart uploads into unnamed temporary filesBodyError
std.http.clientHTTP/1.1 client: pooled connections, deadlines and cancellation, bounded redirects, an explicit proxy, and replay of idempotent requests onlyClientError
std.http.cookieCookie fields read leniently and Set-Cookie fields validated against injection, with secure defaultsCookieError
std.http.filesStatic files below a Root, opened one segment at a time without following links, with media types and conditional requestsFilesError
std.http.httpsstd.http.client for https URLs through std.tls, verified by default, with CONNECT tunnels through a proxyClientError
std.http.proxyThe client address and scheme behind explicitly trusted reverse proxies; deployment guidanceProxyError
std.http.serverHTTP/1.1 server: routing, a bounded worker pool and admission queue, idle connections parked off the workers, per-phase deadlines, and graceful shutdownServerError
std.http.sseServer-Sent Events from a server exchange: event, id, multi-line data, comments and retry, flushed per event, with disconnect and shutdown detectionSseError
std.http.tlsstd.http.server over std.tls, with handshake deadlinesServerError
std.http.typedTyped head parsing and writes, fixed/chunked/close-delimited bodies, and guarded connection recovery with concrete causes and progressFramingError[E], Partial[E]
std.http.websocketRFC 6455 WebSocket connections: the handshake as a server exchange or a ws client, bounded framed messages, pings and the closing handshakeWebSocketError
std.http.wssstd.http.websocket clients for wss URLs through std.tlsWebSocketError
std.imageOwned 8-bit pixel buffers, bounded PNG decoding and encoding, cropping, colour conversion and resizingImageError
std.ioPartial-progress byte stream contracts, retry helpers, fixed-capacity buffering, file and process-stream adapters, and checked sequential binary fields in an owned memory cursorStreamError, Partial, CopyError, CloseError, BinaryError
std.io.typedByte stream protocols that carry a caller-chosen error type, buffering, adapters for std.io streams, and exact read, write, and copy helpersStepError[E], Partial[E], CopyFailure[R, W]
std.jsonStrict JSON under depth, input, and output limits: resumable event decoder, validating encoder, and a value treeJsonError
std.jwtJSON Web Tokens: compact JWS signing and verification with the algorithm fixed by the key, strict decoding, and explicit-clock claim checksJwtError
std.logLeveled events with typed fields, delivered to caller-chosen sinks: logfmt lines, bounded memory, or a nonblocking channelLogError
std.markdownCommonMark 0.31.2 parsing into events and HTML rendering, under input, depth, and output limitsMarkdownError
std.templateBounded Jinja-style text templates with explicit JSON values, HTML escaping, conditions, loops and named inheritanceTemplateError
std.mathFloating-point functions, checked rounding, integer algorithms, integer and float helpers, and constantsMathError, OverflowError[T]
std.mimeMedia types: RFC 9110 parsing and formatting with parameters, media-range matching, and the file-extension tableParseError, AllocError
std.netTCP listeners and streams, UDP sockets, IP addresses and name lookup, with deadlines and cancellationNetError
std.pathLossless Linux paths, lexical operations, checked text conversion and escaped displayIoError, AllocError
std.processChildren spawned from an argument vector with no implicit shell, piped streams, bounded output collection, signals, and explicit reapingIoError, StreamError
std.randomCaller-owned seeded generators with unbiased ranges, shuffling, and index sampling; not for secretsRandomError
std.readyReadiness waits on pipes and other handles, bounded by a deadline and a cancellation tokenWaitError
std.regexLinear-time regular expressions over text and bytes: search, captures, iteration, split, and replacement under explicit pattern, memory, and work limitsRegexError
std.reportBounded human-readable report rendering with std.fmtFormatError
std.secretsOperating-system entropy: secret bytes, hex and base64url tokens, and unbiased integers, with no fallback sourceSecretsError
std.shlexShell-style word splitting and POSIX argument quoting, without execution or expansionShlexError, AllocError
std.sketchBounded distinct counts, sampled quantiles and frequent-item bounds with versioned checkpointsSketchError, AllocError, BytesError
std.sketch.xorStatic approximate membership over numeric identities with bounded constructionSketchError, AllocError, BytesError
std.sketch.cuckooScalable approximate membership with bounded growth and receipt-directed deletionSketchError, AllocError, BytesError
std.signalSIGTERM and SIGINT as an event to wait or select on, and a helper that cancels a token on oneSignalError, WaitError
std.simdPortable fixed-lane values, masks, checked and wrapping arithmetic, selection, and bounded list loads/storesNone
std.statDescriptive f64 statistics, inclusive quantiles, and normal, uniform and exponential distributions with explicit RNG samplingStatError
std.plotLayered charts from owned columns or record accessors, validated mappings, grouped statistics, and deterministic streaming SVGPlotError
std.linalgDense f64 matrices, products, solves, LU, QR, Cholesky, SVD and eigen decompositions through an optional faer engineAllocError, LinalgError
std.syncShared cooperative cancellation tokensAllocError
std.systemBounded Linux procfs snapshots: CPUs, memory, load, uptime, block devices, disk I/O and process statusIoError, SystemError
std.tempfileUnnamed and named temporary files, recursively cleaned directories, context managers and explicit ownership transferIoError, FsError, StreamError, AllocError
std.testAssertions that explain their failure on standard error, self-removing scratch directories, the seeded generator for plenty test, and fake clocks and streamsTestError
std.textBounded builders, joining, scalar/word wrapping, shortening, and indentationTextError
std.threadExplicit scoped thread and owned-job importsThreadError, SpawnError[F]
std.timeChecked durations, monotonic instants and deadlines, wall timestamps, and sleepRangeError
std.tlsTLS 1.2 and 1.3 client and server streams over std.net TCP, with verified certificates, client certificates, ALPN, deadlines, and cancellationTlsError
std.tomlStrict TOML 1.0 parsing, value-tree writing and format-preserving document edits, under depth, input, and output limitsTomlError
std.unicodeUnicode 17 normalization, combining classes, and Mark classificationTextError
std.unitsSI dimensions, prefixed and common units, physical constants, and dimension-aware square roots, sums and trigonometry over QuantityMathError, RangeError
std.units.catalogueEvery SI prefix on every SI unit and the other named units of NIST SP 811None
std.urlStrict RFC 3986 absolute URL parsing and formatting without normalization, component-aware percent encoding, and query pairsUrlError
std.uuidUUID values, canonical text and network bytes, random v4 and timestamp-prefixed v7 generationParseError, BytesError, SecretsError, RangeError
std.xmlBounded UTF-8 XML event readers and validating stream writers, without DTDs or external entitiesXmlError

The generated signature index lists every public declaration of every module on one page. Standard library conventions states the naming, error, parameter and type rules public modules follow, and where modules still differ.

Planned modules appear only in the backlog. The tutorial introduces the library in Use the standard math library, Enumerate and classify paths, and Prune before descending.

Importing a standard module

Standard modules use the ordinary import forms:

import std.math
import std.math as math
from std.math import sqrt, pi
from std.math import MathError as Error

An import binds only the names it lists. import std.math requires the full std.math.sqrt qualification; an alias shortens it.

std is reserved. Each of these is an error:

  • a std directory, std.plenty, or std.plentyi in the source root;
  • a declaration named std;
  • an import that binds a non-standard module as std.

An unknown standard module, including a bare import std, is an error that lists the available modules. It never falls back to a local file.

How standard modules are compiled

A standard module passes through ordinary parsing, visibility checks, type checking, specialization, and native emission. Its private helpers stay private. Repeated imports, through any alias or dependency path, share its nominal types, so a MathError from one module equals a MathError from another. The scope rationale records when a module uses a native library instead of Plenty source.

The four concurrency modules export canonical builtin identities instead of wrapper functions. Their imports reach the existing ownership and worker checks directly, including scoped joins and blocking-wait diagnostics. Their prelude spellings remain available. Importing one of these under its own builtin name is permitted only when it denotes the same builtin; unrelated name collisions remain errors. Generic constructor and error aliases retain the same types.

Embedded modules have toolchain identities such as std/math.plenty, independent of the installation path. A diagnostic located inside a standard module, such as a note on a generic helper instantiated with an unsupported type, uses that name. The source-only APIs (check_source, compile_source_*) have no source root, so they can import std modules but not project modules.

The runtime packaging page describes how the sources ship with the compiler.

Reading a module page

Each module page gives every public function’s signature and states:

  • whether it returns a plain value or a Result, and which error variants it reports;
  • whether it borrows or consumes its arguments;
  • whether it allocates;
  • the limits that differ from the Python module of the same name.

Recoverable failures use typed errors: std.math defines MathError, while std.path and std.fs share the native IoError and storage AllocError. The filesystem walker adds WalkError to retain attempted paths and operations. ? propagates an error to a caller returning the same error type or Failure. std.error states the conventions modules follow for typed causes, native codes, and allocation failure. Module functions accept named arguments and defaults; the signature index shows each default.

Acknowledgements