| 1 |
// Any copyright is dedicated to the Public Domain. |
| 2 |
// http://creativecommons.org/publicdomain/zero/1.0/ |
| 3 |
|
| 4 |
//! A demo that showcases the basic usage of iterators in rkv. |
| 5 |
//! |
| 6 |
//! You can test this out by running: |
| 7 |
//! |
| 8 |
//! cargo run --example iterator |
| 9 |
|
| 10 |
use std::{fs, str}; |
| 11 |
|
| 12 |
use tempfile::Builder; |
| 13 |
|
| 14 |
use rkv::{ |
| 15 |
backend::{SafeMode, SafeModeDatabase, SafeModeEnvironment}, |
| 16 |
Manager, Rkv, SingleStore, StoreError, StoreOptions, Value, |
| 17 |
}; |
| 18 |
|
| 19 |
fn main() { |
| 20 |
let root = Builder::new().prefix("iterator").tempdir().unwrap(); |
| 21 |
fs::create_dir_all(root.path()).unwrap(); |
| 22 |
let p = root.path(); |
| 23 |
|
| 24 |
let mut manager = Manager::<SafeModeEnvironment>::singleton().write().unwrap(); |
| 25 |
let created_arc = manager.get_or_create(p, Rkv::new::<SafeMode>).unwrap(); |
| 26 |
let k = created_arc.read().unwrap(); |
| 27 |
let store = k.open_single("store", StoreOptions::create()).unwrap(); |
| 28 |
|
| 29 |
populate_store(&k, store).unwrap(); |
| 30 |
|
| 31 |
let reader = k.read().unwrap(); |
| 32 |
|
| 33 |
println!("Iterating from the beginning..."); |
| 34 |
// Reader::iter_start() iterates from the first item in the store, and |
| 35 |
// returns the (key, value) tuples in order. |
| 36 |
let mut iter = store.iter_start(&reader).unwrap(); |
| 37 |
while let Some(Ok((country, city))) = iter.next() { |
| 38 |
let country = str::from_utf8(country).unwrap(); |
| 39 |
println!("{country}, {city:?}"); |
| 40 |
} |
| 41 |
|
| 42 |
println!(); |
| 43 |
println!("Iterating from the given key..."); |
| 44 |
// Reader::iter_from() iterates from the first key equal to or greater |
| 45 |
// than the given key. |
| 46 |
let mut iter = store.iter_from(&reader, "Japan").unwrap(); |
| 47 |
while let Some(Ok((country, city))) = iter.next() { |
| 48 |
println!("{}, {city:?}", str::from_utf8(country).unwrap()); |
| 49 |
} |
| 50 |
|
| 51 |
println!(); |
| 52 |
println!("Iterating from the given prefix..."); |
| 53 |
let mut iter = store.iter_from(&reader, "Un").unwrap(); |
| 54 |
while let Some(Ok((country, city))) = iter.next() { |
| 55 |
println!("{}, {city:?}", str::from_utf8(country).unwrap()); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
fn populate_store( |
| 60 |
k: &Rkv<SafeModeEnvironment>, |
| 61 |
store: SingleStore<SafeModeDatabase>, |
| 62 |
) -> Result<(), StoreError> { |
| 63 |
let mut writer = k.write()?; |
| 64 |
for (country, city) in vec![ |
| 65 |
("Canada", Value::Str("Ottawa")), |
| 66 |
("United States of America", Value::Str("Washington")), |
| 67 |
("Germany", Value::Str("Berlin")), |
| 68 |
("France", Value::Str("Paris")), |
| 69 |
("Italy", Value::Str("Rome")), |
| 70 |
("United Kingdom", Value::Str("London")), |
| 71 |
("Japan", Value::Str("Tokyo")), |
| 72 |
] { |
| 73 |
store.put(&mut writer, country, &city)?; |
| 74 |
} |
| 75 |
writer.commit() |
| 76 |
} |