simple_bitset/
bitset64.rs1use core::fmt;
2use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index};
3#[cfg(feature = "serde")]
4use {
5 sequential_storage::map::PostcardValue,
6 serde::{Deserialize, Serialize},
7};
8
9#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct BitSet64(u64);
14
15impl BitSet64 {
16 #[must_use]
18 pub const fn new() -> Self {
19 Self(0)
20 }
21}
22
23#[cfg(feature = "serde")]
24impl PostcardValue<'_> for BitSet64 {}
25
26impl Default for BitSet64 {
27 fn default() -> Self {
28 Self::new()
29 }
30}
31
32impl BitSet64 {
33 #[inline]
35 pub fn reset_all(&mut self) {
36 self.0 = 0;
37 }
38
39 #[inline]
41 pub fn reset(&mut self, index: u8) {
42 if index < 64 {
43 self.0 &= !(1u64 << index);
44 }
45 }
46
47 #[inline]
49 pub fn set_all(&mut self) {
50 self.0 = u64::MAX;
51 }
52
53 #[inline]
55 pub fn set(&mut self, index: u8) {
56 if index < 64 {
57 self.0 |= 1u64 << index;
58 }
59 }
60
61 #[inline]
63 pub fn flip(&mut self, index: u8) {
64 if index < 64 {
65 self.0 ^= 1u64 << index;
66 }
67 }
68
69 #[inline]
71 pub fn flip_all(&mut self) {
72 self.0 = !self.0;
73 }
74
75 #[inline]
78 pub fn and_not(&mut self, other: Self) {
79 self.0 &= !other.0;
80 }
81
82 #[inline]
85 #[must_use]
86 pub fn test(&self, index: u8) -> bool {
87 if index < 64 {
88 (self.0 & (1u64 << index)) != 0
89 } else {
90 false
91 }
92 }
93
94 #[inline]
96 #[must_use]
97 pub const fn count_ones(&self) -> u32 {
98 self.0.count_ones()
99 }
100
101 #[inline]
104 #[must_use]
105 pub const fn leading_zeros(&self) -> u32 {
106 self.0.leading_zeros()
107 }
108
109 #[inline]
111 #[must_use]
112 pub const fn is_empty(&self) -> bool {
113 self.0 == 0
114 }
115
116 #[inline]
119 #[must_use]
120 pub const fn last_set(&self) -> Option<u8> {
121 if self.is_empty() {
122 None
123 } else {
124 #[allow(clippy::cast_possible_truncation)]
126 Some(63 - self.0.leading_zeros() as u8)
127 }
128 }
129
130 #[inline]
132 #[must_use]
133 pub const fn is_superset(&self, other: &BitSet64) -> bool {
134 (self.0 & other.0) == other.0
137 }
138
139 #[inline]
141 #[must_use]
142 pub const fn is_subset(&self, other: &BitSet64) -> bool {
143 other.is_superset(self)
144 }
145
146 #[inline]
149 #[must_use]
150 pub const fn intersects(&self, other: &Self) -> bool {
151 self.0 & other.0 != 0
154 }
155
156 #[inline]
158 #[must_use]
159 pub fn iter(&self) -> BitSet64Iter {
160 self.into_iter()
161 }
162}
163
164impl BitOr for BitSet64 {
167 type Output = Self;
168 fn bitor(self, rhs: Self) -> Self::Output {
169 Self(self.0 | rhs.0)
170 }
171}
172
173impl BitAnd for BitSet64 {
174 type Output = Self;
175 fn bitand(self, rhs: Self) -> Self::Output {
176 Self(self.0 & rhs.0)
177 }
178}
179
180impl BitXor for BitSet64 {
181 type Output = Self;
182 fn bitxor(self, rhs: Self) -> Self::Output {
183 Self(self.0 ^ rhs.0)
184 }
185}
186
187impl BitOrAssign for BitSet64 {
188 fn bitor_assign(&mut self, rhs: Self) {
189 self.0 |= rhs.0;
190 }
191}
192
193impl BitAndAssign for BitSet64 {
194 fn bitand_assign(&mut self, rhs: Self) {
195 self.0 &= rhs.0;
196 }
197}
198
199impl BitXorAssign for BitSet64 {
200 fn bitxor_assign(&mut self, rhs: Self) {
201 self.0 ^= rhs.0;
202 }
203}
204
205impl Index<u8> for BitSet64 {
206 type Output = bool;
207
208 fn index(&self, index: u8) -> &Self::Output {
209 if self.test(index) { &true } else { &false }
211 }
212}
213
214impl Index<usize> for BitSet64 {
215 type Output = bool;
216
217 #[allow(clippy::cast_possible_truncation)]
218 fn index(&self, index: usize) -> &Self::Output {
219 if self.test(index as u8) { &true } else { &false }
221 }
222}
223
224impl From<u32> for BitSet64 {
226 #[inline]
227 fn from(a: u32) -> Self {
228 Self(u64::from(a))
229 }
230}
231
232impl From<(u32, u32)> for BitSet64 {
234 #[inline]
235 fn from((a, b): (u32, u32)) -> Self {
236 Self(u64::from(a) << 32 | u64::from(b))
237 }
238}
239
240#[derive(Debug, Default, Eq, PartialEq)]
244pub struct BitSet64Iter(u64);
245
246impl Iterator for BitSet64Iter {
248 type Item = u8;
249
250 fn next(&mut self) -> Option<Self::Item> {
251 if self.0 == 0 {
252 None
253 } else {
254 #[allow(clippy::cast_possible_truncation)]
256 let index = self.0.trailing_zeros() as u8;
257 self.0 &= self.0 - 1;
259 Some(index)
260 }
261 }
262
263 #[inline]
264 fn size_hint(&self) -> (usize, Option<usize>) {
265 let len = self.0.count_ones() as usize;
267 (len, Some(len))
268 }
269}
270
271impl ExactSizeIterator for BitSet64Iter {}
273impl core::iter::FusedIterator for BitSet64Iter {}
274
275impl IntoIterator for &BitSet64 {
277 type Item = u8;
278 type IntoIter = BitSet64Iter;
279
280 fn into_iter(self) -> Self::IntoIter {
281 BitSet64Iter(self.0)
284 }
285}
286
287impl IntoIterator for BitSet64 {
289 type Item = u8;
290 type IntoIter = BitSet64Iter;
291
292 fn into_iter(self) -> Self::IntoIter {
293 BitSet64Iter(self.0)
296 }
297}
298
299impl FromIterator<u8> for BitSet64 {
301 fn from_iter<I: IntoIterator<Item = u8>>(iter: I) -> Self {
302 let mut bitset = Self::new();
303 for index in iter {
304 bitset.set(index);
305 }
306 bitset
307 }
308}
309
310impl Extend<u8> for BitSet64 {
311 fn extend<I: IntoIterator<Item = u8>>(&mut self, iter: I) {
312 for index in iter {
313 self.set(index);
314 }
315 }
316}
317
318impl fmt::Binary for BitSet64 {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 if f.alternate() {
324 f.write_str("0b")?;
325 }
326 for i in (0..64).rev() {
328 let val = (self.0 >> i) & 1;
329 write!(f, "{val}")?;
330 }
331
332 Ok(())
333 }
334}
335
336impl fmt::UpperHex for BitSet64 {
337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 if f.alternate() {
339 f.write_str("0x")?;
340 }
341 write!(f, "{:016X}", self.0)
342 }
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348
349 fn is_normal<T: Sized + Send + Sync + Unpin>() {}
350 fn is_full<T: Sized + Send + Sync + Unpin + Copy + Clone + Default + PartialEq>() {}
351 #[cfg(feature = "serde")]
352 fn is_config<T: Serialize + for<'a> Deserialize<'a>>() {}
353
354 #[test]
355 fn normal_types() {
356 is_full::<BitSet64>();
357 #[cfg(feature = "serde")]
358 is_config::<BitSet64>();
359 is_normal::<BitSet64Iter>();
360 }
361
362 #[test]
363 fn new() {
364 let mut bits = BitSet64::new();
365 bits.set(42);
366 assert!(bits[42u8]);
367 assert!(bits.test(42));
368 }
369
370 #[test]
371 fn const_new() {
372 const FLAGS: BitSet64 = BitSet64::new();
373 const EMPTY_CHECK: bool = FLAGS.is_empty(); assert_eq!(0, FLAGS.0);
375 #[allow(clippy::assertions_on_constants)]
376 {
377 assert!(EMPTY_CHECK);
378 }
379 }
380
381 #[test]
382 fn assign() {
383 let mut bits = BitSet64::new();
384 bits.set(42);
385 assert!(bits[42u8]);
386 assert!(bits.test(42));
387 let mask = bits;
388 assert!(mask.test(42));
389 }
390
391 #[test]
392 fn from() {
393 let _bits = BitSet64::from((0xab_u32, 0x12_u32));
394 }
395
396 #[test]
397 fn flip_all() {
398 let mut bitset = BitSet64::new();
399
400 bitset.set(0);
402 bitset.set(32);
403
404 bitset.flip_all();
405
406 assert!(!bitset.test(0));
408 assert!(!bitset.test(32));
409 assert!(bitset.test(1));
410 assert!(bitset.test(33));
411
412 let mut empty_set = BitSet64::new();
414 empty_set.flip_all(); let mut full_set = BitSet64::new();
417 full_set.set_all();
418
419 assert_eq!(empty_set, full_set);
420
421 empty_set.flip_all(); assert!(empty_set.is_empty());
423 }
424
425 #[test]
426 fn inplace_logical_ops() {
427 let mut set_a = BitSet64::new();
428 let mut set_b = BitSet64::new();
429
430 set_a.set(10);
432 set_a.set(50);
433
434 set_b.set(10);
435 set_b.set(60);
436
437 let mut result = set_a;
439 result &= set_b;
440 assert!(result.test(10));
441 assert!(!result.test(50));
442 assert!(!result.test(60));
443
444 let mut result = set_a;
446 result |= set_b;
447 assert!(result.test(10));
448 assert!(result.test(50));
449 assert!(result.test(60));
450
451 let mut result = set_a;
453 result ^= set_b;
454 assert!(!result.test(10)); assert!(result.test(50));
456 assert!(result.test(60));
457
458 let mut result = set_a;
460 result.and_not(set_b);
461 assert!(!result.test(10)); assert!(result.test(50)); assert!(!result.test(60)); }
465
466 #[test]
467 fn exercise() {
468 let mut system_flags = BitSet64::new();
469 let error_mask = BitSet64::new(); system_flags |= error_mask;
473
474 system_flags ^= error_mask;
476
477 system_flags &= BitSet64(0x0000_FFFF_FFFF_FFFF);
479
480 let mut set_a = BitSet64::new();
481 set_a.set(10);
482 set_a.set(20);
483
484 let mut set_b = BitSet64::new();
485 set_b.set(20);
486 set_b.set(30);
487
488 let common = set_a & set_b;
490 assert!(!common.test(10));
491 assert!(common.test(20));
492 assert!(!common.test(30));
493
494 let all = set_a | set_b;
496 assert!(all.test(10));
497 assert!(all.test(20));
498 assert!(all.test(30));
499
500 let diff = set_a ^ set_b;
502 assert!(diff.test(10));
503 assert!(!diff.test(20));
504 assert!(diff.test(30));
505 }
506
507 #[test]
508 fn iterator_consuming() {
509 let mut bits = BitSet64::new();
510 bits.set(2);
511 bits.set(10);
512
513 let mut sum = 0;
514 let mut count = 0;
515 for bit in &bits {
516 sum += bit;
517 count += 1;
518 }
519 assert_eq!(2, count);
520 assert_eq!(12, sum);
521 }
522
523 #[test]
524 fn into_iter_consuming() {
525 let mut bits = BitSet64::new();
526 bits.set(0);
527 bits.set(10);
528 bits.set(63);
529
530 let mut iter = bits.into_iter();
532
533 assert_eq!(iter.next(), Some(0));
534 assert_eq!(iter.next(), Some(10));
535 assert_eq!(iter.next(), Some(63));
536 assert_eq!(iter.next(), None);
537
538 }
540
541 #[test]
542 fn non_consuming_iterator() {
543 let bits = BitSet64(0b1101); let mut sum = 0;
546 let mut count = 0;
547
548 for bit in &bits {
550 sum += bit;
551 count += 1;
552 }
553 assert_eq!(3, count);
554 assert_eq!(5, sum);
555
556 let mut sum = 0;
557 let mut count = 0;
558 for bit in &bits {
560 sum += bit;
561 count += 1;
562 }
563 assert_eq!(3, count);
564 assert_eq!(5, sum);
565 }
566
567 #[test]
568 fn non_consuming_iterator2() {
569 let mut bits = BitSet64::new();
570 bits.set(5);
571 bits.set(12);
572
573 let count = bits.iter().count();
575 assert_eq!(count, 2);
576
577 let mut last_val = 0;
579 for bit in &bits {
580 last_val = bit;
581 }
582 assert_eq!(last_val, 12);
583
584 assert!(bits.test(5));
586 }
587
588 #[test]
589 fn from_iterator() {
590 let indices = [1, 3, 5];
591 let bits: BitSet64 = indices.iter().copied().collect();
593
594 assert!(bits.test(1));
595 assert!(bits.test(3));
596 assert!(bits.test(5));
597 assert!(!bits.test(2));
598 }
599
600 #[test]
601 fn empty_and_full() {
602 let empty = BitSet64::new();
603 assert_eq!(empty.iter().count(), 0);
604
605 let mut full = BitSet64::new();
606 full.set_all();
607 assert_eq!(full.iter().count(), 64);
608 }
609}