Module std.builtins

Built-in types, traits, and functions available in every Hew program.

No import is needed. This page includes actor delivery and lifecycle types, machine interfaces, core traits, assertions, conversion, and program control functions. Focused operations also appear in their std modules.

Contents

Functions

Function println

pub fn println<T: Display>(value: T)

Print a value followed by a newline.

Accepts any type that implements Display.

Examples

fn main() {
    println(42);
    println("hello");
    println(true);
}

Function print

pub fn print<T: Display>(value: T)

Print a value without a trailing newline.

Examples

fn main() {
    print("Enter name: ");
}

Function assert

pub fn assert(condition: bool)

Assert that a condition is true, raising a recoverable logical fault when it is false.

A failure reports the condition's source text. When the condition is a comparison (==, !=, <, <=, >, >=), both operands are evaluated once and shown, with a line diff when either value spans lines. The optional second argument, assert(condition, message), is a string evaluated only when the assertion fails.

Examples

fn add(a: i64, b: i64) -> i64 {
    a + b
}

fn main() {
    assert(add(1, 2) == 3);
    assert(add(2, 2) > 3, "sums grow");
}

Function to_string

pub fn to_string<T: Display>(value: T) -> string

Convert any value to its string representation.

Accepts any type that implements Display — this includes all numeric primitives, bool, char, string, and user types with a Display impl.

Examples

fn main() {
    let s = to_string(42);     // "42"
    let t = to_string(true);   // "true"
    let u = to_string('x');    // "x"
}

Function sleep

pub fn sleep(d: duration)

Pause execution for the given duration.

The caller suspends cooperatively (inside an actor handler) or blocks the thread (in fn main / free functions).

Sub-millisecond semantics (context-dependent)

Sub-millisecond values behave differently depending on the execution context:

  • Actor handlers (cooperative suspend): the duration is converted to milliseconds (floor). A sub-ms value (e.g. 500ns) becomes 0ms, which arms a zero-deadline timer wheel entry and still suspends and resumes the actor at the next scheduler tick. The actor is never truly sleeping for the nanosecond count.
  • fn main / free functions (blocking): the OS sleep is requested at full nanosecond precision. sleep(500ns) sleeps for approximately 500 ns (subject to OS timer granularity, typically ≥1 µs on Linux/macOS).
  • WASM target: the duration is converted to milliseconds and rounded up to a minimum of 1 ms. sleep(500ns) becomes sleep(1ms) on WASM.

Examples

fn main() {
    sleep(10ms);   // sleep for 10 milliseconds
    sleep(2s);     // sleep for 2 seconds
    sleep(500ms);  // sleep for 500 milliseconds
}

Function sleep_until

pub fn sleep_until(target: instant)

Pause execution until the given monotonic instant.

If target is already in the past, returns immediately. Use instant + duration to construct a future instant:

fn main() {
    let deadline = instant.now() + 10ms;
    sleep_until(deadline);   // wait until 10 ms from now
}

The instant + duration operation adds a duration offset to a monotonic timestamp, returning a new instant. The commutative form (duration + instant) also works.

Examples

fn main() {
    let deadline = instant.now();
    // ... do work ...
    sleep_until(deadline);   // wait until the deadline if not yet reached

    // Sleep for exactly 50 ms from a fixed reference point:
    let t0 = instant.now();
    // ... do work ...
    sleep_until(t0 + 50ms);  // accounts for time already spent
}

Function exit

pub fn exit(code: i32)

Terminate the program immediately with the given exit code.

This function never returns and does not run scope cleanup. Return from main for orderly cleanup. An unrecovered fault instead reports its diagnostic and exits with status 1 on the native path.

Function panic

pub fn panic(message: string)

Terminate the program with an error message.

This function never returns.

Examples

fn main() {
    panic("something went wrong");
}

Types

Struct NodeId

Stable key-derived node identity.

Methods

via Display

fn fmt(self) -> string

Struct ActorId

Identity of one live actor incarnation. This value grants no actor access.

Fields

value: u64

Methods

via Display

fn fmt(self) -> string

Enum Caller

The authenticated origin of a received handler call.

Variants

Actor(ActorId)
Task
Timer
Node(NodeId)

Struct Call

One handler delivery, consumed by exactly one of proceed or refuse.

Struct Outcome

A completed handler delivery, returned by its interceptor.

Struct Location

Complete remote actor location.

Methods

via Display

fn fmt(self) -> string

Struct SourceLocation

Source position of a compile-time invocation.

Fields

file: string
line: i64
column: i64

Enum NodeTransport

Authenticated distributed node transports. Ordinary QUIC sockets use std.net.quic.

Variants

Tcp
QuicMesh

Struct NodeConfig

Configuration supplied once to Node.start. Set key to a non-empty identity-file path; NodeConfig.at leaves it empty. Keep that file across restarts so the node identity remains stable.

Fields

bind: string
transport: NodeTransport
key: string
cluster: string
seeds: Vec<string>

Enum NodeError

A node lifecycle operation could not apply the supplied configuration.

Variants

Config
Key
Unreachable
Refused

Methods

via Display

fn fmt(self) -> string

Struct ActorMailbox

An immutable one-way view for void receive handlers. Construct one with mailbox(target, on_full: ...). A receive call through the view submits under that policy and returns as soon as admission or a policy-selected discard is resolved. The policy type records whether submission can suspend. A call on the actor handle itself waits for the handler to finish instead.

Fields

target: Target

Struct ActorTimerMailbox

An actor-owned one-shot submission view. Construct with mailbox(self, after: delay, overdue: limit); overdue is optional.

Fields

target: Target
after: duration
overdue: duration
has_overdue: bool

Struct Timer

A cancellation handle for an actor-owned one-shot request. Dropping this handle does not cancel the request. The handle cannot be sent to another actor; stopping or restarting its owner cancels pending timers.

Struct ActorPolicy

An immutable completion view choosing how its own calls are admitted. Construct one with policy(target, on_full: ...). A call through the view waits for the handler exactly as a call on the actor handle does; the policy decides only what happens when the destination mailbox is full. .Wait is the bare-handle behaviour; .Reject yields ActorError.Rejected(failure) instead of parking the caller.

Fields

target: Target

Struct Message

Owned request description for one-way submission recovery. Consuming retry() and to(target) retain the request's typing.

Fields

target: Target
message_id: u32
payload: Payload

Struct ActorRequestOwner

Internal owner of an unaccepted completion request.

Struct ActorRequestAdmission

Struct ActorRequest

The request protocol is a sealed, inferred type parameter. The original payload stays inside its runtime owner until admission or cleanup.

Fields

owner: ActorRequestOwner

Struct SendFailure

A rejected submission retains its complete unaccepted message.

Fields

reason: SendError
message: M

Methods

via Display

fn fmt(self) -> string

Enum Delivery

Successful submission describes acceptance or a discard. A discard is a loss either the destination's declared mailbox policy or the sender's own on_full chose; the message is gone either way and nothing is retryable.

Variants

Accepted
Discarded

Methods

via Display

fn fmt(self) -> string

Enum OnFull

A sender chooses how its own submission responds to a full mailbox.

Variants

Reject
Wait
DropNewest

Struct RejectSend

Struct WaitSend

Struct DropNewestSend

Enum SendError

Error returned when a send cannot be completed.

Variants

Full

The destination mailbox is full.

Closed

A sink or connection has closed.

Partition

The route to the peer is unavailable or the peer is suspected dead.

StaleRef

The pid refers to an old session or actor incarnation.

LocalShutdown

The local node is shutting down before the send can complete.

Cancelled

The caller cancelled the send before it completed.

VersionMismatch

The peer rejected the send because protocol or schema versions differ.

Backpressure

The destination or route is applying flow control.

Dead

The destination actor accepts no more messages.

WriteTimedOut(i64)

A socket write passed its deadline after this many bytes of the item reached the operating system. The peer's view of the stream is unknown, so the caller retires the stream.

Unauthorized

The peer refused this message's grant before admission.

InvalidMessage

Encoding or decoding refused the message before admission.

TimedOut

The request deadline expired before admission.

MessageTooLarge

The complete encoded message exceeds the destination route's capacity.

Methods

via Display

fn fmt(self) -> string

Enum LookupError

Error returned when Node.lookup(name) cannot resolve a discovery location.

Returned as Err(LookupError.NotFound) when no actor is registered under name on the current node (or any peer with a gossiped name). The variants below cover missing names, unavailable routes, stale references, and caller cancellation.

Variants

NotFound

No actor is registered under the requested name.

Partition

The lookup route is unavailable or the peer is suspected dead.

StaleRef

The name resolved to an old session or actor incarnation.

Cancelled

The caller cancelled the lookup before it completed.

LocalShutdown

The local node is shutting down before the lookup can complete.

VersionMismatch

The peer rejected the lookup because protocol or schema versions differ.

Methods

via Display

fn fmt(self) -> string

Enum Never

The error of a handler that cannot fail.

Never has no values, so ActorError<Never>.Failed can never be constructed: a call on an infallible handler reports transport and lifecycle outcomes only.

Methods

via Display

fn fmt(self) -> string

Enum ActorError

Error of a completion call on an actor handle.

E is the handler's declared fails type — Never when the handler cannot fail. Req carries an unaccepted request when admission may reject it. Omitted parameters default to Never.

Only Rejected is safely retryable: nothing was accepted, so the caller may make the same call again. Other variants do not return the request or establish whether its handler ran; repeating it may duplicate work.

Variants

Rejected(SendFailure<Req>)

Nothing was accepted. failure.reason explains why; failure.message.retry() or .to(target) consumes the sealed request.

Failed(E)

The handler ran and returned its declared error.

Refused

An interceptor refused the delivery before the handler ran.

Trapped

The handler faulted; its actor retains ownership of the fault.

Dead

The destination actor is gone and will not come back.

TimedOut

The caller's deadline elapsed before a reply arrived.

NodeNotRunning

The local node is not running, or is shutting down and refused this call before admitting it. A policy(target, on_full: .Reject) call refused by shutdown reports Rejected with SendError.LocalShutdown instead and returns its request.

RoutingFailed

The destination node or actor could not be routed.

EncodeFailed

The request or reply payload could not be encoded or decoded.

ConnectionDropped

The remote connection closed before the reply arrived.

Partition

The route to the peer is unavailable or the peer is suspected dead.

MessageTooLarge

The complete encoded request or reply exceeds the route's capacity. A reply refusal may follow handler execution; it is not safe to retry.

Methods

via Display

fn fmt(self) -> string

Enum LinkError

Failure to subscribe to an actor's exit through link or monitor. Both operations require a current actor to receive the notification; a target that is already dead or unreachable is not an error, it answers with an immediate exit or DOWN.

Variants

NoContext

Methods

via Display

fn fmt(self) -> string

Struct MachineDeparture

Ordered, opt-in snapshots taken after exit hooks and before transition bodies.

Fields

target: S
subtree: T

Struct MachineObservedStep

Fields

report: R
departures: Vec<MachineDeparture<S, T>>

Enum MachineStepError

A bounded machine step did not commit its staged configuration or outputs.

Variants

InvalidLimit
LimitExceeded

Methods

via Display

fn fmt(self) -> string

Enum MachineDisposition

Variants

Taken
Ignored

Struct MachineStepInfo

Fields

input: string
rules: Vec<i64>
disposition: MachineDisposition

Struct VecIter

An owned double-ended cursor backed by ordered option slots.

Construction moves the elements into an ordered Vec<Option<T>> and adds one empty scratch slot. Each step exchanges its selected slot with the scratch slot, pops the owned option, and restores the empty scratch slot. Untaken elements remain in logical order, so early drop releases them in that order. Exhaustion leaves a live cursor that drops at scope exit.

Construction takes O(n) time and an additional O(n) buffer, including one option tag per element. An unshared cursor's end steps take O(1) time without cloning elements. Detaching a copied cursor follows ordinary Vec copy-on-write rules and can take O(n) time. Value-copy rules preserve independent source and cursor copies when their elements support cloning; clone-free elements remain owned.

Fields

slots: Vec<Option<T>>
front: i64
back: i64

Methods

via Iterator

fn next(var self) -> Option<Self.Item>

via DoubleEndedIterator

fn next_back(var self) -> Option<Self.Item>

Struct StringIter

A snapshot cursor over a string's Unicode scalars.

Fields

text: string
front: i64
back: i64

Methods

via Iterator

fn next(var self) -> Option<Self.Item>

via DoubleEndedIterator

fn next_back(var self) -> Option<Self.Item>

Struct HashMapIter

An owned snapshot cursor over a map's paired keys and values.

Each yielded pair is independently owned. The source map remains usable, and later changes to it do not affect this cursor. Iteration order is unspecified. Exhaustion leaves the cursor live until ordinary scope cleanup.

Fields

ks: Vec<K>
vs: Vec<V>
idx: i64

Methods

via Iterator

fn next(var self) -> Option<Self.Item>

Struct timestamp

An absolute Unix wall-clock moment with nanosecond precision.

Construction and field access are sealed by the compiler. Use the explicit Unix-unit methods; a timestamp never implicitly becomes an integer or instant.

Fields

seconds: i64
nanoseconds: u32

Enum TimestampError

An invalid normalized timestamp or an overflowing Unix-unit conversion.

Variants

InvalidNanoseconds
OutOfRange

Methods

via Display

fn fmt(self) -> string

Enum ScopeFailure

A structured scope failure, available only after child and deferred cleanup. Parent cancellation propagates to the enclosing scope and is not recoverable here.

Variants

Deadline { message: string }
Fault { message: string }

Methods

via Display

fn fmt(self) -> string

Traits

Trait Machine

A machine's ordinary staged evaluator and committed transition metadata.

Methods

fn step_observed_with_limit(var self, event: Self.Event, limit: i64, requested: Vec<Self.Scope>) -> Result<MachineObservedStep<Self.Step, Self.Scope, Self.Subtree>, MachineStepError>
fn step(var self, event: Self.Event, limit: i64 = 1024) -> Result<Self.Step, MachineStepError>
fn step_info(self, report: Self.Step) -> MachineStepInfo

Trait Iterator

Produce a sequence of values one item at a time.

User-defined iterators implement this trait directly; for loops accept values whose type implements IntoIterator and walk the resulting Iterator to bind each yielded Item.

next takes its receiver mutably (var self): iterator implementations step their internal state in place (cursor advance, decrement remaining, flush a buffer) and surface successive items through the Option<Self.Item> return. Callers must hold the iterator in a var binding so that the mutated receiver remains observable between calls; binding the iterator with let is rejected by the checker with a "receiver requires mutable binding" diagnostic.

Iterator methods with mutable receivers keep the iterator Live past exhaustion; drop fires at scope exit, not at the None return. This is a deliberate shift from a hypothetical by-move shape: exhaustion is a Some → None boundary, not a lifetime boundary. Iterator implementations that own non-shared resources (heap-owning buffers, channel readers) inherit the "exhaustion ≠ drop" invariant — see the lifecycle-symmetry invariant in docs/internal/engineering-invariants.md.

Methods

fn next(var self) -> Option<Self.Item>

Trait DoubleEndedIterator

An iterator whose front and back share the same remaining items.

Methods

fn next_back(var self) -> Option<Self.Item>

Trait IntoIterator

Convert a value into an Iterator.

For trait-based iteration, a for loop creates a mutable iterator and calls next() until it returns None. The item type is <Self.IntoIter as Iterator>.Item. Built-in collections also support borrowed iteration; a loop over an unbounded generic Vec<T> borrows its elements rather than taking ownership of them.

IntoIter carries the Iterator<Item = Self.Item> bound so that callers projecting <T as IntoIterator>.IntoIter.Item always agree with <T as IntoIterator>.Item. Concrete IntoIterator impls live next to each collection (Vec, HashSet, HashMap); this trait declaration reserves the surface only.

Methods

fn into_iter(consume self) -> Self.IntoIter

Trait Index

c[i] and c.get(i) for EVERY indexable collection resolve through this trait. A new collection type gets both accessors by writing one impl — no compiler change (the A195 mandate).

  • get(self, i) -> Option<Self.Output> is the FUNDAMENTAL safe accessor: None on out-of-bounds/absent, else Some(elem) where the payload is a FRESH, independently-droppable owner (retain-share for strings, deep clone for owned records/enums, by-value for scalars). The container is borrowed, not consumed.
  • at(self, i) -> Self.Output is the TRAPPING accessor: c[i]. It asserts presence and traps (TrapKind.IndexOutOfBounds) on absence.

Idx is a trait TYPE PARAMETER (not an associated type) so a collection may index by more than one key type (Vec/bytes/string by i64; HashMap by K), and a future Index<Range> slicing convergence is accommodated.

Leaf containers (Vec/HashMap/bytes/string) carry intrinsic bodies the compiler lowers directly (the index_get/index_at lang-items); user composites write ordinary Hew bodies that delegate to a leaf's get.

Methods

fn get(self, index: Idx) -> Option<Self.Output>
fn at(self, index: Idx) -> Self.Output

Trait Display

Convert a value of type Self into a human-readable string.

Implementing Display for a type lets it flow through print, println, to_string, len, and stop. The trait method must return a string derived from the receiver without invoking print itself (otherwise the output path becomes recursive).

Blanket impls below cover the primitive numeric kinds, bool, char, and string; user types add their own impls per receiver.

Methods

fn fmt(self) -> string

Trait Error

The marker an error type carries so it can be erased to dyn Error.

Error adds no methods of its own: an error is a value that can say what went wrong, so Display is the whole obligation. impl Error for MyError {} on a type that declares no Display supplies one: the variant name, then ": " and the payloads, each through its own Display.

Trait From

Declares that a Source error converts into Self where a failure leaves a function. ? and return error apply it; everywhere else the conversion is the explicit call Target.from(value).

A conversion never chains, and erasure into dyn Error needs no impl.

Methods

fn from(value: Source) -> Self

Inherent methods

impl Timer

fn cancel(self)

Before firing, cancel delivery. After firing, disarm only the overdue check.

impl Location

fn node_id(self) -> NodeId

Return the stable node identity.

fn incarnation(self) -> u32

Return the node-session incarnation.

impl<T> Vec<T>

fn swap(self, left: i64, right: i64)

Exchange two owned elements. Both indices must be in bounds.

impl<T> Vec<T>

fn iter(self) -> VecIter<T>

Create an independent cursor using the ordinary value-copy rules.

impl<K: Hash + Eq, V: Clone> HashMap<K, V>

pub fn get_or_insert_with(var self, consume key: K, factory: fn() -> V) -> V

Return an independent value, computing and inserting it only when absent. A factory failure occurs before the map is changed.

pub fn update(var self, consume key: K, transform: fn(V) -> V) -> Option<V>

Replace an existing value using an independent copy, returning the new value. An absent key skips the callback. Callback failure preserves the old entry.

impl timestamp

fn now() -> timestamp

Read the host wall clock as normalized Unix seconds and nanoseconds.

impl timestamp

fn from_unix_parts(seconds: i64, nanos: u32) -> timestamp fails TimestampError

Construct normalized Unix seconds and a nanosecond fraction.

fn unix_secs_floor(self) -> i64

Whole Unix seconds rounded toward negative infinity.

fn unix_millis_floor(self) -> i64 fails TimestampError

Whole Unix milliseconds rounded toward negative infinity.

fn unix_micros_floor(self) -> i64 fails TimestampError

Whole Unix microseconds rounded toward negative infinity.

fn unix_nanos(self) -> i64 fails TimestampError

Exact Unix nanoseconds, failing when the i64 result cannot hold them.

impl duration

fn millis_ceil(self) -> i64

Whole milliseconds rounded upward, preserving positive sub-millisecond waits.