Elffuss BraidHub

utopia-ia/elffuss-braid public

71ae7b5a0cf6 · 2.1 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 let id = objects.put(kind, payload).map_err(Error::objects)?;
28 let expected = ObjectId::hash(kind, payload);
29 if id != expected {
30 return Err(Error::BadBraidObject {
31 id,
32 detail: format!("the store gave this id to the {kind} {expected}"),
33 });
34 }
35 Ok(id)
36}
37
38/// Every entry of a directory, whether it is one flat node or split.
39pub(crate) fn tree_entries<O: Objects>(objects: &O, root: ObjectId) -> Result<Vec<Entry>, Error> {
40 let mut failure = None;
41 let entries = read_directory(root, |id| match get(objects, id, Kind::Tree) {
42 Ok(bytes) => Some(bytes),
43 Err(err) => {
44 failure.get_or_insert(err);
45 None
46 }
47 });
48 if let Some(err) = failure {
49 return Err(err);
50 }
51 entries.map_err(|err| Error::BadBraidObject {
52 id: root,
53 detail: err.to_string(),
54 })
55}
56
57/// A decoded changeset.
58pub(crate) fn changeset<O: Objects>(objects: &O, id: &ObjectId) -> Result<Changeset, Error> {
59 let bytes = get(objects, id, Kind::Changeset)?;
60 Changeset::decode(&bytes).map_err(|err| Error::BadBraidObject {
61 id: *id,
62 detail: err.to_string(),
63 })
64}