unqlite 1.5.0

Rust `unqlite` library wrapper.
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
417
418
419
420
421
422
423
424
425
426
use crate::error::{Result, Wrap};
use crate::ffi::{
    unqlite, unqlite_kv_cursor, unqlite_kv_cursor_data, unqlite_kv_cursor_data_callback,
    unqlite_kv_cursor_delete_entry, unqlite_kv_cursor_first_entry, unqlite_kv_cursor_init,
    unqlite_kv_cursor_key, unqlite_kv_cursor_key_callback, unqlite_kv_cursor_last_entry,
    unqlite_kv_cursor_next_entry, unqlite_kv_cursor_prev_entry, unqlite_kv_cursor_release,
    unqlite_kv_cursor_reset, unqlite_kv_cursor_seek, unqlite_kv_cursor_valid_entry,
};
use std::mem;
use std::os::raw::c_void;
use std::ptr::{self, NonNull};
use crate::vars::{UNQLITE_CURSOR_MATCH_EXACT, UNQLITE_CURSOR_MATCH_GE, UNQLITE_CURSOR_MATCH_LE};
use crate::UnQLite;

/// Cursor iterator interfaces.
///
/// Cursors provide a mechanism by which you can iterate over the records in a database. Using
/// cursors, you can seek, fetch, move, and delete database records.
///
/// To iterate over database records, from the first record to the last, simply call `first`
/// to get the first valid cursor and loop to the next:
///
/// ```
/// # extern crate unqlite;
/// #
/// use unqlite::{UnQLite, Cursor};
/// #
/// # #[cfg(feature = "enable-threads")]
/// # fn main() {
/// let unqlite = UnQLite::create_temp();
/// let mut entry = unqlite.first();
///
/// loop {
///     if entry.is_none() { break; }
///
///     let record = entry.expect("valid entry");
///     println!("{:?}", record.key_value());
///     entry = record.next();
/// }
/// # }
/// # #[cfg(not(feature = "enable-threads"))]
/// # fn main() { }
/// ```
///
/// To iterate over database records, from the last record to the first, just replace `first` as
/// `last`, call `prev` instead of `next()` on `entry`.
///
/// You can also use cursors to search for records and start the iteration process from there.
/// To do that, start from [`seek`](#tymethod.seek) method.
///
/// To retrieve record key/value from a valid cursor, just use like:
///
/// ```ignore
/// let entry = ...; // Get the cursor entry
/// let key = entry.key();                   // Key only
/// let value = entry.value();               // Value only
/// let (key, value) = entry.key_value();    // Key-Value pair
/// ```
///
/// To delete a record from the database using the cursor interface, simply point to the target
/// record using `seek` and call `delete` on the `Entry` object.
///
/// A rusty `Iterator` style would perform in a short time.
pub trait Cursor {
    /// Returns the first entry.
    fn first(&self) -> Option<Entry>;

    /// Retruns the last entry.
    fn last(&self) -> Option<Entry>;

    /// Seek an entry by `key`.
    ///
    /// The `pos` `Direction` options:
    ///
    ///   * **Exact**: If the record exists, the cursor is left pointing to it,
    /// otherwise return `None`.
    ///   * **Le**: The cursor is left pointing to the largest key in the database that is smaller
    /// than `key`, If the database contains no keys smaller than `key`, it returns `None`.
    ///   * **Ge**: Oppsite to **Le**, it returns the smallest `Entry` in the database that is
    ///   larger than `key`.If the database contains no keys smaller than `key`, return `None`.
    fn seek<K: AsRef<[u8]>>(&self, key: K, pos: Direction) -> Option<Entry>;
}

impl Cursor for UnQLite {
    fn first(&self) -> Option<Entry> {
        RawCursor::init(self)
            .and_then(|cur| cur.first())
            .ok()
            .and_then(|cur| cur.valid())
            .map(Entry)
    }
    fn last(&self) -> Option<Entry> {
        RawCursor::init(self)
            .and_then(|cur| cur.last())
            .ok()
            .and_then(|cur| cur.valid())
            .map(Entry)
    }
    fn seek<K: AsRef<[u8]>>(&self, key: K, pos: Direction) -> Option<Entry> {
        RawCursor::init(self)
            .and_then(|cur| cur.seek(key, pos))
            .ok()
            .and_then(|cur| cur.valid())
            .map(Entry)
    }
}

/// A valid cursor entry of record.
pub struct Entry(RawCursor);

impl Entry {
    /// Returns the key of record
    pub fn key(&self) -> Vec<u8> {
        self.0.key().unwrap()
    }
    /// Returns the value
    pub fn value(&self) -> Vec<u8> {
        self.0.value().unwrap()
    }
    /// Returns the key-value pair
    pub fn key_value(&self) -> (Vec<u8>, Vec<u8>) {
        self.0.key_value().unwrap()
    }

    /// Use mangle function for callback of key.
    ///
    /// The callback function should define as this:
    ///
    /// ```ignore
    /// #[no_mangle]
    /// #[allow(private_no_mangle_fns)]         // <-- this should be added to avoid warning
    /// pub extern fn print_data(ptr: *const c_void, len: u32, _data: *mut c_void) -> i32 {
    ///     // Do stuff with (ptr, len)
    ///     println!("Key/Value length is {}", len);
    ///     0
    /// }
    /// ```
    pub fn key_callback(
        &self,
        func: extern "C" fn(*const c_void, u32, *mut c_void) -> i32,
        data: *mut c_void,
    ) {
        self.0.key_callback(func, data)
    }

    /// Use mangle function for callback of value
    pub fn value_callback(
        &self,
        func: extern "C" fn(*const c_void, u32, *mut c_void) -> i32,
        data: *mut c_void,
    ) {
        self.0.value_callback(func, data)
    }

    /// Goto next entry.
    ///
    /// Returns `None` if there's no valid cursors.
    pub fn next(self) -> Option<Self> {
        self.0.next().ok().and_then(|raw| raw.valid()).map(Entry)
    }

    /// Goto previous entry.
    ///
    /// Returns `None` if no valid cursors.
    pub fn prev(self) -> Option<Self> {
        self.0.prev().ok().and_then(|raw| raw.valid()).map(Entry)
    }

    /// Delete the pointed record.
    pub fn delete(self) -> Option<Self> {
        self.0.delete().ok().and_then(|raw| raw.valid()).map(Entry)
    }
}

pub enum Direction {
    /// Seek the cursor exactly
    Exact = UNQLITE_CURSOR_MATCH_EXACT as isize,
    Le = UNQLITE_CURSOR_MATCH_LE as isize,
    Ge = UNQLITE_CURSOR_MATCH_GE as isize,
}

struct RawCursor {
    engine: NonNull<unqlite>,
    cursor: NonNull<unqlite_kv_cursor>,
}

macro_rules! eval {
    ($i: ident, $($e: expr),*) => (
        unsafe {
            paste::expr! {
                [<unqlite_kv_cursor_ $i>]($($e),*)
            }
        }
    );
}

macro_rules! wrap {
    ($i: ident, $($e: expr),*) => (eval!($i, $($e),*).wrap());
}

macro_rules! wrap_in_place {
    ($self_:ident, $i: ident) => (
        wrap!($i, $self_.cursor()).map(|_| $self_)
    );
    ($self_:ident, $i: ident, $($e: expr),+) => (
        wrap!($i, $self_.cursor(), $($e),+).map(|_| $self_)
    );
}

impl RawCursor {
    /// Opening Database Cursors
    pub fn init(unqlite: &UnQLite) -> Result<Self> {
        let mut cursor: *mut unqlite_kv_cursor = unsafe { mem::MaybeUninit::uninit().assume_init() };
        wrap!(init, unqlite.as_raw_mut_ptr(), &mut cursor).map(|_| RawCursor {
            engine: unqlite.engine,
            cursor: unsafe { NonNull::new_unchecked(cursor) },
        })
    }

    #[allow(dead_code)]
    pub fn reset(self) -> Result<Self> {
        wrap_in_place!(self, reset)
    }

    pub fn release(&self) -> Result<()> {
        wrap!(release, self.engine(), self.cursor())
    }

    /// # Positioning Database Cursors
    ///
    /// * seek
    /// * first
    /// * last
    /// * next
    /// * prev
    ///
    pub fn seek<Key: AsRef<[u8]>>(self, key: Key, pos: Direction) -> Result<Self> {
        wrap_in_place!(
            self,
            seek,
            key.as_ref().as_ptr() as _,
            key.as_ref().len() as _,
            pos as _
        )
    }
    pub fn first(self) -> Result<Self> {
        wrap_in_place!(self, first_entry)
    }
    pub fn last(self) -> Result<Self> {
        wrap_in_place!(self, last_entry)
    }
    pub fn next(self) -> Result<Self> {
        wrap_in_place!(self, next_entry)
    }
    pub fn prev(self) -> Result<Self> {
        wrap_in_place!(self, prev_entry)
    }

    /// Check if the cursor reperesent a valid entry
    pub fn is_valid(&self) -> bool {
        match eval!(valid_entry, self.cursor()) {
            1 => true,
            0 => false,
            _ => unreachable!(),
        }
    }

    pub fn valid(self) -> Option<Self> {
        if self.is_valid() {
            Some(self)
        } else {
            None
        }
    }

    /// Extracting Data from Database Cursors
    pub fn key(&self) -> Result<Vec<u8>> {
        debug_assert!(self.is_valid());

        self.key_len().and_then(|mut len| {
            let ptr = unsafe { ::libc::malloc(len as _) };
            wrap!(key, self.cursor(), ptr as _, &mut len)
                .map(|_| unsafe { Vec::from_raw_parts(ptr as _, len as _, len as _) })
        })
    }

    pub fn key_callback(
        &self,
        func: extern "C" fn(*const c_void, u32, *mut c_void) -> i32,
        data: *mut c_void,
    ) {
        eval!(key_callback, self.cursor(), Some(func), data);
    }

    pub fn value(&self) -> Result<Vec<u8>> {
        debug_assert!(self.is_valid());

        self.value_len().and_then(|mut len| {
            let ptr = unsafe { ::libc::malloc(len as _) };
            wrap!(data, self.cursor(), ptr as _, &mut len)
                .map(|_| unsafe { Vec::from_raw_parts(ptr as _, len as _, len as _) })
        })
    }

    pub fn value_callback(
        &self,
        func: extern "C" fn(*const c_void, u32, *mut c_void) -> i32,
        data: *mut c_void,
    ) {
        eval!(data_callback, self.cursor(), Some(func), data);
    }

    pub fn key_value(&self) -> Result<(Vec<u8>, Vec<u8>)> {
        self.key()
            .and_then(|key| self.value().map(|value| (key, value)))
    }

    /// Deleting Records using Database Cursors
    pub fn delete(self) -> Result<Self> {
        wrap_in_place!(self, delete_entry)
    }

    pub fn key_len(&self) -> Result<i32> {
        let mut len = 0i32;
        wrap!(key, self.cursor(), ptr::null_mut() as _, &mut len).map(|_| len)
    }
    pub fn value_len(&self) -> Result<i64> {
        let mut len = 0i64;
        wrap!(data, self.cursor(), ptr::null_mut() as _, &mut len).map(|_| len)
    }

    unsafe fn cursor(&self) -> *mut unqlite_kv_cursor {
        self.cursor.as_ptr()
    }
    unsafe fn engine(&self) -> *mut unqlite {
        self.engine.as_ptr()
    }
}

impl Drop for RawCursor {
    fn drop(&mut self) {
        let _ = self.release();
    }
}

#[cfg(test)]
#[cfg(feature = "enable-threads")]
mod tests {
    use super::*;
    use std::os::raw::c_void;
    use std::ptr;
    use crate::{UnQLite, KV};

    macro_rules! _test_assert_eq {
        ($lhs:expr, ($rhs_0:expr, $rhs_1:expr)) => {{
            let kv = $lhs;
            assert_eq!(
                (
                    String::from_utf8(kv.0).unwrap(),
                    String::from_utf8(kv.1).unwrap()
                ),
                ($rhs_0.to_string(), $rhs_1.to_string())
            )
        }};
        ($lhs:expr, $rhs:expr) => {
            assert_eq!(String::from_utf8($lhs).unwrap(), $rhs.to_string())
        };
    }

    #[no_mangle]
    pub extern "C" fn print_data(ptr: *const c_void, _len: u32, _data: *mut c_void) -> i32 {
        println!("Key callback: {:?}", ptr);
        0
    }

    #[test]
    fn test_kv_cursor() {
        let unqlite = UnQLite::create_in_memory();
        unqlite.kv_store("abc", "1").unwrap();
        unqlite.kv_store("cde", "3").unwrap();
        unqlite.kv_store("bcd", "2").unwrap();

        let entry = unqlite.first().unwrap();
        _test_assert_eq!(entry.key(), "abc");
        _test_assert_eq!(entry.value(), "1");
        _test_assert_eq!(entry.key_value(), ("abc", "1"));
        let entry = entry.next().unwrap();
        _test_assert_eq!(entry.key(), "cde");
        _test_assert_eq!(entry.value(), "3");
        _test_assert_eq!(entry.key_value(), ("cde", "3"));
        let entry = entry.next().unwrap();
        entry.key_callback(print_data, ptr::null_mut());
        _test_assert_eq!(entry.key(), "bcd");
        _test_assert_eq!(entry.value(), "2");
        _test_assert_eq!(entry.key_value(), ("bcd", "2"));
        let entry = entry.next(); // Now reach the end
        assert!(entry.is_none());

        let mut entry = unqlite.last();
        loop {
            if entry.is_none() {
                break;
            }

            let current = entry.expect("valid entry");
            println!("{:?}", current.key_value());
            entry = current.prev();
        }
    }

    #[test]
    fn test_delete() {
        let uq = UnQLite::create_temp();
        uq.kv_store("abc", "1").unwrap();
        let mut entry = uq.first();
        loop {
            if entry.is_none() {
                break;
            }

            let current = entry.expect("valie_entry");
            println!("{:?}", current.key_value());
            entry = current.delete();
        }
    }
}