|
| 1 | +use super::*; |
| 2 | + |
| 3 | +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] |
| 4 | +#[serde(deny_unknown_fields, rename_all = "kebab-case", transparent)] |
| 5 | +pub struct Directory { |
| 6 | + pub(crate) entries: BTreeMap<Component, Entry>, |
| 7 | +} |
| 8 | + |
| 9 | +impl Directory { |
| 10 | + pub(crate) fn create_directory(&mut self, path: &RelativePath) -> Result { |
| 11 | + let mut current = self; |
| 12 | + for component in path.components() { |
| 13 | + current = current.create_directory_entry(component)?; |
| 14 | + } |
| 15 | + Ok(()) |
| 16 | + } |
| 17 | + |
| 18 | + fn create_directory_entry(&mut self, component: Component) -> Result<&mut Directory> { |
| 19 | + let entry = self |
| 20 | + .entries |
| 21 | + .entry(component) |
| 22 | + .or_insert(Entry::Directory(Directory::new())); |
| 23 | + |
| 24 | + match entry { |
| 25 | + Entry::Directory(directory) => Ok(directory), |
| 26 | + Entry::File(_file) => Err( |
| 27 | + error::Internal { |
| 28 | + message: "entry `{component}` already contains file", |
| 29 | + } |
| 30 | + .build(), |
| 31 | + ), |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + pub(crate) fn create_file(&mut self, path: &RelativePath, file: File) -> Result { |
| 36 | + let mut components = path.components().peekable(); |
| 37 | + |
| 38 | + let mut current = self; |
| 39 | + while let Some(component) = components.next() { |
| 40 | + if components.peek().is_none() { |
| 41 | + ensure! { |
| 42 | + current.entries.insert(component, Entry::File(file)).is_none(), |
| 43 | + error::Internal { |
| 44 | + message: "entry `{component}` already contains file", |
| 45 | + } |
| 46 | + } |
| 47 | + return Ok(()); |
| 48 | + } |
| 49 | + |
| 50 | + current = current.create_directory_entry(component)?; |
| 51 | + } |
| 52 | + |
| 53 | + Ok(()) |
| 54 | + } |
| 55 | + |
| 56 | + pub(crate) fn fingerprint(&self) -> Hash { |
| 57 | + let mut hasher = FieldHasher::new(Context::Directory); |
| 58 | + |
| 59 | + hasher.array(0, self.entries.len().into_u64()); |
| 60 | + |
| 61 | + for (component, entry) in &self.entries { |
| 62 | + hasher.element(entry.fingerprint(component)); |
| 63 | + } |
| 64 | + |
| 65 | + hasher.finalize() |
| 66 | + } |
| 67 | + |
| 68 | + pub(crate) fn is_empty(&self) -> bool { |
| 69 | + self.entries.is_empty() |
| 70 | + } |
| 71 | + |
| 72 | + pub(crate) fn new() -> Self { |
| 73 | + Self::default() |
| 74 | + } |
| 75 | +} |
0 commit comments