Files
bLEH/allocator.go

90 lines
2.1 KiB
Go

// Copyright (C) 2026 ciciplusplus
// SPDX-License-Identifier: GPL-2.0-only
package main
import (
"fmt"
"unsafe"
)
// TODO: Deal with fragmentation
// TODO: Write tests
// TODO: There is additonal bookkeeping (e.g. node lists) which are allocated off storage.
// Maybe it need to be fixed, dunno
// TODO: Add safe checks (e.g. check on free that slice didn't grow)
type Allocator struct {
storage []byte
head *node
allocated map[unsafe.Pointer]*node
}
type node struct {
next *node
data []byte
}
func NewAllocator(size int) *Allocator {
storage := make([]byte, size)
head := node{next: nil, data: storage}
return &Allocator{storage: storage, head: &head, allocated: make(map[unsafe.Pointer]*node)}
}
func (a *Allocator) GetStartAddress() unsafe.Pointer {
return unsafe.Pointer(&a.storage[0])
}
func (a *Allocator) GetSize() int {
return len(a.storage)
}
func (a *Allocator) Malloc(size int) ([]byte, error) {
var prev *node
curr := a.head
for curr != nil {
currSize := len(curr.data)
if currSize >= size {
if currSize == size {
if prev != nil {
prev.next = curr.next
} else {
if curr != a.head {
panic(fmt.Sprintf("Unexpected node %p, expected head %p", curr, a.head))
}
a.head = a.head.next
}
curr.next = nil
a.allocated[unsafe.Pointer(&curr.data[0])] = curr
return curr.data, nil
}
oldData, newData := curr.data[:currSize-size], curr.data[currSize-size:]
curr.data = oldData
// TODO: is node allocated on stack or heap here?
newNode := node{next: nil, data: newData}
a.allocated[unsafe.Pointer(&newData[0])] = &newNode
return newData, nil
}
prev = curr
curr = curr.next
}
return nil, fmt.Errorf("ERROR: Cannot alloc bytes of size %d", size)
}
func (a *Allocator) Free(bytes []byte) {
for i := range bytes {
bytes[i] = 0
}
var freedNode *node
var ok bool
ptr := unsafe.Pointer(&bytes[0])
if freedNode, ok = a.allocated[ptr]; !ok {
panic(fmt.Sprintf("FATAL: Unknown bytes %v for Free()", bytes))
}
delete(a.allocated, ptr)
freedNode.next = a.head
a.head = freedNode
}