Skip to content

Commit

Permalink
Ring buffer for allocator
Browse files Browse the repository at this point in the history
  • Loading branch information
outofforest committed Dec 13, 2024
1 parent fbf0eab commit 23e6aad
Show file tree
Hide file tree
Showing 3 changed files with 329 additions and 168 deletions.
168 changes: 0 additions & 168 deletions alloc/benchmark_test.go

This file was deleted.

51 changes: 51 additions & 0 deletions alloc/ring.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package alloc

import (
"github.com/pkg/errors"
)

func newRing[T any](capacity uint64) (*ring[T], []T) {
addresses := make([]T, capacity)
return &ring[T]{
addresses: addresses,
capacity: capacity,
commitPtr: capacity,
}, addresses
}

type ring[T any] struct {
addresses []T

capacity uint64
allocPtr, commitPtr, deallocPtr uint64
}

func (r *ring[T]) Allocate() (T, error) {
if r.allocPtr == r.commitPtr {
var t T
return t, errors.New("no free address to allocate")
}
if r.allocPtr == r.capacity {
r.allocPtr = 0
}
a := r.addresses[r.allocPtr]
r.allocPtr++
return a, nil
}

func (r *ring[T]) Deallocate(item T) {
if r.deallocPtr == r.capacity {
r.deallocPtr = 0
}
if r.deallocPtr == r.allocPtr {
// This is really critical because it means that we deallocated more than allocated.
panic("no space left in the ring for deallocation")
}

r.addresses[r.deallocPtr] = item
r.deallocPtr++
}

func (r *ring[T]) Commit() {
r.commitPtr = r.deallocPtr - 1
}
Loading

0 comments on commit 23e6aad

Please sign in to comment.