forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbit.rs
2152 lines (1973 loc) · 63.2 KB
/
bit.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
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// FIXME(Gankro): BitVec and BitSet are very tightly coupled. Ideally (for
// maintenance), they should be in separate files/modules, with BitSet only
// using BitVec's public API. This will be hard for performance though, because
// `BitVec` will not want to leak its internal representation while its internal
// representation as `u32`s must be assumed for best performance.
// FIXME(tbu-): `BitVec`'s methods shouldn't be `union`, `intersection`, but
// rather `or` and `and`.
// (1) Be careful, most things can overflow here because the amount of bits in
// memory can overflow `usize`.
// (2) Make sure that the underlying vector has no excess length:
// E. g. `nbits == 16`, `storage.len() == 2` would be excess length,
// because the last word isn't used at all. This is important because some
// methods rely on it (for *CORRECTNESS*).
// (3) Make sure that the unused bits in the last word are zeroed out, again
// other methods rely on it for *CORRECTNESS*.
// (4) `BitSet` is tightly coupled with `BitVec`, so any changes you make in
// `BitVec` will need to be reflected in `BitSet`.
//! Collections implemented with bit vectors.
//!
//! # Examples
//!
//! This is a simple example of the [Sieve of Eratosthenes][sieve]
//! which calculates prime numbers up to a given limit.
//!
//! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
//!
//! ```
//! # #![feature(collections, core, step_by)]
//! use std::collections::{BitSet, BitVec};
//! use std::iter;
//!
//! let max_prime = 10000;
//!
//! // Store the primes as a BitSet
//! let primes = {
//! // Assume all numbers are prime to begin, and then we
//! // cross off non-primes progressively
//! let mut bv = BitVec::from_elem(max_prime, true);
//!
//! // Neither 0 nor 1 are prime
//! bv.set(0, false);
//! bv.set(1, false);
//!
//! for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as usize) {
//! // if i is a prime
//! if bv[i] {
//! // Mark all multiples of i as non-prime (any multiples below i * i
//! // will have been marked as non-prime previously)
//! for j in (i * i..max_prime).step_by(i) { bv.set(j, false) }
//! }
//! }
//! BitSet::from_bit_vec(bv)
//! };
//!
//! // Simple primality tests below our max bound
//! let print_primes = 20;
//! print!("The primes below {} are: ", print_primes);
//! for x in 0..print_primes {
//! if primes.contains(&x) {
//! print!("{} ", x);
//! }
//! }
//! println!("");
//!
//! // We can manipulate the internal BitVec
//! let num_primes = primes.get_ref().iter().filter(|x| *x).count();
//! println!("There are {} primes below {}", num_primes, max_prime);
//! ```
use core::prelude::*;
use core::cmp::Ordering;
use core::cmp;
use core::fmt;
use core::hash;
use core::iter::RandomAccessIterator;
use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned};
use core::iter::{self, FromIterator};
use core::mem::swap;
use core::ops::Index;
use core::slice;
use core::{u8, u32, usize};
use bit_set; //so meta
use Vec;
type Blocks<'a> = Cloned<slice::Iter<'a, u32>>;
type MutBlocks<'a> = slice::IterMut<'a, u32>;
type MatchWords<'a> = Chain<Enumerate<Blocks<'a>>, Skip<Take<Enumerate<Repeat<u32>>>>>;
fn reverse_bits(byte: u8) -> u8 {
let mut result = 0;
for i in 0..u8::BITS {
result |= ((byte >> i) & 1) << (u8::BITS - 1 - i);
}
result
}
// Take two BitVec's, and return iterators of their words, where the shorter one
// has been padded with 0's
fn match_words <'a,'b>(a: &'a BitVec, b: &'b BitVec) -> (MatchWords<'a>, MatchWords<'b>) {
let a_len = a.storage.len();
let b_len = b.storage.len();
// have to uselessly pretend to pad the longer one for type matching
if a_len < b_len {
(a.blocks().enumerate().chain(iter::repeat(0).enumerate().take(b_len).skip(a_len)),
b.blocks().enumerate().chain(iter::repeat(0).enumerate().take(0).skip(0)))
} else {
(a.blocks().enumerate().chain(iter::repeat(0).enumerate().take(0).skip(0)),
b.blocks().enumerate().chain(iter::repeat(0).enumerate().take(a_len).skip(b_len)))
}
}
static TRUE: bool = true;
static FALSE: bool = false;
/// The bitvector type.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
///
/// // insert all primes less than 10
/// bv.set(2, true);
/// bv.set(3, true);
/// bv.set(5, true);
/// bv.set(7, true);
/// println!("{:?}", bv);
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
///
/// // flip all values in bitvector, producing non-primes less than 10
/// bv.negate();
/// println!("{:?}", bv);
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
///
/// // reset bitvector to empty
/// bv.clear();
/// println!("{:?}", bv);
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
/// ```
#[unstable(feature = "collections",
reason = "RFC 509")]
pub struct BitVec {
/// Internal representation of the bit vector
storage: Vec<u32>,
/// The number of valid bits in the internal representation
nbits: usize
}
// FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
impl Index<usize> for BitVec {
type Output = bool;
#[inline]
fn index(&self, i: usize) -> &bool {
if self.get(i).expect("index out of bounds") {
&TRUE
} else {
&FALSE
}
}
}
/// Computes how many blocks are needed to store that many bits
fn blocks_for_bits(bits: usize) -> usize {
// If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
// reserve enough. But if we want exactly a multiple of 32, this will actually allocate
// one too many. So we need to check if that's the case. We can do that by computing if
// bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
// superior modulo operator on a power of two to this.
//
// Note that we can technically avoid this branch with the expression
// `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
if bits % u32::BITS == 0 {
bits / u32::BITS
} else {
bits / u32::BITS + 1
}
}
/// Computes the bitmask for the final word of the vector
fn mask_for_bits(bits: usize) -> u32 {
// Note especially that a perfect multiple of u32::BITS should mask all 1s.
!0 >> (u32::BITS - bits % u32::BITS) % u32::BITS
}
impl BitVec {
/// Applies the given operation to the blocks of self and other, and sets
/// self to be the result. This relies on the caller not to corrupt the
/// last word.
#[inline]
fn process<F>(&mut self, other: &BitVec, mut op: F) -> bool where F: FnMut(u32, u32) -> u32 {
assert_eq!(self.len(), other.len());
// This could theoretically be a `debug_assert!`.
assert_eq!(self.storage.len(), other.storage.len());
let mut changed_bits = 0;
for (a, b) in self.blocks_mut().zip(other.blocks()) {
let w = op(*a, b);
changed_bits |= *a ^ w;
*a = w;
}
changed_bits != 0
}
/// Iterator over mutable refs to the underlying blocks of data.
fn blocks_mut(&mut self) -> MutBlocks {
// (2)
self.storage.iter_mut()
}
/// Iterator over the underlying blocks of data
fn blocks(&self) -> Blocks {
// (2)
self.storage.iter().cloned()
}
/// An operation might screw up the unused bits in the last block of the
/// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
fn fix_last_block(&mut self) {
let extra_bits = self.len() % u32::BITS;
if extra_bits > 0 {
let mask = (1 << extra_bits) - 1;
let storage_len = self.storage.len();
self.storage[storage_len - 1] &= mask;
}
}
/// Creates an empty `BitVec`.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
/// let mut bv = BitVec::new();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> BitVec {
BitVec { storage: Vec::new(), nbits: 0 }
}
/// Creates a `BitVec` that holds `nbits` elements, setting each element
/// to `bit`.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// assert_eq!(bv.len(), 10);
/// for x in bv.iter() {
/// assert_eq!(x, false);
/// }
/// ```
pub fn from_elem(nbits: usize, bit: bool) -> BitVec {
let nblocks = blocks_for_bits(nbits);
let mut bit_vec = BitVec {
storage: repeat(if bit { !0 } else { 0 }).take(nblocks).collect(),
nbits: nbits
};
bit_vec.fix_last_block();
bit_vec
}
/// Constructs a new, empty `BitVec` with the specified capacity.
///
/// The bitvector will be able to hold at least `capacity` bits without
/// reallocating. If `capacity` is 0, it will not allocate.
///
/// It is important to note that this function does not specify the
/// *length* of the returned bitvector, but only the *capacity*.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(nbits: usize) -> BitVec {
BitVec {
storage: Vec::with_capacity(blocks_for_bits(nbits)),
nbits: 0,
}
}
/// Transforms a byte-vector into a `BitVec`. Each byte becomes eight bits,
/// with the most significant bits of each byte coming first. Each
/// bit becomes `true` if equal to 1 or `false` if equal to 0.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b10100000, 0b00010010]);
/// assert!(bv.eq_vec(&[true, false, true, false,
/// false, false, false, false,
/// false, false, false, true,
/// false, false, true, false]));
/// ```
pub fn from_bytes(bytes: &[u8]) -> BitVec {
let len = bytes.len().checked_mul(u8::BITS).expect("capacity overflow");
let mut bit_vec = BitVec::with_capacity(len);
let complete_words = bytes.len() / 4;
let extra_bytes = bytes.len() % 4;
bit_vec.nbits = len;
for i in 0..complete_words {
bit_vec.storage.push(
((reverse_bits(bytes[i * 4 + 0]) as u32) << 0) |
((reverse_bits(bytes[i * 4 + 1]) as u32) << 8) |
((reverse_bits(bytes[i * 4 + 2]) as u32) << 16) |
((reverse_bits(bytes[i * 4 + 3]) as u32) << 24)
);
}
if extra_bytes > 0 {
let mut last_word = 0;
for (i, &byte) in bytes[complete_words*4..].iter().enumerate() {
last_word |= (reverse_bits(byte) as u32) << (i * 8);
}
bit_vec.storage.push(last_word);
}
bit_vec
}
/// Creates a `BitVec` of the specified length where the value at each index
/// is `f(index)`.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_fn(5, |i| { i % 2 == 0 });
/// assert!(bv.eq_vec(&[true, false, true, false, true]));
/// ```
pub fn from_fn<F>(len: usize, mut f: F) -> BitVec where F: FnMut(usize) -> bool {
let mut bit_vec = BitVec::from_elem(len, false);
for i in 0..len {
bit_vec.set(i, f(i));
}
bit_vec
}
/// Retrieves the value at index `i`, or `None` if the index is out of bounds.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01100000]);
/// assert_eq!(bv.get(0), Some(false));
/// assert_eq!(bv.get(1), Some(true));
/// assert_eq!(bv.get(100), None);
///
/// // Can also use array indexing
/// assert_eq!(bv[1], true);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self, i: usize) -> Option<bool> {
if i >= self.nbits {
return None;
}
let w = i / u32::BITS;
let b = i % u32::BITS;
self.storage.get(w).map(|&block|
(block & (1 << b)) != 0
)
}
/// Sets the value of a bit at an index `i`.
///
/// # Panics
///
/// Panics if `i` is out of bounds.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, false);
/// bv.set(3, true);
/// assert_eq!(bv[3], true);
/// ```
#[inline]
#[unstable(feature = "collections",
reason = "panic semantics are likely to change in the future")]
pub fn set(&mut self, i: usize, x: bool) {
assert!(i < self.nbits);
let w = i / u32::BITS;
let b = i % u32::BITS;
let flag = 1 << b;
let val = if x { self.storage[w] | flag }
else { self.storage[w] & !flag };
self.storage[w] = val;
}
/// Sets all bits to 1.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// let after = 0b11111111;
///
/// let mut bv = BitVec::from_bytes(&[before]);
/// bv.set_all();
/// assert_eq!(bv, BitVec::from_bytes(&[after]));
/// ```
#[inline]
pub fn set_all(&mut self) {
for w in &mut self.storage { *w = !0; }
self.fix_last_block();
}
/// Flips all bits.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// let after = 0b10011111;
///
/// let mut bv = BitVec::from_bytes(&[before]);
/// bv.negate();
/// assert_eq!(bv, BitVec::from_bytes(&[after]));
/// ```
#[inline]
pub fn negate(&mut self) {
for w in &mut self.storage { *w = !*w; }
self.fix_last_block();
}
/// Calculates the union of two bitvectors. This acts like the bitwise `or`
/// function.
///
/// Sets `self` to the union of `self` and `other`. Both bitvectors must be
/// the same length. Returns `true` if `self` changed.
///
/// # Panics
///
/// Panics if the bitvectors are of different lengths.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let a = 0b01100100;
/// let b = 0b01011010;
/// let res = 0b01111110;
///
/// let mut a = BitVec::from_bytes(&[a]);
/// let b = BitVec::from_bytes(&[b]);
///
/// assert!(a.union(&b));
/// assert_eq!(a, BitVec::from_bytes(&[res]));
/// ```
#[inline]
pub fn union(&mut self, other: &BitVec) -> bool {
self.process(other, |w1, w2| w1 | w2)
}
/// Calculates the intersection of two bitvectors. This acts like the
/// bitwise `and` function.
///
/// Sets `self` to the intersection of `self` and `other`. Both bitvectors
/// must be the same length. Returns `true` if `self` changed.
///
/// # Panics
///
/// Panics if the bitvectors are of different lengths.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let a = 0b01100100;
/// let b = 0b01011010;
/// let res = 0b01000000;
///
/// let mut a = BitVec::from_bytes(&[a]);
/// let b = BitVec::from_bytes(&[b]);
///
/// assert!(a.intersect(&b));
/// assert_eq!(a, BitVec::from_bytes(&[res]));
/// ```
#[inline]
pub fn intersect(&mut self, other: &BitVec) -> bool {
self.process(other, |w1, w2| w1 & w2)
}
/// Calculates the difference between two bitvectors.
///
/// Sets each element of `self` to the value of that element minus the
/// element of `other` at the same index. Both bitvectors must be the same
/// length. Returns `true` if `self` changed.
///
/// # Panics
///
/// Panics if the bitvectors are of different length.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let a = 0b01100100;
/// let b = 0b01011010;
/// let a_b = 0b00100100; // a - b
/// let b_a = 0b00011010; // b - a
///
/// let mut bva = BitVec::from_bytes(&[a]);
/// let bvb = BitVec::from_bytes(&[b]);
///
/// assert!(bva.difference(&bvb));
/// assert_eq!(bva, BitVec::from_bytes(&[a_b]));
///
/// let bva = BitVec::from_bytes(&[a]);
/// let mut bvb = BitVec::from_bytes(&[b]);
///
/// assert!(bvb.difference(&bva));
/// assert_eq!(bvb, BitVec::from_bytes(&[b_a]));
/// ```
#[inline]
pub fn difference(&mut self, other: &BitVec) -> bool {
self.process(other, |w1, w2| w1 & !w2)
}
/// Returns `true` if all bits are 1.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, true);
/// assert_eq!(bv.all(), true);
///
/// bv.set(1, false);
/// assert_eq!(bv.all(), false);
/// ```
pub fn all(&self) -> bool {
let mut last_word = !0;
// Check that every block but the last is all-ones...
self.blocks().all(|elem| {
let tmp = last_word;
last_word = elem;
tmp == !0
// and then check the last one has enough ones
}) && (last_word == mask_for_bits(self.nbits))
}
/// Returns an iterator over the elements of the vector in order.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
/// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter(&self) -> Iter {
Iter { bit_vec: self, next_idx: 0, end_idx: self.nbits }
}
/// Moves all bits from `other` into `Self`, leaving `other` empty.
///
/// # Examples
///
/// ```
/// # #![feature(collections, bit_vec_append_split_off)]
/// use std::collections::BitVec;
///
/// let mut a = BitVec::from_bytes(&[0b10000000]);
/// let mut b = BitVec::from_bytes(&[0b01100001]);
///
/// a.append(&mut b);
///
/// assert_eq!(a.len(), 16);
/// assert_eq!(b.len(), 0);
/// assert!(a.eq_vec(&[true, false, false, false, false, false, false, false,
/// false, true, true, false, false, false, false, true]));
/// ```
#[unstable(feature = "bit_vec_append_split_off",
reason = "recently added as part of collections reform 2")]
pub fn append(&mut self, other: &mut Self) {
let b = self.len() % u32::BITS;
self.nbits += other.len();
other.nbits = 0;
if b == 0 {
self.storage.append(&mut other.storage);
} else {
self.storage.reserve(other.storage.len());
for block in other.storage.drain(..) {
*(self.storage.last_mut().unwrap()) |= block << b;
self.storage.push(block >> (u32::BITS - b));
}
}
}
/// Splits the `BitVec` into two at the given bit,
/// retaining the first half in-place and returning the second one.
///
/// # Panics
///
/// Panics if `at` is out of bounds.
///
/// # Examples
///
/// ```
/// # #![feature(collections, bit_vec_append_split_off)]
/// use std::collections::BitVec;
/// let mut a = BitVec::new();
/// a.push(true);
/// a.push(false);
/// a.push(false);
/// a.push(true);
///
/// let b = a.split_off(2);
///
/// assert_eq!(a.len(), 2);
/// assert_eq!(b.len(), 2);
/// assert!(a.eq_vec(&[true, false]));
/// assert!(b.eq_vec(&[false, true]));
/// ```
#[unstable(feature = "bit_vec_append_split_off",
reason = "recently added as part of collections reform 2")]
pub fn split_off(&mut self, at: usize) -> Self {
assert!(at <= self.len(), "`at` out of bounds");
let mut other = BitVec::new();
if at == 0 {
swap(self, &mut other);
return other;
} else if at == self.len() {
return other;
}
let w = at / u32::BITS;
let b = at % u32::BITS;
other.nbits = self.nbits - at;
self.nbits = at;
if b == 0 {
// Split at block boundary
other.storage = self.storage.split_off(w);
} else {
other.storage.reserve(self.storage.len() - w);
{
let mut iter = self.storage[w..].iter();
let mut last = *iter.next().unwrap();
for &cur in iter {
other.storage.push((last >> b) | (cur << (u32::BITS - b)));
last = cur;
}
other.storage.push(last >> b);
}
self.storage.truncate(w+1);
self.fix_last_block();
}
other
}
/// Returns `true` if all bits are 0.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// assert_eq!(bv.none(), true);
///
/// bv.set(3, true);
/// assert_eq!(bv.none(), false);
/// ```
pub fn none(&self) -> bool {
self.blocks().all(|w| w == 0)
}
/// Returns `true` if any bit is 1.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// assert_eq!(bv.any(), false);
///
/// bv.set(3, true);
/// assert_eq!(bv.any(), true);
/// ```
#[inline]
pub fn any(&self) -> bool {
!self.none()
}
/// Organises the bits into bytes, such that the first bit in the
/// `BitVec` becomes the high-order bit of the first byte. If the
/// size of the `BitVec` is not a multiple of eight then trailing bits
/// will be filled-in with `false`.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(3, true);
/// bv.set(1, false);
///
/// assert_eq!(bv.to_bytes(), [0b10100000]);
///
/// let mut bv = BitVec::from_elem(9, false);
/// bv.set(2, true);
/// bv.set(8, true);
///
/// assert_eq!(bv.to_bytes(), [0b00100000, 0b10000000]);
/// ```
pub fn to_bytes(&self) -> Vec<u8> {
fn bit(bit_vec: &BitVec, byte: usize, bit: usize) -> u8 {
let offset = byte * 8 + bit;
if offset >= bit_vec.nbits {
0
} else {
(bit_vec[offset] as u8) << (7 - bit)
}
}
let len = self.nbits/8 +
if self.nbits % 8 == 0 { 0 } else { 1 };
(0..len).map(|i|
bit(self, i, 0) |
bit(self, i, 1) |
bit(self, i, 2) |
bit(self, i, 3) |
bit(self, i, 4) |
bit(self, i, 5) |
bit(self, i, 6) |
bit(self, i, 7)
).collect()
}
/// Compares a `BitVec` to a slice of `bool`s.
/// Both the `BitVec` and slice must have the same length.
///
/// # Panics
///
/// Panics if the `BitVec` and slice are of different length.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b10100000]);
///
/// assert!(bv.eq_vec(&[true, false, true, false,
/// false, false, false, false]));
/// ```
pub fn eq_vec(&self, v: &[bool]) -> bool {
assert_eq!(self.nbits, v.len());
iter::order::eq(self.iter(), v.iter().cloned())
}
/// Shortens a `BitVec`, dropping excess elements.
///
/// If `len` is greater than the vector's current length, this has no
/// effect.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_bytes(&[0b01001011]);
/// bv.truncate(2);
/// assert!(bv.eq_vec(&[false, true]));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn truncate(&mut self, len: usize) {
if len < self.len() {
self.nbits = len;
// This fixes (2).
self.storage.truncate(blocks_for_bits(len));
self.fix_last_block();
}
}
/// Reserves capacity for at least `additional` more bits to be inserted in the given
/// `BitVec`. The collection may reserve more space to avoid frequent reallocations.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(3, false);
/// bv.reserve(10);
/// assert_eq!(bv.len(), 3);
/// assert!(bv.capacity() >= 13);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve(&mut self, additional: usize) {
let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
let storage_len = self.storage.len();
if desired_cap > self.capacity() {
self.storage.reserve(blocks_for_bits(desired_cap) - storage_len);
}
}
/// Reserves the minimum capacity for exactly `additional` more bits to be inserted in the
/// given `BitVec`. Does nothing if the capacity is already sufficient.
///
/// Note that the allocator may give the collection more space than it requests. Therefore
/// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
/// insertions are expected.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(3, false);
/// bv.reserve(10);
/// assert_eq!(bv.len(), 3);
/// assert!(bv.capacity() >= 13);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve_exact(&mut self, additional: usize) {
let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
let storage_len = self.storage.len();
if desired_cap > self.capacity() {
self.storage.reserve_exact(blocks_for_bits(desired_cap) - storage_len);
}
}
/// Returns the capacity in bits for this bit vector. Inserting any
/// element less than this amount will not trigger a resizing.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::new();
/// bv.reserve(10);
/// assert!(bv.capacity() >= 10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn capacity(&self) -> usize {
self.storage.capacity().checked_mul(u32::BITS).unwrap_or(usize::MAX)
}
/// Grows the `BitVec` in-place, adding `n` copies of `value` to the `BitVec`.
///
/// # Panics
///
/// Panics if the new len overflows a `usize`.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_bytes(&[0b01001011]);
/// bv.grow(2, true);
/// assert_eq!(bv.len(), 10);
/// assert_eq!(bv.to_bytes(), [0b01001011, 0b11000000]);
/// ```
pub fn grow(&mut self, n: usize, value: bool) {
// Note: we just bulk set all the bits in the last word in this fn in multiple places
// which is technically wrong if not all of these bits are to be used. However, at the end
// of this fn we call `fix_last_block` at the end of this fn, which should fix this.
let new_nbits = self.nbits.checked_add(n).expect("capacity overflow");
let new_nblocks = blocks_for_bits(new_nbits);
let full_value = if value { !0 } else { 0 };
// Correct the old tail word, setting or clearing formerly unused bits
let num_cur_blocks = blocks_for_bits(self.nbits);
if self.nbits % u32::BITS > 0 {
let mask = mask_for_bits(self.nbits);
if value {
self.storage[num_cur_blocks - 1] |= !mask;
} else {
// Extra bits are already zero by invariant.
}
}
// Fill in words after the old tail word
let stop_idx = cmp::min(self.storage.len(), new_nblocks);
for idx in num_cur_blocks..stop_idx {
self.storage[idx] = full_value;
}
// Allocate new words, if needed
if new_nblocks > self.storage.len() {
let to_add = new_nblocks - self.storage.len();
self.storage.extend(repeat(full_value).take(to_add));
}
// Adjust internal bit count
self.nbits = new_nbits;
self.fix_last_block();
}
/// Removes the last bit from the BitVec, and returns it. Returns None if the BitVec is empty.
///
/// # Examples
///
/// ```
/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_bytes(&[0b01001001]);
/// assert_eq!(bv.pop(), Some(true));
/// assert_eq!(bv.pop(), Some(false));
/// assert_eq!(bv.len(), 6);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> Option<bool> {
if self.is_empty() {
None
} else {
let i = self.nbits - 1;
let ret = self[i];
// (3)
self.set(i, false);
self.nbits = i;
if self.nbits % u32::BITS == 0 {
// (2)
self.storage.pop();
}
Some(ret)