"""F2 — Memory monomers (MC_16–MC_23)."""
from typing import Any

_MAX_ALLOC = 65536


def load(mem: dict, key: Any) -> Any | None:
    """MC_16: load from memory map."""
    return mem.get(key)


def store(mem: dict, key: Any, value: Any) -> bool:
    """MC_17: store into memory map."""
    mem[key] = value
    return True


def push(stack: list, value: Any) -> list:
    """MC_18: push onto stack."""
    stack.append(value)
    return stack


def pop(stack: list) -> tuple[Any | None, list]:
    """MC_19: pop from stack → (value, stack)."""
    if not stack:
        return (None, stack)
    val = stack.pop()
    return (val, stack)


def peek(stack: list) -> Any | None:
    """MC_20: peek top of stack."""
    return stack[-1] if stack else None


def alloc(size: int) -> list:
    """MC_21: allocate list of given size (capped at 65536)."""
    return [None] * min(size, _MAX_ALLOC)


def free(mem: dict, key: Any) -> bool:
    """MC_22: free key from memory map."""
    if key in mem:
        del mem[key]
        return True
    return False


def len_mem(mem: dict | list) -> int:
    """MC_23: length of memory structure."""
    return len(mem)
