Crate strflags

source ·
Expand description

A string-enum and string-flags with fixed variants that can also accept arbitrary data.

This is more extensible than traditional enums, bitflags or enumset, while being more ergonomic and more typo-resiliant than a set of strings like HashSet<String>.

Example

str_flags! {
    pub Color: [
        Red,
        Green,
        DarkBlue,
    ]
}

This Generates

pub struct Color(..)

And consts:

  • pub const Red: Color = "red";
  • pub const Green: Color = "green";
  • pub const DarkBlue: Color = "darkblue";

Note: The implementation is not &'static str and subject to change.

And implements

Flags

You can create a Flags<Color> like this

 let flags = Color::Red | Color::Green | Color::new("Yellow");
 assert!(flags.contains(Color::Red));
 assert!(flags.contains(Color::new("Green")));
 assert!(flags.contains(Color::new("yELLOW")));
 assert!(!flags.contains(Color::DarkBlue));
 assert!(!flags.contains(Color::new("Black")));

Format

We stores all data in flatlowercase to avoid case mismatches and some typos.

Serialization and Deserialization

We use a string to serialize our “string enums”.

e.g. "red"

We use a csv string to serialize our Flags.

e.g. "dog|cat|giraffe"

This ensures converting from enum to Flags does not break serialization formats.

The debug feature

Allowing any string to be an enum variant is obviously prone to typos. When the debug feature is enabled, we performs a fuzzy string check every time a comparison is made and emit a warn! though the log crate if similar strings are found.

This is obviously slow so be careful when using this feature.

Macros

Structs

  • A set of string-enums

Traits

Functions