memory

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 9 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 from modernc.org/memory, a pure Go allocator that maps pages from the OS (mmap, VirtualAlloc) directly. 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.

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 go through modernc's size classes and are slower than Go's new. The typed pool and typedarena skip that: once a chunk has room, getting a value is a free-list pop or a bump of an index, and they beat new even with the misuse guards on. Per allocation (just bench, linux/amd64, 8 threads, this machine is noisy so read these as rough):

Operation Checked memory_unchecked Go new
pool Get + Put 4–5 ns 4 ns 10 ns
typedarena Alloc, Reset every 1024 4.2 ns 3.5 ns 12.5 ns
New + Free 43 ns 21–26 ns 10 ns
hashmap set + get 36–45 ns 36 ns 19–26 ns (map)

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

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
pool.Item[T] one T Pool.Get Pool.Put

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.

Panics instead of corruption

Every allocation carries a 16-byte header recording its allocator and whether it is live. These panic at the point of the mistake:

  • freeing twice, or resizing a handle that was already resized
  • 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 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

Not caught: a stale handle whose memory was freed and has since been handed out again, Refs, and Go pointers or slices obtained from a handle and kept after it was freed. After Close, touching old handles faults instead of panicking, since their pages are unmapped.

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 header, 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; a mutex serialises every call.

Both satisfy memory.Allocator, which every function and container takes. Stats reports live allocations and bytes, Trim returns retained empty pages to the OS, and Close releases everything at once.

Packages

Package What it is
memory Allocators and the Ptr, Ref, Slice and String handles
vector Growable slice: Push, Pop, At, Ptr, Set, RemoveAt, DeleteFunc, Truncate, Reserve, Clip, All
hashmap Linear probing with backward-shift deletion and stored hashes; capacity hint, Clip
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

Containers are not safe for concurrent use, even on a Shared allocator.

Recipes

Recipe What it does
just check Every release gate in order: vet, lint, test, test-unchecked, 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 race Tests under the race detector (needs cgo; the library itself never does)
just build Compile-check every package
just fuzz [time] Fuzz each container against its Go 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, cross-builds for arm64, 386, FreeBSD and Windows on arm64, golangci-lint, and a minute of fuzzing per 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 allocator.go, memory.go and string.go, the boundary between typed values and raw memory.

Documentation

Overview

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

Memory comes from modernc.org/memory, a pure Go allocator that maps pages from the operating system directly. 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 and String, point only into memory the garbage collector does not manage and may be stored off-heap.

Local serves a single goroutine; Shared serialises access for several.

Misuse panics instead of corrupting memory. Every allocation carries a 16-byte header naming its allocator 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 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.

Building with the memory_unchecked tag compiles these checks out: no header, 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")
)

Functions

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.

Types

type Allocator

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

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

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. Handles from before Close are rejected afterwards.

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.

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 (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 Shared

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

Shared is an Allocator safe for concurrent use: a mutex serialises every call. 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) 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.

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 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. n == 0 frees s. s must come from the same allocator and be live, or ResizeSlice panics.

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.

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.

func AppendString

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

AppendString appends more to s, returning the grown String. On error s is left intact.

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.

Directories

Path Synopsis
Package hashmap provides a hash map whose entries live off the Go heap.
Package hashmap provides a hash map whose entries live off the Go heap.
internal
chunks
Package chunks carves single values and short runs of a type from fixed-size off-heap chunks, the storage behind typedarena and pool.
Package chunks carves single values and short runs of a type from fixed-size off-heap chunks, the storage behind typedarena and pool.
memtest
Package memtest provides test helpers shared by the memory-go packages.
Package memtest provides test helpers shared by the memory-go packages.
Package linkedlist provides a doubly linked list whose nodes live off the Go heap in one contiguous pool and link to each other by index.
Package linkedlist provides a doubly linked list whose nodes live off the Go heap in one contiguous pool and link to each other by index.
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 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 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