4/34
Part 1 of 7 · alloc and freeLearn and do

One slot per unit is correct, but its cost grows with the arena

The obvious version keeps one slot for every unit

The first idea copies the memory: a list with one slot per unit.

class SlotAllocator:
    def __init__(self, size):
        # None: free; else the start of the block that holds it
        self.slots = [None] * size
        # start -> size of each live block
        self.sizes = {}

    def alloc(self, n):
        # free slots in a row, ending here
        run = 0
        for addr, slot in enumerate(self.slots):
            run = run + 1 if slot is None else 0
            if run == n:
                start = addr - n + 1
                self.slots[start:addr + 1] = [start] * n
                self.sizes[start] = n
                return start
        return None

    def free(self, addr):
        if addr not in self.sizes:
            raise ValueError(f"no live block starts at {addr}")
        n = self.sizes.pop(addr)
        self.slots[addr:addr + n] = [None] * n
        return n


a = SlotAllocator(8)
print(a.alloc(3), a.alloc(2), a.alloc(4))
print(a.slots)
0 3 None
[0, 0, 0, 3, 3, None, None, None]

A slot holds None while its unit is free, and otherwise the start of the block that holds it. alloc counts free slots in a row until the count reaches n. free clears the block's slots. Here is the scan for the alloc(4) that failed:

The slots, and the run count for alloc(4)
01234567
holds
00033
count
00000123
Never 4: every slot is read, and alloc returns None.

A slot holds the start of the block that holds its unit, or None, drawn as a free unit.

It's correct, and for an arena of 10 units it's a fine answer. The cost is the problem.

slot_alloc(slots, n) is the alloc of SlotAllocator above, pulled out as a function, with one bug in it: on an empty arena it returns -1. Find the line and fix it.