#matching #bitpacking #binary #decoder #macro #integer #bindings

macro no-std bitmatch

A macro to allow matching, binding, and packing the individual bits of integers

2 releases

0.1.1 Mar 21, 2020
0.1.0 Jan 20, 2020

#1594 in Rust patterns

Download history 720/week @ 2023-12-14 623/week @ 2023-12-21 818/week @ 2023-12-28 757/week @ 2024-01-04 868/week @ 2024-01-11 1015/week @ 2024-01-18 922/week @ 2024-01-25 855/week @ 2024-02-01 928/week @ 2024-02-08 955/week @ 2024-02-15 1048/week @ 2024-02-22 818/week @ 2024-02-29 869/week @ 2024-03-07 679/week @ 2024-03-14 858/week @ 2024-03-21 685/week @ 2024-03-28

3,278 downloads per month
Used in 11 crates (3 directly)

MPL-2.0 license

24KB
428 lines

Bitmatch

Crates.io Library Version Number Crates.io Library License Docs.rs Documentation Version Number

The bitmatch crate provides tools for packing and unpacking integers as sequences of bits. Supports #![no_std].

Examples

Using #[bitmatch] with a let unpacks the bits into separate single-character variables for each letter you use.

Using bitpack!() re-packs the bits from those single-character variables into a single integer.

use bitmatch::bitmatch;

#[bitmatch]
fn interleave(n: u8) -> u8 {
    #[bitmatch]
    let "xxxx_yyyy" = n;
    bitpack!("xyxy_xyxy")
}

fn main() {
    assert_eq!(interleave(0xF0), 0xAA);
}

You can use #[bitmatch] on a match as well, and it will ensure that the literal portions match, and bind the variable portions.

use bitmatch::bitmatch;
#[bitmatch]
fn decode(inst: u8) -> String {
    #[bitmatch]
    match inst {
        "00oo_aabb" => format!("Op {}, {}, {}", o, a, b),
        "0100_aaii" => format!("Val {}, {}", a, i),
        "01??_????" => format!("Invalid"),
        "10ii_aabb" => format!("Ld {}, {}, {}", a, b, i),
        "11ii_aabb" => format!("St {}, {}, {}", a, b, i),
    }
}

Dependencies

~2MB
~45K SLoC