concurrent_slotmap/lib.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 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
#![allow(unused_unsafe, clippy::inline_always)]
#![warn(rust_2018_idioms, missing_debug_implementations)]
#![forbid(unsafe_op_in_unsafe_fn, clippy::undocumented_unsafe_blocks)]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
use alloc::borrow::Cow;
use core::{
cell::UnsafeCell,
fmt, hint,
iter::{self, FusedIterator},
mem::MaybeUninit,
num::NonZeroU32,
ops::Deref,
panic::{RefUnwindSafe, UnwindSafe},
slice,
sync::atomic::{
AtomicU32, AtomicU64,
Ordering::{Acquire, Relaxed, Release},
},
};
use virtual_buffer::vec::Vec;
pub mod epoch;
/// The slot index used to signify the lack thereof.
const NIL: u32 = u32::MAX;
/// The number of low bits that can be used for tagged generations.
const TAG_BITS: u32 = 8;
/// The mask for tagged generations.
const TAG_MASK: u32 = (1 << TAG_BITS) - 1;
#[cfg_attr(not(doc), repr(C))]
pub struct SlotMap<T, C: Collector<T> = DefaultCollector> {
slots: Vec<Slot<T>>,
len: AtomicU32,
global: epoch::GlobalHandle,
collector: C,
_alignment1: CacheAligned,
/// The free-list. This is the list of slots which have already been dropped and are ready to
/// be claimed by insert operations.
free_list: AtomicU32,
_alignment2: CacheAligned,
/// Free-lists queued for inclusion in the `free_list`. Since the global epoch can only be
/// advanced if all pinned local epochs are pinned in the current global epoch, we only need
/// two free-lists in the queue: one for the current global epoch and one for the previous
/// epoch. This way a thread can always push a slot into list `(epoch / 2) % 2`, and whenever
/// the global epoch is advanced, since we know that the lag can be at most one step, we can be
/// certain that the list which was lagging behind before the global epoch was advanced is now
/// safe to drop and prepend to the `free_list`.
///
/// The atomic packs the list's head in the lower 32 bits and the epoch of the last push in the
/// upper 32 bits. The epoch must not be updated if it would be going backwards; it's only
/// updated when the last epoch is at least 2 steps behind the local epoch, at which point -
/// after removing the list from the queue and updating the epoch - we can be certain that no
/// other threads are accessing any of the slots in the list.
free_list_queue: [AtomicU64; 2],
}
impl<T, C: Collector<T>> UnwindSafe for SlotMap<T, C> {}
impl<T, C: Collector<T>> RefUnwindSafe for SlotMap<T, C> {}
impl<T> SlotMap<T, DefaultCollector> {
#[must_use]
pub fn new(max_capacity: u32) -> Self {
Self::with_global(max_capacity, epoch::GlobalHandle::new())
}
#[must_use]
pub fn with_global(max_capacity: u32, global: epoch::GlobalHandle) -> Self {
Self::with_global_and_collector(max_capacity, global, DefaultCollector)
}
}
impl<T, C: Collector<T>> SlotMap<T, C> {
#[must_use]
pub fn with_collector(max_capacity: u32, collector: C) -> Self {
Self::with_global_and_collector(max_capacity, epoch::GlobalHandle::new(), collector)
}
#[must_use]
pub fn with_global_and_collector(
max_capacity: u32,
global: epoch::GlobalHandle,
collector: C,
) -> Self {
SlotMap {
slots: Vec::new(max_capacity as usize),
len: AtomicU32::new(0),
global,
collector,
_alignment1: CacheAligned,
free_list: AtomicU32::new(NIL),
_alignment2: CacheAligned,
free_list_queue: [
AtomicU64::new(u64::from(NIL)),
AtomicU64::new(u64::from(NIL) | 2 << 32),
],
}
}
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
#[inline]
#[must_use]
pub fn capacity(&self) -> u32 {
self.slots.capacity() as u32
}
#[inline]
#[must_use]
pub fn len(&self) -> u32 {
self.len.load(Relaxed)
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
#[must_use]
pub fn global(&self) -> &epoch::GlobalHandle {
&self.global
}
#[inline]
#[must_use]
pub fn collector(&self) -> &C {
&self.collector
}
/// # Panics
///
/// Panics if `guard.global()` does not equal `self.global()`.
#[inline]
pub fn insert<'a>(&'a self, value: T, guard: impl Into<Cow<'a, epoch::Guard<'a>>>) -> SlotId {
self.insert_inner(value, 0, guard.into())
}
/// # Panics
///
/// - Panics if `guard.global()` does not equal `self.global()`.
/// - Panics if `tag` has more than the low 8 bits set.
#[inline]
pub fn insert_with_tag<'a>(
&'a self,
value: T,
tag: u32,
guard: impl Into<Cow<'a, epoch::Guard<'a>>>,
) -> SlotId {
self.insert_inner(value, tag, guard.into())
}
#[allow(clippy::needless_pass_by_value)]
fn insert_inner<'a>(&'a self, value: T, tag: u32, guard: Cow<'a, epoch::Guard<'a>>) -> SlotId {
assert_eq!(guard.global(), &self.global);
assert_eq!(tag & !TAG_MASK, 0);
let mut free_list_head = self.free_list.load(Acquire);
let mut backoff = Backoff::new();
loop {
if free_list_head == NIL {
break;
}
// SAFETY: We always push indices of existing slots into the free-lists and the slots
// vector never shrinks, therefore the index must have staid in bounds.
let slot = unsafe { self.slots.get_unchecked(free_list_head as usize) };
let next_free = slot.next_free.load(Relaxed);
match self
.free_list
.compare_exchange_weak(free_list_head, next_free, Release, Acquire)
{
Ok(_) => {
// SAFETY: `SlotMap::remove[_mut]` guarantees that the free-list only contains
// slots that are no longer read by any threads, and we have removed the slot
// from the free-list such that no other threads can be writing the same slot.
unsafe { slot.value.get().cast::<T>().write(value) };
let new_generation = slot
.generation
.fetch_add(OCCUPIED_BIT | tag, Release)
.wrapping_add(OCCUPIED_BIT | tag);
self.len.fetch_add(1, Relaxed);
// SAFETY: `SlotMap::remove[_mut]` guarantees that a freed slot has its
// generation's `OCCUPIED_BIT` unset, and since we incremented the generation,
// the bit must have been flipped again.
return unsafe { SlotId::new_unchecked(free_list_head, new_generation) };
}
Err(new_head) => {
free_list_head = new_head;
backoff.spin();
}
}
}
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = self.slots.push(Slot::new(value, tag)) as u32;
self.len.fetch_add(1, Relaxed);
// SAFETY: The `OCCUPIED_BIT` is set.
unsafe { SlotId::new_unchecked(index, OCCUPIED_BIT | tag) }
}
pub fn insert_mut(&mut self, value: T) -> SlotId {
self.insert_with_tag_mut(value, 0)
}
/// # Panics
///
/// Panics if `tag` has more than the low 8 bits set.
pub fn insert_with_tag_mut(&mut self, value: T, tag: u32) -> SlotId {
assert_eq!(tag & !TAG_MASK, 0);
let free_list_head = *self.free_list.get_mut();
if free_list_head != NIL {
// SAFETY: We always push indices of existing slots into the free-lists and the slots
// vector never shrinks, therefore the index must have staid in bounds.
let slot = unsafe { self.slots.get_unchecked_mut(free_list_head as usize) };
let new_generation = slot.generation.get_mut().wrapping_add(OCCUPIED_BIT | tag);
*slot.generation.get_mut() = new_generation;
*self.free_list.get_mut() = *slot.next_free.get_mut();
*slot.value.get_mut() = MaybeUninit::new(value);
*self.len.get_mut() += 1;
// SAFETY: `SlotMap::remove[_mut]` guarantees that a freed slot has its generation's
// `OCCUPIED_BIT` unset, and since we incremented the generation, the bit must have been
// flipped again.
return unsafe { SlotId::new_unchecked(free_list_head, new_generation) };
}
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = self.slots.push_mut(Slot::new(value, tag)) as u32;
*self.len.get_mut() += 1;
// SAFETY: The `OCCUPIED_BIT` is set.
unsafe { SlotId::new_unchecked(index, OCCUPIED_BIT | tag) }
}
/// # Panics
///
/// Panics if `guard.global()` does not equal `self.global()`.
#[inline]
pub fn remove<'a>(
&'a self,
id: SlotId,
guard: impl Into<Cow<'a, epoch::Guard<'a>>>,
) -> Option<Ref<'a, T>> {
self.remove_inner(id, guard.into())
}
fn remove_inner<'a>(
&'a self,
id: SlotId,
guard: Cow<'a, epoch::Guard<'a>>,
) -> Option<Ref<'a, T>> {
assert_eq!(guard.global(), &self.global);
let slot = self.slots.get(id.index as usize)?;
let new_generation = (id.generation() & !TAG_MASK).wrapping_add(OCCUPIED_BIT);
// This works thanks to the invariant of `SlotId` that the `OCCUPIED_BIT` of its generation
// must be set. That means that the only outcome possible in case of success here is that
// the `OCCUPIED_BIT` is unset and the generation is advanced.
if slot
.generation
.compare_exchange(id.generation(), new_generation, Acquire, Relaxed)
.is_err()
{
return None;
}
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value is
// visible here.
// * The `compare_exchange` above succeeded, which means that the previous generation of the
// slot must have matched `id.generation`. By `SlotId`'s invariant, its generation's
// occupied bit must be set. Since the generation matched, the slot's occupied bit must
// have been set, which makes reading the value safe as the only way the occupied bit can
// be set is in `SlotMap::insert[_mut]` after initialization of the slot.
// * We unset the slot's `OCCUPIED_BIT` such that no other threads can be attempting to push
// it into the free-lists.
Some(unsafe { self.remove_inner_inner(id.index, guard) })
}
// Inner indeed.
unsafe fn remove_inner_inner<'a>(
&'a self,
index: u32,
guard: Cow<'a, epoch::Guard<'a>>,
) -> Ref<'a, T> {
// SAFETY: The caller must ensure that `index` is in bounds.
let slot = unsafe { self.slots.get_unchecked(index as usize) };
let epoch = guard.epoch();
let queued_list = &self.free_list_queue[((epoch >> 1) & 1) as usize];
let mut queued_state = queued_list.load(Acquire);
let mut backoff = Backoff::new();
loop {
let queued_head = (queued_state & 0xFFFF_FFFF) as u32;
let queued_epoch = (queued_state >> 32) as u32;
let epoch_interval = epoch.wrapping_sub(queued_epoch);
if epoch_interval == 0 {
slot.next_free.store(queued_head, Relaxed);
let new_state = u64::from(index) | u64::from(queued_epoch) << 32;
match queued_list.compare_exchange_weak(queued_state, new_state, Release, Acquire) {
Ok(_) => {
self.len.fetch_sub(1, Relaxed);
// SAFETY: The caller must ensure that the inner value was initialized and
// that said write was synchronized with and made visible here.
break unsafe { Ref { slot, guard } };
}
Err(new_state) => {
queued_state = new_state;
backoff.spin();
}
}
} else {
let local_epoch_is_behind_queue = epoch_interval & (1 << 31) != 0;
// TODO: What's preventing this? If we pushed into the list as above in this case,
// it could happen that:
// * Thread A loads global epoch, preempts.
// * Thread B advances the global epoch twice to epoch E.
// * Thread A pins itself in epoch E - 4.
// * Thread A removes slot S, sees the last push into the queued list was E - 4.
// * Thread B removes slot P, sees the last push into the queued list was E - 4,
// drops slot S which could still be accessed by thread A.
assert!(!local_epoch_is_behind_queue);
debug_assert!(epoch_interval >= 4);
slot.next_free.store(NIL, Relaxed);
let new_state = u64::from(index) | u64::from(epoch) << 32;
match queued_list.compare_exchange_weak(queued_state, new_state, Release, Acquire) {
Ok(_) => {
self.len.fetch_sub(1, Relaxed);
// SAFETY: Having ended up here, the global epoch must have been advanced
// at least 2 steps from the last push into the queued list and we removed
// the list from the queue, which means that no other threads can be
// accessing any of the slots in the list.
unsafe { self.collect_unchecked(queued_head) };
// SAFETY: The caller must ensure that the inner value was initialized and
// that said write was synchronized with and made visible here.
break unsafe { Ref { slot, guard } };
}
Err(new_state) => {
queued_state = new_state;
backoff.spin();
}
}
}
}
}
/// # Panics
///
/// Panics if `guard.global()` does not equal `self.global()`.
pub fn try_collect(&self, guard: &epoch::Guard<'_>) {
assert_eq!(guard.global(), &self.global);
let epoch = guard.epoch();
let queued_list = &self.free_list_queue[((epoch >> 1) & 1) as usize];
let mut queued_state = queued_list.load(Acquire);
let mut backoff = Backoff::new();
loop {
let queued_head = (queued_state & 0xFFFF_FFFF) as u32;
let queued_epoch = (queued_state >> 32) as u32;
let epoch_interval = epoch.wrapping_sub(queued_epoch);
if epoch_interval == 0 {
break;
} else {
let local_epoch_is_behind_queue = epoch_interval & (1 << 31) != 0;
assert!(!local_epoch_is_behind_queue);
let new_state = u64::from(NIL) | u64::from(queued_epoch) << 32;
match queued_list.compare_exchange_weak(queued_state, new_state, Relaxed, Acquire) {
Ok(_) => {
// SAFETY: Having ended up here, the global epoch must have been advanced
// at least 2 steps from the last push into the queued list and we removed
// the list from the queue, which means that no other threads can be
// accessing any of the slots in the list.
unsafe { self.collect_unchecked(queued_head) };
break;
}
Err(new_state) => {
queued_state = new_state;
backoff.spin();
}
}
}
}
}
#[cold]
unsafe fn collect_unchecked(&self, queued_head: u32) {
if queued_head == NIL {
// There is no garbage.
return;
}
let mut queued_tail = queued_head;
let mut queued_tail_slot;
// Drop the queued free-list and find the tail slot.
loop {
// SAFETY: We always push indices of existing slots into the free-lists and the slots
// vector never shrinks, therefore the index must have staid in bounds.
queued_tail_slot = unsafe { self.slots.get_unchecked(queued_tail as usize) };
let ptr = queued_tail_slot.value.get().cast::<T>();
// SAFETY: The caller must ensure that we have exclusive access to this list.
unsafe { self.collector.collect(ptr) };
let next_free = queued_tail_slot.next_free.load(Acquire);
if next_free == NIL {
break;
}
queued_tail = next_free;
}
let mut free_list_head = self.free_list.load(Acquire);
let mut backoff = Backoff::new();
// Free the queued free-list by prepending it to the free-list.
loop {
queued_tail_slot.next_free.store(free_list_head, Relaxed);
match self.free_list.compare_exchange_weak(
free_list_head,
queued_head,
Release,
Acquire,
) {
Ok(_) => break,
Err(new_head) => {
free_list_head = new_head;
backoff.spin();
}
}
}
}
pub fn remove_mut(&mut self, id: SlotId) -> Option<T> {
let slot = self.slots.get_mut(id.index as usize)?;
let generation = *slot.generation.get_mut();
if generation == id.generation() {
*slot.generation.get_mut() = (id.generation() & !TAG_MASK).wrapping_add(OCCUPIED_BIT);
*slot.next_free.get_mut() = *self.free_list.get_mut();
*self.free_list.get_mut() = id.index;
*self.len.get_mut() -= 1;
// SAFETY:
// * The mutable reference makes sure that access to the slot is synchronized.
// * We checked that `id.generation` matches the slot's generation, which includes the
// occupied bit. By `SlotId`'s invariant, its generation's occupied bit must be set.
// Since the generation matched, the slot's occupied bit must be set, which makes
// reading the value safe as the only way the occupied bit can be set is in
// `SlotMap::insert[_mut]` after initialization of the slot.
// * We incremented the slot's generation such that its `OCCUPIED_BIT` is unset and its
// generation is advanced, such that future attempts to access the slot will fail.
Some(unsafe { slot.value.get().cast::<T>().read() })
} else {
None
}
}
#[cfg(test)]
fn remove_index<'a>(
&'a self,
index: u32,
guard: impl Into<Cow<'a, epoch::Guard<'a>>>,
) -> Option<Ref<'a, T>> {
self.remove_index_inner(index, guard.into())
}
#[cfg(test)]
fn remove_index_inner<'a>(
&'a self,
index: u32,
guard: Cow<'a, epoch::Guard<'a>>,
) -> Option<Ref<'a, T>> {
assert_eq!(guard.global(), &self.global);
let slot = self.slots.get(index as usize)?;
let mut generation = slot.generation.load(Relaxed);
let mut backoff = Backoff::new();
loop {
if generation & OCCUPIED_BIT == 0 {
return None;
}
let new_generation = (generation & !TAG_MASK).wrapping_add(OCCUPIED_BIT);
match slot.generation.compare_exchange_weak(
generation,
new_generation,
Acquire,
Relaxed,
) {
Ok(_) => break,
Err(new_generation) => {
generation = new_generation;
backoff.spin();
}
}
}
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value is
// visible here.
// * The `compare_exchange_weak` above succeeded, which means that the previous generation
// of the slot must have had its `OCCUPIED_BIT` set, which makes reading the value safe as
// the only way the occupied bit can be set is in `SlotMap::insert[_mut]` after
// initialization of the slot.
// * We unset the slot's `OCCUPIED_BIT` such that no other threads can be attempting to push
// it into the free-lists.
Some(unsafe { self.remove_inner_inner(index, guard) })
}
/// # Panics
///
/// Panics if `guard.global()` does not equal `self.global()`.
#[inline(always)]
#[must_use]
pub fn get<'a>(
&'a self,
id: SlotId,
guard: impl Into<Cow<'a, epoch::Guard<'a>>>,
) -> Option<Ref<'a, T>> {
self.get_inner(id, guard.into())
}
#[inline(always)]
fn get_inner<'a>(&'a self, id: SlotId, guard: Cow<'a, epoch::Guard<'a>>) -> Option<Ref<'a, T>> {
assert_eq!(guard.global(), &self.global);
let slot = self.slots.get(id.index as usize)?;
let generation = slot.generation.load(Acquire);
if generation == id.generation() {
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value
// is visible here.
// * We checked that `id.generation` matches the slot's generation, which includes the
// occupied bit. By `SlotId`'s invariant, its generation's occupied bit must be set.
// Since the generation matched, the slot's occupied bit must be set, which makes
// reading the value safe as the only way the occupied bit can be set is in
// `SlotMap::insert[_mut]` after initialization of the slot.
Some(unsafe { Ref { slot, guard } })
} else {
None
}
}
/// # Safety
///
/// You must ensure that the epoch is [pinned] before you call this method and that the
/// returned reference doesn't outlive all [`epoch::Guard`]s active on the thread, or that all
/// accesses to `self` are externally synchronized (for example through the use of a `Mutex` or
/// by being single-threaded).
///
/// [pinned]: epoch::pin
#[inline(always)]
pub unsafe fn get_unprotected(&self, id: SlotId) -> Option<&T> {
let slot = self.slots.get(id.index as usize)?;
let generation = slot.generation.load(Acquire);
if generation == id.generation() {
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value
// is visible here.
// * We checked that `id.generation` matches the slot's generation, which includes the
// occupied bit. By `SlotId`'s invariant, its generation's occupied bit must be set.
// Since the generation matched, the slot's occupied bit must be set, which makes
// reading the value safe as the only way the occupied bit can be set is in
// `SlotMap::insert[_mut]` after initialization of the slot.
// * The caller must ensure that the returned reference is protected by a guard before
// the call and that the returned reference doesn't outlive said guard, or that
// synchronization is ensured externally.
Some(unsafe { slot.value_unchecked() })
} else {
None
}
}
#[inline(always)]
pub fn get_mut(&mut self, id: SlotId) -> Option<&mut T> {
let slot = self.slots.get_mut(id.index as usize)?;
let generation = *slot.generation.get_mut();
if generation == id.generation() {
// SAFETY:
// * The mutable reference makes sure that access to the slot is synchronized.
// * We checked that `id.generation` matches the slot's generation, which includes the
// occupied bit. By `SlotId`'s invariant, its generation's occupied bit must be set.
// Since the generation matched, the slot's occupied bit must be set, which makes
// reading the value safe as the only way the occupied bit can be set is in
// `SlotMap::insert[_mut]` after initialization of the slot.
Some(unsafe { slot.value_unchecked_mut() })
} else {
None
}
}
#[inline]
pub fn get_many_mut<const N: usize>(&mut self, ids: [SlotId; N]) -> Option<[&mut T; N]> {
fn get_many_check_valid<const N: usize>(ids: &[SlotId; N], len: u32) -> bool {
let mut valid = true;
for (i, id) in ids.iter().enumerate() {
valid &= id.index() < len;
for id2 in &ids[..i] {
valid &= id.index() != id2.index();
}
}
valid
}
// Our capacity can never exceed `u32::MAX`, so the length of the slots can't either.
#[allow(clippy::cast_possible_truncation)]
let len = self.slots.len() as u32;
if get_many_check_valid(&ids, len) {
// SAFETY: We checked that all indices are disjunct and in bounds of the slots vector.
unsafe { self.get_many_unchecked_mut(ids) }
} else {
None
}
}
#[inline]
unsafe fn get_many_unchecked_mut<const N: usize>(
&mut self,
ids: [SlotId; N],
) -> Option<[&mut T; N]> {
let slots_ptr = self.slots.as_mut_ptr();
let mut refs = MaybeUninit::<[&mut T; N]>::uninit();
let refs_ptr = refs.as_mut_ptr().cast::<&mut T>();
for i in 0..N {
// SAFETY: `i` is in bounds of the array.
let id = unsafe { ids.get_unchecked(i) };
// SAFETY: The caller must ensure that `ids` contains only IDs whose indices are in
// bounds of the slots vector.
let slot = unsafe { slots_ptr.add(id.index() as usize) };
// SAFETY: The caller must ensure that `ids` contains only IDs with disjunct indices.
let slot = unsafe { &mut *slot };
let generation = *slot.generation.get_mut();
if generation != id.generation() {
return None;
}
// SAFETY:
// * The mutable reference makes sure that access to the slot is synchronized.
// * We checked that `id.generation` matches the slot's generation, which includes the
// occupied bit. By `SlotId`'s invariant, its generation's occupied bit must be set.
// Since the generation matched, the slot's occupied bit must be set, which makes
// reading the value safe as the only way the occupied bit can be set is in
// `SlotMap::insert[_mut]` after initialization of the slot.
let value = unsafe { slot.value_unchecked_mut() };
// SAFETY: `i` is in bounds of the array.
unsafe { *refs_ptr.add(i) = value };
}
// SAFETY: We initialized all the elements.
Some(unsafe { refs.assume_init() })
}
/// # Panics
///
/// Panics if `guard.global()` does not equal `self.global()`.
#[inline(always)]
pub fn index<'a>(
&'a self,
index: u32,
guard: impl Into<Cow<'a, epoch::Guard<'a>>>,
) -> Option<Ref<'a, T>> {
self.index_inner(index, guard.into())
}
#[inline(always)]
fn index_inner<'a>(
&'a self,
index: u32,
guard: Cow<'a, epoch::Guard<'a>>,
) -> Option<Ref<'a, T>> {
assert_eq!(guard.global(), &self.global);
let slot = self.slots.get(index as usize)?;
let generation = slot.generation.load(Acquire);
if generation & OCCUPIED_BIT != 0 {
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value
// is visible here.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
Some(unsafe { Ref { slot, guard } })
} else {
None
}
}
/// # Safety
///
/// You must ensure that the epoch is [pinned] before you call this method and that the
/// returned reference doesn't outlive all [`epoch::Guard`]s active on the thread, or that all
/// accesses to `self` are externally synchronized (for example through the use of a `Mutex` or
/// by being single-threaded).
///
/// [pinned]: epoch::pin
#[inline(always)]
pub unsafe fn index_unprotected(&self, index: u32) -> Option<&T> {
let slot = self.slots.get(index as usize)?;
let generation = slot.generation.load(Acquire);
if generation & OCCUPIED_BIT != 0 {
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value
// is visible here.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
// * The caller must ensure that the returned reference is protected by a guard before
// the call and that the returned reference doesn't outlive said guard, or that
// synchronization is ensured externally.
Some(unsafe { slot.value_unchecked() })
} else {
None
}
}
#[inline(always)]
pub fn index_mut(&mut self, index: u32) -> Option<&mut T> {
let slot = self.slots.get_mut(index as usize)?;
let generation = *slot.generation.get_mut();
if generation & OCCUPIED_BIT != 0 {
// SAFETY:
// * The mutable reference makes sure that access to the slot is synchronized.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
Some(unsafe { slot.value_unchecked_mut() })
} else {
None
}
}
/// # Safety
///
/// `index` must be in bounds of the slots vector and the slot must have been initialized and
/// must not be free.
///
/// # Panics
///
/// Panics if `guard.global()` does not equal `self.global()`.
#[inline(always)]
pub unsafe fn index_unchecked<'a>(
&'a self,
index: u32,
guard: impl Into<Cow<'a, epoch::Guard<'a>>>,
) -> Ref<'a, T> {
// SAFETY: Ensured by the caller.
unsafe { self.index_unchecked_inner(index, guard.into()) }
}
#[inline(always)]
unsafe fn index_unchecked_inner<'a>(
&'a self,
index: u32,
guard: Cow<'a, epoch::Guard<'a>>,
) -> Ref<'a, T> {
assert_eq!(guard.global(), &self.global);
// SAFETY: The caller must ensure that the index is in bounds.
let slot = unsafe { self.slots.get_unchecked(index as usize) };
let _generation = slot.generation.load(Acquire);
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value is
// visible here.
// * The caller must ensure that the slot is initialized.
unsafe { Ref { slot, guard } }
}
/// # Safety
///
/// * `index` must be in bounds of the slots vector and the slot must have been initialized and
/// must not be free.
/// * You must ensure that the epoch is [pinned] before you call this method and that the
/// returned reference doesn't outlive all [`epoch::Guard`]s active on the thread, or that
/// all accesses to `self` are externally synchronized (for example through the use of a
/// `Mutex` or by being single-threaded).
///
/// [pinned]: epoch::pin
#[inline(always)]
pub unsafe fn index_unchecked_unprotected(&self, index: u32) -> &T {
// SAFETY: The caller must ensure that the index is in bounds.
let slot = unsafe { self.slots.get_unchecked(index as usize) };
let _generation = slot.generation.load(Acquire);
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written value is
// visible here.
// * The caller must ensure that the slot is initialized.
// * The caller must ensure that the returned reference is protected by a guard before the
// call and that the returned reference doesn't outlive said guard, or that
// synchronization is ensured externally.
unsafe { slot.value_unchecked() }
}
/// # Safety
///
/// `index` must be in bounds of the slots vector and the slot must have been initialized and
/// must not be free.
#[inline(always)]
pub unsafe fn index_unchecked_mut(&mut self, index: u32) -> &mut T {
// SAFETY: The caller must ensure that the index is in bounds.
let slot = unsafe { self.slots.get_unchecked_mut(index as usize) };
// SAFETY:
// * The mutable reference makes sure that access to the slot is synchronized.
// * The caller must ensure that the slot is initialized.
unsafe { slot.value_unchecked_mut() }
}
/// # Panics
///
/// Panics if `guard.global()` does not equal `self.global()`.
#[inline]
pub fn iter<'a>(&'a self, guard: impl Into<Cow<'a, epoch::Guard<'a>>>) -> Iter<'a, T> {
self.iter_inner(guard.into())
}
#[inline]
fn iter_inner<'a>(&'a self, guard: Cow<'a, epoch::Guard<'a>>) -> Iter<'a, T> {
assert_eq!(guard.global(), &self.global);
Iter {
slots: self.slots.iter().enumerate(),
guard,
}
}
/// # Safety
///
/// You must ensure that the epoch is [pinned] before you call this method and that the
/// returned reference doesn't outlive all [`epoch::Guard`]s active on the thread, or that all
/// accesses to `self` are externally synchronized (for example through the use of a `Mutex` or
/// by being single-threaded).
#[inline]
pub unsafe fn iter_unprotected(&self) -> IterUnprotected<'_, T> {
IterUnprotected {
slots: self.slots.iter().enumerate(),
}
}
#[inline]
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut {
slots: self.slots.iter_mut().enumerate(),
}
}
}
// We don't want to print the `_alignment` fields.
#[allow(clippy::missing_fields_in_debug)]
impl<T: fmt::Debug, C: Collector<T>> fmt::Debug for SlotMap<T, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct Slots;
impl fmt::Debug for Slots {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("[..]")
}
}
struct List<'a, T, C: Collector<T>>(&'a SlotMap<T, C>, u32);
impl<T, C: Collector<T>> fmt::Debug for List<'_, T, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut head = self.1;
let mut debug = f.debug_list();
while head != NIL {
debug.entry(&head);
// SAFETY: We always push indices of existing slots into the free-lists and the
// slots vector never shrinks, therefore the index must have staid in bounds.
let slot = unsafe { self.0.slots.get_unchecked(head as usize) };
head = slot.next_free.load(Acquire);
}
debug.finish()
}
}
struct QueuedList<'a, T, C: Collector<T>>(&'a SlotMap<T, C>, u64);
impl<T, C: Collector<T>> fmt::Debug for QueuedList<'_, T, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let state = self.1;
let head = (state & 0xFFFF_FFFF) as u32;
let epoch = (state >> 32) as u32;
let mut debug = f.debug_struct("QueuedList");
debug
.field("entries", &List(self.0, head))
.field("epoch", &epoch);
debug.finish()
}
}
let mut debug = f.debug_struct("SlotMap");
debug
.field("slots", &Slots)
.field("len", &self.len)
.field("global", &self.global)
.field("free_list", &List(self, self.free_list.load(Acquire)))
.field(
"free_list_queue",
&[
QueuedList(self, self.free_list_queue[0].load(Acquire)),
QueuedList(self, self.free_list_queue[1].load(Acquire)),
],
);
debug.finish()
}
}
impl<T, C: Collector<T>> Drop for SlotMap<T, C> {
fn drop(&mut self) {
if !core::mem::needs_drop::<T>() {
return;
}
for list in &mut self.free_list_queue {
let mut head = (*list.get_mut() & 0xFFFF_FFFF) as u32;
while head != NIL {
// SAFETY: We always push indices of existing slots into the free-lists and the
// slots vector never shrinks, therefore the index must have staid in bounds.
let slot = unsafe { self.slots.get_unchecked_mut(head as usize) };
let ptr = slot.value.get_mut().as_mut_ptr();
// SAFETY: We can be certain that this slot has been initialized, since the only
// way in which it could have been queued for freeing is in `SlotMap::remove` if
// the slot was inserted before.
unsafe { self.collector.collect(ptr) };
head = *slot.next_free.get_mut();
}
}
for slot in &mut self.slots {
if *slot.generation.get_mut() & OCCUPIED_BIT != 0 {
let ptr = slot.value.get_mut().as_mut_ptr();
// SAFETY:
// * The mutable reference makes sure that access to the slot is synchronized.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
unsafe { self.collector.collect(ptr) };
}
}
}
}
impl<'a, T, C: Collector<T>> IntoIterator for &'a mut SlotMap<T, C> {
type Item = (SlotId, &'a mut T);
type IntoIter = IterMut<'a, T>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
const OCCUPIED_BIT: u32 = 1 << TAG_BITS;
struct Slot<T> {
generation: AtomicU32,
next_free: AtomicU32,
value: UnsafeCell<MaybeUninit<T>>,
}
// SAFETY: The user of `Slot` must ensure that access to `Slot::value` is synchronized.
unsafe impl<T: Sync> Sync for Slot<T> {}
impl<T> Slot<T> {
fn new(value: T, tag: u32) -> Self {
Slot {
generation: AtomicU32::new(OCCUPIED_BIT | tag),
next_free: AtomicU32::new(NIL),
value: UnsafeCell::new(MaybeUninit::new(value)),
}
}
unsafe fn value_unchecked(&self) -> &T {
// SAFETY: The caller must ensure that access to the cell's inner value is synchronized.
let value = unsafe { &*self.value.get() };
// SAFETY: The caller must ensure that the slot has been initialized.
unsafe { value.assume_init_ref() }
}
unsafe fn value_unchecked_mut(&mut self) -> &mut T {
// SAFETY: The caller must ensure that the slot has been initialized.
unsafe { self.value.get_mut().assume_init_mut() }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SlotId {
index: u32,
generation: NonZeroU32,
}
impl SlotId {
pub const INVALID: Self = SlotId {
index: u32::MAX,
generation: NonZeroU32::MAX,
};
#[cfg(test)]
const fn new(index: u32, generation: u32) -> Self {
assert!(generation & OCCUPIED_BIT != 0);
// SAFETY: We checked that the `OCCUPIED_BIT` is set.
unsafe { SlotId::new_unchecked(index, generation) }
}
const unsafe fn new_unchecked(index: u32, generation: u32) -> Self {
// SAFETY: The caller must ensure that the `OCCUPIED_BIT` of `generation` is set, which
// means it must be non-zero.
let generation = unsafe { NonZeroU32::new_unchecked(generation) };
SlotId { index, generation }
}
#[inline(always)]
#[must_use]
pub const fn index(self) -> u32 {
self.index
}
#[inline(always)]
#[must_use]
pub const fn generation(self) -> u32 {
self.generation.get()
}
#[inline(always)]
#[must_use]
pub const fn tag(self) -> u32 {
self.generation.get() & TAG_MASK
}
}
pub struct Ref<'a, T> {
slot: &'a Slot<T>,
#[allow(dead_code)]
guard: Cow<'a, epoch::Guard<'a>>,
}
impl<T> Deref for Ref<'_, T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
// SAFETY: The constructor of `Ref` must ensure that the inner value was initialized and
// that said write was synchronized with and made visible here. As for future writes to the
// inner value, we know that none can happen as long as our `Guard` wasn't dropped.
unsafe { self.slot.value_unchecked() }
}
}
impl<T: fmt::Debug> fmt::Debug for Ref<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<T: fmt::Display> fmt::Display for Ref<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
pub struct Iter<'a, T> {
slots: iter::Enumerate<slice::Iter<'a, Slot<T>>>,
guard: Cow<'a, epoch::Guard<'a>>,
}
impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Iter").finish_non_exhaustive()
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = (SlotId, Ref<'a, T>);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
loop {
let (index, slot) = self.slots.next()?;
let generation = slot.generation.load(Acquire);
if generation & OCCUPIED_BIT != 0 {
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = index as u32;
// SAFETY: We checked that the occupied bit is set.
let id = unsafe { SlotId::new_unchecked(index, generation) };
let guard = self.guard.clone();
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written
// value is visible here.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
let r = unsafe { Ref { slot, guard } };
break Some((id, r));
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.slots.len()))
}
}
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
loop {
let (index, slot) = self.slots.next_back()?;
let generation = slot.generation.load(Acquire);
if generation & OCCUPIED_BIT != 0 {
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = index as u32;
// SAFETY: We checked that the occupied bit is set.
let id = unsafe { SlotId::new_unchecked(index, generation) };
let guard = self.guard.clone();
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written
// value is visible here.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
let r = unsafe { Ref { slot, guard } };
break Some((id, r));
}
}
}
}
impl<T> FusedIterator for Iter<'_, T> {}
pub struct IterUnprotected<'a, T> {
slots: iter::Enumerate<slice::Iter<'a, Slot<T>>>,
}
impl<T: fmt::Debug> fmt::Debug for IterUnprotected<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IterUnprotected").finish_non_exhaustive()
}
}
impl<'a, T> Iterator for IterUnprotected<'a, T> {
type Item = (SlotId, &'a T);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
loop {
let (index, slot) = self.slots.next()?;
let generation = slot.generation.load(Acquire);
if generation & OCCUPIED_BIT != 0 {
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = index as u32;
// SAFETY: We checked that the occupied bit is set.
let id = unsafe { SlotId::new_unchecked(index, generation) };
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written
// value is visible here.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
// * The caller of `SlotMap::iter_unprotected` must ensure that the returned
// iterator is protected by a guard before the call and that the returned iterator
// doesn't outlive said guard, or that synchronization is ensured externally.
let r = unsafe { slot.value_unchecked() };
break Some((id, r));
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.slots.len()))
}
}
impl<'a, T> DoubleEndedIterator for IterUnprotected<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
loop {
let (index, slot) = self.slots.next_back()?;
let generation = slot.generation.load(Acquire);
if generation & OCCUPIED_BIT != 0 {
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = index as u32;
// SAFETY: We checked that the occupied bit is set.
let id = unsafe { SlotId::new_unchecked(index, generation) };
// SAFETY:
// * The `Acquire` ordering when loading the slot's generation synchronizes with the
// `Release` ordering in `SlotMap::insert`, making sure that the newly written
// value is visible here.
// * We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
// * The caller of `SlotMap::iter_unprotected` must ensure that the returned
// iterator is protected by a guard before the call and that the returned iterator
// doesn't outlive said guard, or that synchronization is ensured externally.
let r = unsafe { slot.value_unchecked() };
break Some((id, r));
}
}
}
}
impl<T> FusedIterator for IterUnprotected<'_, T> {}
pub struct IterMut<'a, T> {
slots: iter::Enumerate<slice::IterMut<'a, Slot<T>>>,
}
impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IterMut").finish_non_exhaustive()
}
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = (SlotId, &'a mut T);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
loop {
let (index, slot) = self.slots.next()?;
let generation = *slot.generation.get_mut();
if generation & OCCUPIED_BIT != 0 {
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = index as u32;
// SAFETY: We checked that the `OCCUPIED_BIT` is set.
let id = unsafe { SlotId::new_unchecked(index, generation) };
// SAFETY: We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
let r = unsafe { slot.value_unchecked_mut() };
break Some((id, r));
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.slots.len()))
}
}
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
loop {
let (index, slot) = self.slots.next_back()?;
let generation = *slot.generation.get_mut();
if generation & OCCUPIED_BIT != 0 {
// Our capacity can never exceed `u32::MAX`.
#[allow(clippy::cast_possible_truncation)]
let index = index as u32;
// SAFETY: We checked that the `OCCUPIED_BIT` is set.
let id = unsafe { SlotId::new_unchecked(index, generation) };
// SAFETY: We checked that the slot is occupied, which means that it must have been
// initialized in `SlotMap::insert[_mut]`.
let r = unsafe { slot.value_unchecked_mut() };
break Some((id, r));
}
}
}
}
impl<T> FusedIterator for IterMut<'_, T> {}
pub trait Collector<T> {
/// # Safety
///
/// This function has the same safety preconditions and semantics as [`ptr::drop_in_place`]. It
/// must be safe to drop the value pointed to by `ptr`.
///
/// [`ptr::drop_in_place`]: core::ptr::drop_in_place
unsafe fn collect(&self, ptr: *mut T);
}
#[derive(Debug)]
pub struct DefaultCollector;
impl<T> Collector<T> for DefaultCollector {
#[inline(always)]
unsafe fn collect(&self, ptr: *mut T) {
// SAFETY: The caller must ensure that it is safe to drop the value.
unsafe { ptr.drop_in_place() }
}
}
#[repr(align(128))]
struct CacheAligned;
const SPIN_LIMIT: u32 = 6;
struct Backoff {
step: u32,
}
impl Backoff {
fn new() -> Self {
Backoff { step: 0 }
}
fn spin(&mut self) {
for _ in 0..1 << self.step {
hint::spin_loop();
}
if self.step <= SPIN_LIMIT {
self.step += 1;
}
}
}
#[cfg(test)]
mod tests {
use self::epoch::PINNINGS_BETWEEN_ADVANCE;
use super::*;
use std::thread;
#[test]
fn basic_usage1() {
let map = SlotMap::new(10);
let guard = &map.global().register_local().into_inner().pin();
let x = map.insert(69, guard);
let y = map.insert(42, guard);
assert_eq!(map.get(x, guard).as_deref(), Some(&69));
assert_eq!(map.get(y, guard).as_deref(), Some(&42));
map.remove(x, guard);
let x2 = map.insert(12, guard);
assert_eq!(map.get(x2, guard).as_deref(), Some(&12));
assert_eq!(map.get(x, guard).as_deref(), None);
map.remove(y, guard);
map.remove(x2, guard);
assert_eq!(map.get(y, guard).as_deref(), None);
assert_eq!(map.get(x2, guard).as_deref(), None);
}
#[test]
fn basic_usage2() {
let map = SlotMap::new(10);
let guard = &map.global().register_local().into_inner().pin();
let x = map.insert(1, guard);
let y = map.insert(2, guard);
let z = map.insert(3, guard);
assert_eq!(map.get(x, guard).as_deref(), Some(&1));
assert_eq!(map.get(y, guard).as_deref(), Some(&2));
assert_eq!(map.get(z, guard).as_deref(), Some(&3));
map.remove(y, guard);
let y2 = map.insert(20, guard);
assert_eq!(map.get(y2, guard).as_deref(), Some(&20));
assert_eq!(map.get(y, guard).as_deref(), None);
map.remove(x, guard);
map.remove(z, guard);
let x2 = map.insert(10, guard);
assert_eq!(map.get(x2, guard).as_deref(), Some(&10));
assert_eq!(map.get(x, guard).as_deref(), None);
let z2 = map.insert(30, guard);
assert_eq!(map.get(z2, guard).as_deref(), Some(&30));
assert_eq!(map.get(x, guard).as_deref(), None);
map.remove(x2, guard);
assert_eq!(map.get(x2, guard).as_deref(), None);
map.remove(y2, guard);
map.remove(z2, guard);
assert_eq!(map.get(y2, guard).as_deref(), None);
assert_eq!(map.get(z2, guard).as_deref(), None);
}
#[test]
fn basic_usage3() {
let map = SlotMap::new(10);
let guard = &map.global().register_local().into_inner().pin();
let x = map.insert(1, guard);
let y = map.insert(2, guard);
assert_eq!(map.get(x, guard).as_deref(), Some(&1));
assert_eq!(map.get(y, guard).as_deref(), Some(&2));
let z = map.insert(3, guard);
assert_eq!(map.get(z, guard).as_deref(), Some(&3));
map.remove(x, guard);
map.remove(z, guard);
let z2 = map.insert(30, guard);
let x2 = map.insert(10, guard);
assert_eq!(map.get(x2, guard).as_deref(), Some(&10));
assert_eq!(map.get(z2, guard).as_deref(), Some(&30));
assert_eq!(map.get(x, guard).as_deref(), None);
assert_eq!(map.get(z, guard).as_deref(), None);
map.remove(x2, guard);
map.remove(y, guard);
map.remove(z2, guard);
assert_eq!(map.get(x2, guard).as_deref(), None);
assert_eq!(map.get(y, guard).as_deref(), None);
assert_eq!(map.get(z2, guard).as_deref(), None);
}
#[test]
fn basic_usage_mut1() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(69);
let y = map.insert_mut(42);
assert_eq!(map.get_mut(x), Some(&mut 69));
assert_eq!(map.get_mut(y), Some(&mut 42));
map.remove_mut(x);
let x2 = map.insert_mut(12);
assert_eq!(map.get_mut(x2), Some(&mut 12));
assert_eq!(map.get_mut(x), None);
map.remove_mut(y);
map.remove_mut(x2);
assert_eq!(map.get_mut(y), None);
assert_eq!(map.get_mut(x2), None);
}
#[test]
fn basic_usage_mut2() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(1);
let y = map.insert_mut(2);
let z = map.insert_mut(3);
assert_eq!(map.get_mut(x), Some(&mut 1));
assert_eq!(map.get_mut(y), Some(&mut 2));
assert_eq!(map.get_mut(z), Some(&mut 3));
map.remove_mut(y);
let y2 = map.insert_mut(20);
assert_eq!(map.get_mut(y2), Some(&mut 20));
assert_eq!(map.get_mut(y), None);
map.remove_mut(x);
map.remove_mut(z);
let x2 = map.insert_mut(10);
assert_eq!(map.get_mut(x2), Some(&mut 10));
assert_eq!(map.get_mut(x), None);
let z2 = map.insert_mut(30);
assert_eq!(map.get_mut(z2), Some(&mut 30));
assert_eq!(map.get_mut(x), None);
map.remove_mut(x2);
assert_eq!(map.get_mut(x2), None);
map.remove_mut(y2);
map.remove_mut(z2);
assert_eq!(map.get_mut(y2), None);
assert_eq!(map.get_mut(z2), None);
}
#[test]
fn basic_usage_mut3() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(1);
let y = map.insert_mut(2);
assert_eq!(map.get_mut(x), Some(&mut 1));
assert_eq!(map.get_mut(y), Some(&mut 2));
let z = map.insert_mut(3);
assert_eq!(map.get_mut(z), Some(&mut 3));
map.remove_mut(x);
map.remove_mut(z);
let z2 = map.insert_mut(30);
let x2 = map.insert_mut(10);
assert_eq!(map.get_mut(x2), Some(&mut 10));
assert_eq!(map.get_mut(z2), Some(&mut 30));
assert_eq!(map.get_mut(x), None);
assert_eq!(map.get_mut(z), None);
map.remove_mut(x2);
map.remove_mut(y);
map.remove_mut(z2);
assert_eq!(map.get_mut(x2), None);
assert_eq!(map.get_mut(y), None);
assert_eq!(map.get_mut(z2), None);
}
#[test]
fn iter1() {
let map = SlotMap::new(10);
let guard = &map.global().register_local().into_inner().pin();
let x = map.insert(1, guard);
let _ = map.insert(2, guard);
let y = map.insert(3, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove(x, guard);
map.remove(y, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 2);
assert!(iter.next().is_none());
map.insert(3, guard);
map.insert(1, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert_eq!(*iter.next().unwrap().1, 1);
assert!(iter.next().is_none());
}
#[test]
fn iter2() {
let map = SlotMap::new(10);
let guard = &map.global().register_local().into_inner().pin();
let x = map.insert(1, guard);
let y = map.insert(2, guard);
let z = map.insert(3, guard);
map.remove(x, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove(y, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove(z, guard);
let mut iter = map.iter(guard);
assert!(iter.next().is_none());
}
#[test]
fn iter3() {
let map = SlotMap::new(10);
let guard = &map.global().register_local().into_inner().pin();
let _ = map.insert(1, guard);
let x = map.insert(2, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 2);
assert!(iter.next().is_none());
map.remove(x, guard);
let x = map.insert(2, guard);
let _ = map.insert(3, guard);
let y = map.insert(4, guard);
map.remove(y, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove(x, guard);
let mut iter = map.iter(guard);
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
}
#[test]
fn iter_mut1() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(1);
let _ = map.insert_mut(2);
let y = map.insert_mut(3);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove_mut(x);
map.remove_mut(y);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 2);
assert!(iter.next().is_none());
map.insert_mut(3);
map.insert_mut(1);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
}
#[test]
fn iter_mut2() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(1);
let y = map.insert_mut(2);
let z = map.insert_mut(3);
map.remove_mut(x);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove_mut(y);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove_mut(z);
let mut iter = map.iter_mut();
assert!(iter.next().is_none());
}
#[test]
fn iter_mut3() {
let mut map = SlotMap::new(10);
let _ = map.insert_mut(1);
let x = map.insert_mut(2);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 2);
assert!(iter.next().is_none());
map.remove_mut(x);
let x = map.insert_mut(2);
let _ = map.insert_mut(3);
let y = map.insert_mut(4);
map.remove_mut(y);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 2);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
map.remove_mut(x);
let mut iter = map.iter_mut();
assert_eq!(*iter.next().unwrap().1, 1);
assert_eq!(*iter.next().unwrap().1, 3);
assert!(iter.next().is_none());
}
#[test]
fn reusing_slots_mut1() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(0);
let y = map.insert_mut(0);
map.remove_mut(y);
let y2 = map.insert_mut(0);
assert_eq!(y2.index, y.index);
assert_ne!(y2.generation, y.generation);
map.remove_mut(x);
let x2 = map.insert_mut(0);
assert_eq!(x2.index, x.index);
assert_ne!(x2.generation, x.generation);
map.remove_mut(y2);
map.remove_mut(x2);
}
#[test]
fn reusing_slots_mut2() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(0);
map.remove_mut(x);
let x2 = map.insert_mut(0);
assert_eq!(x.index, x2.index);
assert_ne!(x.generation, x2.generation);
let y = map.insert_mut(0);
let z = map.insert_mut(0);
map.remove_mut(y);
map.remove_mut(x2);
let x3 = map.insert_mut(0);
let y2 = map.insert_mut(0);
assert_eq!(x3.index, x2.index);
assert_ne!(x3.generation, x2.generation);
assert_eq!(y2.index, y.index);
assert_ne!(y2.generation, y.generation);
map.remove_mut(x3);
map.remove_mut(y2);
map.remove_mut(z);
}
#[test]
fn reusing_slots_mut3() {
let mut map = SlotMap::new(10);
let x = map.insert_mut(0);
let y = map.insert_mut(0);
map.remove_mut(x);
map.remove_mut(y);
let y2 = map.insert_mut(0);
let x2 = map.insert_mut(0);
let z = map.insert_mut(0);
assert_eq!(x2.index, x.index);
assert_ne!(x2.generation, x.generation);
assert_eq!(y2.index, y.index);
assert_ne!(y2.generation, y.generation);
map.remove_mut(x2);
map.remove_mut(z);
map.remove_mut(y2);
let y3 = map.insert_mut(0);
let z2 = map.insert_mut(0);
let x3 = map.insert_mut(0);
assert_eq!(y3.index, y2.index);
assert_ne!(y3.generation, y2.generation);
assert_eq!(z2.index, z.index);
assert_ne!(z2.generation, z.generation);
assert_eq!(x3.index, x2.index);
assert_ne!(x3.generation, x2.generation);
map.remove_mut(x3);
map.remove_mut(y3);
map.remove_mut(z2);
}
#[test]
fn get_many_mut() {
let mut map = SlotMap::new(3);
let x = map.insert_mut(1);
let y = map.insert_mut(2);
let z = map.insert_mut(3);
assert_eq!(map.get_many_mut([x, y]), Some([&mut 1, &mut 2]));
assert_eq!(map.get_many_mut([y, z]), Some([&mut 2, &mut 3]));
assert_eq!(map.get_many_mut([z, x]), Some([&mut 3, &mut 1]));
assert_eq!(map.get_many_mut([x, y, z]), Some([&mut 1, &mut 2, &mut 3]));
assert_eq!(map.get_many_mut([z, y, x]), Some([&mut 3, &mut 2, &mut 1]));
assert_eq!(map.get_many_mut([x, x]), None);
assert_eq!(map.get_many_mut([x, SlotId::new(3, OCCUPIED_BIT)]), None);
map.remove_mut(y);
assert_eq!(map.get_many_mut([x, z]), Some([&mut 1, &mut 3]));
assert_eq!(map.get_many_mut([y]), None);
assert_eq!(map.get_many_mut([x, y]), None);
assert_eq!(map.get_many_mut([y, z]), None);
let y = map.insert_mut(2);
assert_eq!(map.get_many_mut([x, y, z]), Some([&mut 1, &mut 2, &mut 3]));
map.remove_mut(x);
map.remove_mut(z);
assert_eq!(map.get_many_mut([y]), Some([&mut 2]));
assert_eq!(map.get_many_mut([x]), None);
assert_eq!(map.get_many_mut([z]), None);
map.remove_mut(y);
assert_eq!(map.get_many_mut([]), Some([]));
}
#[test]
fn tagged() {
let map = SlotMap::new(1);
let guard = &map.global().register_local().into_inner().pin();
let x = map.insert_with_tag(42, 1, guard);
assert_eq!(x.generation() & TAG_MASK, 1);
assert_eq!(map.get(x, guard).as_deref(), Some(&42));
}
#[test]
fn tagged_mut() {
let mut map = SlotMap::new(1);
let x = map.insert_with_tag_mut(42, 1);
assert_eq!(x.generation() & TAG_MASK, 1);
assert_eq!(map.get_mut(x), Some(&mut 42));
}
// TODO: Testing concurrent generational collections is the most massive pain in the ass. We
// aren't testing the actual implementations but rather ones that don't take the generation into
// account because of that.
#[cfg(not(miri))]
const ITERATIONS: u32 = 1_000_000;
#[cfg(miri)]
const ITERATIONS: u32 = 1_000;
#[test]
fn multi_threaded1() {
const THREADS: u32 = 2;
let map = SlotMap::new(ITERATIONS);
thread::scope(|s| {
let inserter = || {
let local = map.global().register_local();
for _ in 0..ITERATIONS / THREADS {
map.insert(0, local.pin());
}
};
for _ in 0..THREADS {
s.spawn(inserter);
}
});
assert_eq!(map.len(), ITERATIONS);
thread::scope(|s| {
let remover = || {
let local = map.global().register_local();
for index in 0..ITERATIONS {
let _ = map.remove(SlotId::new(index, OCCUPIED_BIT), local.pin());
}
};
for _ in 0..THREADS {
s.spawn(remover);
}
});
assert_eq!(map.len(), 0);
}
// TODO: This test is just fundamentally broken.
#[test]
fn multi_threaded2() {
const CAPACITY: u32 = PINNINGS_BETWEEN_ADVANCE as u32 * 3;
let map = SlotMap::new(ITERATIONS / 2);
thread::scope(|s| {
let insert_remover = || {
let local = map.global().register_local();
for _ in 0..ITERATIONS / 6 {
let x = map.insert(0, local.pin());
let y = map.insert(0, local.pin());
map.remove(y, local.pin());
let z = map.insert(0, local.pin());
map.remove(x, local.pin());
map.remove(z, local.pin());
}
};
let iterator = || {
let local = map.global().register_local();
for _ in 0..ITERATIONS / CAPACITY * 2 {
for index in 0..CAPACITY {
if let Some(value) = map.index(index, local.pin()) {
let _ = *value;
}
}
}
};
s.spawn(iterator);
s.spawn(iterator);
s.spawn(iterator);
s.spawn(insert_remover);
});
}
#[test]
fn multi_threaded3() {
let map = SlotMap::new(ITERATIONS / 10);
thread::scope(|s| {
let inserter = || {
let local = map.global().register_local();
for i in 0..ITERATIONS {
if i % 10 == 0 {
map.insert(0, local.pin());
} else {
thread::yield_now();
}
}
};
let remover = || {
let local = map.global().register_local();
for _ in 0..ITERATIONS {
map.remove_index(0, local.pin());
}
};
let getter = || {
let local = map.global().register_local();
for _ in 0..ITERATIONS {
if let Some(value) = map.index(0, local.pin()) {
let _ = *value;
}
}
};
s.spawn(getter);
s.spawn(getter);
s.spawn(getter);
s.spawn(getter);
s.spawn(remover);
s.spawn(remover);
s.spawn(remover);
s.spawn(inserter);
});
}
}