""" tree.py — Tree object interface for Trove. A tree is a named mapping of entries to UUIDs, serialized as UTF-8 JSON. Corresponds to a 'tree' row in the objects table; this class handles only the data field — storage is the caller's concern. """ import json from .trove import ObjectId class Tree: def __init__(self, data: bytes | None = None): """ Initialize a Tree. If data is provided, deserialize from UTF-8 JSON bytes. An empty Tree is created if data is None. """ if not data: self._entries: dict[str, ObjectId] = {} else: self._entries = json.loads(data.decode("utf-8")) def serialize(self) -> bytes: """Serialize the tree to UTF-8 JSON bytes.""" return json.dumps(self._entries).encode("utf-8") def set_entry(self, name: str, object_id: ObjectId) -> None: """Add or update an entry mapping name -> uuid.""" self._entries[name] = object_id def get_entry(self, name: str) -> ObjectId: """Get the uuid associated with a name, or raise KeyError if not found.""" return self._entries[name] def rm_entry(self, name: str) -> None: """Remove an entry by name. Raises KeyError if not found.""" del self._entries[name] def list(self) -> dict[str, ObjectId]: """Return a shallow copy of all entries as {name: uuid}.""" return dict(self._entries)