btree
Some checks failed
Rust CI / Test Suite (push) Failing after 2s
Rust CI / Clippy (push) Failing after 4s

This commit is contained in:
cscherr 2025-06-04 18:06:01 +02:00
parent dd51d8d1d1
commit 325c491691
Signed by: cscherrNT
GPG key ID: 8E2B45BC51A27EA7
2 changed files with 55 additions and 57 deletions

View file

@ -1,66 +1,61 @@
#[derive(Clone, Debug, Default)]
pub struct BTree<K: Ord, V> {
root: Option<Node<K, V>>,
len: usize,
use crate::vec::Vec;
#[derive(Clone, Debug)]
pub struct BTree<T> {
root: Node<T>,
degree: usize,
}
#[derive(Clone, Debug)]
pub struct Node<K, V> {
key: K,
value: V,
struct Node<T> {
keys: Vec<T>,
children: Vec<Node<T>>,
}
impl<K, V> Node<K, V> {
pub fn new_root(key: K, value: V) -> Self {
Node { key, value }
}
}
impl<K: Ord, V> BTree<K, V> {
pub fn new() -> Self {
Self { root: None, len: 0 }
}
pub fn clear(&mut self) {
self.root = None;
self.len = 0;
}
pub fn rebalance() {
todo!()
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
if let Some(root) = &self.root {
todo!()
} else {
let new_node = Node::new_root(key, value);
self.root = Some(new_node);
None
impl<T> Node<T>
where
T: Ord,
{
fn new(degree: usize, keys: Option<Vec<T>>, children: Option<Vec<Node<T>>>) -> Self {
Node {
keys: match keys {
Some(keys) => keys,
None => Vec::with_capacity(degree - 1),
},
children: match children {
Some(children) => children,
None => Vec::with_capacity(degree),
},
}
}
pub fn remove(&mut self, key: K) -> Option<V> {
fn is_leaf(&self) -> bool {
self.children.is_empty()
}
}
impl<T: Ord> BTree<T> {
pub fn new(branch_factor: usize) -> Self {
let degree = 2 * branch_factor;
Self {
root: Node::new(degree, None, None),
degree,
}
}
pub fn clear(&mut self) {
self.root = Node::new(self.degree, None, None);
}
fn rebalance() {
todo!()
}
pub fn has_key(&self, key: K) -> bool {
pub fn insert(&mut self, value: T) -> Option<T> {
todo!()
}
pub fn get(&self, key: K) -> Option<&V> {
todo!()
}
pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
todo!()
}
pub fn get_node(&self, key: K) -> Option<&Node<K, V>> {
todo!()
}
pub fn get_node_mut(&mut self, key: K) -> Option<&mut Node<K, V>> {
pub fn has(&self, value: T) -> bool {
todo!()
}
}
@ -70,18 +65,20 @@ mod test {
use super::*;
#[test]
fn test_create() {
let _tree = BTree::<u32, u32>::default();
let _tree = BTree::<u32>::new();
}
#[test]
fn test_insert() {
let mut tree = BTree::<u32, &str>::default();
tree.insert(19, "19");
tree.insert(9, "09");
tree.insert(14, "14");
let mut tree = BTree::<u32>::new();
let data = &[19, 125, 25, 16, 2, 73, 384, 435, 12924, 42, 125251, 2548];
assert!(tree.get(19).is_some_and(|s| *s == "19"));
assert!(tree.get(9).is_some_and(|s| *s == "09"));
assert!(tree.get(14).is_some_and(|s| *s == "14"));
for d in data {
assert!(tree.insert(*d).is_none())
}
for d in data {
assert!(tree.has(*d))
}
}
}

View file

@ -1,2 +1,3 @@
pub mod btree;
pub mod raw_vec;
pub mod vec;