Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 2.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Small helpers for paths: names joined by `/`, as raw bytes.
5
6use std::borrow::Cow;
7
8use crate::error::Error;
9
10/// The most names a path may have: 1,024.
11///
12/// This is a store policy, not part of the hashed format, which sets no
13/// limit. A store refuses a change whose paths are deeper, so no tree it holds
14/// is deeper either, and every walk over a tree stops with
15/// [`Error::TooDeep`] instead of going further.
16pub const MAX_PATH_DEPTH: usize = 1024;
17
18/// How many bytes of a path messages show.
19const SHOWN_BYTES: usize = 256;
20
21/// `dir/name`, or `name` when `dir` is the root (empty).
22pub(crate) fn join(dir: &[u8], name: &[u8]) -> Vec<u8> {
23 let mut path = Vec::with_capacity(dir.len() + 1 + name.len());
24 if !dir.is_empty() {
25 path.extend_from_slice(dir);
26 path.push(b'/');
27 }
28 path.extend_from_slice(name);
29 path
30}
31
32/// The last name of a path.
33pub(crate) fn last_name(path: &[u8]) -> &[u8] {
34 path.rsplit(|byte| *byte == b'/').next().unwrap_or(path)
35}
36
37/// How many names a path has; the root, empty, has none.
38pub(crate) fn depth(path: &[u8]) -> usize {
39 if path.is_empty() {
40 0
41 } else {
42 1 + path.iter().filter(|byte| **byte == b'/').count()
43 }
44}
45
46/// Fails if `path` has more than [`MAX_PATH_DEPTH`] names.
47pub(crate) fn check_depth(path: &[u8]) -> Result<(), Error> {
48 if depth(path) > MAX_PATH_DEPTH {
49 return Err(Error::TooDeep {
50 path: path.to_vec(),
51 });
52 }
53 Ok(())
54}
55
56/// A path for messages, cut short if it is long.
57pub(crate) fn show(path: &[u8]) -> Cow<'_, str> {
58 if path.len() <= SHOWN_BYTES {
59 return String::from_utf8_lossy(path);
60 }
61 let mut shown = String::from_utf8_lossy(&path[..SHOWN_BYTES]).into_owned();
62 shown.push('…');
63 Cow::Owned(shown)
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn helpers() {
72 assert_eq!(join(b"", b"a"), b"a");
73 assert_eq!(join(b"a/b", b"c"), b"a/b/c");
74 assert_eq!(last_name(b"a/b/c"), b"c");
75 assert_eq!(last_name(b"c"), b"c");
76 assert_eq!(show(b"caf\xc3\xa9"), "caf\u{e9}");
77 assert_eq!(show(&[b'a'; 300]).chars().count(), SHOWN_BYTES + 1);
78 assert_eq!(depth(b""), 0);
79 assert_eq!(depth(b"a"), 1);
80 assert_eq!(depth(b"a/b/c"), 3);
81 }
82
83 #[test]
84 fn depth_limit() {
85 let deepest = vec!["d"; MAX_PATH_DEPTH].join("/");
86 assert!(check_depth(deepest.as_bytes()).is_ok());
87 let deeper = format!("{deepest}/d");
88 assert!(matches!(
89 check_depth(deeper.as_bytes()),
90 Err(Error::TooDeep { path }) if path == deeper.as_bytes()
91 ));
92 }
93}