use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use anyhow::Result;
use borsh::{BorshDeserialize, BorshSerialize};
#[cfg(any(test))]
use proptest_derive::Arbitrary;
use crate::{
node_type::{Node, NodeKey},
types::Version,
KeyHash, OwnedValue,
};
pub trait TreeWriter {
fn write_node_batch(&self, node_batch: &NodeBatch) -> Result<()>;
}
#[derive(Debug, Clone, PartialEq, Default, Eq, borsh::BorshSerialize, borsh::BorshDeserialize)]
pub struct NodeBatch {
nodes: BTreeMap<NodeKey, Node>,
values: BTreeMap<(Version, KeyHash), Option<OwnedValue>>,
}
impl NodeBatch {
pub fn new(
nodes: BTreeMap<NodeKey, Node>,
values: BTreeMap<(Version, KeyHash), Option<OwnedValue>>,
) -> Self {
NodeBatch { nodes, values }
}
pub fn clear(&mut self) {
self.nodes.clear();
self.values.clear()
}
pub fn get_node(&self, node_key: &NodeKey) -> Option<&Node> {
self.nodes.get(node_key)
}
pub fn nodes(&self) -> &BTreeMap<NodeKey, Node> {
&self.nodes
}
pub fn insert_node(&mut self, node_key: NodeKey, node: Node) -> Option<Node> {
self.nodes.insert(node_key, node)
}
pub fn insert_value(&mut self, version: Version, key_hash: KeyHash, value: OwnedValue) {
self.values.insert((version, key_hash), Some(value));
}
pub fn values(&self) -> &BTreeMap<(Version, KeyHash), core::option::Option<Vec<u8>>> {
&self.values
}
pub fn extend(
&mut self,
nodes: impl IntoIterator<Item = (NodeKey, Node)>,
values: impl IntoIterator<Item = ((Version, KeyHash), Option<OwnedValue>)>,
) {
self.nodes.extend(nodes);
self.values.extend(values);
}
pub fn merge(&mut self, rhs: Self) {
self.extend(rhs.nodes, rhs.values)
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.values.is_empty()
}
}
pub type StaleNodeIndexBatch = BTreeSet<StaleNodeIndex>;
#[derive(Clone, Debug, Default, Eq, PartialEq, borsh::BorshSerialize, borsh::BorshDeserialize)]
pub struct NodeStats {
pub new_nodes: usize,
pub new_leaves: usize,
pub stale_nodes: usize,
pub stale_leaves: usize,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, BorshDeserialize, BorshSerialize)]
#[cfg_attr(any(test), derive(Arbitrary))]
pub struct StaleNodeIndex {
pub stale_since_version: Version,
pub node_key: NodeKey,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, BorshSerialize, BorshDeserialize)]
pub struct TreeUpdateBatch {
pub node_batch: NodeBatch,
pub stale_node_index_batch: StaleNodeIndexBatch,
pub node_stats: Vec<NodeStats>,
}