7 releases

0.3.0 Aug 8, 2024
0.2.0 Jul 19, 2023
0.1.4 Sep 17, 2021
0.1.3 Jan 31, 2020
0.1.2 Mar 10, 2018

#189 in Encoding

Download history 19511/week @ 2024-08-21 32311/week @ 2024-08-28 24671/week @ 2024-09-04 21612/week @ 2024-09-11 18408/week @ 2024-09-18 17588/week @ 2024-09-25 13098/week @ 2024-10-02 11296/week @ 2024-10-09 21394/week @ 2024-10-16 23354/week @ 2024-10-23 21648/week @ 2024-10-30 19077/week @ 2024-11-06 18156/week @ 2024-11-13 23467/week @ 2024-11-20 28083/week @ 2024-11-27 23128/week @ 2024-12-04

95,997 downloads per month
Used in ron

MIT license

15KB
251 lines

Option sets with built-in Serde support

option_set on crates.io option_set on docs.rs option_set Downloads option_set License Lines of Code Twitter

This crate implements a macro option_set which knows how to serialize and deserialize itself to/from a sequence of strings. The macro invocation looks very much like bitflags!(), with a few useful additions. In fact, the underlying type is generated by the bitflags!() macro, therefore you will need the bitflags crate if you are using this library.

Usage

#[macro_use]
extern crate option_set;
#[macro_use]
extern crate bitflags;
extern crate serde;
extern crate serde_json;

option_set! {
    struct FooOptions: UpperCamel + u16 {
        const BAR_FIRST        = 0x0001;
        const QUX_SECOND_THING = 0x0080;
        const LOL_3RD          = 0x4000;
    }
}

fn main() {
    let opts_in = FooOptions::BAR_FIRST | FooOptions::LOL_3RD;
    let json = serde_json::to_string_pretty(&opts_in).unwrap();

    println!("{}", json);

    let opts_out: FooOptions = serde_json::from_str(&json).unwrap();

    println!("{:?}", opts_out);
    assert!(opts_out == opts_in);
}

In the struct declaration, the first identifier after the colon (UpperCamel in the above example) controls how the name of each flag is transformed before serialization. This is necessary because the flags are not real struct fields or enum variants, so #[serde(rename_all = "...")] and the like don't work on them.

The possible name transformations are the variants of the CaseTransform enum.

The second type, after the + sign, is the underlying type of the bitmask, which is usually an exact-width integer.

License

MIT

Dependencies

~125–355KB