Add tree data object
This commit is contained in:
parent
75c6bbe57b
commit
e78d479c14
1 changed files with 37 additions and 0 deletions
37
trovedb/tree.py
Normal file
37
trovedb/tree.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
"""
|
||||
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
|
||||
|
||||
|
||||
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 data is None:
|
||||
self._entries: dict[str, str] = {}
|
||||
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, uuid: str) -> None:
|
||||
"""Add or update an entry mapping name -> uuid."""
|
||||
self._entries[name] = uuid
|
||||
|
||||
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, str]:
|
||||
"""Return a shallow copy of all entries as {name: uuid}."""
|
||||
return dict(self._entries)
|
||||
Loading…
Add table
Add a link
Reference in a new issue