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 ¶
- Constants
- Variables
- func Free[T any](a Allocator, p Ptr[T]) error
- func FreeSlice[T any](a Allocator, s Slice[T]) error
- func FreeString(a Allocator, s String) error
- func Populate[T any](s Slice[T]) error
- func SyncMemoryLimit(total int64, sources ...Footprinter) (int64, error)
- type Allocator
- type Arena
- type Footprint
- type Footprinter
- type Index
- type Local
- type Mark
- type Ptr
- type Ref
- type Region
- func (r *Region[T]) Cap() int
- func (r *Region[T]) Close() error
- func (r *Region[T]) Elems() []T
- func (r *Region[T]) Footprint() Footprint
- func (r *Region[T]) Grow(n int) (Index[T], error)
- func (r *Region[T]) IndexAt(i int) Index[T]
- func (r *Region[T]) Len() int
- func (r *Region[T]) Populate() error
- func (r *Region[T]) Ptr(i Index[T]) *T
- func (r *Region[T]) Truncate(n int) error
- func (r *Region[T]) UseHugePages() error
- type Shared
- type Slice
- type Stats
- type String
- type View
Examples ¶
Constants ¶
const Checked = true
Checked reports whether the misuse guards are compiled in, which they are unless the build sets the memory_unchecked tag.
Variables ¶
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") // ErrArenaParent reports an Arena whose parent cannot lend it spans. ErrArenaParent = errors.New("arena parent must be a Local or a Shared") // ErrAlignment reports an alignment that is not a power of two up to 4 KiB. ErrAlignment = errors.New("invalid alignment") )
var ErrOverLimit = errors.New("off-heap memory exceeds the limit")
ErrOverLimit reports off-heap memory that alone exceeds a memory limit.
var ErrRegionFull = errors.New("region is full")
ErrRegionFull reports growth past the length a Region reserved.
Functions ¶
func Free ¶
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 ¶
FreeSlice releases s. Freeing the empty Slice does nothing. Freeing s twice, or through another allocator, panics.
func Populate ¶ added in v0.4.0
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.
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, and spans it holds count in its own Footprint, not the parent's. 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, err := memory.NewArena(&parent)
if err != nil {
panic(err)
}
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
NewArena returns an empty Arena drawing from a, which must be a Local or a Shared.
func (*Arena) Footprint ¶ added in v0.4.0
Footprint reports the spans a holds from its parent and the large allocations it holds through it.
func (*Arena) Free ¶ added in v0.4.0
Free frees everything allocated from a and returns its spans to the parent. a remains usable.
func (*Arena) Release ¶ added in v0.4.0
Release frees everything allocated since m was taken, keeping the memory for reuse. It panics on the zero Mark and on a Mark it can tell has been released past.
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
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.
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 ¶
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
Footprint reports the memory l holds from the operating system.
func (*Local) SetProfile ¶ added in v0.4.0
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) 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 NewUninit ¶ added in v0.4.0
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.
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.
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 << 30)
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
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]) Close ¶ added in v0.4.0
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
Footprint reports the memory r holds from the operating system.
func (*Region[T]) Grow ¶ added in v0.4.0
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
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]) Populate ¶ added in v0.4.0
Populate makes the current elements of r resident now, like the function Populate.
func (*Region[T]) Ptr ¶ added in v0.4.0
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
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
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 ¶
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
Footprint reports the memory s holds from the operating system.
func (*Shared) SetProfile ¶ added in v0.4.0
SetProfile behaves like Local.SetProfile.
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 MakeSliceAligned ¶ added in v0.4.0
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 MakeSliceUninit ¶ added in v0.4.0
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.
func ResizeSlice ¶
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 (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.
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 ¶
AppendString appends more to s, returning the grown String. Errors follow ResizeSlice.
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.
Source Files
¶
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. |
|
memtest
Package memtest provides test helpers shared by the memory-go packages.
|
Package memtest provides test helpers shared by the memory-go packages. |
|
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. |
|
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 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. |