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
|
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//! A demo that showcases the basic usage of iterators in rkv.
//!
//! You can test this out by running:
//!
//! cargo run --example iterator
use std::{
fs,
str,
};
use tempfile::Builder;
use rkv::{
backend::{
Lmdb,
LmdbDatabase,
LmdbEnvironment,
},
Manager,
Rkv,
SingleStore,
StoreError,
StoreOptions,
Value,
};
fn main() {
let root = Builder::new().prefix("iterator").tempdir().unwrap();
fs::create_dir_all(root.path()).unwrap();
let p = root.path();
let mut manager = Manager::<LmdbEnvironment>::singleton().write().unwrap();
let created_arc = manager.get_or_create(p, Rkv::new::<Lmdb>).unwrap();
let k = created_arc.read().unwrap();
let store = k.open_single("store", StoreOptions::create()).unwrap();
populate_store(&k, store).unwrap();
let reader = k.read().unwrap();
println!("Iterating from the beginning...");
// Reader::iter_start() iterates from the first item in the store, and
// returns the (key, value) tuples in order.
let mut iter = store.iter_start(&reader).unwrap();
while let Some(Ok((country, city))) = iter.next() {
println!("{}, {:?}", str::from_utf8(country).unwrap(), city);
}
println!();
println!("Iterating from the given key...");
// Reader::iter_from() iterates from the first key equal to or greater
// than the given key.
let mut iter = store.iter_from(&reader, "Japan").unwrap();
while let Some(Ok((country, city))) = iter.next() {
println!("{}, {:?}", str::from_utf8(country).unwrap(), city);
}
println!();
println!("Iterating from the given prefix...");
let mut iter = store.iter_from(&reader, "Un").unwrap();
while let Some(Ok((country, city))) = iter.next() {
println!("{}, {:?}", str::from_utf8(country).unwrap(), city);
}
}
fn populate_store(k: &Rkv<LmdbEnvironment>, store: SingleStore<LmdbDatabase>) -> Result<(), StoreError> {
let mut writer = k.write()?;
for (country, city) in vec![
("Canada", Value::Str("Ottawa")),
("United States of America", Value::Str("Washington")),
("Germany", Value::Str("Berlin")),
("France", Value::Str("Paris")),
("Italy", Value::Str("Rome")),
("United Kingdom", Value::Str("London")),
("Japan", Value::Str("Tokyo")),
] {
store.put(&mut writer, country, &city)?;
}
writer.commit()
}
|