use std::fmt::Debug;
use crate::{KEY_ARRAY, POINTER_ARRAY};
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Output<K, V> {
#[default]
Null,
KeyIsNew,
KeyExists,
NewKeyPointer(Option<Item<K, V>>, Option<Pointer<K, V>>),
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Pointer<K, V> {
pub child: Box<Node<K, V>>,
pub counter: usize,
}
impl<K, V> Pointer<K, V> {
pub fn new() -> Pointer<K, V> {
Pointer {
child: Node::new(),
counter: 0,
}
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Node<K, V> {
pub keys: [Option<Item<K, V>>; KEY_ARRAY],
pub n: usize, pub leaf: bool,
pub pointers: [Option<Pointer<K, V>>; POINTER_ARRAY],
}
impl<K, V> Node<K, V> {
pub fn new() -> Box<Node<K, V>> {
Box::default()
}
}
impl<K, V> Default for Box<Node<K, V>> {
fn default() -> Self {
Box::new(Node {
keys: Default::default(),
pointers: Default::default(),
n: 0,
leaf: true,
})
}
}
impl<K, V> Node<K, V> {
pub fn is_full(&self) -> bool {
self.n == KEY_ARRAY
}
pub fn is_empty(&self) -> bool {
for item in &self.keys {
match item {
Some(_) => return false,
None => continue,
}
}
true
}
pub fn size(&self) -> usize {
let key_count = self.keys.iter().filter(|key| key.is_some()).count();
let pointer_count = self
.pointers
.iter()
.filter_map(|pointer| pointer.as_ref().map(|pointer| pointer.counter))
.sum::<usize>();
key_count + pointer_count
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Item<K, V> {
pub key: K,
pub value: V,
}
impl<K, V> Item<K, V> {
pub fn new(key: K, value: V) -> Item<K, V> {
Item { key, value }
}
}