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 ¶
- Constants
- Variables
- func CheckType[T any]() error
- 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 FreezeSlice[T any](a Allocator, s Slice[T]) error
- func Populate[T any](s Slice[T]) error
- func SyncMemoryLimit(total int64, sources ...Footprinter) (int64, error)
- func ThawSlice[T any](a Allocator, s Slice[T]) error
- func Unpin[T any](ps *Pins, p *Pinned[T])
- func WithArena(parent ArenaParent, f func(*Arena) error) (err error)
- type Allocator
- type Arena
- type ArenaParent
- type Faulty
- type Footprint
- type Footprinter
- type Guarded
- type Index
- type Local
- type Mark
- type Ownable
- type Owned
- type Pinned
- type Pins
- 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]) File() *os.File
- func (r *Region[T]) Footprint() Footprint
- func (r *Region[T]) Freeze() error
- func (r *Region[T]) Frozen() bool
- 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]) Sync() error
- func (r *Region[T]) Thaw() error
- func (r *Region[T]) Truncate(n int) error
- func (r *Region[T]) UseHugePages() error
- type Shared
- type Slice
- func MakeSlice[T any](a Allocator, n int) (Slice[T], error)
- func MakeSliceAligned[T any](a Allocator, n, align int) (Slice[T], error)
- func MakeSliceAlignedUninit[T any](a Allocator, n, align int) (Slice[T], error)
- func MakeSliceUninit[T any](a Allocator, n int) (Slice[T], error)
- func ResizeSlice[T any](a Allocator, s Slice[T], n int) (Slice[T], error)
- func SliceFrom[T any](a Allocator, values []T) (Slice[T], error)
- 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") // ErrAlignment reports an alignment that is not a power of two up to 4 KiB. ErrAlignment = errors.New("invalid alignment") )
var ( // ErrFrozen reports a change to memory that Freeze or FreezeSlice made // read-only. ErrFrozen = errors.New("memory is frozen") // share its pages with other allocations. ErrSharesPages = errors.New("allocation shares its pages") )
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") )
var ErrInjected = errors.New("injected failure")
ErrInjected is the failure a Faulty allocator reports.
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 CheckType ¶ added in v0.6.0
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 ¶
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 FreezeSlice ¶ added in v0.6.0
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
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
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
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.
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
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
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
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
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.
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
NewFaulty returns a Faulty over a that does not fail until told to.
func (*Faulty) FailAllocsAfter ¶ added in v0.5.0
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
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.
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
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
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
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.
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 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
Own takes over h, which must come from a and be live, and returns its owner. Nothing else may free h afterwards.
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
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.
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.
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. 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.
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. 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
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
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
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
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]) Close ¶ added in v0.4.0
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
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
Footprint reports the memory r holds from the operating system.
func (*Region[T]) Freeze ¶ added in v0.6.0
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]) Grow ¶ added in v0.4.0
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
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. A frozen r returns ErrFrozen.
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]) Sync ¶ added in v0.6.0
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
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
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
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 MakeSliceAlignedUninit ¶ added in v0.5.0
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
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 ¶
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
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.
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 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. |