├── .gitignore ├── LICENSE.md ├── README.md └── btree.rs /.gitignore: -------------------------------------------------------------------------------- 1 | btree 2 | *~ -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2023 Phil Eaton 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # btree-rs 2 | 3 | Fundementally a port of 4 | https://opendatastructures.org/ods-python/14_2_B_Trees.html to Rust. 5 | 6 | 7 | ```console 8 | $ rustc btree.rs 9 | $ ./btree 10 | Inserting 10 = bif. 11 | Inserting 9 = abe. 12 | Inserting 8 = bar. 13 | Inserting 6 = blub. 14 | Inserting 3 = abc. 15 | Inserting 1 = foo. 16 | 17 | DONE INSERTING. VALIDATING. 18 | 19 | 1 = "foo" 20 | 3 = "abc" 21 | 6 = "blub" 22 | 8 = "bar" 23 | 9 = "abe" 24 | 10 = "bif" 25 | 26 | VALIDATED. NOW FOR NOT FOUND. 27 | 28 | 0: Not found 29 | 2: Not found 30 | 7: Not found 31 | 100: Not found 32 | ``` 33 | -------------------------------------------------------------------------------- /btree.rs: -------------------------------------------------------------------------------- 1 | struct BTreeNode { 2 | node_size: usize, 3 | keys: Vec, 4 | children: Vec>, 5 | values: Vec, 6 | } 7 | 8 | impl BTreeNode { 9 | fn new(node_size: usize) -> BTreeNode { 10 | return BTreeNode:: { 11 | node_size: node_size, 12 | // At the end of any operation there should only be 13 | // `node_size` keys left. However, we leave space for an 14 | // extra key for when we split. 15 | keys: Vec::::with_capacity(node_size + 1), 16 | children: Vec::>::with_capacity(node_size + 1), 17 | // As with keys, values has extra space. At the end of an 18 | // operation there should be at most `node_size` values. 19 | values: Vec::::with_capacity(node_size + 1), 20 | }; 21 | } 22 | 23 | fn display(&self, depth: usize) { 24 | for (i, key) in self.keys.iter().enumerate() { 25 | if i < self.children.len() { 26 | self.children[i].display(depth + 1); 27 | } 28 | 29 | let k = key.clone(); 30 | let v = self.values[i].clone(); 31 | println!("{}{:?} = {:?}", " ".repeat(depth * 2), k, v); 32 | } 33 | 34 | if self.children.len() > self.keys.len() { 35 | self.children[self.children.len() - 1].display(depth + 1); 36 | } 37 | } 38 | 39 | fn next_index(keys: &Vec, key: &K) -> i32 { 40 | let mut low: i32 = 0; 41 | let mut high = keys.len() as i32; 42 | while low != high { 43 | let mid = (low + high) / 2; 44 | let ordering = key.cmp(&keys[mid as usize]); 45 | if ordering == std::cmp::Ordering::Less { 46 | high = mid; 47 | } else if ordering == std::cmp::Ordering::Greater { 48 | low = mid + 1; 49 | } else { 50 | return -mid - 1; 51 | } 52 | } 53 | 54 | return low; 55 | } 56 | 57 | fn lookup_path(&self, key: &K) -> Vec { 58 | let mut stack = Vec::::new(); 59 | let mut curnode = self; 60 | loop { 61 | let i = BTreeNode::::next_index(&curnode.keys, key); 62 | if i < 0 { 63 | stack.push(-(i + 1) as usize); 64 | break; 65 | } else if (i as usize) < curnode.children.len() { 66 | curnode = &curnode.children[i as usize]; 67 | stack.push(i as usize); 68 | } else { 69 | stack.clear(); 70 | break; 71 | } 72 | } 73 | 74 | stack.reverse(); 75 | return stack; 76 | } 77 | 78 | fn lookup(&self, key: &K) -> Option { 79 | let mut path = self.lookup_path(key); 80 | let mut curnode = self; 81 | let mut valueindex = 0; 82 | while let Some(index) = path.pop() { 83 | if path.len() == 0 { 84 | valueindex = index; 85 | break; 86 | } 87 | 88 | curnode = &curnode.children[index]; 89 | } 90 | 91 | if curnode.keys[valueindex] == *key { 92 | return Some(curnode.values[valueindex].clone()); 93 | } 94 | 95 | return None; 96 | } 97 | 98 | fn split(&mut self) -> BTreeNode { 99 | let mid = self.keys.len() / 2; // Will always be floor()ed; 100 | let mut new = BTreeNode::::new(self.node_size); 101 | new.keys = self.keys[mid..].to_vec(); 102 | new.values = self.values[mid..].to_vec(); 103 | 104 | self.keys.drain(mid..); 105 | self.values.drain(mid..); 106 | 107 | return new; 108 | } 109 | 110 | fn insert_recursive(&mut self, key: K, value: V) -> Option> { 111 | let i = BTreeNode::::next_index(&self.keys, &key); 112 | // Leaf node, add to values. 113 | if self.children.len() == 0 { 114 | let i = if i < 0 { -(i + 1) } else { i } as usize; 115 | self.keys.insert(i, key); 116 | self.values.insert(i, value); 117 | } else { 118 | let i = i as usize; 119 | let children = &mut self.children; 120 | assert!(i <= children.len() + 1); 121 | // Create space for a new right-most child. 122 | if i == children.len() { 123 | children.push(BTreeNode::::new(self.node_size)); 124 | } 125 | let new_node = children[i].insert_recursive(key, value); 126 | if let Some(mut n) = new_node { 127 | let new_key = n.keys.remove(0); 128 | let new_value = n.values.remove(0); 129 | children.insert(i + 1, n); 130 | self.keys.insert(i, new_key); 131 | self.values.insert(i, new_value); 132 | } 133 | } 134 | 135 | if self.keys.len() == self.node_size + 1 { 136 | return Some(self.split()); 137 | } 138 | 139 | return None; 140 | } 141 | } 142 | 143 | struct BTree { 144 | root: BTreeNode, 145 | } 146 | 147 | impl BTree { 148 | fn new(node_size: usize) -> BTree { 149 | return BTree:: { 150 | root: BTreeNode::::new(node_size), 151 | }; 152 | } 153 | 154 | fn lookup(&self, key: &K) -> Option { 155 | return self.root.lookup(key); 156 | } 157 | 158 | fn insert(&mut self, key: K, value: V) { 159 | let mut overflow = if let Some(n) = self.root.insert_recursive(key, value) { 160 | n 161 | } else { 162 | return; 163 | }; 164 | 165 | let newroot = BTreeNode::::new(self.root.node_size); 166 | let overflow_key = overflow.keys.remove(0); 167 | let overflow_value = overflow.values.remove(0); 168 | let old = std::mem::replace(&mut self.root, newroot); 169 | self.root.children.push(old); 170 | 171 | self.root.keys.push(overflow_key); 172 | assert!(self.root.keys.len() == 1); 173 | self.root.values.push(overflow_value); 174 | assert!(self.root.values.len() == 1); 175 | 176 | self.root.children.push(overflow); 177 | assert!(self.root.children.len() == 2); 178 | } 179 | } 180 | 181 | fn debug_lookup(b: &BTree, key: i32) { 182 | let val = b.lookup(&key); 183 | if let Some(val) = val { 184 | println!("{}: {}", key, val); 185 | } else { 186 | println!("{}: Not found", key); 187 | } 188 | } 189 | 190 | fn main() { 191 | let b = &mut BTree::::new(2); 192 | let mut data = vec![ 193 | (1, String::from("foo")), 194 | (3, String::from("abc")), 195 | (6, String::from("blub")), 196 | (8, String::from("bar")), 197 | (9, String::from("abe")), 198 | (10, String::from("bif")), 199 | ]; 200 | data.reverse(); 201 | for (i, (key, value)) in data.iter().enumerate() { 202 | println!("Inserting {} = {}.", key, value); 203 | b.insert(key.clone(), value.clone()); 204 | for (key, _) in data[..i + 1].iter() { 205 | assert!(b.lookup(key).is_some()); 206 | } 207 | } 208 | 209 | println!("\nDONE INSERTING. VALIDATING.\n"); 210 | 211 | data.reverse(); 212 | for (key, _) in data.iter() { 213 | assert!(b.lookup(key).is_some()); 214 | } 215 | 216 | b.root.display(0); 217 | 218 | println!("\nVALIDATED. NOW FOR NOT FOUND.\n"); 219 | 220 | // Not found 221 | debug_lookup(b, 0); 222 | debug_lookup(b, 2); 223 | debug_lookup(b, 7); 224 | debug_lookup(b, 100); 225 | } 226 | --------------------------------------------------------------------------------