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
//! [<img alt="github" src="https://img.shields.io/badge/github-udoprog/uniset-8da0cb?style=for-the-badge&logo=github" height="20">](https://github.com/udoprog/uniset)
//! [<img alt="crates.io" src="https://img.shields.io/crates/v/uniset.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/uniset)
//! [<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-uniset-66c2a5?style=for-the-badge&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/uniset)
//!
//! A hierarchical, growable bit set with support for in-place atomic
//! operations.
//!
//! The idea is based on [hibitset], but dynamically growing instead of having a
//! fixed capacity. By being careful with the underlying data layout, we also
//! support structural sharing between the [local] and [atomic] bitsets.
//!
//! <br>
//!
//! ## Features
//!
//! * `vec-safety` - Avoid relying on the assumption that `&mut Vec<T>` can be
//! safely coerced to `&mut Vec<U>` if `T` and `U` have an identical memory
//! layouts (enabled by default, [issue #1]).
//!
//! <br>
//!
//! ## Examples
//!
//! ```
//! use uniset::BitSet;
//!
//! let mut set = BitSet::new();
//! assert!(set.is_empty());
//! assert_eq!(0, set.capacity());
//!
//! set.set(127);
//! set.set(128);
//! assert!(!set.is_empty());
//!
//! assert!(set.test(128));
//! assert_eq!(vec![127, 128], set.iter().collect::<Vec<_>>());
//! assert!(!set.is_empty());
//!
//! assert_eq!(vec![127, 128], set.drain().collect::<Vec<_>>());
//! assert!(set.is_empty());
//! ```
//!
//! [issue #1]: https://github.com/udoprog/unicycle/issues/1
//! [hibitset]: https://docs.rs/hibitset
//! [local]: https://docs.rs/uniset/latest/uniset/struct.BitSet.html
//! [atomic]: https://docs.rs/uniset/latest/uniset/struct.AtomicBitSet.html
#![deny(missing_docs)]
#![allow(clippy::identity_op)]
use std::{
fmt, iter, mem, ops, slice,
sync::atomic::{AtomicUsize, Ordering},
};
#[cfg(feature = "vec-safety")]
use self::vec_safety::Layers;
#[cfg(not(feature = "vec-safety"))]
type Layers<T> = Vec<T>;
/// A private marker trait that promises that the implementing type has an
/// identical memory layout to another Layer].
///
/// The only purpose of this trait is to server to make [`convert_layers`]
/// safer.
///
/// # Safety
///
/// Implementer must assert that the implementing type has an identical layout
/// to a [Layer].
unsafe trait CoerceLayer {
/// The target layer being coerced into.
type Target;
}
/// Bits in a single usize.
const BITS: usize = mem::size_of::<usize>() * 8;
const BITS_SHIFT: usize = BITS.trailing_zeros() as usize;
const MAX_LAYERS: usize = BITS / 4;
/// Precalculated shifts for each layer.
///
/// The shift is used to shift the bits in a given index to the least
/// significant position so it can be used as an index for that layer.
static SHIFT: [usize; 12] = [
0,
1 * BITS_SHIFT,
2 * BITS_SHIFT,
3 * BITS_SHIFT,
4 * BITS_SHIFT,
5 * BITS_SHIFT,
6 * BITS_SHIFT,
7 * BITS_SHIFT,
8 * BITS_SHIFT,
9 * BITS_SHIFT,
10 * BITS_SHIFT,
11 * BITS_SHIFT,
];
/// Same as `SHIFT`, but shifted to the "layer above it".
static SHIFT2: [usize; 12] = [
1 * BITS_SHIFT,
2 * BITS_SHIFT,
3 * BITS_SHIFT,
4 * BITS_SHIFT,
5 * BITS_SHIFT,
6 * BITS_SHIFT,
7 * BITS_SHIFT,
8 * BITS_SHIFT,
9 * BITS_SHIFT,
10 * BITS_SHIFT,
11 * BITS_SHIFT,
12 * BITS_SHIFT,
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct LayerLayout {
/// The length of the layer.
cap: usize,
}
/// A sparse, layered bit set.
///
/// Layered bit sets support efficient iteration, union, and intersection
/// operations since they maintain summary layers of the bits which are set in
/// layers below it.
///
/// [`BitSet`] and [`AtomicBitSet`]'s are guaranteed to have an identical memory
/// layout, so they support zero-cost back and forth conversion.
///
/// The [`into_atomic`] and [`as_atomic`] methods are provided for converting to
/// an [`AtomicBitSet`].
///
/// [`into_atomic`]: BitSet::into_atomic
/// [`as_atomic`]: BitSet::as_atomic
#[repr(C)]
#[derive(Clone)]
pub struct BitSet {
/// Layers of bits.
layers: Layers<Layer>,
/// The capacity of the bitset in number of bits it can store.
cap: usize,
}
impl BitSet {
/// Construct a new, empty BitSet with an empty capacity.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::new();
/// assert!(set.is_empty());
/// assert_eq!(0, set.capacity());
/// ```
pub fn new() -> Self {
Self {
layers: Layers::new(),
cap: 0,
}
}
/// Construct a new, empty [`BitSet`] with the specified capacity.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(1024);
/// assert!(set.is_empty());
/// assert_eq!(1024, set.capacity());
/// ```
pub fn with_capacity(capacity: usize) -> Self {
let mut this = Self::new();
this.reserve(capacity);
this
}
/// Test if the bit set is empty.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(64);
/// assert!(set.is_empty());
/// set.set(2);
/// assert!(!set.is_empty());
/// set.clear(2);
/// assert!(set.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
// The top, summary layer is zero.
self.layers.last().map(|l| l[0] == 0).unwrap_or(true)
}
/// Get the current capacity of the bitset.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::new();
/// assert!(set.is_empty());
/// assert_eq!(0, set.capacity());
/// ```
pub fn capacity(&self) -> usize {
self.cap
}
/// Return a slice of the underlying, raw layers.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(128);
/// set.set(1);
/// set.set(5);
/// // Note: two layers since we specified a capacity of 128.
/// assert_eq!(vec![&[0b100010, 0][..], &[1]], set.as_slice());
/// ```
pub fn as_slice(&self) -> &[Layer] {
self.layers.as_slice()
}
/// Return a mutable slice of the underlying, raw layers.
pub fn as_mut_slice(&mut self) -> &mut [Layer] {
self.layers.as_mut_slice()
}
/// Convert in-place into an [`AtomicBitSet`].
///
/// Atomic bit sets uses structural sharing with the current set, so this
/// is a constant time `O(1)` operation.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(1024);
///
/// let atomic = set.into_atomic();
/// atomic.set(42);
///
/// let set = atomic.into_local();
/// assert!(set.test(42));
/// ```
pub fn into_atomic(mut self) -> AtomicBitSet {
AtomicBitSet {
layers: convert_layers(mem::replace(&mut self.layers, Layers::new())),
cap: mem::replace(&mut self.cap, 0),
}
}
/// Convert in-place into a reference to an [`AtomicBitSet`].
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let set = BitSet::with_capacity(1024);
///
/// set.as_atomic().set(42);
/// assert!(set.test(42));
/// ```
pub fn as_atomic(&self) -> &AtomicBitSet {
// Safety: BitSet and AtomicBitSet are guaranteed to have identical
// memory layouts.
unsafe { &*(self as *const _ as *const AtomicBitSet) }
}
/// Set the given bit.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(64);
///
/// assert!(set.is_empty());
/// set.set(2);
/// assert!(!set.is_empty());
/// ```
pub fn set(&mut self, mut position: usize) {
if position >= self.cap {
self.reserve(position + 1);
}
for layer in &mut self.layers {
let slot = position / BITS;
let offset = position % BITS;
layer.set(slot, offset);
position >>= BITS_SHIFT;
}
}
/// Clear the given bit.
///
/// # Panics
///
/// Panics if the position does not fit within the capacity of the [`BitSet`].
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(64);
///
/// set.clear(2);
/// assert!(set.is_empty());
/// set.set(2);
/// assert!(!set.is_empty());
/// set.clear(2);
/// assert!(set.is_empty());
/// set.clear(2);
/// assert!(set.is_empty());
/// ```
pub fn clear(&mut self, mut position: usize) {
if position >= self.cap {
return;
}
for layer in &mut self.layers {
let slot = position / BITS;
let offset = position % BITS;
layer.clear(slot, offset);
position >>= BITS_SHIFT;
}
}
/// Test if the given position is set.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(64);
///
/// assert!(set.is_empty());
/// set.set(2);
/// assert!(!set.is_empty());
/// assert!(set.test(2));
/// assert!(!set.test(3));
/// ```
pub fn test(&self, position: usize) -> bool {
if position >= self.cap {
return false;
}
let slot = position / BITS;
let offset = position % BITS;
self.layers[0].test(slot, offset)
}
/// Reserve enough space to store the given number of elements.
///
/// This will not reserve space for exactly as many elements specified, but
/// will round up to the closest order of magnitude of 2.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
/// let mut set = BitSet::with_capacity(128);
/// assert_eq!(128, set.capacity());
/// set.reserve(250);
/// assert_eq!(256, set.capacity());
/// ```
pub fn reserve(&mut self, cap: usize) {
if self.cap >= cap {
return;
}
let cap = round_capacity_up(cap);
let mut new = bit_set_layout(cap).peekable();
let mut old = self.layers.as_mut_slice().iter_mut();
while let (Some(layer), Some(&LayerLayout { cap, .. })) = (old.next(), new.peek()) {
debug_assert!(cap >= layer.cap);
// Layer needs to grow.
if cap > 0 {
layer.grow(cap);
}
// Skip to next new layer.
new.next();
}
if self.layers.is_empty() {
self.layers.extend(new.map(|l| Layer::with_capacity(l.cap)));
} else {
// Fill in new layers since we needed to expand.
//
// Note: structure is guaranteed to only have one usize at the top
// so we only need to bother looking at that when we grow.
for (depth, l) in (self.layers.len() - 1..).zip(new) {
let mut layer = Layer::with_capacity(l.cap);
layer[0] = if self.layers[depth][0] > 0 { 1 } else { 0 };
self.layers.push(layer);
}
}
// Add new layers!
self.cap = cap;
}
/// Create a draining iterator over the bitset, yielding all elements in
/// order of their index.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(128);
/// set.set(127);
/// set.set(32);
/// set.set(3);
///
/// assert_eq!(vec![3, 32, 127], set.drain().collect::<Vec<_>>());
/// assert!(set.is_empty());
/// ```
///
/// Draining one bit at a time.
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(128);
///
/// set.set(127);
/// set.set(32);
/// set.set(3);
///
/// assert_eq!(Some(3), set.drain().next());
/// assert_eq!(Some(32), set.drain().next());
/// assert_eq!(Some(127), set.drain().next());
/// assert!(set.is_empty());
/// ```
///
/// Saving the state of the draining iterator.
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(128);
///
/// set.set(127);
/// set.set(32);
/// set.set(3);
///
/// let mut it = set.drain();
///
/// assert_eq!(Some(3), it.next());
/// assert_eq!(Some(32), it.next());
/// assert!(it.snapshot().is_some());
/// assert_eq!(Some(127), it.next());
/// assert!(it.snapshot().is_none());
/// assert_eq!(None, it.next());
/// assert!(it.snapshot().is_none());
/// ```
pub fn drain(&mut self) -> Drain<'_> {
let depth = self.layers.len().saturating_sub(1);
Drain {
layers: self.layers.as_mut_slice(),
index: 0,
depth,
#[cfg(feature = "test-op-count")]
op_count: 0,
}
}
/// Start a drain operation using the given configuration parameters.
///
/// These are acquired from [Drain::snapshot], and can be used to resume
/// draining at a specific point.
///
/// Resuming a drain from a snapshot can be more efficient in certain
/// scenarios, like if the [`BitSet`] is very large.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(128);
///
/// set.set(127);
/// set.set(32);
/// set.set(3);
///
/// let mut it = set.drain();
///
/// assert_eq!(Some(3), it.next());
/// let snapshot = it.snapshot();
/// // Get rid of the existing iterator.
/// drop(it);
///
/// let snapshot = snapshot.expect("draining iteration hasn't ended");
///
/// let mut it = set.drain_from(snapshot);
/// assert_eq!(Some(32), it.next());
/// assert_eq!(Some(127), it.next());
/// assert_eq!(None, it.next());
/// ```
///
/// Trying to snapshot from an empty draining iterator:
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(128);
///
/// set.set(3);
///
/// let mut it = set.drain();
///
/// assert!(it.snapshot().is_some());
/// assert_eq!(Some(3), it.next());
/// assert!(it.snapshot().is_none());
/// ```
pub fn drain_from(&mut self, DrainSnapshot(index, depth): DrainSnapshot) -> Drain<'_> {
Drain {
layers: self.layers.as_mut_slice(),
index,
depth,
#[cfg(feature = "test-op-count")]
op_count: 0,
}
}
/// Create an iterator over the bitset, yielding all elements in order of
/// their index.
///
/// Note that iterator allocates a vector with a size matching the number of
/// layers in the [`BitSet`].
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(128);
/// set.set(127);
/// set.set(32);
/// set.set(3);
///
/// assert_eq!(vec![3, 32, 127], set.iter().collect::<Vec<_>>());
/// assert!(!set.is_empty());
/// ```
pub fn iter(&self) -> Iter<'_> {
let depth = self.layers.len().saturating_sub(1);
Iter {
layers: self.layers.as_slice(),
masks: [0; MAX_LAYERS],
index: 0,
depth,
#[cfg(feature = "test-op-count")]
op_count: 0,
}
}
}
impl<I: slice::SliceIndex<[Layer]>> ops::Index<I> for BitSet {
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
ops::Index::index(self.as_slice(), index)
}
}
impl<I: slice::SliceIndex<[Layer]>> ops::IndexMut<I> for BitSet {
#[inline]
fn index_mut(&mut self, index: I) -> &mut Self::Output {
ops::IndexMut::index_mut(self.as_mut_slice(), index)
}
}
impl Default for BitSet {
fn default() -> Self {
Self::new()
}
}
/// The snapshot of a drain in progress. This is created using
/// [Drain::snapshot].
///
/// See [BitSet::drain_from] for examples.
#[derive(Clone, Copy)]
pub struct DrainSnapshot(usize, usize);
/// A draining iterator of a [`BitSet`].
///
/// See [BitSet::drain] for examples.
pub struct Drain<'a> {
layers: &'a mut [Layer],
index: usize,
depth: usize,
#[cfg(feature = "test-op-count")]
pub(crate) op_count: usize,
}
impl Drain<'_> {
/// Save a snapshot of the of the draining iterator, unless it is done
/// already. This can then be used by [BitSet::drain_from] to efficiently
/// resume iteration from the given snapshot.
///
/// See [BitSet::drain_from] for examples.
pub fn snapshot(&self) -> Option<DrainSnapshot> {
if self.layers.is_empty() {
None
} else {
Some(DrainSnapshot(self.index, self.depth))
}
}
}
impl Iterator for Drain<'_> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.layers.is_empty() {
return None;
}
loop {
#[cfg(feature = "test-op-count")]
{
self.op_count += 1;
}
let offset = self.index >> SHIFT2[self.depth];
// Unsafe version:
// let slot = unsafe { self.layers.get_unchecked_mut(self.depth).get_unchecked_mut(offset) };
let slot = &mut self.layers[self.depth][offset];
if *slot == 0 {
self.layers = &mut [];
return None;
}
if self.depth > 0 {
// Advance into a deeper layer. We set the base index to
// the value of the deeper layer.
//
// We calculate the index based on the offset that we are
// currently at and the information we get at the current
// layer of bits.
self.index = (offset << SHIFT2[self.depth])
+ ((slot.trailing_zeros() as usize) << SHIFT[self.depth]);
self.depth -= 1;
continue;
}
// We are now in layer 0. The number of trailing zeros indicates
// the bit set.
let trail = slot.trailing_zeros() as usize;
// NB: if this doesn't hold, a prior layer lied and we ended up
// here in vain.
debug_assert!(trail < BITS);
let index = self.index + trail;
// NB: assert that we are actually unsetting a bit.
debug_assert!(*slot & !(1 << trail) != *slot);
// Clear the current slot.
*slot &= !(1 << trail);
// Slot is not empty yet.
if *slot != 0 {
return Some(index);
}
// Clear upper layers until we find one that is not set again -
// then use that as hour new depth.
for (depth, layer) in (1..).zip(self.layers[1..].iter_mut()) {
let offset = index >> SHIFT2[depth];
// Unsafe version:
// let slot = unsafe { layer.get_unchecked_mut(offset) };
let slot = &mut layer[offset];
// If this doesn't hold, then we have previously failed at
// populating the summary layers of the set.
debug_assert!(*slot != 0);
*slot &= !(1 << ((index >> SHIFT[depth]) % BITS));
if *slot != 0 {
// update the index to be the bottom of the next value set
// layer.
self.depth = depth;
// We calculate the index based on the offset that we are
// currently at and the information we get at the current
// layer of bits.
self.index = (offset << SHIFT2[depth])
+ ((slot.trailing_zeros() as usize) << SHIFT[depth]);
return Some(index);
}
}
// The entire bitset is cleared. We are done.
self.layers = &mut [];
return Some(index);
}
}
}
/// An iterator over a [`BitSet`].
///
/// See [BitSet::iter] for examples.
pub struct Iter<'a> {
layers: &'a [Layer],
masks: [u8; MAX_LAYERS],
index: usize,
depth: usize,
#[cfg(feature = "test-op-count")]
pub(crate) op_count: usize,
}
impl Iterator for Iter<'_> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.layers.is_empty() {
return None;
}
loop {
#[cfg(feature = "test-op-count")]
{
self.op_count += 1;
}
let mask = self.masks[self.depth];
if mask != BITS as u8 {
let offset = self.index >> SHIFT2[self.depth];
// Unsafe version:
// let slot = unsafe { self.layers.get_unchecked(self.depth).get_unchecked(offset) };
let slot = self.layers[self.depth][offset];
let slot = (slot >> mask) << mask;
if slot != 0 {
let tail = slot.trailing_zeros() as usize;
self.masks[self.depth] = (tail + 1) as u8;
// Advance one layer down, setting the index to the bit matching
// the offset we are interested in.
if self.depth > 0 {
self.index = (offset << SHIFT2[self.depth]) + (tail << SHIFT[self.depth]);
self.depth -= 1;
continue;
}
return Some(self.index + tail);
}
}
self.masks[self.depth] = 0;
self.depth += 1;
if self.depth == self.layers.len() {
self.layers = &[];
return None;
}
}
}
}
/// The same as [`BitSet`], except it provides atomic methods.
///
/// [`BitSet`] and [`AtomicBitSet`]'s are guaranteed to have an identical memory
/// layout, so they support zero-cost back and forth conversion.
///
/// The [`as_local_mut`] and [`into_local`] methods can be used to convert to a
/// local unsynchronized bitset.
///
/// [`as_local_mut`]: AtomicBitSet::as_local_mut
/// [`into_local`]: AtomicBitSet::into_local
#[repr(C)]
pub struct AtomicBitSet {
/// Layers of bits.
layers: Layers<AtomicLayer>,
/// The capacity of the bit set in number of bits it can store.
cap: usize,
}
impl AtomicBitSet {
/// Construct a new, empty atomic bit set.
///
/// # Examples
///
/// ```
/// use uniset::AtomicBitSet;
///
/// let set = AtomicBitSet::new();
/// let set = set.into_local();
/// assert!(set.is_empty());
/// ```
pub fn new() -> Self {
Self {
layers: Layers::new(),
cap: 0,
}
}
/// Get the current capacity of the bitset.
///
/// # Examples
///
/// ```
/// use uniset::AtomicBitSet;
///
/// let set = AtomicBitSet::new();
/// assert_eq!(0, set.capacity());
/// ```
pub fn capacity(&self) -> usize {
self.cap
}
/// Set the given bit atomically.
///
/// We can do this to an [`AtomicBitSet`] since the required modifications
/// that needs to be performed against each layer are idempotent of the
/// order in which they are applied.
///
/// # Panics
///
/// Call will panic if the position is not within the capacity of the
/// [`AtomicBitSet`].
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let set = BitSet::with_capacity(1024).into_atomic();
/// set.set(1000);
/// let set = set.into_local();
/// assert!(set.test(1000));
/// ```
pub fn set(&self, mut position: usize) {
assert!(
position < self.cap,
"position {} is out of bounds for layer capacity {}",
position,
self.cap
);
for layer in &self.layers {
let slot = position / BITS;
let offset = position % BITS;
layer.set(slot, offset);
position >>= BITS_SHIFT;
}
}
/// Convert in-place into a a [`BitSet`].
///
/// This is safe, since this function requires exclusive owned access to the
/// [`AtomicBitSet`], and we assert that their memory layouts are identical.
///
/// [`BitSet`]: BitSet
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::new();
/// set.reserve(1024);
///
/// let atomic = set.into_atomic();
/// atomic.set(42);
///
/// let set = atomic.into_local();
/// assert!(set.test(42));
/// ```
pub fn into_local(mut self) -> BitSet {
BitSet {
layers: convert_layers(mem::replace(&mut self.layers, Layers::new())),
cap: mem::replace(&mut self.cap, 0),
}
}
/// Convert in-place into a mutable reference to a [`BitSet`].
///
/// This is safe, since this function requires exclusive mutable access to
/// the [`AtomicBitSet`], and we assert that their memory layouts are
/// identical.
///
/// [`BitSet`]: BitSet
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let mut set = BitSet::with_capacity(1024).into_atomic();
///
/// set.set(21);
/// set.set(42);
///
/// {
/// let set = set.as_local_mut();
/// // Clearing is only safe with BitSet's since we require exclusive
/// // mutable access to the collection being cleared.
/// set.clear(21);
/// }
///
/// let set = set.into_local();
/// assert!(!set.test(21));
/// assert!(set.test(42));
/// ```
pub fn as_local_mut(&mut self) -> &mut BitSet {
// Safety: BitSet and AtomicBitSet are guaranteed to have identical
// internal structures.
unsafe { &mut *(self as *mut _ as *mut BitSet) }
}
}
impl Default for AtomicBitSet {
fn default() -> Self {
Self::new()
}
}
/// A single layer of bits.
///
/// This is carefully constructed to be structurally equivalent to
/// [AtomicLayer].
/// So that coercing between the two is sound.
#[repr(C)]
pub struct Layer {
/// Bits.
bits: *mut usize,
cap: usize,
}
unsafe impl CoerceLayer for Layer {
type Target = AtomicLayer;
}
unsafe impl Send for Layer {}
unsafe impl Sync for Layer {}
impl Layer {
/// Allocate a new raw layer with the specified capacity.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// assert_eq!(vec![0usize; 4], Layer::with_capacity(4));
/// ```
pub fn with_capacity(cap: usize) -> Layer {
// Create an already initialized layer of bits.
let mut vec = mem::ManuallyDrop::new(vec![0usize; cap]);
Layer {
bits: vec.as_mut_ptr(),
cap,
}
}
/// Create an iterator over the raw underlying data for the layer.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// let mut layer = Layer::with_capacity(2);
///
/// let mut it = layer.iter();
/// assert_eq!(Some(&0), it.next());
/// assert_eq!(Some(&0), it.next());
/// assert_eq!(None, it.next());
///
/// layer.set(0, 63);
///
/// let mut it = layer.iter();
/// assert_eq!(Some(&(1 << 63)), it.next());
/// assert_eq!(Some(&0), it.next());
/// assert_eq!(None, it.next());
/// ```
pub fn iter(&self) -> slice::Iter<'_, usize> {
self.as_slice().iter()
}
/// Return the given layer as a slice.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// let mut layer = Layer::with_capacity(2);
/// assert_eq!(vec![0, 0], layer);
/// assert_eq!(0, layer.as_slice()[0]);
/// layer.set(0, 42);
/// assert_eq!(1 << 42, layer.as_slice()[0]);
/// ```
pub fn as_slice(&self) -> &[usize] {
unsafe { slice::from_raw_parts(self.bits, self.cap) }
}
/// Return the given layer as a mutable slice.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// let mut layer = Layer::with_capacity(2);
/// assert_eq!(vec![0, 0], layer);
/// layer.as_mut_slice()[0] = 42;
/// assert_eq!(vec![42, 0], layer);
/// ```
pub fn as_mut_slice(&mut self) -> &mut [usize] {
unsafe { slice::from_raw_parts_mut(self.bits, self.cap) }
}
/// Reserve exactly the specified number of elements in this layer.
///
/// Each added element is zerod as it is grown.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// let mut layer = Layer::with_capacity(0);
/// assert_eq!(vec![], layer);
/// layer.grow(2);
/// assert_eq!(vec![0, 0], layer);
/// ```
pub fn grow(&mut self, new: usize) {
// Nothing to do.
if self.cap >= new {
return;
}
let mut vec =
mem::ManuallyDrop::new(unsafe { Vec::from_raw_parts(self.bits, self.cap, self.cap) });
vec.reserve_exact(new - self.cap);
// Initialize new values.
for _ in self.cap..new {
vec.push(0usize);
}
debug_assert!(vec.len() == vec.capacity());
self.bits = vec.as_mut_ptr();
self.cap = vec.capacity();
}
/// Set the given bit in this layer.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// let mut layer = Layer::with_capacity(2);
/// layer.set(0, 63);
/// assert_eq!(vec![1usize << 63, 0usize], layer);
/// ```
pub fn set(&mut self, slot: usize, offset: usize) {
*self.slot_mut(slot) |= 1 << offset;
}
/// Clear the given bit in this layer.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// let mut layer = Layer::with_capacity(2);
/// layer.set(0, 63);
/// assert_eq!(vec![1usize << 63, 0usize], layer);
/// layer.clear(0, 63);
/// assert_eq!(vec![0usize, 0usize], layer);
/// ```
pub fn clear(&mut self, slot: usize, offset: usize) {
*self.slot_mut(slot) &= !(1 << offset);
}
/// Set the given bit in this layer, where `element` indicates how many
/// elements are affected per position.
///
/// # Examples
///
/// ```
/// use uniset::Layer;
///
/// let mut layer = Layer::with_capacity(2);
/// assert!(!layer.test(0, 63));
/// layer.set(0, 63);
/// assert!(layer.test(0, 63));
/// ```
pub fn test(&self, slot: usize, offset: usize) -> bool {
*self.slot(slot) & (1 << offset) > 0
}
#[inline(always)]
fn slot(&self, slot: usize) -> &usize {
assert!(slot < self.cap);
// Safety: We check that the slot fits within the capacity.
unsafe { &*self.bits.add(slot) }
}
#[inline(always)]
fn slot_mut(&mut self, slot: usize) -> &mut usize {
assert!(slot < self.cap);
// Safety: We check that the slot fits within the capacity.
unsafe { &mut *self.bits.add(slot) }
}
#[inline(always)]
#[allow(unused)]
unsafe fn get_unchecked(&self, slot: usize) -> usize {
debug_assert!(slot < self.cap);
*self.bits.add(slot)
}
#[inline(always)]
#[allow(unused)]
unsafe fn get_unchecked_mut(&mut self, slot: usize) -> &mut usize {
debug_assert!(slot < self.cap);
&mut *self.bits.add(slot)
}
}
impl From<Vec<usize>> for Layer {
fn from(mut value: Vec<usize>) -> Self {
if value.len() < value.capacity() {
value.shrink_to_fit();
}
let mut value = mem::ManuallyDrop::new(value);
Self {
bits: value.as_mut_ptr(),
cap: value.capacity(),
}
}
}
impl Clone for Layer {
fn clone(&self) -> Self {
let mut vec = mem::ManuallyDrop::new(self.as_slice().to_vec());
Self {
bits: vec.as_mut_ptr(),
cap: vec.capacity(),
}
}
}
impl fmt::Debug for Layer {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "{:?}", self.as_slice())
}
}
impl<S> PartialEq<S> for Layer
where
S: AsRef<[usize]>,
{
fn eq(&self, other: &S) -> bool {
self.as_slice() == other.as_ref()
}
}
impl<'a> PartialEq<Layer> for &'a [usize] {
fn eq(&self, other: &Layer) -> bool {
*self == other.as_slice()
}
}
impl PartialEq<Layer> for Vec<usize> {
fn eq(&self, other: &Layer) -> bool {
self.as_slice() == other.as_slice()
}
}
impl Eq for Layer {}
impl AsRef<[usize]> for Layer {
fn as_ref(&self) -> &[usize] {
self.as_slice()
}
}
impl<I: slice::SliceIndex<[usize]>> ops::Index<I> for Layer {
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
ops::Index::index(self.as_slice(), index)
}
}
impl<I: slice::SliceIndex<[usize]>> ops::IndexMut<I> for Layer {
#[inline]
fn index_mut(&mut self, index: I) -> &mut Self::Output {
ops::IndexMut::index_mut(self.as_mut_slice(), index)
}
}
impl Drop for Layer {
fn drop(&mut self) {
unsafe {
drop(Vec::from_raw_parts(self.bits, self.cap, self.cap));
}
}
}
/// A single layer of the bitset, that can be atomically updated.
///
/// This is carefully constructed to be structurally equivalent to
/// [Layer].
/// So that coercing between the two is sound.
#[repr(C)]
struct AtomicLayer {
bits: *mut AtomicUsize,
cap: usize,
}
unsafe impl CoerceLayer for AtomicLayer {
type Target = Layer;
}
unsafe impl Send for AtomicLayer {}
unsafe impl Sync for AtomicLayer {}
impl AtomicLayer {
/// Set the given bit in this layer atomically.
///
/// This allows mutating the layer through a shared reference.
///
/// # Examples
///
/// ```
/// use uniset::BitSet;
///
/// let set = BitSet::with_capacity(64);
///
/// assert!(set.is_empty());
/// set.as_atomic().set(2);
/// assert!(!set.is_empty());
/// ```
pub fn set(&self, slot: usize, offset: usize) {
// Ordering: We rely on external synchronization when testing the layers
// So total memory ordering does not matter as long as we apply all
// necessary operations to all layers - which is guaranteed by
// [AtomicBitSet::set].
self.slot(slot).fetch_or(1 << offset, Ordering::Relaxed);
}
/// Return the given layer as a slice.
fn as_slice(&self) -> &[AtomicUsize] {
unsafe { slice::from_raw_parts(self.bits, self.cap) }
}
#[inline(always)]
fn slot(&self, slot: usize) -> &AtomicUsize {
assert!(slot < self.cap);
// Safety: We check that the slot fits within the capacity.
unsafe { &*self.bits.add(slot) }
}
}
impl AsRef<[AtomicUsize]> for AtomicLayer {
fn as_ref(&self) -> &[AtomicUsize] {
self.as_slice()
}
}
impl Drop for AtomicLayer {
fn drop(&mut self) {
// Safety: We keep track of the capacity internally.
unsafe {
drop(Vec::from_raw_parts(self.bits, self.cap, self.cap));
}
}
}
fn round_bits_up(value: usize) -> usize {
let m = value % BITS;
if m == 0 {
value
} else {
value + (BITS - m)
}
}
/// Helper function to generate the necessary layout of the bit set layers
/// given a desired `capacity`.
fn bit_set_layout(capacity: usize) -> impl Iterator<Item = LayerLayout> + Clone {
let mut cap = round_bits_up(capacity);
iter::from_fn(move || {
if cap == 1 {
return None;
}
cap = round_bits_up(cap) / BITS;
if cap > 0 {
Some(LayerLayout { cap })
} else {
None
}
})
}
/// Round up the capacity to be the closest power of 2.
fn round_capacity_up(cap: usize) -> usize {
if cap == 0 {
return 0;
}
if cap > 1 << 63 {
return std::usize::MAX;
}
// Cap is already a power of two.
let cap = if cap == 1usize << cap.trailing_zeros() {
cap
} else {
1usize << (BITS - cap.leading_zeros() as usize)
};
usize::max(16, cap)
}
/// Convert a vector into a different type, assuming the constituent type has
/// an identical layout to the converted type.
fn convert_layers<T, U>(vec: Layers<T>) -> Layers<U>
where
T: CoerceLayer<Target = U>,
{
debug_assert!(mem::size_of::<T>() == mem::size_of::<U>());
debug_assert!(mem::align_of::<T>() == mem::align_of::<U>());
let mut vec = mem::ManuallyDrop::new(vec);
// Safety: we guarantee safety by requiring that `T` and `U` implements
// `IsLayer`.
unsafe { Layers::from_raw_parts(vec.as_mut_ptr() as *mut U, vec.len(), vec.capacity()) }
}
#[cfg(feature = "vec-safety")]
mod vec_safety {
use std::{iter, marker, mem, ops, slice};
/// Storage for layers.
///
/// We use this _instead_ of `Vec<T>` since we want layout guarantees.
///
/// Note: this type is underdocumented since it is internal, and its only
/// goal is to provide an equivalent compatible API as Vec<T>, so look
/// there for documentation.
#[repr(C)]
pub(super) struct Layers<T> {
data: *mut T,
len: usize,
cap: usize,
_marker: marker::PhantomData<T>,
}
unsafe impl<T> Send for Layers<T> where T: Send {}
unsafe impl<T> Sync for Layers<T> where T: Sync {}
impl<T> Layers<T> {
/// Note: Can't be a constant function :(.
pub(super) fn new() -> Self {
let mut vec = mem::ManuallyDrop::new(Vec::<T>::new());
Self {
data: vec.as_mut_ptr(),
len: vec.len(),
cap: vec.capacity(),
_marker: marker::PhantomData,
}
}
pub(super) fn as_mut_ptr(&mut self) -> *mut T {
self.data
}
pub(super) fn len(&self) -> usize {
self.len
}
pub(super) fn is_empty(&self) -> bool {
self.len == 0
}
pub(super) fn capacity(&self) -> usize {
self.cap
}
pub(super) fn as_mut_slice(&mut self) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(self.data, self.len) }
}
pub(super) fn as_slice(&self) -> &[T] {
unsafe { slice::from_raw_parts(self.data as *const T, self.len) }
}
pub(super) fn last(&self) -> Option<&T> {
self.as_slice().last()
}
pub(super) fn push(&mut self, value: T) {
self.as_vec(|vec| vec.push(value));
}
pub(super) unsafe fn from_raw_parts(data: *mut T, len: usize, cap: usize) -> Self {
Self {
data,
len,
cap,
_marker: marker::PhantomData,
}
}
#[inline(always)]
fn as_vec<F>(&mut self, f: F)
where
F: FnOnce(&mut Vec<T>),
{
let mut vec = mem::ManuallyDrop::new(unsafe {
Vec::from_raw_parts(self.data, self.len, self.cap)
});
f(&mut vec);
self.data = vec.as_mut_ptr();
self.len = vec.len();
self.cap = vec.capacity();
}
}
impl<T> Default for Layers<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> Clone for Layers<T>
where
T: Clone,
{
fn clone(&self) -> Self {
let mut vec = mem::ManuallyDrop::new(unsafe {
Vec::from_raw_parts(self.data, self.len, self.cap)
})
.clone();
Self {
data: vec.as_mut_ptr(),
len: vec.len(),
cap: vec.capacity(),
_marker: marker::PhantomData,
}
}
}
impl<'a, T> IntoIterator for &'a mut Layers<T> {
type IntoIter = slice::IterMut<'a, T>;
type Item = &'a mut T;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.as_mut_slice().iter_mut()
}
}
impl<'a, T> IntoIterator for &'a Layers<T> {
type IntoIter = slice::Iter<'a, T>;
type Item = &'a T;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.as_slice().iter()
}
}
impl<T, I: slice::SliceIndex<[T]>> ops::Index<I> for Layers<T> {
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
ops::Index::index(self.as_slice(), index)
}
}
impl<T, I: slice::SliceIndex<[T]>> ops::IndexMut<I> for Layers<T> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut Self::Output {
ops::IndexMut::index_mut(self.as_mut_slice(), index)
}
}
impl<T> iter::Extend<T> for Layers<T> {
#[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.as_vec(|vec| vec.extend(iter));
}
}
impl<T> Drop for Layers<T> {
fn drop(&mut self) {
drop(unsafe { Vec::from_raw_parts(self.data, self.len, self.cap) });
}
}
}
#[cfg(test)]
mod tests {
use super::{bit_set_layout, AtomicBitSet, BitSet};
#[test]
fn assert_send_and_sync() {
assert_traits(BitSet::new());
assert_traits(AtomicBitSet::new());
fn assert_traits<T: Send + Sync>(_: T) {}
}
#[test]
fn test_set_and_test() {
let mut set = BitSet::new();
set.reserve(1024);
set.set(1);
set.set(64);
set.set(129);
set.set(1023);
assert!(set.test(1));
assert!(set.test(64));
assert!(set.test(129));
assert!(set.test(1023));
assert!(!set.test(1022));
let mut layer0 = [0usize; 16];
layer0[0] = 1 << 1;
layer0[1] = 1;
layer0[2] = 1 << 1;
layer0[15] = 1 << 63;
let mut layer1 = [0usize; 1];
layer1[0] = 1 << 15 | 1 << 2 | 1 << 1 | 1;
assert_eq!(vec![&layer0[..], &layer1[..]], set.as_slice());
}
#[test]
fn test_bit_layout() {
assert!(bit_set_layout(0).collect::<Vec<_>>().is_empty());
assert_eq!(
vec![1],
bit_set_layout(64).map(|l| l.cap).collect::<Vec<_>>()
);
assert_eq!(
vec![2, 1],
bit_set_layout(128).map(|l| l.cap).collect::<Vec<_>>()
);
assert_eq!(
vec![64, 1],
bit_set_layout(4096).map(|l| l.cap).collect::<Vec<_>>()
);
assert_eq!(
vec![65, 2, 1],
bit_set_layout(4097).map(|l| l.cap).collect::<Vec<_>>()
);
assert_eq!(
vec![2, 1],
bit_set_layout(65).map(|l| l.cap).collect::<Vec<_>>()
);
assert_eq!(
vec![2, 1],
bit_set_layout(128).map(|l| l.cap).collect::<Vec<_>>()
);
assert_eq!(
vec![3, 1],
bit_set_layout(129).map(|l| l.cap).collect::<Vec<_>>()
);
assert_eq!(
vec![65, 2, 1],
bit_set_layout(4097).map(|l| l.cap).collect::<Vec<_>>()
);
}
// NB: test to run through miri to make sure we reserve layers appropriately.
#[test]
fn test_reserve() {
let mut b = BitSet::new();
b.reserve(1_000);
b.reserve(10_000);
assert_ne!(
bit_set_layout(1_000).collect::<Vec<_>>(),
bit_set_layout(10_000).collect::<Vec<_>>()
);
}
macro_rules! drain_test {
($cap:expr, $sample:expr, $expected_op_count:expr) => {{
let mut set = BitSet::new();
set.reserve($cap);
let positions: Vec<usize> = $sample;
for p in positions.iter().copied() {
set.set(p);
}
let mut drain = set.drain();
assert_eq!(positions, (&mut drain).collect::<Vec<_>>());
#[cfg(feature = "test-op-count")]
{
let op_count = drain.op_count;
assert_eq!($expected_op_count, op_count);
}
// Assert that all layers are zero.
assert!(set
.as_slice()
.into_iter()
.all(|l| l.iter().all(|n| *n == 0)));
}};
}
macro_rules! iter_test {
($cap:expr, $sample:expr, $expected_op_count:expr) => {{
let mut set = BitSet::new();
set.reserve($cap);
let positions: Vec<usize> = $sample;
for p in positions.iter().copied() {
set.set(p);
}
let mut iter = set.iter();
assert_eq!(positions, (&mut iter).collect::<Vec<_>>());
#[cfg(feature = "test-op-count")]
{
let op_count = iter.op_count;
assert_eq!($expected_op_count, op_count);
}
}};
}
#[test]
fn test_drain() {
drain_test!(0, vec![], 0);
drain_test!(1024, vec![], 1);
drain_test!(64, vec![0], 1);
drain_test!(64, vec![0, 1], 2);
drain_test!(64, vec![0, 1, 63], 3);
drain_test!(128, vec![64], 3);
drain_test!(128, vec![0, 32, 64], 7);
drain_test!(4096, vec![0, 32, 64, 3030, 4095], 13);
drain_test!(
1_000_000,
vec![0, 32, 64, 3030, 4095, 50_000, 102110, 203020, 500000, 803020, 900900],
51
);
#[cfg(not(miri))]
drain_test!(1_000_000, (0..1_000_000).collect::<Vec<usize>>(), 1_031_748);
#[cfg(not(miri))]
drain_test!(
10_000_000,
vec![0, 32, 64, 3030, 4095, 50_000, 102110, 203020, 500000, 803020, 900900, 9_009_009],
58
);
}
#[test]
fn test_iter() {
iter_test!(0, vec![], 0);
iter_test!(1024, vec![], 1);
iter_test!(64, vec![0, 2], 3);
iter_test!(64, vec![0, 1], 3);
iter_test!(128, vec![64], 4);
iter_test!(128, vec![0, 32, 64], 8);
iter_test!(4096, vec![0, 32, 64, 3030, 4095], 14);
iter_test!(
1_000_000,
vec![0, 32, 64, 3030, 4095, 50_000, 102110, 203020, 500000, 803020, 900900],
52
);
#[cfg(not(miri))]
iter_test!(
10_000_000,
vec![0, 32, 64, 3030, 4095, 50_000, 102110, 203020, 500000, 803020, 900900, 9_009_009],
59
);
#[cfg(not(miri))]
iter_test!(1_000_000, (0..1_000_000).collect::<Vec<usize>>(), 1_031_749);
}
#[test]
fn test_round_capacity_up() {
use super::round_capacity_up;
assert_eq!(0, round_capacity_up(0));
assert_eq!(16, round_capacity_up(1));
assert_eq!(32, round_capacity_up(17));
assert_eq!(32, round_capacity_up(32));
assert_eq!(
(std::usize::MAX >> 1) + 1,
round_capacity_up(std::usize::MAX >> 1)
);
assert_eq!(std::usize::MAX, round_capacity_up((1usize << 63) + 1));
}
#[test]
fn test_grow_one_at_a_time() {
let mut active = BitSet::new();
for i in 0..128 {
active.reserve(i);
}
}
}