flagged 0.1.0

Bitflag-based warning type
Documentation
  • Coverage
  • 0%
    0 out of 7 items documented0 out of 4 items with examples
  • Size
  • Source code size: 16.46 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 374.73 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 11s Average build duration of successful builds.
  • all releases: 11s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • ozaner/flagged
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • ozaner

flagged

flagged is a Rust library for creating Flagged values, that is, values with an associated set of bitflags.

Purpose

The main use case of the Flagged struct is to be able to return values from a function along with associated warnings. There already exist crates that accomplish this like warned and wresult, but these crates instead represent their warnings as a Vec. This means that every call of a function that returns one of these warning types, must also potentially allocate a Vec. For many use cases, this seems like overkill. This was the inciting reason for the creation of this crate.

Installation

The flagged crate depends on the enumflag2 crate, and so both must be included in your Cargo.toml:

[dependencies]
flagged = "0.1.0"
enumflags2 = "0.7.9"

Note that as long as this issue is still open, flagged cannot simply reexport the enumflags2 crate.

Also note that, since enumflags2 still has a major version of 0, every version change is potentially breaking. As such, using the specific version above is recommended.

Usage

To create a flagged value, we first need to define a BitFlag c-like enum to use it with:

#[bitflags]
#[repr(u8)] //bitflags must have an explicit repr
#[derive(Clone, Copy)] //bitflags must impl `Copy`
pub enum ParsingWarning {
    TooLong,
    TooShort,
    InvalidToken,
}

With this defined, we can now define a function that returns a Flagged value:

pub fn parse(str: &str) -> Flagged<MyStruct, ParsingWarning> {
    //... rest of the fn
    Flagged {
        value: myStruct,
        flags: myFlags,
    }
}

We can then access the value, warnings, as well as perform other operations on the returned Flagged value:

let f = parse(&"Hello, World");

//access wrapped value
println!("{}", f.value);

//access flags
if f.flags.contains(ParsingWarning::InvalidToken) {
    println!("Invalid character found, ignoring!");
}

//turn into a result and error when any flags are set
assert!(f.flags.to_result().is_err());

//turn into a result and error only when certain flags are set
assert!(f.flags.to_result_against(ParsingWarning::TooShort | ParsingWarning::TooLong).is_err());

Note that the flags field is of type BitFlags from the enumflag2 crate, you can read more about it in the docs.