memory

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 15 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.

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

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.

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.

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 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: 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. 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.

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, and the Ptr, Ref, Slice, View, Index and String handles
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
memtest Local and Shared 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.

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.

Local serves a single goroutine, Shared several without contending, and Arena frees whole groups of allocations at once. Region grows in place without moving.

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.

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 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 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 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 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 and *Arena 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 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 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. 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 (*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. 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]) 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]) 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.

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.

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]) 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.

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 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.
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 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