Skip to content

Instantly share code, notes, and snippets.

@DaseinPhaos
Last active January 25, 2025 16:59
Show Gist options
  • Save DaseinPhaos/d418161c1147fecad41939b27002d080 to your computer and use it in GitHub Desktop.
Save DaseinPhaos/d418161c1147fecad41939b27002d080 to your computer and use it in GitHub Desktop.
Port of [OffsetAllocator](https://github.com/sebbbi/OffsetAllocator) by (C) Sebastian Aaltonen 2023 in JAI
/*
Port of [OffsetAllocator](https://github.com/sebbbi/OffsetAllocator) by (C) Sebastian Aaltonen 2023
MIT License
Copyright (c) 2023 Sebastian Aaltonen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#module_parameters(USE_16_BIT_NODE_INDICES := false, DEBUG_VERBOSE := false);
OAllocation :: struct {
NO_SPACE:u32: 0xffffffff;
offset:= NO_SPACE;
metadata:NodeIndex= NO_SPACE.(NodeIndex, trunc); // internal: node index
}
OStorageReport :: struct {
totalFreeSpace: u32;
largestFreeRegion: u32;
}
OStorageReportFull :: struct {
Region :: struct {
size: u32;
count: u32;
}
freeRegions:[NUM_LEAF_BINS]Region;
}
OAllocator :: struct {
Node :: struct {
unused :NodeIndex: (0xffffffff).(NodeIndex, trunc);
dataOffset: u32;
dataSize: u32;
binListPrev:= unused;
binListNext:= unused;
neighborPrev:= unused;
neighborNext:= unused;
used:= false; // TODO: Merge as bit flag
}
m_size: u32;
m_freeStorage: u32;
m_usedBinsTop: u32;
m_usedBins: [NUM_TOP_BINS]u8;
m_binIndices: [NUM_LEAF_BINS]NodeIndex;
m_nodes: []Node;
m_freeNodes: *NodeIndex;
m_freeOffset: u32;
}
oalloc_init :: (using this: *OAllocator, size: u32, maxAllocs: u32 = 128 * 1024) {
m_size = size;
m_nodes = .{};
m_freeNodes = null;
oalloc_reset(this, maxAllocs);
}
oalloc_reset :: (using this: *OAllocator, maxAllocs: u32) {
#if (size_of(NodeIndex) == 2) {
assert(maxAllocs <= 65536);
}
m_freeStorage = 0;
m_usedBinsTop = 0;
m_freeOffset = maxAllocs - 1;
for * m_usedBins {
it.* = 0;
}
for * m_binIndices {
it.* = Node.unused;
}
// what??
if (m_nodes) then free(m_nodes.data);
if (m_freeNodes) then free(m_freeNodes);
m_nodes = NewArray(maxAllocs, Node);
freeNodes := NewArray(maxAllocs, NodeIndex);
m_freeNodes = freeNodes.data;
// Freelist is a stack. Nodes in inverse order so that [0] pops first.
for * freeNodes {
it.* = xx (maxAllocs - it_index - 1);
}
// Start state: Whole storage as one big node
// Algorithm will split remainders and push them back as smaller nodes
insertNodeIntoBin(this, m_size, 0);
}
oalloc_destroy :: (using this: *OAllocator) {
free(m_nodes.data);
free(m_freeNodes);
}
oalloc_allocate :: (using this: *OAllocator, size: u32) -> OAllocation {
// Out of allocations?
if (m_freeOffset == 0) {
return .{offset = OAllocation.NO_SPACE, metadata = OAllocation.NO_SPACE};
}
// Round up to bin index to ensure that alloc >= bin
// Gives us min bin index that fits the size
minBinIndex := OSmallFloat.uintToFloatRoundUp(size);
minTopBinIndex := minBinIndex >> TOP_BINS_INDEX_SHIFT;
minLeafBinIndex := minBinIndex & LEAF_BINS_INDEX_MASK;
topBinIndex := minTopBinIndex;
leafBinIndex := OAllocation.NO_SPACE;
// If top bin exists, scan its leaf bin. This can fail (NO_SPACE).
if (m_usedBinsTop & (1 << topBinIndex)) {
leafBinIndex = findLowestSetBitAfter(m_usedBins[topBinIndex], minLeafBinIndex);
}
// If we didn't find space in top bin, we search top bin from +1
if (leafBinIndex == OAllocation.NO_SPACE) {
topBinIndex = findLowestSetBitAfter(m_usedBinsTop, minTopBinIndex + 1);
// Out of space?
if (topBinIndex == OAllocation.NO_SPACE) {
return .{offset = OAllocation.NO_SPACE, metadata = OAllocation.NO_SPACE};
}
// All leaf bins here fit the alloc, since the top bin was rounded up. Start leaf search from bit 0.
// NOTE: This search can't fail since at least one leaf bit was set because the top bit was set.
leafBinIndex = tzcnt_nonzero(m_usedBins[topBinIndex]);
}
binIndex := (topBinIndex << TOP_BINS_INDEX_SHIFT) | leafBinIndex;
// Pop the top node of the bin. Bin top = node.next.
nodeIndex := m_binIndices[binIndex];
node := *m_nodes[nodeIndex];
nodeTotalSize := node.dataSize;
node.dataSize = size;
node.used = true;
m_binIndices[binIndex] = node.binListNext;
if (node.binListNext != Node.unused) {
m_nodes[node.binListNext].binListPrev = Node.unused;
}
m_freeStorage -= nodeTotalSize;
#if DEBUG_VERBOSE {
print("Free storage: % (-%) (allocate)\n", m_freeStorage, nodeTotalSize);
}
// Bin empty?
if (m_binIndices[binIndex] == Node.unused) {
// Remove a leaf bin mask bit
m_usedBins[topBinIndex] &= ~((1).(u8) << leafBinIndex);
// All leaf bins empty?
if (m_usedBins[topBinIndex] == 0) {
// Remove a top bin mask bit
m_usedBinsTop &= ~((1).(u32) << topBinIndex);
}
}
// Push back reminder N elements to a lower bin
reminderSize := nodeTotalSize - size;
if (reminderSize > 0) {
newNodeIndex := insertNodeIntoBin(this, reminderSize, node.dataOffset + size);
// Link nodes next to each other so that we can merge them later if both are free
// And update the old next neighbor to point to the new node (in middle)
if (node.neighborNext != Node.unused) {
m_nodes[node.neighborNext].neighborPrev = newNodeIndex;
}
m_nodes[newNodeIndex].neighborPrev = nodeIndex;
m_nodes[newNodeIndex].neighborNext = node.neighborNext;
node.neighborNext = newNodeIndex;
}
return .{offset = node.dataOffset, metadata = nodeIndex};
}
oalloc_free :: (using this: *OAllocator, allocation: OAllocation) {
assert(allocation.metadata != OAllocation.NO_SPACE);
if (!m_nodes) return;
nodeIndex := allocation.metadata;
node := *m_nodes[nodeIndex];
// Double delete check
assert(node.used == true);
// Merge with neighbors...
offset := node.dataOffset;
size := node.dataSize;
if ((node.neighborPrev != Node.unused) && (m_nodes[node.neighborPrev].used == false)) {
// Previous (contiguous) free node: Change offset to previous node offset. Sum sizes
prevNode := *m_nodes[node.neighborPrev];
offset = prevNode.dataOffset;
size += prevNode.dataSize;
// Remove node from the bin linked list and put it in the freelist
removeNodeFromBin(this, node.neighborPrev);
assert(prevNode.neighborNext == nodeIndex);
node.neighborPrev = prevNode.neighborPrev;
}
if ((node.neighborNext != Node.unused) && (m_nodes[node.neighborNext].used == false)) {
// Next (contiguous) free node: Offset remains the same. Sum sizes.
nextNode := *m_nodes[node.neighborNext];
size += nextNode.dataSize;
// Remove node from the bin linked list and put it in the freelist
removeNodeFromBin(this, node.neighborNext);
assert(nextNode.neighborPrev == nodeIndex);
node.neighborNext = nextNode.neighborNext;
}
neighborNext := node.neighborNext;
neighborPrev := node.neighborPrev;
// Insert the removed node to freelist
#if DEBUG_VERBOSE {
print("Putting node % into freelist[%] (free)\n", nodeIndex, m_freeOffset + 1);
}
m_freeOffset += 1;
m_freeNodes[m_freeOffset] = nodeIndex;
// Insert the (combined) free node to bin
combinedNodeIndex := insertNodeIntoBin(this, size, offset);
// Connect neighbors with the new combined node
if (neighborNext != Node.unused) {
m_nodes[combinedNodeIndex].neighborNext = neighborNext;
m_nodes[neighborNext].neighborPrev = combinedNodeIndex;
}
if (neighborPrev != Node.unused) {
m_nodes[combinedNodeIndex].neighborPrev = neighborPrev;
m_nodes[neighborPrev].neighborNext = combinedNodeIndex;
}
}
oalloc_size :: (using this: OAllocator, allocation: OAllocation) -> u32 {
if (allocation.metadata == OAllocation.NO_SPACE) return 0;
if (!m_nodes) return 0;
return m_nodes[allocation.metadata].dataSize;
}
oalloc_report :: (using this: OAllocator) -> OStorageReport {
largestFreeRegion :u32= 0;
freeStorage :u32= 0;
// Out of allocations? -> Zero free space
if (m_freeOffset > 0) {
freeStorage = m_freeStorage;
if (m_usedBinsTop) {
topBinIndex := (31).(u32) - lzcnt_nonzero(m_usedBinsTop);
leafBinIndex := (31).(u32) - lzcnt_nonzero(m_usedBins[topBinIndex]);
largestFreeRegion = OSmallFloat.floatToUint((topBinIndex << TOP_BINS_INDEX_SHIFT) | leafBinIndex);
assert(freeStorage >= largestFreeRegion);
}
}
return .{totalFreeSpace = freeStorage, largestFreeRegion = largestFreeRegion};
}
oalloc_report_full :: (using this: OAllocator) -> OStorageReportFull {
report: OStorageReportFull;
for m_binIndices {
nodeIndex := it;
count :u32= 0;
while nodeIndex != Node.unused {
nodeIndex = m_nodes[nodeIndex].binListNext;
count+=1;
}
report.freeRegions[it_index] = .{size = OSmallFloat.floatToUint(i), count = count };
}
return report;
}
OSmallFloat :: struct {
MANTISSA_BITS :u32: 3;
MANTISSA_VALUE :u32: 1 << MANTISSA_BITS;
MANTISSA_MASK :u32: MANTISSA_VALUE - 1;
// Bin sizes follow floating point (exponent + mantissa) distribution (piecewise linear log approx)
// This ensures that for each size class, the average overhead percentage stays the same
uintToFloatRoundUp :: (size: u32) -> u32 {
exp :u32= 0;
mantissa :u32= 0;
if (size < MANTISSA_VALUE) {
// Denorm: 0..(MANTISSA_VALUE-1)
mantissa = size;
} else {
// Normalized: Hidden high bit always 1. Not stored. Just like float.
leadingZeros := lzcnt_nonzero(size);
highestSetBit := 31 - leadingZeros;
mantissaStartBit := highestSetBit - MANTISSA_BITS;
exp = mantissaStartBit + 1;
mantissa = (size >> mantissaStartBit) & MANTISSA_MASK;
lowBitsMask := ((1).(u32) << mantissaStartBit) - 1;
// Round up!
if ((size & lowBitsMask) != 0) then mantissa+=1;
}
return (exp << MANTISSA_BITS) + mantissa; // + allows mantissa->exp overflow for round up
}
uintToFloatRoundDown :: (size: u32) -> u32 {
exp :u32= 0;
mantissa :u32= 0;
if (size < MANTISSA_VALUE) {
// Denorm: 0..(MANTISSA_VALUE-1)
mantissa = size;
} else {
// Normalized: Hidden high bit always 1. Not stored. Just like float.
leadingZeros := lzcnt_nonzero(size);
highestSetBit := 31 - leadingZeros;
mantissaStartBit := highestSetBit - MANTISSA_BITS;
exp = mantissaStartBit + 1;
mantissa = (size >> mantissaStartBit) & MANTISSA_MASK;
}
return (exp << MANTISSA_BITS) | mantissa;
}
floatToUint :: (floatValue: u32) -> u32 {
exponent := floatValue >> MANTISSA_BITS;
mantissa := floatValue & MANTISSA_MASK;
if (exponent == 0) {
// Denorms
return mantissa;
} else {
return (mantissa | MANTISSA_VALUE) << (exponent - 1);
}
}
}
#scope_file
#import "Basic";
// 16 bit offsets mode will halve the metadata storage cost
// But it only supports up to 65536 maximum allocation count
#if USE_16_BIT_NODE_INDICES {
NodeIndex :: u16;
} else {
NodeIndex :: u32;
}
NUM_TOP_BINS :u32: 32;
BINS_PER_LEAF :u32: 8;
TOP_BINS_INDEX_SHIFT :u32: 3;
LEAF_BINS_INDEX_MASK :u32: 0x7;
NUM_LEAF_BINS :u32: NUM_TOP_BINS * BINS_PER_LEAF;
pop_u32 :: (_x: u32, $use_asm := true) -> u32 #expand {
#if use_asm && CPU == .X64 {
result: u32;
#asm {popcnt.d result, _x;}
return result;
} else {
x := _x;
x = x - ((x >> 1) & 0x5555_5555);
x = (x & 0x3333_3333) + ((x >> 2) & 0x3333_3333);
x = (x + (x >> 4)) & 0x0f0f_0f0f;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x3f;
}
}
// Utility functions
lzcnt_nonzero :: inline (v: u32) -> u32 {
x := v;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return pop_u32(~x);
}
tzcnt_nonzero :: inline (v: u32) -> u32 {
// densist lookup, John Reiser
s_ntz_table :: u8.[
32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4,
7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18
];
xi := cast(s32)v;
xi = (xi & (-xi)); // Isolate rightmost 1-bit.
xi %= 37;
return s_ntz_table[xi];
}
findLowestSetBitAfter :: (bitMask: u32, startBitIndex: u32) -> u32 {
maskBeforeStartIndex := ((1).(u32) << startBitIndex) - 1;
maskAfterStartIndex := ~maskBeforeStartIndex;
bitsAfter := bitMask & maskAfterStartIndex;
if (bitsAfter == 0) return OAllocation.NO_SPACE;
return tzcnt_nonzero(bitsAfter);
}
insertNodeIntoBin :: (using this: *OAllocator, size: u32, dataOffset: u32) -> u32 {
// Round down to bin index to ensure that bin >= alloc
binIndex := OSmallFloat.uintToFloatRoundDown(size);
topBinIndex := binIndex >> TOP_BINS_INDEX_SHIFT;
leafBinIndex := binIndex & LEAF_BINS_INDEX_MASK;
// Bin was empty before?
if (m_binIndices[binIndex] == Node.unused) {
// Set bin mask bits
m_usedBins[topBinIndex] |= (1).(u8) << leafBinIndex;
m_usedBinsTop |= (1).(u32) << topBinIndex;
}
// Take a freelist node and insert on top of the bin linked list (next = old top)
topNodeIndex := m_binIndices[binIndex];
nodeIndex := m_freeNodes[m_freeOffset];
m_freeOffset -= 1;
#if DEBUG_VERBOSE {
print("Getting node % from freelist[%]\n", nodeIndex, m_freeOffset + 1);
}
m_nodes[nodeIndex] = .{dataOffset = dataOffset, dataSize = size, binListNext = topNodeIndex};
if (topNodeIndex != Node.unused) {
m_nodes[topNodeIndex].binListPrev = nodeIndex;
}
m_binIndices[binIndex] = nodeIndex;
m_freeStorage += size;
#if DEBUG_VERBOSE {
printf("Free storage: % (+%) (insertNodeIntoBin)\n", m_freeStorage, size);
}
return nodeIndex;
}
removeNodeFromBin :: (using this: *OAllocator, nodeIndex: u32) {
node := *m_nodes[nodeIndex];
if (node.binListPrev != Node.unused) {
// Easy case: We have previous node. Just remove this node from the middle of the list.
m_nodes[node.binListPrev].binListNext = node.binListNext;
if (node.binListNext != Node.unused) {
m_nodes[node.binListNext].binListPrev = node.binListPrev;
}
} else {
// Hard case: We are the first node in a bin. Find the bin.
// Round down to bin index to ensure that bin >= alloc
binIndex := OSmallFloat.uintToFloatRoundDown(node.dataSize);
topBinIndex := binIndex >> TOP_BINS_INDEX_SHIFT;
leafBinIndex := binIndex & LEAF_BINS_INDEX_MASK;
m_binIndices[binIndex] = node.binListNext;
if (node.binListNext != Node.unused) {
m_nodes[node.binListNext].binListPrev = Node.unused;
}
// Bin empty?
if (m_binIndices[binIndex] == Node.unused) {
// Remove a leaf bin mask bit
m_usedBins[topBinIndex] &= ~((1).(u8) << leafBinIndex);
// All leaf bins empty?
if (m_usedBins[topBinIndex] == 0) {
// Remove a top bin mask bit
m_usedBinsTop &= ~((1).(u32) << topBinIndex);
}
}
}
// Insert the node to freelist
#if DEBUG_VERBOSE {
print("Putting node % into freelist[%] (removeNodeFromBin)\n", nodeIndex, m_freeOffset + 1);
}
m_freeOffset += 1;
m_freeNodes[m_freeOffset] = nodeIndex;
m_freeStorage -= node.dataSize;
#if DEBUG_VERBOSE {
printf("Free storage: % (-%) (removeNodeFromBin)\n", m_freeStorage, node.dataSize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment