Docs · Standard library

@mem

@mem holds the Allocator interface and the allocators that implement it, Buffer for collecting bytes in memory, byte operations, and transmuteTo for reinterpreting a pointer. Guide 09, Pointers and memory teaches allocators, and the memory model states how long their memory lives.

Vyi
import { Allocator, OutOfMemory, systemAllocator } from "@mem"
import { ArenaAllocator, FixedBufferAllocator } from "@mem"
import { PageAllocator, pageAllocator } from "@mem"
import { TestingAllocator } from "@mem"
import { Buffer, copy, equal, compare, fill } from "@mem"
import { transmuteTo, offsetPtr } from "@mem"

Exports

NameKindSummary
Allocatorinterfaceanything that hands out memory: alloc and free
OutOfMemoryerror declarationthe one way an allocation fails
systemAllocatorcon Allocatorthe platform heap
FixedBufferAllocatorstructhands out pieces of a buffer you provide
ArenaAllocatorstructhands out pieces of chunks taken from a parent allocator
PageAllocator, pageAllocatorstruct, con Allocatorwhole pages from the operating system
TestingAllocatorstructcounts the allocations of a parent allocator
Bufferstructbytes collected in allocator memory; a Writer and a Reader
copy, equal, compare, fillfunctionsoperations on byte views
transmuteTofunctionthe same pointer as another pointer type
offsetPtrfunctiona pointer moved by a number of elements (planned)
WasmAllocatorstructthe type behind systemAllocator on WebAssembly
LibcAllocatorstructthe type behind systemAllocator on x86-64-linux and arm64-linux

Allocator

Vyi
import { OutOfMemory } from "@mem"

interface Allocator {
    'mem,
    fn (a: *mut Allocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8 '(a.mem),
    fn (a: *mut Allocator) free(buf: [*mut]u8),
}
MethodSignatureContract
allocfn (a: *mut Allocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8exactly size bytes at an address that is a multiple of align, or Err(OutOfMemory); never null, never an empty view in place of an error
freefn (a: *mut Allocator) free(buf: [*mut]u8)gives back the view alloc returned; may do nothing
newfn (a: Allocator) new(known T: type) OutOfMemory!*mut Tone T: sizeof T bytes at alignof T
newfn (a: Allocator) new(known T: type, count: i32) OutOfMemory![*mut]Tcount elements of T
putfn (a: Allocator) put(v: _) OutOfMemory!_a copy of v in new memory, and a pointer to it; put(*closure) stores a closure's captured values and returns the closure
deletefn (a: Allocator) delete(ptr: *mut _)frees what a single new or put returned; the size comes from the pointer's type
deletefn (a: Allocator) delete(ptr: [*mut]_)frees what new(T, count) returned; the size comes from the view

An allocator implements alloc and free; new, put, and delete are methods on the interface itself, so every allocator has them. A function that allocates takes an Allocator parameter. Pass systemAllocator as it is, and an allocator struct as a pointer, &arena, which converts to Allocator.

Memory from an allocator lives as long as the allocator's mem slot: an arena's own lifetime, or the buffer a fixed-buffer allocator carves. The compiler checks that nothing keeps such memory longer (memory model). It does not track free, delete, or reset: using memory after them compiles and reads whatever is there.

The result of alloc, new, and put is a Result, used through try, catch, or match before the memory is reached. Using it as the memory is reported as this value has type Result(OutOfMemory, [*mut]u8), but the binding is declared [*mut]u8:

Vyi · does not compile
import { systemAllocator } from "@mem"

fn main() !u8 {
    con buf: [*mut]u8 = systemAllocator.alloc(8, 1)   // error: this value has type Result(OutOfMemory, [*mut]u8)
    return Ok(0)
}
Vyi
import { Allocator, OutOfMemory, systemAllocator } from "@mem"
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn origin(alloc: Allocator) OutOfMemory!*mut Point {
    return alloc.put(Point{ x: 0, y: 0 })
}

fn main() !u8 {
    con p = try origin(systemAllocator)
    defer systemAllocator.delete(p)
    p.x = 3
    println(p.x)        // prints 3

    con scores = try systemAllocator.new(i32, 4)
    defer systemAllocator.delete(scores)
    println(scores.len) // prints 4
    return Ok(0)
}

OutOfMemory

error OutOfMemory { OutOfMemory "out of memory" } is the failure of every allocation. Write the member as OutOfMemory.OutOfMemory, or OutOfMemory where the expected type is OutOfMemory, as in return Err(OutOfMemory). It converts to the open error type, so try on an allocation works in any function that returns !T. One that reaches the end of main prints error: out of memory.

Writing an allocator

A type whose methods match alloc and free converts to Allocator. This one refuses every request:

Vyi
import { Allocator, OutOfMemory } from "@mem"
import { println } from "@fmt"

struct Refuse { }

fn (a: *mut Refuse) alloc(size: i32, align: i32) OutOfMemory![*mut]u8 {
    return Err(OutOfMemory)
}

fn (a: *mut Refuse) free(buf: [*mut]u8) { }

fn main() !u8 {
    mut refuse = Refuse{ }
    con alloc: Allocator = &refuse
    con slot = alloc.new(i32) catch {
        println("no memory")   // prints no memory
        return Ok(0)
    }
    return Ok(0)
}

Both methods are required. A type without free does not convert:

Vyi · does not compile
import { Allocator, OutOfMemory } from "@mem"

struct Refuse { }

fn (a: *mut Refuse) alloc(size: i32, align: i32) OutOfMemory![*mut]u8 {
    return Err(OutOfMemory)
}

fn main() !u8 {
    mut refuse = Refuse{ }
    con alloc: Allocator = &refuse   // error: this value has type *mut Refuse, but the binding is declared Allocator
    return Ok(0)
}

An allocator has no resize. To grow a buffer, allocate a larger one, copy, and free the old one, as Buffer does.

systemAllocator

export con systemAllocator: Allocator is the platform heap, ready to pass wherever an Allocator is expected. Its type depends on the target:

WebAssembly (WasmAllocator)x86-64-linux, arm64-linux (LibcAllocator)
alloctakes the next size bytes of linear memory, growing it in 64 KiB pageslibc malloc
freedoes nothing: linear memory only growslibc free; give back only what this allocator returned
failureOutOfMemory when linear memory cannot grownot detected: a failed malloc is not reported (planned)
alignhonoredat most 16 (what malloc gives); larger values are not honored (planned)

Import systemAllocator, not its type. WasmAllocator.new() makes a second allocator over the same memory, which hands out the same addresses as systemAllocator. WasmAllocator exists only on WebAssembly and LibcAllocator only on the Linux targets.

FixedBufferAllocator

MemberSignatureResult
newfn (FixedBufferAllocator) new(buf: [*mut]u8) FixedBufferAllocatoran allocator over buf, with nothing handed out
allocfn (a: *mut FixedBufferAllocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8the next size bytes of buf, or OutOfMemory when they do not fit
freefn (a: *mut FixedBufferAllocator) free(buf: [*mut]u8)does nothing
resetfn (a: *mut FixedBufferAllocator) reset()makes the whole buffer available again
fieldspub buf: [*mut]u8, pub used: i32used is the number of bytes handed out, padding included
  • free does nothing; reset() reclaims. Memory comes back only all at once. Everything handed out before reset() is dead after it.
  • It never allocates and never grows. A full buffer fails with OutOfMemory.
  • align is counted from the start of buf, so a result is aligned only as far as buf itself is.
  • Its memory lives as long as buf, so memory carved from a local array cannot leave that array's function.
Vyi
import { Allocator, FixedBufferAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut space = [16]u8[]
    mut fixed = FixedBufferAllocator.new([*mut]u8(&space))
    con alloc: Allocator = &fixed

    con first = try alloc.alloc(10, 1)
    alloc.free(first)
    println(fixed.used)                 // prints 10
    con full = alloc.alloc(10, 1) catch {
        println("full")                 // prints full
        fixed.reset()
        try alloc.alloc(10, 1)
    }
    println(fixed.used)                 // prints 10
    return Ok(0)
}

ArenaAllocator

MemberSignatureResult
newfn (ArenaAllocator) new(parent: Allocator, chunkBytes: i32 = 4096) ArenaAllocatoran empty arena over parent; takes nothing yet
allocfn (a: *mut ArenaAllocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8the next size bytes of the current chunk, taking a new chunk when they do not fit
freefn (a: *mut ArenaAllocator) free(buf: [*mut]u8)does nothing
resetfn (a: *mut ArenaAllocator) reset()starts again from the first chunk and keeps every chunk
deinitfn (a: *mut ArenaAllocator) deinit()gives every chunk back to parent; the arena can be used again
allocatorfn (a: *mut ArenaAllocator) allocator() Allocatorthe arena as an Allocator, the same value as &arena
  • The first allocation takes a chunk of chunkBytes from parent. When a request does not fit, the arena takes a new chunk at least twice the size of the last one, or the size of the request if that is larger. Earlier chunks stay where they are, so earlier memory stays valid.
  • alloc fails with OutOfMemory only when parent does.
  • Chunks are aligned to 16 bytes, so an align above 16 is not guaranteed.
  • free does nothing. After reset() the arena hands out the same memory again, so everything from before is dead; deinit() also returns the memory to parent. Put defer arena.deinit() after creating an arena.
  • Its memory lives as long as the arena.
Vyi
import { ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut arena = ArenaAllocator.new(systemAllocator)
    defer arena.deinit()

    con first = try arena.new(u8, 32)
    arena.reset()
    con second = try arena.new(u8, 32)
    println(first.ptr == second.ptr)   // prints true
    return Ok(0)
}

PageAllocator

export con pageAllocator: Allocator takes whole pages from the operating system; PageAllocator is its type. It is what other allocators are built on, not one to allocate single values from.

WebAssemblyx86-64-linux, arm64-linux
allocgrows linear memory by enough 64 KiB pages for sizemmap of size bytes, rounded up to pages by the system
freedoes nothingmunmap
failureOutOfMemory when memory cannot growOutOfMemory when mmap fails

The view alloc returns is size bytes long, starting at a page boundary.

TestingAllocator

MemberSignatureResult
newfn (TestingAllocator) new(parent: Allocator) TestingAllocatora counter over parent
alloc, freethe Allocator methodspass the call to parent and count it
liveAllocationsfn (a: TestingAllocator) liveAllocations() i32allocations not yet freed
totalAllocationsfn (a: TestingAllocator) totalAllocations() i32every allocation so far
fieldspub parent: Allocator, pub live: i32, pub total: i32the counts

A test checks that liveAllocations() is 0 at the end. Over an allocator whose free does nothing, freeing still counts.

Vyi
import { Allocator, TestingAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut counted = TestingAllocator.new(systemAllocator)
    con alloc: Allocator = &counted
    con scores = try alloc.new(i32, 4)
    println(counted.liveAllocations())   // prints 1
    alloc.delete(scores)
    println(counted.liveAllocations())   // prints 0
    return Ok(0)
}

Buffer

A Buffer collects bytes in memory from an allocator, or reads from bytes it was given. It satisfies @io's Writer and Reader (@io).

MemberSignatureResult
fromAllocfn (Buffer) fromAlloc(a: Allocator) Bufferan empty buffer that grows through a
fromBytesfn (Buffer) fromBytes(src: [*con]u8) Buffera read-only buffer over src, not a copy
writefn (b: *mut Buffer) write(buf: [*con]u8) error!i32appends buf and returns buf.len; fails with OutOfMemory when growing fails
readfn (b: *mut Buffer) read(buf: [*mut]u8) error!i32copies the next unread bytes into buf and returns how many; Ok(0) when all are read
lengthfn (b: Buffer) length() i32the bytes written, or the length of src
asBytesfn (b: Buffer) asBytes() [*con]u8a view of the bytes, not a copy; valid until the buffer grows or is freed
bytesfn (b: Buffer) bytes(a: Allocator) OutOfMemory![*con]u8a copy in memory from a; the buffer stays usable
takeBytesfn (b: *mut Buffer) takeBytes() [*mut]u8the buffer's own memory, not a copy; the buffer is finished
deinitfn (b: *mut Buffer) deinit()frees the memory; does nothing on a read-only or finished buffer
  • When a write does not fit, the buffer allocates a block of twice the capacity (at least 8 bytes), copies, and frees the old block through its allocator.
  • After takeBytes() the caller owns the bytes and frees them through the buffer's allocator. The buffer is finished: deinit does nothing, and another write or takeBytes panics.
  • write or takeBytes on a buffer from fromBytes panics; read works.
  • println takes a [*con]u8, not a [*mut]u8: bind the result of takeBytes() with a type, con text: [*con]u8 = b.takeBytes(), to print it.
PanicWhen
buffer: write after takeByteswrite on a finished buffer
buffer: takeBytes on a sealed buffera second takeBytes
buffer: write to a read-only sourcewrite on a buffer from fromBytes
buffer: takeBytes on a read-only sourcetakeBytes on a buffer from fromBytes
buffer: initial allocation failedfromAlloc when the allocator fails
Vyi
import { Buffer, ArenaAllocator, systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut arena = ArenaAllocator.new(systemAllocator)
    defer arena.deinit()

    mut log = Buffer.fromAlloc(&arena)
    try log.write("disk ")
    try log.write("full")
    println(log.length())       // prints 9
    println(log.asBytes())      // prints disk full

    con text: [*con]u8 = log.takeBytes()
    println(text)               // prints disk full
    return Ok(0)
}

Byte operations

FunctionSignatureResult
copyfn copy(dst: [*mut]u8, src: [*con]u8)copies src into the start of dst; the two may overlap
equalfn equal(a: [*con]u8, b: [*con]u8) booltrue when the lengths and bytes are equal
comparefn compare(a: [*con]u8, b: [*con]u8) i32negative, 0, or positive as a orders before, equal to, or after b, byte by byte; a prefix orders first
fillfn fill(dst: [*mut]u8, b: u8)sets every byte of dst to b

copy panics with copy: destination too small when dst.len < src.len. Only the sign of compare's result is meaningful. On the Linux targets these call libc's memmove, memcmp, and memset.

Vyi
import { copy, equal, compare, fill } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    mut space = [6]u8[]
    con code = [*mut]u8(&space)
    fill(code, u8('-'))
    copy(code, "ab")
    println(code[..4] == "ab--")     // prints true
    println(equal("tea", "tea"))     // prints true
    println(compare("ab", "abc") < 0) // prints true
    return Ok(0)
}

transmuteTo

FormSignatureResult
one pointerfn transmuteTo(known U: type, src: _) Usrc's address as a U
array pointerfn transmuteTo(known U: type, src: _, count: i32) Uan array pointer U at src's address with count elements

transmuteTo gives the same address as another pointer type. Nothing is checked: not that the memory holds valid U values, and not, in the array form, that count elements fit. Use it only between pointer types; a non-pointer U is not supported. The result lives as long as src. It is how new turns the bytes from alloc into a *mut T, and how C memory becomes an array pointer.

Vyi
import { systemAllocator, transmuteTo } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    con words = try systemAllocator.new(u32, 1)
    words[0] = 258
    con bytes = transmuteTo([*mut]u8, words, 4)
    println(bytes[0])   // prints 2
    println(bytes[1])   // prints 1
    return Ok(0)
}

258 is 0x0102, and every target stores the low byte first.

offsetPtr

offsetPtr(T, p, n), a *mut T that points n elements past p, is exported and does not compile yet (planned). Walk memory with an array pointer and an index instead.

See also: guide 09, Pointers and memory, the memory model, @core for the containers built on allocators, and @io.