Bit fields and masks for rust!

Related tags

Command-line ubits
Overview

ubits

crates.io Downloads Build Docs Licence

Bit fields and masks for rust!

Provides a macro for generating bit field types complete with flags and some helpful trait implementations.

Supports field widths of 8, 16, 32, 64 and 128 bits.

  • [bitfield] - macro documentation.
  • [examples] - examples of the output generated by the [bitfield] macro.

Note: the example module is only complied with documentation builds and is not available for importing in the wild.

Usage

Generate a bitfield struct with a flag enum... (The following examples all use this as a definition.)

use ubits::bitfield;

    bitfield! {
        pub u8 ExampleField
        ExampleFlags {
            0 : Flag0
            1 : Flag1
            2 : Flag2
            3 : Flag3
            4 : Flag4
            5 : Flag5
            6 : Flag6
            7 : Flag7
        }
    }

Instances

From integer:

let from_integer = ExampleField(123);
assert_eq!(ExampleField(123), from_integer);

From a binary string:

let from_binary = ExampleField::from_binary_str("01111011");
assert_eq!(ExampleField(123), from_binary)

From ones:

let from_ones = ExampleField::ones();
assert_eq!("11111111", from_ones.as_binary());
assert_eq!(255, from_ones.as_integer());

From zeros:

let from_zeros = ExampleField::zeros();
assert_eq!("00000000", from_zeros.as_binary());
assert_eq!(0, from_zeros.as_integer());

Field Access

Get bit value by field:

let field = ExampleField::from_binary_str("01010101");
assert!(field.get(ExampleFlags::Flag0));
assert!(!field.get(ExampleFlags::Flag1));

Get bit value by index:

let field = ExampleField::from_binary_str("01010101");
assert!(field.get_index(0));
assert!(!field.get_index(1));

Set bit value by field:

let mut field = ExampleField::from_binary_str("01010101");
field.set(ExampleFlags::Flag1);
field.set(ExampleFlags::Flag3);
assert_eq!("01011111", field.as_binary());

Set bit value by index:

let mut field = ExampleField::from_binary_str("01010101");
field.set_index(1);
field.set_index(3);
assert_eq!("01011111", field.as_binary());

Clear bit value by field:

let mut field = ExampleField::from_binary_str("01010101");
field.clear(ExampleFlags::Flag0);
field.clear(ExampleFlags::Flag2);
assert_eq!("01010000", field.as_binary());

Clear bit value by index:

let mut field = ExampleField::from_binary_str("01010101");
field.clear_index(0);
field.clear_index(2);
assert_eq!("01010000", field.as_binary());

Toggle bit value by field:

let mut field = ExampleField::from_binary_str("01010101");
field.toggle(ExampleFlags::Flag0);
assert_eq!("01010100", field.as_binary());
field.toggle(ExampleFlags::Flag0);
assert_eq!("01010101", field.as_binary());

Toggle bit value by index:

let mut field = ExampleField::from_binary_str("01010101");
field.toggle_index(0);
assert_eq!("01010100", field.as_binary());
field.toggle_index(0);
assert_eq!("01010101", field.as_binary());

Combinations

Combine bit fields:
(use into_combined to consume self)

let mut a = ExampleField::from_binary_str("01010101");
let b = ExampleField::from_binary_str("10101010");
assert_eq!("11111111", a.combine(b).as_binary());

Get the intersection of two bitfields:
(use into_intersection to consume self)

let mut a = ExampleField::from_binary_str("11000011");
let b = ExampleField::from_binary_str("01111110");
assert_eq!("01000010", a.intersect(b).as_binary());

Get the diff of two bitfields:
(use into_diff to consume self)

let mut a = ExampleField::from_binary_str("11000011");
let b = ExampleField::from_binary_str("01100110");
assert_eq!("10100101", a.diff(b).as_binary());

Bitwise

Both bit field instances and flags use bitwise operators to change bit values.

let mut from_zeros = ExampleField::zeros();
assert_eq!("00000000", from_zeros.as_binary());

// set bit to 1
from_zeros |= ExampleFlags::Flag1;
assert_eq!("00000010", from_zeros.as_binary());

// set bit back to 0
from_zeros &= ExampleFlags::Flag1;
assert_eq!("00000000", from_zeros.as_binary());

// toggle a bit
from_zeros ^= ExampleFlags::Flag1;
assert_eq!("00000010", from_zeros.as_binary());

from_zeros ^= ExampleFlags::Flag1;
assert_eq!("00000000", from_zeros.as_binary());

Operations can also be chained together:

let mut from_zeros = ExampleField::zeros() | ExampleFlags::Flag1 | ExampleFlags::Flag3;
assert_eq!("00001010", from_zeros.as_binary());

Bitfield instances can also be created from combining flags:

let mut from_zeros = ExampleFlags::Flag1 | ExampleFlags::Flag3;
assert_eq!("00001010", from_zeros.as_binary());

Fields named with flags

The generated flags enum allows you to access bits by name. The flag has an associated [u8] value, which determines the index its target bit. (See [bitfield] for more info)

With the following input...

1 0 1 0 0 1 1 0

and the following flags...

0 : f1
1 : f1
2 : f2
3 : f3
4 : f4
5 : f5
6 : f6
7 : f7

we end up with this layout.

name f7 f6 f5 f4 f3 f2 f1 f0
bit value 1 0 1 0 0 1 1 0
index 7 6 5 4 3 2 1 0

With the same input and only the first few flags:

0 : f0
1 : f1
2 : f2

we end up with this layout.

name f2 f1 f0
bit value 1 0 1 0 0 1 1 0
index 7 6 5 4 3 2 1 0

Using the same input, but with dispersed flags:

1 : f0
3 : f1
6 : f2

we end up with this layout.

name f2 f1 f0
bit value 1 0 1 0 0 1 1 0
index 7 6 5 4 3 2 1 0
Comments
  • Manual approval required for workflow run 2226409555

    Manual approval required for workflow run 2226409555

    Workflow is pending manual review. URL: https://github.com/manoadamro/ubits/actions/runs/2226409555

    Required approvers: [manoadamro]

    Respond "approved", "approve", "lgtm", "yes" to continue workflow or "denied", "deny", "no" to cancel.

    opened by github-actions[bot] 2
  • Manual approval required for workflow run 2265540925

    Manual approval required for workflow run 2265540925

    Workflow is pending manual review. URL: https://github.com/manoadamro/ubits/actions/runs/2265540925

    Required approvers: [manoadamro]

    Respond "approved", "approve", "lgtm", "yes" to continue workflow or "denied", "deny", "no" to cancel.

    opened by github-actions[bot] 0
  • Manual approval required for workflow run 2265540925

    Manual approval required for workflow run 2265540925

    Workflow is pending manual review. URL: https://github.com/manoadamro/ubits/actions/runs/2265540925

    Required approvers: [manoadamro]

    Respond "approved", "approve", "lgtm", "yes" to continue workflow or "denied", "deny", "no" to cancel.

    opened by github-actions[bot] 0
  • Update actions/checkout action to v3

    Update actions/checkout action to v3

    WhiteSource Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | actions/checkout | action | major | v2 -> v3 |


    Release Notes

    actions/checkout

    v3

    Compare Source


    Configuration

    📅 Schedule: At any time (no schedule defined).

    đŸšĻ Automerge: Disabled by config. Please merge this manually once you are satisfied.

    â™ģ Rebasing: Renovate will not automatically rebase this PR, because other commits have been found.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by WhiteSource Renovate. View repository job log here.

    opened by renovate[bot] 0
  • Configure Renovate

    Configure Renovate

    WhiteSource Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    đŸšĻ To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • Cargo.toml (cargo)
    • .github/workflows/rust.yml (github-actions)

    Configuration

    🔡 Renovate has detected a custom config for this PR. Feel free to ask for help if you have any doubts and would like it reviewed.

    Important: Now that this branch is edited, Renovate can't rebase it from the base branch any more. If you make changes to the base branch that could impact this onboarding PR, please merge them manually.

    What to Expect

    With your current configuration, Renovate will create 1 Pull Request:

    Update actions/checkout action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-checkout-3.x
    • Merge into: main
    • Upgrade actions/checkout to v3

    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by WhiteSource Renovate. View repository job log here.

    opened by renovate[bot] 0
  • Update Rust crate paste to 1.0.9

    Update Rust crate paste to 1.0.9

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | paste | dependencies | patch | 1.0.7 -> 1.0.9 |


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    đŸšĻ Automerge: Disabled by config. Please merge this manually once you are satisfied.

    â™ģ Rebasing: Renovate will not automatically rebase this PR, because other commits have been found.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Edited/Blocked

    These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

    Detected dependencies

    cargo
    Cargo.toml
    • doc-comment 0.3.3
    • safe-transmute 0.11.2
    • paste 1.0.7
    github-actions
    .github/workflows/rust.yml
    • actions/checkout v3
    • actions-rs/toolchain v1
    • actions/checkout v3
    • actions-rs/toolchain v1
    • actions/checkout v3
    • actions-rs/toolchain v1
    • actions-rs/clippy-check v1
    • actions/checkout v3
    • actions-rs/toolchain v1
    • actions/checkout v3
    • actions-rs/toolchain v1
    • manoadamro/rust-release v1
    • katyo/publish-crates v1
    • actions/checkout v3
    • actions-rs/toolchain v1
    • manoadamro/rust-release v1
    • katyo/publish-crates v1

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
    opened by renovate[bot] 0
Releases(v0.3.1)
Owner
Adam Romano
will code for biscuits
Adam Romano
A bit like tee, a bit like script, but all with a fake tty. Lets you remote control and watch a process

teetty teetty is a wrapper binary to execute a command in a pty while providing remote control facilities. This allows logging the stdout of a process

Armin Ronacher 259 Jan 3, 2023
A lightweight, zero-dependency struct diffing library which allows changed fields to be collected and applied

structdiff A lightweight, zero-dependency struct diffing library which allows changed fields to be collected and applied. Derive Difference on a struc

null 7 Dec 25, 2022
Easy access of struct fields in strings using different/custom pre/postfix: "Hello, {field}" in rust

Easy access to struct fields in strings ?? add strung to the dependencies in the Cargo.toml: [dependencies] strung = "0.1.3" ?? use/import everything

Dekirisu 2 Sep 19, 2022
Sudoku Solver using bitmasks and bit-manipulation with Rust đŸĻ€ and egui 🎨

sudoku-solver Download This Rust application implements a very memory efficent algorithm to solve sudoku and lets the user know when a unique solution

cameron 24 Apr 10, 2023
Fast conversion between linear float and 8-bit sRGB

fast-srgb8 Small crate implementing fast conversion between linear float and 8-bit sRGB. Includes API for performing 4 simultaneous conversions, which

Thom Chiovoloni 13 Sep 3, 2022
Advent of Code 2021, also an attempt to practice a bit of Rust.

Advent of Code 2021 Advent of Code 2021 (my first one!), also an attempt to practice a bit of Rust. Running (Assuming that the respective inputs are i

Edoardo Debenedetti 1 Dec 3, 2021
An Intel HAXM powered, protected mode, 32 bit, hypervisor addition calculator, written in Rust.

HyperCalc An Intel HAXM powered, protected mode, 32 bit, hypervisor addition calculator, written in Rust. Purpose None ?? . Mostly just to learn Rust

Michael B. 2 Mar 29, 2022
CIEBII - Check if every bit is intact

CIEBII Checks If Every Byte Is Intact CIEBII is an image file format that checks if every single byte is intact. What does it do if it finds that a by

Codingsquirrel 2 Oct 7, 2022
Stockbook embeds 1-bit raster images in your code at compile time

stockbook Stockbook embeds 1-bit raster images in your code at compile time. Designed primarily for #![no_std] usage, in embedded or other program-mem

Karol Belina 3 Oct 27, 2022
A micro crate that simplifies a bit the use of the std macro thread_local!.

with-thread-local A micro crate that simplifies a bit the use of the std macro thread_local!. extern crate regex; use with_thread_local::with_thread_

Cecile Tonglet 3 Jan 11, 2023
Work to enable a Classic Mac (24-bit 68000) with ~16MB of RAM.

Apple SE FDHD ROM analysis In order to build a Mac clone that doesn't fully emulate the hardware (which is possible because the ROM abstracts hardware

Simon Frankau 6 Oct 6, 2023
Warp is a blazingly fast, Rust-based terminal that makes you and your team more productive at running, debugging, and deploying code and infrastructure.

Warp is a blazingly fast, Rust-based terminal that makes you and your team more productive at running, debugging, and deploying code and infrastructure.

Warp 10.4k Jan 4, 2023
Sets of libraries and tools to write applications and libraries mixing OCaml and Rust

Sets of libraries and tools to write applications and libraries mixing OCaml and Rust. These libraries will help keeping your types and data structures synchronized, and enable seamless exchange between OCaml and Rust

Meta 36 Jan 28, 2023
A comprehensive collection of resources and learning materials for Rust programming, empowering developers to explore and master the modern, safe, and blazingly fast language.

?? Awesome Rust Lang ⛰ī¸ Project Description : Welcome to the Awesome Rust Lang repository! This is a comprehensive collection of resources for Rust, a

Shubham Raj 16 May 29, 2023
REC2 (Rusty External Command and Control) is client and server tool allowing auditor to execute command from VirusTotal and Mastodon APIs written in Rust. đŸĻ€

Information: REC2 is an old personal project (early 2023) that I didn't continue development on. It's part of a list of projects that helped me to lea

Quentin Texier (g0h4n) 104 Oct 7, 2023
A lightweight and high-performance order-book designed to process level 2 and trades data. Available in Rust and Python

ninjabook A lightweight and high-performance order-book implemented in Rust, designed to process level 2 and trades data. Available in Python and Rust

Ninja Quant 134 Jul 22, 2024
JiaShiwen 12 Nov 5, 2022
This is a simple lnd poller and web front-end to see and read boosts and boostagrams.

Helipad This package will poll a Lightning LND node for invoices related to Podcasting 2.0 and display them in a web interface. It's intended for use

Podcastindex.org 26 Dec 29, 2022
Downloads and provides debug symbols and source code for nix derivations to gdb and other debuginfod-capable debuggers as needed.

nixseparatedebuginfod Downloads and provides debug symbols and source code for nix derivations to gdb and other debuginfod-capable debuggers as needed

Guillaume Girol 16 Mar 6, 2023