trove/trovedb/tree.py

45 lines
1.4 KiB
Python
Raw Permalink Normal View History

2026-03-15 20:48:43 -05:00
"""
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
2026-03-24 21:22:24 -05:00
from .trove import ObjectId
2026-03-15 20:48:43 -05:00
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:
2026-03-24 21:22:24 -05:00
self._entries: dict[str, ObjectId] = {}
2026-03-15 20:48:43 -05:00
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")
2026-03-24 21:22:24 -05:00
def set_entry(self, name: str, object_id: ObjectId) -> None:
2026-03-15 20:48:43 -05:00
"""Add or update an entry mapping name -> uuid."""
self._entries[name] = object_id
2026-03-24 21:22:24 -05:00
def get_entry(self, name: str) -> ObjectId:
"""Get the uuid associated with a name, or raise KeyError if not found."""
return self._entries[name]
2026-03-15 20:48:43 -05:00
def rm_entry(self, name: str) -> None:
"""Remove an entry by name. Raises KeyError if not found."""
del self._entries[name]
2026-03-24 21:22:24 -05:00
def list(self) -> dict[str, ObjectId]:
2026-03-15 20:48:43 -05:00
"""Return a shallow copy of all entries as {name: uuid}."""
return dict(self._entries)