Crates.io | bitmatch |
lib.rs | bitmatch |
version | 0.1.1 |
source | src |
created_at | 2020-01-20 00:15:08.187419 |
updated_at | 2020-03-21 21:31:49.142864 |
description | A macro to allow matching, binding, and packing the individual bits of integers. |
homepage | |
repository | https://github.com/porglezomp/bitmatch |
max_upload_size | |
id | 200302 |
size | 27,681 |
The bitmatch crate provides tools for packing and unpacking integers as
sequences of bits. Supports #![no_std]
.
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),
}
}