engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
Documentation
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
//! This module contains tools for working with indices as a mask of boolean values (may
//! eventually be implemented with bitvectors depending on real world performance).

use crate::Result;
use bitvec::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexMask {
    mask: BitVec,
}

impl IndexMask {
    /// Create a new IndexMask with the specified length and initial value.
    ///
    /// # Arguments
    ///
    /// * `len`: the length of the mask
    /// * `value`: the initial value for each index in the mask
    ///
    /// returns: `IndexMask`
    pub fn new(len: usize, value: bool) -> Self {
        let mask = BitVec::repeat(value, len);
        IndexMask { mask }
    }

    /// Create an `IndexMask` from a list of indices that should be set to `true`.
    ///
    /// Any index not listed will be `false`. Returns an error if any index is out of bounds for the
    /// specified mask length.
    ///
    /// # Arguments
    ///
    /// * `indices`: the indices to mark as `true`
    /// * `len`: the total length of the mask
    ///
    /// returns: `Result<IndexMask>`
    pub fn try_from_indices(indices: &[usize], len: usize) -> Result<Self> {
        let mut mask = BitVec::repeat(false, len);
        for &index in indices {
            if index >= len {
                return Err(format!("Index {} is out of bounds for length {}", index, len).into());
            }
            mask.set(index, true);
        }
        Ok(IndexMask { mask })
    }

    /// Get the index values stored in the mask as a vector of `usize`.
    pub fn to_indices(&self) -> Vec<usize> {
        let mut indices = Vec::with_capacity(self.mask.len() / 16);

        for (i, bit) in self.mask.iter().enumerate() {
            if *bit {
                indices.push(i);
            }
        }

        indices
    }

    /// Set the value at the specified index
    pub fn set(&mut self, index: usize, value: bool) {
        self.mask.set(index, value);
    }

    /// Get the value at the specified index.
    pub fn get(&self, index: usize) -> bool {
        self.mask[index]
    }

    #[allow(clippy::len_without_is_empty)]
    /// Get the length of the mask.
    pub fn len(&self) -> usize {
        self.mask.len()
    }

    /// Iterate over the indices where the mask is `true`.
    pub fn iter_true(&self) -> MaskTrueIterator<'_> {
        MaskTrueIterator {
            mask: self,
            current: 0,
        }
    }

    /// Get the number of indices where the mask is `true`.
    pub fn count_true(&self) -> usize {
        self.iter_true().count()
    }

    /// Clone the elements from `items` whose indices are marked `true` in this mask.
    ///
    /// The input slice must have the same length as the mask.
    ///
    /// # Arguments
    ///
    /// * `items`: the items to select from
    ///
    /// returns: `Result<Vec<T>>`
    pub fn clone_indices_of<T: Clone>(&self, items: &[T]) -> Result<Vec<T>> {
        if items.len() != self.len() {
            return Err(format!(
                "Items length {} does not match mask length {}",
                items.len(),
                self.len()
            )
            .into());
        }

        let mut result = Vec::with_capacity(self.to_indices().len());
        for index in self.iter_true() {
            result.push(items[index].clone());
        }
        Ok(result)
    }

    // ==========================================================================================
    // NOT Operations
    // ==========================================================================================

    /// Modify the mask so that all values are the opposite of their current value.
    pub fn not_mut(&mut self) {
        for u in self.mask.as_raw_mut_slice() {
            *u = !*u;
        }
    }

    /// Return a new mask that is the opposite/inversion of the current mask.
    pub fn not(&self) -> Self {
        let mut new_mask = self.clone();
        new_mask.not_mut();
        new_mask
    }

    // ==========================================================================================
    // OR (Union) Operations
    // ==========================================================================================

    /// Creates and returns a new mask that is the result of a bitwise OR operation between this
    /// mask and another mask. This is the equivalent of a set union operation, as it will
    /// combine the indices that are true in either mask.
    ///
    /// This will return an error if the two masks are not of the same length.
    ///
    /// # Arguments
    ///
    /// * `other`: The other `IndexMask` to OR with this one.
    ///
    /// returns: Result<IndexMask, Box<dyn Error, Global>>
    pub fn or(&self, other: &IndexMask) -> Result<Self> {
        let mut new_mask = self.clone();
        new_mask.or_mut(other)?;
        Ok(new_mask)
    }

    /// Performs a bitwise OR operation on the mask with another mask, modifying the current mask.
    /// This is the equivalent of a set union operation, as it will combine the indices that are
    /// true in either mask.
    ///
    /// This will return an error if the two masks are not of the same length.
    ///
    /// # Arguments
    ///
    /// * `other`: The other `IndexMask` to OR with this one.
    ///
    /// returns: Result<(), Box<dyn Error, Global>>
    pub fn or_mut(&mut self, other: &IndexMask) -> Result<()> {
        if self.mask.len() != other.mask.len() {
            return Err("Masks must be of the same length".into());
        }

        self.or_mut_unchecked(other);
        Ok(())
    }

    /// Performs a bitwise OR operation on the mask with another mask, modifying the current mask.
    /// This does not check for length, so it zips the two masks directly. It will not panic if the
    /// lengths are different, but the result will not be what's expected. ONLY USE THIS IF YOU ARE
    /// SURE THAT THE MASKS ARE OF THE SAME LENGTH.
    ///
    /// Because the index mask internally uses a bit vector backed by `usize`, don't expect this
    /// method to combine only up to the length of the shorter mask. If this mask is longer than
    /// `other`, the extra bits at the end of the last `usize::BITS`-bit chunk will contaminate
    /// their counterparts in this mask.
    ///
    /// # Arguments
    ///
    /// * `other`:
    ///
    /// returns: ()
    pub fn or_mut_unchecked(&mut self, other: &IndexMask) {
        let self_mask = self.mask.as_raw_mut_slice();
        let other_mask = other.mask.as_raw_slice();

        for (a, b) in self_mask.iter_mut().zip(other_mask.iter()) {
            *a |= *b;
        }
    }

    // ==========================================================================================
    // AND (Intersection) Operations
    // ==========================================================================================

    /// Creates and returns a new mask that is the result of a bitwise AND operation between this
    /// mask and another mask. This is the equivalent of a set intersection operation, as it will
    /// only keep the indices that are true in both masks.
    ///
    /// Will return an error if the two masks are not of the same length.
    ///
    /// # Arguments
    ///
    /// * `other`: the other `IndexMask` to AND with this one.
    ///
    /// returns: Result<IndexMask, Box<dyn Error, Global>>
    pub fn and(&self, other: &IndexMask) -> Result<Self> {
        let mut new_mask = self.clone();
        new_mask.and_mut(other)?;
        Ok(new_mask)
    }

    /// Perform a bitwise AND operation with another mask, modifying this mask in place.
    ///
    /// Returns an error if the masks are different lengths.
    pub fn and_mut(&mut self, other: &IndexMask) -> Result<()> {
        if self.mask.len() != other.mask.len() {
            return Err("Masks must be of the same length".into());
        }

        self.and_mut_unchecked(other);
        Ok(())
    }

    /// Performs a bitwise AND operation on the mask with another mask, modifying the current mask.
    /// This does not check for length, so it zips the two masks directly. It will not panic if the
    /// lengths are different, but the result will not be what's expected. ONLY USE THIS IF YOU ARE
    /// SURE THAT THE MASKS ARE OF THE SAME LENGTH.
    ///
    /// Because the index mask internally uses a bit-vector backed by `usize`, don't expect this
    /// method to combine only up to the length of the shorter mask. If this mask is longer than
    /// `other`, the extra bits at the end of the last `usize::BITS`-bit chunk will contaminate
    /// their counterparts in this mask.
    ///
    /// # Arguments
    ///
    /// * `other`: a reference to another `IndexMask` to AND with this one.
    ///
    /// returns: ()
    pub fn and_mut_unchecked(&mut self, other: &IndexMask) {
        let self_mask = self.mask.as_raw_mut_slice();
        let other_mask = other.mask.as_raw_slice();

        for (a, b) in self_mask.iter_mut().zip(other_mask.iter()) {
            *a &= *b;
        }
    }

    // ==========================================================================================
    // AND NOT (Difference) Operations
    // ==========================================================================================

    /// Creates and returns a new mask that is the result of a bitwise AND NOT operation between
    /// this mask and another mask. This is the equivalent of a set difference operation, as it will
    /// remove the elements of this mask that are also true in the other mask.
    ///
    /// This is more efficient than using `this.and(other.not())` because it avoids creating a new
    /// mask for the NOT operation, instead doing the AND NOT operation directly.
    ///
    /// This will return an error if the two masks are not of the same length.
    ///
    /// # Arguments
    ///
    /// * `other`: the other `IndexMask` to AND NOT with this one.
    ///
    /// returns: Result<IndexMask, Box<dyn Error, Global>>
    pub fn and_not(&self, other: &IndexMask) -> Result<Self> {
        let mut new_mask = self.clone();
        new_mask.and_not_mut(other)?;
        Ok(new_mask)
    }

    /// Performs a bitwise AND NOT operation on this mask using another mask, modifying the current
    /// mask in place. This is the equivalent of a set difference operation, as it will
    /// remove the elements of this mask that are also true in the other mask.
    ///
    /// This is more efficient than using `this.and(other.not())` because it avoids creating a new
    /// mask for the NOT operation, instead doing the AND NOT operation directly.
    ///
    /// This will return an error if the two masks are not of the same length.
    ///
    /// # Arguments
    ///
    /// * `other`:
    ///
    /// returns: Result<(), Box<dyn Error, Global>>
    pub fn and_not_mut(&mut self, other: &IndexMask) -> Result<()> {
        if self.mask.len() != other.mask.len() {
            return Err("Masks must be of the same length".into());
        }

        let self_mask = self.mask.as_raw_mut_slice();
        let other_mask = other.mask.as_raw_slice();

        for (a, b) in self_mask.iter_mut().zip(other_mask.iter()) {
            *a &= !*b;
        }
        Ok(())
    }

    /// Fill the entire mask with a single boolean value.
    pub fn fill(&mut self, value: bool) {
        for u in self.mask.as_raw_mut_slice() {
            *u = if value { !0 } else { 0 };
        }
    }

    /// Returns true if all bits are set to false
    pub fn is_empty(&self) -> bool {
        // A zero length mask has no true bits, and also has no raw chunks to check, so it has to
        // be handled before the chunk arithmetic below underflows on it.
        if self.mask.is_empty() {
            return true;
        }

        // First, we'll check the full usize elements
        let last_chunk = self.mask.as_raw_slice().len() - 1;
        if self.mask.as_raw_slice()[0..last_chunk]
            .iter()
            .any(|u| *u != 0)
        {
            false
        } else {
            for i in (last_chunk * usize::BITS as usize)..self.mask.len() {
                if self.get(i) {
                    return false;
                }
            }
            true
        }
    }

    /// Returns the first true index and sets it to false
    pub fn pop_true(&mut self) -> Option<usize> {
        let first = self.iter_true().next();
        if let Some(first) = first {
            self.set(first, false);
            return Some(first);
        }

        None
    }
}

pub struct MaskTrueIterator<'a> {
    mask: &'a IndexMask,
    current: usize,
}

impl<'a> Iterator for MaskTrueIterator<'a> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        while self.current < self.mask.len() {
            if self.mask.get(self.current) {
                let index = self.current;
                self.current += 1;
                return Some(index);
            }

            self.current += 1;
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::prelude::StdRng;
    use rand::{RngExt, SeedableRng};

    #[test]
    fn empty_mask_starting_zero() {
        let mask = IndexMask::new(1000, false);
        assert!(mask.is_empty());
    }

    #[test]
    fn zero_length_mask_is_empty() {
        let mask = IndexMask::new(0, false);
        assert!(mask.is_empty());
        assert_eq!(mask.len(), 0);
        assert!(mask.to_indices().is_empty());
    }

    #[test]
    fn equality_compares_length_and_bits() {
        let a = IndexMask::try_from_indices(&[1, 3], 8).unwrap();
        let b = IndexMask::try_from_indices(&[1, 3], 8).unwrap();
        let different_bits = IndexMask::try_from_indices(&[1, 4], 8).unwrap();
        let different_len = IndexMask::try_from_indices(&[1, 3], 9).unwrap();

        assert_eq!(a, b);
        assert_ne!(a, different_bits);
        assert_ne!(a, different_len);
    }

    #[test]
    fn empty_mask_starting_true() {
        let mask = IndexMask::new(1000, true);
        assert!(!mask.is_empty());
    }

    #[test]
    fn empty_mask_starting_true_manual_set_false() {
        let mut mask = IndexMask::new(1000, true);
        for i in 0..mask.len() {
            mask.set(i, false);
        }
        assert!(mask.is_empty());
    }

    #[test]
    fn or_returns_new_mask_with_union_and_keeps_inputs() {
        let left = IndexMask::try_from_indices(&[0, 2, 5], 8).unwrap();
        let right = IndexMask::try_from_indices(&[1, 2, 6], 8).unwrap();

        let result = left.or(&right).unwrap();

        assert_eq!(result.to_indices(), vec![0, 1, 2, 5, 6]);
        assert_eq!(left.to_indices(), vec![0, 2, 5]);
        assert_eq!(right.to_indices(), vec![1, 2, 6]);
    }

    #[test]
    fn or_returns_error_for_different_lengths() {
        let left = IndexMask::new(4, true);
        let right = IndexMask::new(5, false);

        let err = left.or(&right).unwrap_err();

        assert_eq!(err.to_string(), "Masks must be of the same length");
    }

    #[test]
    fn not_returns_new_inverted_mask_without_modifying_original() {
        let mask = IndexMask::try_from_indices(&[1, 3, 4], 6).unwrap();

        let inverted = mask.not();

        assert_eq!(inverted.to_indices(), vec![0, 2, 5]);
        assert_eq!(mask.to_indices(), vec![1, 3, 4]);
    }

    #[test]
    fn clone_indices_of_returns_error_when_item_length_does_not_match_mask_length() {
        let mask = IndexMask::try_from_indices(&[0, 2], 4).unwrap();
        let items = vec!["a", "b", "c"];

        let err = mask.clone_indices_of(&items).unwrap_err();

        assert_eq!(
            err.to_string(),
            "Items length 3 does not match mask length 4"
        );
    }

    #[test]
    fn fill_sets_all_bits_to_false() {
        let mut mask = IndexMask::new(300, true);

        mask.fill(false);

        assert_eq!(mask.len(), 300);
        for i in 0..mask.len() {
            assert!(!mask.get(i), "expected index {} to be false", i);
        }
    }

    #[test]
    fn fill_sets_all_bits_to_true() {
        let mut mask = IndexMask::new(300, false);

        mask.fill(true);

        assert_eq!(mask.len(), 300);
        for i in 0..mask.len() {
            assert!(mask.get(i), "expected index {} to be true", i);
        }
    }

    #[test]
    fn and_not_mut_removes_bits_present_in_other() {
        let mut left = IndexMask::try_from_indices(&[0, 2, 4, 6], 8).unwrap();
        let right = IndexMask::try_from_indices(&[2, 3, 6, 7], 8).unwrap();

        left.and_not_mut(&right).unwrap();

        assert_eq!(left.to_indices(), vec![0, 4]);
    }

    #[test]
    fn and_not_returns_new_mask_without_modifying_original() {
        let left = IndexMask::try_from_indices(&[1, 2, 5, 7], 8).unwrap();
        let right = IndexMask::try_from_indices(&[2, 4, 7], 8).unwrap();

        let result = left.and_not(&right).unwrap();

        assert_eq!(result.to_indices(), vec![1, 5]);
        assert_eq!(left.to_indices(), vec![1, 2, 5, 7]);
        assert_eq!(right.to_indices(), vec![2, 4, 7]);
    }

    #[test]
    fn and_returns_new_mask_with_intersection_and_keeps_inputs() {
        let left = IndexMask::try_from_indices(&[0, 2, 3, 6], 8).unwrap();
        let right = IndexMask::try_from_indices(&[1, 2, 6, 7], 8).unwrap();

        let result = left.and(&right).unwrap();

        assert_eq!(result.to_indices(), vec![2, 6]);
        assert_eq!(left.to_indices(), vec![0, 2, 3, 6]);
        assert_eq!(right.to_indices(), vec![1, 2, 6, 7]);
    }

    #[test]
    fn and_not_mut_returns_error_for_different_lengths() {
        let mut left = IndexMask::new(4, true);
        let right = IndexMask::new(5, false);

        let err = left.and_not_mut(&right).unwrap_err();

        assert_eq!(err.to_string(), "Masks must be of the same length");
        assert_eq!(left.to_indices(), vec![0, 1, 2, 3]);
    }

    #[test]
    fn and_returns_error_for_different_lengths() {
        let left = IndexMask::new(4, true);
        let right = IndexMask::new(5, false);

        let err = left.and(&right).unwrap_err();

        assert_eq!(err.to_string(), "Masks must be of the same length");
    }

    #[cfg(test)]
    mod stress_tests {
        use super::*;
        use rand::rngs::StdRng;
        use rand::{RngExt, SeedableRng};

        #[test]
        fn stress_set_and_get() {
            let len = 10_000;
            let mut rng = StdRng::seed_from_u64(42);
            let mut mask = IndexMask::new(len, false);
            let mut vec = vec![false; len];

            for _ in 0..100_000 {
                let idx = rng.random_range(0..len);
                let val = rng.random_bool(0.5);
                mask.set(idx, val);
                vec[idx] = val;
            }

            for (i, &v) in vec.iter().enumerate() {
                assert_eq!(mask.get(i), v, "Mismatch at index {}", i);
            }
        }

        #[test]
        fn stress_flip() {
            let len = 5_000;
            let mut rng = StdRng::seed_from_u64(123);
            let mut mask = IndexMask::new(len, false);
            let mut vec = vec![false; len];

            for _ in 0..10 {
                for (i, v) in vec.iter_mut().enumerate() {
                    let val = rng.random_bool(0.5);
                    mask.set(i, val);
                    *v = val;
                }
                mask.not_mut();
                for v in vec.iter_mut() {
                    *v = !*v;
                }
                for (i, &v) in vec.iter().enumerate() {
                    assert_eq!(mask.get(i), v, "Mismatch after flip at index {}", i);
                }
            }
        }

        #[test]
        fn stress_to_indices() {
            let len = 2_000;
            let mut rng = StdRng::seed_from_u64(999);
            let mut mask = IndexMask::new(len, false);
            let mut vec = vec![false; len];

            for (i, v) in vec.iter_mut().enumerate() {
                let val = rng.random_bool(0.3);
                mask.set(i, val);
                *v = val;
            }

            let mask_indices = mask.to_indices();
            let vec_indices: Vec<usize> = vec
                .iter()
                .enumerate()
                .filter_map(|(i, &v)| if v { Some(i) } else { None })
                .collect();

            assert_eq!(mask_indices, vec_indices, "Indices mismatch");
        }

        #[test]
        fn stress_to_true_sparse() {
            let len = 10_000;
            let mut rng = StdRng::seed_from_u64(345);

            for _ in 0..1000 {
                let mut mask = IndexMask::new(len, false);
                let i = rng.random_range(0..len);
                mask.set(i, true);

                let mask_indices = mask.to_indices();
                assert_eq!(mask_indices.len(), 1, "Indices mismatch");
                assert_eq!(mask_indices[0], i, "Indices mismatch");
            }
        }

        #[test]
        fn stress_to_true_iter() {
            let len = 10_000;
            let mut rng = StdRng::seed_from_u64(345);
            let mut mask = IndexMask::new(len, false);
            let mut vec = vec![false; len];

            for (i, v) in vec.iter_mut().enumerate() {
                let val = rng.random_bool(0.3);
                mask.set(i, val);
                *v = val;
            }

            let mut mask_indices = Vec::new();
            for index in mask.iter_true() {
                mask_indices.push(index);
            }

            let vec_indices: Vec<usize> = vec
                .iter()
                .enumerate()
                .filter_map(|(i, &v)| if v { Some(i) } else { None })
                .collect();

            assert_eq!(mask_indices, vec_indices, "Indices mismatch");
        }

        #[test]
        fn stress_and() {
            let len = 100_000;
            let mut rng = StdRng::seed_from_u64(345);

            for _ in 0..100 {
                let mut mask0 = IndexMask::new(len, false);
                let mut mask1 = IndexMask::new(len, false);

                let mut vec0 = vec![false; len];
                let mut vec1 = vec![false; len];

                for i in 0..len {
                    let val0 = rng.random_bool(0.3);
                    vec0[i] = val0;
                    mask0.set(i, val0);

                    let val1 = rng.random_bool(0.3);
                    vec1[i] = val1;
                    mask1.set(i, val1);
                }

                let expected = vec0
                    .iter()
                    .zip(vec1.iter())
                    .map(|(&v0, &v1)| v0 && v1)
                    .collect::<Vec<bool>>();

                mask0.and_mut(&mask1).unwrap();

                for (i, &exp) in expected.iter().enumerate() {
                    assert_eq!(mask0.get(i), exp, "Mismatch after OR at index {}", i);
                }
            }
        }

        #[test]
        fn stress_or() {
            let len = 100_000;
            let mut rng = StdRng::seed_from_u64(345);

            for _ in 0..100 {
                let mut mask0 = IndexMask::new(len, false);
                let mut mask1 = IndexMask::new(len, false);

                let mut vec0 = vec![false; len];
                let mut vec1 = vec![false; len];

                for i in 0..len {
                    let val0 = rng.random_bool(0.3);
                    vec0[i] = val0;
                    mask0.set(i, val0);

                    let val1 = rng.random_bool(0.3);
                    vec1[i] = val1;
                    mask1.set(i, val1);
                }

                let expected = vec0
                    .iter()
                    .zip(vec1.iter())
                    .map(|(&v0, &v1)| v0 || v1)
                    .collect::<Vec<bool>>();

                mask0.or_mut(&mask1).unwrap();

                for (i, &exp) in expected.iter().enumerate() {
                    assert_eq!(mask0.get(i), exp, "Mismatch after OR at index {}", i);
                }
            }
        }
    }

    #[test]
    fn stress_pop_true() {
        let len = 50_000;
        let mut rng = StdRng::seed_from_u64(1_337);

        for _ in 0..1000 {
            let mut mask = IndexMask::new(len, false);

            for _ in 0..5 {
                mask.set(rng.random_range(0..len), true);
            }
            let mut expected_result = mask.to_indices();
            let expected = expected_result[0];
            expected_result.remove(0);

            let result = mask.pop_true();
            assert_eq!(result, Some(expected));
            assert_eq!(mask.to_indices(), expected_result);
        }
    }
}