use std::collections::BTreeMap;
use crate::log::{Hash, leaf_hash};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Node {
Leaf {
content: Vec<u8>,
},
Branch {
header: Vec<u8>,
children: BTreeMap<String, Node>,
},
}
const BRANCH_TAG: u8 = 0x02;
impl Node {
#[must_use]
pub fn leaf(content: impl Into<Vec<u8>>) -> Self {
Self::Leaf {
content: content.into(),
}
}
#[must_use]
pub fn branch(header: impl Into<Vec<u8>>) -> Self {
Self::Branch {
header: header.into(),
children: BTreeMap::new(),
}
}
#[must_use]
pub fn with_child(mut self, name: impl Into<String>, child: Self) -> Self {
if let Self::Branch { children, .. } = &mut self {
children.insert(name.into(), child);
}
self
}
#[must_use]
pub const fn is_branch(&self) -> bool {
matches!(self, Self::Branch { .. })
}
#[must_use]
pub fn children(&self) -> Option<&BTreeMap<String, Node>> {
match self {
Self::Branch { children, .. } => Some(children),
Self::Leaf { .. } => None,
}
}
#[must_use]
pub fn hash(&self) -> Hash {
match self {
Self::Leaf { content } => leaf_hash(content),
Self::Branch { header, children } => {
let mut buf = vec![BRANCH_TAG];
buf.extend_from_slice(&(header.len() as u64).to_le_bytes());
buf.extend_from_slice(header);
for (name, child) in children {
let name_bytes = name.as_bytes();
buf.extend_from_slice(&(name_bytes.len() as u64).to_le_bytes());
buf.extend_from_slice(name_bytes);
buf.extend_from_slice(&child.hash());
}
leaf_hash(&buf)
}
}
}
#[must_use]
pub fn find(&self, path: &str) -> Option<&Node> {
if path.is_empty() {
return Some(self);
}
let (head, rest) = path.split_once('/').unwrap_or((path, ""));
self.children()?.get(head)?.find(rest)
}
#[must_use]
pub fn leaves(&self) -> Vec<(String, Hash)> {
let mut out = Vec::new();
self.collect_leaves(String::new(), &mut out);
out
}
fn collect_leaves(&self, prefix: String, out: &mut Vec<(String, Hash)>) {
match self {
Self::Leaf { .. } => out.push((prefix, self.hash())),
Self::Branch { children, .. } => {
for (name, child) in children {
let path = if prefix.is_empty() {
name.clone()
} else {
format!("{prefix}/{name}")
};
child.collect_leaves(path, out);
}
}
}
}
}