Skip to content

Commit ee3e32d

Browse files
committed
Add cbor to save and load methods
1 parent d9d0e7b commit ee3e32d

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

src/python/qubed/serialisation.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -297,13 +297,35 @@ def to_cbor(node: Qube) -> dict:
297297

298298

299299
def load(cls: type[Qube], path: str | Path) -> Qube:
300-
with open(path, "r") as f:
301-
return cls.from_json(json.load(f))
302-
303-
304-
def save(qube: Qube, path: str | Path):
305-
with open(path, "w") as f:
306-
json.dump(qube.to_json(), f)
300+
path = Path(path)
301+
if not path.exists():
302+
raise ValueError(f"{path} does not exist!")
303+
304+
if path.suffix == ".json":
305+
with open(path, "r") as f:
306+
return cls.from_json(json.load(f))
307+
elif path.suffix == ".cbor":
308+
with open(path, "rb") as f:
309+
return Qube.from_cbor(f.read())
310+
else:
311+
raise ValueError(f"Unknown filetype {path.suffix}")
312+
313+
314+
def save(qube: Qube, path: str | Path, type="json"):
315+
path = Path(path)
316+
print(path.suffix)
317+
if path.suffix == ".cbor":
318+
type = "cbor"
319+
320+
if type == "json":
321+
with open(path, "w") as f:
322+
json.dump(qube.to_json(), f)
323+
elif type == "cbor":
324+
print("Saving as cbor")
325+
with open(path, "wb") as f:
326+
f.write(qube.to_cbor())
327+
else:
328+
raise ValueError(f"Unkown filetype {type}")
307329

308330

309331
def from_tree(cls: type[Qube], tree_str: str):

0 commit comments

Comments
 (0)