#bit-set #bit-array #boolean #fixed #hold #able #integer

no-std cbitset

A bit set, being able to hold a fixed amount of booleans in an array of integers

2 unstable releases

Uses old Rust 2015

0.2.0 May 26, 2019
0.1.0 Sep 22, 2018

#70 in No standard library

Download history 1868/week @ 2023-11-29 1678/week @ 2023-12-06 1884/week @ 2023-12-13 1896/week @ 2023-12-20 1234/week @ 2023-12-27 1352/week @ 2024-01-03 1753/week @ 2024-01-10 1662/week @ 2024-01-17 1848/week @ 2024-01-24 1634/week @ 2024-01-31 1660/week @ 2024-02-07 1843/week @ 2024-02-14 1834/week @ 2024-02-21 2121/week @ 2024-02-28 1870/week @ 2024-03-06 1465/week @ 2024-03-13

7,653 downloads per month
Used in 21 crates (2 directly)

MIT license

19KB
334 lines

cbitset Crates.io

A bit set, being able to hold a fixed amount of booleans in an array of integers.

Alternatives

There are already quite a few libraries out there for bit sets, but I can't seem to find a #![no_std] one that works with fixed-sized arrays. Most of them seem to want to be dynamic.

cbitset also is repr(transparent), meaning the representation of the struct is guaranteed to be the same as the inner array, making it usable from stuff where the struct representation is important, such as relibc.

Inspiration

I think this is a relatively common thing to do in C, for I stumbled upon the concept in the MUSL standard library. An example is its usage in strspn.

While it's a relatively easy concept, the implementation can be pretty unreadable. So maybe it should be abstracted away with some kind of... zero cost abstraction?

Example

Bit sets are extremely cheap. You can store any number from 0 to 255 in an array of 4x 64-bit numbers. Lookup should in theory be O(1). An example usage of this is once again strspn. Here it is in rust, using this library:

/// The C standard library function strspn, reimplemented in rust. It works by
/// placing all allowed values in a bit set, and returning on the first
/// character not on the list. A BitSet256 uses no heap allocations and only 4
/// 64-bit integers in stack memory.
fn strspn(s: &[u8], accept: &[u8]) -> usize {
    let mut allow = BitSet256::new();

    for &c in accept {
        allow.insert(c as usize);
    }

    for (i, &c) in s.iter().enumerate() {
        if !allow.contains(c as usize) {
            return i;
        }
    }
    s.len()
}

Dependencies

~155KB