Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrOutOfMemory indicates no suitable block is available. ErrOutOfMemory = errors.New("buddy: out of memory") // ErrInvalidSize indicates the requested size is invalid. ErrInvalidSize = errors.New("buddy: invalid size (zero or too large)") // ErrDoubleFree indicates an attempt to free an unallocated block. ErrDoubleFree = errors.New("buddy: double free or invalid block") // ErrInvalidConfig indicates invalid allocator configuration. ErrInvalidConfig = errors.New("buddy: invalid configuration") )
Functions ¶
This section is empty.
Types ¶
type BuddyAllocator ¶
type BuddyAllocator struct {
// contains filtered or unexported fields
}
BuddyAllocator implements the buddy memory allocation algorithm.
The allocator manages a contiguous region of memory by dividing it into power-of-2 sized blocks. When allocating, blocks are split recursively until the smallest fitting size is found. When freeing, adjacent "buddy" blocks are merged back together.
Time complexity: O(log n) for both allocation and deallocation. Space overhead: O(n) bits for tracking block states.
func NewBuddyAllocator ¶
func NewBuddyAllocator(totalSize, minBlockSize uint64) (*BuddyAllocator, error)
NewBuddyAllocator creates a new buddy allocator.
Parameters:
- totalSize: Total memory to manage (must be power of 2)
- minBlockSize: Smallest allocatable unit (must be power of 2, <= totalSize)
Returns error if parameters are invalid.
func (*BuddyAllocator) Alloc ¶
func (b *BuddyAllocator) Alloc(size uint64) (BuddyBlock, error)
Alloc allocates a block of at least the requested size.
The returned block size will be rounded up to the next power of 2, and at least minBlockSize. Returns ErrOutOfMemory if no suitable block is available, ErrInvalidSize if size is 0 or exceeds totalSize.
func (*BuddyAllocator) Free ¶
func (b *BuddyAllocator) Free(block BuddyBlock) error
Free releases a previously allocated block.
Returns ErrDoubleFree if the block was not allocated or already freed.
func (*BuddyAllocator) Reset ¶
func (b *BuddyAllocator) Reset()
Reset releases all allocations and resets the allocator to initial state.
func (*BuddyAllocator) Stats ¶
func (b *BuddyAllocator) Stats() BuddyStats
Stats returns current allocator statistics.
type BuddyBlock ¶
type BuddyBlock struct {
Offset uint64 // Offset within the managed region
Size uint64 // Actual size (power of 2, >= requested)
// contains filtered or unexported fields
}
BuddyBlock represents an allocated memory block.
type BuddyStats ¶
type BuddyStats struct {
TotalSize uint64 // Total managed memory
AllocatedSize uint64 // Currently allocated
AllocationCount uint64 // Number of active allocations
PeakAllocated uint64 // Peak allocated size
TotalAllocated uint64 // Cumulative allocated (for throughput)
TotalFreed uint64 // Cumulative freed
SplitCount uint64 // Number of block splits
MergeCount uint64 // Number of block merges
}
BuddyStats contains allocator statistics.