Elffuss BraidHub

utopia-ia/elffuss-braid public

38b3e04f7d4a · 2.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Reading and writing braid objects, with kinds checked and errors converted.
5
6use braid_format::{Changeset, Entry, Kind, ObjectId, Objects, read_directory};
7
8use crate::error::Error;
9
10/// Fetches an object that must be of `kind`.
11pub(crate) fn get<O: Objects>(objects: &O, id: &ObjectId, kind: Kind) -> Result<Vec<u8>, Error> {
12 match objects.get(id).map_err(Error::objects)? {
13 Some((found, payload)) if found == kind => Ok(payload),
14 Some((found, _)) => Err(Error::BadBraidObject {
15 id: *id,
16 detail: format!("is a {found}, expected a {kind}"),
17 }),
18 None => Err(Error::MissingBraidObject {
19 id: *id,
20 expected: kind,
21 }),
22 }
23}
24
25/// Stores an object and checks the id the store gives back.
26pub(crate) fn put<O: Objects>(objects: &O, kind: Kind, payload: &[u8]) -> Result<ObjectId, Error> {
27 put_hinted(objects, kind, payload, None)
28}
29
30/// Stores an object, with an object it is probably close to as a hint for
31/// the store, and checks the id the store gives back.
32pub(crate) fn put_hinted<O: Objects>(
33 objects: &O,
34 kind: Kind,
35 payload: &[u8],
36 similar: Option<&ObjectId>,
37) -> Result<ObjectId, Error> {
38 let id = match similar {
39 Some(similar) => objects.put_similar(kind, payload, similar),
40 None => objects.put(kind, payload),
41 }
42 .map_err(Error::objects)?;
43 let expected = ObjectId::hash(kind, payload);
44 if id != expected {
45 return Err(Error::BadBraidObject {
46 id,
47 detail: format!("the store gave this id to the {kind} {expected}"),
48 });
49 }
50 Ok(id)
51}
52
53/// Every entry of a directory, whether it is one flat node or split.
54pub(crate) fn tree_entries<O: Objects>(objects: &O, root: ObjectId) -> Result<Vec<Entry>, Error> {
55 let mut failure = None;
56 let entries = read_directory(root, |id| match get(objects, id, Kind::Tree) {
57 Ok(bytes) => Some(bytes),
58 Err(err) => {
59 failure.get_or_insert(err);
60 None
61 }
62 });
63 if let Some(err) = failure {
64 return Err(err);
65 }
66 entries.map_err(|err| Error::BadBraidObject {
67 id: root,
68 detail: err.to_string(),
69 })
70}
71
72/// A decoded changeset.
73pub(crate) fn changeset<O: Objects>(objects: &O, id: &ObjectId) -> Result<Changeset, Error> {
74 let bytes = get(objects, id, Kind::Changeset)?;
75 Changeset::decode(&bytes).map_err(|err| Error::BadBraidObject {
76 id: *id,
77 detail: err.to_string(),
78 })
79}