1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use crate::FileSystemTree::{self, *};
use std::collections::BTreeMap;

macro_rules! get_content {
    ($variant:ident, $source:expr) => {
        if let $variant(content) = $source {
            Some(content)
        } else {
            None
        }
    };
}

impl<Path, FileContent> FileSystemTree<Path, FileContent>
where
    Path: Ord,
{
    /// Get immutable reference to the file content.
    pub fn file_content(&self) -> Option<&'_ FileContent> {
        get_content!(File, self)
    }

    /// Get immutable reference to the directory content.
    pub fn dir_content(&self) -> Option<&'_ BTreeMap<Path, Self>> {
        get_content!(Directory, self)
    }

    /// Get immutable reference to a descendant of any level.
    pub fn path<'a>(&'a self, path: &'a mut impl Iterator<Item = &'a Path>) -> Option<&'a Self> {
        if let Some(current) = path.next() {
            self.dir_content()?.get(current)?.path(path)
        } else {
            Some(self)
        }
    }

    /// Get mutable reference to the file content.
    pub fn file_content_mut(&mut self) -> Option<&'_ mut FileContent> {
        get_content!(File, self)
    }

    /// Get mutable reference to the directory content.
    pub fn dir_content_mut(&mut self) -> Option<&'_ mut BTreeMap<Path, Self>> {
        get_content!(Directory, self)
    }

    /// Get mutable reference to a descendant of any level.
    pub fn path_mut<'a>(
        &'a mut self,
        path: &'a mut impl Iterator<Item = &'a Path>,
    ) -> Option<&'a mut Self> {
        if let Some(current) = path.next() {
            self.dir_content_mut()?.get_mut(current)?.path_mut(path)
        } else {
            Some(self)
        }
    }
}