cranelift_bitset/scalar.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
//! Scalar bitsets.
use core::mem::size_of;
use core::ops::{Add, BitAnd, BitOr, Not, Shl, Shr, Sub};
/// A small bitset built on top of a single primitive integer type.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// // Create a new bitset backed with a `u32`.
/// let mut bitset = ScalarBitSet::<u32>::new();
///
/// // Bitsets are initially empty.
/// assert!(bitset.is_empty());
/// assert_eq!(bitset.len(), 0);
///
/// // Insert into the bitset.
/// bitset.insert(4);
/// bitset.insert(5);
/// bitset.insert(6);
///
/// // Now the bitset is not empty.
/// assert_eq!(bitset.len(), 3);
/// assert!(!bitset.is_empty());
/// assert!(bitset.contains(4));
/// assert!(bitset.contains(5));
/// assert!(bitset.contains(6));
///
/// // Remove an element from the bitset.
/// let was_present = bitset.remove(6);
/// assert!(was_present);
/// assert!(!bitset.contains(6));
/// assert_eq!(bitset.len(), 2);
///
/// // Can iterate over the elements in the set.
/// let elems: Vec<_> = bitset.iter().collect();
/// assert_eq!(elems, [4, 5]);
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
feature = "enable-serde",
derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
pub struct ScalarBitSet<T>(pub T);
impl<T> core::fmt::Debug for ScalarBitSet<T>
where
T: ScalarBitSetStorage,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut s = f.debug_struct(core::any::type_name::<Self>());
for i in 0..Self::capacity() {
use alloc::string::ToString;
let i = u8::try_from(i).unwrap();
s.field(&i.to_string(), &self.contains(i));
}
s.finish()
}
}
impl<T> Default for ScalarBitSet<T>
where
T: ScalarBitSetStorage,
{
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> ScalarBitSet<T>
where
T: ScalarBitSetStorage,
{
/// Create a new, empty bitset.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let bitset = ScalarBitSet::<u64>::new();
///
/// assert!(bitset.is_empty());
/// ```
#[inline]
pub fn new() -> Self {
Self(T::from(0))
}
/// Construct a bitset with the half-open range `[lo, hi)` inserted.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let bitset = ScalarBitSet::<u64>::from_range(3, 6);
///
/// assert_eq!(bitset.len(), 3);
///
/// assert!(bitset.contains(3));
/// assert!(bitset.contains(4));
/// assert!(bitset.contains(5));
/// ```
///
/// # Panics
///
/// Panics if `lo > hi` or if `hi > Self::capacity()`.
///
/// ```should_panic
/// use cranelift_bitset::ScalarBitSet;
///
/// // The lower bound may not be larger than the upper bound.
/// let bitset = ScalarBitSet::<u64>::from_range(6, 3);
/// ```
///
/// ```should_panic
/// use cranelift_bitset::ScalarBitSet;
///
/// // The bounds must fit within the backing scalar type.
/// let bitset = ScalarBitSet::<u64>::from_range(3, 69);
/// ```
#[inline]
pub fn from_range(lo: u8, hi: u8) -> Self {
assert!(lo <= hi);
assert!(hi <= Self::capacity());
let one = T::from(1);
// We can't just do (one << hi) - one here as the shift may overflow
let hi_rng = if hi >= 1 {
(one << (hi - 1)) + ((one << (hi - 1)) - one)
} else {
T::from(0)
};
let lo_rng = (one << lo) - one;
Self(hi_rng - lo_rng)
}
/// The maximum number of bits that can be stored in this bitset.
///
/// If you need more bits than this, use a
/// [`CompoundBitSet`][crate::CompoundBitSet] instead of a `ScalarBitSet`.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// assert_eq!(ScalarBitSet::<u8>::capacity(), 8);
/// assert_eq!(ScalarBitSet::<u64>::capacity(), 64);
/// ```
#[inline]
pub fn capacity() -> u8 {
u8::try_from(size_of::<T>()).unwrap() * 8
}
/// Get the number of elements in this set.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u64>::new();
///
/// assert_eq!(bitset.len(), 0);
///
/// bitset.insert(24);
/// bitset.insert(13);
/// bitset.insert(36);
///
/// assert_eq!(bitset.len(), 3);
/// ```
#[inline]
pub fn len(&self) -> u8 {
self.0.count_ones()
}
/// Is this bitset empty?
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u16>::new();
///
/// assert!(bitset.is_empty());
///
/// bitset.insert(10);
///
/// assert!(!bitset.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.0 == T::from(0)
}
/// Check whether this bitset contains `i`.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u8>::new();
///
/// assert!(!bitset.contains(7));
///
/// bitset.insert(7);
///
/// assert!(bitset.contains(7));
/// ```
///
/// # Panics
///
/// Panics if `i` is greater than or equal to [`Self::capacity()`][Self::capacity].
///
/// ```should_panic
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u8>::new();
///
/// // A `ScalarBitSet<u8>` can only hold the elements `0..=7`, so `8` is
/// // out of bounds and will trigger a panic.
/// bitset.contains(8);
/// ```
#[inline]
pub fn contains(&self, i: u8) -> bool {
assert!(i < Self::capacity());
self.0 & (T::from(1) << i) != T::from(0)
}
/// Insert `i` into this bitset.
///
/// Returns whether the value was newly inserted. That is:
///
/// * If the set did not previously contain `i` then `true` is returned.
///
/// * If the set already contained `i` then `false` is returned.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u8>::new();
///
/// // When an element is inserted that was not already present in the set,
/// // then `true` is returned.
/// let is_new = bitset.insert(7);
/// assert!(is_new);
///
/// // The element is now present in the set.
/// assert!(bitset.contains(7));
///
/// // And when the element is already in the set, `false` is returned from
/// // `insert`.
/// let is_new = bitset.insert(7);
/// assert!(!is_new);
/// ```
///
/// # Panics
///
/// Panics if `i` is greater than or equal to [`Self::capacity()`][Self::capacity].
///
/// ```should_panic
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u32>::new();
///
/// // A `ScalarBitSet<u32>` can only hold the elements `0..=31`, so `42` is
/// // out of bounds and will trigger a panic.
/// bitset.insert(42);
/// ```
#[inline]
pub fn insert(&mut self, i: u8) -> bool {
let is_new = !self.contains(i);
self.0 = self.0 | (T::from(1) << i);
is_new
}
/// Remove `i` from this bitset.
///
/// Returns whether `i` was previously in this set or not.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u128>::new();
///
/// // Removing an element that was not present in the set returns `false`.
/// let was_present = bitset.remove(100);
/// assert!(!was_present);
///
/// // And when the element was in the set, `true` is returned.
/// bitset.insert(100);
/// let was_present = bitset.remove(100);
/// assert!(was_present);
/// ```
///
/// # Panics
///
/// Panics if `i` is greater than or equal to [`Self::capacity()`][Self::capacity].
///
/// ```should_panic
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u16>::new();
///
/// // A `ScalarBitSet<u16>` can only hold the elements `0..=15`, so `20` is
/// // out of bounds and will trigger a panic.
/// bitset.remove(20);
/// ```
#[inline]
pub fn remove(&mut self, i: u8) -> bool {
let was_present = self.contains(i);
self.0 = self.0 & !(T::from(1) << i);
was_present
}
/// Remove all entries from this bitset.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u32>::new();
///
/// bitset.insert(10);
/// bitset.insert(20);
/// bitset.insert(30);
///
/// bitset.clear();
///
/// assert!(bitset.is_empty());
/// ```
#[inline]
pub fn clear(&mut self) {
self.0 = T::from(0);
}
/// Remove and return the smallest value in the bitset.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u64>::new();
///
/// bitset.insert(0);
/// bitset.insert(24);
/// bitset.insert(13);
/// bitset.insert(36);
///
/// assert_eq!(bitset.pop_min(), Some(0));
/// assert_eq!(bitset.pop_min(), Some(13));
/// assert_eq!(bitset.pop_min(), Some(24));
/// assert_eq!(bitset.pop_min(), Some(36));
/// assert_eq!(bitset.pop_min(), None);
/// ```
#[inline]
pub fn pop_min(&mut self) -> Option<u8> {
let min = self.min()?;
self.remove(min);
Some(min)
}
/// Remove and return the largest value in the bitset.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u64>::new();
///
/// bitset.insert(0);
/// bitset.insert(24);
/// bitset.insert(13);
/// bitset.insert(36);
///
/// assert_eq!(bitset.pop_max(), Some(36));
/// assert_eq!(bitset.pop_max(), Some(24));
/// assert_eq!(bitset.pop_max(), Some(13));
/// assert_eq!(bitset.pop_max(), Some(0));
/// assert_eq!(bitset.pop_max(), None);
/// ```
#[inline]
pub fn pop_max(&mut self) -> Option<u8> {
let max = self.max()?;
self.remove(max);
Some(max)
}
/// Return the smallest number contained in this bitset or `None` if this
/// bitset is empty.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u64>::new();
///
/// // When the bitset is empty, `min` returns `None`.
/// assert_eq!(bitset.min(), None);
///
/// bitset.insert(28);
/// bitset.insert(1);
/// bitset.insert(63);
///
/// // When the bitset is not empty, it returns the smallest element.
/// assert_eq!(bitset.min(), Some(1));
/// ```
#[inline]
pub fn min(&self) -> Option<u8> {
if self.0 == T::from(0) {
None
} else {
Some(self.0.trailing_zeros())
}
}
/// Return the largest number contained in the bitset or None if this bitset
/// is empty
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u64>::new();
///
/// // When the bitset is empty, `max` returns `None`.
/// assert_eq!(bitset.max(), None);
///
/// bitset.insert(0);
/// bitset.insert(36);
/// bitset.insert(49);
///
/// // When the bitset is not empty, it returns the smallest element.
/// assert_eq!(bitset.max(), Some(49));
/// ```
#[inline]
pub fn max(&self) -> Option<u8> {
if self.0 == T::from(0) {
None
} else {
let leading_zeroes = self.0.leading_zeros();
Some(Self::capacity() - leading_zeroes - 1)
}
}
/// Iterate over the items in this set.
///
/// Items are always yielded in sorted order.
///
/// # Example
///
/// ```
/// use cranelift_bitset::ScalarBitSet;
///
/// let mut bitset = ScalarBitSet::<u64>::new();
///
/// bitset.insert(19);
/// bitset.insert(3);
/// bitset.insert(63);
/// bitset.insert(0);
///
/// assert_eq!(
/// bitset.iter().collect::<Vec<_>>(),
/// [0, 3, 19, 63],
/// );
/// ```
#[inline]
pub fn iter(self) -> Iter<T> {
Iter { bitset: self }
}
}
impl<T> IntoIterator for ScalarBitSet<T>
where
T: ScalarBitSetStorage,
{
type Item = u8;
type IntoIter = Iter<T>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a ScalarBitSet<T>
where
T: ScalarBitSetStorage,
{
type Item = u8;
type IntoIter = Iter<T>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<T: ScalarBitSetStorage> From<T> for ScalarBitSet<T> {
fn from(bits: T) -> Self {
Self(bits)
}
}
/// A trait implemented by all integers that can be used as the backing storage
/// for a [`ScalarBitSet`].
///
/// You shouldn't have to implement this yourself, it is already implemented for
/// `u{8,16,32,64,128}` and if you need more bits than that, then use
/// [`CompoundBitSet`][crate::CompoundBitSet] instead.
pub trait ScalarBitSetStorage:
Default
+ From<u8>
+ Shl<u8, Output = Self>
+ Shr<u8, Output = Self>
+ BitAnd<Output = Self>
+ BitOr<Output = Self>
+ Not<Output = Self>
+ Sub<Output = Self>
+ Add<Output = Self>
+ PartialEq
+ Copy
{
/// Count the number of leading zeros.
fn leading_zeros(self) -> u8;
/// Count the number of trailing zeros.
fn trailing_zeros(self) -> u8;
/// Count the number of bits set in this integer.
fn count_ones(self) -> u8;
}
macro_rules! impl_storage {
( $int:ty ) => {
impl ScalarBitSetStorage for $int {
fn leading_zeros(self) -> u8 {
u8::try_from(self.leading_zeros()).unwrap()
}
fn trailing_zeros(self) -> u8 {
u8::try_from(self.trailing_zeros()).unwrap()
}
fn count_ones(self) -> u8 {
u8::try_from(self.count_ones()).unwrap()
}
}
};
}
impl_storage!(u8);
impl_storage!(u16);
impl_storage!(u32);
impl_storage!(u64);
impl_storage!(u128);
impl_storage!(usize);
/// An iterator over the elements in a [`ScalarBitSet`].
pub struct Iter<T> {
bitset: ScalarBitSet<T>,
}
impl<T> Iterator for Iter<T>
where
T: ScalarBitSetStorage,
{
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.bitset.pop_min()
}
}
impl<T> DoubleEndedIterator for Iter<T>
where
T: ScalarBitSetStorage,
{
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
self.bitset.pop_max()
}
}
impl<T> ExactSizeIterator for Iter<T>
where
T: ScalarBitSetStorage,
{
#[inline]
fn len(&self) -> usize {
usize::from(self.bitset.len())
}
}
#[cfg(feature = "arbitrary")]
impl<'a, T> arbitrary::Arbitrary<'a> for ScalarBitSet<T>
where
T: ScalarBitSetStorage + arbitrary::Arbitrary<'a>,
{
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
T::arbitrary(u).map(Self)
}
}