A Rust crate to expressively declare bitfield-like structs

Overview

proc-bitfield

A Rust crate to expressively declare bitfield-like structs, automatically ensuring their correctness at compile time and declaring accessors.

Typical usage

bitfield! {
    #[derive(Clone, Copy, PartialEq, Eq)]
    pub struct Example(pub u16): Debug {
        // A single field spanning the entire bitfield, using an unbounded range
        pub raw: u16 @ ..,

        // Single-bit flags
        pub vblank: bool [read_only] @ 0,
        pub hblank: bool [write_only] @ 1,
        pub vcount_match: bool @ 2,

        // Multi-bit field, specified using an inclusive range
        pub irq_mask: u8 @ 3..=5,

        // Bit 6 is ignored

        // Single-bit field, specified using an exclusive range
        pub vcount_compare_high: u8 @ 7..8,

        // 8-bit field specified using its start bit and length
        pub vcount_compare_low: u8 @ 8; 8,
    }
}

Automatic Debug implementation

A fmt::Debug implementation can be implemented automatically for a given bitfield struct by adding : Debug after the tuple struct-like storage type declaration; the generated fmt function will output the type's raw value as well as all of its fields' values.

nightly feature

Optionally, the nightly feature can be enabled to use const Trait functionality: this makes the BitRange and Bit traits be implemented using const fns for all integer types, and enables the option to use const fns for field accessors.

With the feature enabled, const fn accessors can be enabled globally for a struct by replacing struct with const struct (i.e. const struct Example(pub u16)), or on a field-by-field basis by prepending const to its type (i.e. raw: const u16 @ ..).

Field declarations

Fields can be declared by using the form:

Visibility IDENTIFIER : Type ([(Attribute ,)* Attribute])? @ FieldRange

where FieldRange corresponds to any of (where L is an alias for LiteralExpression):

  • .., to use every bit
  • L..=L, to use the bits specified by an inclusive range
  • L..L, to use the bits specified by an exclusive range
  • L; L, to use bits specified by a (start, length) pair
  • L, to use a single bit; unlike all other specifications, this is only valid for bool fields, and will use the Bit trait instead of BitRange

Attributes can be optionally specified in brackets, matching any of the ones defined below.

Access restrictions

Fields are both readable and writable by default, but can be declared read-only or write-only using respectively the read_only and write_only attributes.

Field type conversions

Fields' "raw" types as specified after the colon are restricted by BitRange implementations on the bitfield's contained type; however, accessors can perform conversions specified through optional attributes. These can be:

  • Infallible conversions, using the From and Into traits, the relevant attributes being:
    • get Type, specifying the type that the raw value will be converted into using From<T> for reads
    • set Type, specifying the type that will be converted into the raw value using Into<T> for writes
    • Type, as shorthand for get Type and set Type
  • Fallible conversions, using the TryFrom and TryInto traits, the relevant attributes being:
    • try_get Type, specifying the type that the raw value will be fallibly converted into using TryFrom<T> for reads
    • try_set Type, specifying the type that will be fallibly converted into the raw value into using TryInto<T> for writes
    • try Type, as shorthand for try_get Type and try_set Type
  • Unsafe (for reads) conversions, using the UnsafeFrom and Into traits, the relevant attributes being:
    • unsafe_get Type, specifying the type that the raw value will be unsafely converted into using UnsafeFrom<T> for reads
    • unsafe Type, as shorthand for unsafe_get Type and set Type
You might also like...
Rust crate for parsing stivale and stivale 2 structures.

stivale-rs Rust crate for parsing stivale and stivale 2 structures. Resources Stivale v2 Specification Stivale Specification License Licensed under ei

A simple entity-component-system crate for rust with serialization support

Gallium A simple entity-component-system crate for rust with serialization support Usage You can include the library using carge: [dependencies] galli

Rust crate to generate, manipulate and traverse trees.

SOCAREL Rust crate to generate, manipulate and traverse trees. It provides iterators for eight different traversal algorithms. Add and remove nodes in

A translation of Brendan Galea's Vulkan tutorial into Rust using the ash crate
A translation of Brendan Galea's Vulkan tutorial into Rust using the ash crate

Rust Light Vulkan Engine This is a translation of Brendan Galea's Vulkan tutorial into rust using the Ash crate. Original tutorial: Brendan Galea's Yo

Community SVD file, peripheral access crate in embedde Rust for WinnerMicro W800, W801 & W806 chip

Community SVD file, peripheral access crate in embedde Rust for WinnerMicro W800, W801 & W806 chip

A high-level Rust crate around the Discord API, aimed to be easy and straight-forward to use.
A high-level Rust crate around the Discord API, aimed to be easy and straight-forward to use.

rs-cord A high-level Rust crate around the Discord API, aimed to be easy and straight-forward to use. Documentation • Crates.io • Discord Navigation M

This crate converts Rust compatible regex-syntax to Vim's NFA engine compatible regex.

This crate converts Rust compatible regex-syntax to Vim's NFA engine compatible regex.

An `abilists` parser crate for Rust

An `abilists` parser crate for Rust

Comments
  • `label-break-value` feature used in `0.2.0` was stabilized for `1.65`, current stable version is `1.63`

    `label-break-value` feature used in `0.2.0` was stabilized for `1.65`, current stable version is `1.63`

    Hi!

    Saw your thread on reddit and immediately checked it out, since I'm working on an I²C driver that has a lot of register-level bitfields, and being dissatisfied with the bitfield crate, was just what I needed.

    I started with 0.1.1 which works fine, but when I tried upgrading to 0.2.0, the proc macro failed to compile since it uses a recently stabilized feature, label-break-value. It wouldn't show on cargo check etc. if you're working on a recent nightly.

    error[E0658]: labels on blocks are unstable
       --> /home/ronen/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-bitfield-macros-0.2.0/src/lib.rs:158:21
        |
    158 |                     'parse: {
        |                     ^^^^^^
        |
        = note: see issue #48594 <https://github.com/rust-lang/rust/issues/48594> for more information
    

    While the driver I'm writing will be mostly used on nightly, I want to support stable, so I'll be sticking to 0.1.1 for now, until 1.65 is out on November 3rd.

    Just an FYI!

    opened by zRedShift 6
Owner
Emulators, Rust, and Rust emulators, also free hugs in the spare time
null
A tool that, like, screams at you when you say like

Dislike Do you, like,... dislike constantly saying "like" as much as I do? Then, like,... you've come the right place! This tool is like EXACTLY what

ElKowar 27 Jun 27, 2022
📦 Crate Protocol allows anyone to create, manage, and trade a tokenized basket of assets, which we refer to as a Crate.

?? Crate Protocol Crate Protocol allows anyone to create, manage, and trade a tokenized basket of assets, which we refer to as a Crate. A Crate is alw

Crate Protocol 63 Oct 31, 2022
A cog-like tool, written in Rust.

Corg A cog-like tool, written in Rust. The primary difference between Cog and Corg is how Corg executes code blocks. Being written in Rust, it cannot

null 1 Jan 19, 2022
Quinine is a Rust library that implements atomic, lock-free, but write-once versions of containers like `Box` or `Arc`

Quinine is a Rust library that implements atomic, lock-free, but write-once versions of containers like `Box` or `Arc`

Paul Khuong 4 Feb 19, 2022
Rust macro to use a match-like syntax as a elegant alternative to nesting if-else statement

cond Rust macro to use a match-like syntax as an elegant alternative to many if-else statements. I got the idea from empty Go switch statements. I tho

CheckM4te 3 Nov 23, 2023
Devops kafka topics like files with kls, ktail, khead and kecho

Devops kafka topics like files with kls, ktail, khead and kecho

imotai 4 Dec 31, 2021
simple, C-like programming language

CUP: C(ompiler) U(nder) P(rogress) A badly named, in-progress programming language just to learn how these things work. Wait, doesn't everyone write a

Mustafa Quraish 287 Dec 28, 2022
Compiler from a lisp-like language to mlog

slimlog slimlog compiles a lisp-like language to mlog Architecture slimlog is divided into three distinct parts Parser Parses the source file Compiler

The Potato Chronicler 6 May 7, 2022
A budget PLC-like board for controlling 24V DC equipment.

Poppy Logic Controller The Poppy Logic Controller is a budget PLC (Programmable Logic Controller). Importantly, it is only an I/O board without any PL

Rahix 6 Jan 4, 2023
xdotool-like for KDE Wayland

kdotool - a xdotool clone for KDE Wayland Introduction Wayland, for security concerns, removed most of the X11 APIs that xdotool uses to simulate user

Jin Liu 25 Dec 3, 2023