aboutsummaryrefslogtreecommitdiff
path: root/src/client/fs/dcache.rs
blob: b171abcf6a3494d5ea6bf366a9542ab5226d391e (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use super::ino::Ino;
use std::{
    collections::{
        btree_map::{self, OccupiedError},
        BTreeMap, HashMap,
    },
    ffi::{OsStr, OsString},
};

#[derive(Debug)]
pub(super) struct Dcache {
    inner: HashMap<Ino, Dentry>,
}

impl Dcache {
    pub fn new() -> Self {
        Self {
            inner: HashMap::new(),
        }
    }

    pub fn get_ino(&self, parent: Ino, name: &OsStr) -> Option<&Ino> {
        self.get(parent).and_then(|dentry| dentry.get(name))
    }

    pub fn try_insert_name(
        &mut self,
        parent: Ino,
        name: OsString,
        ino: Ino,
    ) -> Option<Result<(), ()>> {
        match self
            .get_mut(parent)
            .map(|dentry| dentry.try_insert(name, ino))
        {
            Some(Ok(_)) => Some(Ok(())),
            Some(Err(_)) => Some(Err(())),
            None => None,
        }
    }

    pub fn add_dentry(&mut self, ino: Ino, parent: Ino) -> Option<Dentry> {
        self.insert(ino, Dentry::new(ino, parent))
    }

    // Map-like API

    pub fn insert(&mut self, ino: Ino, dentry: Dentry) -> Option<Dentry> {
        self.inner.insert(ino, dentry)
    }

    pub fn get(&self, ino: Ino) -> Option<&Dentry> {
        self.inner.get(&ino)
    }

    pub fn get_mut(&mut self, ino: Ino) -> Option<&mut Dentry> {
        self.inner.get_mut(&ino)
    }

    pub fn remove(&mut self, ino: Ino) -> Option<Dentry> {
        self.inner.remove(&ino)
    }
}

#[derive(Debug)]
pub(super) struct Dentry {
    inner: BTreeMap<OsString, Ino>,
    pub loaded: bool,
}

impl Dentry {
    pub fn new(ino: Ino, parent: Ino) -> Self {
        let mut dentry = Self {
            inner: BTreeMap::new(),
            loaded: false,
        };

        dentry.insert(".".into(), ino);
        dentry.insert("..".into(), parent);

        dentry
    }

    pub fn insert(&mut self, k: OsString, v: Ino) -> Option<Ino> {
        self.inner.insert(k, v)
    }

    pub fn try_insert(
        &mut self,
        k: OsString,
        v: Ino,
    ) -> Result<&mut Ino, btree_map::OccupiedError<'_, OsString, Ino>> {
        self.inner.try_insert(k, v)
    }

    pub fn get(&self, k: &OsStr) -> Option<&Ino> {
        self.inner.get(k)
    }

    pub fn remove(&mut self, k: &OsStr) -> Option<Ino> {
        self.inner.remove(k)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&OsString, &Ino)> {
        self.inner.iter()
    }
}