1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
extern crate crossbeam_epoch; pub mod error; pub mod leaf; pub mod leafnode; pub mod node; use crossbeam_epoch::{Atomic, Guard, Owned}; use error::{InsertError, RemoveError, SearchError}; use leaf::{Leaf, LeafScanner}; use node::Node; use std::fmt; use std::sync::atomic::Ordering::{Acquire, Relaxed}; /// A scalable concurrent tree map implementation. /// /// scc::TreeIndex is a B+ tree variant that is optimized for read operations. /// Read operations, such as scan, read, are neither blocked nor interrupted by all the other types of operations. /// Write operations, such as insert, remove, do not block if they do not entail structural changes to the tree. pub struct TreeIndex<K, V> where K: Clone + Ord + Send + Sync, V: Clone + Send + Sync, { root: Atomic<Node<K, V>>, } impl<K, V> Default for TreeIndex<K, V> where K: Clone + Ord + Send + Sync, V: Clone + Send + Sync, { /// Creates a TreeIndex instance with the default parameters. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = Default::default(); /// /// let result = treeindex.read(&1, |key, value| *value); /// assert!(result.is_none()); /// ``` fn default() -> Self { TreeIndex::new() } } impl<K, V> TreeIndex<K, V> where K: Clone + Ord + Send + Sync, V: Clone + Send + Sync, { /// Creates an empty TreeIndex instance. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// let result = treeindex.read(&1, |key, value| *value); /// assert!(result.is_none()); /// ``` pub fn new() -> TreeIndex<K, V> { TreeIndex { root: Atomic::null(), } } /// Inserts a a key-value pair. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// let result = treeindex.insert(1, 10); /// assert!(result.is_ok()); /// /// let result = treeindex.insert(1, 11); /// assert_eq!(result.err().unwrap(), (1, 11)); /// /// let result = treeindex.read(&1, |key, value| *value); /// assert_eq!(result.unwrap(), 10); /// ``` pub fn insert(&self, mut key: K, mut value: V) -> Result<(), (K, V)> { loop { let guard = crossbeam_epoch::pin(); let mut root_node = self.root.load(Acquire, &guard); if root_node.is_null() { let new_root = Owned::new(Node::new(0, true)); match self .root .compare_and_set(root_node, new_root, Relaxed, &guard) { Ok(new_root) => root_node = new_root, Err(_) => continue, } } let root_node_ref = unsafe { root_node.deref() }; match root_node_ref.insert(key, value, &guard) { Ok(_) => return Ok(()), Err(error) => match error { InsertError::Duplicated(entry) => return Err(entry), InsertError::Full(entry) => { root_node_ref.split_root(&self.root, &guard); key = entry.0; value = entry.1; } InsertError::Retry(entry) => { key = entry.0; value = entry.1; } }, } } } /// Removes a key-value pair. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// let result = treeindex.remove(&1); /// assert!(!result); /// /// let result = treeindex.insert(1, 10); /// assert!(result.is_ok()); /// /// let result = treeindex.remove(&1); /// assert!(result); /// ``` pub fn remove(&self, key: &K) -> bool { let mut has_been_removed = false; let guard = crossbeam_epoch::pin(); let mut root_node = self.root.load(Acquire, &guard); loop { if root_node.is_null() { return has_been_removed; } let root_node_ref = unsafe { root_node.deref() }; match root_node_ref.remove(key, &guard) { Ok(removed) => return removed || has_been_removed, Err(remove_error) => match remove_error { RemoveError::Coalesce(removed) => { if removed && !has_been_removed { has_been_removed = true; } Node::update_root(root_node, &self.root, &guard); return has_been_removed; } RemoveError::Retry(removed) => { if removed && !has_been_removed { has_been_removed = true; } } }, }; let root_node_new = self.root.load(Acquire, &guard); root_node = root_node_new; } } /// Reads a key-value pair. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// let result = treeindex.read(&1, |key, value| *value); /// assert!(result.is_none()); /// /// let result = treeindex.insert(1, 10); /// assert!(result.is_ok()); /// /// let result = treeindex.read(&1, |key, value| *value); /// assert_eq!(result.unwrap(), 10); /// ``` pub fn read<U, F: FnOnce(&K, &V) -> U>(&self, key: &K, f: F) -> Option<U> { let guard = crossbeam_epoch::pin(); loop { let root_node = self.root.load(Acquire, &guard); if root_node.is_null() { return None; } match unsafe { root_node.deref().search(key, &guard) } { Ok(result) => { if let Some(value) = result { return Some(f(key, value)); } else { return None; } } Err(err) => match err { SearchError::Retry => continue, }, } } } /// Clears the TreeIndex. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// for key in 0..16u64 { /// let result = treeindex.insert(key, 10); /// assert!(result.is_ok()); /// } /// /// treeindex.clear(); /// /// let result = treeindex.len(); /// assert_eq!(result, 0); /// ``` pub fn clear(&self) { let guard = crossbeam_epoch::pin(); Node::remove_root(&self.root, &guard); } /// Returns the size of the TreeIndex. /// /// It internally scans all the leaf nodes, and therefore the time complexity is O(N). /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// for key in 0..16u64 { /// let result = treeindex.insert(key, 10); /// assert!(result.is_ok()); /// } /// /// let result = treeindex.len(); /// assert_eq!(result, 16); /// ``` pub fn len(&self) -> usize { self.iter().count() } /// Returns the depth of the TreeIndex. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// for key in 0..16u64 { /// let result = treeindex.insert(key, 10); /// assert!(result.is_ok()); /// } /// /// let result = treeindex.depth(); /// assert_eq!(result, 1); /// ``` pub fn depth(&self) -> usize { let guard = crossbeam_epoch::pin(); let root_node = self.root.load(Acquire, &guard); if !root_node.is_null() { unsafe { root_node.deref().floor() + 1 } } else { 0 } } /// Returns a Scanner. /// /// The returned Scanner starts scanning from the minimum key-value pair. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// let result = treeindex.insert(1, 10); /// assert!(result.is_ok()); /// /// let result = treeindex.insert(2, 11); /// assert!(result.is_ok()); /// /// let result = treeindex.insert(3, 13); /// assert!(result.is_ok()); /// /// let mut scanner = treeindex.iter(); /// assert_eq!(scanner.next().unwrap(), (&1, &10)); /// assert_eq!(scanner.next().unwrap(), (&2, &11)); /// assert_eq!(scanner.next().unwrap(), (&3, &13)); /// assert!(scanner.next().is_none()); /// ``` pub fn iter(&self) -> Scanner<K, V> { Scanner::new(self) } /// Returns a Scanner that starts from the given key if it exists. /// /// In case the key does not exist, and there is a key that is greater than the given key, /// a Scanner pointing to the key is returned. /// /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// let result = treeindex.insert(1, 10); /// assert!(result.is_ok()); /// /// let result = treeindex.insert(2, 11); /// assert!(result.is_ok()); /// /// let result = treeindex.insert(3, 13); /// assert!(result.is_ok()); /// /// if let Some(mut scanner) = treeindex.from(&2) { /// assert_eq!(scanner.get().unwrap(), (&2, &11)); /// assert_eq!(scanner.next().unwrap(), (&3, &13)); /// assert!(scanner.next().is_none()); /// } /// ``` pub fn from(&self, key: &K) -> Option<Scanner<K, V>> { Scanner::from(self, key) } } impl<K, V> TreeIndex<K, V> where K: Clone + fmt::Display + Ord + Send + Sync, V: Clone + fmt::Display + Send + Sync, { /// Prints the TreeIndex contents to the given output in the DOT language. /// /// # Examples /// ``` /// use scc::TreeIndex; /// /// let treeindex: TreeIndex<u64, u32> = TreeIndex::new(); /// /// let result = treeindex.insert(1, 10); /// assert!(result.is_ok()); /// /// treeindex.print(&mut std::io::stdout()); /// ``` pub fn print<T: std::io::Write>(&self, output: &mut T) -> std::io::Result<()> { output.write_fmt(format_args!("digraph {{\n"))?; let guard = crossbeam_epoch::pin(); let root_node = self.root.load(Acquire, &guard); if !root_node.is_null() { unsafe { root_node.deref().print(output, &guard) }? } output.write_fmt(format_args!("}}")) } } impl<K, V> Drop for TreeIndex<K, V> where K: Clone + Ord + Send + Sync, V: Clone + Send + Sync, { fn drop(&mut self) { self.clear(); } } /// Scanner implements Iterator for TreeIndex. pub struct Scanner<'a, K, V> where K: Clone + Ord + Send + Sync, V: Clone + Send + Sync, { tree: &'a TreeIndex<K, V>, leaf_scanner: Option<LeafScanner<'a, K, V>>, guard: Guard, } impl<'a, K: Clone + Ord + Send + Sync, V: Clone + Send + Sync> Scanner<'a, K, V> { fn new(tree: &'a TreeIndex<K, V>) -> Scanner<'a, K, V> { Scanner::<'a, K, V> { tree, leaf_scanner: None, guard: crossbeam_epoch::pin(), } } fn from(tree: &'a TreeIndex<K, V>, min_allowed_key: &K) -> Option<Scanner<'a, K, V>> { let mut scanner = Scanner::<'a, K, V> { tree, leaf_scanner: None, guard: crossbeam_epoch::pin(), }; loop { let root_node = tree.root.load(Acquire, &scanner.guard); if root_node.is_null() { return None; } if let Ok(leaf_scanner) = unsafe { &*root_node.as_raw() }.max_less(min_allowed_key, &scanner.guard) { scanner.leaf_scanner.replace(unsafe { // Prolongs the lifetime as the rust type system cannot infer the actual lifetime correctly. std::mem::transmute::<_, LeafScanner<'a, K, V>>(leaf_scanner) }); break; } } while let Some((key_ref, _)) = scanner.next() { if key_ref.cmp(min_allowed_key) != std::cmp::Ordering::Less { return Some(scanner); } } None } /// Returns a reference to the entry that the scanner is currently pointing to. pub fn get(&self) -> Option<(&'a K, &'a V)> { if let Some(leaf_scanner) = self.leaf_scanner.as_ref() { return leaf_scanner.get(); } None } } impl<'a, K, V> Iterator for Scanner<'a, K, V> where K: Clone + Ord + Send + Sync, V: Clone + Send + Sync, { type Item = (&'a K, &'a V); fn next(&mut self) -> Option<Self::Item> { if self.leaf_scanner.is_none() { loop { let root_node = self.tree.root.load(Acquire, &self.guard); if root_node.is_null() { return None; } if let Ok(leaf_scanner) = unsafe { &*root_node.as_raw() }.min(&self.guard) { self.leaf_scanner.replace(unsafe { // Prolongs the lifetime as the rust type system cannot infer the actual lifetime correctly. std::mem::transmute::<_, LeafScanner<'a, K, V>>(leaf_scanner) }); break; } } } if let Some(mut scanner) = self.leaf_scanner.take() { let min_allowed_key = scanner.get().map(|(key, _)| key); if let Some(result) = scanner.next() { self.leaf_scanner.replace(scanner); return Some(result); } // Proceeds to the next leaf node. while let Some(mut new_scanner) = unsafe { // Checking min_allowed_key is necessary, because, // - Remove: merges two leaf nodes, therefore the unbounded leaf of the lower key node is relocated. // - Scanner: the unbounded leaf of the lower key node can be scanned twice after a jump. std::mem::transmute::<_, Option<LeafScanner<'a, K, V>>>(scanner.jump(&self.guard)) .take() } { while let Some(entry) = new_scanner.next() { if min_allowed_key .as_ref() .map_or_else(|| true, |&key| key.cmp(entry.0) == std::cmp::Ordering::Less) { self.leaf_scanner.replace(new_scanner); return Some(entry); } } scanner = new_scanner; } } None } }