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
|
#![allow(clippy::from_over_into)]
use crate::common::ip::Addr;
use crate::common::ip::Block;
use crate::common::ip::Meta;
use crate::common::trie;
use std::collections::HashMap;
pub struct Database {
pub trie: trie::Trie,
pub meta: HashMap<String, String>,
}
pub struct BlockInfo {
exists: bool,
parent: Option<Block>,
child_count: usize,
start: Addr,
end: Addr,
size: u128,
}
impl Database {
pub fn new() -> Self {
Database {
trie: trie::Trie::new(),
meta: HashMap::new(),
}
}
pub fn get(&self, block: &Block) -> Option<Block> {
self.trie.find(block)
}
/// Sets `meta` on the given `block`. Replaces the metadata if `block` already exists.
/// Creates the block if it doesn't exist.
pub fn set(&mut self, block: Block, meta: Meta) {
self.trie.insert(block, meta);
}
/// Returns the parent of the given block.
///
/// Returns `None` if the block has no parents.
pub fn parent(&self, block: &Block) -> Option<Block> {
self.trie.parent(block)
}
/// Returns the children of the given block.
///
/// Returns an empty `Vec` if the given block has no children.
pub fn children(&self, block: &Block) -> Vec<Block> {
self.trie.children(block)
}
pub fn info(&self, block: &Block) -> BlockInfo {
BlockInfo {
exists: self.exists(block),
parent: self.trie.parent(block),
child_count: self.trie.children(block).len(),
start: block.start(),
end: block.end(),
size: block.size(),
}
}
pub fn del(&self, _block: &Block) -> Option<()> {
None
}
pub fn exists(&self, block: &Block) -> bool {
self.trie.find(block).is_some()
}
}
// Into
impl Into<Vec<(&str, String)>> for BlockInfo {
fn into(self) -> Vec<(&'static str, String)> {
vec![
("EXISTS", self.exists.to_string()),
(
"PARENT",
self.parent.map(|x| x.to_string()).unwrap_or_default(),
),
("CHILD-COUNT", self.child_count.to_string()),
("RANGE", format!("{} - {}", self.start, self.end)),
("SIZE", self.size.to_string()),
]
}
}
|