This page is the reference for the built-in std module and its namespaces.
For the language rules around imports, values, and types, see language.md.
std := import("std")
std is always available via import("std") and is exposed as a struct-backed namespace object. Relative source imports use the same namespace model.
The entries below describe the public library surface. This page is intentionally reference-shaped: look up a function here once you already know which part of std you need.
Where a function is naturally generic, this page uses informal generic-style
signatures like [T] or [K, V] to show the type relationship between
arguments and results. These are documentation signatures, not callable
syntax on std itself.
| Namespace | Purpose |
|---|---|
std.io, std.fmt |
Script output/input and formatted text. |
std.core |
Collections, type predicates, errors, cloning, and GC inspection. |
std.Arg |
Variant used for heterogeneous scalar arguments. |
std.conv |
Explicit value conversions. |
std.string, std.bytes |
UTF-8 string operations and byte-oriented binary operations. |
std.array, std.sort |
Array construction and sorting. |
std.math, std.rand |
Numeric operations and non-cryptographic pseudorandom values. |
std.json, std.hex, std.base64 |
Data interchange and text encodings. |
std.crypto |
Hashing, HMAC, AEAD encryption, key derivation, and asymmetric cryptography. |
std.regexp, std.template |
Pattern matching and template rendering. |
std.Time, std.time |
Time values and time-related helpers. |
Capability modules such as cap:env and cap:fs are deliberately not part
of std; their authority and availability are documented in capabilities.md.
Unless an entry says otherwise, values returned by std are owned by the
script runtime. A returned array or map is a normal mutable Gengoscript value;
assigning it aliases that collection under the language rules in language.md.
An entry that says “Errors” names a runtime panic, not an ordinary returned
error value. Check each signature: capability-style (value, error) results
are not the general std convention. Complexity is omitted where no stable
implementation-independent bound is currently guaranteed.
- Prints arguments followed by a newline.
- Returns
null.
- Prints arguments without a trailing newline.
- Returns
null.
fmtis a string with Go-style format verbs.- Errors:
ArityMismatchwhen placeholder count and args differ;TypeErrorwhen arg type does not match verb;RangeErrorwhen formatted output exceeds 64 MB. - To get the formatted string instead of printing it, use
std.fmt.format.
- Like
std.io.printbut writes to stderr. - Returns
null.
- Like
std.io.printfbut writes to stderr. The same 64 MB output cap applies. - Returns
null.
- Like
std.io.printlnbut writes to stderr. - Returns
null.
- Reads up to
max_bytesbytes from stdin in a single call (capped at the runtimemax_input_byteslimit). - Returns the bytes as a string, or
nullon EOF.
- Reads all of stdin until EOF (capped at the runtime
max_input_byteslimit). - Returns the full content as a string, or
nullif nothing was read.
- Reads one line from stdin (capped at the runtime
max_input_byteslimit), stripping the trailing\n/\r\n. - Returns the line as a string, or
nullon EOF.
| Verb | Meaning |
|---|---|
%v |
Default format (same as the print family) |
%s |
String; precision trims to N runes (%.3s) |
%q |
Quoted string with Go-style escape sequences |
%d |
Decimal integer |
%b |
Binary integer |
%o |
Octal integer |
%x |
Hexadecimal (lowercase) |
%X |
Hexadecimal (uppercase) |
%f |
Floating-point, decimal notation (default precision 6) |
%e |
Scientific notation, lowercase exponent |
%E |
Scientific notation, uppercase exponent |
%g |
%e for large exponents, %f otherwise |
%G |
Like %g with uppercase exponent |
%t |
Boolean (true / false) |
%c |
Integer as Unicode code point |
%% |
Literal % |
Flags (between % and the verb):
| Flag | Meaning |
|---|---|
- |
Left-align within field width |
0 |
Zero-pad numeric fields |
+ |
Always print sign for numeric values |
|
Space before positive numbers |
# |
Alternate form: 0x / 0X / 0 / 0b prefix for %x/%X/%o/%b |
Width and precision: %8d (minimum width 8), %.2f (2 decimal places), %8.3f (both).
- Returns the formatted string.
fmtuses the same Go-style verbs asstd.io.printf. - Errors:
ArityMismatchwhen placeholder count and args differ;TypeErrorwhen arg type does not match verb;RangeErrorwhen formatted output exceeds 64 MB.
- Returns
vrendered as a string, exactly asstd.io.printlnwould display it. - Works for any value: scalars, arrays, maps, structs, variants, named types.
- Returns
""for anullargument. - Errors:
RangeErrorwhen the rendered string exceeds 64 MB.
- String: rune count (Unicode code points)
- Array/map/struct instance: element/field count
- Tuple: element count
- Errors:
TypeErroron unsupported input
- String: UTF-8 byte count
- Errors:
TypeErroron unsupported input
- Returns new array with appended items
- Errors:
TypeErrorif first arg is not array
- Creates first-class error value
msgmust be string
- Returns
trueiffvis an error value
- Called inside a
deferfunction during a panic unwind - Returns the original panic payload and marks the panic as recovered; the
payload may be an
erroror another non-null value fromtrap - Returns
nullif not unwinding or if already recovered
- Returns a stable type name
- Plain scalars report names like
int,float,decimal,bigint,bool,string,rune,error,null - A statically known named scalar expression returns its declared name, even though its runtime value is the base scalar
- Dynamically typed named scalars report their base runtime type; named runtime values and struct instances report their declared type name
- Anonymous typed arrays and maps report
arrayandmap
truefor integral numbers and named integer values
truefor non-integral numbers and named float values
truefor strings and named string values
truefor arrays and named array values
truefor maps and named map values
truefor struct instances
trueonly fornull
- Structural equality for arrays, maps, struct instances, named values, variants, strings, and scalars
- Map comparison is by key/value content, not insertion order
- Deep clone for arrays, maps, struct instances, named values, variants, and strings
- Immutable scalar values are returned unchanged
- Triggers GC
- Returns
null
- Returns current live object count (number)
- Returns map with keys:
heap_used_bytesheap_size_byteslive_objects
- Returns extended GC stats with keys:
heap_used_bytes,heap_size_bytes,live_objects,gc_runs,gc_time_ns,alloc_object_calls,alloc_managed_slice_calls,alloc_managed_bytes_calls
- Returns array of all keys in a map
- Errors:
TypeErroron non-map
- Returns array of all values in a map
- Errors:
TypeErroron non-map
- Returns
trueiffkeyexists inmap - Errors:
TypeErroron non-map
- Removes
keyfrommap; returns the removed value ornull - Errors:
TypeErroron non-map
- Returns
trueiffarrcontainsneedle(usesdeep_equal) - Errors:
TypeErroron non-array
- Returns a new array with the element at
indexremoved - Errors:
TypeErroron non-array,IndexOutOfBounds
std.Arg is a built-in variant that covers all primitive scalar types. It
exists so library authors can write heterogeneous variadic functions without
exposing the unsafe any type to callers.
| Arm | Payload type |
|---|---|
std.Arg.Int(n) |
int |
std.Arg.Float(f) |
float |
std.Arg.Decimal(d) |
decimal (any scale) |
std.Arg.Rune(r) |
rune |
std.Arg.Bool(b) |
bool |
std.Arg.Str(s) |
string |
std.Arg.Err(e) |
error |
Declare a variadic parameter typed std.Arg and switch over the arm to
dispatch on the actual scalar type:
func log_args(prefix string, ...args std.Arg) string {
out := prefix + ":"
for a in args {
switch a {
case .Int as n { out = out + " int:" + std.conv.to_string(n) }
case .Str as s { out = out + " str:" + s }
case .Bool as b { out = out + " bool:" + std.conv.to_string(b) }
case .Float as f { out = out + " float:" + std.conv.to_string(f) }
case .Rune as r { out = out + " rune:" + std.conv.to_string(r) }
case .Err as e { out = out + " err:" + string(e) }
case .Decimal as d { out = out + " dec:" + std.conv.to_string(d) }
}
}
return out
}
log_args("x", std.Arg.Int(42), std.Arg.Bool(true), std.Arg.Str("hi"))
- Converts number/rune/boolean/string to integer-number (truncate)
- Errors:
TypeErroron invalid conversion
- Converts number/rune/boolean/string to float-number
- Errors:
TypeErroron invalid conversion
- Explicit conversion to boolean:
false,null,0, and""convert tofalse; everything else converts totrue - Named values convert through their underlying value
- This is the only truthiness in the language —
if/not/and/orand template{{if}}require an actualbool
- Converts number/rune/boolean/null/string/error to string
- Errors:
TypeErroron unsupported input
- Splits
sbysep - Empty
sepsplits into UTF-8 runes
- Joins array of strings with separator
sep
- Trims leading and trailing ASCII whitespace
- Uppercases ASCII letters
- Lowercases ASCII letters
- Returns
trueiffsbegins withprefix
- Returns
trueiffsends withsuffix
- Returns rune index of first occurrence, or
-1
- Returns rune index of last occurrence, or
-1
- Replaces all non-overlapping occurrences of
oldwithnew - Empty
oldreturnssunchanged
- Returns
srepeatedntimes - Errors:
RangeErrorifn < 0or if the result would exceed 64 MB
- Returns a 2-element array
[head, tail]split on the first occurrence ofsep - Returns
[null, null]ifsepis not present
- Returns
trueifsubappears anywhere ins, elsefalse - Empty
subalways returnstrue
- Creates mutable string builder with
.write,.str, and.reset
- Counts non-overlapping occurrences of
subins
- Splits
sby ASCII whitespace (spaces, tabs, newlines) into an array
- Pads to a byte width using the bytes in
pad; a multi-bytepadcan be truncated at the final byte boundary. Do not use these functions when the result must preserve UTF-8 rune boundaries.
- Case-insensitive equality for ASCII strings
- Returns
trueif any byte incharsappears ins; it is not a Unicode-rune operation.
- Trims leading or trailing bytes that appear in
chars(single-byte characters only; multi-byte runes incharsare not recognised)
- Removes
prefixorsuffixif present; returnssunchanged otherwise
- Splits
sbysepinto at mostnsubstrings; final element contains the rest - With an empty separator, splits at UTF-8 codepoint boundaries (same behaviour as
std.string.split(s, ""))
- Returns array of elements where
pred(element)istrue
- Returns array of
fn(element)for each element
- Folds
arrleft-to-right:fn(init, arr[0]), thenfn(result, arr[1]), etc.
- Returns sub-array from
start(inclusive) toend(exclusive)
- Returns array of pairs
[a[0], b[0]], [a[1], b[1]], …
- Flattens one level of nesting:
[[1,2],[3]]→[1,2,3]
- Returns first element where
pred(element)istrue, ornull
- Returns index of first element where
pred(element)istrue, or-1
- Returns
trueifpred(element)istruefor every element
- Returns
trueifpred(element)istruefor at least one element
- Splits
arrinto sub-arrays of lengthsize; last chunk may be shorter - Errors:
RangeErrorifsize <= 0
- Returns a new array sorted in ascending order (int, float, or string elements); the original is unchanged
- Returns a new array sorted in descending order; the original is unchanged
- Returns a new array sorted using a comparator called as
cmp(left, right); the original is unchanged cmpmay return a negative / zero / positiveintorfloat, or aboolwheretruemeansleft < right
- Absolute value of
x - Integer inputs stay
int; floating inputs stayfloat
- Square root of
x
- Floor, ceiling, nearest integer (half-away-from-zero)
- Trigonometric functions; argument in radians
- Natural, base-2, and base-10 logarithms
baseraised to the powerexp
- Minimum / maximum of two numbers
- When both inputs are
int, the result staysint
- π ≈ 3.14159265358979… (constant)
- Euler's number ≈ 2.71828182845904… (constant)
- Golden ratio ≈ 1.618033988749895… (constant)
- Positive infinity (constant)
- Returns NaN
- Returns
trueifxis NaN
- Returns
trueifxis infinite;sign=0matches any sign,sign>0matches positive,sign<0matches negative
- Returns the sign of
x:-1,0, or1; preserves int type for integer inputs
- Clamps
vto the[min, max]range
- Truncates toward zero
e^x; errors:RangeErrorif result is not finite
2^x; errors:RangeErrorif result is not finite
- Cube root
- Euclidean distance
sqrt(x^2 + y^2)
- Floating-point modulo (IEEE 754
fmod); errors:DivisionByZeroify == 0 - For integer and named-type modulo, use the
modkeyword operator instead.
- Inverse trigonometric functions; errors:
RangeErroron domain error
- Hyperbolic trigonometric functions; errors:
RangeErrorif result is not finite
- Uniform float in
[0.0, 1.0) - Auto-seeds from OS entropy on first call
- Uniform int in
[0, n) - Errors:
RangeErrorifn ≤ 0
- Uniform int in
[lo, hi]inclusive - Errors:
RangeErroriflo > hi
- Seeds the global PRNG with
n - Useful for reproducible test sequences
- Returns a random element from
arr - Errors:
RangeErroron empty array,TypeErrorif not an array
- Returns a random permutation of
[0, n)(Fisher-Yates shuffle) - Errors:
RangeErrorifn < 0
- Normally-distributed float (Box-Muller transform)
- Parses a JSON string and returns the corresponding gengo value
- JSON null →
null, booleans →bool, strings →string, arrays → array, objects → map - Integer JSON numbers become
int; non-integral JSON numbers becomefloat - A JSON integer outside
int's 64-bit signed range silently becomes afloat(and, forstd.json.stringify, prints with the corresponding loss of precision) — there is no automatic promotion tobigint - Errors:
TypeErroron invalid JSON
- Parses a JSON string and returns a
std.JSONValuevariant value - Use this when the JSON structure is not known ahead of time; the result can be pattern-matched exhaustively with
switch - Integer JSON numbers become
.jint; non-integral JSON numbers become.jfloat - Errors:
TypeErroron invalid JSON
- Serializes a gengo value to a JSON string
- Arrays → JSON arrays, maps → JSON objects (string keys required), scalars → JSON primitives
- Named scalar values serialize as their underlying scalar
- Non-serializable values (struct instances, closures, etc.) emit
null - Returns
string
- Returns
trueifsis valid JSON,falseotherwise
- Parses JSON and re-serialises with the given indentation;
indent_strmust be"\t"or exactly 1, 2, 3, 4, or 8 spaces (the underlying widths Zig's JSON stringifier supports — 5, 6, and 7 spaces are not available) - Errors:
TypeErroron invalid JSON, or on anindent_stroutside the supported set
- The
JSONValuevariant type; both names refer to the same type object - Arms:
| Arm | Payload | JSON source |
|---|---|---|
.jnull |
— | null |
.jbool(b) |
bool |
true / false |
.jint(n) |
int |
integer numbers |
.jfloat(f) |
float |
fractional numbers |
.jstr(s) |
string |
string values |
.jarray(items) |
[]JSONValue |
arrays |
.jobject(m) |
[string]JSONValue |
objects |
doc := std.json.parse_value(src)
switch doc {
case .jobject as m {
switch m["name"] {
case .jstr as s { std.io.println(s) }
}
}
case .jarray as items {
for item in items {
switch item {
case .jint as n { std.io.println(n) }
case .jfloat as f { std.io.println(f) }
}
}
}
case .jnull { std.io.println("null") }
}
- Encodes a string or array of bytes to a lowercase hex string
- Decodes a hex string to a string; errors:
TypeErroron invalid hex
- Encodes a string or array of bytes to base64
- Decodes a base64 string; errors:
TypeErroron invalid base64
- URL-safe base64 variant (uses
-and_instead of+and/)
Cryptographic hashing, authentication, encryption, and key derivation.
All functions that return raw bytes return them as a string (Gengo's byte-string type); use std.hex.encode / std.base64.encode to convert to text.
Hash and HMAC outputs are returned as lowercase hex strings.
- SHA-256 of
data; returns a 64-character lowercase hex string.
- SHA-512 of
data; returns a 128-character lowercase hex string.
- BLAKE3 of
data; returns a 64-character lowercase hex string.
- MD5 of
data; returns a 32-character lowercase hex string. Use only for legacy compatibility — MD5 is cryptographically broken.
- SHA-1 of
data; returns a 40-character lowercase hex string. Use only for legacy compatibility — SHA-1 is cryptographically weak.
- HMAC-SHA256; returns a 64-character lowercase hex string.
- HMAC-SHA512; returns a 128-character lowercase hex string.
All seal functions return ciphertext + authentication tag as a raw byte string.
All open functions return the decrypted plaintext string, or raise CryptoError if the tag is invalid.
- AES-GCM encryption.
keymust be 16 bytes (AES-128) or 32 bytes (AES-256);noncemust be 12 bytes.
- AES-GCM decryption. Errors:
CryptoErroron authentication failure,TypeErroron wrong key/nonce length.
- ChaCha20-Poly1305 encryption.
keymust be 32 bytes;noncemust be 12 bytes.
- ChaCha20-Poly1305 decryption. Errors:
CryptoErroron authentication failure.
- XChaCha20-Poly1305 encryption.
keymust be 32 bytes;noncemust be 24 bytes (vs 12 for ChaCha20-Poly1305). The longer nonce makes it safe to generate randomly.
- XChaCha20-Poly1305 decryption. Errors:
CryptoErroron authentication failure.
- HKDF-SHA256 (RFC 5869) key derivation.
ikmis the input key material;saltandinfoare optional context strings (pass""to omit).lengthis the number of output bytes (integer, max 8160). Returns raw bytes.
- Argon2id password hashing / key derivation.
memory_kb,threads, anditerationsare integers. Returns raw bytes of lengthkey_length. Recommended minimum:memory_kb=65536,threads=4,iterations=3.
- bcrypt password hash.
costis the work factor (integer, 4–31; typical production value: 12). Returns a 60-character bcrypt hash string.
- Verifies
passwordagainst a bcrypthash. Returnstrueorfalse.
- Ed25519 signature.
seedmust be 32 bytes (the private key seed). Returns a 64-byte raw signature string.
- Verifies an Ed25519
signatureovermessagewith the given 32-bytepubkey. Returnstrueorfalse.
- X25519 Diffie-Hellman (RFC 7748).
secretandpubkeymust each be 32 bytes. Returns the 32-byte shared secret as a raw byte string.
- Returns
ncryptographically secure random bytes as a raw byte string.
- Compares two strings in constant time. Returns
trueif they are identical. Use this to compare MACs or other secrets to avoid timing side-channels.
Raw byte string construction, decomposition, integer encoding/decoding, and
byte-indexed search. Unlike std.string, all positions and lengths here are
byte offsets, not rune indices.
Background: Gengo strings are UTF-8. A typed rune declaration followed by
string(r) for a value above 127 produces a multi-byte UTF-8 sequence, not
the raw byte value. std.bytes.u8 is the escape hatch: it takes any integer
0–255 and produces a 1-byte binary string.
- Returns a 1-byte binary string containing raw byte
n & 255 - This is the primitive for building binary data; converting a rune value to
stringis not equivalent (it produces UTF-8 bytes)
- Converts an array of integer byte values (0–255 each) to a binary string
- Each element is truncated to its low 8 bits
- Returns
srepeatedntimes as a single binary string - Errors:
RangeErrorif the result would exceed 64 MB
- Returns an array of integer byte values (0–255) for each byte in
s
- Returns the integer byte value (0–255) at byte offset
i - Errors:
RangeErrorifiis out of bounds
- Returns the byte substring
s[from:to](byte-indexed, not rune-indexed) - Errors:
RangeErrorif indices are out of range
- Returns the number of bytes in
s(same asstd.core.bytelen)
All encoding functions accept any integer and truncate to the appropriate width.
| Function | Width | Byte order |
|---|---|---|
std.bytes.u16be(n) |
2 bytes | big-endian |
std.bytes.u32be(n) |
4 bytes | big-endian |
std.bytes.u64be(n) |
8 bytes | big-endian |
std.bytes.u16le(n) |
2 bytes | little-endian |
std.bytes.u32le(n) |
4 bytes | little-endian |
std.bytes.u64le(n) |
8 bytes | little-endian |
All float encoding functions accept a float or int argument and produce IEEE 754 bytes.
| Function | Width | Byte order |
|---|---|---|
std.bytes.f32be(n) |
4 bytes | big-endian |
std.bytes.f64be(n) |
8 bytes | big-endian |
std.bytes.f32le(n) |
4 bytes | little-endian |
std.bytes.f64le(n) |
8 bytes | little-endian |
All decoding functions take a binary string s and byte offset i.
Errors: RangeError if there are insufficient bytes at i.
| Function | Width | Byte order | Return |
|---|---|---|---|
std.bytes.u16be_at(s, i) |
2 bytes | big-endian | int (0–65535) |
std.bytes.u32be_at(s, i) |
4 bytes | big-endian | int (0–4294967295) |
std.bytes.u64be_at(s, i) |
8 bytes | big-endian | int (i64 bit pattern) |
std.bytes.u16le_at(s, i) |
2 bytes | little-endian | int (0–65535) |
std.bytes.u32le_at(s, i) |
4 bytes | little-endian | int (0–4294967295) |
std.bytes.u64le_at(s, i) |
8 bytes | little-endian | int (i64 bit pattern) |
All float decoding functions take a binary string s and byte offset i.
Errors: RangeError if there are insufficient bytes at i.
| Function | Width | Byte order | Return |
|---|---|---|---|
std.bytes.f32be_at(s, i) |
4 bytes | big-endian | float |
std.bytes.f64be_at(s, i) |
8 bytes | big-endian | float |
std.bytes.f32le_at(s, i) |
4 bytes | little-endian | float |
std.bytes.f64le_at(s, i) |
8 bytes | little-endian | float |
- Returns the byte offset of the first occurrence of
subins, or-1
- Returns
trueifsubappears anywhere ins
- Returns
trueifsbegins withprefix
- Returns
trueifsends withsuffix
- Returns the number of non-overlapping occurrences of
subins
- Returns a copy of
swith every occurrence ofoldreplaced bynew
std := import("std")
b := std.bytes
// Build a 4-byte big-endian frame
frame := b.u16be(0xDEAD) + b.u16be(0xBEEF)
std.io.println(std.hex.encode(frame)) // "deadbeef"
// Read it back
std.io.println(b.u16be_at(frame, 0)) // 57005
std.io.println(b.u16be_at(frame, 2)) // 48879
// Pack/unpack round-trip
raw := b.pack([0x01, 0x80, 0xFF])
parts := b.unpack(raw)
std.io.println(parts[1]) // 128 (not 2 as rune() would give)
Backtracking NFA engine. All functions accept either a pattern string or a compiled regexp object returned by std.regexp.compile.
Supported syntax: . * + ? ^ $ | () [...] [^...] character ranges, \d \D \w \W \s \S shorthands.
Errors: InvalidRegexp on a malformed pattern; RangeError when the input string s exceeds 1 MB.
When a pattern's group alternation nesting exceeds 200 levels, the engine treats the input as not matching rather than erroring.
- Returns
trueifpatternmatches anywhere ins
- Returns the first matching substring, or
nullif not found
- Returns array of all non-overlapping matches
- Replaces every non-overlapping occurrence of
patterninswithrepl; returns new string
- Splits
sat each match ofpattern; returns array of strings
- Compiles
patterninto a reusablestd.Regexpobject std.Regexpis the named type for compiled regular expressions- The object supports method-call syntax:
re.match(s),re.find(s),re.find_all(s),re.replace(s, repl),re.split(s)
Go-style text templates with {{ / }} delimiters.
- Parses and executes
srcagainstdatain one call - Returns the rendered string
- Errors:
InvalidTemplateon malformed template,TypeErroron type mismatch
- Compiles
srcinto a reusableTemplateobject - Errors:
InvalidTemplateon malformed template
- Executes a compiled template object returned by
std.template.parse - Equivalent to
tmpl.execute(data) - Returns the rendered string
- Executes a compiled template against
data - Returns the rendered string
- Returns
trueifsrcis a well-formed template,falseotherwise
- Registers a named function on a compiled template for use in
{{call_fn}}tags - Returns
null
Template.add_func(name, fn) is the equivalent method-call form.
| Tag | Description |
|---|---|
{{.field}} |
Field/key access on current context |
{{.a.b}} |
Chained field access |
{{.}} |
Current context value |
{{if .expr}}…{{end}} |
Conditional block |
{{if .expr}}…{{else}}…{{end}} |
Conditional with else |
{{with .expr}}…{{end}} |
Scoped context block |
{{/* comment */}} |
Comment (emits nothing) |
range iterates over arrays: {{range .items}}…{{end}} binds each element as . in turn. An optional {{else}} block runs when the array is empty.
std.Time is a named type over int. Raw value is milliseconds since Unix epoch, UTC. All arithmetic and comparison operators work through the underlying int.
| Function | Returns | Notes |
|---|---|---|
std.time.now() |
std.Time |
Current wall time |
std.time.from_unix(sec) |
std.Time |
Integer seconds → Time |
std.time.from_unix_ms(ms) |
std.Time |
Integer milliseconds → Time |
std.time.parse(str, fmt) |
std.Time |
Errors: TypeError/RangeError on bad input |
std.time.since(t) |
float |
Milliseconds elapsed since t (now − t); equivalent to t.since() |
std.time.until(t) |
float |
Milliseconds until t (t − now); equivalent to t.until() |
std.time.sleep(ms) |
null |
Suspends execution for an integer number of milliseconds; operation budget is charged one operation per requested nanosecond before suspension. Only supported at top-level execution (the CLI, or an embedding's run/runPath/begin) — calling it from a function invoked via engine_call/Runtime.call fails immediately with SleepNotAllowed rather than suspending. See embedding.md's "std.time.sleep and Suspension" section for how a host resumes a suspended script. |
Duration constants (plain int, milliseconds):
std.time.ms std.time.second std.time.minute std.time.hour std.time.day
| Method | Returns | Notes |
|---|---|---|
.unix() |
int |
Whole seconds since epoch |
.unix_ms() |
float |
Milliseconds since epoch |
.parts() |
map |
Keys: year month day hour min sec ms weekday (0=Sunday) |
.format(fmt) |
string |
Errors: NoSpaceLeft when the expanded format string exceeds 512 bytes |
.add_ms(n) |
std.Time |
|
.add_s(n) |
std.Time |
|
.add_m(n) |
std.Time |
|
.add_h(n) |
std.Time |
|
.sub(t2) |
float |
ms difference self − t2, may be negative |
.before(t2) |
bool |
|
.after(t2) |
bool |
|
.equal(t2) |
bool |
|
.is_zero() |
bool |
|
.since() |
float |
Milliseconds elapsed since this time (now − self) |
.until() |
float |
Milliseconds until this time (self − now) |
.add_date(years, months, days) |
std.Time |
Adds calendar units; errors: RangeError if the delta causes an i32 overflow in any component |
.iso_week() |
map |
Keys: year, week |
- Parses a duration string like
"1h30m","2.5s","100ms","1us", or"1ns"into milliseconds - Supports leading
+/-, compound forms, bare zero, and bothµsandμs - Returns
float
| Verb | Output | Verb | Output |
|---|---|---|---|
%Y |
year (4 digits) | %H |
hour 00–23 |
%m |
month 01–12 |
%M |
minute 00–59 |
%d |
day 01–31 |
%S |
second 00–59 |
%L |
millisecond 000–999 |
%A |
weekday name |
%a |
short weekday | %B |
month name |
%b |
short month | %% |
literal % |
parse accepts: %Y (4-digit year), %y (2-digit year, 2000-based), %m, %d, %H, %M, %S, %L (milliseconds), %B (full month name), %a (weekday name, consumed but not used), %W (week number, consumed but not used). All times are UTC.