Exercise 3: Three Differently-Sized Records, and Why a Fixed Offset Table Can't Work — Possible Solution ==================================================================== THE TEST ------------------------------ p3 = Page() small_records = [b'a', b'bb', b'ccc'] # 1, 2, and 3 bytes respectively slots = [p3.add_record(r) for r in small_records] RESULT ------------------------------ slots = [0, 1, 2] p3.get_record(0) == b'a' p3.get_record(1) == b'bb' p3.get_record(2) == b'ccc' All three records, of three genuinely different lengths, round-trip byte-for-byte correctly. WHY VARIABLE-LENGTH RECORDS MAKE A FIXED OFFSET TABLE IMPOSSIBLE ------------------------------ A "fixed offset table" would mean: slot N's own record always starts at some predictable formula like `HEADER_SIZE + N * RECORD_SIZE` -- which only works if every record occupies the exact same number of bytes, RECORD_SIZE, known in advance. That's true for Chapter 2's own fixed-width INTEGER columns (always exactly 8 bytes), but records in this exercise are 1, 2, and 3 bytes respectively -- there is no single RECORD_SIZE that could describe all three. If a fixed-offset scheme tried to use, say, 3 bytes per slot (the largest record's own size) to accommodate all of them uniformly, it would waste 2 bytes storing b'a' (padding it out to 3 bytes it doesn't need) and 1 byte storing b'bb' -- and that waste gets worse, not better, the more the record sizes in a real table actually vary (a real TEXT column might hold anything from an empty string to a paragraph). The slot directory sidesteps this entirely by storing each record's OWN actual offset and OWN actual length explicitly, per slot, rather than deriving a formula that assumes uniform size. get_record(i) reads slot i's own stored (offset, length) pair and slices out exactly that many bytes starting at exactly that offset -- there's no assumption anywhere that record i's own size has any particular relationship to record i-1's or i+1's own size. Slot 0 legitimately points at a 1-byte record, slot 1 at a 2-byte record immediately "before" it in memory (since data grows backward), and slot 2 at a 3-byte record -- three completely independent lengths, each one explicitly recorded rather than assumed. WHY THIS WORKS AS AN ANSWER ------------------------------ This confirms the WHOLE POINT of a slot directory, distinct from a simple fixed-size record array: it exists specifically to handle records whose sizes genuinely differ from each other, by storing the "where does this one live, and how big is it" information explicitly, per record, rather than trying to compute it from a single global record size that a variable-length format (like Chapter 2's own TEXT columns) can never actually have.