"""
02_coalescing.py -- boundary tags and the four coalescing cases
================================================================

[Questions this demo answers]
  - When you free a block, its free neighbours should merge into it so the
    space stays usable. What are the four cases, and why is a FOOTER (boundary
    tag) what makes merging with the PREVIOUS block O(1)?
  - What does splitting do on allocation, and how do split + coalesce keep the
    heap from fragmenting into dust?

[How to run]
  python3 02_coalescing.py

[How to read the output]
  Each part sets up a specific neighbour situation, frees a block, and prints
  the block list before and after, so you can see the merge. A=allocated,
  F=free, with the block's total size.

[About this tool]  heap.py is a teaching allocator (Python); not malloclab.

[Systems link / CS:APP 9.9.11]
  Without coalescing, freeing leaves the heap as a litter of small free blocks
  (external fragmentation) even as memory is returned. Boundary tags let the
  allocator look at the block just BELOW the one being freed in O(1) (its
  footer sits right before the current header), so coalescing is constant time
  in all four cases.
"""

import heap


def show(h, label):
    print("  %-22s %s" % (label, h.describe()))


def case(title, setup):
    """Run one coalescing scenario. setup(h) allocates and returns (free_ptr)."""
    print(title)
    h = heap.Heap(640)
    ptr = setup(h)
    show(h, "before free:")
    h.free(ptr)
    show(h, "after free:")
    print()


def part_cases():
    print("PART A: the four coalescing cases (free the MIDDLE block each time)\n")

    # Case 1: both neighbours allocated -> no coalescing.
    def c1(h):
        a = h.malloc(80); m = h.malloc(80); z = h.malloc(80)  # noqa: F841
        return m
    case("Case 1: prev allocated, next allocated -> no merge", c1)

    # Case 2: next free -> merge forward.
    def c2(h):
        a = h.malloc(80); m = h.malloc(80); z = h.malloc(80)  # noqa: F841
        h.free(z)                                              # next becomes free
        return m
    case("Case 2: prev allocated, next FREE -> merge with next", c2)

    # Case 3: prev free -> merge backward (needs the footer to find prev).
    def c3(h):
        a = h.malloc(80); m = h.malloc(80); z = h.malloc(80)  # noqa: F841
        h.free(a)                                              # prev becomes free
        return m
    case("Case 3: prev FREE, next allocated -> merge with prev (uses the footer)", c3)

    # Case 4: both free -> merge both.
    def c4(h):
        a = h.malloc(80); m = h.malloc(80); z = h.malloc(80)  # noqa: F841
        h.free(a); h.free(z)
        return m
    case("Case 4: prev FREE, next FREE -> merge all three", c4)


def part_split():
    print("PART B: splitting on allocation")
    h = heap.Heap(640)
    show(h, "empty heap:")
    p = h.malloc(32)
    show(h, "after malloc(32):")
    print("  The one big free block was SPLIT: a block just big enough for the")
    print("  request, and the remainder left free. Splitting avoids handing out a")
    print("  huge block for a small request (internal fragmentation).\n")
    h.free(p)
    show(h, "after free:")
    print("  Freeing coalesced the split piece back with the remainder: one big")
    print("  free block again. Split on malloc, coalesce on free -- together they")
    print("  keep the heap from grinding down into unusable splinters.\n")


def part_why_footer():
    print("PART C: why the footer (boundary tag) matters")
    print("  To merge a freed block with the block BEFORE it, the allocator must find")
    print("  that previous block's header. In an implicit list it cannot walk backward")
    print("  from addresses alone. The FOOTER -- a copy of the header at the END of")
    print("  every block -- sits in the 8 bytes right before the current block's")
    print("  header, so the allocator reads it in O(1) to get the previous block's")
    print("  size and allocated bit. That is what makes Case 3 and Case 4 constant")
    print("  time instead of a full scan from the start of the heap.\n")


def main():
    print("=== Demo 02: coalescing and boundary tags ===\n")
    part_cases()
    part_split()
    part_why_footer()
    print("Observations:")
    print("  * Freeing merges with any free neighbour, in four cases; without it the")
    print("    heap fragments even as memory is returned.")
    print("  * The footer (boundary tag) lets a block find its predecessor in O(1), so")
    print("    backward coalescing (cases 3 and 4) is constant time.")
    print("  * malloc SPLITS a big free block to fit; free COALESCES; the pair keeps")
    print("    free space in as few, as large pieces as possible.")


if __name__ == "__main__":
    main()
