1 // Copyright 2017-2018 By tickdream125@hotmail.com. 2 // 3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or 4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license 5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your 6 // option. This file may not be copied, modified, or distributed 7 // except according to those terms. 8 9 // This file brings from https://github.com/tickbh/rbtree-rs/blob/master/src/lib.rs 10 // Thanks to the author tickbh 11 12 #![allow(dead_code)] 13 14 use core::cmp::Ord; 15 use core::cmp::Ordering; 16 use core::fmt::{self, Debug}; 17 use core::iter::{FromIterator, IntoIterator}; 18 use core::marker; 19 use core::mem; 20 use core::ops::Index; 21 use core::ptr; 22 23 use alloc::boxed::Box; 24 25 use crate::kdebug; 26 27 #[derive(Debug, Copy, Clone, PartialEq, Eq)] 28 enum Color { 29 Red, 30 Black, 31 } 32 33 /*****************RBTreeNode***************************/ 34 struct RBTreeNode<K: Ord, V> { 35 color: Color, 36 left: NodePtr<K, V>, 37 right: NodePtr<K, V>, 38 parent: NodePtr<K, V>, 39 key: K, 40 value: V, 41 } 42 43 impl<K: Ord, V> RBTreeNode<K, V> { 44 #[inline] 45 fn pair(self) -> (K, V) { 46 (self.key, self.value) 47 } 48 } 49 50 impl<K, V> Debug for RBTreeNode<K, V> 51 where 52 K: Ord + Debug, 53 V: Debug, 54 { 55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 56 write!(f, "k:{:?} v:{:?} c:{:?}", self.key, self.value, self.color) 57 } 58 } 59 60 /*****************NodePtr***************************/ 61 #[derive(Debug)] 62 struct NodePtr<K: Ord, V>(*mut RBTreeNode<K, V>); 63 64 impl<K: Ord, V> Clone for NodePtr<K, V> { 65 fn clone(&self) -> NodePtr<K, V> { 66 NodePtr(self.0) 67 } 68 } 69 70 impl<K: Ord, V> Copy for NodePtr<K, V> {} 71 72 impl<K: Ord, V> Ord for NodePtr<K, V> { 73 fn cmp(&self, other: &NodePtr<K, V>) -> Ordering { 74 unsafe { (*self.0).key.cmp(&(*other.0).key) } 75 } 76 } 77 78 impl<K: Ord, V> PartialOrd for NodePtr<K, V> { 79 fn partial_cmp(&self, other: &NodePtr<K, V>) -> Option<Ordering> { 80 unsafe { Some((*self.0).key.cmp(&(*other.0).key)) } 81 } 82 } 83 84 impl<K: Ord, V> PartialEq for NodePtr<K, V> { 85 fn eq(&self, other: &NodePtr<K, V>) -> bool { 86 self.0 == other.0 87 } 88 } 89 90 impl<K: Ord, V> Eq for NodePtr<K, V> {} 91 92 impl<K: Ord, V> NodePtr<K, V> { 93 fn new(k: K, v: V) -> NodePtr<K, V> { 94 let node = RBTreeNode { 95 color: Color::Black, 96 left: NodePtr::null(), 97 right: NodePtr::null(), 98 parent: NodePtr::null(), 99 key: k, 100 value: v, 101 }; 102 NodePtr(Box::into_raw(Box::new(node))) 103 } 104 105 #[inline] 106 fn set_color(&mut self, color: Color) { 107 if self.is_null() { 108 return; 109 } 110 unsafe { 111 (*self.0).color = color; 112 } 113 } 114 115 #[inline] 116 fn set_red_color(&mut self) { 117 self.set_color(Color::Red); 118 } 119 120 #[inline] 121 fn set_black_color(&mut self) { 122 self.set_color(Color::Black); 123 } 124 125 #[inline] 126 fn get_color(&self) -> Color { 127 if self.is_null() { 128 return Color::Black; 129 } 130 unsafe { (*self.0).color } 131 } 132 133 #[inline] 134 fn is_red_color(&self) -> bool { 135 if self.is_null() { 136 return false; 137 } 138 unsafe { (*self.0).color == Color::Red } 139 } 140 141 #[inline] 142 fn is_black_color(&self) -> bool { 143 if self.is_null() { 144 return true; 145 } 146 unsafe { (*self.0).color == Color::Black } 147 } 148 149 #[inline] 150 fn is_left_child(&self) -> bool { 151 self.parent().left() == *self 152 } 153 154 #[inline] 155 fn is_right_child(&self) -> bool { 156 self.parent().right() == *self 157 } 158 159 #[inline] 160 fn min_node(self) -> NodePtr<K, V> { 161 let mut temp = self.clone(); 162 while !temp.left().is_null() { 163 temp = temp.left(); 164 } 165 return temp; 166 } 167 168 #[inline] 169 fn max_node(self) -> NodePtr<K, V> { 170 let mut temp = self.clone(); 171 while !temp.right().is_null() { 172 temp = temp.right(); 173 } 174 return temp; 175 } 176 177 #[inline] 178 fn next(self) -> NodePtr<K, V> { 179 if !self.right().is_null() { 180 self.right().min_node() 181 } else { 182 let mut temp = self; 183 loop { 184 if temp.parent().is_null() { 185 return NodePtr::null(); 186 } 187 if temp.is_left_child() { 188 return temp.parent(); 189 } 190 temp = temp.parent(); 191 } 192 } 193 } 194 195 #[inline] 196 fn prev(self) -> NodePtr<K, V> { 197 if !self.left().is_null() { 198 self.left().max_node() 199 } else { 200 let mut temp = self; 201 loop { 202 if temp.parent().is_null() { 203 return NodePtr::null(); 204 } 205 if temp.is_right_child() { 206 return temp.parent(); 207 } 208 temp = temp.parent(); 209 } 210 } 211 } 212 213 #[inline] 214 fn set_parent(&mut self, parent: NodePtr<K, V>) { 215 if self.is_null() { 216 return; 217 } 218 unsafe { (*self.0).parent = parent } 219 } 220 221 #[inline] 222 fn set_left(&mut self, left: NodePtr<K, V>) { 223 if self.is_null() { 224 return; 225 } 226 unsafe { (*self.0).left = left } 227 } 228 229 #[inline] 230 fn set_right(&mut self, right: NodePtr<K, V>) { 231 if self.is_null() { 232 return; 233 } 234 unsafe { (*self.0).right = right } 235 } 236 237 #[inline] 238 fn parent(&self) -> NodePtr<K, V> { 239 if self.is_null() { 240 return NodePtr::null(); 241 } 242 unsafe { (*self.0).parent.clone() } 243 } 244 245 #[inline] 246 fn left(&self) -> NodePtr<K, V> { 247 if self.is_null() { 248 return NodePtr::null(); 249 } 250 unsafe { (*self.0).left.clone() } 251 } 252 253 #[inline] 254 fn right(&self) -> NodePtr<K, V> { 255 if self.is_null() { 256 return NodePtr::null(); 257 } 258 unsafe { (*self.0).right.clone() } 259 } 260 261 #[inline] 262 fn null() -> NodePtr<K, V> { 263 NodePtr(ptr::null_mut()) 264 } 265 266 #[inline] 267 fn is_null(&self) -> bool { 268 self.0.is_null() 269 } 270 } 271 272 impl<K: Ord + Clone, V: Clone> NodePtr<K, V> { 273 unsafe fn deep_clone(&self) -> NodePtr<K, V> { 274 let mut node = NodePtr::new((*self.0).key.clone(), (*self.0).value.clone()); 275 if !self.left().is_null() { 276 node.set_left(self.left().deep_clone()); 277 node.left().set_parent(node); 278 } 279 if !self.right().is_null() { 280 node.set_right(self.right().deep_clone()); 281 node.right().set_parent(node); 282 } 283 node 284 } 285 } 286 287 /// A red black tree implemented with Rust 288 /// It is required that the keys implement the [`Ord`] traits. 289 290 /// # Examples 291 /// ```rust 292 /// use rbtree::RBTree; 293 /// // type inference lets us omit an explicit type signature (which 294 /// // would be `RBTree<&str, &str>` in this example). 295 /// let mut book_reviews = RBTree::new(); 296 /// 297 /// // review some books. 298 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book."); 299 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece."); 300 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable."); 301 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot."); 302 /// 303 /// // check for a specific one. 304 /// if !book_reviews.contains_key(&"Les Misérables") { 305 /// kdebug!( 306 /// "We've got {} reviews, but Les Misérables ain't one.", 307 /// book_reviews.len() 308 /// ); 309 /// } 310 /// 311 /// // oops, this review has a lot of spelling mistakes, let's delete it. 312 /// book_reviews.remove(&"The Adventures of Sherlock Holmes"); 313 /// 314 /// // look up the values associated with some keys. 315 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; 316 /// for book in &to_find { 317 /// match book_reviews.get(book) { 318 /// Some(review) => kdebug!("{}: {}", book, review), 319 /// None => kdebug!("{} is unreviewed.", book), 320 /// } 321 /// } 322 /// 323 /// // iterate over everything. 324 /// for (book, review) in book_reviews.iter() { 325 /// kdebug!("{}: \"{}\"", book, review); 326 /// } 327 /// 328 /// book_reviews.print_tree(); 329 /// ``` 330 /// 331 /// // A `RBTree` with fixed list of elements can be initialized from an array: 332 /// ``` 333 /// use rbtree::RBTree; 334 /// let timber_resources: RBTree<&str, i32> = 335 /// [("Norway", 100), 336 /// ("Denmark", 50), 337 /// ("Iceland", 10)] 338 /// .iter().cloned().collect(); 339 /// // use the values stored in rbtree 340 /// ``` 341 pub struct RBTree<K: Ord, V> { 342 root: NodePtr<K, V>, 343 len: usize, 344 } 345 346 // Drop all owned pointers if the tree is dropped 347 impl<K: Ord, V> Drop for RBTree<K, V> { 348 #[inline] 349 fn drop(&mut self) { 350 self.clear(); 351 } 352 } 353 354 /// If key and value are both impl Clone, we can call clone to get a copy. 355 impl<K: Ord + Clone, V: Clone> Clone for RBTree<K, V> { 356 fn clone(&self) -> RBTree<K, V> { 357 unsafe { 358 let mut new = RBTree::new(); 359 new.root = self.root.deep_clone(); 360 new.len = self.len; 361 new 362 } 363 } 364 } 365 366 impl<K, V> Debug for RBTree<K, V> 367 where 368 K: Ord + Debug, 369 V: Debug, 370 { 371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 372 f.debug_map().entries(self.iter()).finish() 373 } 374 } 375 376 /// This is a method to help us to get inner struct. 377 impl<K: Ord + Debug, V: Debug> RBTree<K, V> { 378 fn tree_print(&self, node: NodePtr<K, V>, direction: i32) { 379 if node.is_null() { 380 return; 381 } 382 if direction == 0 { 383 unsafe { 384 kdebug!("'{:?}' is root node", (*node.0)); 385 } 386 } else { 387 let direct = if direction == -1 { "left" } else { "right" }; 388 unsafe { 389 kdebug!( 390 "{:?} is {:?}'s {:?} child ", 391 (*node.0), 392 *node.parent().0, 393 direct 394 ); 395 } 396 } 397 self.tree_print(node.left(), -1); 398 self.tree_print(node.right(), 1); 399 } 400 401 pub fn print_tree(&self) { 402 if self.root.is_null() { 403 kdebug!("This is a empty tree"); 404 return; 405 } 406 kdebug!("This tree size = {:?}, begin:-------------", self.len()); 407 self.tree_print(self.root, 0); 408 kdebug!("end--------------------------"); 409 } 410 } 411 412 /// all key be same, but it has multi key, if has multi key, it perhaps no correct 413 impl<K, V> PartialEq for RBTree<K, V> 414 where 415 K: Eq + Ord, 416 V: PartialEq, 417 { 418 fn eq(&self, other: &RBTree<K, V>) -> bool { 419 if self.len() != other.len() { 420 return false; 421 } 422 423 self.iter() 424 .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v)) 425 } 426 } 427 428 impl<K, V> Eq for RBTree<K, V> 429 where 430 K: Eq + Ord, 431 V: Eq, 432 { 433 } 434 435 impl<'a, K, V> Index<&'a K> for RBTree<K, V> 436 where 437 K: Ord, 438 { 439 type Output = V; 440 441 #[inline] 442 fn index(&self, index: &K) -> &V { 443 self.get(index).expect("no entry found for key") 444 } 445 } 446 447 impl<K: Ord, V> FromIterator<(K, V)> for RBTree<K, V> { 448 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> RBTree<K, V> { 449 let mut tree = RBTree::new(); 450 tree.extend(iter); 451 tree 452 } 453 } 454 455 /// RBTree into iter 456 impl<K: Ord, V> Extend<(K, V)> for RBTree<K, V> { 457 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) { 458 let iter = iter.into_iter(); 459 for (k, v) in iter { 460 self.insert(k, v); 461 } 462 } 463 } 464 465 /// provide the rbtree all keys 466 /// # Examples 467 /// ``` 468 /// use rbtree::RBTree; 469 /// let mut m = RBTree::new(); 470 /// for i in 1..6 { 471 /// m.insert(i, i); 472 /// } 473 /// let vec = vec![1, 2, 3, 4, 5]; 474 /// let key_vec: Vec<_> = m.keys().cloned().collect(); 475 /// assert_eq!(vec, key_vec); 476 /// ``` 477 pub struct Keys<'a, K: Ord + 'a, V: 'a> { 478 inner: Iter<'a, K, V>, 479 } 480 481 impl<'a, K: Ord, V> Clone for Keys<'a, K, V> { 482 fn clone(&self) -> Keys<'a, K, V> { 483 Keys { 484 inner: self.inner.clone(), 485 } 486 } 487 } 488 489 impl<'a, K: Ord + Debug, V> fmt::Debug for Keys<'a, K, V> { 490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 491 f.debug_list().entries(self.clone()).finish() 492 } 493 } 494 495 impl<'a, K: Ord, V> Iterator for Keys<'a, K, V> { 496 type Item = &'a K; 497 498 #[inline] 499 fn next(&mut self) -> Option<&'a K> { 500 self.inner.next().map(|(k, _)| k) 501 } 502 503 #[inline] 504 fn size_hint(&self) -> (usize, Option<usize>) { 505 self.inner.size_hint() 506 } 507 } 508 509 /// provide the rbtree all values order by key 510 /// # Examples 511 /// ``` 512 /// use rbtree::RBTree; 513 /// let mut m = RBTree::new(); 514 /// m.insert(2, 5); 515 /// m.insert(1, 6); 516 /// m.insert(3, 8); 517 /// m.insert(4, 9); 518 /// let vec = vec![6, 5, 8, 9]; 519 /// let key_vec: Vec<_> = m.values().cloned().collect(); 520 /// assert_eq!(vec, key_vec); 521 /// ``` 522 pub struct Values<'a, K: 'a + Ord, V: 'a> { 523 inner: Iter<'a, K, V>, 524 } 525 526 impl<'a, K: Ord, V> Clone for Values<'a, K, V> { 527 fn clone(&self) -> Values<'a, K, V> { 528 Values { 529 inner: self.inner.clone(), 530 } 531 } 532 } 533 534 impl<'a, K: Ord + Debug, V: Debug> fmt::Debug for Values<'a, K, V> { 535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 536 f.debug_list().entries(self.clone()).finish() 537 } 538 } 539 540 impl<'a, K: Ord, V> Iterator for Values<'a, K, V> { 541 type Item = &'a V; 542 543 #[inline] 544 fn next(&mut self) -> Option<&'a V> { 545 self.inner.next().map(|(_, v)| v) 546 } 547 548 #[inline] 549 fn size_hint(&self) -> (usize, Option<usize>) { 550 self.inner.size_hint() 551 } 552 } 553 554 /// provide the rbtree all values and it can be modify 555 /// # Examples 556 /// ``` 557 /// use rbtree::RBTree; 558 /// let mut m = RBTree::new(); 559 /// for i in 0..32 { 560 /// m.insert(i, i); 561 /// } 562 /// assert_eq!(m.len(), 32); 563 /// for v in m.values_mut() { 564 /// *v *= 2; 565 /// } 566 /// for i in 0..32 { 567 /// assert_eq!(m.get(&i).unwrap(), &(i * 2)); 568 /// } 569 /// ``` 570 pub struct ValuesMut<'a, K: 'a + Ord, V: 'a> { 571 inner: IterMut<'a, K, V>, 572 } 573 574 impl<'a, K: Ord, V> Clone for ValuesMut<'a, K, V> { 575 fn clone(&self) -> ValuesMut<'a, K, V> { 576 ValuesMut { 577 inner: self.inner.clone(), 578 } 579 } 580 } 581 582 impl<'a, K: Ord + Debug, V: Debug> fmt::Debug for ValuesMut<'a, K, V> { 583 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 584 f.debug_list().entries(self.clone()).finish() 585 } 586 } 587 588 impl<'a, K: Ord, V> Iterator for ValuesMut<'a, K, V> { 589 type Item = &'a mut V; 590 591 #[inline] 592 fn next(&mut self) -> Option<&'a mut V> { 593 self.inner.next().map(|(_, v)| v) 594 } 595 596 #[inline] 597 fn size_hint(&self) -> (usize, Option<usize>) { 598 self.inner.size_hint() 599 } 600 } 601 602 /// Convert RBTree to iter, move out the tree. 603 pub struct IntoIter<K: Ord, V> { 604 head: NodePtr<K, V>, 605 tail: NodePtr<K, V>, 606 len: usize, 607 } 608 609 // Drop all owned pointers if the collection is dropped 610 impl<K: Ord, V> Drop for IntoIter<K, V> { 611 #[inline] 612 fn drop(&mut self) { 613 for (_, _) in self {} 614 } 615 } 616 617 impl<K: Ord, V> Iterator for IntoIter<K, V> { 618 type Item = (K, V); 619 620 fn next(&mut self) -> Option<(K, V)> { 621 if self.len == 0 { 622 return None; 623 } 624 625 if self.head.is_null() { 626 return None; 627 } 628 629 let next = self.head.next(); 630 let (k, v) = unsafe { 631 ( 632 core::ptr::read(&(*self.head.0).key), 633 core::ptr::read(&(*self.head.0).value), 634 ) 635 }; 636 self.head = next; 637 self.len -= 1; 638 Some((k, v)) 639 } 640 641 fn size_hint(&self) -> (usize, Option<usize>) { 642 (self.len, Some(self.len)) 643 } 644 } 645 646 impl<K: Ord, V> DoubleEndedIterator for IntoIter<K, V> { 647 #[inline] 648 fn next_back(&mut self) -> Option<(K, V)> { 649 if self.len == 0 { 650 return None; 651 } 652 653 if self.tail.is_null() { 654 return None; 655 } 656 657 let prev = self.tail.prev(); 658 let obj = unsafe { Box::from_raw(self.tail.0) }; 659 let (k, v) = obj.pair(); 660 self.tail = prev; 661 self.len -= 1; 662 Some((k, v)) 663 } 664 } 665 666 /// provide iter ref for RBTree 667 /// # Examples 668 /// ``` 669 /// use rbtree::RBTree; 670 /// let mut m = RBTree::new(); 671 /// for i in 0..32 { 672 /// m.insert(i, i * 2); 673 /// } 674 /// assert_eq!(m.len(), 32); 675 /// let mut observed: u32 = 0; 676 /// for (k, v) in m.iter() { 677 /// assert_eq!(*v, *k * 2); 678 /// observed |= 1 << *k; 679 /// } 680 /// assert_eq!(observed, 0xFFFF_FFFF); 681 /// ``` 682 pub struct Iter<'a, K: Ord + 'a, V: 'a> { 683 head: NodePtr<K, V>, 684 tail: NodePtr<K, V>, 685 len: usize, 686 _marker: marker::PhantomData<&'a ()>, 687 } 688 689 impl<'a, K: Ord + 'a, V: 'a> Clone for Iter<'a, K, V> { 690 fn clone(&self) -> Iter<'a, K, V> { 691 Iter { 692 head: self.head, 693 tail: self.tail, 694 len: self.len, 695 _marker: self._marker, 696 } 697 } 698 } 699 700 impl<'a, K: Ord + 'a, V: 'a> Iterator for Iter<'a, K, V> { 701 type Item = (&'a K, &'a V); 702 703 fn next(&mut self) -> Option<(&'a K, &'a V)> { 704 if self.len == 0 { 705 return None; 706 } 707 708 if self.head.is_null() { 709 return None; 710 } 711 712 let (k, v) = unsafe { (&(*self.head.0).key, &(*self.head.0).value) }; 713 self.head = self.head.next(); 714 self.len -= 1; 715 Some((k, v)) 716 } 717 718 fn size_hint(&self) -> (usize, Option<usize>) { 719 (self.len, Some(self.len)) 720 } 721 } 722 723 impl<'a, K: Ord + 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> { 724 #[inline] 725 fn next_back(&mut self) -> Option<(&'a K, &'a V)> { 726 // kdebug!("len = {:?}", self.len); 727 if self.len == 0 { 728 return None; 729 } 730 731 if self.tail == self.head { 732 return None; 733 } 734 735 let (k, v) = unsafe { (&(*self.tail.0).key, &(*self.tail.0).value) }; 736 self.tail = self.tail.prev(); 737 self.len -= 1; 738 Some((k, v)) 739 } 740 } 741 742 /// provide iter mut ref for RBTree 743 /// # Examples 744 /// ``` 745 /// use rbtree::RBTree; 746 /// let mut m = RBTree::new(); 747 /// for i in 0..32 { 748 /// m.insert(i, i); 749 /// } 750 /// assert_eq!(m.len(), 32); 751 /// for (_, v) in m.iter_mut() { 752 /// *v *= 2; 753 /// } 754 /// for i in 0..32 { 755 /// assert_eq!(m.get(&i).unwrap(), &(i * 2)); 756 /// } 757 /// ``` 758 pub struct IterMut<'a, K: Ord + 'a, V: 'a> { 759 head: NodePtr<K, V>, 760 tail: NodePtr<K, V>, 761 len: usize, 762 _marker: marker::PhantomData<&'a ()>, 763 } 764 765 impl<'a, K: Ord + 'a, V: 'a> Clone for IterMut<'a, K, V> { 766 fn clone(&self) -> IterMut<'a, K, V> { 767 IterMut { 768 head: self.head, 769 tail: self.tail, 770 len: self.len, 771 _marker: self._marker, 772 } 773 } 774 } 775 776 impl<'a, K: Ord + 'a, V: 'a> Iterator for IterMut<'a, K, V> { 777 type Item = (&'a K, &'a mut V); 778 779 fn next(&mut self) -> Option<(&'a K, &'a mut V)> { 780 if self.len == 0 { 781 return None; 782 } 783 784 if self.head.is_null() { 785 return None; 786 } 787 788 let (k, v) = unsafe { (&(*self.head.0).key, &mut (*self.head.0).value) }; 789 self.head = self.head.next(); 790 self.len -= 1; 791 Some((k, v)) 792 } 793 794 fn size_hint(&self) -> (usize, Option<usize>) { 795 (self.len, Some(self.len)) 796 } 797 } 798 799 impl<'a, K: Ord + 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> { 800 #[inline] 801 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { 802 if self.len == 0 { 803 return None; 804 } 805 806 if self.tail == self.head { 807 return None; 808 } 809 810 let (k, v) = unsafe { (&(*self.tail.0).key, &mut (*self.tail.0).value) }; 811 self.tail = self.tail.prev(); 812 self.len -= 1; 813 Some((k, v)) 814 } 815 } 816 817 impl<K: Ord, V> IntoIterator for RBTree<K, V> { 818 type Item = (K, V); 819 type IntoIter = IntoIter<K, V>; 820 821 #[inline] 822 fn into_iter(mut self) -> IntoIter<K, V> { 823 let iter = if self.root.is_null() { 824 IntoIter { 825 head: NodePtr::null(), 826 tail: NodePtr::null(), 827 len: self.len, 828 } 829 } else { 830 IntoIter { 831 head: self.first_child(), 832 tail: self.last_child(), 833 len: self.len, 834 } 835 }; 836 self.fast_clear(); 837 iter 838 } 839 } 840 841 impl<K: Ord, V> RBTree<K, V> { 842 /// Creates an empty `RBTree`. 843 pub fn new() -> RBTree<K, V> { 844 RBTree { 845 root: NodePtr::null(), 846 len: 0, 847 } 848 } 849 850 /// Returns the len of `RBTree`. 851 #[inline] 852 pub fn len(&self) -> usize { 853 self.len 854 } 855 856 /// Returns `true` if the `RBTree` is empty. 857 #[inline] 858 pub fn is_empty(&self) -> bool { 859 self.root.is_null() 860 } 861 862 /* 863 * 对红黑树的节点(x)进行左旋转 864 * 865 * 左旋示意图(对节点x进行左旋): 866 * px px 867 * / / 868 * x y 869 * / \ --(左旋)--> / \ # 870 * lx y x ry 871 * / \ / \ 872 * ly ry lx ly 873 * 874 * 875 */ 876 #[inline] 877 unsafe fn left_rotate(&mut self, mut node: NodePtr<K, V>) { 878 let mut temp = node.right(); 879 node.set_right(temp.left()); 880 881 if !temp.left().is_null() { 882 temp.left().set_parent(node.clone()); 883 } 884 885 temp.set_parent(node.parent()); 886 if node == self.root { 887 self.root = temp.clone(); 888 } else if node == node.parent().left() { 889 node.parent().set_left(temp.clone()); 890 } else { 891 node.parent().set_right(temp.clone()); 892 } 893 894 temp.set_left(node.clone()); 895 node.set_parent(temp.clone()); 896 } 897 898 /* 899 * 对红黑树的节点(y)进行右旋转 900 * 901 * 右旋示意图(对节点y进行左旋): 902 * py py 903 * / / 904 * y x 905 * / \ --(右旋)--> / \ # 906 * x ry lx y 907 * / \ / \ # 908 * lx rx rx ry 909 * 910 */ 911 #[inline] 912 unsafe fn right_rotate(&mut self, mut node: NodePtr<K, V>) { 913 let mut temp = node.left(); 914 node.set_left(temp.right()); 915 916 if !temp.right().is_null() { 917 temp.right().set_parent(node.clone()); 918 } 919 920 temp.set_parent(node.parent()); 921 if node == self.root { 922 self.root = temp.clone(); 923 } else if node == node.parent().right() { 924 node.parent().set_right(temp.clone()); 925 } else { 926 node.parent().set_left(temp.clone()); 927 } 928 929 temp.set_right(node.clone()); 930 node.set_parent(temp.clone()); 931 } 932 933 /// replace value if key exist, if not exist insert it. 934 /// # Examples 935 /// ``` 936 /// use rbtree::RBTree; 937 /// let mut m = RBTree::new(); 938 /// assert_eq!(m.len(), 0); 939 /// m.insert(2, 4); 940 /// assert_eq!(m.len(), 1); 941 /// assert_eq!(m.replace_or_insert(2, 6).unwrap(), 4); 942 /// assert_eq!(m.len(), 1); 943 /// assert_eq!(*m.get(&2).unwrap(), 6); 944 /// ``` 945 #[inline] 946 pub fn replace_or_insert(&mut self, k: K, mut v: V) -> Option<V> { 947 let node = self.find_node(&k); 948 if node.is_null() { 949 self.insert(k, v); 950 return None; 951 } 952 953 unsafe { 954 mem::swap(&mut v, &mut (*node.0).value); 955 } 956 957 Some(v) 958 } 959 960 #[inline] 961 unsafe fn insert_fixup(&mut self, mut node: NodePtr<K, V>) { 962 let mut parent; 963 let mut gparent; 964 965 while node.parent().is_red_color() { 966 parent = node.parent(); 967 gparent = parent.parent(); 968 //若“父节点”是“祖父节点的左孩子” 969 if parent == gparent.left() { 970 // Case 1条件:叔叔节点是红色 971 let mut uncle = gparent.right(); 972 if !uncle.is_null() && uncle.is_red_color() { 973 uncle.set_black_color(); 974 parent.set_black_color(); 975 gparent.set_red_color(); 976 node = gparent; 977 continue; 978 } 979 980 // Case 2条件:叔叔是黑色,且当前节点是右孩子 981 if parent.right() == node { 982 self.left_rotate(parent); 983 let temp = parent; 984 parent = node; 985 node = temp; 986 } 987 988 // Case 3条件:叔叔是黑色,且当前节点是左孩子。 989 parent.set_black_color(); 990 gparent.set_red_color(); 991 self.right_rotate(gparent); 992 } else { 993 // Case 1条件:叔叔节点是红色 994 let mut uncle = gparent.left(); 995 if !uncle.is_null() && uncle.is_red_color() { 996 uncle.set_black_color(); 997 parent.set_black_color(); 998 gparent.set_red_color(); 999 node = gparent; 1000 continue; 1001 } 1002 1003 // Case 2条件:叔叔是黑色,且当前节点是右孩子 1004 if parent.left() == node { 1005 self.right_rotate(parent); 1006 let temp = parent; 1007 parent = node; 1008 node = temp; 1009 } 1010 1011 // Case 3条件:叔叔是黑色,且当前节点是左孩子。 1012 parent.set_black_color(); 1013 gparent.set_red_color(); 1014 self.left_rotate(gparent); 1015 } 1016 } 1017 self.root.set_black_color(); 1018 } 1019 1020 #[inline] 1021 pub fn insert(&mut self, k: K, v: V) { 1022 self.len += 1; 1023 let mut node = NodePtr::new(k, v); 1024 let mut y = NodePtr::null(); 1025 let mut x = self.root; 1026 1027 while !x.is_null() { 1028 y = x; 1029 match node.cmp(&&mut x) { 1030 Ordering::Less => { 1031 x = x.left(); 1032 } 1033 _ => { 1034 x = x.right(); 1035 } 1036 }; 1037 } 1038 node.set_parent(y); 1039 1040 if y.is_null() { 1041 self.root = node; 1042 } else { 1043 match node.cmp(&&mut y) { 1044 Ordering::Less => { 1045 y.set_left(node); 1046 } 1047 _ => { 1048 y.set_right(node); 1049 } 1050 }; 1051 } 1052 1053 node.set_red_color(); 1054 unsafe { 1055 self.insert_fixup(node); 1056 } 1057 } 1058 1059 #[inline] 1060 fn find_node(&self, k: &K) -> NodePtr<K, V> { 1061 if self.root.is_null() { 1062 return NodePtr::null(); 1063 } 1064 let mut temp = &self.root; 1065 unsafe { 1066 loop { 1067 let next = match k.cmp(&(*temp.0).key) { 1068 Ordering::Less => &mut (*temp.0).left, 1069 Ordering::Greater => &mut (*temp.0).right, 1070 Ordering::Equal => return *temp, 1071 }; 1072 if next.is_null() { 1073 break; 1074 } 1075 temp = next; 1076 } 1077 } 1078 NodePtr::null() 1079 } 1080 1081 #[inline] 1082 fn first_child(&self) -> NodePtr<K, V> { 1083 if self.root.is_null() { 1084 NodePtr::null() 1085 } else { 1086 let mut temp = self.root; 1087 while !temp.left().is_null() { 1088 temp = temp.left(); 1089 } 1090 return temp; 1091 } 1092 } 1093 1094 #[inline] 1095 fn last_child(&self) -> NodePtr<K, V> { 1096 if self.root.is_null() { 1097 NodePtr::null() 1098 } else { 1099 let mut temp = self.root; 1100 while !temp.right().is_null() { 1101 temp = temp.right(); 1102 } 1103 return temp; 1104 } 1105 } 1106 1107 #[inline] 1108 pub fn get_first(&self) -> Option<(&K, &V)> { 1109 let first = self.first_child(); 1110 if first.is_null() { 1111 return None; 1112 } 1113 unsafe { Some((&(*first.0).key, &(*first.0).value)) } 1114 } 1115 1116 #[inline] 1117 pub fn get_last(&self) -> Option<(&K, &V)> { 1118 let last = self.last_child(); 1119 if last.is_null() { 1120 return None; 1121 } 1122 unsafe { Some((&(*last.0).key, &(*last.0).value)) } 1123 } 1124 1125 #[inline] 1126 pub fn pop_first(&mut self) -> Option<(K, V)> { 1127 let first = self.first_child(); 1128 if first.is_null() { 1129 return None; 1130 } 1131 unsafe { Some(self.delete(first)) } 1132 } 1133 1134 #[inline] 1135 pub fn pop_last(&mut self) -> Option<(K, V)> { 1136 let last = self.last_child(); 1137 if last.is_null() { 1138 return None; 1139 } 1140 unsafe { Some(self.delete(last)) } 1141 } 1142 1143 #[inline] 1144 pub fn get_first_mut(&mut self) -> Option<(&K, &mut V)> { 1145 let first = self.first_child(); 1146 if first.is_null() { 1147 return None; 1148 } 1149 unsafe { Some((&(*first.0).key, &mut (*first.0).value)) } 1150 } 1151 1152 #[inline] 1153 pub fn get_last_mut(&mut self) -> Option<(&K, &mut V)> { 1154 let last = self.last_child(); 1155 if last.is_null() { 1156 return None; 1157 } 1158 unsafe { Some((&(*last.0).key, &mut (*last.0).value)) } 1159 } 1160 1161 #[inline] 1162 pub fn get(&self, k: &K) -> Option<&V> { 1163 let node = self.find_node(k); 1164 if node.is_null() { 1165 return None; 1166 } 1167 1168 unsafe { Some(&(*node.0).value) } 1169 } 1170 1171 #[inline] 1172 pub fn get_mut(&mut self, k: &K) -> Option<&mut V> { 1173 let node = self.find_node(k); 1174 if node.is_null() { 1175 return None; 1176 } 1177 1178 unsafe { Some(&mut (*node.0).value) } 1179 } 1180 1181 #[inline] 1182 pub fn contains_key(&self, k: &K) -> bool { 1183 let node = self.find_node(k); 1184 if node.is_null() { 1185 return false; 1186 } 1187 true 1188 } 1189 1190 #[inline] 1191 fn clear_recurse(&mut self, current: NodePtr<K, V>) { 1192 if !current.is_null() { 1193 unsafe { 1194 self.clear_recurse(current.left()); 1195 self.clear_recurse(current.right()); 1196 drop(Box::from_raw(current.0)); 1197 } 1198 } 1199 } 1200 1201 #[inline] 1202 pub fn clear(&mut self) { 1203 let root = self.root; 1204 self.root = NodePtr::null(); 1205 self.clear_recurse(root); 1206 } 1207 1208 /// Empties the `RBTree` without freeing objects in it. 1209 #[inline] 1210 fn fast_clear(&mut self) { 1211 self.root = NodePtr::null(); 1212 } 1213 1214 #[inline] 1215 pub fn remove(&mut self, k: &K) -> Option<V> { 1216 let node = self.find_node(k); 1217 if node.is_null() { 1218 return None; 1219 } 1220 unsafe { Some(self.delete(node).1) } 1221 } 1222 1223 #[inline] 1224 unsafe fn delete_fixup(&mut self, mut node: NodePtr<K, V>, mut parent: NodePtr<K, V>) { 1225 let mut other; 1226 while node != self.root && node.is_black_color() { 1227 if parent.left() == node { 1228 other = parent.right(); 1229 //x的兄弟w是红色的 1230 if other.is_red_color() { 1231 other.set_black_color(); 1232 parent.set_red_color(); 1233 self.left_rotate(parent); 1234 other = parent.right(); 1235 } 1236 1237 //x的兄弟w是黑色,且w的俩个孩子也都是黑色的 1238 if other.left().is_black_color() && other.right().is_black_color() { 1239 other.set_red_color(); 1240 node = parent; 1241 parent = node.parent(); 1242 } else { 1243 //x的兄弟w是黑色的,并且w的左孩子是红色,右孩子为黑色。 1244 if other.right().is_black_color() { 1245 other.left().set_black_color(); 1246 other.set_red_color(); 1247 self.right_rotate(other); 1248 other = parent.right(); 1249 } 1250 //x的兄弟w是黑色的;并且w的右孩子是红色的,左孩子任意颜色。 1251 other.set_color(parent.get_color()); 1252 parent.set_black_color(); 1253 other.right().set_black_color(); 1254 self.left_rotate(parent); 1255 node = self.root; 1256 break; 1257 } 1258 } else { 1259 other = parent.left(); 1260 //x的兄弟w是红色的 1261 if other.is_red_color() { 1262 other.set_black_color(); 1263 parent.set_red_color(); 1264 self.right_rotate(parent); 1265 other = parent.left(); 1266 } 1267 1268 //x的兄弟w是黑色,且w的俩个孩子也都是黑色的 1269 if other.left().is_black_color() && other.right().is_black_color() { 1270 other.set_red_color(); 1271 node = parent; 1272 parent = node.parent(); 1273 } else { 1274 //x的兄弟w是黑色的,并且w的左孩子是红色,右孩子为黑色。 1275 if other.left().is_black_color() { 1276 other.right().set_black_color(); 1277 other.set_red_color(); 1278 self.left_rotate(other); 1279 other = parent.left(); 1280 } 1281 //x的兄弟w是黑色的;并且w的右孩子是红色的,左孩子任意颜色。 1282 other.set_color(parent.get_color()); 1283 parent.set_black_color(); 1284 other.left().set_black_color(); 1285 self.right_rotate(parent); 1286 node = self.root; 1287 break; 1288 } 1289 } 1290 } 1291 1292 node.set_black_color(); 1293 } 1294 1295 #[inline] 1296 unsafe fn delete(&mut self, node: NodePtr<K, V>) -> (K, V) { 1297 let mut child; 1298 let mut parent; 1299 let color; 1300 1301 self.len -= 1; 1302 // 被删除节点的"左右孩子都不为空"的情况。 1303 if !node.left().is_null() && !node.right().is_null() { 1304 // 被删节点的后继节点。(称为"取代节点") 1305 // 用它来取代"被删节点"的位置,然后再将"被删节点"去掉。 1306 let mut replace = node.right().min_node(); 1307 if node == self.root { 1308 self.root = replace; 1309 } else { 1310 if node.parent().left() == node { 1311 node.parent().set_left(replace); 1312 } else { 1313 node.parent().set_right(replace); 1314 } 1315 } 1316 1317 // child是"取代节点"的右孩子,也是需要"调整的节点"。 1318 // "取代节点"肯定不存在左孩子!因为它是一个后继节点。 1319 child = replace.right(); 1320 parent = replace.parent(); 1321 color = replace.get_color(); 1322 if parent == node { 1323 parent = replace; 1324 } else { 1325 if !child.is_null() { 1326 child.set_parent(parent); 1327 } 1328 parent.set_left(child); 1329 replace.set_right(node.right()); 1330 node.right().set_parent(replace); 1331 } 1332 1333 replace.set_parent(node.parent()); 1334 replace.set_color(node.get_color()); 1335 replace.set_left(node.left()); 1336 node.left().set_parent(replace); 1337 1338 if color == Color::Black { 1339 self.delete_fixup(child, parent); 1340 } 1341 1342 let obj = Box::from_raw(node.0); 1343 return obj.pair(); 1344 } 1345 1346 if !node.left().is_null() { 1347 child = node.left(); 1348 } else { 1349 child = node.right(); 1350 } 1351 1352 parent = node.parent(); 1353 color = node.get_color(); 1354 if !child.is_null() { 1355 child.set_parent(parent); 1356 } 1357 1358 if self.root == node { 1359 self.root = child 1360 } else { 1361 if parent.left() == node { 1362 parent.set_left(child); 1363 } else { 1364 parent.set_right(child); 1365 } 1366 } 1367 1368 if color == Color::Black { 1369 self.delete_fixup(child, parent); 1370 } 1371 1372 let obj = Box::from_raw(node.0); 1373 return obj.pair(); 1374 } 1375 1376 /// Return the keys iter 1377 #[inline] 1378 pub fn keys(&self) -> Keys<K, V> { 1379 Keys { inner: self.iter() } 1380 } 1381 1382 /// Return the value iter 1383 #[inline] 1384 pub fn values(&self) -> Values<K, V> { 1385 Values { inner: self.iter() } 1386 } 1387 1388 /// Return the value iter mut 1389 #[inline] 1390 pub fn values_mut(&mut self) -> ValuesMut<K, V> { 1391 ValuesMut { 1392 inner: self.iter_mut(), 1393 } 1394 } 1395 1396 /// Return the key and value iter 1397 #[inline] 1398 pub fn iter(&self) -> Iter<K, V> { 1399 Iter { 1400 head: self.first_child(), 1401 tail: self.last_child(), 1402 len: self.len, 1403 _marker: marker::PhantomData, 1404 } 1405 } 1406 1407 /// Return the key and mut value iter 1408 #[inline] 1409 pub fn iter_mut(&mut self) -> IterMut<K, V> { 1410 IterMut { 1411 head: self.first_child(), 1412 tail: self.last_child(), 1413 len: self.len, 1414 _marker: marker::PhantomData, 1415 } 1416 } 1417 } 1418 1419 #[cfg(test)] 1420 mod tests { 1421 1422 #[test] 1423 fn test_insert() { 1424 use crate::libs::rbtree::RBTree; 1425 let mut m = RBTree::new(); 1426 assert_eq!(m.len(), 0); 1427 m.insert(1, 2); 1428 assert_eq!(m.len(), 1); 1429 m.insert(2, 4); 1430 assert_eq!(m.len(), 2); 1431 m.insert(2, 6); 1432 assert_eq!(m.len(), 3); 1433 assert_eq!(*m.get(&1).unwrap(), 2); 1434 assert_eq!(*m.get(&2).unwrap(), 4); 1435 assert_eq!(*m.get(&2).unwrap(), 4); 1436 } 1437 1438 #[test] 1439 fn test_replace() { 1440 use crate::libs::rbtree::RBTree; 1441 let mut m = RBTree::new(); 1442 assert_eq!(m.len(), 0); 1443 m.insert(2, 4); 1444 assert_eq!(m.len(), 1); 1445 assert_eq!(m.replace_or_insert(2, 6).unwrap(), 4); 1446 assert_eq!(m.len(), 1); 1447 assert_eq!(*m.get(&2).unwrap(), 6); 1448 } 1449 1450 #[test] 1451 fn test_clone() { 1452 use crate::libs::rbtree::RBTree; 1453 let mut m = RBTree::new(); 1454 assert_eq!(m.len(), 0); 1455 m.insert(1, 2); 1456 assert_eq!(m.len(), 1); 1457 m.insert(2, 4); 1458 assert_eq!(m.len(), 2); 1459 let m2 = m.clone(); 1460 m.clear(); 1461 assert_eq!(*m2.get(&1).unwrap(), 2); 1462 assert_eq!(*m2.get(&2).unwrap(), 4); 1463 assert_eq!(m2.len(), 2); 1464 } 1465 1466 #[test] 1467 fn test_empty_remove() { 1468 use crate::libs::rbtree::RBTree; 1469 let mut m: RBTree<isize, bool> = RBTree::new(); 1470 assert_eq!(m.remove(&0), None); 1471 } 1472 1473 #[test] 1474 fn test_empty_iter() { 1475 use crate::libs::rbtree::RBTree; 1476 let mut m: RBTree<isize, bool> = RBTree::new(); 1477 assert_eq!(m.iter().next(), None); 1478 assert_eq!(m.iter_mut().next(), None); 1479 assert_eq!(m.len(), 0); 1480 assert!(m.is_empty()); 1481 assert_eq!(m.into_iter().next(), None); 1482 } 1483 1484 #[test] 1485 fn test_lots_of_insertions() { 1486 use crate::libs::rbtree::RBTree; 1487 let mut m = RBTree::new(); 1488 1489 // Try this a few times to make sure we never screw up the hashmap's 1490 // internal state. 1491 for _ in 0..10 { 1492 assert!(m.is_empty()); 1493 1494 for i in 1..101 { 1495 m.insert(i, i); 1496 1497 for j in 1..i + 1 { 1498 let r = m.get(&j); 1499 assert_eq!(r, Some(&j)); 1500 } 1501 1502 for j in i + 1..101 { 1503 let r = m.get(&j); 1504 assert_eq!(r, None); 1505 } 1506 } 1507 1508 for i in 101..201 { 1509 assert!(!m.contains_key(&i)); 1510 } 1511 1512 // remove forwards 1513 for i in 1..101 { 1514 assert!(m.remove(&i).is_some()); 1515 1516 for j in 1..i + 1 { 1517 assert!(!m.contains_key(&j)); 1518 } 1519 1520 for j in i + 1..101 { 1521 assert!(m.contains_key(&j)); 1522 } 1523 } 1524 1525 for i in 1..101 { 1526 assert!(!m.contains_key(&i)); 1527 } 1528 1529 for i in 1..101 { 1530 m.insert(i, i); 1531 } 1532 1533 // remove backwards 1534 for i in (1..101).rev() { 1535 assert!(m.remove(&i).is_some()); 1536 1537 for j in i..101 { 1538 assert!(!m.contains_key(&j)); 1539 } 1540 1541 for j in 1..i { 1542 assert!(m.contains_key(&j)); 1543 } 1544 } 1545 } 1546 } 1547 1548 #[test] 1549 fn test_find_mut() { 1550 use crate::libs::rbtree::RBTree; 1551 let mut m = RBTree::new(); 1552 m.insert(1, 12); 1553 m.insert(2, 8); 1554 m.insert(5, 14); 1555 let new = 100; 1556 match m.get_mut(&5) { 1557 None => panic!(), 1558 Some(x) => *x = new, 1559 } 1560 assert_eq!(m.get(&5), Some(&new)); 1561 } 1562 1563 #[test] 1564 fn test_remove() { 1565 use crate::libs::rbtree::RBTree; 1566 let mut m = RBTree::new(); 1567 m.insert(1, 2); 1568 assert_eq!(*m.get(&1).unwrap(), 2); 1569 m.insert(5, 3); 1570 assert_eq!(*m.get(&5).unwrap(), 3); 1571 m.insert(9, 4); 1572 assert_eq!(*m.get(&1).unwrap(), 2); 1573 assert_eq!(*m.get(&5).unwrap(), 3); 1574 assert_eq!(*m.get(&9).unwrap(), 4); 1575 assert_eq!(m.remove(&1).unwrap(), 2); 1576 assert_eq!(m.remove(&5).unwrap(), 3); 1577 assert_eq!(m.remove(&9).unwrap(), 4); 1578 assert_eq!(m.len(), 0); 1579 } 1580 1581 #[test] 1582 fn test_is_empty() { 1583 use crate::libs::rbtree::RBTree; 1584 let mut m = RBTree::new(); 1585 m.insert(1, 2); 1586 assert!(!m.is_empty()); 1587 assert!(m.remove(&1).is_some()); 1588 assert!(m.is_empty()); 1589 } 1590 1591 #[test] 1592 fn test_pop() { 1593 use crate::libs::rbtree::RBTree; 1594 let mut m = RBTree::new(); 1595 m.insert(2, 4); 1596 m.insert(1, 2); 1597 m.insert(3, 6); 1598 assert_eq!(m.len(), 3); 1599 assert_eq!(m.pop_first(), Some((1, 2))); 1600 assert_eq!(m.len(), 2); 1601 assert_eq!(m.pop_last(), Some((3, 6))); 1602 assert_eq!(m.len(), 1); 1603 assert_eq!(m.get_first(), Some((&2, &4))); 1604 assert_eq!(m.get_last(), Some((&2, &4))); 1605 } 1606 1607 #[test] 1608 fn test_iterate() { 1609 use crate::libs::rbtree::RBTree; 1610 let mut m = RBTree::new(); 1611 for i in 0..32 { 1612 m.insert(i, i * 2); 1613 } 1614 assert_eq!(m.len(), 32); 1615 1616 let mut observed: u32 = 0; 1617 1618 for (k, v) in m.iter() { 1619 assert_eq!(*v, *k * 2); 1620 observed |= 1 << *k; 1621 } 1622 assert_eq!(observed, 0xFFFF_FFFF); 1623 } 1624 1625 #[test] 1626 fn test_keys() { 1627 use crate::libs::rbtree::RBTree; 1628 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; 1629 let map: RBTree<_, _> = vec.into_iter().collect(); 1630 let keys: Vec<_> = map.keys().cloned().collect(); 1631 assert_eq!(keys.len(), 3); 1632 assert!(keys.contains(&1)); 1633 assert!(keys.contains(&2)); 1634 assert!(keys.contains(&3)); 1635 } 1636 1637 #[test] 1638 fn test_values() { 1639 use crate::libs::rbtree::RBTree; 1640 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; 1641 let map: RBTree<_, _> = vec.into_iter().collect(); 1642 let values: Vec<_> = map.values().cloned().collect(); 1643 assert_eq!(values.len(), 3); 1644 assert!(values.contains(&'a')); 1645 assert!(values.contains(&'b')); 1646 assert!(values.contains(&'c')); 1647 } 1648 1649 #[test] 1650 fn test_values_mut() { 1651 use crate::libs::rbtree::RBTree; 1652 let vec = vec![(1, 1), (2, 2), (3, 3)]; 1653 let mut map: RBTree<_, _> = vec.into_iter().collect(); 1654 for value in map.values_mut() { 1655 *value = (*value) * 2 1656 } 1657 let values: Vec<_> = map.values().cloned().collect(); 1658 assert_eq!(values.len(), 3); 1659 assert!(values.contains(&2)); 1660 assert!(values.contains(&4)); 1661 assert!(values.contains(&6)); 1662 } 1663 1664 #[test] 1665 fn test_find() { 1666 use crate::libs::rbtree::RBTree; 1667 let mut m = RBTree::new(); 1668 assert!(m.get(&1).is_none()); 1669 m.insert(1, 2); 1670 match m.get(&1) { 1671 None => panic!(), 1672 Some(v) => assert_eq!(*v, 2), 1673 } 1674 } 1675 1676 #[test] 1677 fn test_eq() { 1678 use crate::libs::rbtree::RBTree; 1679 let mut m1 = RBTree::new(); 1680 m1.insert(1, 2); 1681 m1.insert(2, 3); 1682 m1.insert(3, 4); 1683 1684 let mut m2 = RBTree::new(); 1685 m2.insert(1, 2); 1686 m2.insert(2, 3); 1687 1688 assert!(m1 != m2); 1689 1690 m2.insert(3, 4); 1691 1692 assert_eq!(m1, m2); 1693 } 1694 1695 #[test] 1696 fn test_show() { 1697 use crate::libs::rbtree::RBTree; 1698 let mut map = RBTree::new(); 1699 let empty: RBTree<i32, i32> = RBTree::new(); 1700 1701 map.insert(1, 2); 1702 map.insert(3, 4); 1703 1704 let map_str = format!("{:?}", map); 1705 1706 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); 1707 assert_eq!(format!("{:?}", empty), "{}"); 1708 } 1709 1710 #[test] 1711 fn test_from_iter() { 1712 use crate::libs::rbtree::RBTree; 1713 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; 1714 1715 let map: RBTree<_, _> = xs.iter().cloned().collect(); 1716 1717 for &(k, v) in &xs { 1718 assert_eq!(map.get(&k), Some(&v)); 1719 } 1720 } 1721 1722 #[test] 1723 fn test_size_hint() { 1724 use crate::libs::rbtree::RBTree; 1725 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; 1726 1727 let map: RBTree<_, _> = xs.iter().cloned().collect(); 1728 1729 let mut iter = map.iter(); 1730 1731 for _ in iter.by_ref().take(3) {} 1732 1733 assert_eq!(iter.size_hint(), (3, Some(3))); 1734 } 1735 1736 #[test] 1737 fn test_iter_len() { 1738 use crate::libs::rbtree::RBTree; 1739 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; 1740 1741 let map: RBTree<_, _> = xs.iter().cloned().collect(); 1742 1743 let mut iter = map.iter(); 1744 1745 for _ in iter.by_ref().take(3) {} 1746 1747 assert_eq!(iter.count(), 3); 1748 } 1749 1750 #[test] 1751 fn test_mut_size_hint() { 1752 use crate::libs::rbtree::RBTree; 1753 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; 1754 1755 let mut map: RBTree<_, _> = xs.iter().cloned().collect(); 1756 1757 let mut iter = map.iter_mut(); 1758 1759 for _ in iter.by_ref().take(3) {} 1760 1761 assert_eq!(iter.size_hint(), (3, Some(3))); 1762 } 1763 1764 #[test] 1765 fn test_iter_mut_len() { 1766 use crate::libs::rbtree::RBTree; 1767 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; 1768 1769 let mut map: RBTree<_, _> = xs.iter().cloned().collect(); 1770 1771 let mut iter = map.iter_mut(); 1772 1773 for _ in iter.by_ref().take(3) {} 1774 1775 assert_eq!(iter.count(), 3); 1776 } 1777 1778 #[test] 1779 fn test_index() { 1780 use crate::libs::rbtree::RBTree; 1781 let mut map = RBTree::new(); 1782 1783 map.insert(1, 2); 1784 map.insert(2, 1); 1785 map.insert(3, 4); 1786 1787 assert_eq!(map[&2], 1); 1788 } 1789 1790 #[test] 1791 #[should_panic] 1792 fn test_index_nonexistent() { 1793 use crate::libs::rbtree::RBTree; 1794 let mut map = RBTree::new(); 1795 1796 map.insert(1, 2); 1797 map.insert(2, 1); 1798 map.insert(3, 4); 1799 1800 map[&4]; 1801 } 1802 1803 #[test] 1804 fn test_extend_iter() { 1805 use crate::libs::rbtree::RBTree; 1806 let mut a = RBTree::new(); 1807 a.insert(1, "one"); 1808 let mut b = RBTree::new(); 1809 b.insert(2, "two"); 1810 b.insert(3, "three"); 1811 1812 a.extend(b.into_iter()); 1813 1814 assert_eq!(a.len(), 3); 1815 assert_eq!(a[&1], "one"); 1816 assert_eq!(a[&2], "two"); 1817 assert_eq!(a[&3], "three"); 1818 } 1819 } 1820