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.

Vyi
import { String, Vec, HashMap, Entry } from "@core"
import { formatInt, formatUint, formatFloat } from "@core"
import { cPtrOf } from "@core"

Exports

NameKindImportSummary
Optional(T)enumnonea value or nothing; ?T is Optional(T)
Result(E, T)enumnonea value or an error; E!T is Result(E, T)
Rangestructnonethe value of a..b and a...b
Array(T, N)typenonea type that carries a length N and holds no elements
Stringstruct@coreUTF-8 text in allocator memory, counted in code points
Vec(T)struct@corea growable list in allocator memory
HashMap(K, V)struct@corea hash map in allocator memory
Entry(K, V)struct@coreone key and value of a HashMap
formatInt, formatUint, formatFloatfunctions@corea number rendered as a String
cPtrOffunction@corea 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)

TypeVariantsSugar
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.

Vyi
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

FieldTypeMeaning
startpub start: i32the first value
endpub end: i32the end, as written
inclusivepub inclusive: bool = falsetrue 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 (.len on an array pointer, length() on a type with @slice). A range with an open end anywhere else, such as con r = 2.., does not compile.
  • for loops over range syntax written in its header, for i in a..b. A Range value is not iterable: for i in r does not compile. Loop over r.start..r.end instead (r.start...r.end when r.inclusive).
Vyi
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

FunctionSignatureResultCost
String.newfn (String) new(alloc: Allocator) Stringan empty stringO(1)
String.fromUtf8fn (String) fromUtf8(alloc: Allocator, src: [*con]u8) Stringa copy of src in memory from allocO(n)
String.fromOwnedUtf8fn (String) fromOwnedUtf8(alloc: Allocator, bytes: [*con]u8) Stringa String over bytes themselves, not a copy; bytes must outlive it, as bytes from Buffer.takeBytes() doO(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

FormMethodResultCost
s[i]fn (s: String) @index(i: i32) charthe code point at position iO(i): decodes from the start
s[lo..hi], s[lo...hi]fn (s: String) @slice(r: Range) Stringthe code points from lo to hi, sharing s's bytes and allocatorO(hi)
s == tfn (s: String) @eq(other: String) booltrue when the bytes are equal; no Unicode normalizationO(n)
s + t, s += tfn (s: String) @add(other: String) Stringa new string from s.alloc holding bothO(n)
for c in sfn (s: String) @iter() StringItereach code point as a char, decoded onceO(n) for the loop
(a HashMap key)fn (s: String) @hash() u32FNV-1a over the bytesO(n)

Positions count from 0; the last code point is s[s.length() - 1]. The iterator type StringIter is not exported.

PanicWhen
string: codepoint index out of boundss[i] with i outside 0 <= i < s.length()
string: slice start out of boundsa slice with lo < 0
string: slice end below starta slice with hi < lo
string: slice end past lengtha slice with hi > s.length()
out of memorybuilding 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

MethodSignatureResult
lengthfn (s: String) length() i32the number of code points. O(1)
byteLenfn (s: String) byteLen() i32the number of bytes. O(1)
byteAtfn (s: String) byteAt(i: i32) u8the byte at byte offset i; panics with array index out of bounds outside 0 <= i < s.byteLen()
asBytesfn (s: String) asBytes() [*con]u8the bytes, not copied
isEmptyfn (s: String) isEmpty() booltrue when there are no bytes
startsWithfn (s: String) startsWith(prefix: String) booltrue when s begins with prefix's bytes; an empty prefix always matches
endsWithfn (s: String) endsWith(suffix: String) booltrue when s ends with suffix's bytes; an empty suffix always matches
indexOfBytefn (s: String) indexOfByte(b: u8) i32the byte offset of the first b, or -1
repeatfn (s: String) repeat(n: i32) Stringa 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).

Vyi
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.

FormSignatureResultCost
Vec(T).newfn (Vec(T)) new(alloc: Allocator, initialCap: i32 = 16) Vec(T)an empty Vec with room for initialCap elementsone allocation
pushfn (v: *mut Vec(T)) push(val: T)adds val after the last elementO(1) amortized
lengthfn (v: Vec(T)) length() i32the number of elementsO(1)
v[i]fn (v: Vec(T)) @index(i: i32) Tthe element at position iO(1)
v[i] = xfn (v: Vec(T)) @setIndex(i: i32, val: T)replaces the element at position iO(1)
v[lo..hi], v[lo...hi]fn (v: Vec(T)) @slice(r: Range) [*mut]Ta view of elements lo to hi, not a copyO(1)
for x in v@index and lengtheach element in orderO(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.

PanicWhen
vec index out of boundsv[i] or v[i] = x with i outside 0 <= i < v.length(); cap does not count
vec slice start out of boundsa slice with lo < 0
vec slice end below starta slice with hi < lo
vec slice end past in-use lengtha slice with hi > v.length()
out of memorynew or a growing push when the allocator fails
Vyi
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.

FormSignatureResultCost
HashMap(K, V).newfn (HashMap(K, V)) new(alloc: Allocator, initialCap: i32 = 16) HashMap(K, V)an empty map with at least initialCap slotsthree allocations
putfn (m: *mut HashMap(K, V)) put(key: K, val: V)adds the entry, or replaces the value of an existing keyO(1) average; a growing put is O(n)
getfn (m: HashMap(K, V)) get(key: K) ?VSome(value), or None when key is absentO(1) average
containsfn (m: HashMap(K, V)) contains(key: K) booltrue when key has an entryO(1) average
removefn (m: *mut HashMap(K, V)) remove(key: K) boolremoves the entry; true when there was oneO(1) average
lengthfn (m: HashMap(K, V)) length() i32the number of entriesO(1)
keysfn (m: HashMap(K, V)) keys() Vec(K)a new Vec of the keysO(cap)
valuesfn (m: HashMap(K, V)) values() Vec(V)a new Vec of the valuesO(cap)
entriesfn (m: HashMap(K, V)) entries() Vec(Entry(K, V))a new Vec of the entriesO(cap)
for e in mfn (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. initialCap is rounded up to the next one, so new(alloc, 5) gives 8 slots and new(alloc, 20) gives 32.
  • Order is not specified. for, keys, values, and entries visit the slots in table order, which changes when the map grows.
  • keys, values, and entries copy. The Vec comes from the map's allocator and does not change when the map does.
  • A loop sees the map as it was. for e in m walks the slots m had when the loop began; a put that grows m inside the loop is not seen.
  • put and new panic with out of memory when 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.

Vyi
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@corebuilt in
String@core, over the bytes@eq, over the bytes
your own typeyou write fn (k: T) @hash() u32you 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`).

Vyi
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

FunctionSignatureResult
formatIntfn formatInt(alloc: Allocator, n: i64) Stringn in base 10, with a - when negative
formatUintfn formatUint(alloc: Allocator, n: u64) Stringn in base 10
formatFloatfn formatFloat(alloc: Allocator, x: f64, decimals: i32) Stringx 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:

Vyi
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).

Vyi
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.