build_fs_tree/tree/
methods.rs

1use crate::FileSystemTree::{self, *};
2use std::collections::BTreeMap;
3
4macro_rules! get_content {
5    ($variant:ident, $source:expr) => {
6        if let $variant(content) = $source {
7            Some(content)
8        } else {
9            None
10        }
11    };
12}
13
14impl<Path, FileContent> FileSystemTree<Path, FileContent>
15where
16    Path: Ord,
17{
18    /// Get immutable reference to the file content.
19    pub fn file_content(&self) -> Option<&'_ FileContent> {
20        get_content!(File, self)
21    }
22
23    /// Get immutable reference to the directory content.
24    pub fn dir_content(&self) -> Option<&'_ BTreeMap<Path, Self>> {
25        get_content!(Directory, self)
26    }
27
28    /// Get immutable reference to a descendant of any level.
29    pub fn path<'a>(&'a self, path: &'a mut impl Iterator<Item = &'a Path>) -> Option<&'a Self> {
30        if let Some(current) = path.next() {
31            self.dir_content()?.get(current)?.path(path)
32        } else {
33            Some(self)
34        }
35    }
36
37    /// Get mutable reference to the file content.
38    pub fn file_content_mut(&mut self) -> Option<&'_ mut FileContent> {
39        get_content!(File, self)
40    }
41
42    /// Get mutable reference to the directory content.
43    pub fn dir_content_mut(&mut self) -> Option<&'_ mut BTreeMap<Path, Self>> {
44        get_content!(Directory, self)
45    }
46
47    /// Get mutable reference to a descendant of any level.
48    pub fn path_mut<'a>(
49        &'a mut self,
50        path: &'a mut impl Iterator<Item = &'a Path>,
51    ) -> Option<&'a mut Self> {
52        if let Some(current) = path.next() {
53            self.dir_content_mut()?.get_mut(current)?.path_mut(path)
54        } else {
55            Some(self)
56        }
57    }
58}