Crates.io | splitbits |
lib.rs | splitbits |
version | 0.1.2 |
source | src |
created_at | 2024-10-19 19:26:42.162581 |
updated_at | 2024-10-21 17:37:46.953196 |
description | Concise bit field extraction |
homepage | |
repository | https://github.com/merehap/splitbits.git |
max_upload_size | |
id | 1415650 |
size | 1,124,160 |
Concise macros for extracting bits from integers and combining bits into integers. No scary syntax. Minimal magic.
use splitbits::splitbits;
// Parse the template ("aaabbbbb"), apply it to the input,
// then generate a struct populated with the bit field values.
let fields = splitbits!(0b11110000, "aaabbbbb");
// Single-letter field names,
// generated from the unique letters in the template above.
assert_eq!(fields.a, 0b111);
assert_eq!(fields.b, 0b10000);
Splitbits replaces tedious, error-prone bit operations with a simple template format, making it easy to extract bits into variables.
Every operation than can be executed at compile time is. Generated code should be as efficient as hand-written bit operations.
Splitbits is intended for cases where bitfield is too heavy-weight syntactically: when you don't want to explicitly declare a new struct for data that you won't use as a return value or argument.
For additional examples, see each macro's page.
use splitbits::combinebits;
let b: u8 = 0b1010_1010;
let m: u8 = 0b1111;
let e: u8 = 0b0000;
let result = combinebits!("bbbb bbbb mmmm eeee");
assert_eq!(result, 0b1010_1010_1111_0000);
use splitbits::splitbits_then_combine;
let output = splitbits_then_combine!(
0b1111_0000, "aaaa ..bb", // input 0, input template 0,
0b1011_1111, "cc.. ....", // input 1, input template 1
"aaaa bbcc", // output template
);
assert_eq!(output, 0b1111_0010);
use splitbits::replacebits;
let a: u16 = 0b101;
let b: u8 = 0b01;
// Placeholder periods in the template are the bits that will not be replaced.
let result = replacebits!(0b10000001, "aaa..bb.");
assert_eq!(result, 0b10100011);
The four base macros cover all the basic functionality that this crate offers and should be sufficient for most use-cases. However, in many situations better ergonomics can be achieved by using these more specialized macro variants.
All four base macros have equivalents that use hexadecimal digits for their templates rather than bits (binary digits). The variants are splithex!, combinehex!, splithex_then_combine!, and replacehex!.
splitbits! itself has many variants which are intended for better ergonomics for the generated variables. The basic variants are:
let
binding.into()
is called on each tuple field
before it reaches the caller. This is useful for when the default type (the smallest integer
type that will fit the field) is a smaller type than the caller would like to use, or if the
caller has a newtype that they would like to use instead.Find thorough documentation of this crate and its many macro variants here, including detailed template syntax, settings, and per-macro documentation and examples.