moka/cht/segment.rs
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 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
//! Segmented lock-free hash tables.
//!
//! Segmented hash tables divide their entries between a number of smaller
//! logical hash tables, or segments. Each segment is entirely independent from
//! the others, and entries are never relocated across segment boundaries.
//!
//! In the context of this crate, a segment refers specifically to an array of
//! bucket pointers. The number of segments in a hash table is rounded up to the
//! nearest power of two; this is so that selecting the segment for a key is no
//! more than a right shift to select the most significant bits of a hashed key.
//!
//! Each segment is entirely independent from the others, all operations can be
//! performed concurrently by multiple threads. Should a set of threads be
//! operating on disjoint sets of segments, the only synchronization between
//! them will be destructive interference as they access and update the bucket
//! array pointer and length for each segment.
//!
//! Compared to the unsegmented hash tables in this crate, the segmented hash
//! tables have higher concurrent write throughput for disjoint sets of keys.
//! However, the segmented hash tables have slightly lower read and
//! single-threaded write throughput. This is because the segmenting structure
//! adds another layer of indirection between the hash table and its buckets.
//!
//! The idea for segmenting hash tables was inspired by the
//! [`ConcurrentHashMap`] from OpenJDK 7, which consists of a number of
//! separately-locked segments. OpenJDK 8 introduced a striped concurrent hash
//! map that stripes a set of bucket locks across the set of buckets using the
//! least significant bits of hashed keys.
//!
//! [`ConcurrentHashMap`]: https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/concurrent/ConcurrentHashMap.java
use crate::cht::map::{
bucket::{self, BucketArray},
bucket_array_ref::BucketArrayRef,
DefaultHashBuilder,
};
use super::iter::{Iter, ScanningGet};
use std::{
borrow::Borrow,
hash::{BuildHasher, Hash},
ptr,
sync::atomic::{self, AtomicUsize, Ordering},
};
use crossbeam_epoch::Atomic;
/// A lock-free hash map implemented with segmented bucket pointer arrays, open
/// addressing, and linear probing.
///
/// By default, `Cache` uses a hashing algorithm selected to provide resistance
/// against HashDoS attacks.
///
/// The default hashing algorithm is the one used by `std::collections::HashMap`,
/// which is currently SipHash 1-3.
///
/// While its performance is very competitive for medium sized keys, other hashing
/// algorithms will outperform it for small keys such as integers as well as large
/// keys such as long strings. However those algorithms will typically not protect
/// against attacks such as HashDoS.
///
/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
/// [`default`], [`with_hasher`], [`with_capacity_and_hasher`],
/// [`with_num_segments_and_hasher`], and
/// [`with_num_segments_capacity_and_hasher`] methods. Many alternative
/// algorithms are available on crates.io, such as the [`AHash`] crate.
///
/// The number of segments can be specified on a per-`HashMap` basis using the
/// [`with_num_segments`], [`with_num_segments_and_capacity`],
/// [`with_num_segments_and_hasher`], and
/// [`with_num_segments_capacity_and_hasher`] methods. By default, the
/// `num-cpus` feature is enabled and [`new`], [`with_capacity`],
/// [`with_hasher`], and [`with_capacity_and_hasher`] will create maps with
/// twice as many segments as the system has CPUs.
///
/// It is required that the keys implement the [`Eq`] and [`Hash`] traits,
/// although this can frequently be achieved by using
/// `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself, it is
/// important that the following property holds:
///
/// ```text
/// k1 == k2 -> hash(k1) == hash(k2)
/// ```
///
/// In other words, if two keys are equal, their hashes must be equal.
///
/// It is a logic error for a key to be modified in such a way that the key's
/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
/// the [`Eq`] trait, changes while it is in the map. This is normally only
/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
///
/// [`AHash`]: https://crates.io/crates/ahash
/// [`default`]: #method.default
/// [`with_hasher`]: #method.with_hasher
/// [`with_capacity`]: #method.with_capacity
/// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
/// [`with_num_segments_and_hasher`]: #method.with_num_segments_and_hasher
/// [`with_num_segments_capacity_and_hasher`]: #method.with_num_segments_capacity_and_hasher
/// [`with_num_segments`]: #method.with_num_segments
/// [`with_num_segments_and_capacity`]: #method.with_num_segments_and_capacity
/// [`new`]: #method.new
/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Ref.html
/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
pub(crate) struct HashMap<K, V, S = DefaultHashBuilder> {
segments: Box<[Segment<K, V>]>,
build_hasher: S,
len: AtomicUsize,
segment_shift: u32,
}
#[cfg(test)]
impl<K, V> HashMap<K, V, DefaultHashBuilder> {
/// Creates an empty `HashMap` with the specified capacity.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating any bucket pointer arrays. If `capacity` is 0, the hash map
/// will not allocate any bucket pointer arrays. However, it will always
/// allocate memory for segment pointers and lengths.
///
/// The `HashMap` will be created with at least twice as many segments as
/// the system has CPUs.
pub fn with_capacity(capacity: usize) -> Self {
Self::with_num_segments_capacity_and_hasher(
default_num_segments(),
capacity,
DefaultHashBuilder::default(),
)
}
}
impl<K, V, S> HashMap<K, V, S> {
/// Creates an empty `HashMap` with the specified number of segments, using
/// `build_hasher` to hash the keys.
///
/// The hash map is initially created with a capacity of 0, so it will not
/// allocate bucket pointer arrays until it is first inserted into. However,
/// it will always allocate memory for segment pointers and lengths.
///
/// # Panics
///
/// Panics if `num_segments` is 0.
pub(crate) fn with_num_segments_and_hasher(num_segments: usize, build_hasher: S) -> Self {
Self::with_num_segments_capacity_and_hasher(num_segments, 0, build_hasher)
}
/// Creates an empty `HashMap` with the specified number of segments and
/// capacity, using `build_hasher` to hash the keys.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating any bucket pointer arrays. If `capacity` is 0, the hash map
/// will not allocate any bucket pointer arrays. However, it will always
/// allocate memory for segment pointers and lengths.
///
/// # Panics
///
/// Panics if `num_segments` is 0.
pub(crate) fn with_num_segments_capacity_and_hasher(
num_segments: usize,
capacity: usize,
build_hasher: S,
) -> Self {
assert!(num_segments > 0);
let actual_num_segments = num_segments.next_power_of_two();
let segment_shift = 64 - actual_num_segments.trailing_zeros();
let mut segments = Vec::with_capacity(actual_num_segments);
if capacity == 0 {
unsafe {
ptr::write_bytes(segments.as_mut_ptr(), 0, actual_num_segments);
segments.set_len(actual_num_segments);
}
} else {
let actual_capacity = (capacity * 2 / actual_num_segments).next_power_of_two();
for _ in 0..actual_num_segments {
segments.push(Segment {
bucket_array: Atomic::new(BucketArray::with_length(0, actual_capacity)),
len: AtomicUsize::new(0),
});
}
}
let segments = segments.into_boxed_slice();
Self {
segments,
build_hasher,
len: AtomicUsize::new(0),
segment_shift,
}
}
pub(crate) fn actual_num_segments(&self) -> usize {
self.segments.len()
}
/// Returns the number of elements in the map.
///
/// # Safety
///
/// This method on its own is safe, but other threads can add or remove
/// elements at any time.
pub(crate) fn len(&self) -> usize {
self.len.load(Ordering::Relaxed)
}
/// Returns `true` if the map contains no elements.
///
/// # Safety
///
/// This method on its own is safe, but other threads can add or remove
/// elements at any time.
pub(crate) fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the number of elements the map can hold without reallocating any
/// bucket pointer arrays.
///
/// Note that all mutating operations except removal will result in a bucket
/// being allocated or reallocated.
///
/// # Safety
///
/// This method on its own is safe, but other threads can increase the
/// capacity of each segment at any time by adding elements.
#[cfg(any(test, feature = "unstable-debug-counters"))]
pub(crate) fn capacity(&self) -> usize {
let guard = &crossbeam_epoch::pin();
self.segments
.iter()
.map(|s| s.bucket_array.load_consume(guard))
.map(|p| unsafe { p.as_ref() })
.map(|a| a.map_or(0, BucketArray::capacity))
.sum::<usize>()
}
#[cfg(test)]
/// Returns the number of segments in the map.
pub(crate) fn num_segments(&self) -> usize {
self.segments.len()
}
}
impl<K: Hash + Eq, V, S: BuildHasher> HashMap<K, V, S> {
#[inline]
pub(crate) fn contains_key(&self, hash: u64, eq: impl FnMut(&K) -> bool) -> bool {
self.get_key_value_and_then(hash, eq, |_, _| Some(()))
.is_some()
}
/// Returns a clone of the value corresponding to the key.
#[inline]
pub(crate) fn get(&self, hash: u64, eq: impl FnMut(&K) -> bool) -> Option<V>
where
V: Clone,
{
self.get_key_value_and(hash, eq, |_, v| v.clone())
}
/// Returns the result of invoking a function with a reference to the
/// key-value pair corresponding to the supplied key.
#[inline]
pub(crate) fn get_key_value_and<T>(
&self,
hash: u64,
eq: impl FnMut(&K) -> bool,
with_entry: impl FnOnce(&K, &V) -> T,
) -> Option<T> {
self.get_key_value_and_then(hash, eq, |k, v| Some(with_entry(k, v)))
}
/// Returns the result of invoking a function with a reference to the
/// key-value pair corresponding to the supplied key.
#[inline]
pub(crate) fn get_key_value_and_then<T>(
&self,
hash: u64,
eq: impl FnMut(&K) -> bool,
with_entry: impl FnOnce(&K, &V) -> Option<T>,
) -> Option<T> {
self.bucket_array_ref(hash)
.get_key_value_and_then(hash, eq, with_entry)
}
/// Inserts a key-value pair into the map, returning the result of invoking
/// a function with a reference to the key-value pair previously
/// corresponding to the supplied key.
///
/// If the map did have this key present, both the key and value are
/// updated.
#[inline]
pub fn insert_entry_and<T>(
&self,
key: K,
hash: u64,
value: V,
with_previous_entry: impl FnOnce(&K, &V) -> T,
) -> Option<T>
where
V: Clone,
{
let result = self
.bucket_array_ref(hash)
// .insert_entry_and(key, hash, value, with_previous_entry);
.insert_with_or_modify_entry_and(
key,
hash,
|| value,
|_k, v| v.clone(),
with_previous_entry,
);
if result.is_none() {
self.len.fetch_add(1, Ordering::Relaxed);
}
result
}
/// Removes a key from the map, returning a clone of the value previously
/// corresponding to the key.
#[inline]
pub(crate) fn remove(&self, hash: u64, eq: impl FnMut(&K) -> bool) -> Option<V>
where
V: Clone,
{
self.remove_entry_if_and(hash, eq, |_, _| true, |_, v| v.clone())
}
/// Removes a key from the map, returning a clone of the key-value pair
/// previously corresponding to the key.
#[inline]
pub(crate) fn remove_entry(&self, hash: u64, eq: impl FnMut(&K) -> bool) -> Option<(K, V)>
where
K: Clone,
V: Clone,
{
self.remove_entry_if_and(hash, eq, |_, _| true, |k, v| (k.clone(), v.clone()))
}
/// Removes a key from the map if a condition is met, returning a clone of
/// the value previously corresponding to the key.
///
/// `condition` will be invoked at least once if [`Some`] is returned. It
/// may also be invoked one or more times if [`None`] is returned.
///
/// [`Some`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
/// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
pub(crate) fn remove_if(
&self,
hash: u64,
eq: impl FnMut(&K) -> bool,
condition: impl FnMut(&K, &V) -> bool,
) -> Option<V>
where
V: Clone,
{
self.remove_entry_if_and(hash, eq, condition, move |_, v| v.clone())
}
/// Removes a key from the map if a condition is met, returning the result
/// of invoking a function with a reference to the key-value pair previously
/// corresponding to the key.
///
/// `condition` will be invoked at least once if [`Some`] is returned. It
/// may also be invoked one or more times if [`None`] is returned.
///
/// [`Some`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
/// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
#[inline]
pub(crate) fn remove_entry_if_and<T>(
&self,
hash: u64,
eq: impl FnMut(&K) -> bool,
condition: impl FnMut(&K, &V) -> bool,
with_previous_entry: impl FnOnce(&K, &V) -> T,
) -> Option<T> {
self.bucket_array_ref(hash)
.remove_entry_if_and(hash, eq, condition, move |k, v| {
self.len.fetch_sub(1, Ordering::Relaxed);
with_previous_entry(k, v)
})
}
/// If no value corresponds to the key, invoke a default function to insert
/// a new key-value pair into the map. Otherwise, modify the existing value
/// and return a clone of the value previously corresponding to the key.
///
/// `on_insert` may be invoked, even if [`None`] is returned.
///
/// `on_modify` will be invoked at least once if [`Some`] is returned. It
/// may also be invoked one or more times if [`None`] is returned.
///
/// [`Some`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
/// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
#[inline]
pub(crate) fn insert_with_or_modify(
&self,
key: K,
hash: u64,
on_insert: impl FnOnce() -> V,
on_modify: impl FnMut(&K, &V) -> V,
) -> Option<V>
where
V: Clone,
{
self.insert_with_or_modify_entry_and(key, hash, on_insert, on_modify, |_, v| v.clone())
}
/// If no value corresponds to the key, invoke a default function to insert
/// a new key-value pair into the map. Otherwise, modify the existing value
/// and return the result of invoking a function with a reference to the
/// key-value pair previously corresponding to the supplied key.
///
/// `on_insert` may be invoked, even if [`None`] is returned.
///
/// `on_modify` will be invoked at least once if [`Some`] is returned. It
/// may also be invoked one or more times if [`None`] is returned.
///
/// [`Some`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
/// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
#[inline]
pub(crate) fn insert_with_or_modify_entry_and<T>(
&self,
key: K,
hash: u64,
on_insert: impl FnOnce() -> V,
on_modify: impl FnMut(&K, &V) -> V,
with_old_entry: impl FnOnce(&K, &V) -> T,
) -> Option<T> {
let result = self.bucket_array_ref(hash).insert_with_or_modify_entry_and(
key,
hash,
on_insert,
on_modify,
with_old_entry,
);
if result.is_none() {
self.len.fetch_add(1, Ordering::Relaxed);
}
result
}
#[inline]
pub(crate) fn insert_if_not_present(&self, key: K, hash: u64, value: V) -> Option<V>
where
V: Clone,
{
let result = self.bucket_array_ref(hash).insert_if_not_present_and(
key,
hash,
|| value,
|_, v| v.clone(),
);
if result.is_none() {
self.len.fetch_add(1, Ordering::Relaxed);
}
result
}
pub(crate) fn keys<T>(&self, segment: usize, with_key: impl FnMut(&K) -> T) -> Option<Vec<T>> {
if segment >= self.segments.len() {
return None;
}
let Segment {
ref bucket_array,
ref len,
} = self.segments[segment];
let bucket_array_ref = BucketArrayRef {
bucket_array,
build_hasher: &self.build_hasher,
len,
};
Some(bucket_array_ref.keys(with_key))
}
pub(crate) fn iter(&self) -> Iter<'_, K, V>
where
K: Clone,
V: Clone,
{
Iter::with_single_cache_segment(self, self.actual_num_segments())
}
#[inline]
pub(crate) fn hash<Q>(&self, key: &Q) -> u64
where
Q: Hash + Eq + ?Sized,
K: Borrow<Q>,
{
bucket::hash(&self.build_hasher, key)
}
}
impl<K, V, S> ScanningGet<K, V> for HashMap<K, V, S>
where
K: Hash + Eq + Clone,
V: Clone,
S: BuildHasher,
{
fn scanning_get(&self, key: &K) -> Option<V> {
let hash = self.hash(key);
self.get_key_value_and_then(hash, |k| k == key, |_k, v| Some(v.clone()))
}
fn keys(&self, cht_segment: usize) -> Option<Vec<K>> {
self.keys(cht_segment, Clone::clone)
}
}
impl<K, V, S> Drop for HashMap<K, V, S> {
fn drop(&mut self) {
// Important: Since we are using a dummy guard returned by `unprotected`,
// those `defer_*` functions will be executed immediately.
let guard = unsafe { &crossbeam_epoch::unprotected() };
atomic::fence(Ordering::Acquire);
for Segment {
bucket_array: this_bucket_array,
..
} in self.segments.iter()
{
let mut current_ptr = this_bucket_array.load(Ordering::Relaxed, guard);
while let Some(current_ref) = unsafe { current_ptr.as_ref() } {
let next_ptr = current_ref.next.load(Ordering::Relaxed, guard);
for this_bucket_ptr in current_ref
.buckets
.iter()
.map(|b| b.load(Ordering::Relaxed, guard))
.filter(|p| !p.is_null())
{
if bucket::is_tombstone(this_bucket_ptr) {
// Only delete tombstones from the newest bucket array.
// The only way this becomes a memory leak is if there was a
// panic during a rehash, in which case we are going to say
// that running destructors and freeing memory is
// best-effort, and our best effort is to not do it
if next_ptr.is_null() {
// Since this bucket is a tombstone, its value should have
// been dropped already. So, here, we only drop the key.
unsafe { bucket::defer_acquire_destroy(guard, this_bucket_ptr) };
}
} else {
// This bucket is live. Drop its key and value. (Fixes #176)
unsafe { bucket::defer_destroy_bucket(guard, this_bucket_ptr) };
}
}
unsafe { bucket::defer_acquire_destroy(guard, current_ptr) };
current_ptr = next_ptr;
}
}
}
}
impl<K, V, S> HashMap<K, V, S> {
#[inline]
fn bucket_array_ref(&'_ self, hash: u64) -> BucketArrayRef<'_, K, V, S> {
let index = self.segment_index_from_hash(hash);
let Segment {
ref bucket_array,
ref len,
} = self.segments[index];
BucketArrayRef {
bucket_array,
build_hasher: &self.build_hasher,
len,
}
}
#[inline]
fn segment_index_from_hash(&'_ self, hash: u64) -> usize {
if self.segment_shift == 64 {
0
} else {
(hash >> self.segment_shift) as usize
}
}
}
struct Segment<K, V> {
bucket_array: Atomic<BucketArray<K, V>>,
len: AtomicUsize,
}
#[cfg(test)]
fn default_num_segments() -> usize {
crate::common::available_parallelism() * 2
}
#[cfg(test)]
mod tests {
use std::{
collections::BTreeMap,
sync::{Arc, Barrier},
thread::{spawn, JoinHandle},
};
use super::*;
use crate::cht::test_util::{run_deferred, DropNotifier, NoisyDropper};
#[test]
fn single_segment() {
let map =
HashMap::with_num_segments_capacity_and_hasher(1, 0, DefaultHashBuilder::default());
assert!(map.is_empty());
assert_eq!(map.len(), 0);
let key = "key1";
let hash = map.hash(key);
assert_eq!(map.insert_entry_and(key, hash, 5, |_, v| *v), None);
assert_eq!(map.get(hash, |k| k == &key), Some(5));
assert!(!map.is_empty());
assert_eq!(map.len(), 1);
assert_eq!(map.remove(hash, |k| k == &key), Some(5));
assert!(map.is_empty());
assert_eq!(map.len(), 0);
run_deferred();
}
#[test]
fn insert_if_not_present() {
let map =
HashMap::with_num_segments_capacity_and_hasher(1, 0, DefaultHashBuilder::default());
let key = "key1";
let hash = map.hash(key);
assert_eq!(map.insert_if_not_present(key, hash, 5), None);
assert_eq!(map.get(hash, |k| k == &key), Some(5));
assert_eq!(map.insert_if_not_present(key, hash, 6), Some(5));
assert_eq!(map.get(hash, |k| k == &key), Some(5));
assert_eq!(map.remove(hash, |k| k == &key), Some(5));
assert_eq!(map.insert_if_not_present(key, hash, 7), None);
assert_eq!(map.get(hash, |k| k == &key), Some(7));
assert_eq!(map.remove(hash, |k| k == &key), Some(7));
assert!(map.is_empty());
assert_eq!(map.len(), 0);
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_insert_if_not_present() {
const NUM_THREADS: usize = 64;
const MAX_VALUE: usize = 512;
let hashmap = Arc::new(HashMap::with_capacity(0));
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|thread_id| {
let hashmap = Arc::clone(&hashmap);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
let mut success_count = 0usize;
for key in 0..MAX_VALUE {
let hash = hashmap.hash(&key);
let result = hashmap.insert_if_not_present(key, hash, thread_id);
if result.is_none() {
success_count += 1;
}
}
(thread_id, success_count)
})
})
.collect();
// Collect the results from the threads and insert into a BTreeMap with
// thread_id as key and success_count as value.
let results1 = threads
.into_iter()
.map(JoinHandle::join)
.collect::<Result<BTreeMap<_, _>, _>>()
.expect("Got an error from a thread");
assert_eq!(hashmap.len(), MAX_VALUE);
// Verify that the sum of success insertion counts should be MAX_VALUE.
let sum_of_insertions: usize = results1.values().sum();
assert_eq!(sum_of_insertions, MAX_VALUE);
// Get all entries from the cht HashMap and turn them into the same format
// (BTreeMap) to results1.
// Initialize results2.
let mut results2 = (0..NUM_THREADS)
.map(|thread_id| (thread_id, 0usize))
.collect::<BTreeMap<_, _>>();
// Get all entries from the cht MashMap.
for key in 0..MAX_VALUE {
let hash = hashmap.hash(&key);
if let Some(thread_id) = hashmap.get(hash, |&k| k == key) {
let count = results2.get_mut(&thread_id).unwrap();
*count += 1;
}
}
// Verify that they are the same.
assert_eq!(results1, results2);
run_deferred();
}
#[test]
fn insertion() {
const MAX_VALUE: i32 = 512;
let map = HashMap::with_capacity(MAX_VALUE as usize);
for i in 0..MAX_VALUE {
assert_eq!(map.insert_entry_and(i, map.hash(&i), i, |_, v| *v), None);
assert!(!map.is_empty());
assert_eq!(map.len(), (i + 1) as usize);
for j in 0..=i {
let hash = map.hash(&j);
assert_eq!(map.get(hash, |&k| k == j), Some(j));
assert_eq!(map.insert_entry_and(j, hash, j, |_, v| *v), Some(j));
}
for l in i + 1..MAX_VALUE {
assert_eq!(map.get(map.hash(&l), |&k| k == l), None);
}
}
run_deferred();
}
#[test]
fn growth() {
const MAX_VALUE: i32 = 512;
let map = HashMap::with_capacity(0);
for i in 0..MAX_VALUE {
assert_eq!(map.insert_entry_and(i, map.hash(&i), i, |_, v| *v), None);
assert!(!map.is_empty());
assert_eq!(map.len(), (i + 1) as usize);
for j in 0..=i {
let hash = map.hash(&j);
assert_eq!(map.get(hash, |&k| k == j), Some(j));
assert_eq!(map.insert_entry_and(j, hash, j, |_, v| *v), Some(j));
}
for l in i + 1..MAX_VALUE {
assert_eq!(map.get(map.hash(&l), |&k| k == l), None);
}
}
run_deferred();
}
// Ignore this test and some other tests on 32-bit mips targets to avoid the following
// error on QEMU user space emulator:
//
// memory allocation of 1052 bytes failed
// process didn't exit successfully: ... (signal: 6, SIGABRT: process abort signal)
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_insertion() {
const MAX_VALUE: i32 = 512;
const NUM_THREADS: usize = 64;
const MAX_INSERTED_VALUE: i32 = (NUM_THREADS as i32) * MAX_VALUE;
let map = Arc::new(HashMap::with_capacity(MAX_INSERTED_VALUE as usize));
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in (0..MAX_VALUE).map(|j| j + (i as i32 * MAX_VALUE)) {
assert_eq!(map.insert_entry_and(j, map.hash(&j), j, |_, v| *v), None);
}
})
})
.collect();
for result in threads.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert!(!map.is_empty());
assert_eq!(map.len(), MAX_INSERTED_VALUE as usize);
for i in 0..MAX_INSERTED_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(i));
}
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_growth() {
const MAX_VALUE: i32 = 512;
const NUM_THREADS: usize = 64;
const MAX_INSERTED_VALUE: i32 = (NUM_THREADS as i32) * MAX_VALUE;
let map = Arc::new(HashMap::with_capacity(0));
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in (0..MAX_VALUE).map(|j| j + (i as i32 * MAX_VALUE)) {
assert_eq!(map.insert_entry_and(j, map.hash(&j), j, |_, v| *v), None);
}
})
})
.collect();
for result in threads.into_iter().map(|t| t.join()) {
assert!(result.is_ok());
}
assert!(!map.is_empty());
assert_eq!(map.len(), MAX_INSERTED_VALUE as usize);
for i in 0..MAX_INSERTED_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(i));
}
run_deferred();
}
#[test]
fn removal() {
const MAX_VALUE: i32 = 512;
let map = HashMap::with_capacity(MAX_VALUE as usize);
for i in 0..MAX_VALUE {
assert_eq!(map.insert_entry_and(i, map.hash(&i), i, |_, v| *v), None);
}
for i in 0..MAX_VALUE {
assert_eq!(map.remove(map.hash(&i), |&k| k == i), Some(i));
}
assert!(map.is_empty());
assert_eq!(map.len(), 0);
for i in 0..MAX_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), None);
}
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_removal() {
const MAX_VALUE: i32 = 512;
const NUM_THREADS: usize = 64;
const MAX_INSERTED_VALUE: i32 = (NUM_THREADS as i32) * MAX_VALUE;
let map = HashMap::with_capacity(MAX_INSERTED_VALUE as usize);
for i in 0..MAX_INSERTED_VALUE {
assert_eq!(map.insert_entry_and(i, map.hash(&i), i, |_, v| *v), None);
}
let map = Arc::new(map);
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in (0..MAX_VALUE).map(|j| j + (i as i32 * MAX_VALUE)) {
assert_eq!(map.remove(map.hash(&j), |&k| k == j), Some(j));
}
})
})
.collect();
for result in threads.into_iter().map(|t| t.join()) {
assert!(result.is_ok());
}
assert_eq!(map.len(), 0);
for i in 0..MAX_INSERTED_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), None);
}
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_insertion_and_removal() {
const MAX_VALUE: i32 = 512;
const NUM_THREADS: usize = 64;
const MAX_INSERTED_VALUE: i32 = (NUM_THREADS as i32) * MAX_VALUE * 2;
const INSERTED_MIDPOINT: i32 = MAX_INSERTED_VALUE / 2;
let map = HashMap::with_capacity(MAX_INSERTED_VALUE as usize);
for i in INSERTED_MIDPOINT..MAX_INSERTED_VALUE {
assert_eq!(map.insert_entry_and(i, map.hash(&i), i, |_, v| *v), None);
}
let map = Arc::new(map);
let barrier = Arc::new(Barrier::new(NUM_THREADS * 2));
#[allow(clippy::needless_collect)]
let insert_threads: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in (0..MAX_VALUE).map(|j| j + (i as i32 * MAX_VALUE)) {
assert_eq!(map.insert_entry_and(j, map.hash(&j), j, |_, v| *v), None);
}
})
})
.collect();
#[allow(clippy::needless_collect)]
let remove_threads: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in (0..MAX_VALUE).map(|j| INSERTED_MIDPOINT + j + (i as i32 * MAX_VALUE))
{
assert_eq!(map.remove(map.hash(&j), |&k| k == j), Some(j));
}
})
})
.collect();
for result in insert_threads
.into_iter()
.chain(remove_threads)
.map(|t| t.join())
{
assert!(result.is_ok());
}
assert!(!map.is_empty());
assert_eq!(map.len(), INSERTED_MIDPOINT as usize);
for i in 0..INSERTED_MIDPOINT {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(i));
}
for i in INSERTED_MIDPOINT..MAX_INSERTED_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), None);
}
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_growth_and_removal() {
const MAX_VALUE: i32 = 512;
const NUM_THREADS: usize = 64;
const MAX_INSERTED_VALUE: i32 = (NUM_THREADS as i32) * MAX_VALUE * 2;
const INSERTED_MIDPOINT: i32 = MAX_INSERTED_VALUE / 2;
let map = HashMap::with_capacity(INSERTED_MIDPOINT as usize);
for i in INSERTED_MIDPOINT..MAX_INSERTED_VALUE {
assert_eq!(map.insert_entry_and(i, map.hash(&i), i, |_, v| *v), None);
}
let map = Arc::new(map);
let barrier = Arc::new(Barrier::new(NUM_THREADS * 2));
#[allow(clippy::needless_collect)]
let insert_threads: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in (0..MAX_VALUE).map(|j| j + (i as i32 * MAX_VALUE)) {
assert_eq!(map.insert_entry_and(j, map.hash(&j), j, |_, v| *v), None);
}
})
})
.collect();
#[allow(clippy::needless_collect)]
let remove_threads: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in (0..MAX_VALUE).map(|j| INSERTED_MIDPOINT + j + (i as i32 * MAX_VALUE))
{
assert_eq!(map.remove(map.hash(&j), |&k| k == j), Some(j));
}
})
})
.collect();
for result in insert_threads
.into_iter()
.chain(remove_threads)
.map(JoinHandle::join)
{
assert!(result.is_ok());
}
assert!(!map.is_empty());
assert_eq!(map.len(), INSERTED_MIDPOINT as usize);
for i in 0..INSERTED_MIDPOINT {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(i));
}
for i in INSERTED_MIDPOINT..MAX_INSERTED_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), None);
}
run_deferred();
}
#[test]
fn insert_with_or_modify() {
let map = HashMap::with_capacity(0);
let key = "key1";
let hash = map.hash(&key);
assert_eq!(
map.insert_with_or_modify(key, hash, || 1, |_, x| x + 1),
None
);
assert_eq!(map.get(hash, |&k| k == key), Some(1));
assert_eq!(
map.insert_with_or_modify(key, hash, || 1, |_, x| x + 1),
Some(1)
);
assert_eq!(map.get(hash, |&k| k == key), Some(2));
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_insert_with_or_modify() {
const NUM_THREADS: usize = 64;
const MAX_VALUE: i32 = 512;
let map = Arc::new(HashMap::with_capacity(0));
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|_| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in 0..MAX_VALUE {
map.insert_with_or_modify(j, map.hash(&j), || 1, |_, x| x + 1);
}
})
})
.collect();
for result in threads.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert_eq!(map.len(), MAX_VALUE as usize);
for i in 0..MAX_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(NUM_THREADS as i32));
}
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_overlapped_insertion() {
const NUM_THREADS: usize = 64;
const MAX_VALUE: i32 = 512;
let map = Arc::new(HashMap::with_capacity(MAX_VALUE as usize));
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|_| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in 0..MAX_VALUE {
map.insert_entry_and(j, map.hash(&j), j, |_, v| *v);
}
})
})
.collect();
for result in threads.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert_eq!(map.len(), MAX_VALUE as usize);
for i in 0..MAX_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(i));
}
run_deferred();
}
// Ignore this test on 32-bit mips and armv5te targets to avoid the following
// error on QEMU user space emulator:
//
// (mips)
// memory allocation of 1052 bytes failed
// process didn't exit successfully: ... (signal: 6, SIGABRT: process abort signal)
//
// (armv5te)
// process didn't exit successfully: ... (signal: 4, SIGILL: illegal instruction)
//
#[cfg_attr(any(armv5te, mips), ignore)]
#[test]
fn concurrent_overlapped_growth() {
const NUM_THREADS: usize = 64;
const MAX_VALUE: i32 = 512;
let map = Arc::new(HashMap::with_capacity(1));
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|_| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in 0..MAX_VALUE {
map.insert_entry_and(j, map.hash(&j), j, |_, v| *v);
}
})
})
.collect();
for result in threads.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert_eq!(map.len(), MAX_VALUE as usize);
for i in 0..MAX_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(i));
}
run_deferred();
}
#[cfg_attr(mips, ignore)]
#[test]
fn concurrent_overlapped_removal() {
const NUM_THREADS: usize = 64;
const MAX_VALUE: i32 = 512;
let map = HashMap::with_capacity(MAX_VALUE as usize);
for i in 0..MAX_VALUE {
map.insert_entry_and(i, map.hash(&i), i, |_, v| *v);
}
let map = Arc::new(map);
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let threads: Vec<_> = (0..NUM_THREADS)
.map(|_| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in 0..MAX_VALUE {
let prev_value = map.remove(map.hash(&j), |&k| k == j);
if let Some(v) = prev_value {
assert_eq!(v, j);
}
}
})
})
.collect();
for result in threads.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert!(map.is_empty());
assert_eq!(map.len(), 0);
for i in 0..MAX_VALUE {
assert_eq!(map.get(map.hash(&i), |&k| k == i), None);
}
run_deferred();
}
#[test]
fn drop_value() {
let key_parent = Arc::new(DropNotifier::new());
let value_parent = Arc::new(DropNotifier::new());
{
let map = HashMap::with_capacity(0);
let hash = map.hash(&0);
assert_eq!(
map.insert_entry_and(
NoisyDropper::new(Arc::clone(&key_parent), 0),
hash,
NoisyDropper::new(Arc::clone(&value_parent), 0),
|_, _| ()
),
None
);
assert!(!map.is_empty());
assert_eq!(map.len(), 1);
map.get_key_value_and(hash, |k| k == &0, |_k, v| assert_eq!(v, &0));
map.remove_entry_if_and(hash, |k| k == &0, |_, _| true, |_k, v| assert_eq!(v, &0));
assert!(map.is_empty());
assert_eq!(map.len(), 0);
assert_eq!(map.get_key_value_and(hash, |k| k == &0, |_, _| ()), None);
run_deferred();
assert!(!key_parent.was_dropped());
assert!(value_parent.was_dropped());
}
run_deferred();
assert!(key_parent.was_dropped());
assert!(value_parent.was_dropped());
}
#[test]
fn drop_many_values() {
const NUM_VALUES: usize = 1 << 16;
let key_parents: Vec<_> = std::iter::repeat_with(|| Arc::new(DropNotifier::new()))
.take(NUM_VALUES)
.collect();
let value_parents: Vec<_> = std::iter::repeat_with(|| Arc::new(DropNotifier::new()))
.take(NUM_VALUES)
.collect();
{
let map = HashMap::with_capacity(0);
assert!(map.is_empty());
assert_eq!(map.len(), 0);
for (i, (this_key_parent, this_value_parent)) in
key_parents.iter().zip(value_parents.iter()).enumerate()
{
assert_eq!(
map.insert_entry_and(
NoisyDropper::new(Arc::clone(this_key_parent), i),
map.hash(&i),
NoisyDropper::new(Arc::clone(this_value_parent), i),
|_, _| ()
),
None
);
assert!(!map.is_empty());
assert_eq!(map.len(), i + 1);
}
for i in 0..NUM_VALUES {
assert_eq!(
map.get_key_value_and(
map.hash(&i),
|k| k == &i,
|k, v| {
assert_eq!(**k, i);
assert_eq!(*v, i);
}
),
Some(())
);
}
for i in 0..NUM_VALUES {
assert_eq!(
map.remove_entry_if_and(
map.hash(&i),
|k| k == &i,
|_, _| true,
|k, v| {
assert_eq!(**k, i);
assert_eq!(*v, i);
}
),
Some(())
);
}
assert!(map.is_empty());
assert_eq!(map.len(), 0);
run_deferred();
let live_key_count =
NUM_VALUES - key_parents.iter().filter(|k| k.was_dropped()).count();
let bucket_array_len = map.capacity() * 2;
assert_eq!(bucket_array_len, map.num_segments() * 128 * 2);
if !cfg!(circleci) {
// TODO: FIXME: These assertions sometimes fail when cargo tarpaulin
// is used on Circle CI.
assert!(live_key_count <= bucket_array_len / 10);
for this_value_parent in value_parents.iter() {
assert!(this_value_parent.was_dropped());
}
}
for i in 0..NUM_VALUES {
assert_eq!(
map.get_key_value_and(map.hash(&i), |k| k == &i, |_, _| ()),
None
);
}
} // The map should be dropped here.
run_deferred();
for this_key_parent in key_parents.into_iter() {
assert!(this_key_parent.was_dropped());
}
for this_value_parent in value_parents.into_iter() {
assert!(this_value_parent.was_dropped());
}
}
#[test]
fn drop_many_values_concurrent() {
const NUM_THREADS: usize = 64;
const NUM_VALUES_PER_THREAD: usize = 512;
const NUM_VALUES: usize = NUM_THREADS * NUM_VALUES_PER_THREAD;
let key_parents: Arc<Vec<_>> = Arc::new(
std::iter::repeat_with(|| Arc::new(DropNotifier::new()))
.take(NUM_VALUES)
.collect(),
);
let value_parents: Arc<Vec<_>> = Arc::new(
std::iter::repeat_with(|| Arc::new(DropNotifier::new()))
.take(NUM_VALUES)
.collect(),
);
{
let map = Arc::new(HashMap::with_capacity(0));
assert!(map.is_empty());
assert_eq!(map.len(), 0);
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let handles: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
let key_parents = Arc::clone(&key_parents);
let value_parents = Arc::clone(&value_parents);
spawn(move || {
barrier.wait();
let these_key_parents = &key_parents
[i * NUM_VALUES_PER_THREAD..(i + 1) * NUM_VALUES_PER_THREAD];
let these_value_parents = &value_parents
[i * NUM_VALUES_PER_THREAD..(i + 1) * NUM_VALUES_PER_THREAD];
for (j, (this_key_parent, this_value_parent)) in these_key_parents
.iter()
.zip(these_value_parents.iter())
.enumerate()
{
let key_value = (i * NUM_VALUES_PER_THREAD + j) as i32;
let hash = map.hash(&key_value);
assert_eq!(
map.insert_entry_and(
NoisyDropper::new(Arc::clone(this_key_parent), key_value),
hash,
NoisyDropper::new(Arc::clone(this_value_parent), key_value),
|_, _| ()
),
None
);
}
})
})
.collect();
for result in handles.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert!(!map.is_empty());
assert_eq!(map.len(), NUM_VALUES);
run_deferred();
for this_key_parent in key_parents.iter() {
assert!(!this_key_parent.was_dropped());
}
for this_value_parent in value_parents.iter() {
assert!(!this_value_parent.was_dropped());
}
for i in (0..NUM_VALUES).map(|i| i as i32) {
assert_eq!(
map.get_key_value_and(
map.hash(&i),
|k| k == &i,
|k, v| {
assert_eq!(**k, i);
assert_eq!(*v, i);
}
),
Some(())
);
}
#[allow(clippy::needless_collect)]
let handles: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in 0..NUM_VALUES_PER_THREAD {
let key_value = (i * NUM_VALUES_PER_THREAD + j) as i32;
assert_eq!(
map.remove_entry_if_and(
map.hash(&key_value),
|k| k == &key_value,
|_, _| true,
|k, v| {
assert_eq!(**k, key_value);
assert_eq!(*v, key_value);
}
),
Some(())
);
}
})
})
.collect();
for result in handles.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert!(map.is_empty());
assert_eq!(map.len(), 0);
run_deferred();
let live_key_count =
NUM_VALUES - key_parents.iter().filter(|k| k.was_dropped()).count();
let bucket_array_len = map.capacity() * 2;
assert_eq!(bucket_array_len, map.num_segments() * 128 * 2);
assert!(live_key_count <= bucket_array_len / 10);
for this_value_parent in value_parents.iter() {
assert!(this_value_parent.was_dropped());
}
for i in (0..NUM_VALUES).map(|i| i as i32) {
assert_eq!(
map.get_key_value_and(map.hash(&i), |k| k == &i, |_, _| ()),
None
);
}
} // The map should be dropped here.
run_deferred();
for this_key_parent in key_parents.iter() {
assert!(this_key_parent.was_dropped());
}
for this_value_parent in value_parents.iter() {
assert!(this_value_parent.was_dropped());
}
}
#[test]
fn drop_map_after_concurrent_updates() {
const NUM_THREADS: usize = 64;
const NUM_VALUES_PER_THREAD: usize = 512;
const NUM_VALUES: usize = NUM_THREADS * NUM_VALUES_PER_THREAD;
let key_parents: Arc<Vec<_>> = Arc::new(
std::iter::repeat_with(|| Arc::new(DropNotifier::new()))
.take(NUM_VALUES)
.collect(),
);
let value_parents: Arc<Vec<_>> = Arc::new(
std::iter::repeat_with(|| Arc::new(DropNotifier::new()))
.take(NUM_VALUES)
.collect(),
);
{
let map = Arc::new(HashMap::with_capacity(0));
assert!(map.is_empty());
assert_eq!(map.len(), 0);
let barrier = Arc::new(Barrier::new(NUM_THREADS));
#[allow(clippy::needless_collect)]
let handles: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
let key_parents = Arc::clone(&key_parents);
let value_parents = Arc::clone(&value_parents);
spawn(move || {
barrier.wait();
let these_key_parents = &key_parents
[i * NUM_VALUES_PER_THREAD..(i + 1) * NUM_VALUES_PER_THREAD];
let these_value_parents = &value_parents
[i * NUM_VALUES_PER_THREAD..(i + 1) * NUM_VALUES_PER_THREAD];
for (j, (this_key_parent, this_value_parent)) in these_key_parents
.iter()
.zip(these_value_parents.iter())
.enumerate()
{
let key_value = (i * NUM_VALUES_PER_THREAD + j) as i32;
let hash = map.hash(&key_value);
assert_eq!(
map.insert_entry_and(
NoisyDropper::new(Arc::clone(this_key_parent), key_value),
hash,
NoisyDropper::new(Arc::clone(this_value_parent), key_value),
|_, _| ()
),
None
);
}
})
})
.collect();
for result in handles.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert!(!map.is_empty());
assert_eq!(map.len(), NUM_VALUES);
run_deferred();
for this_key_parent in key_parents.iter() {
assert!(!this_key_parent.was_dropped());
}
for this_value_parent in value_parents.iter() {
assert!(!this_value_parent.was_dropped());
}
for i in (0..NUM_VALUES).map(|i| i as i32) {
assert_eq!(
map.get_key_value_and(
map.hash(&i),
|k| k == &i,
|k, v| {
assert_eq!(**k, i);
assert_eq!(*v, i);
}
),
Some(())
);
}
#[allow(clippy::needless_collect)]
let handles: Vec<_> = (0..NUM_THREADS)
.map(|i| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
spawn(move || {
barrier.wait();
for j in 0..NUM_VALUES_PER_THREAD {
let key_value = (i * NUM_VALUES_PER_THREAD + j) as i32;
if key_value % 4 == 0 {
assert_eq!(
map.remove_entry_if_and(
map.hash(&key_value),
|k| k == &key_value,
|_, _| true,
|k, v| {
assert_eq!(**k, key_value);
assert_eq!(*v, key_value);
}
),
Some(())
);
}
}
})
})
.collect();
for result in handles.into_iter().map(JoinHandle::join) {
assert!(result.is_ok());
}
assert!(!map.is_empty());
assert_eq!(map.len(), NUM_VALUES / 4 * 3);
} // The map should be dropped here.
run_deferred();
for this_key_parent in key_parents.iter() {
assert!(this_key_parent.was_dropped());
}
for this_value_parent in value_parents.iter() {
assert!(this_value_parent.was_dropped());
}
}
#[test]
fn remove_if() {
const NUM_VALUES: i32 = 512;
let is_even = |_: &i32, v: &i32| *v % 2 == 0;
let map = HashMap::with_capacity(0);
for i in 0..NUM_VALUES {
assert_eq!(map.insert_entry_and(i, map.hash(&i), i, |_, v| *v), None);
}
for i in 0..NUM_VALUES {
if is_even(&i, &i) {
assert_eq!(map.remove_if(map.hash(&i), |&k| k == i, is_even), Some(i));
} else {
assert_eq!(map.remove_if(map.hash(&i), |&k| k == i, is_even), None);
}
}
for i in (0..NUM_VALUES).filter(|i| i % 2 == 0) {
assert_eq!(map.get(map.hash(&i), |&k| k == i), None);
}
for i in (0..NUM_VALUES).filter(|i| i % 2 != 0) {
assert_eq!(map.get(map.hash(&i), |&k| k == i), Some(i));
}
run_deferred();
}
#[test]
fn keys_in_single_segment() {
let map =
HashMap::with_num_segments_capacity_and_hasher(1, 0, DefaultHashBuilder::default());
assert!(map.is_empty());
assert_eq!(map.len(), 0);
const NUM_KEYS: usize = 200;
for i in 0..NUM_KEYS {
let hash = map.hash(&i);
assert_eq!(map.insert_entry_and(i, hash, i, |_, v| *v), None);
}
assert!(!map.is_empty());
assert_eq!(map.len(), NUM_KEYS);
let mut keys = map.keys(0, |k| *k).unwrap();
assert_eq!(keys.len(), NUM_KEYS);
keys.sort_unstable();
for (i, key) in keys.into_iter().enumerate() {
assert_eq!(i, key);
}
for i in (0..NUM_KEYS).step_by(2) {
assert_eq!(map.remove(map.hash(&i), |&k| k == i), Some(i));
}
assert!(!map.is_empty());
assert_eq!(map.len(), NUM_KEYS / 2);
let mut keys = map.keys(0, |k| *k).unwrap();
assert_eq!(keys.len(), NUM_KEYS / 2);
keys.sort_unstable();
for (i, key) in keys.into_iter().enumerate() {
assert_eq!(i, key / 2);
}
run_deferred();
}
}