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 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
//! double-map
//!
//! `DHashMap` is like a `std::collection::HashMap`, but allow to use double key to single data/value
//!
use std::collections::hash_map;
use std::collections::HashMap;
use std::collections::TryReserveError;
use core::hash::{BuildHasher, Hash};
use std::borrow::Borrow;
use std::mem;
use std::fmt::{self, Debug};
#[derive(Clone)]
pub struct DHashMap<K1, K2, V, S = hash_map::RandomState>
{
value_map: HashMap<K1, (K2, V), S>,
key_map: HashMap<K2, K1, S>,
}
impl<K1, K2, V> DHashMap<K1, K2, V, hash_map::RandomState>
{
/// Creates a new empty [`DHashMap`] with [`RandomState`](std::collections::hash_map::RandomState)
/// type of hash builder to hash keys.
///
/// The primary key is of type `K1` and the secondary key is of type `K2`.
/// The value is of type `V`.
///
/// Internally, two [`HashMap`](`std::collections::HashMap`) are created. One of type
/// `HashMap<K1, (K2, V)>` to hold the `(K2, V)` tuple, and second one of type
/// `HashMap<K2, K1>` just for holding the primary key of type `K1`.
/// We hold the `(K2, V)` tuple inside first `Hashmap` for synchronization purpose,
/// so that we can organize checking that both primary key of type `K1` and the
/// secondary key is of type `K2` refers to the same value, and so on.
///
/// The hash map is initially created with a capacity of 0, so it will not allocate until
/// it is first inserted into.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// let mut map: DHashMap<u32, &str, i32> = DHashMap::new();
///
/// // The created DHashMap hold none elements
/// assert_eq!(map.len(), 0);
///
/// // The created DHashMap also didn't allocate memory
/// assert_eq!(map.capacity(), 0);
///
/// // Now we insert elements inside created DHashMap
/// map.insert(1, "One", 1);
/// // We can see that the DHashMap hold 1 element
/// assert_eq!(map.len(), 1);
/// // And it also allocate some capacity (by default it starts from 3 element)
/// assert!(map.capacity() > 1);
/// ```
#[inline]
#[must_use]
pub fn new() -> DHashMap<K1, K2, V, hash_map::RandomState> {
DHashMap {
value_map: HashMap::new(),
key_map: HashMap::new(),
}
}
/// Creates an empty [`DHashMap`] with the specified capacity.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// let mut map: DHashMap<&str, i32, &str> = DHashMap::with_capacity(5);
///
/// // The created DHashMap hold none elements
/// assert_eq!(map.len(), 0);
/// // But it can hold at least 5 elements without reallocating
/// let empty_map_capacity = map.capacity();
/// assert!(empty_map_capacity >= 5);
///
/// // Now we insert some 5 elements inside created DHashMap
/// map.insert("One", 1, "a");
/// map.insert("Two", 2, "b");
/// map.insert("Three", 3, "c");
/// map.insert("Four", 4, "d");
/// map.insert("Five", 5, "e");
///
/// // We can see that the DHashMap hold 5 elements
/// assert_eq!(map.len(), 5);
/// // But it capacity dosn't changed
/// assert_eq!(map.capacity(), empty_map_capacity)
/// ```
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> DHashMap<K1, K2, V, hash_map::RandomState> {
DHashMap {
value_map: HashMap::with_capacity(capacity),
key_map: HashMap::with_capacity(capacity),
}
}
}
impl<K1, K2, V, S> DHashMap<K1, K2, V, S>
where
S: Clone
{
/// Creates an empty [`DHashMap`] which will use the given hash builder to hash
/// keys.
///
/// The created map has the default initial capacity, witch is equal to 0, so
/// it will not allocate until it is first inserted into.
///
/// Warning: `hash_builder` is normally randomly generated, and
/// is designed to allow [`DHashMap`] to be resistant to attacks that
/// cause many collisions and very poor performance. Setting it
/// manually using this function can expose a DoS attack vector.
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the [`DHashMap`] to be useful, see its documentation for details.
/// It also should implement the [`Clone`] trait because we create two
/// [`HashMap`] inside [`DHashMap`], so that we need to
/// [`clone`](core::clone::Clone::clone) hash_builder for passing it inside
/// two inner `HashMap`.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// use std::collections::hash_map::RandomState;
///
/// let s = RandomState::new();
/// let mut map = DHashMap::with_hasher(s);
///
/// // The created DHashMap hold none elements
/// assert_eq!(map.len(), 0);
///
/// // The created DHashMap also didn't allocate memory
/// assert_eq!(map.capacity(), 0);
///
/// // Now we insert elements inside created DHashMap
/// map.insert("One", 1, 2);
/// // We can see that the DHashMap hold 1 element
/// assert_eq!(map.len(), 1);
/// // And it also allocate some capacity (by default it starts from 3 element)
/// assert!(map.capacity() > 1);
/// ```
#[inline]
pub fn with_hasher(hash_builder: S) -> DHashMap<K1, K2, V, S> {
DHashMap {
value_map: HashMap::with_hasher(hash_builder.clone()),
key_map: HashMap::with_hasher(hash_builder),
}
}
/// Creates an empty [`DHashMap`] with the specified capacity, using `hash_builder`
/// to hash the keys.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// Warning: `hash_builder` is normally randomly generated, and
/// is designed to allow HashMaps to be resistant to attacks that
/// cause many collisions and very poor performance. Setting it
/// manually using this function can expose a DoS attack vector.
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the [`DHashMap`] to be useful, see its documentation for details.
/// It also should implement the [`Clone`] trait because we create two
/// [`HashMap`] inside [`DHashMap`], so that we need to
/// [`clone`](core::clone::Clone::clone) hash_builder for passing it inside
/// two inner `HashMap`.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// use std::collections::hash_map::RandomState;
///
/// let s = RandomState::new();
/// let mut map = DHashMap::with_capacity_and_hasher(5, s);
///
/// // The created DHashMap hold none elements
/// assert_eq!(map.len(), 0);
/// // But it can hold at least 5 elements without reallocating
/// let empty_map_capacity = map.capacity();
/// assert!(empty_map_capacity >= 5);
///
/// // Now we insert some 5 elements inside created DHashMap
/// map.insert("One", 1, "a");
/// map.insert("Two", 2, "b");
/// map.insert("Three", 3, "c");
/// map.insert("Four", 4, "d");
/// map.insert("Five", 5, "e");
///
/// // We can see that the DHashMap hold 5 elements
/// assert_eq!(map.len(), 5);
/// // But it capacity dosn't changed
/// assert_eq!(map.capacity(), empty_map_capacity)
/// ```
#[inline]
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> DHashMap<K1, K2, V, S> {
DHashMap {
value_map: HashMap::with_capacity_and_hasher(capacity, hash_builder.clone()),
key_map: HashMap::with_capacity_and_hasher(capacity, hash_builder),
}
}
}
impl<K1, K2, V, S> DHashMap<K1, K2, V, S>
{
/// Returns the number of elements the map can hold without reallocating.
///
/// This number is a lower bound; the `DHashMap<K1, K2, V>` collection might
/// be able to hold more, but is guaranteed to be able to hold at least this many.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// let map = DHashMap::<i32, &str, &str>::with_capacity(16);
///
/// // The created DHashMap can hold at least 16 elements
/// assert!(map.capacity() >= 16);
/// // But for not it dosn't hold any element
/// assert_eq!(map.len(), 0);
/// ```
#[inline]
pub fn capacity(&self) -> usize {
// we only take into account because it contain the most important part of
// hashtable - the value
self.value_map.capacity()
}
#[inline]
pub fn len(&self) -> usize {
// we only take into account because it contain the most important part of
// hashtable - the value
self.value_map.len()
}
/// Returns `true` if the map contains no elements.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
///
/// let mut a = DHashMap::new();
/// // The created DHashMap didn't hold any element, so it's empty
/// assert!(a.is_empty() && a.len() == 0);
/// // We insert one element
/// a.insert(1, "a", "One");
/// // And can be sure that DHashMap is not empty but hold one element
/// assert!(!a.is_empty() && a.len() == 1);
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
// we only take into account because it contain the most important part of
// hashtable - the value
self.value_map.is_empty()
}
#[inline]
pub fn clear(&mut self) {
self.value_map.clear();
self.key_map.clear();
}
/// Returns a reference to the map's [`BuildHasher`].
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// use std::collections::hash_map::RandomState;
///
/// let hasher = RandomState::new();
/// let map: DHashMap<i32, i32, i32> = DHashMap::with_hasher(hasher);
/// let hasher: &RandomState = map.hasher();
/// ```
#[inline]
pub fn hasher(&self) -> &S {
self.value_map.hasher()
}
}
impl<K1, K2, V, S> DHashMap<K1, K2, V, S>
where
K1: Eq + Hash,
K2: Eq + Hash,
S: BuildHasher,
{
/// Reserves capacity for at least `additional` more elements to be inserted
/// in the `DHashMap<K1, K2, V>`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// # Panics
///
/// Panics if the new allocation size overflows [`usize::Max`] / 2.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// let mut a = DHashMap::<&str, i128, &str>::new();
/// a.insert("apple", 1, "a");
/// a.insert("banana", 2, "b");
/// a.insert("Cherry", 3, "c");
///
/// // We reserve space for additional 10 elements
/// a.reserve(10);
/// // And can see that created DHashMap can hold at least 13 elements
/// assert!(a.capacity() >= 13);
/// ```
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.value_map.reserve(additional);
self.key_map.reserve(additional);
}
/// Tries to reserve capacity for at least `additional` more elements to be inserted
/// in the given `DHashMap<K1, K2, V>`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
///
/// let mut map: DHashMap<i32, &str, isize> = DHashMap::new();
/// map.try_reserve(10).expect("something go wrong");
/// assert!(map.capacity() >= 10);
/// ```
#[inline]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.value_map.try_reserve(additional)?;
self.key_map.try_reserve(additional)
}
/// Shrinks the capacity of the map as much as possible. It will drop
/// down as much as possible while maintaining the internal rules
/// and possibly leaving some space in accordance with the resize policy.
///
/// Note that in the general case the capacity is not *guaranteed* to shrink,
/// but a zero-length DHashMap should generally shrink to capacity zero.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
/// let mut a = DHashMap::<i32, &str, &str>::with_capacity(16);
///
/// // This DHashMap can hold at least 16 element
/// let capacity_before_shrink = a.capacity();
/// assert!(capacity_before_shrink >= 16);
///
/// // And after shrink it capacity is less that before
/// a.shrink_to_fit();
/// assert!(a.capacity() < capacity_before_shrink);
///
/// // If we reserve some memory and insert some elements
/// a.reserve(100);
/// a.insert(1, "a", "One");
/// a.insert(1, "b", "Two");
/// assert!(a.capacity() >= 100);
///
/// // After shrink_to_fit method the capacity If we reserve some memory and insert some elements
/// a.shrink_to_fit();
/// assert!(a.capacity() >= 2 && a.capacity() < 100);
/// ```
#[inline]
pub fn shrink_to_fit(&mut self) {
self.value_map.shrink_to_fit();
self.key_map.shrink_to_fit();
}
/// Shrinks the capacity of the map with a lower limit. It will drop
/// down no lower than the supplied limit while maintaining the internal rules
/// and possibly leaving some space in accordance with the resize policy.
///
/// If the current capacity is less than the lower limit, this is a no-op.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
///
/// let mut map: DHashMap<i32, i32, i32> = DHashMap::with_capacity(100);
/// map.insert(1, 2, 3);
/// map.insert(4, 5, 6);
/// map.insert(7, 8, 9);
/// assert!(map.capacity() >= 100);
/// map.shrink_to(10);
/// assert!(map.capacity() >= 10 && map.capacity() < 100);
/// map.shrink_to(0);
/// assert!(map.capacity() >= 3 && map.capacity() < 10);
/// ```
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.value_map.shrink_to(min_capacity);
self.key_map.shrink_to(min_capacity);
}
/// Tries to gets the given keys' corresponding entry in the map for in-place manipulation.
///
/// Returns [`Entry`] enum if `all` of the following is `true`:
/// - Both key #1 and key #2 are vacant or already exists with some value.
/// - Both key #1 and key #2 refer to the same value.
///
/// When the above statements is `false`, [`entry`](DHashMap::entry) method return [`EntryError`] structure
/// which contains the [`ErrorKind`] enum, and the values of provided keys (that can be used for another purpose).
///
/// Depending on the points below, different [`ErrorKind`] variants may be returned:
/// - When key #1 is vacant, but key #2 is already exists with some value the returned [`ErrorKind`] variant
/// is [`ErrorKind::VacantK1AndOccupiedK2`].
/// - When key #1 is already exists with some value, but key #2 is vacant the returned [`ErrorKind`] variant
/// is [`ErrorKind::OccupiedK1AndVacantK2`].
/// - When both key #1 and key #2 is already exists with some values, but points to different entries (values)
/// the returned [`ErrorKind`] variant is [`ErrorKind::KeysPointsToDiffEntries`].
///
/// # Examples
///
/// ```
/// use double_map::{DHashMap, ErrorKind};
///
/// let mut letters = DHashMap::new();
///
/// for ch in "a short treatise on fungi".chars() {
/// if let Ok(entry) = letters.entry(ch.clone(), ch) {
/// let counter = entry.or_insert(0);
/// *counter += 1;
/// }
/// }
///
/// // Return [`ErrorKind::OccupiedK1AndVacantK2`] if key #1 is already exists with some value, but key #2 is vacant.
/// let error_kind = letters.entry('s', 'y').unwrap_err().error;
/// assert_eq!(error_kind, ErrorKind::OccupiedK1AndVacantK2);
/// // Return [`ErrorKind::VacantK1AndOccupiedK2`] if key #1 is vacant, but key #2 is already exists with some value.
/// let error_kind = letters.entry('y', 's').unwrap_err().error;
/// assert_eq!(error_kind, ErrorKind::VacantK1AndOccupiedK2);
///
/// // Return [`ErrorKind::KeysPointsToDiffEntries`] if both key #1 and key #2 are already exists with some values,
/// // but points to different entries (values).
/// let error_kind = letters.entry('s', 't').unwrap_err().error;
/// assert_eq!(error_kind, ErrorKind::KeysPointsToDiffEntries);
/// ```
#[inline]
pub fn entry(&mut self, k1: K1, k2: K2) -> Result<Entry<'_, K1, K2, V>, EntryError<K1, K2>> {
if let Some((key2_exist, _)) = self.value_map.get(&k1) {
if let Some(key1_exist) = self.key_map.get(&k2) {
return if k1 == *key1_exist && k2 == *key2_exist {
Ok(self.map_occupied_entry(k1, k2))
} else {
Err(EntryError {
error: ErrorKind::KeysPointsToDiffEntries,
keys: (k1, k2),
})
};
} else {
Err(EntryError {
error: ErrorKind::OccupiedK1AndVacantK2,
keys: (k1, k2),
})
}
} else {
return if self.key_map.get(&k2).is_some() {
Err(EntryError {
error: ErrorKind::VacantK1AndOccupiedK2,
keys: (k1, k2),
})
} else {
Ok(self.map_vacant_entry(k1, k2))
};
}
}
// This function used only inside this crate. Both entry are occupied
#[inline]
fn map_occupied_entry(&mut self, k1: K1, k2: K2) -> Entry<'_, K1, K2, V> {
let raw_v = self.value_map.entry(k1);
let raw_k = self.key_map.entry(k2);
match raw_v {
hash_map::Entry::Occupied(base_v) => match raw_k {
hash_map::Entry::Occupied(base_k) => {
Entry::Occupied(OccupiedEntry { base_v, base_k })
}
_ => unreachable!(),
},
_ => unreachable!(),
}
}
// This function used only inside this crate. Both entry are vacant
#[inline]
fn map_vacant_entry(&mut self, k1: K1, k2: K2) -> Entry<'_, K1, K2, V> {
let raw_v = self.value_map.entry(k1);
let raw_k = self.key_map.entry(k2);
match raw_v {
hash_map::Entry::Vacant(base_v) => match raw_k {
hash_map::Entry::Vacant(base_k) => Entry::Vacant(VacantEntry { base_v, base_k }),
_ => unreachable!(),
},
_ => unreachable!(),
}
}
/// Returns a reference to the value corresponding to the given primary key (key #1).
///
/// The key may be any borrowed form of the map's key type, but
/// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
/// the key type.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
///
/// let mut map = DHashMap::new();
/// map.insert(1, "a", "One");
/// assert_eq!(map.get_key1(&1), Some(&"One"));
/// assert_eq!(map.get_key1(&2), None);
/// ```
#[inline]
pub fn get_key1<Q: ?Sized>(&self, k1: &Q) -> Option<&V>
where
K1: Borrow<Q>,
Q: Hash + Eq,
{
let (_, value) = self.value_map.get(k1)?;
Some(value)
}
/// Returns a reference to the value corresponding to the given secondary key (key #2).
///
/// The key may be any borrowed form of the map's key type, but
/// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
/// the key type.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
///
/// let mut map = DHashMap::new();
/// map.insert(1, "a", "One");
/// assert_eq!(map.get_key2(&"a"), Some(&"One"));
/// assert_eq!(map.get_key2(&"b"), None);
/// ```
#[inline]
pub fn get_key2<Q: ?Sized>(&self, k2: &Q) -> Option<&V>
where
K2: Borrow<Q>,
Q: Hash + Eq,
{
let key = self.key_map.get(k2)?;
let (_, value) = self.value_map.get(key)?;
Some(value)
}
#[inline]
pub fn get_mut_key1<Q: ?Sized>(&mut self, k1: &Q) -> Option<&mut V>
where
K1: Borrow<Q>,
Q: Hash + Eq,
{
let (_, value) = self.value_map.get_mut(k1)?;
Some(value)
}
#[inline]
pub fn get_mut_key2<Q: ?Sized>(&mut self, k2: &Q) -> Option<&mut V>
where
K2: Borrow<Q>,
Q: Hash + Eq,
{
let key = self.key_map.get(k2)?;
let (_, value) = self.value_map.get_mut(key)?;
Some(value)
}
}
impl<K1, K2, V, S> DHashMap<K1, K2, V, S>
where
K1: Eq + Hash + Clone,
K2: Eq + Hash + Clone,
S: BuildHasher,
{
#[inline]
pub fn insert_unchecked(&mut self, k1: K1, k2: K2, v: V) -> Option<V> {
self.key_map.insert(k2.clone(), k1.clone());
let (_, v) = self.value_map.insert(k1, (k2, v))?;
Some(v)
}
#[inline]
pub fn insert(&mut self, k1: K1, k2: K2, v: V) -> Option<Result<V, InsertError<K1, K2, V>>> {
match self.entry(k1, k2) {
Ok(entry) => match entry {
Entry::Occupied(mut entry) => {
let v = entry.insert(v);
Some(Ok(v))
}
Entry::Vacant(entry) => {
entry.insert(v);
None
}
},
Err(EntryError { error, keys }) => Some(Err(InsertError {
error,
keys,
value: v,
})),
}
}
#[inline]
pub fn try_insert(
&mut self,
k1: K1,
k2: K2,
v: V,
) -> Result<&mut V, TryInsertError<K1, K2, V>> {
match self.entry(k1, k2) {
Ok(entry) => match entry {
Entry::Occupied(entry) => {
Err(TryInsertError::Occupied(OccupiedError { entry, value: v }))
}
Entry::Vacant(entry) => Ok(entry.insert(v)),
},
Err(EntryError { error, keys }) => Err(TryInsertError::Other(InsertError {
error,
keys,
value: v,
})),
}
}
#[inline]
pub fn remove_key1<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
K1: Borrow<Q>,
Q: Hash + Eq,
{
let (key, value) = self.value_map.remove(key)?;
self.key_map.remove(&key);
Some(value)
}
#[inline]
pub fn remove_key2<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
K2: Borrow<Q>,
Q: Hash + Eq,
{
let key = self.key_map.remove(key)?;
let (_, value) = self.value_map.remove(&key)?;
Some(value)
}
}
/// A view into an occupied entry in a [`DHashMap`].
/// It is part of the [`Entry`] enum and [`OccupiedError`] struct.
#[derive(Debug)]
pub struct OccupiedEntry<'a, K1: 'a, K2: 'a, V: 'a> {
base_v: hash_map::OccupiedEntry<'a, K1, (K2, V)>,
base_k: hash_map::OccupiedEntry<'a, K2, K1>,
}
impl<'a, K1, K2, V> OccupiedEntry<'a, K1, K2, V>
where
K1: Eq + Hash + Clone,
K2: Eq + Hash + Clone,
{
/// Gets a reference to the key #1 in the entry.
///
/// # Examples
///
/// ```
/// use double_map::DHashMap;
///
/// let mut map: DHashMap<&str, u32, i32> = DHashMap::new();
/// map.entry("poneyland", 0).unwrap().or_insert(12);
/// assert_eq!(map.entry("poneyland", 0).unwrap().key1(), &"poneyland");
/// ```
#[inline]
pub fn key1(&self) -> &K1 {
self.base_v.key()
}
#[inline]
pub fn key2(&self) -> &K2 {
self.base_k.key()
}
#[inline]
pub fn keys(&self) -> (&K1, &K2) {
(self.base_v.key(), self.base_k.key())
}
#[inline]
pub fn remove_entry(self) -> (K1, K2, V) {
self.base_k.remove_entry();
let (k1, (k2, v)) = self.base_v.remove_entry();
(k1, k2, v)
}
#[inline]
pub fn get(&self) -> &V {
let (_, v) = self.base_v.get();
v
}
#[inline]
pub fn get_mut(&mut self) -> &mut V {
let (_, v) = self.base_v.get_mut();
v
}
#[inline]
pub fn into_mut(self) -> &'a mut V {
let (_, v) = self.base_v.into_mut();
v
}
#[inline]
pub fn insert(&mut self, mut value: V) -> V {
let old_value = self.get_mut();
mem::swap(&mut value, old_value);
value
}
#[inline]
pub fn remove(self) -> V {
self.remove_entry().2
}
}
/// A view into a vacant entry in a [`DHashMap`].
/// It is part of the [`Entry`] enum.
#[derive(Debug)]
pub struct VacantEntry<'a, K1: 'a, K2: 'a, V: 'a> {
base_v: hash_map::VacantEntry<'a, K1, (K2, V)>,
base_k: hash_map::VacantEntry<'a, K2, K1>,
}
impl<'a, K1: 'a, K2: 'a, V: 'a> VacantEntry<'a, K1, K2, V>
where
K1: Eq + Hash + Clone,
K2: Eq + Hash + Clone,
{
#[inline]
pub fn key1(&self) -> &K1 {
self.base_v.key()
}
#[inline]
pub fn key2(&self) -> &K2 {
self.base_k.key()
}
#[inline]
pub fn keys(&self) -> (&K1, &K2) {
(self.base_v.key(), self.base_k.key())
}
#[inline]
pub fn into_keys(self) -> (K1, K2) {
(self.base_v.into_key(), self.base_k.into_key())
}
#[inline]
pub fn insert(self, value: V) -> &'a mut V {
let k2 = self.base_k.key().clone();
self.base_k.insert(self.base_v.key().clone());
let (_, v) = self.base_v.insert((k2, value));
v
}
}
/// A view into a single entry in a map, which may either be vacant or occupied.
///
/// This `enum` is constructed from the [`entry`] method on [`DHashMap`].
///
/// [`entry`]: DHashMap::entry
#[derive(Debug)]
pub enum Entry<'a, K1: 'a, K2: 'a, V: 'a> {
/// An occupied entry.
Occupied(OccupiedEntry<'a, K1, K2, V>),
/// A vacant entry.
Vacant(VacantEntry<'a, K1, K2, V>),
}
impl<'a, K1, K2, V> Entry<'a, K1, K2, V>
where
K1: Eq + Hash + Clone,
K2: Eq + Hash + Clone,
{
#[inline]
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default),
}
}
#[inline]
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(default()),
}
}
#[inline]
pub fn or_insert_with_key1<F: FnOnce(&K1) -> V>(self, default: F) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let value = default(entry.key1());
entry.insert(value)
}
}
}
#[inline]
pub fn or_insert_with_key2<F: FnOnce(&K2) -> V>(self, default: F) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let value = default(entry.key2());
entry.insert(value)
}
}
}
#[inline]
pub fn or_insert_with_keys<F: FnOnce(&K1, &K2) -> V>(self, default: F) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let value = default(entry.key1(), entry.key2());
entry.insert(value)
}
}
}
#[inline]
pub fn key1(&self) -> &K1 {
match *self {
Entry::Occupied(ref entry) => entry.key1(),
Entry::Vacant(ref entry) => entry.key1(),
}
}
#[inline]
pub fn key2(&self) -> &K2 {
match *self {
Entry::Occupied(ref entry) => entry.key2(),
Entry::Vacant(ref entry) => entry.key2(),
}
}
#[inline]
pub fn keys(&self) -> (&K1, &K2) {
match *self {
Entry::Occupied(ref entry) => entry.keys(),
Entry::Vacant(ref entry) => entry.keys(),
}
}
#[inline]
pub fn and_modify<F>(self, f: F) -> Self
where
F: FnOnce(&mut V),
{
match self {
Entry::Occupied(mut entry) => {
f(entry.get_mut());
Entry::Occupied(entry)
}
Entry::Vacant(entry) => Entry::Vacant(entry),
}
}
}
impl<'a, K1, K2, V: Default> Entry<'a, K1, K2, V>
where
K1: Eq + Hash + Clone,
K2: Eq + Hash + Clone,
{
#[inline]
pub fn or_default(self) -> &'a mut V {
match self {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => entry.insert(Default::default()),
}
}
}
/// A view into an error kind returned by [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
/// [`try_insert`](DHashMap::try_insert) methods of the [`DHashMap`].
/// It is part of the [`EntryError`] structure, [`InsertError`] structure and [`TryInsertError`]
/// enum.
///
/// Explains why [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
/// [`try_insert`](DHashMap::try_insert) methods fail.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
/// Returns when key #1 is vacant, but key #2 is already exists with some value.
VacantK1AndOccupiedK2,
/// Returns when key #1 is already exists with some value, but key #2 is vacant.
OccupiedK1AndVacantK2,
/// Returns when both key #1 and key #2 is already exists with some values, but points
/// to different entries (values).
KeysPointsToDiffEntries,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let error_txt = match *self {
ErrorKind::OccupiedK1AndVacantK2 => "occupied key #1 but vacant key #2",
ErrorKind::VacantK1AndOccupiedK2 => "vacant key #1 but occupied key #2",
ErrorKind::KeysPointsToDiffEntries => {
"key #1 and key #2 exists, but points to different entries"
}
};
write!(f, "{}", error_txt)
}
}
impl std::error::Error for ErrorKind {}
/// The error returned by [`entry`](DHashMap::entry) method when there is no way to distinguish
/// which entry should be returned. For more information about error kinds look to [`ErrorKind`]
/// enum.
///
/// Contains the [`ErrorKind`] enum, and the values of provided keys (that can be used for another
/// purpose).
#[derive(Debug)]
pub struct EntryError<K1, K2> {
/// A view into an error kind returned by [`entry`](DHashMap::entry),
/// [`insert`](DHashMap::insert), [`try_insert`](DHashMap::try_insert) methods of the [`DHashMap`].
/// It is part of the [`EntryError`] structure, [`InsertError`] structure and [`TryInsertError`]
/// enum. Explains [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
/// [`try_insert`](DHashMap::try_insert) methods fail. For more information about error
/// kind look to [`ErrorKind`] enum.
pub error: ErrorKind,
/// The provided values of keys that was returned because of error. For more information about
/// error kind look to [`ErrorKind`] enum.
pub keys: (K1, K2),
}
impl<K1: Debug, K2: Debug> fmt::Display for EntryError<K1, K2> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let key_txt = match self.error {
ErrorKind::VacantK1AndOccupiedK2 => format!(
"key #1 = {:?} - vacant, but key #2 = {:?} - exist",
self.keys.0, self.keys.1
),
ErrorKind::OccupiedK1AndVacantK2 => format!(
"key #1 = {:?} - exist, but key #2 = {:?} - vacant",
self.keys.0, self.keys.1
),
ErrorKind::KeysPointsToDiffEntries => format!(
"key #1 = {:?} and key #2 = {:?} points to different entries",
self.keys.0, self.keys.1
),
};
write!(f, "failed to get entry, because {}", key_txt)
}
}
impl<K1: Debug, K2: Debug> std::error::Error for EntryError<K1, K2> {}
/// The error returned by [`insert`](DHashMap::insert) method (and also
/// [`try_insert`](DHashMap::try_insert) method) when there is no way to distinguish
/// how given value with key #1 and key #2 should be inserted. It is also part of the
/// [`TryInsertError`] enum which if returned by [`try_insert`](DHashMap::try_insert) method
/// of [`DHashMap`]. For more information about error kinds look to [`ErrorKind`] enum.
///
/// Contains the [`ErrorKind`] enum, the provided keys and value that were not inserted.
/// These returned keys and value can be used for another purpose.
#[derive(Debug)]
pub struct InsertError<K1, K2, V> {
/// A view into an error kind returned by [`entry`](DHashMap::entry),
/// [`insert`](DHashMap::insert), [`try_insert`](DHashMap::try_insert) methods of the [`DHashMap`].
/// It is part of the [`EntryError`] structure, [`InsertError`] structure and [`TryInsertError`]
/// enum. Explains [`entry`](DHashMap::entry), [`insert`](DHashMap::insert),
/// [`try_insert`](DHashMap::try_insert) methods fail. For more information about error
/// kind look to [`ErrorKind`] enum.
pub error: ErrorKind,
/// The provided keys that was returned because of error. For more information about
/// error kind look to [`ErrorKind`] enum.
pub keys: (K1, K2),
/// The value which was not inserted because of the error. For more information about error
/// kind look to [`ErrorKind`] enum.
pub value: V,
}
impl<K1: Debug, K2: Debug, V: Debug> fmt::Display for InsertError<K1, K2, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let key_txt = match self.error {
ErrorKind::VacantK1AndOccupiedK2 => format!(
"key #1 = {:?} - vacant, but key #2 = {:?} - exist",
self.keys.0, self.keys.1
),
ErrorKind::OccupiedK1AndVacantK2 => format!(
"key #1 = {:?} - exist, but key #2 = {:?} - vacant",
self.keys.0, self.keys.1
),
ErrorKind::KeysPointsToDiffEntries => format!(
"key #1 = {:?} and key #2 = {:?} points to different entries",
self.keys.0, self.keys.1
),
};
write!(
f,
"failed to insert {:?}, because of {}",
self.value, key_txt
)
}
}
impl<K1: Debug, K2: Debug, V: Debug> std::error::Error for InsertError<K1, K2, V> {}
/// The error returned by [`try_insert`](DHashMap::try_insert) (as a part of the [`TryInsertError`]
/// enum) when the keys already exists and points to the same value.
///
/// Contains the occupied entry, and the value that was not inserted. It is part of the
/// [`TryInsertError`] enum.
#[derive(Debug)]
pub struct OccupiedError<'a, K1: 'a, K2: 'a, V: 'a> {
/// The entry in the map that was already occupied. It contains [`OccupiedEntry`] structure
/// which is also a part of the [`Entry`] enum.
pub entry: OccupiedEntry<'a, K1, K2, V>,
/// The value which was not inserted, because the entry was already occupied.
pub value: V,
}
impl<'a, K1, K2, V> fmt::Display for OccupiedError<'a, K1, K2, V>
where
K1: Eq + Hash + Clone + Debug,
K2: Eq + Hash + Clone + Debug,
V: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"failed to insert {:?}, key #1 = {:?} and key #2 = {:?} already exist with value {:?}",
self.value,
self.entry.key1(),
self.entry.key2(),
self.entry.get(),
)
}
}
impl<'a, K1, K2, V> std::error::Error for OccupiedError<'a, K1, K2, V>
where
K1: Eq + Hash + Clone + Debug,
K2: Eq + Hash + Clone + Debug,
V: Debug,
{
}
/// The error returned by [`try_insert`](DHashMap::try_insert) method when the keys already exists
/// and points to the same value (look to [`OccupiedError`]) or there is no way to distinguish how
/// given value with key #1 and key #2 should be inserted. For more information about error kinds
/// look to [`OccupiedError`], [`InsertError`] structures and [`ErrorKind`] enum.
///
/// Depending of error kind, this enum can contain:
/// - When there is [`TryInsertError::Occupied`] variant, it contains the occupied entry, and
/// the value that was not inserted (through [`OccupiedError`] structure).
/// - When there is [`TryInsertError::Other`] variant, it contains the [`ErrorKind`] enum,
/// the provided keys and value that were not inserted (through [`InsertError`] structure).
#[derive(Debug)]
pub enum TryInsertError<'a, K1: 'a, K2: 'a, V: 'a> {
/// The error kind returned by [`try_insert`](DHashMap::try_insert) when the keys already
/// exists and points to the same value. Contains the [`OccupiedError`] structure.
Occupied(OccupiedError<'a, K1, K2, V>),
/// The error kind returned by [`try_insert`](DHashMap::try_insert) method when there is no
/// way to distinguish how given value with key #1 and key #2 should be inserted. For more
/// information about error kinds look to [`InsertError`] structure and [`ErrorKind`] enum.
///
/// Contains the [`InsertError`] structure.
Other(InsertError<K1, K2, V>),
}
impl<'a, K1, K2, V> fmt::Display for TryInsertError<'a, K1, K2, V>
where
K1: Eq + Hash + Clone + Debug,
K2: Eq + Hash + Clone + Debug,
V: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let txt = match self {
TryInsertError::Occupied(error) => error.to_string(),
TryInsertError::Other(error) => error.to_string(),
};
write!(f, "{}", txt)
}
}
impl<'a, K1, K2, V> std::error::Error for TryInsertError<'a, K1, K2, V>
where
K1: Eq + Hash + Clone + Debug,
K2: Eq + Hash + Clone + Debug,
V: Debug,
{
}