bit_array/
lib.rs

1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Copyright 2016 The bit-array developers.
6//
7//
8// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
9// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
10// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
11// option. This file may not be copied, modified, or distributed
12// except according to those terms.
13
14// FIXME(Gankro): BitVec and BitSet are very tightly coupled. Ideally (for
15// maintenance), they should be in separate files/modules, with BitSet only
16// using BitVec's public API. This will be hard for performance though, because
17// `BitVec` will not want to leak its internal representation while its internal
18// representation as `u32`s must be assumed for best performance.
19
20// FIXME(tbu-): `BitVec`'s methods shouldn't be `union`, `intersection`, but
21// rather `or` and `and`.
22
23// (1) Be careful, most things can overflow here because the amount of bits in
24//     memory can overflow `usize`.
25// (2) Make sure that the underlying array has no excess length:
26//     E. g. `nbits == 16`, `storage.len() == 2` would be excess length,
27//     because the last word isn't used at all. This is important because some
28//     methods rely on it (for *CORRECTNESS*).
29// (3) Make sure that the unused bits in the last word are zeroed out, again
30//     other methods rely on it for *CORRECTNESS*.
31// (4) `BitSet` is tightly coupled with `BitVec`, so any changes you make in
32// `BitVec` will need to be reflected in `BitSet`.
33
34//! Collections implemented with bit arrays.
35//!
36//! # Examples
37//!
38//! This is a simple example of the [Sieve of Eratosthenes][sieve]
39//! which calculates prime numbers up to a given limit.
40//!
41//! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
42//!
43//! ```
44//! extern crate typenum;
45//! # extern crate bit_array;
46//! use bit_array::BitArray;
47//! use typenum::{Unsigned, U10000};
48//!
49//! # fn main() {
50//!
51//! // Store the primes as a BitArray
52//! let primes = {
53//!     // Assume all numbers are prime to begin, and then we
54//!     // cross off non-primes progressively
55//!     let mut bv = BitArray::<u32, U10000>::from_elem(true);
56//!
57//!     // Neither 0 nor 1 are prime
58//!     bv.set(0, false);
59//!     bv.set(1, false);
60//!
61//!     for i in 2.. 1 + (U10000::to_usize() as f64).sqrt() as usize {
62//!         // if i is a prime
63//!         if bv[i] {
64//!             // Mark all multiples of i as non-prime (any multiples below i * i
65//!             // will have been marked as non-prime previously)
66//!             for j in i.. {
67//!                 if i * j >= U10000::to_usize() {
68//!                     break;
69//!                 }
70//!                 bv.set(i * j, false)
71//!             }
72//!         }
73//!     }
74//!     bv
75//! };
76//!
77//! // Simple primality tests below our max bound
78//! let print_primes = 20;
79//! print!("The primes below {} are: ", print_primes);
80//! for x in 0..print_primes {
81//!     if primes.get(x).unwrap_or(false) {
82//!         print!("{} ", x);
83//!     }
84//! }
85//! println!("");
86//!
87//! let num_primes = primes.iter().filter(|x| *x).count();
88//! println!("There are {} primes below {}", num_primes, U10000::to_usize());
89//! assert_eq!(num_primes, 1_229);
90//! # }
91//! ```
92
93#![cfg_attr(all(test, feature = "nightly"), feature(test))]
94#[cfg(all(test, feature = "nightly"))] extern crate test;
95#[cfg(all(test, feature = "nightly"))] extern crate rand;
96
97extern crate generic_array;
98extern crate typenum;
99extern crate bit_vec;
100
101use std::cmp::Ordering;
102use std::cmp;
103use std::fmt;
104use std::hash;
105use std::iter::{Chain, Enumerate, Repeat, Skip, Take};
106use std::iter::FromIterator;
107use std::slice;
108use std::{u8, usize};
109use bit_vec::BitBlock;
110use generic_array::GenericArray;
111use typenum::{Unsigned, Sum, Sub1, NonZero, U8, U16, U32, U64, Quot};
112
113type MutBlocks<'a, B> = slice::IterMut<'a, B>;
114type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
115
116use std::ops::*;
117
118/// Traits for determing how many bits a primitive contains
119pub trait BitsIn {
120    type Output;
121}
122
123pub type BitsInOut<A> = <A as BitsIn>::Output;
124
125macro_rules! bitsin_prim {
126    ($(($prim: ty, $bits: ty)),*) => ($(
127        impl BitsIn for $prim { type Output = $bits; }
128    )*)
129}
130
131bitsin_prim!(
132    (u8, U8),
133    (u16, U16),
134    (u32, U32),
135    (u64, U64)
136);
137
138#[cfg(target_pointer_width = "32")]
139bitsin_prim!((usize, U32));
140
141#[cfg(target_pointer_width = "64")]
142bitsin_prim!((usize, U64));
143
144fn reverse_bits(byte: u8) -> u8 {
145    let mut result = 0;
146    for i in 0..u8::bits() {
147        result = result | ((byte >> i) & 1) << (u8::bits() - 1 - i);
148    }
149    result
150}
151
152static TRUE: bool = true;
153static FALSE: bool = false;
154
155/// The bitarray type.
156///
157/// # Examples
158///
159/// ```
160/// extern crate typenum;
161/// # extern crate bit_array;
162/// use bit_array::BitArray;
163/// use typenum::U10;
164///
165/// # fn main() {
166/// let mut bv = BitArray::<u32, U10>::from_elem(false);
167///
168/// // insert all primes less than 10
169/// bv.set(2, true);
170/// bv.set(3, true);
171/// bv.set(5, true);
172/// bv.set(7, true);
173/// println!("{:?}", bv);
174/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
175///
176/// // flip all values in bitarray, producing non-primes less than 10
177/// bv.negate();
178/// println!("{:?}", bv);
179/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
180///
181/// // reset bitarray to empty
182/// bv.clear();
183/// println!("{:?}", bv);
184/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
185/// # }
186/// ```
187pub struct BitArray<B: BitsIn, NBits: Unsigned + NonZero>
188    where NBits: Add<<B as BitsIn>::Output>,
189    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
190    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
191    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
192{
193    storage: GenericArray<B, 
194        // based on the calculation `(nbits + U32_BITS - 1) / 32::BITS` in bit-vec
195        Quot<
196            Sub1<Sum<NBits, BitsInOut<B>>>
197            ,BitsInOut<B>
198            >
199        >,
200}
201
202// FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
203impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> Index<usize> for BitArray<B, NBits>
204    where NBits: Add<<B as BitsIn>::Output>,
205    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
206    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
207    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
208{
209    type Output = bool;
210
211    #[inline]
212    fn index(&self, i: usize) -> &bool {
213        if self.get(i).expect("index out of bounds") {
214            &TRUE
215        } else {
216            &FALSE
217        }
218    }
219}
220
221/// Computes the bitmask for the final word of the array
222fn mask_for_bits<B: BitBlock>(bits: usize) -> B {
223    // Note especially that a perfect multiple of U32_BITS should mask all 1s.
224    (!B::zero()) >> ((B::bits() - bits % B::bits()) % B::bits())
225}
226
227impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> BitArray<B, NBits>
228    where NBits: Add<<B as BitsIn>::Output>,
229    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
230    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
231    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
232{
233
234    /// Creates an empty `BitArray`.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// extern crate typenum;
240    /// # extern crate bit_array;
241    /// use bit_array::BitArray;
242    /// use typenum::U8;
243    ///
244    /// # fn main() {
245    /// let mut bv = BitArray::<u32, U8>::new();
246    /// # }
247    /// ```
248    pub fn new() -> Self {
249        Default::default()
250    }
251
252    /// Creates a `BitArray`, setting each element
253    /// to `bit`.
254    ///
255    /// # Examples
256    ///
257    /// ```
258    /// extern crate typenum;
259    /// # extern crate bit_array;
260    /// use bit_array::BitArray;
261    /// use typenum::U10;
262    ///
263    /// # fn main() {
264    /// let mut bv = BitArray::<u32, U10>::from_elem(false);
265    /// assert_eq!(bv.len(), 10);
266    /// for x in bv.iter() {
267    ///     assert_eq!(x, false);
268    /// }
269    /// # }
270    /// ```
271    pub fn from_elem(bit: bool) -> Self {
272        let mut bit_array = BitArray::new();
273        if bit {
274            bit_array.set_all();
275        }
276        bit_array.fix_last_block();
277        bit_array
278    }
279
280    /// Transforms a byte-array into a `BitArray`. Each byte becomes eight bits,
281    /// with the most significant bits of each byte coming first. Each
282    /// bit becomes `true` if equal to 1 or `false` if equal to 0.
283    ///
284    /// # Examples
285    ///
286    /// ```
287    /// extern crate typenum;
288    /// # extern crate bit_array;
289    /// use bit_array::BitArray;
290    /// use typenum::U8;
291    ///
292    /// # fn main() {
293    /// let bv = BitArray::<u32, U8>::from_bytes(&[0b10100000, 0b00010010]);
294    /// assert!(bv.eq_vec(&[true, false, true, false,
295    ///                     false, false, false, false,
296    ///                     false, false, false, true,
297    ///                     false, false, true, false]));
298    /// # }
299    /// ```
300    pub fn from_bytes(bytes: &[u8]) -> Self {
301        let total_bits = bytes.len().checked_mul(u8::bits()).expect("capacity overflow");
302        let mut bit_array = BitArray::new();
303        let total_array_bits = bit_array.storage.len() * B::bits();
304        assert!(total_bits <= total_array_bits, "bit_array with {:?} bits cannot handle byte array of {:?} bits", total_array_bits, total_bits);
305        let complete_words = bytes.len() / B::bytes();
306        let extra_bytes = bytes.len() % B::bytes();
307
308        for i in 0..complete_words {
309            let mut accumulator = B::zero();
310            for idx in 0..B::bytes() {
311                accumulator = accumulator |
312                    (B::from_byte(reverse_bits(bytes[i * B::bytes() + idx])) << (idx * 8))
313            }
314            *bit_array.storage.get_mut(i).unwrap() = accumulator;
315        }
316
317        if extra_bytes > 0 {
318            let mut last_word = B::zero();
319            for (i, &byte) in bytes[complete_words * B::bytes()..].iter().enumerate() {
320                last_word = last_word |
321                    (B::from_byte(reverse_bits(byte)) << (i * 8));
322            }
323            *bit_array.storage.last_mut().unwrap() = last_word;
324        }
325
326        bit_array
327    }
328
329    /// Creates a `BitArray` of the specified length where the value at each index
330    /// is `f(index)`.
331    ///
332    /// # Examples
333    ///
334    /// ```
335    /// extern crate typenum;
336    /// # extern crate bit_array;
337    /// use bit_array::BitArray;
338    /// use typenum::U5;
339    ///
340    /// # fn main() {
341    /// let bv = BitArray::<u32, U5>::from_fn(|i| { i % 2 == 0 });
342    /// assert!(bv.eq_vec(&[true, false, true, false, true]));
343    /// # }
344    /// ```
345    pub fn from_fn<F>(mut f: F) -> Self
346        where F: FnMut(usize) -> bool
347    {
348        let mut bit_array = BitArray::from_elem(false);
349        for i in 0..NBits::to_usize() {
350            bit_array.set(i, f(i));
351        }
352        bit_array
353    }
354
355    /// Applies the given operation to the blocks of self and other, and sets
356    /// self to be the result. This relies on the caller not to corrupt the
357    /// last word.
358    #[inline]
359    fn process<F>(&mut self, other: &BitArray<B, NBits>, mut op: F) -> bool
360    		where F: FnMut(B, B) -> B {
361        // This could theoretically be a `debug_assert!`.
362        assert_eq!(self.storage.len(), other.storage.len());
363        let mut changed_bits = B::zero();
364        for (a, b) in self.blocks_mut().zip(other.blocks()) {
365            let w = op(*a, b);
366            changed_bits = changed_bits | (*a ^ w);
367            *a = w;
368        }
369        changed_bits != B::zero()
370    }
371    
372    /// Iterator over mutable refs to  the underlying blocks of data.
373    fn blocks_mut(&mut self) -> MutBlocks<B> {
374        // (2)
375        self.storage.iter_mut()
376    }
377
378    /// Iterator over the underlying blocks of data
379    pub fn blocks(&self) -> Blocks<B> {
380        // (2)
381        Blocks{iter: self.storage.iter()}
382    }
383
384    /// Exposes the raw block storage of this BitArray
385    ///
386    /// Only really intended for BitSet.
387    pub fn storage(&self) -> &[B] {
388    	&self.storage
389    }
390
391    /// Exposes the raw block storage of this BitArray
392    ///
393    /// Can probably cause unsafety. Only really intended for BitSet.
394    pub unsafe fn storage_mut(&mut self) -> &mut[B] {
395    	&mut self.storage
396    }
397
398    /// An operation might screw up the unused bits in the last block of the
399    /// `BitArray`. As per (3), it's assumed to be all 0s. This method fixes it up.
400    fn fix_last_block(&mut self) {
401        let extra_bits = self.len() % B::bits();
402        if extra_bits > 0 {
403            let mask = (B::one() << extra_bits) - B::one();
404            let storage_len = self.storage.len();
405            let block = &mut self.storage[storage_len - 1];
406            *block = *block & mask;
407        }
408    }
409
410    /// Retrieves the value at index `i`, or `None` if the index is out of bounds.
411    ///
412    /// # Examples
413    ///
414    /// ```
415    /// extern crate typenum;
416    /// # extern crate bit_array;
417    /// use bit_array::BitArray;
418    /// use typenum::U8;
419    ///
420    /// # fn main() {
421    /// let bv = BitArray::<u32, U8>::from_bytes(&[0b01100000]);
422    /// assert_eq!(bv.get(0), Some(false));
423    /// assert_eq!(bv.get(1), Some(true));
424    /// assert_eq!(bv.get(100), None);
425    ///
426    /// // Can also use array indexing
427    /// assert_eq!(bv[1], true);
428    /// # }
429    /// ```
430    #[inline]
431    pub fn get(&self, i: usize) -> Option<bool> {
432        if i >= NBits::to_usize() {
433            return None;
434        }
435        let w = i / B::bits();
436        let b = i % B::bits();
437        self.storage.get(w).map(|&block|
438            (block & (B::one() << b)) != B::zero()
439        )
440    }
441
442    /// Sets the value of a bit at an index `i`.
443    ///
444    /// # Panics
445    ///
446    /// Panics if `i` is out of bounds.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// extern crate typenum;
452    /// # extern crate bit_array;
453    /// use bit_array::BitArray;
454    /// use typenum::U8;
455    ///
456    /// # fn main() {
457    /// let mut bv = BitArray::<u32, U8>::from_elem(false);
458    /// bv.set(3, true);
459    /// assert_eq!(bv[3], true);
460    /// # }
461    /// ```
462    #[inline]
463    pub fn set(&mut self, i: usize, x: bool) {
464        assert!(i < NBits::to_usize(), "index out of bounds: {:?} >= {:?}", i, NBits::to_usize());
465        let w = i / B::bits();
466        let b = i % B::bits();
467        let flag = B::one() << b;
468        let val = if x { self.storage[w] | flag }
469                  else { self.storage[w] & !flag };
470        self.storage[w] = val;
471    }
472
473    /// Sets all bits to 1.
474    ///
475    /// # Examples
476    ///
477    /// ```
478    /// extern crate typenum;
479    /// # extern crate bit_array;
480    /// use bit_array::BitArray;
481    /// use typenum::U8;
482    ///
483    /// # fn main() {
484    /// let before = 0b01100000;
485    /// let after  = 0b11111111;
486    ///
487    /// let mut bv = BitArray::<u32, U8>::from_bytes(&[before]);
488    /// bv.set_all();
489    /// assert_eq!(bv, BitArray::<u32, U8>::from_bytes(&[after]));
490    /// # }
491    /// ```
492    #[inline]
493    pub fn set_all(&mut self) {
494        for w in self.storage.deref_mut() { *w = !B::zero(); }
495        self.fix_last_block();
496    }
497
498    /// Flips all bits.
499    ///
500    /// # Examples
501    ///
502    /// ```
503    /// extern crate typenum;
504    /// # extern crate bit_array;
505    /// use bit_array::BitArray;
506    /// use typenum::U8;
507    ///
508    /// # fn main() {
509    /// let before = 0b01100000;
510    /// let after  = 0b10011111;
511    ///
512    /// let mut bv = BitArray::<u32, U8>::from_bytes(&[before]);
513    /// bv.negate();
514    /// assert_eq!(bv, BitArray::<u32, U8>::from_bytes(&[after]));
515    /// # }
516    /// ```
517    #[inline]
518    pub fn negate(&mut self) {
519        for w in self.storage.deref_mut() { *w = !*w; }
520        self.fix_last_block();
521    }
522
523    /// Calculates the union of two bitarrays. This acts like the bitwise `or`
524    /// function.
525    ///
526    /// Sets `self` to the union of `self` and `other`. Both bitarrays must be
527    /// the same length. Returns `true` if `self` changed.
528    ///
529    /// # Panics
530    ///
531    /// Panics if the bitarrays are of different lengths.
532    ///
533    /// # Examples
534    ///
535    /// ```
536    /// extern crate typenum;
537    /// # extern crate bit_array;
538    /// use bit_array::BitArray;
539    /// use typenum::U8;
540    ///
541    /// # fn main() {
542    /// let a   = 0b01100100;
543    /// let b   = 0b01011010;
544    /// let res = 0b01111110;
545    ///
546    /// let mut a = BitArray::<u32, U8>::from_bytes(&[a]);
547    /// let b = BitArray::<u32, U8>::from_bytes(&[b]);
548    ///
549    /// assert!(a.union(&b));
550    /// assert_eq!(a, BitArray::<u32, U8>::from_bytes(&[res]));
551    /// # }
552    /// ```
553    #[inline]
554    pub fn union(&mut self, other: &Self) -> bool {
555        self.process(other, |w1, w2| (w1 | w2))
556    }
557
558    /// Calculates the intersection of two bitarrays. This acts like the
559    /// bitwise `and` function.
560    ///
561    /// Sets `self` to the intersection of `self` and `other`. Both bitarrays
562    /// must be the same length. Returns `true` if `self` changed.
563    ///
564    /// # Panics
565    ///
566    /// Panics if the bitarrays are of different lengths.
567    ///
568    /// # Examples
569    ///
570    /// ```
571    /// extern crate typenum;
572    /// # extern crate bit_array;
573    /// use bit_array::BitArray;
574    /// use typenum::U8;
575    ///
576    /// # fn main() {
577    /// let a   = 0b01100100;
578    /// let b   = 0b01011010;
579    /// let res = 0b01000000;
580    ///
581    /// let mut a = BitArray::<u32, U8>::from_bytes(&[a]);
582    /// let b = BitArray::<u32, U8>::from_bytes(&[b]);
583    ///
584    /// assert!(a.intersect(&b));
585    /// assert_eq!(a, BitArray::<u32, U8>::from_bytes(&[res]));
586    /// # }
587    /// ```
588    #[inline]
589    pub fn intersect(&mut self, other: &Self) -> bool {
590        self.process(other, |w1, w2| (w1 & w2))
591    }
592
593    /// Calculates the difference between two bitarrays.
594    ///
595    /// Sets each element of `self` to the value of that element minus the
596    /// element of `other` at the same index. Both bitarrays must be the same
597    /// length. Returns `true` if `self` changed.
598    ///
599    /// # Panics
600    ///
601    /// Panics if the bitarrays are of different length.
602    ///
603    /// # Examples
604    ///
605    /// ```
606    /// extern crate typenum;
607    /// # extern crate bit_array;
608    /// use bit_array::BitArray;
609    /// use typenum::U8;
610    ///
611    /// # fn main() {
612    /// let a   = 0b01100100;
613    /// let b   = 0b01011010;
614    /// let a_b = 0b00100100; // a - b
615    /// let b_a = 0b00011010; // b - a
616    ///
617    /// let mut bva = BitArray::<u32, U8>::from_bytes(&[a]);
618    /// let bvb = BitArray::<u32, U8>::from_bytes(&[b]);
619    ///
620    /// assert!(bva.difference(&bvb));
621    /// assert_eq!(bva, BitArray::<u32, U8>::from_bytes(&[a_b]));
622    ///
623    /// let bva = BitArray::<u32, U8>::from_bytes(&[a]);
624    /// let mut bvb = BitArray::<u32, U8>::from_bytes(&[b]);
625    ///
626    /// assert!(bvb.difference(&bva));
627    /// assert_eq!(bvb, BitArray::<u32, U8>::from_bytes(&[b_a]));
628    /// # }
629    /// ```
630    #[inline]
631    pub fn difference(&mut self, other: &Self) -> bool {
632        self.process(other, |w1, w2| (w1 & !w2))
633    }
634
635    /// Returns `true` if all bits are 1.
636    ///
637    /// # Examples
638    ///
639    /// ```
640    /// extern crate typenum;
641    /// # extern crate bit_array;
642    /// use bit_array::BitArray;
643    /// use typenum::U8;
644    ///
645    /// # fn main() {
646    /// let mut bv = BitArray::<u32, U8>::from_elem(true);
647    /// assert_eq!(bv.all(), true);
648    ///
649    /// bv.set(1, false);
650    /// assert_eq!(bv.all(), false);
651    /// # }
652    /// ```
653    pub fn all(&self) -> bool {
654        let mut last_word = !B::zero();
655        // Check that every block but the last is all-ones...
656        self.blocks().all(|elem| {
657            let tmp = last_word;
658            last_word = elem;
659            tmp == !B::zero()
660        // and then check the last one has enough ones
661        }) && (last_word == mask_for_bits(NBits::to_usize()))
662    }
663
664    /// Returns an iterator over the elements of the array in order.
665    ///
666    /// # Examples
667    ///
668    /// ```
669    /// extern crate typenum;
670    /// # extern crate bit_array;
671    /// use bit_array::BitArray;
672    /// use typenum::U16;
673    ///
674    /// # fn main() {
675    /// let bv = BitArray::<u32, U16>::from_bytes(&[0b01110100, 0b10010010]);
676    /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
677    /// # }
678    /// ```
679    #[inline]
680    pub fn iter(&self) -> Iter<B, NBits> {
681        Iter { bit_array: self, range: 0..NBits::to_usize() }
682    }
683
684
685    /// Returns `true` if all bits are 0.
686    ///
687    /// # Examples
688    ///
689    /// ```
690    /// extern crate typenum;
691    /// # extern crate bit_array;
692    /// use bit_array::BitArray;
693    /// use typenum::U8;
694    ///
695    /// # fn main() {
696    /// let mut bv = BitArray::<u32, U8>::from_elem(false);
697    /// assert_eq!(bv.none(), true);
698    ///
699    /// bv.set(3, true);
700    /// assert_eq!(bv.none(), false);
701    /// # }
702    /// ```
703    pub fn none(&self) -> bool {
704        self.blocks().all(|w| w == B::zero())
705    }
706
707    /// Returns `true` if any bit is 1.
708    ///
709    /// # Examples
710    ///
711    /// ```
712    /// extern crate typenum;
713    /// # extern crate bit_array;
714    /// use bit_array::BitArray;
715    /// use typenum::U8;
716    ///
717    /// # fn main() {
718    /// let mut bv = BitArray::<u32, U8>::from_elem(false);
719    /// assert_eq!(bv.any(), false);
720    ///
721    /// bv.set(3, true);
722    /// assert_eq!(bv.any(), true);
723    /// # }
724    /// ```
725    #[inline]
726    pub fn any(&self) -> bool {
727        !self.none()
728    }
729
730    /// Organises the bits into bytes, such that the first bit in the
731    /// `BitArray` becomes the high-order bit of the first byte. If the
732    /// size of the `BitArray` is not a multiple of eight then trailing bits
733    /// will be filled-in with `false`.
734    ///
735    /// # Examples
736    ///
737    /// ```
738    /// extern crate typenum;
739    /// # extern crate bit_array;
740    /// use bit_array::BitArray;
741    /// use typenum::{U3, U9};
742    ///
743    /// # fn main() {
744    /// let mut bv = BitArray::<u32, U3>::from_elem(true);
745    /// bv.set(1, false);
746    ///
747    /// assert_eq!(bv.to_bytes(), [0b10100000]);
748    ///
749    /// let mut bv = BitArray::<u32, U9>::from_elem(false);
750    /// bv.set(2, true);
751    /// bv.set(8, true);
752    ///
753    /// assert_eq!(bv.to_bytes(), [0b00100000, 0b10000000]);
754    /// # }
755    /// ```
756    pub fn to_bytes(&self) -> Vec<u8> {
757    	// Oh lord, we're mapping this to bytes bit-by-bit!
758        fn bit<B: BitBlock + BitsIn + Default, NBits: Unsigned + NonZero>(bit_array: &BitArray<B, NBits>, byte: usize, bit: usize) -> u8 
759            where NBits: Add<<B as BitsIn>::Output>,
760            <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
761            <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
762            <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
763        {
764            let offset = byte * 8 + bit;
765            if offset >= NBits::to_usize() {
766                0
767            } else {
768                (bit_array.get(offset).unwrap() as u8) << (7 - bit)
769            }
770        }
771
772        let len = NBits::to_usize() / 8 +
773                  if NBits::to_usize() % 8 == 0 { 0 } else { 1 };
774        (0..len).map(|i|
775            bit(self, i, 0) |
776            bit(self, i, 1) |
777            bit(self, i, 2) |
778            bit(self, i, 3) |
779            bit(self, i, 4) |
780            bit(self, i, 5) |
781            bit(self, i, 6) |
782            bit(self, i, 7)
783        ).collect()
784    }
785
786
787    /// Compares a `BitArray` to a slice of `bool`s.
788    /// Both the `BitArray` and slice must have the same length.
789    ///
790    /// # Panics
791    ///
792    /// Panics if the `BitArray` and slice are of different length.
793    ///
794    /// # Examples
795    ///
796    /// ```
797    /// extern crate typenum;
798    /// # extern crate bit_array;
799    /// use bit_array::BitArray;
800    /// use typenum::U8;
801    ///
802    /// # fn main() {
803    /// let bv = BitArray::<u32, U8>::from_bytes(&[0b10100000]);
804    ///
805    /// assert!(bv.eq_vec(&[true, false, true, false,
806    ///                     false, false, false, false]));
807    /// # }
808    /// ```
809    pub fn eq_vec(&self, v: &[bool]) -> bool {
810        self.iter().zip(v.iter().cloned()).all(|(b1, b2)| b1 == b2)
811    }
812
813    /// Returns the total number of bits in this array
814    #[inline]
815    pub fn len(&self) -> usize { NBits::to_usize() }
816
817    /// Clears all bits in this array.
818    #[inline]
819    pub fn clear(&mut self) {
820        for w in self.storage.deref_mut() { *w = B::zero(); }
821    }
822}
823
824impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> Default for BitArray<B, NBits>
825    where NBits: Add<<B as BitsIn>::Output>,
826    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
827    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
828    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
829{
830    fn default() -> Self { BitArray { storage: GenericArray::new() } }
831}
832
833impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> FromIterator<bool> for BitArray<B, NBits>
834    where NBits: Add<<B as BitsIn>::Output>,
835    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
836    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
837    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
838{
839    fn from_iter<I: IntoIterator<Item=bool>>(iter: I) -> Self {
840        let mut ret: Self = Default::default();
841        for (i, val) in iter.into_iter().enumerate() {
842            ret.set(i, val);
843        }
844        ret
845    }
846}
847
848impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> Clone for BitArray<B, NBits>
849    where NBits: Add<<B as BitsIn>::Output>,
850    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
851    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
852    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
853{
854    #[inline]
855    fn clone(&self) -> Self {
856        BitArray { storage: self.storage.clone()}
857    }
858
859    #[inline]
860    fn clone_from(&mut self, source: &Self) {
861        self.storage.clone_from(&source.storage);
862    }
863}
864
865impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> PartialOrd for BitArray<B, NBits>
866    where NBits: Add<<B as BitsIn>::Output>,
867    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
868    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
869    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
870{
871    #[inline]
872    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
873        Some(self.cmp(other))
874    }
875}
876
877impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> Ord for BitArray<B, NBits>
878    where NBits: Add<<B as BitsIn>::Output>,
879    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
880    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
881    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
882{
883    #[inline]
884    fn cmp(&self, other: &Self) -> Ordering {
885        let mut a = self.iter();
886        let mut b = other.iter();
887        loop {
888            match (a.next(), b.next()) {
889                (Some(x), Some(y)) => match x.cmp(&y) {
890                    Ordering::Equal => {}
891                    otherwise => return otherwise,
892                },
893                (None, None) => return Ordering::Equal,
894                (None, _) => return Ordering::Less,
895                (_, None) => return Ordering::Greater,
896            }
897        }
898    }
899}
900
901impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> fmt::Debug for BitArray<B, NBits> 
902    where NBits: Add<<B as BitsIn>::Output>,
903    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
904    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
905    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
906{
907    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
908        for bit in self {
909            try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
910        }
911        Ok(())
912    }
913}
914
915impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> hash::Hash for BitArray<B, NBits> 
916    where NBits: Add<<B as BitsIn>::Output>,
917    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
918    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
919    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
920{
921    fn hash<H: hash::Hasher>(&self, state: &mut H) {
922        for elem in self.blocks() {
923            elem.hash(state);
924        }
925    }
926}
927
928impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> cmp::PartialEq for BitArray<B, NBits>
929    where NBits: Add<<B as BitsIn>::Output>,
930    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
931    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
932    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
933{
934    #[inline]
935    fn eq(&self, other: &Self) -> bool {
936        self.blocks().zip(other.blocks()).all(|(w1, w2)| w1 == w2)
937    }
938}
939
940impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> cmp::Eq for BitArray<B, NBits>
941    where NBits: Add<<B as BitsIn>::Output>,
942    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
943    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
944    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
945{}
946
947
948/// An iterator for `BitArray`.
949#[derive(Clone)]
950pub struct Iter<'a, B: 'a + BitsIn + BitBlock + Default, NBits:'a + Unsigned + NonZero> 
951    where NBits: Add<<B as BitsIn>::Output>,
952    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
953    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
954    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
955{
956    bit_array: &'a BitArray<B, NBits>,
957    range: Range<usize>,
958}
959
960impl<'a, B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> Iterator for Iter<'a, B, NBits> 
961    where NBits: Add<<B as BitsIn>::Output>,
962    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
963    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
964    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
965{
966    type Item = bool;
967
968    #[inline]
969    fn next(&mut self) -> Option<bool> {
970        // NB: indexing is slow for extern crates when it has to go through &TRUE or &FALSE
971        // variables.  get is more direct, and unwrap is fine since we're sure of the range.
972        self.range.next().map(|i| self.bit_array.get(i).unwrap())
973    }
974
975    fn size_hint(&self) -> (usize, Option<usize>) {
976        self.range.size_hint()
977    }
978}
979
980impl<'a, B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> DoubleEndedIterator for Iter<'a, B, NBits> 
981    where NBits: Add<<B as BitsIn>::Output>,
982    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
983    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
984    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
985{
986    #[inline]
987    fn next_back(&mut self) -> Option<bool> {
988        self.range.next_back().map(|i| self.bit_array.get(i).unwrap())
989    }
990}
991
992impl<'a, B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> ExactSizeIterator for Iter<'a, B, NBits> 
993    where NBits: Add<<B as BitsIn>::Output>,
994    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
995    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
996    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
997{}
998
999
1000impl<'a, B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> IntoIterator for &'a BitArray<B, NBits> 
1001    where NBits: Add<<B as BitsIn>::Output>,
1002    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
1003    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
1004    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
1005{
1006    type Item = bool;
1007    type IntoIter = Iter<'a, B, NBits>;
1008
1009    fn into_iter(self) -> Iter<'a, B, NBits> {
1010        self.iter()
1011    }
1012}
1013
1014pub struct IntoIter<B: BitsIn, NBits: Unsigned + NonZero>
1015    where NBits: Add<<B as BitsIn>::Output>,
1016    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
1017    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
1018    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
1019{
1020    bit_array: BitArray<B, NBits>,
1021    range: Range<usize>,
1022}
1023
1024impl<B: BitBlock + BitsIn + Default, NBits: Unsigned + NonZero> Iterator for IntoIter<B, NBits> 
1025    where NBits: Add<<B as BitsIn>::Output>,
1026    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
1027    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
1028    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
1029{
1030    type Item = bool;
1031
1032    #[inline]
1033    fn next(&mut self) -> Option<bool> {
1034        self.range.next().map(|i| self.bit_array.get(i).unwrap())
1035    }
1036}
1037
1038impl<B: BitBlock + BitsIn + Default, NBits: Unsigned + NonZero> DoubleEndedIterator for IntoIter<B, NBits> 
1039    where NBits: Add<<B as BitsIn>::Output>,
1040    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
1041    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
1042    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
1043{
1044    #[inline]
1045    fn next_back(&mut self) -> Option<bool> {
1046        self.range.next_back().map(|i| self.bit_array.get(i).unwrap())
1047    }
1048}
1049
1050impl<B: BitBlock + BitsIn + Default, NBits: Unsigned + NonZero> ExactSizeIterator for IntoIter<B, NBits> 
1051    where NBits: Add<<B as BitsIn>::Output>,
1052    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
1053    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
1054    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
1055{}
1056
1057impl<B: BitsIn + BitBlock + Default, NBits: Unsigned + NonZero> IntoIterator for BitArray<B, NBits> 
1058    where NBits: Add<<B as BitsIn>::Output>,
1059    <NBits as Add<<B as BitsIn>::Output>>::Output: Sub<typenum::B1>,
1060    <<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output: Div<<B as BitsIn>::Output>,
1061    <<<NBits as Add<<B as BitsIn>::Output>>::Output as Sub<typenum::B1>>::Output as Div<<B as BitsIn>::Output>>::Output: generic_array::ArrayLength<B>
1062{
1063    type Item = bool;
1064    type IntoIter = IntoIter<B, NBits>;
1065
1066    fn into_iter(self) -> IntoIter<B, NBits> {
1067        IntoIter { bit_array: self, range: 0..NBits::to_usize() }
1068    }
1069}
1070
1071/// An iterator over the blocks of a `BitArray`.
1072#[derive(Clone)]
1073pub struct Blocks<'a, B: 'a> {
1074    iter: slice::Iter<'a, B>,
1075}
1076
1077impl<'a, B: BitBlock> Iterator for Blocks<'a, B> {
1078    type Item = B;
1079
1080    #[inline]
1081    fn next(&mut self) -> Option<B> {
1082        self.iter.next().cloned()
1083    }
1084
1085    fn size_hint(&self) -> (usize, Option<usize>) {
1086        self.iter.size_hint()
1087    }
1088}
1089
1090impl<'a, B: BitBlock> DoubleEndedIterator for Blocks<'a, B> {
1091    #[inline]
1092    fn next_back(&mut self) -> Option<B> {
1093        self.iter.next_back().cloned()
1094    }
1095}
1096
1097impl<'a, B: BitBlock> ExactSizeIterator for Blocks<'a, B> {}
1098
1099
1100
1101#[cfg(test)]
1102mod tests {
1103    use super::{BitArray, Iter};
1104    use typenum::*;
1105
1106    #[test]
1107    fn test_to_str() {
1108        let eightbits = BitArray::<u32, U8>::from_elem(false);
1109        assert_eq!(format!("{:?}", eightbits), "00000000")
1110    }
1111
1112    #[test]
1113    fn test_1_element() {
1114        let mut act = BitArray::<u32, U1>::from_elem(false);
1115        assert!(act.eq_vec(&[false]));
1116        assert!(act.none() && !act.all());
1117        act = BitArray::<u32, U1>::from_elem(true);
1118        assert!(act.eq_vec(&[true]));
1119        assert!(!act.none() && act.all());
1120    }
1121
1122    #[test]
1123    fn test_2_elements() {
1124        let mut b = BitArray::<u32, U2>::from_elem(false);
1125        b.set(0, true);
1126        b.set(1, false);
1127        assert_eq!(format!("{:?}", b), "10");
1128        assert!(!b.none() && !b.all());
1129    }
1130
1131    #[test]
1132    fn test_10_elements() {
1133        let mut act;
1134        // all 0
1135
1136        act = BitArray::<u32, U10>::from_elem(false);
1137        assert!((act.eq_vec(
1138                    &[false, false, false, false, false, false, false, false, false, false])));
1139        assert!(act.none() && !act.all());
1140        // all 1
1141
1142        act = BitArray::<u32, U10>::from_elem(true);
1143        assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
1144        assert!(!act.none() && act.all());
1145        // mixed
1146
1147        act = BitArray::<u32, U10>::from_elem(false);
1148        act.set(0, true);
1149        act.set(1, true);
1150        act.set(2, true);
1151        act.set(3, true);
1152        act.set(4, true);
1153        assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false])));
1154        assert!(!act.none() && !act.all());
1155        // mixed
1156
1157        act = BitArray::<u32, U10>::from_elem(false);
1158        act.set(5, true);
1159        act.set(6, true);
1160        act.set(7, true);
1161        act.set(8, true);
1162        act.set(9, true);
1163        assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
1164        assert!(!act.none() && !act.all());
1165        // mixed
1166
1167        act = BitArray::<u32, U10>::from_elem(false);
1168        act.set(0, true);
1169        act.set(3, true);
1170        act.set(6, true);
1171        act.set(9, true);
1172        assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
1173        assert!(!act.none() && !act.all());
1174    }
1175
1176    #[test]
1177    fn test_31_elements() {
1178        let mut act;
1179        // all 0
1180
1181        act = BitArray::<u32, U31>::from_elem(false);
1182        assert!(act.eq_vec(
1183                &[false, false, false, false, false, false, false, false, false, false, false,
1184                  false, false, false, false, false, false, false, false, false, false, false,
1185                  false, false, false, false, false, false, false, false, false]));
1186        assert!(act.none() && !act.all());
1187        // all 1
1188
1189        act = BitArray::<u32, U31>::from_elem(true);
1190        assert!(act.eq_vec(
1191                &[true, true, true, true, true, true, true, true, true, true, true, true, true,
1192                  true, true, true, true, true, true, true, true, true, true, true, true, true,
1193                  true, true, true, true, true]));
1194        assert!(!act.none() && act.all());
1195        // mixed
1196
1197        act = BitArray::<u32, U31>::from_elem(false);
1198        act.set(0, true);
1199        act.set(1, true);
1200        act.set(2, true);
1201        act.set(3, true);
1202        act.set(4, true);
1203        act.set(5, true);
1204        act.set(6, true);
1205        act.set(7, true);
1206        assert!(act.eq_vec(
1207                &[true, true, true, true, true, true, true, true, false, false, false, false, false,
1208                  false, false, false, false, false, false, false, false, false, false, false,
1209                  false, false, false, false, false, false, false]));
1210        assert!(!act.none() && !act.all());
1211        // mixed
1212
1213        act = BitArray::<u32, U31>::from_elem(false);
1214        act.set(16, true);
1215        act.set(17, true);
1216        act.set(18, true);
1217        act.set(19, true);
1218        act.set(20, true);
1219        act.set(21, true);
1220        act.set(22, true);
1221        act.set(23, true);
1222        assert!(act.eq_vec(
1223                &[false, false, false, false, false, false, false, false, false, false, false,
1224                  false, false, false, false, false, true, true, true, true, true, true, true, true,
1225                  false, false, false, false, false, false, false]));
1226        assert!(!act.none() && !act.all());
1227        // mixed
1228
1229        act = BitArray::<u32, U31>::from_elem(false);
1230        act.set(24, true);
1231        act.set(25, true);
1232        act.set(26, true);
1233        act.set(27, true);
1234        act.set(28, true);
1235        act.set(29, true);
1236        act.set(30, true);
1237        assert!(act.eq_vec(
1238                &[false, false, false, false, false, false, false, false, false, false, false,
1239                  false, false, false, false, false, false, false, false, false, false, false,
1240                  false, false, true, true, true, true, true, true, true]));
1241        assert!(!act.none() && !act.all());
1242        // mixed
1243
1244        act = BitArray::<u32, U31>::from_elem(false);
1245        act.set(3, true);
1246        act.set(17, true);
1247        act.set(30, true);
1248        assert!(act.eq_vec(
1249                &[false, false, false, true, false, false, false, false, false, false, false, false,
1250                  false, false, false, false, false, true, false, false, false, false, false, false,
1251                  false, false, false, false, false, false, true]));
1252        assert!(!act.none() && !act.all());
1253    }
1254
1255    #[test]
1256    fn test_32_elements() {
1257        let mut act;
1258        // all 0
1259
1260        act = BitArray::<u32, U32>::from_elem(false);
1261        assert!(act.eq_vec(
1262                &[false, false, false, false, false, false, false, false, false, false, false,
1263                  false, false, false, false, false, false, false, false, false, false, false,
1264                  false, false, false, false, false, false, false, false, false, false]));
1265        assert!(act.none() && !act.all());
1266        // all 1
1267
1268        act = BitArray::<u32, U32>::from_elem(true);
1269        assert!(act.eq_vec(
1270                &[true, true, true, true, true, true, true, true, true, true, true, true, true,
1271                  true, true, true, true, true, true, true, true, true, true, true, true, true,
1272                  true, true, true, true, true, true]));
1273        assert!(!act.none() && act.all());
1274        // mixed
1275
1276        act = BitArray::<u32, U32>::from_elem(false);
1277        act.set(0, true);
1278        act.set(1, true);
1279        act.set(2, true);
1280        act.set(3, true);
1281        act.set(4, true);
1282        act.set(5, true);
1283        act.set(6, true);
1284        act.set(7, true);
1285        assert!(act.eq_vec(
1286                &[true, true, true, true, true, true, true, true, false, false, false, false, false,
1287                  false, false, false, false, false, false, false, false, false, false, false,
1288                  false, false, false, false, false, false, false, false]));
1289        assert!(!act.none() && !act.all());
1290        // mixed
1291
1292        act = BitArray::<u32, U32>::from_elem(false);
1293        act.set(16, true);
1294        act.set(17, true);
1295        act.set(18, true);
1296        act.set(19, true);
1297        act.set(20, true);
1298        act.set(21, true);
1299        act.set(22, true);
1300        act.set(23, true);
1301        assert!(act.eq_vec(
1302                &[false, false, false, false, false, false, false, false, false, false, false,
1303                  false, false, false, false, false, true, true, true, true, true, true, true, true,
1304                  false, false, false, false, false, false, false, false]));
1305        assert!(!act.none() && !act.all());
1306        // mixed
1307
1308        act = BitArray::<u32, U32>::from_elem(false);
1309        act.set(24, true);
1310        act.set(25, true);
1311        act.set(26, true);
1312        act.set(27, true);
1313        act.set(28, true);
1314        act.set(29, true);
1315        act.set(30, true);
1316        act.set(31, true);
1317        assert!(act.eq_vec(
1318                &[false, false, false, false, false, false, false, false, false, false, false,
1319                  false, false, false, false, false, false, false, false, false, false, false,
1320                  false, false, true, true, true, true, true, true, true, true]));
1321        assert!(!act.none() && !act.all());
1322        // mixed
1323
1324        act = BitArray::<u32, U32>::from_elem(false);
1325        act.set(3, true);
1326        act.set(17, true);
1327        act.set(30, true);
1328        act.set(31, true);
1329        assert!(act.eq_vec(
1330                &[false, false, false, true, false, false, false, false, false, false, false, false,
1331                  false, false, false, false, false, true, false, false, false, false, false, false,
1332                  false, false, false, false, false, false, true, true]));
1333        assert!(!act.none() && !act.all());
1334    }
1335
1336    #[test]
1337    fn test_33_elements() {
1338        let mut act;
1339        // all 0
1340
1341        act = BitArray::<u32, U33>::from_elem(false);
1342        assert!(act.eq_vec(
1343                &[false, false, false, false, false, false, false, false, false, false, false,
1344                  false, false, false, false, false, false, false, false, false, false, false,
1345                  false, false, false, false, false, false, false, false, false, false, false]));
1346        assert!(act.none() && !act.all());
1347        // all 1
1348
1349        act = BitArray::<u32, U33>::from_elem(true);
1350        assert!(act.eq_vec(
1351                &[true, true, true, true, true, true, true, true, true, true, true, true, true,
1352                  true, true, true, true, true, true, true, true, true, true, true, true, true,
1353                  true, true, true, true, true, true, true]));
1354        assert!(!act.none() && act.all());
1355        // mixed
1356
1357        act = BitArray::<u32, U33>::from_elem(false);
1358        act.set(0, true);
1359        act.set(1, true);
1360        act.set(2, true);
1361        act.set(3, true);
1362        act.set(4, true);
1363        act.set(5, true);
1364        act.set(6, true);
1365        act.set(7, true);
1366        assert!(act.eq_vec(
1367                &[true, true, true, true, true, true, true, true, false, false, false, false, false,
1368                  false, false, false, false, false, false, false, false, false, false, false,
1369                  false, false, false, false, false, false, false, false, false]));
1370        assert!(!act.none() && !act.all());
1371        // mixed
1372
1373        act = BitArray::<u32, U33>::from_elem(false);
1374        act.set(16, true);
1375        act.set(17, true);
1376        act.set(18, true);
1377        act.set(19, true);
1378        act.set(20, true);
1379        act.set(21, true);
1380        act.set(22, true);
1381        act.set(23, true);
1382        assert!(act.eq_vec(
1383                &[false, false, false, false, false, false, false, false, false, false, false,
1384                  false, false, false, false, false, true, true, true, true, true, true, true, true,
1385                  false, false, false, false, false, false, false, false, false]));
1386        assert!(!act.none() && !act.all());
1387        // mixed
1388
1389        act = BitArray::<u32, U33>::from_elem(false);
1390        act.set(24, true);
1391        act.set(25, true);
1392        act.set(26, true);
1393        act.set(27, true);
1394        act.set(28, true);
1395        act.set(29, true);
1396        act.set(30, true);
1397        act.set(31, true);
1398        assert!(act.eq_vec(
1399                &[false, false, false, false, false, false, false, false, false, false, false,
1400                  false, false, false, false, false, false, false, false, false, false, false,
1401                  false, false, true, true, true, true, true, true, true, true, false]));
1402        assert!(!act.none() && !act.all());
1403        // mixed
1404
1405        act = BitArray::<u32, U33>::from_elem(false);
1406        act.set(3, true);
1407        act.set(17, true);
1408        act.set(30, true);
1409        act.set(31, true);
1410        act.set(32, true);
1411        assert!(act.eq_vec(
1412                &[false, false, false, true, false, false, false, false, false, false, false, false,
1413                  false, false, false, false, false, true, false, false, false, false, false, false,
1414                  false, false, false, false, false, false, true, true, true]));
1415        assert!(!act.none() && !act.all());
1416    }
1417
1418    #[test]
1419    fn test_equal_sneaky_small() {
1420        let mut a = BitArray::<u32, U1>::from_elem(false);
1421        a.set(0, true);
1422
1423        let mut b = BitArray::<u32, U1>::from_elem(true);
1424        b.set(0, true);
1425
1426        assert_eq!(a, b);
1427    }
1428
1429    #[test]
1430    fn test_equal_sneaky_big() {
1431        let mut a = BitArray::<u32, U100>::from_elem(false);
1432        for i in 0..100 {
1433            a.set(i, true);
1434        }
1435
1436        let mut b = BitArray::<u32, U100>::from_elem(true);
1437        for i in 0..100 {
1438            b.set(i, true);
1439        }
1440
1441        assert_eq!(a, b);
1442    }
1443
1444    #[test]
1445    fn test_from_bytes() {
1446        let bit_array = BitArray::<u32, U24>::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
1447        let str = concat!("10110110", "00000000", "11111111");
1448        assert_eq!(format!("{:?}", bit_array), str);
1449    }
1450
1451    #[test]
1452    fn test_to_bytes() {
1453        let mut bv = BitArray::<u32, U3>::from_elem(true);
1454        bv.set(1, false);
1455        assert_eq!(bv.to_bytes(), [0b10100000]);
1456
1457        let mut bv = BitArray::<u32, U9>::from_elem(false);
1458        bv.set(2, true);
1459        bv.set(8, true);
1460        assert_eq!(bv.to_bytes(), [0b00100000, 0b10000000]);
1461    }
1462
1463    #[test]
1464    fn test_from_bools() {
1465        let bools = vec![true, false, true, true];
1466        let bit_array: BitArray<u32, U4> = bools.iter().map(|n| *n).collect();
1467        assert_eq!(format!("{:?}", bit_array), "1011");
1468    }
1469
1470    #[test]
1471    fn test_to_bools() {
1472        let bools = vec![false, false, true, false, false, true, true, false];
1473        assert_eq!(BitArray::<u32, U8>::from_bytes(&[0b00100110]).iter().collect::<Vec<bool>>(), bools);
1474    }
1475
1476
1477    #[test]
1478    fn test_bit_array_iterator() {
1479        let bools = vec![true, false, true, true];
1480        let bit_array: BitArray<u32, U4> = bools.iter().map(|n| *n).collect();
1481
1482        assert_eq!(bit_array.iter().collect::<Vec<bool>>(), bools);
1483
1484        let long: Vec<_> = (0..10000).map(|i| i % 2 == 0).collect();
1485        let bit_array: BitArray<u32, U10000> = long.iter().map(|n| *n).collect();
1486        assert_eq!(bit_array.iter().collect::<Vec<bool>>(), long)
1487    }
1488
1489    #[test]
1490    fn test_small_difference() {
1491        let mut b1 = BitArray::<u32, U3>::from_elem(false);
1492        let mut b2 = BitArray::<u32, U3>::from_elem(false);
1493        b1.set(0, true);
1494        b1.set(1, true);
1495        b2.set(1, true);
1496        b2.set(2, true);
1497        assert!(b1.difference(&b2));
1498        assert!(b1[0]);
1499        assert!(!b1[1]);
1500        assert!(!b1[2]);
1501    }
1502
1503    #[test]
1504    fn test_big_difference() {
1505        let mut b1 = BitArray::<u32, U100>::from_elem(false);
1506        let mut b2 = BitArray::<u32, U100>::from_elem(false);
1507        b1.set(0, true);
1508        b1.set(40, true);
1509        b2.set(40, true);
1510        b2.set(80, true);
1511        assert!(b1.difference(&b2));
1512        assert!(b1[0]);
1513        assert!(!b1[40]);
1514        assert!(!b1[80]);
1515    }
1516
1517    #[test]
1518    fn test_small_clear() {
1519        let mut b = BitArray::<u32, U14>::from_elem(true);
1520        assert!(!b.none() && b.all());
1521        b.clear();
1522        assert!(b.none() && !b.all());
1523    }
1524
1525    #[test]
1526    fn test_big_clear() {
1527        let mut b = BitArray::<u32, U140>::from_elem(true);
1528        assert!(!b.none() && b.all());
1529        b.clear();
1530        assert!(b.none() && !b.all());
1531    }
1532
1533    #[test]
1534    fn test_bit_array_lt() {
1535        let mut a = BitArray::<u32, U5>::from_elem(false);
1536        let mut b = BitArray::<u32, U5>::from_elem(false);
1537
1538        assert!(!(a < b) && !(b < a));
1539        b.set(2, true);
1540        assert!(a < b);
1541        a.set(3, true);
1542        assert!(a < b);
1543        a.set(2, true);
1544        assert!(!(a < b) && b < a);
1545        b.set(0, true);
1546        assert!(a < b);
1547    }
1548
1549    #[test]
1550    fn test_ord() {
1551        let mut a = BitArray::<u32, U5>::from_elem(false);
1552        let mut b = BitArray::<u32, U5>::from_elem(false);
1553
1554        assert!(a <= b && a >= b);
1555        a.set(1, true);
1556        assert!(a > b && a >= b);
1557        assert!(b < a && b <= a);
1558        b.set(1, true);
1559        b.set(2, true);
1560        assert!(b > a && b >= a);
1561        assert!(a < b && a <= b);
1562    }
1563
1564
1565    #[test]
1566    fn test_small_bit_array_tests() {
1567        let v = BitArray::<u32, U8>::from_bytes(&[0]);
1568        assert!(!v.all());
1569        assert!(!v.any());
1570        assert!(v.none());
1571
1572        let v = BitArray::<u32, U8>::from_bytes(&[0b00010100]);
1573        assert!(!v.all());
1574        assert!(v.any());
1575        assert!(!v.none());
1576
1577        let v = BitArray::<u32, U8>::from_bytes(&[0xFF]);
1578        assert!(v.all());
1579        assert!(v.any());
1580        assert!(!v.none());
1581    }
1582
1583    #[test]
1584    fn test_big_bit_array_tests() {
1585        let v = BitArray::<u32, U88>::from_bytes(&[ // 88 bits
1586            0, 0, 0, 0,
1587            0, 0, 0, 0,
1588            0, 0, 0]);
1589        assert!(!v.all());
1590        assert!(!v.any());
1591        assert!(v.none());
1592
1593        let v = BitArray::<u32, U88>::from_bytes(&[ // 88 bits
1594            0, 0, 0b00010100, 0,
1595            0, 0, 0, 0b00110100,
1596            0, 0, 0]);
1597        assert!(!v.all());
1598        assert!(v.any());
1599        assert!(!v.none());
1600
1601        let v = BitArray::<u32, U88>::from_bytes(&[ // 88 bits
1602            0xFF, 0xFF, 0xFF, 0xFF,
1603            0xFF, 0xFF, 0xFF, 0xFF,
1604            0xFF, 0xFF, 0xFF]);
1605        assert!(v.all());
1606        assert!(v.any());
1607        assert!(!v.none());
1608    }
1609
1610
1611    #[test]
1612    fn test_into_iter() {
1613        let bools = vec![true, false, true, true];
1614        let bit_array: BitArray<u32, U4> = bools.iter().map(|n| *n).collect();
1615        let mut iter = bit_array.into_iter();
1616        assert_eq!(Some(true), iter.next());
1617        assert_eq!(Some(false), iter.next());
1618        assert_eq!(Some(true), iter.next());
1619        assert_eq!(Some(true), iter.next());
1620        assert_eq!(None, iter.next());
1621        assert_eq!(None, iter.next());
1622
1623        let bit_array: BitArray<u32, U4> = bools.iter().map(|n| *n).collect();
1624        let mut iter = bit_array.into_iter();
1625        assert_eq!(Some(true), iter.next_back());
1626        assert_eq!(Some(true), iter.next_back());
1627        assert_eq!(Some(false), iter.next_back());
1628        assert_eq!(Some(true), iter.next_back());
1629        assert_eq!(None, iter.next_back());
1630        assert_eq!(None, iter.next_back());
1631
1632        let bit_array: BitArray<u32, U4> = bools.iter().map(|n| *n).collect();
1633        let mut iter = bit_array.into_iter();
1634        assert_eq!(Some(true), iter.next_back());
1635        assert_eq!(Some(true), iter.next());
1636        assert_eq!(Some(false), iter.next());
1637        assert_eq!(Some(true), iter.next_back());
1638        assert_eq!(None, iter.next());
1639        assert_eq!(None, iter.next_back());
1640    }
1641
1642    #[test]
1643    fn iter() {
1644        let b: BitArray<u32, U10> = BitArray::new();
1645        let _a: Iter<u32, U10> = b.iter();
1646    }
1647    
1648}
1649
1650#[cfg(all(test, feature = "nightly"))] mod bench;