memory

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

memory-go

Typed manual memory management for Go without cgo: values and containers that live outside the Go heap, so the garbage collector never scans or frees them.

Memory comes straight from the OS (mmap, VirtualAlloc) through an allocator written for this module: size-classed spans for small values, a mapping each for large ones. CGO_ENABLED=0 builds work. The API follows mm-go, which does the same on top of C calloc through cgo, but misuse panics instead of corrupting memory.

Where off-heap memory cannot reach, the module bridges to the Go heap: funcs, interfaces and closures named from off-heap structures by pointer-free handles, pinned Go pointers, off-heap memory freed by the GC, and chunked pools for types that must stay on the Go heap. Regions can be backed by files and frozen read-only, and a guard-page allocator catches every use after free in tests.

go get github.com/stubbedev/memory-go

Usage

var a memory.Local
defer a.Close()

type node struct {
	Key         int
	Name        memory.String
	Left, Right memory.Ptr[node]
}

n, err := memory.New[node](&a)
if err != nil {
	return err
}
n.Value().Key = 42

xs, err := vector.New[int](&a, 0)
if err != nil {
	return err
}
if err := xs.Push(42); err != nil {
	return err
}

Why

A large pointer-rich structure costs the GC on every cycle, because it must trace every pointer. Off-heap it costs nothing. Full runtime.GC() with a balanced binary tree of 2²⁰ − 1 nodes alive (just bench, linux/amd64, 8 threads):

Tree GC cycle
*goNode on the Go heap 3.64 ms
memory.Ptr[offNode] off-heap 0.13 ms

Allocation speed depends on which tool you use. General-purpose New and Free cost more than Go's new. The typed pool and typedarena skip the allocator: once a chunk has room, getting a value is a free-list pop or a bump of an index. Per allocation (just bench, linux/amd64, 12 threads; this machine is noisy, so read these as rough):

Operation Checked memory_unchecked Go
pool Get + Put 7 ns 5 ns 15 ns (new)
typedarena Alloc, Reset every 1024 8 ns 5 ns 15 ns (new)
Arena New, Reset every 1024 26 ns 17 ns 15 ns (new)
New + Free 57 ns 29 ns 15 ns (new)
hashmap get, Int hasher, 16K entries 12 ns 12 ns
hashmap set + get 164 ns 77 ns 80 ns (map)
hashmap set + get, Int hasher, presized 79 ns 70 ns

Go's numbers leave out the GC work its allocations cause later; the off-heap ones have none.

Memory (u64-to-u64, or a 24-byte node):

memory-go Go
hashmap entry 34 B at 8M entries, 19–39 B in general 47 B
New of a 24-byte node 24 B 24 B plus GC headroom
pool of a 24-byte node 32 B, 24 B unchecked
Node with two 4-byte Index links 16 B
Vector pushed to 1 GiB 1.05 GB peak RSS 3.6 GB (append)

Handles

Off-heap memory may not hold Go pointers, since the GC cannot see them there. Every allocation checks its type and returns ErrHoldsPointers naming the offending field (memory: main.user: .Name is string: type holds Go pointers). These handles point only into off-heap memory and may be stored there:

Handle Owns Created by Released by
Ptr[T] one T New Free
Slice[T] n consecutive Ts MakeSlice, ResizeSlice FreeSlice
String UTF-8 bytes NewString, AppendString FreeString
Ref[T] nothing Ptr.Ref, Slice.Ref, typedarena its owner
View[T] nothing Slice.View its owner
Index[T] nothing, in 4 bytes Region.Grow, Region.IndexAt its Region
pool.Item[T] one T Pool.Get Pool.Put
Pinned[T] a pin of a Go *T Pin Unpin, Pins.UnpinAll
heapref.Ref[T] a slot holding a Go T Table.Put Table.Delete
heapref.WeakRef[T] a slot holding a weak *T Weak.Put Weak.Delete
heapref.FuncID[F] nothing, in 4 bytes Funcs.Register never
union.Value one registered value, inline up to 16 bytes union.Store union.Free

Ptr.Value, Slice.Elems and String.String hand out ordinary Go pointers, slices and strings for access. Those stay valid until the handle is freed or resized and must not outlive it.

Pinned Go objects

A Pinned[T] is the exception: a real Go pointer, allowed off-heap the way cgo allows C memory to hold pointers to pinned Go objects. Pin(&pins, p) pins *p in a memory.Pins, which keeps it alive and unmoved from the Go heap, so Pins must itself stay reachable until everything in it is unpinned; dropping it with live pins makes the runtime panic about a leaking pinned pointer. Unpin(&pins, &h) clears the handle before releasing the pin, because the collector inspects the old value of a handle as it is overwritten and the object may be gone once unpinned; clear any other copies first. Only pointers can be pinned, so keep a func off-heap as a pinned *func().

Owned handles

Own(a, h) hands a Ptr, Slice or String from a Shared to a small owner on the Go heap that frees it once the owner is unreachable, or right away on Close, which also cancels the collection-time free. That free runs on a goroutine of the runtime's, so only a Shared can own handles; the type of Own enforces it. Keep the owner alive while using its Handle. An owner collected after its Shared was closed leaves the memory alone, since Close already released it.

Go values

Off-heap memory cannot hold a func, interface, map or closure, but it can name one. heapref.Table[T] keeps values of any type in a Go slice the collector scans and hands out a Ref[T] of two 4-byte words, slot and generation, which passes the pointer check and may sit in a Ptr, vector or hashmap. A value stays alive while its slot does; Delete clears the slot so the collector can reclaim the value, and the slot is reused under a new generation.

var handlers heapref.Table[func(int)]
r, err := handlers.Put(func(n int) { fmt.Println(n) })
t, err := memory.New[timer](&a) // timer has a field OnFire heapref.Ref[func(int)]
t.Value().OnFire = r
handlers.Get(t.Value().OnFire)(42)

heapref.Weak[T] holds weak.Pointers instead, so an off-heap cache can name Go objects without keeping them alive: Get returns nil once the target is gone, and the slot stays in use until Delete. heapref.Funcs[F] registers functions for good and names each by a 4-byte FuncID. It does not deduplicate, since func values are not comparable and closures share their code; register each function once. With the guards compiled in, using a deleted Ref or one from another table panics. None of these is safe for concurrent use.

Interfaces off-heap

An interface holds Go pointers, so it cannot be stored off-heap. union stands in for one when the concrete types are plain data: a union.Registry assigns each registered type a 4-byte ID, and a union.Value holds the ID and the bytes of the value, inline up to 16 bytes and in an allocation beyond that. A Value holds no Go pointers itself, so vectors, hashmaps and memory.New take it.

var r union.Registry
if _, err := union.Register[circle](&r); err != nil { // rejects pointer types
	return err
}
v, err := union.Store(a, &r, circle{R: 1}) // or StoreInterface(a, &r, shape)
if err != nil {
	return err
}
defer union.Free(a, v)
c, ok := union.Load[circle](&r, v)      // false for any other type
s := union.Interface(&r, v).(shape)      // rebuilt without reflection

Registered types may hold memory handles such as memory.String; the Value copies the handle, not what it owns. memory.CheckType applies the same pointer check to any type.

Pointer-holding types

Types with strings, slices, maps, funcs or interfaces cannot live off-heap. heapslab gives them the same chunked Pool (Get, Put, Len, Reset, Free) and Arena (Alloc, AllocSlice, Reset, Free), but over ordinary []T chunks on the Go heap. The GC still scans every pointer, so this does not remove its work the way off-heap memory does. What it buys: one GC object per chunk instead of one per value, neighbours in the same cache lines, allocation that is a pop or a bump, and bulk reuse. Put and Reset zero what they take back, so whatever those values referenced is collectable at once. Use it for many short-lived or batch-scoped values of one pointer-holding type: parse trees, per-request graphs, connection state. For a few long-lived values, plain new is simpler.

A pointer into a chunk keeps the whole chunk alive, so nothing dangles: the one hazard is using a value after Put or Reset, which then aliases whatever the slot holds next. Checked builds catch that for Pool items, like pool does, at 8 bytes per value; an Arena checks nothing. A pool keeps its free list in a slice of pointers to the values put back.

A 40-byte node holding a string and two pointers (go test -bench . ./heapslab, linux/amd64, 12 threads on a loaded machine, so read these as ratios):

Operation Checked memory_unchecked Go new
Pool Get + Put 8–15 ns 7 ns 31–50 ns
Arena Alloc, Reset every 1024 3–5 ns 3 ns 31–50 ns
Build a 2²⁰ − 1 node tree, per node, GC included 11 ns (Arena) 39 ns
Full runtime.GC() with that tree alive 2.8 ms (Arena), 3.4 ms (Pool) 7.3 ms

The same tree off-heap costs the GC 0.13 ms (see Why), so prefer memory.Ptr handles where the type allows it.

Reservation

An allocation of up to 8 KiB takes a slot from a size class, four to a doubling, so rounding wastes at most a quarter. Slots of a power-of-two size are aligned to it, up to 4 KiB. MakeSliceAligned asks for an alignment, and NewUninit, MakeSliceUninit, MakeSliceAlignedUninit and Pool.GetUninit skip zeroing a value about to be overwritten, except that a new value of a type holding handles is always zeroed: the collector inspects the old contents of a handle as it is overwritten. NewFrom and SliceFrom allocate and copy in one call.

Anything larger gets its own mapping rounded up to whole OS pages, starting on a page: a 1024×1024 RGBA buffer (4 MiB) reserves 4 MiB plus at most one page. Stats.Bytes reports these reservations. On Linux, growing one remaps it instead of copying, so no moment holds both copies, and shrinking unmaps the tail in place on every Unix.

Freed large mappings are kept for reuse by an allocation of the same page count, up to the allocator's peak of live large bytes plus 4 MiB; beyond that the oldest are unmapped. Retired mappings stay committed only within a budget: the largest of 4 MiB, an eighth of live large bytes, and the newest mapping if it is at most 32 MiB, so a frame buffer stays warm while the old doublings of a growing vector do not stay resident. The rest are decommitted except for their last page, which keeps the freed trailer readable, and read as zero without being touched when reused. Trim returns every retained mapping and empty span. Stats covers what is allocated; Footprint covers what is held from the OS, which is what Trim and memory limits care about.

Huge pages

UseHugePages aligns later allocations of at least 2 MiB to 2 MiB and asks Linux for huge pages, including where THP is set to madvise. Pointer chasing over 1 GiB took 105 ns per step on 4 KiB pages and about 75 ns on huge pages here. It is opt-in because such memory can become resident in 2 MiB steps, first touch can take much longer when physical memory is fragmented, and growing an allocation copies instead of remapping. Region.UseHugePages does the same for a region.

Regions

Region[T] reserves address space for up to 2³²−2 elements and uses memory only for those it holds, so it grows without ever moving and pointers into it stay valid. An Index[T] names an element in four bytes and stays meaningful wherever the region is mapped. vector.NewStable gives a vector the same property. Regions are checked for bounds only.

Files

OpenRegion[T](path, maxLen) and NewRegionFile[T](f, maxLen) back a region with a file mapped shared, so a structure linked by Index persists across runs and can be shared between processes. The file starts with a 64-byte header recording the element size, alignment, a fingerprint of the field layout, the byte order and the length; reopening with a different T returns ErrRegionMismatch naming the difference, and a file that is not a region ErrNotRegionFile. Address space for maxLen elements is reserved up front, so elements never move; the file grows in 1 MiB steps on Grow and shrinks on Truncate. On Windows the file is extended to the full reservation while mapped (sparse where the file system allows) and cut back on Close. Sync flushes the elements and length to stable storage (msync and fsync, or FlushViewOfFile and FlushFileBuffers). On Linux, NewSharedRegion backs a region with a memfd; hand r.File() to a child in exec.Cmd.ExtraFiles and open it there with NewRegionFile.

What is guaranteed:

  • Writes reach the file's page cache at once: other processes mapping it see them, and they survive a crash or kill of the writing process without Sync.
  • The length is raised only after the file has grown and lowered only after the dropped elements were cleared, so after a process crash the file always opens, and elements past the length read as zero. An interrupted Truncate can leave dropped elements zeroed but still counted.
  • After an operating system crash or power loss, only what the last completed Sync covered is guaranteed. Pages written since may be lost in any combination, including the length disagreeing with the elements. No write is atomic beyond what the hardware gives an aligned word. On macOS, fsync does not flush the drive's cache.
  • Files are tied to the byte order and the layout of T, not to an address.
  • One process at a time may Grow or Truncate; others see the length the file had when they opened it.
Protection

Region.Freeze makes a region read-only with mprotect or VirtualProtect, so a stray write faults instead of corrupting it; Grow, Truncate and Populate return ErrFrozen until Thaw. FreezeSlice and ThawSlice do the same for a Slice over 8 KiB, which owns whole pages; smaller ones return ErrSharesPages. Resizing a frozen Slice returns ErrFrozen, and freeing it thaws it first, so the allocator never writes to a frozen page. Populate must not be called on a frozen Slice.

Prefaulting

Populate and Region.Populate make memory resident in one batch, so a latency-sensitive section takes no page faults on it. Contents do not change.

The runtime

The Go runtime cannot see off-heap memory, so GOMEMLIMIT alone lets a process overshoot. SyncMemoryLimit sets the runtime's limit to a total minus what your allocators hold committed; call it periodically. SetProfile records the call stack of every live allocation in a pprof profile, for finding leaks.

For the final binary, profile-guided optimisation (default.pgo, see go help build) inlines this module's hot paths past the normal budget, including the liveness checks on handles.

Panics instead of corruption

Every small allocation has an entry in a side table of its span, recording its size and whether it is live, and every span records its allocator; a large allocation has a 16-byte trailer. Neither sits between values, so checked builds use the same slots as unchecked ones. These panic at the point of the mistake:

  • freeing twice, or freeing, resizing or reading a handle that was already resized, even when the resize kept the same address
  • freeing or resizing through a different allocator than the one that allocated
  • reading a freed Ptr, Slice or String through the handle
  • putting a pool.Item or heapslab.Item back twice or into another pool, or reading it after Put
  • using one Local from several goroutines at once
  • out-of-range indices in every container

Handing a Mark to Release after a Reset or Free, or from another arena, panics too.

Not caught by Local, Shared and Arena: a stale handle whose memory was freed and has since been handed out again, Refs, Views and Indexes, and Go pointers or slices obtained from a handle and kept after it was freed. Run the tests on memory.Guarded (see Finding use after free) to catch all of these except Indexes, which belong to a Region. An Arena panics on a handle past its mark but not on one whose space was handed out again, and does not detect a double free. Release frees everything allocated or resized since the Mark, so a container from before the Mark that grew after it is gone too, and a Vector caches its elements without rechecking them, so using one after that goes uncaught. Reading through an old handle faults instead of panicking once its pages are unmapped: after Close or Trim, once a freed large mapping leaves the retention budget, after a large resize that remapped or shrank it, or on Windows once a span has been decommitted. Freeing or resizing a large allocation is checked against the allocator's own table of live mappings, so a stale or foreign large handle panics even then, and in memory_unchecked builds too.

Allocation failures (out of memory, negative or overflowing sizes, pointer types) come back as errors.

Opting out

Build with -tags memory_unchecked to compile the guards out: no side table or trailer, no liveness or owner checks and no concurrency guard. Misuse then corrupts memory silently instead of panicking, so test without the tag first. The pointer-type check and Stats remain. Only the final binary's build decides, so a library depending on memory-go cannot turn the checks off for its users. memory.Checked reports which build you are in. See Why for what it saves.

Allocators

Type Use
memory.Local One goroutine. Zero value is ready; must not be copied after use.
memory.Shared Several goroutines. Each call works in a shard of its own, and memory freed on another shard returns to its owner without a lock.
memory.Arena One goroutine. Mixed types bump-allocated from a parent's spans; Mark, Release and Reset free in bulk, and WithArena scopes one to a function.
memory.Guarded Debugging, from several goroutines. Pages of its own and a guard page per allocation, freed addresses never reused; slow and wasteful, for tests.

All satisfy memory.Allocator, which every function and container takes, so a hashmap can live in an arena and vanish with it. Stats reports live allocations and bytes, Footprint what is held from the OS, Trim returns retained empty pages to the OS, and Close releases everything at once. An arena's Footprint and its parent's add up to the true total, so pass both to SyncMemoryLimit.

Packages

Package What it is
memory Allocators, Region (anonymous or file-backed), the Ptr, Ref, Slice, View, Index, String and Pinned handles, and Owned
vector Growable slice: Push, Pop, At, Ptr, Set, RemoveAt, DeleteFunc, Truncate, Reserve, Clip, All, Values, From, and Append for bulk copies; NewStable never moves
hashmap Swiss table: Map for comparable keys with an optional Hasher such as Int, Strings for text keys looked up without allocating; Contains, Keys, Values, Clear, Clip, a capacity hint, Map.GetOrSet and Map.Upsert that hash once, and Map.GetMany for batched lookups that overlap their cache misses
btree Ordered map with Min, Max, All, Keys, Values, From, Range and Backward
intern One copy of each distinct string, named by a 4-byte Symbol
bufpool Recycled byte buffers of power-of-two sizes, aligned for direct I/O
ring Bounded lock-free queue from one goroutine to one other
linkedlist Doubly linked list in one pooled node vector linked by index; freed nodes are reused, Clip compacts
minheap Binary heap ordered by a less func, with DeleteFunc and Clip
typedarena Chunked bump allocator for one type, handing out Refs; Reset reuses its warm chunks, Free releases them
pool Free-list allocator for one type: Get and Put individual values without touching the allocator
heapref Go-heap values such as funcs, interfaces and maps named from off-heap memory by pointer-free handles: Table, Weak and Funcs
union Tagged union: a Value holds one value of any registered pointer-free type, so interface-typed data can live off-heap
heapslab Pool and Arena for one type that holds Go pointers, carved from Go-heap chunks; Put and Reset zero what they take back
memtest Local, Shared and Guarded allocators that fail a test on a leak

Containers are not safe for concurrent use, even on a Shared allocator. memory.String is not comparable, because == could only compare addresses; use hashmap.Strings to key by text. Adding or removing entries of a hashmap, btree or linkedlist while ranging over All, From, Range, Backward, Keys or Values panics instead of reading freed or reused slots.

Testing failure paths

Allocation failures are hard to provoke, so memory.NewFaulty wraps an allocator and fails it on demand: FailAllocsAfter(n) for out-of-memory, FailFreesAfter(n) for the operating system refusing memory back. This module's own containers are swept this way, failing each allocation and free in turn.

Finding use after free

memory.Guarded gives every allocation pages of its own, ending the value exactly at an inaccessible guard page, and on free makes the pages inaccessible and never hands their addresses out again. Any later use of freed memory faults at the point of the mistake, whether through the handle, a Ref, a View or a Go pointer kept from Value or Elems, and so does writing past the end. Reading a freed Ptr, Slice or String through its handle panics with a message instead, resizing always moves, and freeing twice, through the wrong allocator or with a stale handle panics. Not guarded: the rest of the value's first page before it, and the padding after it that a larger requested alignment needs.

memtest.Guarded(t) returns one that fails the test on a leak, so a suite written against memtest.Local runs on it by swapping the constructor. Turn faults into recoverable panics with debug.SetPanicOnFault(true) to assert on them.

Each allocation costs at least a page of memory, two of address space and, on Linux, a mapping of the vm.max_map_count limit (65530 by default), so keep it out of production. Freed address space stays reserved until Close; NewGuarded(quarantine) caps it, returning the oldest fully freed blocks to the operating system beyond that. Those still fault until the operating system maps something else at their addresses, which can then hide a use after free.

Recipes

Recipe What it does
just check Every release gate in order: vet, lint, test, test-unchecked, test-32bit, race, build
just vet Static analysis with go vet
just lint golangci-lint run against the strict config in .golangci.yml
just test go test ./...
just test-unchecked go test ./... with the guards compiled out
just test-32bit go test ./... as a 32-bit program
just race Tests under the race detector (needs cgo; the library itself never does)
just build Compile-check every package
just fuzz [time] Fuzz each allocator and container against its model, 30s each by default
just bench All benchmarks, including the GC comparison
just fmt Format every Go source in place

Every dev tool (Go toolchain pinned to the version go.mod declares, gopls, golangci-lint, delve, just, git, gh) comes from the flake: direnv allow on entry, or nix develop explicitly. GOTOOLCHAIN=local keeps the compiler from downloading itself.

Nix

  • nix build builds and tests the module (nix/package.nix; the dev shell is nix/shell.nix, both imported by flake.nix; update vendorHash whenever go.sum changes)
  • nix fmt formats the nix files with alejandra

CI

.github/workflows/test.yml runs vet and tests on Linux, macOS and Windows, with and without memory_unchecked, the race detector on Linux and macOS, the tests as a 32-bit program, cross-builds for arm64, 386, FreeBSD and Windows on arm64, golangci-lint, and a minute of fuzzing per allocator and container. .github/workflows/security.yml runs CodeQL (Go and GitHub Actions), Grype and govulncheck, uploading findings to code scanning; dependency review gates pull requests. Dependabot keeps the module and the workflows current.

Linting

.golangci.yml starts from the standard linter set and layers on bodyclose, copyloopvar, errorlint, gosec, intrange, misspell, modernize, nolintlint, perfsprint, revive (default rules plus exported), unconvert, unparam, usestdlibvars and whitespace, with gofumpt and gci as formatters. No issue caps: every finding fails the build. gosec's unsafe audit (G103) is waived only for the files that form the boundary between typed values and raw memory, listed in .golangci.yml.

Documentation

Overview

Package memory allocates typed values outside the Go heap without cgo.

Memory comes straight from the operating system: small allocations from size-classed spans, large ones from a mapping of their own, rounded up to whole pages. The garbage collector neither scans nor frees it, so every value placed there must be free of Go pointers: no pointers, slices, strings, maps, channels, functions or interfaces. Every allocation checks this and returns ErrHoldsPointers otherwise. The handle types of this package, Ptr, Ref, Slice, View, Index and String, refer only to memory the garbage collector does not manage and may be stored off-heap. So may Pinned, a Go pointer to an object a Pins keeps pinned on the Go heap, as cgo allows C memory to hold pointers to pinned Go objects. Owned frees a handle from a Shared once a small owner on the Go heap becomes unreachable.

Local serves a single goroutine, Shared several without contending, and Arena frees whole groups of allocations at once. Region grows in place without moving, and OpenRegion backs one with a file so that it persists and can be shared between processes. Region.Freeze and FreezeSlice make memory read-only, so that a stray write faults. Guarded is for tests: it gives every allocation pages of its own followed by a guard page and never reuses freed addresses, so use after free and overruns fault where they happen.

Misuse panics instead of corrupting memory. Every allocation is tracked in a side table or trailer recording its allocator, its size and whether it is live, so a double free, a free or resize through the wrong allocator, and reading a freed Ptr, Slice or String, or one that has since been resized, through its handle all panic, as does using a Local from several goroutines at once. A handle to memory that has since been freed and handed out again cannot be told apart from its new owner, and Refs and Go pointers obtained from handles are not checked, except on Guarded.

Building with the memory_unchecked tag compiles these checks out: no side table, no liveness or owner checks and no concurrency guard, roughly halving the cost of an allocation. Misuse then corrupts memory silently. The pointer-type check and Stats remain.

Example
package main

import (
	"fmt"

	memory "github.com/stubbedev/memory-go"
)

func main() {
	var a memory.Local
	defer a.Close()

	type vec3 struct{ X, Y, Z float64 }

	v, err := memory.New[vec3](&a)
	if err != nil {
		panic(err)
	}
	*v.Value() = vec3{X: 1, Y: 2, Z: 3}
	fmt.Println(*v.Value())

	s, err := memory.MakeSlice[int](&a, 3)
	if err != nil {
		panic(err)
	}
	copy(s.Elems(), []int{10, 20, 30})
	if s, err = memory.ResizeSlice(&a, s, 4); err != nil {
		panic(err)
	}
	fmt.Println(s.Elems())

	_, err = memory.New[string](&a)
	fmt.Println(err)

	if err := memory.FreeSlice(&a, s); err != nil {
		panic(err)
	}
	if err := memory.Free(&a, v); err != nil {
		panic(err)
	}
	fmt.Println(a.Stats())
}
Output:
{1 2 3}
[10 20 30 0]
memory: string: type holds Go pointers
{0 0}
Example (LinkedValues)
package main

import (
	"fmt"

	memory "github.com/stubbedev/memory-go"
)

func main() {
	var a memory.Local
	defer a.Close()

	type node struct {
		Name memory.String
		Next memory.Ptr[node]
	}

	var head memory.Ptr[node]
	for _, name := range []string{"c", "b", "a"} {
		n, err := memory.New[node](&a)
		if err != nil {
			panic(err)
		}
		label, err := memory.NewString(&a, name)
		if err != nil {
			panic(err)
		}
		*n.Value() = node{Name: label, Next: head}
		head = n
	}
	for n := head; !n.IsNil(); {
		fmt.Print(n.Value().Name, " ")
		next := n.Value().Next
		if err := memory.FreeString(&a, n.Value().Name); err != nil {
			panic(err)
		}
		if err := memory.Free(&a, n); err != nil {
			panic(err)
		}
		n = next
	}
	fmt.Println()
}
Output:
a b c

Index

Examples

Constants

View Source
const Checked = true

Checked reports whether the misuse guards are compiled in, which they are unless the build sets the memory_unchecked tag.

Variables

View Source
var (
	// ErrHoldsPointers reports a type that holds Go pointers and so cannot
	// live off-heap.
	ErrHoldsPointers = errors.New("type holds Go pointers")
	// ErrNegativeLen reports a negative length or capacity.
	ErrNegativeLen = errors.New("negative length")
	// ErrTooLarge reports a size that overflows int.
	ErrTooLarge = errors.New("allocation size overflows int")
	// ErrAlignment reports an alignment that is not a power of two up to 4 KiB.
	ErrAlignment = errors.New("invalid alignment")
)
View Source
var (
	// ErrFrozen reports a change to memory that Freeze or FreezeSlice made
	// read-only.
	ErrFrozen = errors.New("memory is frozen")
	// ErrSharesPages reports an attempt to protect an allocation small enough to
	// share its pages with other allocations.
	ErrSharesPages = errors.New("allocation shares its pages")
)
View Source
var (
	// ErrNotRegionFile reports a file that does not hold a Region: wrong magic,
	// format version or byte order, or shorter than its recorded length.
	ErrNotRegionFile = errors.New("not a region file")
	// ErrRegionMismatch reports a region file written for an element type of a
	// different size, alignment or layout.
	ErrRegionMismatch = errors.New("region file holds a different element type")
)
View Source
var ErrInjected = errors.New("injected failure")

ErrInjected is the failure a Faulty allocator reports.

View Source
var ErrOverLimit = errors.New("off-heap memory exceeds the limit")

ErrOverLimit reports off-heap memory that alone exceeds a memory limit.

View Source
var ErrRegionFull = errors.New("region is full")

ErrRegionFull reports growth past the length a Region reserved.

Functions

func CheckType added in v0.6.0

func CheckType[T any]() error

CheckType returns an error wrapping ErrHoldsPointers if T holds Go pointers and so cannot live off-heap, naming the offending field, and nil otherwise. Every allocation runs this check; packages that copy a T into off-heap memory by other means use it to apply the same rule.

func Free

func Free[T any](a Allocator, p Ptr[T]) error

Free releases p, which must come from New on the same allocator. Freeing a nil Ptr does nothing. Freeing p twice, or through another allocator, panics.

func FreeSlice

func FreeSlice[T any](a Allocator, s Slice[T]) error

FreeSlice releases s. Freeing the empty Slice does nothing. Freeing s twice, or through another allocator, panics.

func FreeString

func FreeString(a Allocator, s String) error

FreeString releases s.

func FreezeSlice added in v0.6.0

func FreezeSlice[T any](a Allocator, s Slice[T]) error

FreezeSlice makes the memory of s read-only, so that writing to it faults instead of corrupting it. Only allocations over 8 KiB own their pages; smaller ones return ErrSharesPages. Resizing a frozen Slice returns ErrFrozen, and freeing it thaws it first. Populate must not be called on a frozen Slice. s must come from a and be live, or FreezeSlice panics.

func Populate added in v0.4.0

func Populate[T any](s Slice[T]) error

Populate makes s resident now, in one batch, so that first use takes no page faults: a fault costs far more than the access it interrupts. Contents do not change. Use it before a latency-sensitive section, knowing RSS rises at once. It panics if s is already freed.

func SyncMemoryLimit added in v0.4.0

func SyncMemoryLimit(total int64, sources ...Footprinter) (int64, error)

SyncMemoryLimit keeps the process within total bytes by setting the Go runtime's soft memory limit, the same knob as GOMEMLIMIT, to total minus what sources hold committed. The runtime cannot see off-heap memory, so without this a limit protects only the Go heap and the process can overshoot it. The limit follows off-heap use only when called, so call it periodically and after large changes. It returns the limit set. If sources alone reach total it returns ErrOverLimit and leaves the limit as it was, because a limit near zero would make the collector run constantly without helping.

func ThawSlice added in v0.6.0

func ThawSlice[T any](a Allocator, s Slice[T]) error

ThawSlice makes the memory of a frozen s writable again. Thawing a Slice that is not frozen does nothing.

func Unpin added in v0.6.0

func Unpin[T any](ps *Pins, p *Pinned[T])

Unpin clears *p and then releases the pin it held, so the handle being unpinned never holds a pointer the garbage collector may since have freed. Clear every other copy of the handle first, for the same reason. Unpinning the nil Pinned does nothing; unpinning a pointer ps does not hold pinned panics.

func WithArena added in v0.5.0

func WithArena(parent ArenaParent, f func(*Arena) error) (err error)

WithArena runs f with a new Arena on parent and frees the Arena when f returns or panics, so nothing allocated in f may be used afterwards. It returns f's error joined with any error from freeing.

Types

type Allocator

type Allocator interface {
	Stats() Stats
	Footprint() Footprint
	// contains filtered or unexported methods
}

Allocator is the memory source every function and container in this module takes. It is implemented by *Local, *Shared, *Arena, *Guarded and *Faulty only.

type Arena added in v0.4.0

type Arena struct {
	// contains filtered or unexported fields
}

Arena is an Allocator that hands out memory by bumping an offset and frees it all at once with Reset, or back to a Mark with Release. It takes spans from a parent allocator and takes mixed types and every container in this module, so a request's whole object graph can go away in one call.

It suits one goroutine at a time. Spans it holds count in its own Footprint and not the parent's; allocations over 8 KiB come from the parent and count in the parent's alone, so summing both gives the true total. Closing the parent invalidates it. Freeing or resizing the most recent allocation reclaims its space or grows it in place; freeing anything else does nothing until Reset. Reading a handle past the current mark panics, but a handle whose space has been handed out again is not caught, and a double free is not detected. The zero Arena is not usable; use NewArena.

Example
package main

import (
	"fmt"

	memory "github.com/stubbedev/memory-go"
)

func main() {
	var parent memory.Local
	defer parent.Close()

	a := memory.NewArena(&parent)
	for request := range 2 {
		name, err := memory.NewString(a, "request")
		if err != nil {
			panic(err)
		}
		fmt.Println(name.String(), request)
		if err := a.Reset(); err != nil {
			panic(err)
		}
	}
}
Output:
request 0
request 1

func NewArena added in v0.4.0

func NewArena(parent ArenaParent) *Arena

NewArena returns an empty Arena drawing from parent.

func (*Arena) Footprint added in v0.4.0

func (a *Arena) Footprint() Footprint

Footprint reports the spans a holds from its parent. Allocations over 8 KiB are held by the parent and count in its Footprint.

func (*Arena) Free added in v0.4.0

func (a *Arena) Free() error

Free frees everything allocated from a, returns its spans to the parent and invalidates every Mark. a remains usable.

func (*Arena) Mark added in v0.4.0

func (a *Arena) Mark() Mark

Mark returns the current position, to Release back to later. An allocation made before the Mark stays where it is from then on: resizing it moves it past the Mark, so the next Release frees it. That includes the storage of a container that grew after the Mark, which must not be used after the Release.

func (*Arena) Release added in v0.4.0

func (a *Arena) Release(m Mark) error

Release frees everything allocated or resized since m was taken, keeping the memory for reuse. It restores the small-allocation counts of Stats to those at m, so a small allocation made before m and freed after it counts as live again until Reset. It panics on the zero Mark, on a Mark from another Arena, on a Mark from before a Reset or Free, and on a Mark it can tell has been released past.

func (*Arena) Reset added in v0.4.0

func (a *Arena) Reset() error

Reset frees everything allocated from a, keeping its spans for reuse, and invalidates every Mark.

func (*Arena) Stats added in v0.4.0

func (a *Arena) Stats() Stats

Stats reports the allocations made since the last Reset, counting a freed allocation only once freed.

type ArenaParent added in v0.5.0

type ArenaParent interface {
	Allocator
	// contains filtered or unexported methods
}

ArenaParent is an allocator an Arena can draw spans from. It is implemented by *Local and *Shared only.

type Faulty added in v0.5.0

type Faulty struct {
	// contains filtered or unexported fields
}

Faulty is an Allocator for tests that fails on demand, because out-of-memory and unmap failures cannot otherwise be provoked. Everything else goes to the wrapped allocator. It is not safe for concurrent use.

func NewFaulty added in v0.5.0

func NewFaulty(a Allocator) *Faulty

NewFaulty returns a Faulty over a that does not fail until told to.

func (*Faulty) FailAllocsAfter added in v0.5.0

func (f *Faulty) FailAllocsAfter(n int)

FailAllocsAfter lets n more allocations succeed, then fails every later one, along with every resize that does not fit in place, leaving their input intact. A negative n stops failing.

func (*Faulty) FailFreesAfter added in v0.5.0

func (f *Faulty) FailFreesAfter(n int)

FailFreesAfter lets n more frees succeed. Each later free still releases the memory but reports an error, as does each later resize, which returns the new memory with it, as when the operating system refuses to take the old memory back. A negative n stops failing.

func (*Faulty) Footprint added in v0.5.0

func (f *Faulty) Footprint() Footprint

Footprint reports the wrapped allocator's Footprint.

func (*Faulty) Stats added in v0.5.0

func (f *Faulty) Stats() Stats

Stats reports the wrapped allocator's Stats.

type Footprint added in v0.4.0

type Footprint struct {
	// Mapped is the address space held, most of which may not be backed by
	// memory.
	Mapped int
	// Committed is an upper bound on the bytes that may be resident: everything
	// handed out so far and not yet returned to the operating system.
	Committed int
	// Retained is the part of Mapped kept for reuse and not currently allocated.
	Retained int
}

Footprint describes the address space and memory an allocator holds from the operating system, whether or not allocations currently use it.

type Footprinter added in v0.4.0

type Footprinter interface {
	Footprint() Footprint
}

Footprinter reports memory held from the operating system. Allocator and Region implement it.

type Guarded added in v0.6.0

type Guarded struct {
	// contains filtered or unexported fields
}

Guarded is a debugging Allocator that turns use after free and buffer overruns into faults at the point of the mistake. Every allocation gets pages of its own, with the value placed flush against a following inaccessible guard page, and a freed allocation's pages are made inaccessible and their addresses never handed out again. So reading or writing freed memory faults through any route: a Ptr, Slice or String, a Ref or View, or a Go pointer or slice obtained from a handle; so does running past the end of an allocation. Reading a freed Ptr, Slice or String through its handle panics with a message instead. Running before the start is caught only past the start of the value's first page, and when a larger alignment is requested the padding after the value up to the next multiple of it is not guarded either.

Realloc always moves, quarantining the old pages. Freeing twice, freeing or resizing a stale or foreign handle, or with the wrong size panics.

Each allocation costs at least two pages of address space and one of memory, and on Linux one memory mapping of the vm.max_map_count limit, which is 65530 by default, so it suits tests rather than production. Freed address space stays reserved until Close, unless NewGuarded set a quarantine budget. Guarded is safe for concurrent use; its zero value is ready for use and keeps every freed range until Close.

func NewGuarded added in v0.6.0

func NewGuarded(quarantine int) *Guarded

NewGuarded returns a Guarded that keeps at most quarantine bytes of freed address space reserved. Beyond that it returns the oldest blocks whose allocations are all freed to the operating system, oldest first. Their addresses still fault until the operating system maps something else there, which can then hide a use after free. A block holding a live allocation is never returned, so the quarantine can exceed the budget. A negative quarantine keeps everything until Close.

func (*Guarded) Close added in v0.6.0

func (g *Guarded) Close() error

Close unmaps every page of g, invalidating everything allocated from it, and leaves g ready for reuse with the same quarantine budget. Using a handle from before Close faults, unless the operating system has mapped its address again.

func (*Guarded) Footprint added in v0.6.0

func (g *Guarded) Footprint() Footprint

Footprint reports the memory g holds from the operating system. Mapped includes guard pages and quarantined address space, Committed counts the pages of live allocations and one bookkeeping page per block, and Retained is the quarantined address space of freed allocations.

func (*Guarded) Stats added in v0.6.0

func (g *Guarded) Stats() Stats

Stats reports the allocations g currently holds. Bytes counts the sizes requested, since nothing is rounded up.

type Index added in v0.4.0

type Index[T any] uint32

Index refers to an element of a Region in four bytes, half the size of a pointer, and may be stored off-heap. It stays meaningful across processes and mappings because it is relative to the Region. The zero Index is nil.

func (Index[T]) IsNil added in v0.4.0

func (i Index[T]) IsNil() bool

IsNil reports whether i refers to nothing.

type Local

type Local struct {
	// contains filtered or unexported fields
}

Local is an Allocator for a single goroutine. Its zero value is ready for use, and it must not be copied after first use. Using it from several goroutines at once panics, unless built with memory_unchecked; use Shared for that.

func (*Local) Close

func (l *Local) Close() error

Close unmaps every page of l, invalidating everything allocated from it, and leaves l ready for reuse. Using a handle from before Close faults, or panics if its address has been mapped again by this allocator.

func (*Local) Footprint added in v0.4.0

func (l *Local) Footprint() Footprint

Footprint reports the memory l holds from the operating system.

func (*Local) SetProfile added in v0.4.0

func (l *Local) SetProfile(p *pprof.Profile)

SetProfile records the call stack of every allocation in p, created with pprof.NewProfile, until it is freed, so `go tool pprof` shows where live off-heap memory came from. It costs a lock and a stack capture per allocation and is meant for finding leaks, not for production. Nil stops recording.

func (*Local) Stats

func (l *Local) Stats() Stats

Stats reports the allocations l currently holds.

func (*Local) Trim

func (l *Local) Trim() error

Trim returns retained empty pages to the operating system.

func (*Local) UseHugePages added in v0.4.0

func (l *Local) UseHugePages()

UseHugePages makes later allocations of at least 2 MiB start on a 2 MiB boundary and asks the operating system to back them with huge pages, which cuts address translation misses on large randomly accessed data. Such allocations can become resident in 2 MiB steps, first touch can be slower when physical memory is fragmented, and growing one copies instead of remapping. Only Linux acts on the request; elsewhere only the alignment changes.

type Mark added in v0.4.0

type Mark struct {
	// contains filtered or unexported fields
}

Mark is a position in an Arena to Release back to.

type Ownable added in v0.6.0

type Ownable interface {
	// contains filtered or unexported methods
}

Ownable is a handle Owned can free: Ptr, Slice or String.

type Owned added in v0.6.0

type Owned[H Ownable] struct {
	// contains filtered or unexported fields
}

Owned ties a handle allocated from a Shared to a small object on the Go heap and frees the handle when that object becomes unreachable, or earlier on Close. The collector frees it on a goroutine of its own, which is why only a Shared can own handles. A handle whose Shared has been closed since Own is left alone, as Close already released it.

func Own added in v0.6.0

func Own[H Ownable](a *Shared, h H) *Owned[H]

Own takes over h, which must come from a and be live, and returns its owner. Nothing else may free h afterwards.

func (*Owned[H]) Close added in v0.6.0

func (o *Owned[H]) Close() error

Close frees the handle now and cancels its release on collection. Closing o again does nothing.

func (*Owned[H]) Handle added in v0.6.0

func (o *Owned[H]) Handle() H

Handle returns the owned handle, or the zero handle after Close. It stays valid only while o is reachable, so keep o alive, for instance with runtime.KeepAlive, until the handle is no longer used.

type Pinned added in v0.6.0

type Pinned[T any] struct {
	// contains filtered or unexported fields
}

Pinned is a Go pointer to a T on the Go heap that may be stored off-heap, the way cgo lets C memory hold pointers to pinned Go objects. Pin creates it through a Pins, which keeps the T alive and unmoved until Unpin; the garbage collector never sees the off-heap copy. The zero Pinned is nil.

Only pointers can be pinned. To keep a func or another pointer-shaped value off-heap, pin a pointer to a variable holding it, such as a *func().

func Pin added in v0.6.0

func Pin[T any](ps *Pins, p *T) Pinned[T]

Pin pins the object p points to in ps and returns a handle to it. Pinning the same pointer again counts, and each Pin needs its own Unpin. A nil p returns the nil Pinned. The runtime refuses pointers into a Go arena.

func (Pinned[T]) IsNil added in v0.6.0

func (p Pinned[T]) IsNil() bool

IsNil reports whether p refers to nothing.

func (Pinned[T]) Value added in v0.6.0

func (p Pinned[T]) Value() *T

Value returns the pinned pointer. It is valid until the T is unpinned; using it after Unpin is not detected.

type Pins added in v0.6.0

type Pins struct {
	// contains filtered or unexported fields
}

Pins pins Go objects for Pinned handles and holds them on the Go heap until they are unpinned, so it must stay reachable from Go for as long as any of its pins are live: dropping a Pins with live pins makes the runtime panic about a leaking pinned pointer. Its zero value is ready for use, it is safe for concurrent use, and it must not be copied after first use.

func (*Pins) Len added in v0.6.0

func (ps *Pins) Len() int

Len returns the number of distinct objects ps holds pinned.

func (*Pins) UnpinAll added in v0.6.0

func (ps *Pins) UnpinAll()

UnpinAll releases every pin held by ps and leaves it ready for reuse. Every Pinned handle from ps must be cleared first or never used again.

type Ptr

type Ptr[T any] struct {
	// contains filtered or unexported fields
}

Ptr owns a single off-heap T allocated by New. Free releases it. The zero Ptr is nil.

func New

func New[T any](a Allocator) (Ptr[T], error)

New allocates a zeroed T.

func NewFrom added in v0.5.0

func NewFrom[T any](a Allocator, value T) (Ptr[T], error)

NewFrom allocates a T holding value.

func NewUninit added in v0.4.0

func NewUninit[T any](a Allocator) (Ptr[T], error)

NewUninit is New without zeroing: the T holds whatever the memory held. Use it only for a value that is written in full before it is read. A T holding handles is zeroed anyway, because the garbage collector inspects the old value of a handle while it is overwritten and would take stale bytes for a pointer.

func (Ptr[T]) IsNil

func (p Ptr[T]) IsNil() bool

IsNil reports whether p refers to nothing.

func (Ptr[T]) Ref

func (p Ptr[T]) Ref() Ref[T]

Ref returns a non-owning reference to the T. It panics if the T is already freed.

func (Ptr[T]) Value

func (p Ptr[T]) Value() *T

Value returns a Go pointer to the T, valid until it is freed. It panics if the T is already freed.

type Ref

type Ref[T any] struct {
	// contains filtered or unexported fields
}

Ref is a non-owning reference to an off-heap T, such as an element of a Slice or a value in a typedarena. It cannot be freed on its own. The zero Ref is nil.

func (Ref[T]) IsNil

func (r Ref[T]) IsNil() bool

IsNil reports whether r refers to nothing.

func (Ref[T]) Value

func (r Ref[T]) Value() *T

Value returns a Go pointer to the T, valid as long as its owner is.

type Region added in v0.4.0

type Region[T any] struct {
	// contains filtered or unexported fields
}

Region is one contiguous array of up to a fixed number of off-heap Ts that grows in place: it reserves address space up front and only uses memory for the elements it has, so pointers into it stay valid until Truncate drops their element or Close. NewRegion backs it with anonymous memory; OpenRegion, NewRegionFile and NewSharedRegion with a file that persists the elements and can be shared between processes. It is not safe for concurrent use, and its elements are not protected by the misuse guards beyond bounds checks.

Example
package main

import (
	"fmt"

	memory "github.com/stubbedev/memory-go"
)

func main() {
	r, err := memory.NewRegion[int64](1 << 24)
	if err != nil {
		panic(err)
	}
	defer r.Close()

	i, err := r.Grow(1)
	if err != nil {
		panic(err)
	}
	first := r.Ptr(i)
	*first = 42
	if _, err := r.Grow(1 << 20); err != nil {
		panic(err)
	}
	fmt.Println(*first, r.Len())
}
Output:
42 1048577

func NewRegion added in v0.4.0

func NewRegion[T any](maxLen int) (*Region[T], error)

NewRegion reserves address space for maxLen Ts without using memory for them. maxLen may be far above what the machine could hold, and is at most 2³²−2 so that every element has an Index.

func NewRegionFile added in v0.6.0

func NewRegionFile[T any](f *os.File, maxLen int) (*Region[T], error)

NewRegionFile maps f, which must be open for reading and writing, as a Region of up to maxLen Ts. An empty f gets a header recording the element type, and one that already holds a Region opens with the elements and length it had; a different element type returns ErrRegionMismatch and anything else ErrNotRegionFile. Address space for maxLen elements is reserved up front, so the elements never move, and the file grows and shrinks with the Region. Writes go straight to the file, so other processes mapping it see them; f may be a memfd or other shared memory file to share a Region with child processes. Only one process may Grow or Truncate it, and others see the length it had when they opened it. On success r owns f and closes it in Close; on error f is left open.

func NewSharedRegion added in v0.6.0

func NewSharedRegion[T any](maxLen int) (*Region[T], error)

NewSharedRegion returns a Region of up to maxLen Ts backed by an anonymous memory file (memfd), on Linux only. Pass r.File() to a child process, for example in exec.Cmd.ExtraFiles, and open it there with NewRegionFile to share the elements; the memory lives until every process has closed it.

func OpenRegion added in v0.6.0

func OpenRegion[T any](path string, maxLen int) (*Region[T], error)

OpenRegion opens the region file at path, creating it if it does not exist, like NewRegionFile. The Region owns the file and closes it in Close.

func (*Region[T]) Cap added in v0.4.0

func (r *Region[T]) Cap() int

Cap returns the length r can grow to.

func (*Region[T]) Close added in v0.4.0

func (r *Region[T]) Close() error

Close releases r, invalidating every pointer into it. A Region backed by a file is unmapped and its file closed; the file stays consistent, but only Sync makes it durable. Closing twice does nothing.

func (*Region[T]) Elems added in v0.4.0

func (r *Region[T]) Elems() []T

Elems returns the elements as a Go slice.

func (*Region[T]) File added in v0.6.0

func (r *Region[T]) File() *os.File

File returns the file backing r, or nil if r is not backed by one. It stays owned by r.

func (*Region[T]) Footprint added in v0.4.0

func (r *Region[T]) Footprint() Footprint

Footprint reports the memory r holds from the operating system.

func (*Region[T]) Freeze added in v0.6.0

func (r *Region[T]) Freeze() error

Freeze makes the elements of r read-only, so that writing to them faults instead of corrupting them. Grow, Truncate and Populate return ErrFrozen until Thaw. Freezing a frozen Region does nothing.

func (*Region[T]) Frozen added in v0.6.0

func (r *Region[T]) Frozen() bool

Frozen reports whether r is frozen.

func (*Region[T]) Grow added in v0.4.0

func (r *Region[T]) Grow(n int) (Index[T], error)

Grow appends n zeroed elements and returns the Index of the first. It does not move existing elements. A frozen r returns ErrFrozen.

func (*Region[T]) IndexAt added in v0.4.0

func (r *Region[T]) IndexAt(i int) Index[T]

IndexAt returns the Index of element i. i may equal Len, naming the element the next Grow creates. It panics if i is out of range.

func (*Region[T]) Len added in v0.4.0

func (r *Region[T]) Len() int

Len returns the number of elements.

func (*Region[T]) Populate added in v0.4.0

func (r *Region[T]) Populate() error

Populate makes the current elements of r resident now, like the function Populate. A frozen r returns ErrFrozen.

func (*Region[T]) Ptr added in v0.4.0

func (r *Region[T]) Ptr(i Index[T]) *T

Ptr returns a pointer to the element i refers to. It panics if i is nil or past the end.

func (*Region[T]) Sync added in v0.6.0

func (r *Region[T]) Sync() error

Sync writes the elements and length of a file-backed r through to stable storage, returning once they are durable. It does nothing for a Region not backed by a file.

func (*Region[T]) Thaw added in v0.6.0

func (r *Region[T]) Thaw() error

Thaw makes the elements of a frozen r writable again. Thawing a Region that is not frozen does nothing.

func (*Region[T]) Truncate added in v0.4.0

func (r *Region[T]) Truncate(n int) error

Truncate shortens r to n elements. Dropped elements read as zero if r grows again, and memory beyond a small slack goes back to the operating system. It panics if n is out of range, and returns ErrFrozen if r is frozen.

func (*Region[T]) UseHugePages added in v0.4.0

func (r *Region[T]) UseHugePages() error

UseHugePages asks the operating system to back r with huge pages. See Local.UseHugePages for the trade-offs.

type Shared

type Shared struct {
	// contains filtered or unexported fields
}

Shared is an Allocator safe for concurrent use. Each goroutine works in a shard of its own for the length of a call, so calls on different processors do not contend, and memory freed on another shard goes back to its owner without a lock. Its zero value is ready for use. Containers built on it are still not safe for concurrent use.

func (*Shared) Close

func (s *Shared) Close() error

Close unmaps every page of s, invalidating everything allocated from it, and leaves s ready for reuse.

func (*Shared) Footprint added in v0.4.0

func (s *Shared) Footprint() Footprint

Footprint reports the memory s holds from the operating system.

func (*Shared) SetProfile added in v0.4.0

func (s *Shared) SetProfile(p *pprof.Profile)

SetProfile behaves like Local.SetProfile.

func (*Shared) Stats

func (s *Shared) Stats() Stats

Stats reports the allocations s currently holds.

func (*Shared) Trim

func (s *Shared) Trim() error

Trim returns retained empty pages to the operating system.

func (*Shared) UseHugePages added in v0.4.0

func (s *Shared) UseHugePages()

UseHugePages behaves like Local.UseHugePages.

type Slice

type Slice[T any] struct {
	// contains filtered or unexported fields
}

Slice owns n consecutive off-heap Ts allocated by MakeSlice or ResizeSlice. FreeSlice releases them. The zero Slice is empty.

func MakeSlice

func MakeSlice[T any](a Allocator, n int) (Slice[T], error)

MakeSlice allocates n zeroed Ts. n == 0 returns the empty Slice.

func MakeSliceAligned added in v0.4.0

func MakeSliceAligned[T any](a Allocator, n, align int) (Slice[T], error)

MakeSliceAligned allocates n zeroed Ts whose first element's address is a multiple of align, for hardware and system interfaces that need it: cache lines, SIMD registers, direct I/O. align must be a power of two no larger than 4 KiB, and allocations over 8 KiB start on an operating system page regardless. The alignment does not survive ResizeSlice unless the new size also gets it.

func MakeSliceAlignedUninit added in v0.5.0

func MakeSliceAlignedUninit[T any](a Allocator, n, align int) (Slice[T], error)

MakeSliceAlignedUninit is MakeSliceAligned without zeroing, for a buffer about to be overwritten. A T holding handles is zeroed anyway; see NewUninit.

func MakeSliceUninit added in v0.4.0

func MakeSliceUninit[T any](a Allocator, n int) (Slice[T], error)

MakeSliceUninit is MakeSlice without zeroing: the elements hold whatever the memory held, and a parser or decoder that overwrites them skips paying for the clear. n == 0 returns the empty Slice. A T holding handles is zeroed anyway; see NewUninit.

func ResizeSlice

func ResizeSlice[T any](a Allocator, s Slice[T], n int) (Slice[T], error)

ResizeSlice changes the length of s to n, keeping the common prefix and zeroing any new elements. On error s is left intact, unless only returning the old memory to the operating system failed: then the resized Slice comes back along with the error, and s is freed. n == 0 frees s. s must come from the same allocator and be live, or ResizeSlice panics.

func SliceFrom added in v0.5.0

func SliceFrom[T any](a Allocator, values []T) (Slice[T], error)

SliceFrom allocates a Slice holding a copy of values. Empty values return the empty Slice.

func (Slice[T]) Elems

func (s Slice[T]) Elems() []T

Elems returns the elements as a Go slice, valid until s is resized or freed. Its capacity equals its length, so append copies to the Go heap. It panics if s is already freed.

func (Slice[T]) Len

func (s Slice[T]) Len() int

Len returns the number of elements.

func (Slice[T]) Ref

func (s Slice[T]) Ref(i int) Ref[T]

Ref returns a non-owning reference to element i, valid until s is resized or freed. It panics if i is out of range or s is already freed.

func (Slice[T]) View added in v0.4.0

func (s Slice[T]) View(from, to int) View[T]

View returns a non-owning handle to elements [from, to), valid until s is resized or freed. It panics if the range is out of bounds or s is already freed.

type Stats

type Stats struct {
	// Live is the number of allocations not yet freed.
	Live int
	// Bytes is the usable size of those allocations, including rounding.
	Bytes int
}

Stats describes the allocations an allocator currently holds.

type String

type String struct {
	// contains filtered or unexported fields
}

String owns off-heap UTF-8 bytes. Unlike a Go string it may be stored off-heap. FreeString releases it. The zero String is empty. It is not comparable, because == could only compare addresses; compare with String(). Use hashmap.Strings to key a map by text.

func AppendString

func AppendString(a Allocator, s String, more string) (String, error)

AppendString appends more to s, returning the grown String. Errors follow ResizeSlice.

func NewString

func NewString(a Allocator, s string) (String, error)

NewString copies s off-heap.

func (String) Bytes

func (s String) Bytes() []byte

Bytes returns the bytes of s, valid until s is freed or appended to. It panics if s is already freed.

func (String) Len

func (s String) Len() int

Len returns the length of s in bytes.

func (String) String

func (s String) String() string

String returns s as a Go string without copying. The result reads freed memory once s is freed or appended to, so copy it with strings.Clone to keep it longer. It panics if s is already freed.

type View added in v0.4.0

type View[T any] struct {
	// contains filtered or unexported fields
}

View is a non-owning handle to consecutive off-heap Ts, such as part of a Slice. It cannot be freed on its own. The zero View is empty.

func (View[T]) Elems added in v0.4.0

func (v View[T]) Elems() []T

Elems returns the elements as a Go slice, valid as long as their owner is. Its capacity equals its length.

func (View[T]) Len added in v0.4.0

func (v View[T]) Len() int

Len returns the number of elements.

Directories

Path Synopsis
Package btree provides an ordered map whose entries live off the Go heap.
Package btree provides an ordered map whose entries live off the Go heap.
Package bufpool recycles off-heap byte buffers of power-of-two sizes, for I/O and decoding that would otherwise churn []byte through the Go heap.
Package bufpool recycles off-heap byte buffers of power-of-two sizes, for I/O and decoding that would otherwise churn []byte through the Go heap.
Package hashmap provides hash maps whose entries live off the Go heap.
Package hashmap provides hash maps whose entries live off the Go heap.
Package heapref lets off-heap memory refer to values on the Go heap.
Package heapref lets off-heap memory refer to values on the Go heap.
Package heapslab provides a free-list Pool and a bump Arena for one type on the Go heap, for types that hold Go pointers and so cannot live off-heap.
Package heapslab provides a free-list Pool and a bump Arena for one type on the Go heap, for types that hold Go pointers and so cannot live off-heap.
Package intern stores each distinct string once, off the Go heap, and names it with a 4-byte Symbol.
Package intern stores each distinct string once, off the Go heap, and names it with a 4-byte Symbol.
internal
chunks
Package chunks carves single values and short runs of a type from fixed-size off-heap chunks, the storage behind typedarena, pool and intern.
Package chunks carves single values and short runs of a type from fixed-size off-heap chunks, the storage behind typedarena, pool and intern.
seq
Package seq adapts iterators of pairs to iterators of one side.
Package seq adapts iterators of pairs to iterators of one side.
slot
Package slot holds the values of a free-list allocator and marks them live or free, so that checked builds catch a value put back twice, put into another pool, or used after it was put back.
Package slot holds the values of a free-list allocator and marks them live or free, so that checked builds catch a value put back twice, put into another pool, or used after it was put back.
swiss
Package swiss is the open-addressed table behind the module's hash maps: groups of eight slots, each with one control byte holding seven bits of the hash, probed a group at a time with word-at-a-time comparisons.
Package swiss is the open-addressed table behind the module's hash maps: groups of eight slots, each with one control byte holding seven bits of the hash, probed a group at a time with word-at-a-time comparisons.
testkit
Package testkit provides the fuzz and benchmark helpers shared by this module's tests.
Package testkit provides the fuzz and benchmark helpers shared by this module's tests.
Package linkedlist provides a doubly linked list whose nodes live off the Go heap in one contiguous pool and link to each other by 32-bit index, so links cost eight bytes per node.
Package linkedlist provides a doubly linked list whose nodes live off the Go heap in one contiguous pool and link to each other by 32-bit index, so links cost eight bytes per node.
Package memtest provides allocators for tests that fail the test on a leak.
Package memtest provides allocators for tests that fail the test on a leak.
Package minheap provides a binary heap whose elements live off the Go heap.
Package minheap provides a binary heap whose elements live off the Go heap.
Package pool provides a free-list allocator for a single type whose values live off the Go heap and are recycled individually.
Package pool provides a free-list allocator for a single type whose values live off the Go heap and are recycled individually.
Package ring provides a bounded lock-free queue from one goroutine to another, whose elements live off the Go heap.
Package ring provides a bounded lock-free queue from one goroutine to another, whose elements live off the Go heap.
Package typedarena provides a chunked bump allocator for a single type whose values live off the Go heap and are freed all at once.
Package typedarena provides a chunked bump allocator for a single type whose values live off the Go heap and are freed all at once.
Package union stores values of several concrete types in one off-heap handle, the way an interface does on the Go heap.
Package union stores values of several concrete types in one off-heap handle, the way an interface does on the Go heap.
Package vector provides a growable slice whose elements live off the Go heap.
Package vector provides a growable slice whose elements live off the Go heap.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL