#bit-fields #bitfields #field #offset #field-value #macro #size

no-std simple_bitfield

使用简单的宏创建与整数具有相同内存结构的位域

8个版本

0.1.8 2020年10月5日
0.1.7 2020年10月3日

#1389数据结构

每月 22 次下载

GPL-3.0 许可证

28KB
330

Crates.io

simple_bitfield - Rust的另一个位域实现

轻松创建与底层类型大小相同的C风格位域,且是 Copy + Clone(要求底层类型也必须 Copy + Clone

use simple_bitfield::{bitfield, Field};

bitfield! {
    // Bitfield with underlying type `u32`
    struct MyBitfield<u32> {
        field1: 3, // First field (least significant) of size 3 bits
        field2: 9,
        _: 6,      // Fields named `_` are skipped (offsets are preserved)
        field3: 1  // Last bit (closest to the highest bit of `u32`)
    }

    // Multiple bitfields can be defined
    // within one macro invocation
    struct AnotherBitfield<u8> {
         _: 7,
        highest_bit: 1
    }
}

 fn main() {
    // Create bitfield object
    let mut a_bitfield = MyBitfield::new(12345);

    // Get the field's value (of underlying type)
    let field3: u32 = a_bitfield.field3.get();

    println!(
        "{:#b} => {:#b}, {:#b}, {:#b}",
        u32::from(a_bitfield), // Convert bitfield to underlying type
        field3,
        a_bitfield.field2.get(),
        a_bitfield.field1.get()
    );

    // Update just that field
    a_bitfield.field1.set(0);

    println!("{:#b}", u32::from(a_bitfield));

    // The type can be inferred, of course
    let another_one: AnotherBitfield::AnotherBitfield = AnotherBitfield::new(184);

    // Fields cannot be moved!
    // let another_one_highest = another_one.highest_bit;

    // Each field has its own type
    let another_one_highest: &AnotherBitfield::highest_bit = &another_one.highest_bit;
    println!("{:#b}", another_one_highest.get())
}

语法

类似于C语言

(pub) struct BitfieldName<BaseType> {
    field_name: field_size,
    _: size_to_skip
}

文档

在docs.rs上: https://docs.rs/simple_bitfield

致谢

最初的想法来自 https://guiand.xyz/blog-posts/bitfields.html

依赖关系

~42KB