Module drone_core::bitfield[][src]

A Bitfield is an integer value treated as a sequence of bits, which can be toggled individually.

A type with named bit-fields can be defined with the attribute macro:

use drone_core::bitfield::Bitfield;

#[derive(Clone, Copy, Bitfield)]
#[bitfield(
    // The syntax of the field definitions is the following:
    //     field_name(mode, offset[, width[, doc_string]])
    // `width` is default to 1 when omitted.
    // `mode` is one of `r` (for read-only), `rw` (for read-write),
    //                  `w` (for write-only).
    foo(rw, 1, 4, "4-bits field"),
    bar(rw, 5, 1, "1-bit field"),
)]
// The choice of the underlying integer determines the total number of bits.
// Available sizes: `u8`, `u16`, `u32`, `u64`, `u128`.
struct MyValue(u8);

//                          * foo bit
let mut value = MyValue(0b0011_1010);
//                           * *** bar bits

// The size of the value is exactly the size of the underlying integer.
assert_eq!(core::mem::size_of_val(&value), 1);

// For one-bit fields, the macro defines the following methods:
//     value.bar() for reading the bit (except `w` mode)
//     value.set_bar() for setting the bit (except `r` mode)
//     value.clear_bar() for clearing the bit (except `r` mode)
//     value.toggle_bar() for toggling the bit (except `r` mode)
assert!(value.bar());
value.clear_bar();
assert!(!value.bar());
value.set_bar();
assert!(value.bar());
value.toggle_bar();
assert!(!value.bar());

// For multiple-bit fields, the macro defines the following methods:
//     value.foo() for reading the bits (except `w` mode)
//     value.write_foo(bits) for writing the bits (except `r` mode)
assert_eq!(value.foo(), 0b1101);
value.write_foo(0b1010);
assert_eq!(value.foo(), 0b1010);

assert_eq!(value.0, 0b0001_0100);

Traits

Bitfield

An integer value treated as a sequence of bits, which can be toggled individually.

Bits

An integer interface for Bitfield.

Derive Macros

Bitfield

Defines a new Bitfield.