tiny-bit-flags 0.1.0

Generate bit-flags struct and methods.
Documentation
  • Coverage
  • 100%
    2 out of 2 items documented2 out of 2 items with examples
  • Size
  • Source code size: 6.22 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.06 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • WuBingzheng/tiny-bit-flags
    2 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • WuBingzheng

Generate bit-flags struct and methods.

It's very simple and easy to use. See the example below for details.

Usage

Import this crate and paste to your Cargo.toml:

[dependencies]
tiny-bit-flags = "0.1"
paste = "1.0"

Invoke the tiny_bit_flags! macro to define flags:

tiny_bit_flags::tiny_bit_flags! {
    struct PrimFlags: u32 { // FORMAT: struct <StructName>: <InnerType>
        // list flags below
        const WRITABLE   = 0b00000001;
        const EXECUTABLE = 0b00000010;
    }
}

This actually generates the following code:

// struct
struct PrimFlags(u32);

impl PrimFlags {
    // constant values
    const WRITABLE: u32   = 0b00000001;
    const EXECUTABLE: u32 = 0b00000010;
    // checking methods
    const fn is_writable(&self) -> bool { ... }
    const fn is_executable(&self) -> bool { ... }
    // setting methods
    const fn set_writable(&mut self) { ... }
    const fn set_executable(&mut self) { ... }
    // clearing methods
    const fn clear_writable(&mut self) { ... }
    const fn clear_executable(&mut self) { ... }
}

Then you can use them in your program:

let mut f = PrimFlags(PrimFlags::WRITABLE); // initialize
assert!(f.is_writable()); // check flag
assert!(!f.is_executable());

f.clear_writable(); // clear flag
assert!(!f.is_writable());

f.set_executable(); // set flag
assert!(f.is_executable());

You can use pub before struct to make all above to be public:

 tiny_bit_flags! {
+    pub struct PrimFlags: u32 {
-    struct PrimFlags: u32 {

You can also derive some traits on the struct:

 tiny_bit_flags! {
+    #[derive(Copy, Clone, Debug, Default)]
     struct PrimFlags: u32 {