herumi / bit_combi_iter

Tiny Rust crate to iterate bit combinations

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

bit_combi_iter

crates.io CI

bit_combi_iter is a small dependency-free crate to enumerate all bit combinations less than given unsigned integer value keeping the number of bits.

use bit_combi_iter::BitCombinations;

fn main() {
    let u = 0b00010100u8;

    let mut c = BitCombinations::new(u);

    println!("{:#b}", c.next().unwrap()); // => 0b00010010
    println!("{:#b}", c.next().unwrap()); // => 0b00010001
    println!("{:#b}", c.next().unwrap()); // => 0b00001100
    println!("{:#b}", c.next().unwrap()); // => 0b00001010
    println!("{:#b}", c.next().unwrap()); // => 0b00001001
    println!("{:#b}", c.next().unwrap()); // => 0b00000110
    println!("{:#b}", c.next().unwrap()); // => 0b00000101
    println!("{:#b}", c.next().unwrap()); // => 0b00000011
    println!("{}", c.next().is_none()); // => true
}

This crate is useful when you want to enumerate all n bit integers including k ones.

// Enumerate all 5 bit integers including 3 ones (as u8)
BitCombinations::new(0b11100u8)
// 11100
// 11010
// 11001
// 01110
// ...

Install

Add this crate to dependencies in your Cargo.toml.

[dependencies]
bit_combi_iter = "1"

API

BitCombinations<U> (U can be u8, u16, u32, u64, u128)

A struct implementing Iterator<Item=U>. Size of this struct is the same as size of U. No additional allocation is necessary.

BitCombinations::<U>::new(init: U) -> Self

new generates a BitCombinations instance initializing with state init.

BitCombinations::<U>::next(&mut self) -> Option<U>

next method generates a next bit combination of the current state. The generated value is always smaller than the next state.

BitCombinations::<U>::peek(self) -> Option<U>

peek method returns the current state. When the iterator finished iterating all combinations, this method returns None.

Special Thanks

The algorithm was borrowed from the blog post by @herumi.

License

Distributed under the MIT License.

About

Tiny Rust crate to iterate bit combinations

License:MIT License


Languages

Language:Rust 100.0%