-
Notifications
You must be signed in to change notification settings - Fork 485
Expand file tree
/
Copy pathakv_disk.rs
More file actions
83 lines (68 loc) · 2.17 KB
/
akv_disk.rs
File metadata and controls
83 lines (68 loc) · 2.17 KB
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
use libactionkv::ActionKV;
use std::collections::HashMap;
#[cfg(target_os = "windows")]
const USAGE: &str = "
Usage:
akv_disk.exe FILE get KEY
akv_disk.exe FILE delete KEY
akv_disk.exe FILE insert KEY VALUE
akv_disk.exe FILE update KEY VALUE
";
#[cfg(not(target_os = "windows"))]
const USAGE: &str = "
Usage:
akv_disk FILE get KEY
akv_disk FILE delete KEY
akv_disk FILE insert KEY VALUE
akv_disk FILE update KEY VALUE
";
type ByteStr = [u8];
type ByteString = Vec<u8>;
fn store_index_on_disk(a: &mut ActionKV, index_key: &ByteStr) {
a.index.remove(index_key);
let index_as_bytes = bincode::serialize(&a.index).unwrap();
a.index = std::collections::HashMap::new();
a.insert(index_key, &index_as_bytes).unwrap();
}
fn main() {
const INDEX_KEY: &ByteStr = b"+index";
let args: Vec<String> = std::env::args().collect();
let fname = args.get(1).expect(&USAGE);
let action = args.get(2).expect(&USAGE).as_ref();
let key = args.get(3).expect(&USAGE).as_ref();
let maybe_value = args.get(4);
let path = std::path::Path::new(&fname);
let mut a = ActionKV::open(path).expect("unable to open file");
a.load().expect("unable to load data");
match action {
"get" => {
let index_as_bytes = a.get(&INDEX_KEY)
.unwrap()
.unwrap();
let index_decoded = bincode::deserialize(&index_as_bytes);
let index: HashMap<ByteString, u64> = index_decoded.unwrap();
match index.get(key) {
None => eprintln!("{:?} not found", key),
Some(&i) => {
let kv = a.get_at(i).unwrap();
println!("{:?}", kv.value) <1>
}
}
}
"delete" => {
a.delete(key).unwrap();
store_index_on_disk(&mut a, INDEX_KEY); <2>
}
"insert" => {
let value = maybe_value.expect(&USAGE).as_ref();
a.insert(key, value).unwrap();
store_index_on_disk(&mut a, INDEX_KEY); <2>
}
"update" => {
let value = maybe_value.expect(&USAGE).as_ref();
a.update(key, value).unwrap();
store_index_on_disk(&mut a, INDEX_KEY); <2>
}
_ => eprintln!("{}", &USAGE),
}
}