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.
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
| Name | Kind | Summary |
|---|---|---|
Allocator | interface | anything that hands out memory: alloc and free |
OutOfMemory | error declaration | the one way an allocation fails |
systemAllocator | con Allocator | the platform heap |
FixedBufferAllocator | struct | hands out pieces of a buffer you provide |
ArenaAllocator | struct | hands out pieces of chunks taken from a parent allocator |
PageAllocator, pageAllocator | struct, con Allocator | whole pages from the operating system |
TestingAllocator | struct | counts the allocations of a parent allocator |
Buffer | struct | bytes collected in allocator memory; a Writer and a Reader |
copy, equal, compare, fill | functions | operations on byte views |
transmuteTo | function | the same pointer as another pointer type |
offsetPtr | function | a pointer moved by a number of elements (planned) |
WasmAllocator | struct | the type behind systemAllocator on WebAssembly |
LibcAllocator | struct | the type behind systemAllocator on x86-64-linux and arm64-linux |
Allocator
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),
}| Method | Signature | Contract |
|---|---|---|
alloc | fn (a: *mut Allocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8 | exactly 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 |
free | fn (a: *mut Allocator) free(buf: [*mut]u8) | gives back the view alloc returned; may do nothing |
new | fn (a: Allocator) new(known T: type) OutOfMemory!*mut T | one T: sizeof T bytes at alignof T |
new | fn (a: Allocator) new(known T: type, count: i32) OutOfMemory![*mut]T | count elements of T |
put | fn (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 |
delete | fn (a: Allocator) delete(ptr: *mut _) | frees what a single new or put returned; the size comes from the pointer's type |
delete | fn (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:
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)
}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:
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:
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) | |
|---|---|---|
alloc | takes the next size bytes of linear memory, growing it in 64 KiB pages | libc malloc |
free | does nothing: linear memory only grows | libc free; give back only what this allocator returned |
| failure | OutOfMemory when linear memory cannot grow | not detected: a failed malloc is not reported (planned) |
align | honored | at 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
| Member | Signature | Result |
|---|---|---|
new | fn (FixedBufferAllocator) new(buf: [*mut]u8) FixedBufferAllocator | an allocator over buf, with nothing handed out |
alloc | fn (a: *mut FixedBufferAllocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8 | the next size bytes of buf, or OutOfMemory when they do not fit |
free | fn (a: *mut FixedBufferAllocator) free(buf: [*mut]u8) | does nothing |
reset | fn (a: *mut FixedBufferAllocator) reset() | makes the whole buffer available again |
| fields | pub buf: [*mut]u8, pub used: i32 | used is the number of bytes handed out, padding included |
freedoes nothing;reset()reclaims. Memory comes back only all at once. Everything handed out beforereset()is dead after it.- It never allocates and never grows. A full buffer fails with
OutOfMemory. alignis counted from the start ofbuf, so a result is aligned only as far asbufitself is.- Its memory lives as long as
buf, so memory carved from a local array cannot leave that array's function.
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
| Member | Signature | Result |
|---|---|---|
new | fn (ArenaAllocator) new(parent: Allocator, chunkBytes: i32 = 4096) ArenaAllocator | an empty arena over parent; takes nothing yet |
alloc | fn (a: *mut ArenaAllocator) alloc(size: i32, align: i32) OutOfMemory![*mut]u8 | the next size bytes of the current chunk, taking a new chunk when they do not fit |
free | fn (a: *mut ArenaAllocator) free(buf: [*mut]u8) | does nothing |
reset | fn (a: *mut ArenaAllocator) reset() | starts again from the first chunk and keeps every chunk |
deinit | fn (a: *mut ArenaAllocator) deinit() | gives every chunk back to parent; the arena can be used again |
allocator | fn (a: *mut ArenaAllocator) allocator() Allocator | the arena as an Allocator, the same value as &arena |
- The first allocation takes a chunk of
chunkBytesfromparent. 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. allocfails withOutOfMemoryonly whenparentdoes.- Chunks are aligned to 16 bytes, so an
alignabove 16 is not guaranteed. freedoes nothing. Afterreset()the arena hands out the same memory again, so everything from before is dead;deinit()also returns the memory toparent. Putdefer arena.deinit()after creating an arena.- Its memory lives as long as the arena.
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.
| WebAssembly | x86-64-linux, arm64-linux | |
|---|---|---|
alloc | grows linear memory by enough 64 KiB pages for size | mmap of size bytes, rounded up to pages by the system |
free | does nothing | munmap |
| failure | OutOfMemory when memory cannot grow | OutOfMemory when mmap fails |
The view alloc returns is size bytes long, starting at a page boundary.
TestingAllocator
| Member | Signature | Result |
|---|---|---|
new | fn (TestingAllocator) new(parent: Allocator) TestingAllocator | a counter over parent |
alloc, free | the Allocator methods | pass the call to parent and count it |
liveAllocations | fn (a: TestingAllocator) liveAllocations() i32 | allocations not yet freed |
totalAllocations | fn (a: TestingAllocator) totalAllocations() i32 | every allocation so far |
| fields | pub parent: Allocator, pub live: i32, pub total: i32 | the counts |
A test checks that liveAllocations() is 0 at the end. Over an allocator
whose free does nothing, freeing still counts.
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).
| Member | Signature | Result |
|---|---|---|
fromAlloc | fn (Buffer) fromAlloc(a: Allocator) Buffer | an empty buffer that grows through a |
fromBytes | fn (Buffer) fromBytes(src: [*con]u8) Buffer | a read-only buffer over src, not a copy |
write | fn (b: *mut Buffer) write(buf: [*con]u8) error!i32 | appends buf and returns buf.len; fails with OutOfMemory when growing fails |
read | fn (b: *mut Buffer) read(buf: [*mut]u8) error!i32 | copies the next unread bytes into buf and returns how many; Ok(0) when all are read |
length | fn (b: Buffer) length() i32 | the bytes written, or the length of src |
asBytes | fn (b: Buffer) asBytes() [*con]u8 | a view of the bytes, not a copy; valid until the buffer grows or is freed |
bytes | fn (b: Buffer) bytes(a: Allocator) OutOfMemory![*con]u8 | a copy in memory from a; the buffer stays usable |
takeBytes | fn (b: *mut Buffer) takeBytes() [*mut]u8 | the buffer's own memory, not a copy; the buffer is finished |
deinit | fn (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:deinitdoes nothing, and anotherwriteortakeBytespanics. writeortakeByteson a buffer fromfromBytespanics;readworks.printlntakes a[*con]u8, not a[*mut]u8: bind the result oftakeBytes()with a type,con text: [*con]u8 = b.takeBytes(), to print it.
| Panic | When |
|---|---|
buffer: write after takeBytes | write on a finished buffer |
buffer: takeBytes on a sealed buffer | a second takeBytes |
buffer: write to a read-only source | write on a buffer from fromBytes |
buffer: takeBytes on a read-only source | takeBytes on a buffer from fromBytes |
buffer: initial allocation failed | fromAlloc when the allocator fails |
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
| Function | Signature | Result |
|---|---|---|
copy | fn copy(dst: [*mut]u8, src: [*con]u8) | copies src into the start of dst; the two may overlap |
equal | fn equal(a: [*con]u8, b: [*con]u8) bool | true when the lengths and bytes are equal |
compare | fn compare(a: [*con]u8, b: [*con]u8) i32 | negative, 0, or positive as a orders before, equal to, or after b, byte by byte; a prefix orders first |
fill | fn 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.
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
| Form | Signature | Result |
|---|---|---|
| one pointer | fn transmuteTo(known U: type, src: _) U | src's address as a U |
| array pointer | fn transmuteTo(known U: type, src: _, count: i32) U | an 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.
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.