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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::mem;

use anyhow::{anyhow, Result};

use crate::storage::mkvs::{
    cache::Cache,
    tree::{Depth, Key, KeyTrait, NodeBox, NodeKind, NodePointer, NodePtrRef, Tree, Value},
};

use super::lookup::FetcherSyncGet;

impl Tree {
    /// Insert a key/value pair into the tree.
    pub fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<Option<Vec<u8>>> {
        let pending_root = self.cache.borrow().get_pending_root();
        let boxed_key = key.to_vec();
        let boxed_val = value.to_vec();

        // Remember where the path from root to target node ends (will end).
        self.cache.borrow_mut().mark_position();

        let (new_root, old_val) = self._insert(pending_root, 0, &boxed_key, boxed_val)?;
        self.cache.borrow_mut().set_pending_root(new_root);

        Ok(old_val)
    }

    fn _insert(
        &mut self,
        ptr: NodePtrRef,
        bit_depth: Depth,
        key: &Key,
        val: Value,
    ) -> Result<(NodePtrRef, Option<Value>)> {
        let node_ref = self
            .cache
            .borrow_mut()
            .deref_node_ptr(ptr.clone(), Some(FetcherSyncGet::new(key, false)))?;

        let (_, key_remainder) = key.split(bit_depth, key.bit_length());

        match classify_noderef!(?node_ref) {
            NodeKind::None => {
                return Ok((self.cache.borrow_mut().new_leaf_node(key, val), None));
            }
            NodeKind::Internal => {
                let node_ref = node_ref.unwrap();
                let (leaf_node, left, right): (NodePtrRef, NodePtrRef, NodePtrRef);
                let cp_len: Depth;
                let label_prefix: Key;
                if let NodeBox::Internal(ref mut n) = *node_ref.borrow_mut() {
                    cp_len = n.label.common_prefix_len(
                        n.label_bit_length,
                        &key_remainder,
                        key.bit_length() - bit_depth,
                    );

                    if cp_len == n.label_bit_length {
                        // The current part of key matched the node's Label. Do recursion.
                        let r: (NodePtrRef, Option<Value>);
                        if key.bit_length() == bit_depth + n.label_bit_length {
                            // Key to insert ends exactly at this node. Add it to the
                            // existing internal node as LeafNode.
                            r = self._insert(
                                n.leaf_node.clone(),
                                bit_depth + n.label_bit_length,
                                key,
                                val,
                            )?;
                            n.leaf_node = r.0;
                        } else if key.get_bit(bit_depth + n.label_bit_length) {
                            // Insert recursively based on the bit value.
                            r = self._insert(
                                n.right.clone(),
                                bit_depth + n.label_bit_length,
                                key,
                                val,
                            )?;
                            n.right = r.0;
                        } else {
                            r = self._insert(
                                n.left.clone(),
                                bit_depth + n.label_bit_length,
                                key,
                                val,
                            )?;
                            n.left = r.0;
                        }

                        if !n.leaf_node.borrow().clean
                            || !n.left.borrow().clean
                            || !n.right.borrow().clean
                        {
                            n.clean = false;
                            ptr.borrow_mut().clean = false;
                            // No longer eligible for eviction as it is dirty.
                            self.cache
                                .borrow_mut()
                                .rollback_node(ptr.clone(), NodeKind::Internal);
                        }

                        return Ok((ptr, r.1));
                    }

                    // Key mismatches the label at position cp_len. Split the edge and
                    // insert new leaf.
                    let label_split = n.label.split(cp_len, n.label_bit_length);
                    label_prefix = label_split.0;
                    n.label = label_split.1;
                    n.label_bit_length -= cp_len;
                    n.clean = false;
                    ptr.borrow_mut().clean = false;
                    // No longer eligible for eviction as it is dirty.
                    self.cache
                        .borrow_mut()
                        .rollback_node(ptr.clone(), NodeKind::Internal);

                    let new_leaf = self.cache.borrow_mut().new_leaf_node(key, val);
                    if key.bit_length() - bit_depth == cp_len {
                        // The key is a prefix of existing path.
                        leaf_node = new_leaf;
                        if n.label.get_bit(0) {
                            left = NodePointer::null_ptr();
                            right = ptr;
                        } else {
                            left = ptr;
                            right = NodePointer::null_ptr();
                        }
                    } else {
                        leaf_node = NodePointer::null_ptr();
                        if key_remainder.get_bit(cp_len) {
                            left = ptr;
                            right = new_leaf;
                        } else {
                            left = new_leaf;
                            right = ptr;
                        }
                    }
                } else {
                    return Err(anyhow!(
                        "insert.rs: unknown internal node_ref {:?}",
                        node_ref
                    ));
                }

                return Ok((
                    self.cache.borrow_mut().new_internal_node(
                        &label_prefix,
                        cp_len,
                        leaf_node,
                        left,
                        right,
                    ),
                    None,
                ));
            }
            NodeKind::Leaf => {
                // If the key matches, we can just update the value.
                let node_ref = node_ref.unwrap();
                let (leaf_node, left, right): (NodePtrRef, NodePtrRef, NodePtrRef);
                let cp_len: Depth;
                let label_prefix: Key;
                if let NodeBox::Leaf(ref mut n) = *node_ref.borrow_mut() {
                    // Should always succeed.
                    if n.key == *key {
                        // If the key matches, we can just update the value.
                        if n.value == val {
                            return Ok((ptr, Some(val)));
                        }
                        let old_val = mem::replace(&mut n.value, val);
                        n.clean = false;
                        ptr.borrow_mut().clean = false;
                        // No longer eligible for eviction as it is dirty.
                        self.cache
                            .borrow_mut()
                            .rollback_node(ptr.clone(), NodeKind::Leaf);
                        return Ok((ptr, Some(old_val)));
                    }

                    let (_, leaf_key_remainder) = n.key.split(bit_depth, n.key.bit_length());
                    cp_len = leaf_key_remainder.common_prefix_len(
                        n.key.bit_length() - bit_depth,
                        &key_remainder,
                        key.bit_length() - bit_depth,
                    );

                    // Key mismatches the label at position cp_len. Split the edge.
                    label_prefix = leaf_key_remainder
                        .split(cp_len, leaf_key_remainder.bit_length())
                        .0;
                    let new_leaf = self.cache.borrow_mut().new_leaf_node(key, val);

                    if key.bit_length() - bit_depth == cp_len {
                        // Inserted key is a prefix of the label.
                        leaf_node = new_leaf;
                        if leaf_key_remainder.get_bit(cp_len) {
                            left = NodePointer::null_ptr();
                            right = ptr;
                        } else {
                            left = ptr;
                            right = NodePointer::null_ptr();
                        }
                    } else if n.key.bit_length() - bit_depth == cp_len {
                        // Label is a prefix of the inserted key.
                        leaf_node = ptr;
                        if key_remainder.get_bit(cp_len) {
                            left = NodePointer::null_ptr();
                            right = new_leaf;
                        } else {
                            left = new_leaf;
                            right = NodePointer::null_ptr();
                        }
                    } else {
                        leaf_node = NodePointer::null_ptr();
                        if key_remainder.get_bit(cp_len) {
                            left = ptr;
                            right = new_leaf;
                        } else {
                            left = new_leaf;
                            right = ptr;
                        }
                    }
                } else {
                    return Err(anyhow!("insert.rs: invalid leaf node_ref {:?}", node_ref));
                }

                let new_internal = self.cache.borrow_mut().new_internal_node(
                    &label_prefix,
                    cp_len,
                    leaf_node,
                    left,
                    right,
                );
                Ok((new_internal, None))
            }
        }
    }
}