Docs · Standard library
@core
@core holds the types the language's sugar stands for (Optional, Result,
Range, Array), the allocator-backed containers (String, Vec,
HashMap), number formatting, and cPtrOf. Guide
07, Optionals and errors and guide
10, Collections and strings
teach them.
import { String, Vec, HashMap, Entry } from "@core"
import { formatInt, formatUint, formatFloat } from "@core"
import { cPtrOf } from "@core"Exports
| Name | Kind | Import | Summary |
|---|---|---|---|
Optional(T) | enum | none | a value or nothing; ?T is Optional(T) |
Result(E, T) | enum | none | a value or an error; E!T is Result(E, T) |
Range | struct | none | the value of a..b and a...b |
Array(T, N) | type | none | a type that carries a length N and holds no elements |
String | struct | @core | UTF-8 text in allocator memory, counted in code points |
Vec(T) | struct | @core | a growable list in allocator memory |
HashMap(K, V) | struct | @core | a hash map in allocator memory |
Entry(K, V) | struct | @core | one key and value of a HashMap |
formatInt, formatUint, formatFloat | functions | @core | a number rendered as a String |
cPtrOf | function | @core | a C pointer to a Vyi pointer's target |
The first four are in scope in every file without an import, so the sugar that
stands for them (?T, !T, a..b) works everywhere. Every other name is
imported from @core by name.
The containers and the formatting functions take an Allocator from
@mem and get all their memory from it. None of their methods
returns an error: when the allocator fails, they panic with out of memory.
Neither do they free memory: growing abandons the old block to the allocator,
and no method gives a container's memory back. Use them with an arena or a
fixed buffer, whose memory is reclaimed all at once.
Optional(T) and Result(E, T)
| Type | Variants | Sugar |
|---|---|---|
Optional(T) | None, Some(T) | ?T |
Result(E, T) | Ok(T), Err(E) | E!T; !T is Result(_, T) with the error type inferred |
Both are ordinary enums. ?i32 and Optional(i32) are the same type, as are
bool!i32 and Result(bool, i32). The variants are written bare where the
expected type is known, and a value never becomes Some or Ok without one
being written. try, catch, match, and if bindings consume them; the
error model states the rules.
import { println } from "@fmt"
fn half(n: i32) ?i32 {
if n % 2 != 0 { return None }
return Some(n / 2)
}
fn main() !u8 {
con even: Optional(i32) = half(10)
println(even catch 0) // prints 5
println(half(7) catch 0) // prints 0
con parsed: Result(bool, i32) = Ok(42)
if Ok(n) = parsed {
println(n) // prints 42
}
return Ok(0)
}Range
| Field | Type | Meaning |
|---|---|---|
start | pub start: i32 | the first value |
end | pub end: i32 | the end, as written |
inclusive | pub inclusive: bool = false | true when end is part of the range |
a..b is Range{ start: a, end: b } and a...b is the same with
inclusive: true. A Range value can be stored, passed, and used to index or
slice: word[r] slices word by r.
- An open end (
..b,a..,..) is filled in only where the range indexes something: the start becomes 0, the end becomes the subject's length (.lenon an array pointer,length()on a type with@slice). A range with an open end anywhere else, such ascon r = 2.., does not compile. forloops over range syntax written in its header,for i in a..b. ARangevalue is not iterable:for i in rdoes not compile. Loop overr.start..r.endinstead (r.start...r.endwhenr.inclusive).
import { println } from "@fmt"
fn main() !u8 {
con word = "abcdef"
con middle = 2...4
println(middle.inclusive) // prints true
println(word[middle]) // prints cde
mut total = 0
for i in middle.start...middle.end {
total += i
}
println(total) // prints 9
return Ok(0)
}Array(T, N)
Array(T, N) is a type that carries an element type and a length and holds no
elements. Its one method, fn (arr: Array(T, N)) len() i32, returns N. It is
a different type from the fixed array [N]T: a [3]i32 does not convert to
Array(i32, 3), and [N]T has no len() method (its length is the field
.len). For a fixed-size array of values, use [N]T
(memory model, fixed arrays).
Array pointers
[*con]T and [*mut]T are part of the language, not of @core. They have
the field .len (an i32) and the field .ptr, and no len() method.
Indexing and slicing are bounds-checked. == compares content only between
byte views ([*con]u8 or [*mut]u8); on other element types it does not
compile. The memory model
states every rule.
String
A String is UTF-8 bytes in allocator memory, together with the allocator they
came from. It never changes after it is built: every operation that makes text
makes a new String. It counts and indexes in code points; byteLen,
byteAt, and asBytes work in bytes. A string literal is a [*con]u8, not a
String.
println from @fmt prints a String once String.intoString is imported
from @fmt (@fmt). Without that import, print
s.asBytes(); passing the String itself is reported as
`type String has no method "intoString"`.
Building a String
| Function | Signature | Result | Cost |
|---|---|---|---|
String.new | fn (String) new(alloc: Allocator) String | an empty string | O(1) |
String.fromUtf8 | fn (String) fromUtf8(alloc: Allocator, src: [*con]u8) String | a copy of src in memory from alloc | O(n) |
String.fromOwnedUtf8 | fn (String) fromOwnedUtf8(alloc: Allocator, bytes: [*con]u8) String | a String over bytes themselves, not a copy; bytes must outlive it, as bytes from Buffer.takeBytes() do | O(n), to count code points |
fromUtf8 and fromOwnedUtf8 do not check that the bytes are valid UTF-8.
Decoding bytes that are not (in s[i], a slice, or a loop) panics with
utf8: unexpected continuation byte or utf8: invalid lead byte.
Operators
| Form | Method | Result | Cost |
|---|---|---|---|
s[i] | fn (s: String) @index(i: i32) char | the code point at position i | O(i): decodes from the start |
s[lo..hi], s[lo...hi] | fn (s: String) @slice(r: Range) String | the code points from lo to hi, sharing s's bytes and allocator | O(hi) |
s == t | fn (s: String) @eq(other: String) bool | true when the bytes are equal; no Unicode normalization | O(n) |
s + t, s += t | fn (s: String) @add(other: String) String | a new string from s.alloc holding both | O(n) |
for c in s | fn (s: String) @iter() StringIter | each code point as a char, decoded once | O(n) for the loop |
(a HashMap key) | fn (s: String) @hash() u32 | FNV-1a over the bytes | O(n) |
Positions count from 0; the last code point is s[s.length() - 1]. The
iterator type StringIter is not exported.
| Panic | When |
|---|---|
string: codepoint index out of bounds | s[i] with i outside 0 <= i < s.length() |
string: slice start out of bounds | a slice with lo < 0 |
string: slice end below start | a slice with hi < lo |
string: slice end past length | a slice with hi > s.length() |
out of memory | building a string (new, fromUtf8, +, repeat) when the allocator fails |
A loop over positions that indexes s[i] takes time proportional to the
square of the length; for c in s takes linear time.
for b in s.asBytes() loops over the bytes.
Methods
| Method | Signature | Result |
|---|---|---|
length | fn (s: String) length() i32 | the number of code points. O(1) |
byteLen | fn (s: String) byteLen() i32 | the number of bytes. O(1) |
byteAt | fn (s: String) byteAt(i: i32) u8 | the byte at byte offset i; panics with array index out of bounds outside 0 <= i < s.byteLen() |
asBytes | fn (s: String) asBytes() [*con]u8 | the bytes, not copied |
isEmpty | fn (s: String) isEmpty() bool | true when there are no bytes |
startsWith | fn (s: String) startsWith(prefix: String) bool | true when s begins with prefix's bytes; an empty prefix always matches |
endsWith | fn (s: String) endsWith(suffix: String) bool | true when s ends with suffix's bytes; an empty suffix always matches |
indexOfByte | fn (s: String) indexOfByte(b: u8) i32 | the byte offset of the first b, or -1 |
repeat | fn (s: String) repeat(n: i32) String | a new string from s.alloc holding s n times; repeat(0) is empty, and a negative n panics |
The public fields are bytes: [*con]u8 (the same view as asBytes()) and
alloc: Allocator (the allocator that + and repeat use).
import { String } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con drink = String.fromUtf8(&arena, "café")
println(drink.length()) // prints 4
println(drink.byteLen()) // prints 5
println(drink[3]) // prints é
println(drink[0..3].asBytes()) // prints caf
con order = drink + String.fromUtf8(&arena, " au lait")
println(order.asBytes()) // prints café au lait
println(order.startsWith(drink)) // prints true
println(order.indexOfByte(u8(' '))) // prints 5
return Ok(0)
}Vec(T)
A Vec(T) holds its elements side by side in one block of allocator memory.
Its public fields are items: [*mut]T (the whole block), cap: i32 (the
number of elements the block has room for), and alloc: Allocator;
length() is the number of elements in use. Elements are stored directly, so
a Vec(Point) holds Point values, not pointers.
| Form | Signature | Result | Cost |
|---|---|---|---|
Vec(T).new | fn (Vec(T)) new(alloc: Allocator, initialCap: i32 = 16) Vec(T) | an empty Vec with room for initialCap elements | one allocation |
push | fn (v: *mut Vec(T)) push(val: T) | adds val after the last element | O(1) amortized |
length | fn (v: Vec(T)) length() i32 | the number of elements | O(1) |
v[i] | fn (v: Vec(T)) @index(i: i32) T | the element at position i | O(1) |
v[i] = x | fn (v: Vec(T)) @setIndex(i: i32, val: T) | replaces the element at position i | O(1) |
v[lo..hi], v[lo...hi] | fn (v: Vec(T)) @slice(r: Range) [*mut]T | a view of elements lo to hi, not a copy | O(1) |
for x in v | @index and length | each element in order | O(n) |
When push finds the block full, it allocates a block of twice the capacity
(8 if the capacity is below 8), copies the elements, and leaves the old block
to the allocator.
A slice goes stale when the Vec grows. v[lo..hi] points into the
current block. After a push that grows the Vec, the slice still points at
the old block: it reads the old values, and writes through it do not reach the
Vec. Nothing reports this. Take slices after the last push.
| Panic | When |
|---|---|
vec index out of bounds | v[i] or v[i] = x with i outside 0 <= i < v.length(); cap does not count |
vec slice start out of bounds | a slice with lo < 0 |
vec slice end below start | a slice with hi < lo |
vec slice end past in-use length | a slice with hi > v.length() |
out of memory | new or a growing push when the allocator fails |
import { Vec } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut scores = Vec(i32).new(&arena, 2)
scores.push(80)
scores.push(95)
con firstTwo = scores[0..2]
scores.push(70) // full: moves to a new block
scores[0] = 85
println(scores[0]) // prints 85
println(firstTwo[0]) // prints 80
println(scores.length()) // prints 3
println(scores.cap) // prints 8
return Ok(0)
}HashMap(K, V)
A HashMap(K, V) keeps its keys and values in allocator memory, in cap
slots. Its public fields are cap: i32, alloc: Allocator, and the slot
arrays ctrl: [*mut]u8, keys: [*mut]K, and vals: [*mut]V (the field
m.keys is the slot array; the method m.keys() collects the keys). It grows
to twice the slots when an insert would fill more than seven-eighths of them,
and rehashes every entry.
| Form | Signature | Result | Cost |
|---|---|---|---|
HashMap(K, V).new | fn (HashMap(K, V)) new(alloc: Allocator, initialCap: i32 = 16) HashMap(K, V) | an empty map with at least initialCap slots | three allocations |
put | fn (m: *mut HashMap(K, V)) put(key: K, val: V) | adds the entry, or replaces the value of an existing key | O(1) average; a growing put is O(n) |
get | fn (m: HashMap(K, V)) get(key: K) ?V | Some(value), or None when key is absent | O(1) average |
contains | fn (m: HashMap(K, V)) contains(key: K) bool | true when key has an entry | O(1) average |
remove | fn (m: *mut HashMap(K, V)) remove(key: K) bool | removes the entry; true when there was one | O(1) average |
length | fn (m: HashMap(K, V)) length() i32 | the number of entries | O(1) |
keys | fn (m: HashMap(K, V)) keys() Vec(K) | a new Vec of the keys | O(cap) |
values | fn (m: HashMap(K, V)) values() Vec(V) | a new Vec of the values | O(cap) |
entries | fn (m: HashMap(K, V)) entries() Vec(Entry(K, V)) | a new Vec of the entries | O(cap) |
for e in m | fn (m: HashMap(K, V)) @iter() HashMapIter(K, V) | each entry as an Entry(K, V) | O(cap) for the loop |
- The slot count is a power of two, and at least 8.
initialCapis rounded up to the next one, sonew(alloc, 5)gives 8 slots andnew(alloc, 20)gives 32. - Order is not specified.
for,keys,values, andentriesvisit the slots in table order, which changes when the map grows. keys,values, andentriescopy. TheVeccomes from the map's allocator and does not change when the map does.- A loop sees the map as it was.
for e in mwalks the slotsmhad when the loop began; aputthat growsminside the loop is not seen. putandnewpanic without of memorywhen the allocator fails.
Entry(K, V) is struct { pub key: K, pub value: V }. Import it to name the
type in a signature. The iterator type HashMapIter(K, V) is not exported.
import { HashMap } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut stock = HashMap(i32, i32).new(&arena)
stock.put(101, 5)
stock.put(102, 3)
stock.put(101, 4) // replaces 5
println(stock.get(101) catch 0) // prints 4
println(stock.get(999) catch 0) // prints 0
println(stock.remove(102)) // prints true
println(stock.length()) // prints 1
mut total = 0
for entry in stock {
total += entry.value
}
println(total) // prints 4
return Ok(0)
}Key types
A key is hashed with its type's @hash() u32 method and compared with ==.
| Key type | @hash | == |
|---|---|---|
i8, i16, i32, i64, u8, u16, u32, u64, char | @core | built in |
String | @core, over the bytes | @eq, over the bytes |
| your own type | you write fn (k: T) @hash() u32 | you write fn (k: T) @eq(other: T) bool |
Keys that compare equal must hash equal. bool, f32, f64, and array
pointers have no @hash. A key type without @hash or == is rejected when
the map's methods are compiled for it, and the error is reported inside
@core (for a struct without @eq:
`operator == is not implemented for type Point`).
import { HashMap } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
struct Cell { row: i32, col: i32 }
fn (c: Cell) @hash() u32 {
return u32(c.row) * 31 + u32(c.col)
}
fn (c: Cell) @eq(other: Cell) bool {
return c.row == other.row && c.col == other.col
}
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
mut sheet = HashMap(Cell, i32).new(&arena)
sheet.put(Cell{ row: 1, col: 2 }, 12)
con value = sheet.get(Cell{ row: 1, col: 2 }) catch 0
println(value) // prints 12
return Ok(0)
}Formatting numbers
| Function | Signature | Result |
|---|---|---|
formatInt | fn formatInt(alloc: Allocator, n: i64) String | n in base 10, with a - when negative |
formatUint | fn formatUint(alloc: Allocator, n: u64) String | n in base 10 |
formatFloat | fn formatFloat(alloc: Allocator, x: f64, decimals: i32) String | x with exactly decimals digits after the point, rounded half away from zero; decimals of 0 gives the whole part with no point |
Each returns a new String from alloc and panics with out of memory when
the allocator fails. A narrower integer converts first:
formatInt(alloc, i64(n)). formatFloat rounds the binary value, so 1.005 with 2 decimals
gives 1.00.
println prints a float with the shortest digits that read back as the same
value (4.5). formatFloat is for a fixed number of decimals:
import { formatFloat, formatInt } from "@core"
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
mut arena = ArenaAllocator.new(systemAllocator)
defer arena.deinit()
con price: f64 = 4.5
con shown = formatFloat(&arena, price, 2)
println(shown.asBytes()) // prints 4.50
con change = formatInt(&arena, -12)
println(change.asBytes()) // prints -12
return Ok(0)
}cPtrOf
fn cPtrOf(known T: type, p: *mut T | [*mut]T) *c_ptr T gives a C pointer to
what p points at: the pointer itself for a *mut T, the first element for a
[*mut]T. It takes writable pointers only; for a [*con]T, use its .ptr.
A C pointer has no bounds checks
(guide 15, C pointers).
import { cPtrOf } from "@core"
import { println } from "@fmt"
fn main() !u8 {
mut prices = [3]i32[10, 20, 30]
con raw = cPtrOf(i32, &prices[0])
println(raw[2]) // prints 30
return Ok(0)
}See also: guide 10, Collections and strings,
the error model, the
memory model, and @mem.