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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//! Represents a single entry in the tree, which may or may not exist

use crate::{
    value::{UserData, UserKey},
    Tree,
};

/// Represents a missing entry in the tree
#[allow(clippy::module_name_repetitions)]
pub struct VacantEntry {
    pub(crate) tree: Tree,
    pub(crate) key: UserKey,
}

#[allow(clippy::module_name_repetitions)]
/// Represents an existing entry in the tree
pub struct OccupiedEntry {
    pub(crate) tree: Tree,
    pub(crate) key: UserKey,
    pub(crate) value: UserData,
}

impl OccupiedEntry {
    /// Gets the entry's value.
    #[must_use]
    pub fn get(&self) -> UserData {
        self.value.clone()
    }

    /// Updates the entry.
    ///
    /// # Errors
    ///
    /// Will return `Err` if an IO error occurs.
    pub fn update<V: AsRef<[u8]>>(&mut self, value: V) -> crate::Result<()> {
        self.value = value.as_ref().into();
        self.tree.insert(self.key.clone(), self.value.clone())?;
        Ok(())
    }
}

impl VacantEntry {
    /// Inserts the entry, making sure it exists and returns the value.
    ///
    /// # Errors
    ///
    /// Will return `Err` if an IO error occurs.
    pub fn insert<V: AsRef<[u8]>>(&self, value: V) -> crate::Result<UserData> {
        let value: UserData = value.as_ref().into();
        self.tree.insert(self.key.clone(), value.clone())?;
        Ok(value)
    }
}

/// Represents a single entry in the tree, which may or may not exist.
pub enum Entry {
    /// Represents a missing entry in the tree
    Vacant(VacantEntry),

    /// Represents an existing entry in the tree
    Occupied(OccupiedEntry),
}

use Entry::{Occupied, Vacant};

impl Entry {
    /// Returns a reference to this entry's key
    ///
    /// # Examples
    ///
    /// ```
    /// # let folder = tempfile::tempdir()?;
    /// use lsm_tree::{Config, Tree};
    ///
    /// let tree = Tree::open(Config::new(folder))?;
    ///
    /// let entry = tree.entry("a")?;
    /// assert_eq!("a".as_bytes(), &*entry.key());
    /// #
    /// # Ok::<(), lsm_tree::Error>(())
    /// ```
    #[must_use]
    pub fn key(&self) -> UserKey {
        match self {
            Vacant(entry) => entry.key.clone(),
            Occupied(entry) => entry.key.clone(),
        }
    }

    /// Updates the value if it exists before any potential inserts.
    ///
    /// # Examples
    ///
    /// ```
    /// # let folder = tempfile::tempdir()?;
    /// use lsm_tree::{Config, Tree};
    ///
    /// let tree = Tree::open(Config::new(folder))?;
    ///
    /// let value = tree.entry("a")?.or_insert("abc")?;
    /// assert_eq!("abc".as_bytes(), &*value);
    ///
    /// let value = tree.entry("a")?.and_update(|_| "def")?.or_insert("abc")?;
    /// assert_eq!("def".as_bytes(), &*value);
    /// #
    /// # Ok::<(), lsm_tree::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Will return `Err` if an IO error occurs.
    pub fn and_update<V: AsRef<[u8]>, F: FnOnce(&UserData) -> V>(
        mut self,
        f: F,
    ) -> crate::Result<Self> {
        if let Occupied(entry) = &mut self {
            entry.update(f(&entry.value).as_ref())?;
        }

        Ok(self)
    }

    /// Ensures a value is in the entry by inserting the default if empty, and returns that value.
    ///
    /// # Examples
    ///
    /// ```
    /// # let folder = tempfile::tempdir()?;
    /// use lsm_tree::{Config, Tree};
    ///
    /// let tree = Tree::open(Config::new(folder))?;
    ///
    /// let value = tree.entry("a")?.or_insert("abc")?;
    /// assert_eq!("abc".as_bytes(), &*value);
    /// #
    /// # Ok::<(), lsm_tree::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Will return `Err` if an IO error occurs.
    pub fn or_insert<V: AsRef<[u8]>>(&self, value: V) -> crate::Result<UserData> {
        match self {
            Vacant(entry) => entry.insert(value),
            Occupied(entry) => Ok(entry.get()),
        }
    }

    /// Ensures a value is in the entry by inserting the result of the default function if empty, and returns that value.
    ///
    /// # Examples
    ///
    /// ```
    /// # let folder = tempfile::tempdir()?;
    /// use lsm_tree::{Config, Tree};
    ///
    /// let tree = Tree::open(Config::new(folder))?;
    ///
    /// let value = tree.entry("a")?.or_insert_with(|| "abc")?;
    /// assert_eq!("abc".as_bytes(), &*value);
    /// #
    /// # Ok::<(), lsm_tree::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Will return `Err` if an IO error occurs.
    pub fn or_insert_with<V: AsRef<[u8]>, F: FnOnce() -> V>(
        &self,
        f: F,
    ) -> crate::Result<UserData> {
        match self {
            Vacant(entry) => entry.insert(f()),
            Occupied(entry) => Ok(entry.get()),
        }
    }

    /// Ensures a value is in the entry by inserting the result of the default function if empty, and returns that value.
    ///
    /// # Examples
    ///
    /// ```
    /// # let folder = tempfile::tempdir()?;
    /// use lsm_tree::{Config, Tree};
    ///
    /// let tree = Tree::open(Config::new(folder))?;
    ///
    /// let value = tree.entry("a")?.or_insert_with_key(|k| k.clone())?;
    /// assert_eq!("a".as_bytes(), &*value);
    /// #
    /// # Ok::<(), lsm_tree::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Will return `Err` if an IO error occurs.
    pub fn or_insert_with_key<V: AsRef<[u8]>, F: FnOnce(&UserData) -> V>(
        &self,
        f: F,
    ) -> crate::Result<UserData> {
        match self {
            Vacant(entry) => entry.insert(f(&entry.key)),
            Occupied(entry) => Ok(entry.get()),
        }
    }
}