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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
use crate::helpers::write_to_level;
use crate::mapper::Mapper;
use crate::rbtree;
use crate::{RBMap, RBTree};
use std::fmt::{Debug, Display, Formatter, Result};
use std::iter::{ExactSizeIterator, FromIterator, FusedIterator};
impl<K: PartialOrd + Debug, V: Debug> Debug for RBMap<K, V> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let mut levels = Vec::new();
write_to_level(&self.map.root, "".to_string(), 0, &mut levels);
let mut f_string = "".to_string();
for i in 0..levels.len() {
f_string += &levels[i];
if i != levels.len() - 1 {
f_string += "\n";
}
}
write!(f, "{}", f_string)
}
}
impl<K: PartialOrd + Debug, V: Debug> Display for RBMap<K, V> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "{:?}", self.ordered())
}
}
impl<K: PartialOrd, V> RBMap<K, V> {
/// Creates and returns a new, empty RBMap
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "World");
/// assert_eq!(map.remove(&"Hello").unwrap(), "World");
/// ```
pub fn new() -> RBMap<K, V> {
RBMap { map: RBTree::new() }
}
/// Creates an RBTree set of the keys
/// contained in this map.
/// # Example:
/// ```
/// use rb_tree::{RBMap, RBTree};
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "World");
/// map.insert("Foo", "Bar");
/// let kset = map.keyset();
/// assert!(kset.contains(&&"Hello"));
/// assert!(kset.contains(&&"Foo"));
/// assert!(!kset.contains(&&"Bar"));
/// ```
pub fn keyset(&self) -> RBTree<&K> {
let mut keys = RBTree::new();
for key in self.keys() {
keys.insert(key);
}
keys
}
/// Creates a set from the keys in this
/// map.
/// # Example:
/// ```
/// use rb_tree::{RBMap, RBTree};
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "World");
/// map.insert("Foo", "Bar");
/// let kset = map.into_keyset();
/// assert!(kset.contains(&"Hello"));
/// assert!(kset.contains(&"Foo"));
/// assert!(!kset.contains(&"Bar"));
/// ```
pub fn into_keyset(self) -> RBTree<K> {
let mut kset = RBTree::new();
for (key, _) in self.into_iter() {
kset.insert(key);
}
kset
}
/// Clears all entries from the RBMap
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "world");
/// map.insert("Foo", "bar");
/// assert_eq!(map.len(), 2);
/// map.clear();
/// assert_eq!(map.len(), 0);
/// assert!(map.remove(&"Hello").is_none());
/// ```
pub fn clear(&mut self) {
self.map = RBTree::new();
}
/// Returns true if the map contains an entry
/// for key, false otherwise.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(!map.contains_key(&"Hello"));
/// map.insert("Hello", "world");
/// assert!(map.contains_key(&"Hello"));
/// ```
pub fn contains_key(&self, key: &K) -> bool {
match self.map.get(&Mapper::new(key, None)) {
None => false,
Some(v) => v.is_some(),
}
}
/// Clears the map and returns an iterator
/// over all key-value pairs that were contained
/// in the order of their keys' PartialOrd order.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "world");
/// map.insert("Foo", "bar");
/// let mut drain = map.drain();
/// assert_eq!(drain.next().unwrap(), ("Foo", "bar"));
/// assert_eq!(drain.next().unwrap(), ("Hello", "world"));
/// assert!(drain.next().is_none());
/// ```
pub fn drain(&mut self) -> Drain<K, V> {
let mut rep = RBTree::new();
std::mem::swap(&mut self.map, &mut rep);
Drain { tree: rep }
}
/// Returns an option containing a reference
/// to the value associated with this key,
/// or none if this key does not have an associated
/// value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(map.get(&"Hello").is_none());
/// map.insert("Hello", "world");
/// assert_eq!(map.get(&"Hello").unwrap(), &"world");
/// ```
pub fn get(&self, key: &K) -> Option<&V> {
self.map.get(&Mapper::new(key, None)).map(|v| v.as_ref())
}
/// Returns an option containing a reference
/// to the key-value pair associated with this
/// key, or none if this key does not have an
/// associated value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(map.get(&"Hello").is_none());
/// map.insert("Hello", "world");
/// assert_eq!(map.get_pair(&"Hello").unwrap(), (&"Hello", &"world"));
/// ```
pub fn get_pair(&self, key: &K) -> Option<(&K, &V)> {
self.map
.get(&Mapper::new(key, None))
.map(|v| (v.key(), v.as_ref()))
}
/// Returns an option containing a reference
/// to the key-value pair associated with this
/// key of which the value is mutable.
/// Returns none if this key does not have an
/// associated value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(map.get(&"Hello").is_none());
/// map.insert("Hello", "world");
/// assert_eq!(map.get_pair(&"Hello").unwrap(), (&"Hello", &"world"));
/// ```
pub fn get_pair_mut(&mut self, key: &K) -> Option<(&K, &mut V)> {
self.map
.get_mut(&Mapper::new(key, None))
.map(|v| v.mut_pair())
}
/// Returns an option containing a mutable
/// reference to the value associated with this
/// key, or none if this key does not have an associated
/// value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(map.get(&"Hello").is_none());
/// map.insert("Hello", "world");
/// *map.get_mut(&"Hello").unwrap() = "world!";
/// assert_eq!(map.get(&"Hello").unwrap(), &"world!");
/// ```
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
self.map
.get_mut(&Mapper::new(key, None))
.map(|v| v.as_mut())
}
/// Returns an option containing a reference to the
/// value associated with the key that has the smallest
/// `PartialOrd` value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.peek(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.peek().unwrap(), &"World");
/// ```
pub fn peek(&self) -> Option<&V> {
self.map.peek().map(|v| v.as_ref())
}
/// Returns an option containing a reference to the
/// value associated with the key that has the largest
/// `PartialOrd` value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.peek_back(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.peek_back().unwrap(), &"Foo");
/// ```
pub fn peek_back(&self) -> Option<&V> {
self.map.peek_back().map(|v| v.as_ref())
}
/// Returns an option containing a pair with a reference to the
/// key with the smallest `PartialOrd` value and a reference
/// to its associated value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.peek_pair(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.peek_pair().unwrap(), (&2, &"World"));
/// ```
pub fn peek_pair(&self) -> Option<(&K, &V)> {
self.map.peek().map(|v| v.pair())
}
/// Returns an option containing a pair with a reference to the
/// key with the largest `PartialOrd` value and a reference
/// to its associated value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.peek_pair_back(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.peek_pair_back().unwrap(), (&7, &"Foo"));
/// ```
pub fn peek_pair_back(&self) -> Option<(&K, &V)> {
self.map.peek_back().map(|v| v.pair())
}
/// Inserts a value to associate with the given key
/// into the map, returning the previously-stored key-value
/// pair if one existed, None otherwise.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "world");
/// map.insert("Foo", "bar");
/// assert_eq!(map.len(), 2);
/// ```
pub fn insert(&mut self, key: K, val: V) -> Option<(K, V)> {
self.map
.replace(Mapper::new(key, Some(val)))
.map(|v| v.consume())
}
/// Returns true if there are no key-value pairs
/// stored in this RBMap, false otherwise.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(map.is_empty());
/// map.insert(1, 2);
/// assert!(!map.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.map.len() == 0
}
/// Returns the number of key-value pairs stored
/// in this RBMap.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.len(), 0);
/// map.insert(1, 1);
/// assert_eq!(map.len(), 1);
/// map.insert(2, 4);
/// assert_eq!(map.len(), 2);
/// map.remove(&2);
/// assert_eq!(map.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.map.len()
}
/// Removes the key-value pair associated with key,
/// if one exists, and returns the associated value,
/// or None if the pair did not exist.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(map.remove(&2).is_none());
/// map.insert(2, 4);
/// assert_eq!(map.remove(&2).unwrap(), 4);
/// ```
pub fn remove(&mut self, key: &K) -> Option<V> {
self.map
.take(&Mapper::new(key, None))
.map(|v| v.consume().1)
}
/// Removes the key-value pair associated with key,
/// if one exists, and returns it, or None if the pair
/// did not exist.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert!(map.remove_entry(&2).is_none());
/// map.insert(2, 4);
/// assert_eq!(map.remove_entry(&2).unwrap(), (2, 4));
/// ```
pub fn remove_entry(&mut self, key: &K) -> Option<(K, V)> {
self.map.take(&Mapper::new(key, None)).map(|v| v.consume())
}
/// Removes the pair associated with the key that has the smallest
/// `PartialOrd` value and returns the associated value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.pop(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.pop().unwrap(), "World");
/// assert_eq!(map.pop().unwrap(), "Hello");
/// ```
pub fn pop(&mut self) -> Option<V> {
self.map.pop().map(|v| v.consume().1)
}
/// Removes the pair associated with the key that has the largest
/// `PartialOrd` value and returns the associated value.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.pop(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.pop_back().unwrap(), "Foo");
/// assert_eq!(map.pop_back().unwrap(), "Bar");
/// ```
pub fn pop_back(&mut self) -> Option<V> {
self.map.pop_back().map(|v| v.consume().1)
}
/// Removes the pair associated with the key that has the smallest
/// `PartialOrd` value and returns it.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.pop_pair(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.pop_pair().unwrap(), (2, "World"));
/// assert_eq!(map.pop_pair().unwrap(), (5, "Hello"));
/// ```
pub fn pop_pair(&mut self) -> Option<(K, V)> {
self.map.pop().map(|v| v.consume())
}
/// Removes the pair associated with the key that has the smallest
/// `PartialOrd` value and returns it.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// assert_eq!(map.pop_pair_back(), None);
///
/// map.insert(5, "Hello");
/// map.insert(2, "World");
/// map.insert(7, "Foo");
/// map.insert(6, "Bar");
///
/// assert_eq!(map.pop_pair_back().unwrap(), (7, "Foo"));
/// assert_eq!(map.pop_pair_back().unwrap(), (6, "Bar"));
/// ```
pub fn pop_pair_back(&mut self) -> Option<(K, V)> {
self.map.pop_back().map(|v| v.consume())
}
/// Removes all key-value pairs that do not return true for the
/// provided method.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert(1, 1);
/// map.insert(2, 4);
/// map.insert(3, 9);
/// map.retain(|_, v| *v % 2 == 0);
///
/// let mut pairs = map.drain();
/// assert_eq!(pairs.next().unwrap(), (2, 4));
/// assert_eq!(pairs.next(), None);
/// ```
pub fn retain<F: FnMut(&K, &mut V) -> bool>(&mut self, mut logic: F) {
let mut rep = RBMap::new();
for (key, mut val) in self.drain() {
if logic(&key, &mut val) {
rep.insert(key, val);
}
}
std::mem::swap(self, &mut rep);
}
/// An iterator that visits all key-value
/// pairs in their key's partialord order.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert(1, 1);
/// map.insert(2, 4);
/// map.insert(3, 9);
///
/// let mut pairs = map.iter();
/// assert_eq!(pairs.next().unwrap(), (&1, &1));
/// assert_eq!(pairs.next().unwrap(), (&2, &4));
/// assert_eq!(pairs.next().unwrap(), (&3, &9));
/// assert_eq!(pairs.next(), None);
/// ```
pub fn iter(&self) -> Iter<K, V> {
Iter {
pos: 0,
ordered: self.ordered(),
}
}
/// An iterator that visits all key-value
/// pairs in their key's partialord order
/// and presents the value only as mutable.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert(1, 1);
/// map.insert(2, 4);
/// map.insert(3, 9);
///
/// map.iter_mut().for_each(|(_, v)| *v *= 2);
///
/// let mut pairs = map.iter();
/// assert_eq!(pairs.next().unwrap(), (&1, &2));
/// assert_eq!(pairs.next().unwrap(), (&2, &8));
/// assert_eq!(pairs.next().unwrap(), (&3, &18));
/// assert_eq!(pairs.next(), None);
/// ```
pub fn iter_mut(&mut self) -> IterMut<K, V> {
IterMut {
iter: self.map.iter(),
}
}
/// An iterator that visits all values
/// in their key's partialord order.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert(1, 1);
/// map.insert(2, 4);
/// map.insert(3, 9);
///
/// let mut vals = map.values();
/// assert_eq!(*vals.next().unwrap(), 1);
/// assert_eq!(*vals.next().unwrap(), 4);
/// assert_eq!(*vals.next().unwrap(), 9);
/// assert_eq!(vals.next(), None);
/// ```
pub fn values(&self) -> Values<K, V> {
Values {
pos: 0,
ordered: self.ordered(),
}
}
/// An iterator that visits all values
/// in their key's partialord order
/// and presents them as mutable.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert(1, 1);
/// map.insert(2, 4);
/// map.insert(3, 9);
///
/// map.values_mut().for_each(|v| *v *= 2);
///
/// let mut vals = map.values();
/// assert_eq!(*vals.next().unwrap(), 2);
/// assert_eq!(*vals.next().unwrap(), 8);
/// assert_eq!(*vals.next().unwrap(), 18);
/// assert_eq!(vals.next(), None);
/// ```
pub fn values_mut(&mut self) -> ValuesMut<K, V> {
ValuesMut {
iter: self.iter_mut(),
}
}
/// An iterator that visits all keys
/// in their partialord order.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
/// map.insert(1, 1);
/// map.insert(2, 4);
/// map.insert(3, 9);
///
/// let mut keys = map.keys();
/// assert_eq!(*keys.next().unwrap(), 1);
/// assert_eq!(*keys.next().unwrap(), 2);
/// assert_eq!(*keys.next().unwrap(), 3);
/// assert_eq!(keys.next(), None);
/// ```
pub fn keys(&self) -> Keys<K, V> {
Keys {
pos: 0,
ordered: self.ordered(),
}
}
/// Provides an interface for ensuring values
/// are allocated to the given key.
/// # Example:
/// ```
/// use rb_tree::RBMap;
///
/// let mut map = RBMap::new();
///
/// let val = map.entry(1).or_insert(2);
/// *val = 3;
/// assert_eq!(*map.get(&1).unwrap(), 3);
/// ```
pub fn entry(&mut self, key: K) -> Entry<K, V> {
Entry { map: self, key }
}
// internal helper methods
fn ordered(&self) -> Vec<(&K, &V)> {
self.map.iter().map(|m| (m.key(), m.as_ref())).collect()
}
}
impl<K: PartialOrd, V: PartialOrd> RBMap<K, V> {
/// Creates an RBTree set of the values
/// contained in this map.
/// # Example:
/// ```
/// use rb_tree::{RBMap, RBTree};
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "World");
/// map.insert("Foo", "Bar");
/// let vset = map.valueset();
/// assert!(vset.contains(&&"World"));
/// assert!(vset.contains(&&"Bar"));
/// assert!(!vset.contains(&&"Foo"));
/// ```
pub fn valueset(&self) -> RBTree<&V> {
let mut values = RBTree::new();
for value in self.values() {
values.insert(value);
}
values
}
/// Creates a set of keys and a set of values
/// from the given map.
///
/// Note: any mapping information is lost
/// when this operation is performed.
/// # Example:
/// ```
/// use rb_tree::{RBMap, RBTree};
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "World");
/// map.insert("Foo", "Bar");
/// let (kset, vset) = map.into_sets();
/// assert!(kset.contains(&"Hello"));
/// assert!(kset.contains(&"Foo"));
/// assert!(!kset.contains(&"Bar"));
/// assert!(vset.contains(&"World"));
/// assert!(vset.contains(&"Bar"));
/// assert!(!vset.contains(&"Foo"));
/// ```
pub fn into_sets(self) -> (RBTree<K>, RBTree<V>) {
let mut kset = RBTree::new();
let mut vset = RBTree::new();
for (key, value) in self.into_iter() {
kset.insert(key);
vset.insert(value);
}
(kset, vset)
}
/// Creates an RBTree set from the values
/// contained in this map.
/// # Example:
/// ```
/// use rb_tree::{RBMap, RBTree};
///
/// let mut map = RBMap::new();
/// map.insert("Hello", "World");
/// map.insert("Foo", "Bar");
/// let vset = map.into_valueset();
/// assert!(vset.contains(&"World"));
/// assert!(vset.contains(&"Bar"));
/// assert!(!vset.contains(&"Foo"));
/// ```
pub fn into_valueset(self) -> RBTree<V> {
let mut vset = RBTree::new();
for (_, value) in self.into_iter() {
vset.insert(value);
}
vset
}
}
impl<K: PartialOrd, V> Default for RBMap<K, V> {
fn default() -> Self {
RBMap::new()
}
}
pub struct IntoIter<K: PartialOrd, V> {
tree: RBTree<Mapper<K, V>>,
}
impl<K: PartialOrd, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
self.tree.pop().map(|v| v.consume())
}
}
/// Provides the trait ExactSizeIterator for IntoIter<K, V>
/// # Example:
/// ```
/// use rb_tree::RBMap;
/// use std::iter::FusedIterator;
///
/// let mut map = RBMap::new();
///
/// map.insert(5, "Is");
/// map.insert(2, "This");
/// map.insert(7, "The");
/// map.insert(6, "Real");
/// map.insert(6, "World");
///
/// let mut iterator = map.into_iter();
/// assert_eq!(iterator.len(), 4);
/// let _ = iterator.next();
/// assert_eq!(iterator.len(), 3);
/// ```
impl<K: PartialOrd, V> ExactSizeIterator for IntoIter<K, V> {
fn len(&self) -> usize {
self.tree.len()
}
}
impl<K: PartialOrd, V> FusedIterator for IntoIter<K, V> {}
impl<K: PartialOrd, V> IntoIterator for RBMap<K, V> {
type Item = (K, V);
type IntoIter = IntoIter<K, V>;
fn into_iter(self) -> IntoIter<K, V> {
IntoIter { tree: self.map }
}
}
impl<K: PartialOrd, V> FromIterator<(K, V)> for RBMap<K, V> {
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut map = RBMap::new();
for (key, val) in iter {
map.insert(key, val);
}
map
}
}
impl<K: PartialOrd, V> Extend<(K, V)> for RBMap<K, V> {
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
for (key, val) in iter {
self.insert(key, val);
}
}
}
impl<'a, K: PartialOrd + Copy + 'a, V: Copy + 'a> Extend<(&'a K, &'a V)> for RBMap<K, V> {
fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
for (&key, &val) in iter {
self.insert(key, val);
}
}
}
// this should be fine to do since only one
// borrow can occur when mutable
pub struct Iter<'a, K: PartialOrd, V> {
pos: usize,
ordered: Vec<(&'a K, &'a V)>,
}
impl<'a, K: PartialOrd, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<(&'a K, &'a V)> {
match self.ordered.get(self.pos) {
Some(v) => {
self.pos += 1;
Some(*v)
}
None => None,
}
}
}
impl<'a, K: PartialOrd, V> ExactSizeIterator for Iter<'a, K, V> {
fn len(&self) -> usize {
self.ordered.len() - self.pos
}
}
impl<'a, K: PartialOrd, V> FusedIterator for Iter<'a, K, V> {}
pub struct Keys<'a, K: PartialOrd, V> {
pos: usize,
ordered: Vec<(&'a K, &'a V)>,
}
impl<'a, K: PartialOrd, V> Iterator for Keys<'a, K, V> {
type Item = &'a K;
fn next(&mut self) -> Option<&'a K> {
match self.ordered.get(self.pos) {
Some(v) => {
self.pos += 1;
Some(v.0)
}
None => None,
}
}
}
impl<'a, K: PartialOrd, V> ExactSizeIterator for Keys<'a, K, V> {
fn len(&self) -> usize {
self.ordered.len() - self.pos
}
}
impl<'a, K: PartialOrd, V> FusedIterator for Keys<'a, K, V> {}
pub struct Values<'a, K: PartialOrd, V> {
pos: usize,
ordered: Vec<(&'a K, &'a V)>,
}
impl<'a, K: PartialOrd, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
fn next(&mut self) -> Option<&'a V> {
match self.ordered.get(self.pos) {
Some(v) => {
self.pos += 1;
Some(v.1)
}
None => None,
}
}
}
impl<'a, K: PartialOrd, V> ExactSizeIterator for Values<'a, K, V> {
fn len(&self) -> usize {
self.ordered.len() - self.pos
}
}
impl<'a, K: PartialOrd, V> FusedIterator for Values<'a, K, V> {}
pub struct ValuesMut<'a, K: PartialOrd, V> {
iter: IterMut<'a, K, V>,
}
impl<'a, K: PartialOrd, V> Iterator for ValuesMut<'a, K, V> {
type Item = &'a mut V;
fn next(&mut self) -> Option<&'a mut V> {
match self.iter.next() {
Some(v) => Some(v.1),
None => None,
}
}
}
impl<'a, K: PartialOrd, V> ExactSizeIterator for ValuesMut<'a, K, V> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl<'a, K: PartialOrd, V> FusedIterator for ValuesMut<'a, K, V> {}
pub struct IterMut<'a, K: PartialOrd, V> {
iter: rbtree::Iter<'a, Mapper<K, V>>,
}
impl<'a, K: PartialOrd, V> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
let next = self.iter.next();
match next {
Some(iv) => {
let v = unsafe {
let ptr = iv as *const Mapper<K, V>;
&mut *(ptr as *mut Mapper<K, V>)
};
Some(v.mut_pair())
}
None => None,
}
}
}
impl<'a, K: PartialOrd, V> ExactSizeIterator for IterMut<'a, K, V> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl<'a, K: PartialOrd, V> FusedIterator for IterMut<'a, K, V> {}
pub struct Drain<K: PartialOrd, V> {
tree: RBTree<Mapper<K, V>>,
}
impl<K: PartialOrd, V> Iterator for Drain<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> {
self.tree.pop().map(|v| v.consume())
}
}
impl<K: PartialOrd, V> ExactSizeIterator for Drain<K, V> {
fn len(&self) -> usize {
self.tree.len()
}
}
impl<K: PartialOrd, V> FusedIterator for Drain<K, V> {}
pub struct Entry<'a, K: PartialOrd, V> {
map: &'a mut RBMap<K, V>,
key: K,
}
/// Follows a similar implementation to std::collections::HashMap,
/// in terms of behaviour, only differs in types used.
/// For further detail about any given method, please refer
/// to the documentation of HashMap::Entry.
/// For the time being only copyable keys can utilise
/// these methods
impl<'a, K: PartialOrd + Copy, V> Entry<'a, K, V> {
pub fn insert(self, val: V) -> (&'a K, &'a mut V) {
match self.map.remove_entry(&self.key) {
Some((k, _)) => {
self.map.insert(k, val);
}
None => {
self.map.insert(self.key, val);
}
}
self.map.get_pair_mut(&self.key).unwrap()
}
pub fn and_modify<F>(self, f: F) -> Entry<'a, K, V>
where
F: FnOnce(&mut V),
{
if let Some(v) = self.map.get_mut(&self.key).as_mut() {
f(*v);
}
self
}
pub fn or_insert(self, default: V) -> &'a mut V {
if !self.map.contains_key(&self.key) {
self.map.insert(self.key, default);
}
self.map.get_mut(&self.key).unwrap()
}
pub fn or_insert_with<F>(self, default: F) -> &'a mut V
where
F: FnOnce() -> V,
{
if !self.map.contains_key(&self.key) {
self.map.insert(self.key, default());
}
self.map.get_mut(&self.key).unwrap()
}
}
impl<'a, K: PartialOrd + Copy, V: Default> Entry<'a, K, V> {
pub fn or_default<F>(self) -> &'a mut V
where
F: FnOnce() -> V,
{
if !self.map.contains_key(&self.key) {
self.map.insert(self.key, V::default());
}
self.map.get_mut(&self.key).unwrap()
}
}