-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlib.rs
1268 lines (1172 loc) · 41.3 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! ## BitVec implemented with [portable-simd](https://github.com/rust-lang/portable-simd).
//!
//! BitVec represents numbers by the position of bits. For example, for the set $\{1,3,5\}$, we
//! can represent it by a just a byte `010101000` -- the most left (high) bit represent if `0`
//! exits in this set or not, the second bit represent `1` ...
//!
//! BitVec is usually used in the algorithm which requires many set intersection/union operations,
//! such like graph mining, formal concept analysis. Set operations in bitvec can be implemented
//! with simple and/or/xor operations so it is much faster than "normal" version of `HashSet`.
//!
//! Furthermore, as SIMD introduces the ability for handling multiple data with a single instruction,
//! set operations can be even faster with SIMD enabled.
//!
//! However, implementation with SIMD in Rust is not really an easy task -- now only low-level API
//! is provided through [core::arch](https://doc.rust-lang.org/core/arch/index.html). It requires
//! many `cfg(target_arch)`s (i.e. different implement on different arch) and
//! assembly-like unsafe function calls.
//!
//! The Rust standard library's portable SIMD API provided a much better API for users. You can just
//! treat SIMD operations as an operation on slices. Portable SIMD wraps all the low-level details
//! for you -- no arch-specified code, no unsafe, just do what you've done on normal integer/floats.
//!
//! This crate uses Portable SIMD to implement a basic bitvec.
//!
//! ### Usage
//!
//! ```rust
//! use bitsvec::BitVec;
//!
//! let mut bitvec = BitVec::ones(1_000); //create a set containing 0 ..= 999
//! bitvec.set(1_999, true); // add 1999 to the set, bitvec will be automatically expanded
//! bitvec.set(500, false); // delete 500 from the set
//! // now the set contains: 0 ..=499, 501..=1999
//! assert_eq!(bitvec.get(500), Some(false));
//! assert_eq!(bitvec.get(5_000), None);
//! // When try to get number larger than current bitvec, it will return `None`.
//! // of course if you don't care, you can just do:
//! assert_eq!(bitvec.get(5_000).unwrap_or(false), false);
//!
//! let bitvec2 = BitVec::zeros(2000); // create a set containing 0 ..=1999
//!
//! let bitvec3 = bitvec.and_cloned(&bitvec2);
//! // and/or/xor/not operation is provided.
//! // these APIs usually have 2 version:
//! // `.and` consume the inputs and `.and_clone()` accepts reference and will do clone on inputs.
//! let bitvec4 = bitvec & bitvec2;
//! // ofcourse you can just use bit-and operator on bitvecs, it will also consumes the inputs.
//! assert_eq!(bitvec3, bitvec4);
//! // A bitvec can also be constructed from a collection of bool, or a colluction of integer:
//! let bitvec: BitVec = (0 .. 10).map(|x| x%2 == 0).into();
//! let bitvec2: BitVec = (0 .. 10).map(|x| x%3 == 0).into();
//! let bitvec3 = BitVec::from_bool_iterator((0..10).map(|x| x%6 == 0));
//! assert_eq!(bitvec & bitvec2, bitvec3)
//! ```
//!
//! ## Performance
//!
//! run `cargo bench` to see the benchmarks on your device.
#![feature(portable_simd)]
#![no_std]
#[cfg(any(test, feature = "std"))]
#[macro_use]
extern crate std;
#[cfg(feature = "std")]
use std::vec::Vec;
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::fmt::{Binary, Debug, Display, Formatter, Result};
use core::ops::*;
use core::simd::*;
use smallvec::{Array, SmallVec};
#[cfg(test)]
mod tests;
// Declare the default BitVec type
pub type BitVec = BitVecSimd<[u64x4; 4], 4>;
/// Representation of a BitVec
///
/// see the module's document for examples and details.
///
#[derive(Debug, Clone)]
#[repr(C)]
pub struct BitVecSimd<A, const L: usize>
where
A: Array + Index<usize>,
A::Item: BitBlock<L>,
{
// internal representation of bitvec
// TODO: try `Vec`, may be better than smallvec
storage: SmallVec<A>,
// actual number of bits exists in storage
nbits: usize,
}
/// Proc macro can not export BitVec
/// macro_rules! can not cancot ident
/// so we use name, name_2 for function names
macro_rules! impl_operation {
($name:ident, $name_cloned:ident, $name_inplace:ident, $op:tt) => {
pub fn $name(self, other: Self) -> Self {
assert_eq!(self.nbits, other.nbits);
let storage = self
.storage
.into_iter()
.zip(other.storage.into_iter())
.map(|(a, b)| a $op b)
.collect();
Self {
storage,
nbits: self.nbits,
}
}
pub fn $name_cloned(&self, other: &Self) -> Self {
assert_eq!(self.nbits, other.nbits);
let storage = self
.storage
.iter()
.cloned()
.zip(other.storage.iter().cloned())
.map(|(a, b)| a $op b)
.collect();
Self {
storage,
nbits: self.nbits,
}
}
pub fn $name_inplace(&mut self, other: &Self) {
assert_eq!(self.nbits, other.nbits);
self.storage.iter_mut().zip(other.storage.iter()).for_each(|(a, b)| a.$name_inplace(b));
}
};
}
impl<A, const L: usize> BitVecSimd<A, L>
where
A: Array + Index<usize>,
A::Item: BitBlock<L>,
{
// convert total bit to length
// input: Number of bits
// output:
//
// 1. the number of Vector used
// 2. after filling 1, the remaining bytes should be filled
// 3. after filling 2, the remaining bits should be filled
//
// notice that this result represents the length of vector
// so if 3. is 0, it means no extra bits after filling bytes
// return (length of storage, u64 of last container, bit of last elem)
// any bits > length of last elem should be set to 0
#[inline]
fn bit_to_len(nbits: usize) -> (usize, usize, usize) {
(
nbits / (A::Item::BIT_WIDTH),
(nbits % A::Item::BIT_WIDTH) / A::Item::ELEMENT_BIT_WIDTH,
nbits % A::Item::ELEMENT_BIT_WIDTH,
)
}
#[inline]
fn set_bit(
flag: bool,
bytes: <A::Item as BitBlock<L>>::Item,
offset: u32,
) -> <A::Item as BitBlock<L>>::Item {
match flag {
true => bytes | A::Item::ONE_ELEMENT.wrapping_shl(offset),
false => bytes & !A::Item::ONE_ELEMENT.wrapping_shl(offset),
}
}
/// Create an empty bitvec with `nbits` initial elements.
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::zeros(10);
/// assert_eq!(bitvec.len(), 10);
/// ```
pub fn zeros(nbits: usize) -> Self {
let len = (nbits + A::Item::BIT_WIDTH - 1) / A::Item::BIT_WIDTH;
let storage = (0..len).map(|_| A::Item::ZERO).collect();
Self { storage, nbits }
}
/// Create a bitvec containing all 0 .. nbits elements.
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::ones(10);
/// assert_eq!(bitvec.len(), 10);
/// ```
pub fn ones(nbits: usize) -> Self {
let (len, bytes, bits) = Self::bit_to_len(nbits);
let mut storage = (0..len).map(|_| A::Item::MAX).collect::<SmallVec<_>>();
if bytes > 0 || bits > 0 {
let mut arr = A::Item::MAX.to_array();
arr[bytes] =
A::Item::MAX_ELEMENT.clear_high_bits((A::Item::ELEMENT_BIT_WIDTH - bits) as u32);
for item in arr.iter_mut().take(A::Item::LANES).skip(bytes + 1) {
*item = A::Item::ZERO_ELEMENT;
}
storage.push(A::Item::from(arr));
}
Self { storage, nbits }
}
/// Create a bitvec from an Iterator of bool.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::from_bool_iterator((0..10).map(|x| x % 2 == 0));
/// assert_eq!(bitvec.len(), 10);
/// assert_eq!(<BitVec as Into<Vec<bool>>>::into(bitvec), vec![true, false, true, false, true, false, true, false, true, false]);
///
/// let bitvec = BitVec::from_bool_iterator((0..1000).map(|x| x < 50));
/// assert_eq!(bitvec.len(), 1000);
/// assert_eq!(bitvec.get(49), Some(true));
/// assert_eq!(bitvec.get(50), Some(false));
/// assert_eq!(bitvec.get(999), Some(false));
/// assert_eq!(<BitVec as Into<Vec<bool>>>::into(bitvec), (0..1000).map(|x| x<50).collect::<Vec<bool>>());
/// ```
pub fn from_bool_iterator<I: Iterator<Item = bool>>(i: I) -> Self {
// FIXME: any better implementation?
let mut storage = SmallVec::new();
let mut current_slice = A::Item::ZERO.to_array();
let mut nbits = 0;
for b in i {
if b {
current_slice[nbits % A::Item::BIT_WIDTH / A::Item::ELEMENT_BIT_WIDTH] |=
A::Item::ONE_ELEMENT.wrapping_shl((nbits % A::Item::ELEMENT_BIT_WIDTH) as u32);
}
nbits += 1;
if nbits % A::Item::BIT_WIDTH == 0 {
storage.push(A::Item::from(current_slice));
current_slice = A::Item::ZERO.to_array();
}
}
if nbits % A::Item::BIT_WIDTH > 0 {
storage.push(A::Item::from(current_slice));
}
Self { storage, nbits }
}
/// Initialize from a set of integers.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::from_slice(&[0,5,9]);
/// assert_eq!(<BitVec as Into<Vec<bool>>>::into(bitvec), vec![true, false, false, false, false, true, false, false, false, true]);
/// ```
pub fn from_slice(slice: &[usize]) -> Self {
let mut bv = BitVecSimd::zeros(slice.len());
for i in slice {
bv.set(*i, true);
}
bv
}
/// Initialize from a E slice.
/// Data will be copied from the slice.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::from_slice_copy(&[3], 3);
/// assert_eq!(bitvec.get(0), Some(true));
/// assert_eq!(bitvec.get(1), Some(true));
/// assert_eq!(bitvec.get(2), Some(false));
/// assert_eq!(bitvec.get(3), None);
/// ```
pub fn from_slice_copy(slice: &[<A::Item as BitBlock<L>>::Item], nbits: usize) -> Self {
let len = (nbits + A::Item::ELEMENT_BIT_WIDTH - 1) / A::Item::ELEMENT_BIT_WIDTH;
assert!(len <= slice.len());
let iter = &mut slice.iter();
let mut storage = SmallVec::with_capacity((len + A::Item::LANES - 1) / A::Item::LANES);
let (i, bytes, bits) = Self::bit_to_len(nbits);
while let Some(a0) = iter.next() {
let mut arr = A::Item::ZERO.to_array();
arr[0] = *a0;
for item in arr.iter_mut().take(A::Item::LANES).skip(1) {
*item = *(iter.next().unwrap_or(&A::Item::ZERO_ELEMENT));
}
if storage.len() == i && (bytes > 0 || bits > 0) {
Self::clear_arr_high_bits(&mut arr, bytes, bits);
}
storage.push(A::Item::from(arr));
}
Self { storage, nbits }
}
/// Initialize from a raw buffer.
/// Data will be copied from the buffer which [ptr] points to.
/// The buffer can be released after initialization.
///
/// # Safety
///
/// If any of the following conditions are violated, the result is Undefined
/// Behavior:
///
/// * ptr should be valid and point to an [allocated object] with length >= buffer_len
///
/// * ptr.offset(buffer_len - 1), **in bytes**, cannot overflow an `isize`.
///
/// * The offset being in bounds cannot rely on "wrapping around" the address
/// space. That is, the infinite-precision sum, **in bytes** must fit in a usize.
///
pub unsafe fn from_raw_copy(
ptr: *const <A::Item as BitBlock<L>>::Item,
buffer_len: usize,
nbits: usize,
) -> Self {
let len = (nbits + A::Item::ELEMENT_BIT_WIDTH - 1) / A::Item::ELEMENT_BIT_WIDTH;
assert!(len <= buffer_len);
let mut storage = SmallVec::with_capacity((len + A::Item::LANES - 1) / A::Item::LANES);
let (i, bytes, bits) = Self::bit_to_len(nbits);
for index in 0..(len as isize) {
let mut arr = A::Item::ZERO.to_array();
for (j, item) in arr.iter_mut().enumerate().take(A::Item::LANES) {
let k = index * A::Item::LANES as isize + j as isize;
*item = if k < len as isize {
// The only unsafe operation happens here
*(ptr.offset(k))
} else {
A::Item::ZERO_ELEMENT
};
}
if storage.len() == i && (bytes > 0 || bits > 0) {
Self::clear_arr_high_bits(&mut arr, bytes, bits);
}
storage.push(A::Item::from(arr));
}
Self { storage, nbits }
}
/// Length of this bitvec.
///
/// To get the number of elements, use `count_ones`
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::ones(3);
/// assert_eq!(bitvec.len(), 3);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.nbits
}
/// Length of underlining storage.
#[inline]
pub fn storage_len(&self) -> usize {
self.storage.len()
}
/// Capacity of underlining storage.
#[inline]
pub fn storage_capacity(&self) -> usize {
self.storage.capacity()
}
/// Returns a raw pointer to the vector's buffer.
pub fn as_ptr(&self) -> *const A::Item {
self.storage.as_ptr()
}
/// Returns a raw mutable pointer to the vector's buffer.
pub fn as_mut_ptr(&mut self) -> *mut A::Item {
self.storage.as_mut_ptr()
}
/// Returns `true` if the data has spilled into a separate heap-allocated buffer.
#[inline]
pub fn spilled(&self) -> bool {
self.storage.spilled()
}
fn clear_arr_high_bits(arr: &mut [<A::Item as BitBlock<L>>::Item], bytes: usize, bits: usize) {
let mut end_bytes = bytes;
if bits > 0 {
arr[end_bytes] =
arr[end_bytes].clear_high_bits((A::Item::ELEMENT_BIT_WIDTH - bits) as u32);
end_bytes += 1;
}
for item in arr.iter_mut().take(A::Item::LANES).skip(end_bytes) {
*item = A::Item::ZERO_ELEMENT;
}
}
fn fill_arr_high_bits(
arr: &mut [<A::Item as BitBlock<L>>::Item],
bytes: usize,
bits: usize,
bytes_max: usize,
) {
let mut end_bytes = bytes;
if bits > 0 {
arr[end_bytes] |= A::Item::MAX_ELEMENT.clear_low_bits(bits as u32);
end_bytes += 1;
}
for item in arr.iter_mut().take(bytes_max).skip(end_bytes) {
*item = A::Item::MAX_ELEMENT;
}
}
fn clear_high_bits(&mut self, i: usize, bytes: usize, bits: usize) {
if bytes > 0 || bits > 0 {
let mut arr = self.storage[i].to_array();
Self::clear_arr_high_bits(&mut arr, bytes, bits);
self.storage[i] = A::Item::from(arr);
}
}
fn fill_high_bits(&mut self, i: usize, bytes: usize, bits: usize, bytes_max: usize) {
if bytes > 0 || bits > 0 {
let mut arr = self.storage[i].to_array();
Self::fill_arr_high_bits(&mut arr, bytes, bits, bytes_max);
self.storage[i] = A::Item::from(arr);
}
}
fn fix_high_bits(
&mut self,
old_i: usize,
old_bytes: usize,
old_bits: usize,
i: usize,
bytes: usize,
bits: usize,
) {
debug_assert!(old_i == i && old_bytes <= bytes && (bytes > 0 || bits > 0));
let mut arr = self.storage[i].to_array();
if old_bytes < bytes {
Self::fill_arr_high_bits(
&mut arr,
old_bytes,
old_bits,
if bits > 0 { bytes + 1 } else { bytes },
);
} else {
debug_assert!(old_bytes == bytes && bits >= old_bits);
if bits > old_bits {
// fix the only byte
arr[bytes] |= A::Item::MAX_ELEMENT.clear_low_bits(old_bits as u32);
}
}
Self::clear_arr_high_bits(&mut arr, bytes, bits);
self.storage[i] = A::Item::from(arr);
}
/// Resize this bitvec to `nbits` in-place.
/// If new length is greater than current length, `value` will be filled.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let mut bitvec = BitVec::ones(3);
/// bitvec.resize(5, false);
/// assert_eq!(bitvec.len(), 5);
/// bitvec.resize(2, false);
/// assert_eq!(bitvec.len(), 2);
/// ```
pub fn resize(&mut self, nbits: usize, value: bool) {
let (i, bytes, bits) = Self::bit_to_len(nbits);
self.storage.resize(
if bytes > 0 || bits > 0 { i + 1 } else { i },
if value { A::Item::MAX } else { A::Item::ZERO },
);
if nbits < self.nbits {
self.clear_high_bits(i, bytes, bits);
} else if value {
// old_i <= i && filling 1
let (old_i, old_bytes, old_bits) = Self::bit_to_len(self.nbits);
if old_i < i {
self.fill_high_bits(old_i, old_bytes, old_bits, A::Item::LANES);
self.clear_high_bits(i, bytes, bits);
} else if bytes > 0 || bits > 0 {
self.fix_high_bits(old_i, old_bytes, old_bits, i, bytes, bits);
}
}
self.nbits = nbits;
}
/// Shink this bitvec to new length in-place.
/// Panics if new length is greater than original.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let mut bitvec = BitVec::ones(3);
/// bitvec.shrink_to(2);
/// assert_eq!(bitvec.len(), 2);
/// ```
pub fn shrink_to(&mut self, nbits: usize) {
if nbits >= self.nbits {
panic!(
"nbits {} should be less than current value {}",
nbits, self.nbits
);
}
self.resize(nbits, false);
}
/// Remove or add `index` to the set.
/// If index > self.len, the bitvec will be expanded to `index`.
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let mut bitvec = BitVec::zeros(10);
/// assert_eq!(bitvec.len(), 10);
/// bitvec.set(15, true);
/// // now 15 has been added to the set, its total len is 16.
/// assert_eq!(bitvec.len(), 16);
/// assert_eq!(bitvec.get(15), Some(true));
/// assert_eq!(bitvec.get(14), Some(false));
/// ```
pub fn set(&mut self, index: usize, flag: bool) {
let (i, bytes, bits) = Self::bit_to_len(index);
if self.nbits <= index {
let new_len = if bytes > 0 || bits > 0 { i + 1 } else { i };
self.storage
.extend((0..new_len - self.storage.len()).map(move |_| A::Item::ZERO));
self.nbits = index + 1;
}
let mut arr = self.storage[i].to_array();
arr[bytes] = Self::set_bit(flag, arr[bytes], bits as u32);
self.storage[i] = A::Item::from(arr);
}
/// Copy content which ptr points to bitvec storage
///
/// # Safety
///
/// This is highly unsafe, due to the number of invariants that aren’t checked.
pub unsafe fn set_raw_copy(&mut self, ptr: *mut A::Item, buffer_len: usize, nbits: usize) {
let new_len = (nbits + A::Item::BIT_WIDTH - 1) / A::Item::BIT_WIDTH;
assert!(new_len <= buffer_len);
if new_len > self.len() {
self.storage
.extend((0..new_len - self.storage.len()).map(move |_| A::Item::ZERO));
}
for i in 0..(new_len as isize) {
self.storage[i as usize] = *ptr.offset(i);
}
self.nbits = nbits;
}
/// Directly set storage to ptr
///
/// # Safety
///
/// This is highly unsafe, due to the number of invariants that aren’t checked.
pub unsafe fn set_raw(
&mut self,
ptr: *mut A::Item,
buffer_len: usize,
capacity: usize,
nbits: usize,
) {
self.storage = SmallVec::from_raw_parts(ptr, buffer_len, capacity);
self.nbits = nbits;
}
/// Set all items in bitvec to false
pub fn set_all_false(&mut self) {
self.storage
.iter_mut()
.for_each(move |x| *x = A::Item::ZERO);
}
/// Set all items in bitvec to true
pub fn set_all_true(&mut self) {
let (_, bytes, bits) = Self::bit_to_len(self.nbits);
self.storage.iter_mut().for_each(move |x| *x = A::Item::MAX);
if bytes > 0 || bits > 0 {
let mut arr = A::Item::MAX.to_array();
arr[bytes] =
A::Item::MAX_ELEMENT.clear_high_bits((A::Item::ELEMENT_BIT_WIDTH - bits) as u32);
for item in arr.iter_mut().take(A::Item::LANES).skip(bytes + 1) {
*item = A::Item::ZERO_ELEMENT;
}
// unwrap here is safe since bytes > 0 || bits > 0 => self.nbits > 0
*(self.storage.last_mut().unwrap()) = A::Item::from(arr);
}
}
/// Set all items in bitvec to flag
pub fn set_all(&mut self, flag: bool) {
match flag {
true => self.set_all_true(),
false => self.set_all_false(),
}
}
/// Check if `index` exists in current set.
///
/// * If exists, return `Some(true)`
/// * If index < current.len and element doesn't exist, return `Some(false)`.
/// * If index >= current.len, return `None`.
///
/// Examlpe:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec : BitVec = (0 .. 15).map(|x| x%3 == 0).into();
/// assert_eq!(bitvec.get(3), Some(true));
/// assert_eq!(bitvec.get(5), Some(false));
/// assert_eq!(bitvec.get(14), Some(false));
/// assert_eq!(bitvec.get(15), None);
/// ```
pub fn get(&self, index: usize) -> Option<bool> {
if self.nbits <= index {
None
} else {
let (index, bytes, bits) = Self::bit_to_len(index);
Some(
self.storage[index].to_array()[bytes]
& A::Item::ONE_ELEMENT.wrapping_shl(bits as u32)
!= A::Item::ZERO_ELEMENT,
)
}
}
/// Directly return a `bool` instead of an `Option`
///
/// * If exists, return `true`.
/// * If doesn't exist, return false.
/// * If index >= current.len, panic.
///
///
/// Examlpe:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec : BitVec = (0 .. 15).map(|x| x%3 == 0).into();
/// assert_eq!(bitvec.get_unchecked(3), true);
/// assert_eq!(bitvec.get_unchecked(5), false);
/// assert_eq!(bitvec.get_unchecked(14), false);
/// ```
pub fn get_unchecked(&self, index: usize) -> bool {
if self.nbits <= index {
panic!("index out of bounds {} > {}", index, self.nbits);
} else {
let (index, bytes, bits) = Self::bit_to_len(index);
(self.storage[index].to_array()[bytes] & A::Item::ONE_ELEMENT.wrapping_shl(bits as u32))
!= A::Item::ZERO_ELEMENT
}
}
impl_operation!(and, and_cloned, and_inplace, &);
impl_operation!(or, or_cloned, or_inplace, |);
impl_operation!(xor, xor_cloned, xor_inplace, ^);
/// difference operation
///
/// `A.difference(B)` calculates `A\B`, e.g.
///
/// ```text
/// A = [1,2,3], B = [2,4,5]
/// A\B = [1,3]
/// ```
///
/// also notice that
///
/// ```text
/// A.difference(B) | B.difference(A) == A ^ B
/// ```
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec: BitVec = (0 .. 5_000).map(|x| x % 2 == 0).into();
/// let bitvec2 : BitVec = (0 .. 5_000).map(|x| x % 3 == 0).into();
/// assert_eq!(bitvec.difference_cloned(&bitvec2) | bitvec2.difference_cloned(&bitvec), bitvec.xor_cloned(&bitvec2));
/// let bitvec3 : BitVec = (0 .. 5_000).map(|x| x % 2 == 0 && x % 3 != 0).into();
/// assert_eq!(bitvec.difference(bitvec2), bitvec3);
/// ```
pub fn difference(self, other: Self) -> Self {
self.and(other.not())
}
pub fn difference_cloned(&self, other: &Self) -> Self {
// FIXME: This implementation has one extra clone
self.and_cloned(&<&BitVecSimd<A, L>>::clone(&other).not())
}
// not should make sure bits > nbits is 0
/// inverse every bits in the vector.
///
/// If your bitvec have len `1_000` and contains `[1,5]`,
/// after inverse it will contains `0, 2..=4, 6..=999`
pub fn inverse(&self) -> Self {
let (i, bytes, bits) = Self::bit_to_len(self.nbits);
let mut storage = self.storage.iter().map(|x| !(*x)).collect::<SmallVec<_>>();
if bytes > 0 || bits > 0 {
assert_eq!(storage.len(), i + 1);
let s: &mut A::Item = &mut storage[i];
let mut arr = s.to_array();
arr[bytes] = arr[bytes].clear_high_bits((A::Item::ELEMENT_BIT_WIDTH - bits) as u32);
for item in arr.iter_mut().take(A::Item::LANES).skip(bytes + 1) {
*item = A::Item::ZERO_ELEMENT;
}
*s = arr.into();
}
Self {
storage,
nbits: self.nbits,
}
}
/// Count the number of elements existing in this bitvec.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec: BitVec = (0..10_000).map(|x| x%2==0).into();
/// assert_eq!(bitvec.count_ones(), 5000);
///
/// let bitvec: BitVec = (0..30_000).map(|x| x%3==0).into();
/// assert_eq!(bitvec.count_ones(), 10_000);
/// ```
pub fn count_ones(&self) -> usize {
self.storage
.iter()
.map(|x| {
x.to_array()
.into_iter()
.map(|a| a.count_ones())
.sum::<u32>()
})
.sum::<u32>() as usize
}
/// Count the number of elements existing in this bitvec, before the specified index.
/// Panics if index is invalid.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec: BitVec = (0..10_000).map(|x| x%2==0).into();
/// assert_eq!(bitvec.count_ones_before(5000), 2500);
///
/// let bitvec: BitVec = (0..30_000).map(|x| x%3==0).into();
/// assert_eq!(bitvec.count_ones_before(10000), 3334);
/// ```
pub fn count_ones_before(&self, index: usize) -> usize {
assert!(index <= self.nbits);
if index == 0 {
return 0;
}
let (i, bytes, bits) = Self::bit_to_len(index - 1);
let mut ones = self
.storage
.iter()
.take(i)
.map(|x| {
x.to_array()
.into_iter()
.map(|a| a.count_ones())
.sum::<u32>()
})
.sum::<u32>();
if bytes > 0 || bits > 0 {
// Safe unwrap here
let arr = self.storage.iter().nth(i).unwrap().to_array();
ones += arr
.into_iter()
.take(bytes)
.map(|x| x.count_ones())
.sum::<u32>();
if bits > 0 {
let x = arr.into_iter().nth(bytes).unwrap();
ones += (x
& (A::Item::ONE_ELEMENT.wrapping_shl((bits + 1) as u32)
- A::Item::ONE_ELEMENT))
.count_ones();
}
}
ones as usize
}
/// Count the number of leading zeros in this bitvec.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let mut bitvec = BitVec::zeros(10);
/// bitvec.set(3, true);
/// assert_eq!(bitvec.leading_zeros(), 6);
/// ```
pub fn leading_zeros(&self) -> usize {
let mut zero_item_count = 0;
let mut iter = self
.storage
.iter()
.rev()
.skip_while(|x| match **x == A::Item::ZERO {
true => {
zero_item_count += A::Item::LANES;
true
}
false => false,
});
if let Some(x) = iter.next() {
let arr = x.to_array();
let mut x_iter =
arr.into_iter()
.rev()
.skip_while(|y| match *y == A::Item::ZERO_ELEMENT {
true => {
zero_item_count += 1;
true
}
false => false,
});
// Safe unwrap here, since there should be at least one non-zero item in arr.
let y = x_iter.next().unwrap();
let raw_leading_zeros =
zero_item_count * A::Item::ELEMENT_BIT_WIDTH + y.leading_zeros() as usize;
let mut extra_leading_zeros = self.nbits % A::Item::BIT_WIDTH;
if extra_leading_zeros > 0 {
extra_leading_zeros = A::Item::BIT_WIDTH - extra_leading_zeros
}
return raw_leading_zeros - extra_leading_zeros;
}
self.nbits
}
/// return true if contains at least 1 element
pub fn any(&self) -> bool {
self.storage.iter().any(|x| {
x.to_array()
.into_iter()
.map(|a| a.count_ones())
.sum::<u32>()
> 0
})
}
/// return true if contains self.len elements
pub fn all(&self) -> bool {
self.count_ones() == self.nbits
}
/// return true if set is empty
pub fn none(&self) -> bool {
!self.any()
}
/// Return true if set is empty.
/// Totally the same with `self.none()`
pub fn is_empty(&self) -> bool {
!self.any()
}
/// Consume self and generate a `Vec<bool>` with length == self.len().
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::from_bool_iterator((0..10).map(|i| i % 3 == 0));
/// let bool_vec = bitvec.into_bools();
/// assert_eq!(bool_vec, vec![true, false, false, true, false, false, true, false, false, true])
/// ```
pub fn into_bools(self) -> Vec<bool> {
self.into()
}
/// Consume self and geterate a `Vec<usize>` which only contains the number exists in this set.
///
/// Example:
///
/// ```rust
/// use bitsvec::BitVec;
///
/// let bitvec = BitVec::from_bool_iterator((0..10).map(|i| i%3 == 0));
/// let usize_vec = bitvec.into_usizes();
/// assert_eq!(usize_vec, vec![0,3,6,9]);
/// ```
pub fn into_usizes(self) -> Vec<usize> {
self.into()
}
}
impl<A, I: Iterator<Item = bool>, const L: usize> From<I> for BitVecSimd<A, L>
where
A: Array + Index<usize>,
A::Item: BitBlock<L>,
{
fn from(i: I) -> Self {
Self::from_bool_iterator(i)
}
}
macro_rules! impl_trait {
(
( $( $name:tt )+ ),
( $( $name1:tt )+ ),
{ $( $body:tt )* }
) =>
{
impl<A, const L: usize> $( $name )+ for $( $name1 )+
where
A: Array + Index<usize>,
A::Item: BitBlock<L>,
{ $( $body )* }
};
}
impl_trait! {
(From< BitVecSimd<A, L> >),
(Vec<bool>),
{
fn from(v: BitVecSimd<A, L>) -> Self {
v.storage
.into_iter()
.flat_map(|x| x.to_array())
.flat_map(|x| {
(0..A::Item::ELEMENT_BIT_WIDTH)
.map(move |i| (x.wrapping_shr(i as u32)) & A::Item::ONE_ELEMENT != A::Item::ZERO_ELEMENT)
})
.take(v.nbits)
.collect()
}
}
}
impl_trait! {
(From< BitVecSimd<A, L> >),
(Vec<usize>),
{
fn from(v: BitVecSimd<A, L>) -> Self {
v.storage
.into_iter()
.flat_map(|x| x.to_array())
.flat_map(|x| { (0..A::Item::ELEMENT_BIT_WIDTH).map(move |i| (x.wrapping_shr(i as u32)) & A::Item::ONE_ELEMENT != A::Item::ZERO_ELEMENT) })
.take(v.nbits)
.enumerate()
.filter(|(_, b)| *b)
.map(|(i, _)| i)
.collect()
}
}
}
impl_trait! {