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
use std::marker::PhantomData;

use lmdb;
use lmdb::Cursor as LMDBCursor;

use crate::error::Error;
use crate::types::{Key, Value};

pub struct Hidden<A, B>(PhantomData<A>, PhantomData<B>);

/// CursorOp provides the ability to specify the position of a cursor
pub enum CursorOp {
    /// Set the cursor to the first position
    First = 0,

    /// Get the key/value for the current position
    Current = 4,

    /// Set the cursor to the last position
    Last = 6,

    /// Move the cursor to the next position
    Next = 8,

    /// Move the cursor to the previous position
    Prev = 12,

    /// Set the cursor to the specified key
    Set = 16,

    /// Set the cursor to the first key greater than or equal to specified key
    SetRange = 17,
}

impl CursorOp {
    fn flag(self) -> u32 {
        self as u32
    }
}

/// Iterable access to the database
pub enum Cursor<'a, K, V> {
    /// Readonly access
    ReadOnly(lmdb::RoCursor<'a>),

    /// Read-write access
    ReadWrite(lmdb::RwCursor<'a>),

    /// Type information
    Phantom(Hidden<K, V>),
}

/// Iter wrapper
pub struct Iter<'a, K, V>(lmdb::Iter<'a>, Hidden<K, V>);

impl<'a, K: Key, V: Value<'a>> Iterator for Iter<'a, K, V>
where
    K: From<&'a [u8]>,
{
    type Item = (K, V);
    fn next(&mut self) -> Option<(K, V)> {
        let (k, v) = match lmdb::Iter::next(&mut self.0) {
            Some((k, v)) => (k, v),
            None => return None,
        };
        Some((K::from(k), V::from_raw(v)))
    }
}

impl<'a, K: Key, V: Value<'a>> Cursor<'a, K, V> {
    /// Returns true when the transaction is ReadOnly
    pub fn is_read_only(&self) -> bool {
        match self {
            Cursor::ReadOnly(_) => true,
            Cursor::ReadWrite(_) => false,
            Cursor::Phantom(_) => unreachable!(),
        }
    }

    pub(crate) fn read_only(cursor: lmdb::RoCursor<'a>) -> Cursor<'a, K, V> {
        Cursor::ReadOnly(cursor)
    }

    pub(crate) fn read_write(cursor: lmdb::RwCursor<'a>) -> Cursor<'a, K, V> {
        Cursor::ReadWrite(cursor)
    }

    #[inline]
    /// Iterate over all key/value pairs
    pub fn iter(&mut self) -> Iter<'a, K, V> {
        match self {
            Cursor::ReadOnly(ref mut ro) => Iter(ro.iter(), Hidden(PhantomData, PhantomData)),
            Cursor::ReadWrite(ref mut rw) => Iter(rw.iter(), Hidden(PhantomData, PhantomData)),
            Cursor::Phantom(_) => unreachable!(),
        }
    }

    #[inline]
    /// Iterate over key/values pairs starting at `key`
    pub fn iter_from(&mut self, key: &'a K) -> Iter<'a, K, V> {
        match self {
            Cursor::ReadOnly(ref mut ro) => {
                Iter(ro.iter_from(key.as_ref()), Hidden(PhantomData, PhantomData))
            }
            Cursor::ReadWrite(ref mut rw) => {
                Iter(rw.iter_from(key.as_ref()), Hidden(PhantomData, PhantomData))
            }
            Cursor::Phantom(_) => unreachable!(),
        }
    }

    #[inline]
    /// Insert a value at the current position
    pub fn set<V0: Into<V>>(&mut self, key: &'a K, value: V0) -> Result<(), Error> {
        match self {
            Cursor::ReadOnly(_) => Err(Error::ReadOnly),
            Cursor::ReadWrite(ref mut rw) => {
                rw.put(
                    &key.as_ref(),
                    &value.into().as_ref(),
                    lmdb::WriteFlags::empty(),
                )?;
                Ok(())
            }
            Cursor::Phantom(_) => unreachable!(),
        }
    }

    #[inline]
    /// Insert a value at the current position
    pub fn del(&mut self) -> Result<(), Error> {
        match self {
            Cursor::ReadOnly(_) => Err(Error::ReadOnly),
            Cursor::ReadWrite(ref mut rw) => {
                rw.del(lmdb::WriteFlags::empty())?;
                Ok(())
            }
            Cursor::Phantom(_) => unreachable!(),
        }
    }

    /// Get a value from the cursor
    pub fn get(&self, key: Option<&K>, op: CursorOp) -> Result<(Option<K>, V), Error>
    where
        K: From<&'a [u8]>,
    {
        let k = match key {
            Some(ref k) => Some(k.as_ref()),
            None => None,
        };

        match self {
            Cursor::ReadOnly(ref ro) => {
                let (_k, _v) = ro.get(k, None, op.flag())?;
                Ok((_k.map(K::from), V::from_raw(_v)))
            }
            Cursor::ReadWrite(ref rw) => {
                let (_k, _v) = rw.get(k, None, op.flag())?;
                Ok((_k.map(K::from), V::from_raw(_v)))
            }
            Cursor::Phantom(_) => unreachable!(),
        }
    }
}