memory

Grow-able byte buffers, string interning pools, and read-only access to allocator and garbage-collector statistics. Import it with import memory.

Buffers and pools are referenced by integer handles returned from their new functions; free them with free when done.

memory.buffer

FunctionSignatureDescription
newmemory.buffer.new() → intAllocate a new buffer; returns its handle
writememory.buffer.write(id: int, data: string) → boolAppend data to the buffer
readmemory.buffer.read(id: int) → stringRead the full buffer contents
resetmemory.buffer.reset(id: int) → voidEmpty the buffer, keeping it allocated
lenmemory.buffer.len(id: int) → intCurrent byte length
freememory.buffer.free(id: int) → voidRelease the buffer

memory.pool

A pool deduplicates equal strings (interning).

FunctionSignatureDescription
newmemory.pool.new() → intAllocate a new interning pool; returns its handle
internmemory.pool.intern(id: int, s: string) → stringReturn the pooled copy of s, adding it if new
hasmemory.pool.has(id: int, s: string) → boolWhether s is already interned
sizememory.pool.size(id: int) → intNumber of interned strings
freememory.pool.free(id: int) → voidRelease the pool

memory.alloc

FunctionSignatureDescription
statsmemory.alloc.stats() → stringJSON string with alloc, totalAlloc, sys, numGC, goroutines
heapAllocmemory.alloc.heapAlloc() → intBytes of allocated heap objects
heapSysmemory.alloc.heapSys() → intBytes of heap memory obtained from the OS
numGCmemory.alloc.numGC() → intCompleted GC cycles

memory.gc

FunctionSignatureDescription
runmemory.gc.run() → voidRun a garbage collection now
setPercentmemory.gc.setPercent(pct: int) → intSet the GC target percentage; returns the previous value
freeOSMemorymemory.gc.freeOSMemory() → voidForce a GC and return unused memory to the OS

Example

import memory

// build a string with a buffer
let buf = memory.buffer.new()
memory.buffer.write(buf, "hello ")
memory.buffer.write(buf, "world")
print(memory.buffer.read(buf))   // hello world
print(memory.buffer.len(buf))    // 11
memory.buffer.free(buf)

// intern repeated strings
let pool = memory.pool.new()
let a = memory.pool.intern(pool, "tag")
let b = memory.pool.intern(pool, "tag")
print(memory.pool.size(pool))    // 1
memory.pool.free(pool)

// inspect heap usage
print(memory.alloc.heapAlloc())
Standard library · View as Markdown · llms-full.txt