aboutsummaryrefslogtreecommitdiff
path: root/src/common/db.rs
diff options
context:
space:
mode:
authorevuez <julien@mulga.net>2022-11-26 15:38:06 -0500
committerevuez <julien@mulga.net>2024-04-03 22:44:12 +0200
commit86098797034cbc7eb6db0cee54e17f8dcaedbc5d (patch)
tree29b6225ead843eb9022296a54657bbadfa1c4da0 /src/common/db.rs
downloadblom-86098797034cbc7eb6db0cee54e17f8dcaedbc5d.tar.gz
Initial commitHEADmain
Diffstat (limited to 'src/common/db.rs')
-rw-r--r--src/common/db.rs89
1 files changed, 89 insertions, 0 deletions
diff --git a/src/common/db.rs b/src/common/db.rs
new file mode 100644
index 0000000..77a1752
--- /dev/null
+++ b/src/common/db.rs
@@ -0,0 +1,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()),
+ ]
+ }
+}