2 releases

Uses old Rust 2015

0.4.4 Apr 4, 2017
0.4.3 Jul 17, 2016

#19 in #bitmask

Download history 149/week @ 2023-12-04 186/week @ 2023-12-11 175/week @ 2023-12-18 102/week @ 2023-12-25 116/week @ 2024-01-01 110/week @ 2024-01-08 104/week @ 2024-01-15 126/week @ 2024-01-22 75/week @ 2024-01-29 109/week @ 2024-02-05 91/week @ 2024-02-12 140/week @ 2024-02-19 120/week @ 2024-02-26 148/week @ 2024-03-04 109/week @ 2024-03-11 133/week @ 2024-03-18

535 downloads per month
Used in 10 crates (6 directly)

MIT/Apache

62KB
1K SLoC

A compile time sized array of bits.

Documentation is available at https://ambaxter.github.io/bit_array/bit_array


lib.rs:

Collections implemented with bit arrays.

Examples

This is a simple example of the Sieve of Eratosthenes which calculates prime numbers up to a given limit.

extern crate typenum;
use bit_array::BitArray;
use typenum::{Unsigned, U10000};


// Store the primes as a BitArray
let primes = {
    // Assume all numbers are prime to begin, and then we
    // cross off non-primes progressively
    let mut bv = BitArray::<u32, U10000>::from_elem(true);

    // Neither 0 nor 1 are prime
    bv.set(0, false);
    bv.set(1, false);

    for i in 2.. 1 + (U10000::to_usize() 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.. {
                if i * j >= U10000::to_usize() {
                    break;
                }
                bv.set(i * j, false)
            }
        }
    }
    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.get(x).unwrap_or(false) {
        print!("{} ", x);
    }
}
println!("");

let num_primes = primes.iter().filter(|x| *x).count();
println!("There are {} primes below {}", num_primes, U10000::to_usize());
assert_eq!(num_primes, 1_229);

Dependencies

~340KB