Documentation
¶
Overview ¶
Package alloc provides page-aligned, reference-counted Memory. An Allocator lends Memory of up to 128 KiB from a fixed arena. NewMemory maps standalone storage. Buffer combines adjacent allocations for larger byte streams.
Index ¶
- Constants
- Variables
- type Allocator
- func (a *Allocator) Acquire(ctx context.Context, size int64) (Memory, error)
- func (a *Allocator) Available() int64
- func (a *Allocator) Capacity() int64
- func (a *Allocator) Close()
- func (a *Allocator) MaxSize() int64
- func (a *Allocator) Region() []byte
- func (a *Allocator) Stats() Stats
- func (a *Allocator) TryAcquire(size int64) (Memory, error)
- type Buffer
- func (b *Buffer) Cap() int
- func (b *Buffer) Freeze() *ReadOnlyBuffer
- func (b *Buffer) Grow(n int) error
- func (b *Buffer) Len() int
- func (b *Buffer) RawAllocations() []Memory
- func (b *Buffer) Read(p []byte) (int, error)
- func (b *Buffer) ReadFrom(r io.Reader) (int64, error)
- func (b *Buffer) Release()
- func (b *Buffer) Reset()
- func (b *Buffer) TakeAllocations() []Memory
- func (b *Buffer) Trim()
- func (b *Buffer) TrimPrefix(n int)
- func (b *Buffer) Write(p []byte) (int, error)
- func (b *Buffer) WriteTo(w io.Writer) (int64, error)
- type BufferView
- type Memory
- type Option
- type ReadOnlyBuffer
- type Stats
Constants ¶
const MaxAllocationSize = spanBytes
MaxAllocationSize is the largest block returned by TryAcquire or Acquire. Buffer can merge adjacent claims into larger contiguous Memory handles.
Variables ¶
var ErrExhausted = errors.New("alloc: allocator exhausted")
ErrExhausted means there are no free pages available for an allocation.
Functions ¶
This section is empty.
Types ¶
type Allocator ¶ added in v2.5.0
type Allocator struct {
// contains filtered or unexported fields
}
Allocator lends page-aligned Memory of up to MaxAllocationSize bytes from one fixed arena, zeroed unless built WithoutZeroing. TryAcquire and release are safe for concurrent use; Acquire retries on exhaustion.
The arena is divided into 128 KiB spans. Each span stores two 64 KiB buddy trees in one atomic word. Requests round up to a power of two, with a 4 KiB minimum, to set an upper limit. The first nonfull span supplies its largest eligible contiguous block within that limit. Above 64 KiB, this is the free run crossing the half boundary; smaller blocks use buddy sizes and alignment. A claim marks the allocation's buddy subtrees and ancestors with one CAS; release coalesces free buddies in the same word.
Allocation uses persistent atomic cursors spread across GOMAXPROCS preferred shards. Cursors retain positions both inside and outside their home shard; a failed search can inspect every span. These are hints, not ownership. Buffer growth batches raw claims and leases each contiguous run, which may exceed MaxAllocationSize. An existing unshared tail can be extended.
func NewAllocator ¶ added in v2.9.0
NewAllocator maps one fixed arena of size bytes rounded up to whole 128 KiB spans. Mapping failures panic. The arena stays mapped until Close.
func (*Allocator) Acquire ¶ added in v2.5.0
Acquire returns one block under the same size limit as TryAcquire; it may be smaller than size. It tries immediately, then retries every 100 ms (or WithRetryInterval) while no pages are free. Context cancellation interrupts the wait. Free capacity is acquired even if ctx is already cancelled.
func (*Allocator) Available ¶ added in v2.9.0
Available reports a snapshot of free bytes. Memory stays in use until its last Unpin. It reads an atomic page counter and must not race Close.
func (*Allocator) Capacity ¶ added in v2.9.0
Capacity reports the arena's size in bytes, or zero after Close. It must not race Close.
func (*Allocator) Close ¶ added in v2.5.0
func (a *Allocator) Close()
Close unmaps the arena. It must not race other use; the caller must release borrowed memory first. Repeated closes are harmless. Do not acquire after Close.
func (*Allocator) MaxSize ¶ added in v2.9.0
MaxSize reports the largest TryAcquire or Acquire result: 128 KiB.
func (*Allocator) Region ¶ added in v2.10.0
Region returns the whole backing mapping for ring-lifetime registration. Memory leases continue to govern access to individual allocations. Keep the allocator open until every ring using this mapping has closed successfully.
func (*Allocator) Stats ¶ added in v2.9.0
Stats sums allocation totals across spans, retained after Close. The counters are read independently, so concurrent acquisitions can appear in one total before the other. Capacity and Available report current usage separately. Collection is disabled by default, returning zero totals. Build with the allocstats tag to enable collection for diagnostics.
func (*Allocator) TryAcquire ¶ added in v2.5.0
TryAcquire returns one contiguous block, zeroed unless built WithoutZeroing. Size is capped at MaxSize and rounded up to a power of two (at least 4 KiB) as an upper limit; the returned block may be smaller. Use len(m.Bytes()) as the acquired size. It returns ErrExhausted when no pages are free. Size must be positive. Buffer combines blocks to satisfy the full request.
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
Buffer is a byte stream backed by allocator memory, in the spirit of bytes.Buffer. Writes acquire Memory as needed without waiting; existing bytes never move. Once every byte has been read, the buffer reuses its memory from the start. Buffer is not safe for concurrent use.
Buffer owns one reference to each acquired Memory until Release. References held elsewhere protect lifetime, not contents: finish reading shared bytes before the buffer drains, resets, and writes over them. Growth requires exclusive ownership of the allocations it merges; do not grow the buffer while its last allocation is pinned elsewhere.
func NewAllocatingBuffer ¶ added in v2.9.0
NewAllocatingBuffer returns a buffer that joins raw allocator claims before creating Memory leases. Grow and Write acquire their full requested capacity.
func (*Buffer) Freeze ¶ added in v2.10.0
func (b *Buffer) Freeze() *ReadOnlyBuffer
Freeze transfers ownership of b's allocations. Do not write, grow, trim or release b afterward. Outstanding I/O may initialize the allocations while holding a reference; wait for it before reading views. After initialization, contents and allocation boundaries stay fixed.
func (*Buffer) Grow ¶ added in v2.9.0
Grow ensures space for n more bytes without waiting for allocator capacity. Memory acquired before an error is retained.
func (*Buffer) RawAllocations ¶ added in v2.9.0
RawAllocations returns the slice of underlying allocations in this buffer. The caller assumes responsibility for managing the safety of the returned allocations. The caller may grab a reference to the underlying Memory if it needs to store a copy. Growth may merge allocations and invalidate unpinned copies of their handles.
func (*Buffer) Read ¶ added in v2.9.0
Read returns io.EOF only when the buffer is empty and p is not.
func (*Buffer) ReadFrom ¶ added in v2.9.0
ReadFrom reads from r directly into allocator memory until EOF or an error. Bytes read before a source or allocation error remain in the buffer.
func (*Buffer) Release ¶ added in v2.9.0
func (b *Buffer) Release()
Release discards all contents and releases the buffer's reference to each allocation. The buffer remains usable and acquires memory again on write.
func (*Buffer) Reset ¶ added in v2.9.0
func (b *Buffer) Reset()
Reset discards all contents and retains allocations for reuse.
func (*Buffer) TakeAllocations ¶ added in v2.10.0
TakeAllocations transfers the allocation slice and its owned references to the caller, leaving b empty. It neither copies handles nor increments references. The caller must eventually Unpin each allocation. Existing borrowed views of this slice remain valid; unlike Release, taking it does not clear the handles.
func (*Buffer) Trim ¶ added in v2.10.0
func (b *Buffer) Trim()
Trim releases unused capacity after the written bytes, rounded up to a page, and clears the padding between the written end and that page boundary. Contents and read/write positions are preserved. Call before sharing the buffer or submitting I/O: shrinking a lease requires exclusive ownership and invalidates unpinned copies of that handle, just like growth.
func (*Buffer) TrimPrefix ¶ added in v2.10.0
appendRaw consumes a raw range, extending the last lease or publishing a new one. Only this boundary between raw storage and Buffer ownership needs leases. TrimPrefix removes and releases n bytes from the beginning before any reads. n must be page-aligned and no greater than the written length. Remaining bytes do not move. Call before sharing allocations; every removed or resized lease requires exclusive ownership and invalidates old copies of its handle.
type BufferView ¶ added in v2.10.0
type BufferView struct {
// contains filtered or unexported fields
}
BufferView is a read-only cursor. Copies have independent positions and borrow the same storage. Keep its ReadOnlyBuffer alive until all views are finished.
func (*BufferView) Len ¶ added in v2.10.0
func (v *BufferView) Len() int
func (*BufferView) Next ¶ added in v2.10.0
func (v *BufferView) Next() ([]byte, error)
Next consumes the next contiguous chunk without copying. A returned slice remains valid until the owning ReadOnlyBuffer is released, including across subsequent Next or Read calls. Exhaustion returns io.EOF and no bytes.
func (*BufferView) Size ¶ added in v2.10.0
func (v *BufferView) Size() int64
type Memory ¶ added in v2.9.0
type Memory struct {
// contains filtered or unexported fields
}
Memory is a handle to one lease of contiguous, page-aligned memory. It is a small value; copies name the same lease. Acquisition returns one reference, each successful TryInc adds one, and every reference is released with Unpin. The last Unpin returns the storage to its owner.
Each lease has a generation, stored with its reference count in a word owned by the allocator. Every operation compares the handle's generation with the word's, and the last Unpin advances the generation, so a handle kept past its lease fails TryInc and panics on Unpin even after the memory is lent again.
func NewMemory ¶ added in v2.9.0
NewMemory maps at least size zeroed bytes, rounded up to a page, without warming it. The returned Memory owns one reference and unmaps its storage on the last Unpin. Invalid sizes and mapping failures panic.
func (Memory) Bytes ¶ added in v2.9.0
Bytes returns the allocation, including any allocator rounding. Hold a reference while using it, including pending I/O. Do not reslice beyond it.
func (Memory) TryInc ¶ added in v2.9.0
TryInc acquires another reference unless this lease has ended or the reference count would overflow. Safe for concurrent use. This checks memory lifetime only; a cache must synchronize lookup-and-pin with eviction.
func (Memory) Unpin ¶ added in v2.9.0
Unpin releases one reference and reports whether it was the last reference. When true is returned, the storage has been returned to its owner: freed in its arena, where another acquisition may already have claimed it, or unmapped. Calling Unpin after the lease has ended is a programming error.
type Option ¶
type Option func(*allocatorConfig)
Option configures an allocator at construction time.
func WithRetryInterval ¶ added in v2.5.0
WithRetryInterval sets the delay between Acquire retries when exhausted. The default is 100 ms. Cancellation interrupts the wait.
func WithWarmup ¶ added in v2.5.0
func WithWarmup() Option
WithWarmup commits the arena's memory at construction. By default, pages are faulted in when first used.
func WithoutZeroing ¶ added in v2.9.0
func WithoutZeroing() Option
WithoutZeroing skips zeroing memory on acquisition, so it holds whatever its previous borrower left. Use it when every byte is written before it is read, such as a direct-I/O read buffer.
type ReadOnlyBuffer ¶ added in v2.10.0
type ReadOnlyBuffer struct {
// contains filtered or unexported fields
}
ReadOnlyBuffer owns a frozen buffer. Retain acquires one reference to the whole buffer; Release frees its allocations when the last owner leaves. Borrowed slices must not be modified and remain valid while a reference is held.
func (*ReadOnlyBuffer) Cap ¶ added in v2.10.0
func (b *ReadOnlyBuffer) Cap() int
func (*ReadOnlyBuffer) First ¶ added in v2.10.0
func (b *ReadOnlyBuffer) First() []byte
First returns a borrowed view of the first allocation, or nil for an empty buffer.
func (*ReadOnlyBuffer) Release ¶ added in v2.10.0
func (b *ReadOnlyBuffer) Release() (freed int64)
Release returns the number of allocation bytes actually freed.
func (*ReadOnlyBuffer) Retain ¶ added in v2.10.0
func (b *ReadOnlyBuffer) Retain() *ReadOnlyBuffer
Retain requires an existing reference and returns another independently owned reference.
func (*ReadOnlyBuffer) View ¶ added in v2.10.0
func (b *ReadOnlyBuffer) View(offset, length int) BufferView
View creates an independent cursor over a byte range within Cap(). It borrows b's reference. The caller must initialize the range before reading it; this permits views of buffers filled directly by I/O rather than Buffer.Write.
type Stats ¶ added in v2.9.0
Stats holds cumulative byte totals for successful acquisitions. RequestedBytes counts the original request before capping or rounding; AllocatedBytes counts the actual returned length. Attempts that acquire nothing contribute nothing. Buffer growth contributes its individual TryAcquire requests. A partial allocation can cause the remaining bytes to be requested again.