#![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, } pub struct BlockInfo { exists: bool, parent: Option, 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 { 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 { 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 { 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> 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()), ] } }