raindb 1.0.0

A persistent key-value store based on an LSM tree implemented in Rust
Documentation
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright (c) 2021 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

use parking_lot::RwLock;
use std::fmt::Debug;
use std::sync::{Arc, Weak};

type Link<T> = Option<SharedNode<T>>;

type WeakLink<T> = Option<Weak<RwLock<Node<T>>>>;

/// A [`Node`] wrapped in concurrency primitives.
pub type SharedNode<T> = Arc<RwLock<Node<T>>>;

/// A node in the linked list.
#[derive(Debug)]
pub struct Node<T>
where
    T: Debug,
{
    /// The element that the node represents.
    pub element: T,

    /**
    A link to the next node.

    This should not be changed except through the linked list itself.
    */
    next: Link<T>,

    /**
    A link to the previous node.

    This should not be changed except through the linked list itself.
    */
    prev: WeakLink<T>,
}

/// Public methods
impl<T> Node<T>
where
    T: Debug,
{
    /**
    Create a new [`Node`] that with empty next and previous links.

    **NOTE**: This is accessible to the crate only for testing purposes.
    */
    pub(crate) fn new(element: T) -> Self {
        Self {
            element,
            next: None,
            prev: None,
        }
    }
}

/**
A doubly-linked linked list that exposes it's structural nodes.

The structural nodes are exposed to enable things like O(1) insertion and removal.

# Concurrency

This linked list is not safe for use without external synchronization. A [`RwLock`] is used on the
nodes purely for interior mutability purposes. This could be made obvious with
[`std::cell::UnsafeCell`] but [`RwLock`] was used so that the code didn't get even more verbose.
*/
#[derive(Debug)]
pub struct LinkedList<T>
where
    T: Debug,
{
    /// The head of the list.
    head: Link<T>,

    /// The tail of the list.
    tail: Link<T>,

    /// The length of the list.
    length: usize,
}

/// Public methods
impl<T> LinkedList<T>
where
    T: Debug,
{
    /// Create a new instance of [`LinkedList`]
    pub fn new() -> Self {
        Self {
            head: None,
            tail: None,
            length: 0,
        }
    }

    /// Remove an element from the tail of the list.
    pub fn pop(&mut self) -> Option<SharedNode<T>> {
        self.tail.take().map(|old_tail_node| {
            self.tail = match old_tail_node.write().prev.take() {
                None => None,
                Some(prev_node) => Weak::upgrade(&prev_node),
            };

            match self.tail.as_mut() {
                None => {
                    // There is no new tail node so the list must be empty
                    self.head = None;
                }
                Some(new_tail_node) => {
                    // The new tail's next should now be `None` since it pointed at the old,
                    // removed tail
                    new_tail_node.write().next = None;
                }
            }

            self.length -= 1;

            old_tail_node
        })
    }

    /// Remove an element from the front of the list.
    pub fn pop_front(&mut self) -> Option<SharedNode<T>> {
        self.head.take().map(|old_head_node| {
            self.head = old_head_node.write().next.clone();

            match self.head.as_ref() {
                None => {
                    // There is no new head node so the list must be empty
                    self.tail = None;
                }
                Some(new_head_node) => {
                    // The new head's previous should now be `None` since it pointed at the old,
                    // removed head
                    new_head_node.write().prev = None;
                }
            }

            self.length -= 1;

            old_head_node
        })
    }

    /// Push an element onto the back of the list.
    pub fn push(&mut self, element: T) -> SharedNode<T> {
        let new_node = Arc::new(RwLock::new(Node::new(element)));
        self.push_node(Arc::clone(&new_node));

        new_node
    }

    /// Push a node onto the back of the list.
    pub fn push_node(&mut self, node: SharedNode<T>) {
        node.write().prev = self.tail.as_ref().map(Arc::downgrade);
        node.write().next = None;

        match self.tail.as_ref() {
            Some(tail_node) => {
                // Fix existing links
                tail_node.write().next = Some(Arc::clone(&node))
            }
            None => self.head = Some(Arc::clone(&node)),
        }

        self.tail = Some(node);
        self.length += 1;
    }

    /// Push an element onto the front of the list.
    pub fn push_front(&mut self, element: T) -> SharedNode<T> {
        let new_node = Arc::new(RwLock::new(Node::new(element)));
        self.push_node_front(Arc::clone(&new_node));

        new_node
    }

    /// Push a node onto the front of the list.
    pub fn push_node_front(&mut self, node: SharedNode<T>) {
        node.write().prev = None;
        node.write().next = self.head.clone();

        match self.head.as_ref() {
            Some(head_node) => {
                // Fix existing links
                head_node.write().prev = Some(Arc::downgrade(&node));
            }
            None => self.tail = Some(Arc::clone(&node)),
        }

        self.head = Some(node);
        self.length += 1;
    }

    /// Remove the given node from the linked list.
    pub fn remove_node(&mut self, target_node: SharedNode<T>) {
        let mutable_target = target_node.write();
        let maybe_previous_node = match mutable_target.prev.as_ref() {
            None => None,
            Some(weak_prev) => Weak::upgrade(weak_prev),
        };

        // Fix the links of the previous and next nodes so that they point at each other instead of
        // the node we are removing
        match maybe_previous_node.clone() {
            Some(previous_node) => {
                previous_node.write().next = mutable_target.next.clone();
            }
            None => {
                // Only head nodes have no previous link
                self.head = mutable_target.next.clone();
            }
        }

        match mutable_target.next.as_ref() {
            Some(next_node) => {
                next_node.write().prev = mutable_target.prev.clone();
            }
            None => {
                // Only tail nodes have no next link
                self.tail = maybe_previous_node;
            }
        }

        self.length -= 1;
    }

    /// Get the length of the list.
    pub fn len(&self) -> usize {
        self.length
    }

    /// Returns true if the list is empty, otherwise false.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Return an iterator over the nodes of the linked list.
    pub fn iter(&self) -> NodeIter<T> {
        NodeIter {
            next: self.head.as_ref().cloned(),
        }
    }

    /// Get a reference to the first node of the linked list.
    pub fn head(&self) -> Link<T> {
        self.head.as_ref().cloned()
    }

    /// Get a reference to the last node of the linked list.
    pub fn tail(&self) -> Link<T> {
        self.tail.as_ref().cloned()
    }
}

impl<T> Drop for LinkedList<T>
where
    T: Debug,
{
    fn drop(&mut self) {
        while self.pop_front().is_some() {}
    }
}

/**
An iterator adapter to keep state for iterating the linked list.

Created by calling [`LinkedList::iter`].
*/
pub struct NodeIter<T>
where
    T: Debug,
{
    /// The next value of the iterator.
    next: Option<SharedNode<T>>,
}

impl<T> Iterator for NodeIter<T>
where
    T: Debug,
{
    type Item = SharedNode<T>;

    fn next(&mut self) -> Option<Self::Item> {
        self.next.take().map(|current_node| {
            self.next = current_node.read().next.as_ref().map(Arc::clone);

            current_node
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn single_threaded_empty_list_returns_zero_length() {
        let list = LinkedList::<u64>::new();
        assert_eq!(list.len(), 0);
    }

    #[test]
    fn single_threaded_can_push_elements() {
        let mut list = LinkedList::<u64>::new();

        let mut pushed = list.push(1);
        assert_eq!(pushed.read().element, 1);
        assert_eq!(list.len(), 1);

        pushed = list.push(2);
        assert_eq!(pushed.read().element, 2);
        assert_eq!(list.len(), 2);

        pushed = list.push(3);
        assert_eq!(pushed.read().element, 3);
        assert_eq!(list.len(), 3);
    }

    #[test]
    fn single_threaded_can_pop_elements() {
        let mut list = LinkedList::<u64>::new();
        list.push(1);
        list.push(2);
        list.push(3);
        assert_eq!(list.len(), 3);

        assert_eq!(list.pop().unwrap().read().element, 3);
        assert_eq!(list.len(), 2);

        assert_eq!(list.pop().unwrap().read().element, 2);
        assert_eq!(list.len(), 1);

        assert_eq!(list.pop().unwrap().read().element, 1);
        assert_eq!(list.len(), 0);

        assert!(list.pop().is_none());
    }

    #[test]
    fn single_threaded_can_push_elements_to_the_front() {
        let mut list = LinkedList::<u64>::new();

        list.push_front(1);
        assert_eq!(list.len(), 1);
        list.push_front(2);
        assert_eq!(list.len(), 2);
        list.push_front(3);
        assert_eq!(list.len(), 3);
    }

    #[test]
    fn single_threaded_can_pop_elements_from_the_front() {
        let mut list = LinkedList::<u64>::new();
        list.push(1);
        list.push(2);
        list.push(3);
        assert_eq!(list.len(), 3);

        assert_eq!(list.pop_front().unwrap().read().element, 1);
        assert_eq!(list.len(), 2);

        assert_eq!(list.pop_front().unwrap().read().element, 2);
        assert_eq!(list.len(), 1);

        assert_eq!(list.pop_front().unwrap().read().element, 3);
        assert_eq!(list.len(), 0);

        assert!(list.pop_front().is_none());
    }

    #[test]
    fn single_threaded_list_can_unlink_head() {
        let mut list = LinkedList::<u64>::new();
        let pushed = list.push(1);
        list.push(2);
        list.push(3);

        list.remove_node(pushed);

        assert_eq!(list.len(), 2);
        assert_eq!(list.pop_front().unwrap().read().element, 2);
    }

    #[test]
    fn single_threaded_list_can_unlink_tail() {
        let mut list = LinkedList::<u64>::new();
        list.push(1);
        list.push(2);
        let pushed = list.push(3);

        list.remove_node(pushed);

        assert_eq!(list.len(), 2);
        assert_eq!(list.pop().unwrap().read().element, 2);
    }

    #[test]
    fn single_threaded_list_can_unlink_node_from_middle() {
        let mut list = LinkedList::<u64>::new();
        list.push(1);
        let pushed = list.push(2);
        list.push(3);

        list.remove_node(pushed);

        assert_eq!(list.len(), 2);
        assert_eq!(list.pop_front().unwrap().read().element, 1);
    }
}