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
use libriakv::RiaKV;

use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;

#[cfg(target_os = "windows")]
const USAGE: &str = "
CLI client for RiaKV key value store with persistent index.

Usage:
    riakv_mem.exe STORAGE_FILE INDEX_FILE get KEY
    riakv_mem.exe STORAGE_FILE INDEX_FILE delete KEY
    riakv_mem.exe STORAGE_FILE INDEX_FILE insert KEY VALUE
    riakv_mem.exe STORAGE_FILE INDEX_FILE update KEY VALUE
";

#[cfg(target_os = "linux")]
const USAGE: &str = "
CLI client for RiaKV key value store with persistent index.

Usage:
    riakv_mem STORAGE_FILE INDEX_FILE get KEY
    riakv_mem STORAGE_FILE INDEX_FILE delete KEY
    riakv_mem STORAGE_FILE INDEX_FILE insert KEY VALUE
    riakv_mem STORAGE_FILE INDEX_FILE update KEY VALUE
";

fn index_file_from_path(path: &Path) -> io::Result<File> {
    OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open(path)
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let storage_fname = args.get(1).expect(&USAGE);
    let index_fname = args.get(2).expect(&USAGE);

    let action = args.get(3).expect(&USAGE).as_ref();
    let key = args.get(4).expect(&USAGE).as_ref();
    let maybe_value = args.get(5);

    let storage_path = Path::new(storage_fname);
    let mut store = RiaKV::open_from_file_at_path(storage_path).expect("unable to open file");

    let index_path = Path::new(index_fname);
    let mut index_file = index_file_from_path(index_path).expect("unable to open index file");
    store
        .load_index(&mut index_file)
        .expect("unable to deserialize index");

    match action {
        "get" => match store.get(key).unwrap() {
            None => eprintln!("{:?} not found", key),
            Some(value) => println!("{:?}", value),
        },

        "delete" => store.delete(key).unwrap(),

        "insert" => {
            let value = maybe_value.expect(&USAGE).as_ref();
            store.insert(key, value).unwrap()
        }

        "update" => {
            let value = maybe_value.expect(&USAGE).as_ref();
            store.update(key, value).unwrap()
        }
        _ => eprintln!("{}", &USAGE),
    }

    store
        .persist_index(&mut index_file)
        .expect("unable to serialize index");
}