noxu-collections 7.2.0

Iterator-based collection views for Noxu DB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Typed sorted-map view of a database.
//!
//! `StoredSortedMap<K, V, KB, VB>` adds
//! sorted-map operations (`first_key`, `last_key`, `iter_from`,
//! `iter_reverse`) on top of [`StoredMap`].  Every operation accepts
//! `txn: Option<&Transaction>`, matching the BDB-JE shape.

use noxu_bind::EntryBinding;
use noxu_db::{Database, Transaction};

use crate::error::Result;
use crate::internal::{
    ScanDirection, StartKey, cursor_endpoint, decode_key, encode_key,
    scan_iter, scan_iter_owned_start,
};
use crate::stored_iterator::StoredIterator;
use crate::stored_map::StoredMap;

/// A typed sorted-map view of a database.
///
/// All `StoredMap` operations are forwarded to the inner map; this
/// type adds sorted-map navigation (`first_key`, `last_key`,
/// `iter_from`, `iter_reverse`).
pub struct StoredSortedMap<'db, K, V, KB, VB>
where
    KB: EntryBinding<K>,
    VB: EntryBinding<V>,
{
    inner: StoredMap<'db, K, V, KB, VB>,
}

impl<'db, K, V, KB, VB> StoredSortedMap<'db, K, V, KB, VB>
where
    KB: EntryBinding<K>,
    VB: EntryBinding<V>,
{
    /// Creates a new typed sorted-map view of the given database.
    pub fn new(db: &'db Database, key_binding: KB, value_binding: VB) -> Self {
        StoredSortedMap {
            inner: StoredMap::new(db, key_binding, value_binding),
        }
    }

    /// Creates a new read-only typed sorted-map view.
    pub fn new_read_only(
        db: &'db Database,
        key_binding: KB,
        value_binding: VB,
    ) -> Self {
        StoredSortedMap {
            inner: StoredMap::new_read_only(db, key_binding, value_binding),
        }
    }

    /// Returns whether this view is read-only.
    pub fn is_read_only(&self) -> bool {
        self.inner.is_read_only()
    }

    /// Returns a reference to the underlying database.
    pub fn database(&self) -> &'db Database {
        self.inner.database()
    }

    /// Returns a reference to the inner [`StoredMap`].
    pub fn as_map(&self) -> &StoredMap<'db, K, V, KB, VB> {
        &self.inner
    }

    /// Inserts or updates a key-value pair.  See [`StoredMap::put`].
    pub fn put(
        &self,
        txn: Option<&Transaction>,
        key: &K,
        value: &V,
    ) -> Result<Option<V>> {
        self.inner.put(txn, key, value)
    }

    /// Retrieves the value associated with the given key.
    pub fn get(&self, txn: Option<&Transaction>, key: &K) -> Result<Option<V>> {
        self.inner.get(txn, key)
    }

    /// Removes the entry for `key`.
    pub fn remove(
        &self,
        txn: Option<&Transaction>,
        key: &K,
    ) -> Result<Option<V>> {
        self.inner.remove(txn, key)
    }

    /// Returns whether `key` is present.
    pub fn contains_key(
        &self,
        txn: Option<&Transaction>,
        key: &K,
    ) -> Result<bool> {
        self.inner.contains_key(txn, key)
    }

    /// Returns the number of records.
    pub fn len(&self, txn: Option<&Transaction>) -> Result<usize> {
        self.inner.len(txn)
    }

    /// Returns whether the database is empty.
    pub fn is_empty(&self, txn: Option<&Transaction>) -> Result<bool> {
        self.inner.is_empty(txn)
    }

    /// Removes every record.
    pub fn clear(&self, txn: Option<&Transaction>) -> Result<()> {
        self.inner.clear(txn)
    }

    /// Lazy forward iterator over every (key, value) pair (review P1-7).
    /// See [`StoredMap::iter`](crate::StoredMap::iter) for the
    /// laziness/lifetime contract.
    pub fn iter<'a>(
        &'a self,
        txn: Option<&'a Transaction>,
    ) -> Result<impl Iterator<Item = Result<(K, V)>> + 'a>
    where
        K: 'a,
        V: 'a,
    {
        self.inner.iter(txn)
    }

    /// Lazy forward iterator over keys.
    pub fn keys<'a>(
        &'a self,
        txn: Option<&'a Transaction>,
    ) -> Result<impl Iterator<Item = Result<K>> + 'a>
    where
        K: 'a,
        V: 'a,
    {
        self.inner.keys(txn)
    }

    /// Lazy forward iterator over values.
    pub fn values<'a>(
        &'a self,
        txn: Option<&'a Transaction>,
    ) -> Result<impl Iterator<Item = Result<V>> + 'a>
    where
        K: 'a,
        V: 'a,
    {
        self.inner.values(txn)
    }

    /// Eager snapshot iterator over every (key, value) pair.
    /// See [`StoredMap::snapshot`](crate::StoredMap::snapshot).
    pub fn snapshot(
        &self,
        txn: Option<&Transaction>,
    ) -> Result<StoredIterator<(K, V)>> {
        self.inner.snapshot(txn)
    }

    /// Eager snapshot iterator over keys.
    pub fn keys_snapshot(
        &self,
        txn: Option<&Transaction>,
    ) -> Result<StoredIterator<K>> {
        self.inner.keys_snapshot(txn)
    }

    /// Eager snapshot iterator over values.
    pub fn values_snapshot(
        &self,
        txn: Option<&Transaction>,
    ) -> Result<StoredIterator<V>> {
        self.inner.values_snapshot(txn)
    }

    /// Returns the smallest key, or `None` if the database is empty.
    pub fn first_key(&self, txn: Option<&Transaction>) -> Result<Option<K>> {
        Ok(self.first_entry(txn)?.map(|(k, _)| k))
    }

    /// Returns the largest key, or `None` if the database is empty.
    pub fn last_key(&self, txn: Option<&Transaction>) -> Result<Option<K>> {
        Ok(self.last_entry(txn)?.map(|(k, _)| k))
    }

    /// Returns the (key, value) pair with the smallest key, or `None`.
    pub fn first_entry(
        &self,
        txn: Option<&Transaction>,
    ) -> Result<Option<(K, V)>> {
        cursor_endpoint(
            self.inner.database(),
            txn,
            self.inner.key_binding(),
            self.inner.value_binding(),
            noxu_db::Get::First,
        )
    }

    /// Returns the (key, value) pair with the largest key, or `None`.
    pub fn last_entry(
        &self,
        txn: Option<&Transaction>,
    ) -> Result<Option<(K, V)>> {
        cursor_endpoint(
            self.inner.database(),
            txn,
            self.inner.key_binding(),
            self.inner.value_binding(),
            noxu_db::Get::Last,
        )
    }

    /// Lazy forward iterator starting at `start_key` (inclusive lower
    /// bound).
    ///
    /// Encodes `start_key` via the key binding and walks the cursor
    /// from the smallest key `>= encoded(start_key)`.  Lazy (review
    /// P1-7); see [`iter`](Self::iter) for the lifetime contract.
    pub fn iter_from<'a>(
        &'a self,
        txn: Option<&'a Transaction>,
        start_key: &K,
    ) -> Result<impl Iterator<Item = Result<(K, V)>> + 'a>
    where
        K: 'a,
        V: 'a,
    {
        let start_entry = encode_key(self.inner.key_binding(), start_key)?;
        let bytes = start_entry.data_opt().unwrap_or(&[]).to_vec();
        scan_iter_owned_start(
            self.inner.database(),
            txn,
            Some(bytes),
            ScanDirection::Forward,
            self.inner.key_binding(),
            self.inner.value_binding(),
            |k, v| (k, v),
        )
    }

    /// Lazy reverse iterator over every (key, value) pair (largest key
    /// first).  See [`iter`](Self::iter) for the lifetime contract.
    pub fn iter_reverse<'a>(
        &'a self,
        txn: Option<&'a Transaction>,
    ) -> Result<impl Iterator<Item = Result<(K, V)>> + 'a>
    where
        K: 'a,
        V: 'a,
    {
        scan_iter(
            self.inner.database(),
            txn,
            StartKey::None,
            ScanDirection::Reverse,
            self.inner.key_binding(),
            self.inner.value_binding(),
            |k, v| (k, v),
        )
    }

    /// Returns the smallest key strictly greater than `key`, or `None`.
    ///
    /// Useful for stepping through keys when only the bindings are
    /// available.  Walks forward from `Get::First` and skips keys
    /// `<= bound` (the `noxu-dbi` `SearchGte`-then-`Next` path is
    /// known to mis-position; see `internal::scan_records` for the
    /// rationale).
    pub fn higher_key(
        &self,
        txn: Option<&Transaction>,
        key: &K,
    ) -> Result<Option<K>> {
        let key_entry = encode_key(self.inner.key_binding(), key)?;
        let bound = key_entry.data_opt().unwrap_or(&[]).to_vec();

        let mut cursor =
            crate::internal::open_cursor(self.inner.database(), txn, None)?;
        let mut k_buf = noxu_db::DatabaseEntry::new();
        let mut d_buf = noxu_db::DatabaseEntry::new();
        let mut status =
            cursor.get(&mut k_buf, &mut d_buf, noxu_db::Get::First, None)?;
        let mut result: Option<K> = None;
        while matches!(status, noxu_db::OperationStatus::Success) {
            let cur = k_buf.data_opt().unwrap_or(&[]);
            if cur > bound.as_slice() {
                result = Some(decode_key(self.inner.key_binding(), &k_buf)?);
                break;
            }
            status =
                cursor.get(&mut k_buf, &mut d_buf, noxu_db::Get::Next, None)?;
        }
        cursor.close()?;
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use noxu_bind::{IntBinding, StringBinding};
    use noxu_db::{DatabaseConfig, Environment, EnvironmentConfig};
    use tempfile::TempDir;

    fn setup() -> (TempDir, Environment, noxu_db::Database) {
        let td = TempDir::new().unwrap();
        let env = Environment::open(
            EnvironmentConfig::new(td.path().to_path_buf())
                .with_allow_create(true)
                .with_transactional(true),
        )
        .unwrap();
        let db = env
            .open_database(
                None,
                "ssm",
                &DatabaseConfig::new()
                    .with_allow_create(true)
                    .with_transactional(true),
            )
            .unwrap();
        (td, env, db)
    }

    fn populate(
        map: &StoredSortedMap<'_, i32, String, IntBinding, StringBinding>,
    ) {
        for (k, v) in
            [(3, "three"), (1, "one"), (2, "two"), (5, "five"), (4, "four")]
        {
            map.put(None, &k, &v.to_string()).unwrap();
        }
    }

    #[test]
    fn first_and_last_key() {
        let (_td, _env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);
        populate(&map);

        assert_eq!(map.first_key(None).unwrap(), Some(1));
        assert_eq!(map.last_key(None).unwrap(), Some(5));
    }

    #[test]
    fn first_and_last_entry() {
        let (_td, _env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);
        populate(&map);

        assert_eq!(
            map.first_entry(None).unwrap(),
            Some((1, "one".to_string())),
        );
        assert_eq!(
            map.last_entry(None).unwrap(),
            Some((5, "five".to_string())),
        );
    }

    #[test]
    fn first_last_empty() {
        let (_td, _env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);
        assert_eq!(map.first_key(None).unwrap(), None);
        assert_eq!(map.last_key(None).unwrap(), None);
        assert_eq!(map.first_entry(None).unwrap(), None);
        assert_eq!(map.last_entry(None).unwrap(), None);
    }

    #[test]
    fn iter_reverse() {
        let (_td, _env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);
        populate(&map);

        let items: Vec<_> =
            map.iter_reverse(None).unwrap().map(Result::unwrap).collect();
        let keys: Vec<i32> = items.iter().map(|(k, _)| *k).collect();
        assert_eq!(keys, vec![5, 4, 3, 2, 1]);
    }

    #[test]
    fn iter_from_inclusive() {
        let (_td, _env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);
        populate(&map);

        let items: Vec<_> =
            map.iter_from(None, &3).unwrap().map(Result::unwrap).collect();
        let keys: Vec<i32> = items.iter().map(|(k, _)| *k).collect();
        assert_eq!(keys, vec![3, 4, 5]);
    }

    #[test]
    fn iter_from_between_keys() {
        let (_td, _env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);
        // 1, 2, 4, 5
        for k in [1, 2, 4, 5] {
            map.put(None, &k, &format!("{k}")).unwrap();
        }
        // start key 3 → smallest key >= 3 is 4
        let items: Vec<_> =
            map.iter_from(None, &3).unwrap().map(Result::unwrap).collect();
        let keys: Vec<i32> = items.iter().map(|(k, _)| *k).collect();
        assert_eq!(keys, vec![4, 5]);
    }

    #[test]
    fn higher_key() {
        let (_td, _env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);
        populate(&map);

        assert_eq!(map.higher_key(None, &1).unwrap(), Some(2));
        assert_eq!(map.higher_key(None, &3).unwrap(), Some(4));
        assert_eq!(map.higher_key(None, &5).unwrap(), None);
        // For a key not in the map, we get the smallest key strictly
        // greater than it.  IntBinding sorts ints two's-complement so
        // 0 < 1 < ... < 5.
        assert_eq!(map.higher_key(None, &0).unwrap(), Some(1));
    }

    #[test]
    fn participates_in_user_txn() {
        let (_td, env, db) = setup();
        let map: StoredSortedMap<'_, i32, String, _, _> =
            StoredSortedMap::new(&db, IntBinding, StringBinding);

        let txn = env.begin_transaction(None).unwrap();
        map.put(Some(&txn), &1, &"one".to_string()).unwrap();
        map.put(Some(&txn), &2, &"two".to_string()).unwrap();
        assert_eq!(map.first_key(Some(&txn)).unwrap(), Some(1));
        txn.commit().unwrap();

        assert_eq!(map.first_key(None).unwrap(), Some(1));
    }
}