1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//! A macro and a trait for implementing a bitset/flag type that
//! serializes to and deserializes from a sequence of strings.
//!
//! # Usage
//!
//! ```
//! option_set::option_set! {
//!     struct FooOptions: UpperCamel + u16 {
//!         const BAR_FIRST        = 0x0001;
//!         const QUX_SECOND_THING = 0x0080;
//!         const LOL_3RD          = 0x4000;
//!     }
//! }
//!
//! 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);
//! ```

#![deny(
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces,
    unused_qualifications,
    missing_docs
)]
#![allow(
    clippy::match_same_arms,
    clippy::clone_on_ref_ptr,
    clippy::needless_pass_by_value
)]
#![deny(
    clippy::wrong_self_convention,
    clippy::used_underscore_binding,
    clippy::module_name_repetitions,
    clippy::similar_names,
    clippy::enum_variant_names,
    clippy::missing_docs_in_private_items,
    clippy::non_ascii_literal,
    clippy::unicode_not_nfc,
    clippy::unwrap_used,
    clippy::map_unwrap_or,
    clippy::manual_filter_map,
    clippy::shadow_unrelated,
    clippy::shadow_reuse,
    clippy::shadow_same,
    clippy::int_plus_one,
    clippy::string_add_assign,
    clippy::if_not_else,
    clippy::invalid_upcast_comparisons,
    clippy::cast_precision_loss,
    clippy::cast_possible_wrap,
    clippy::cast_possible_truncation,
    clippy::mutex_integer,
    clippy::mut_mut,
    clippy::items_after_statements,
    clippy::print_stdout,
    clippy::mem_forget,
    clippy::maybe_infinite_iter
)]

use heck::{
    ToKebabCase, ToLowerCamelCase, ToShoutySnakeCase, ToSnakeCase, ToTitleCase, ToUpperCamelCase,
};
use serde::de::{Deserialize, SeqAccess, Visitor};
use serde::ser::SerializeSeq;
use serde::{Deserializer, Serializer};
use std::borrow::Cow;
use std::fmt::{self, Formatter};
use std::marker::PhantomData;
use std::ops::{BitAnd, BitOrAssign, Deref};

/// Defines an option set type.
#[macro_export]
macro_rules! option_set {
    ($(#[$outer:meta])* pub struct $name:ident: $case:ident + $repr:ty {
        $($(#[$inner:ident $($args:tt)*])* const $variant:ident = $value:expr;)*
    }) => {
        bitflags::bitflags! {
            $(#[$outer])*
            #[derive(Clone, Copy, Default, PartialEq, Eq, Hash, Debug)]
            pub struct $name: $repr {
                $(
                    $(#[$inner $($args)*])*
                    const $variant = $value;
                )*
            }
        }

        impl $crate::OptionSet for $name {
            const VARIANTS: &'static [$name] = &[$($name::$variant,)*];
            const NAMES: &'static [&'static str] = &[$(stringify!($variant),)*];
        }

        impl ::serde::ser::Serialize for $name {
            fn serialize<S: ::serde::ser::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
                $crate::serialize(self, serializer, $crate::CaseTransform::$case)
            }
        }

        impl<'de> ::serde::de::Deserialize<'de> for $name {
            fn deserialize<D: ::serde::de::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
                $crate::deserialize(deserializer, $crate::CaseTransform::$case)
            }
        }
    };
    ($(#[$outer:meta])* struct $name:ident: $case:ident + $repr:ty {
        $($(#[$inner:ident $($args:tt)*])* const $variant:ident = $value:expr;)*
    }) => {
        bitflags::bitflags! {
            $(#[$outer])*
            #[derive(Clone, Copy, Default, PartialEq, Eq, Hash, Debug)]
            struct $name: $repr {
                $(
                    $(#[$inner $($args)*])*
                    const $variant = $value;
                )*
            }
        }

        impl $crate::OptionSet for $name {
            const VARIANTS: &'static [$name] = &[$($name::$variant,)*];
            const NAMES: &'static [&'static str] = &[$(stringify!($variant),)*];
        }

        impl ::serde::ser::Serialize for $name {
            fn serialize<S: ::serde::ser::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
                $crate::serialize(self, serializer, $crate::CaseTransform::$case)
            }
        }

        impl<'de> ::serde::de::Deserialize<'de> for $name {
            fn deserialize<D: ::serde::de::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
                $crate::deserialize(deserializer, $crate::CaseTransform::$case)
            }
        }
    };
}

/// Trait for bit flags that forwards to std traits for useful bit operators.
pub trait OptionSet: Copy + Default + Eq + BitAnd<Output = Self> + BitOrAssign + 'static {
    /// The basis flags (in the algebraic sense): one for each independent option.
    const VARIANTS: &'static [Self];
    /// The corresponding names. `VARIANTS.len() == NAMES.len()` must always hold.
    const NAMES: &'static [&'static str];
}

/// Type that knows how to transform the case of individual option flag names.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CaseTransform {
    /// Do not transform the name.
    #[default]
    Identity,
    /// `lower_snake_case`
    LowerSnake,
    /// `UPPER_SNAKE_CASE`
    UpperSnake,
    /// `lowerCamelCase`
    LowerCamel,
    /// `UpperCamelCase`
    UpperCamel,
    /// `kebab-case`
    Kebab,
    /// `Title Case`
    Title,
}

impl CaseTransform {
    /// Converts the name of an option flag to the specified case
    fn apply(self, s: &str) -> Cow<str> {
        use CaseTransform::*;

        match self {
            Identity => Cow::Borrowed(s),
            LowerSnake => Cow::Owned(s.to_snake_case()),
            UpperSnake => Cow::Owned(s.to_shouty_snake_case()),
            LowerCamel => Cow::Owned(s.to_lower_camel_case()),
            UpperCamel => Cow::Owned(s.to_upper_camel_case()),
            Kebab => Cow::Owned(s.to_kebab_case()),
            Title => Cow::Owned(s.to_title_case()),
        }
    }
}

/// Serialize an OptionSet's set bits as a sequence of strings.
pub fn serialize<T, S>(
    options: &T,
    serializer: S,
    transform: CaseTransform,
) -> Result<S::Ok, S::Error>
where
    T: OptionSet,
    S: Serializer,
{
    assert!(T::VARIANTS.len() == T::NAMES.len());

    let mut seq = serializer.serialize_seq(T::NAMES.len().into())?;

    for (&variant, &name) in T::VARIANTS.iter().zip(T::NAMES) {
        if *options & variant == variant {
            seq.serialize_element(&transform.apply(name))?;
        }
    }

    seq.end()
}

/// Deserialize set bits from a sequence of name strings.
pub fn deserialize<'de, T, D>(deserializer: D, transform: CaseTransform) -> Result<T, D::Error>
where
    T: OptionSet,
    D: Deserializer<'de>,
{
    deserializer.deserialize_seq(OptionSetVisitor(transform, PhantomData))
}

/// This visitor tries to associate bitflag values with their name.
#[derive(Debug, Clone, Copy)]
struct OptionSetVisitor<T: OptionSet>(CaseTransform, PhantomData<T>);

impl<'de, T: OptionSet> Visitor<'de> for OptionSetVisitor<T> {
    type Value = T;

    fn expecting(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str("set of option strings")
    }

    fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
        assert!(T::VARIANTS.len() == T::NAMES.len());

        match self.0 {
            CaseTransform::Identity => extract_bits(seq, T::NAMES),
            _ => {
                let names: Vec<_> = T::NAMES.iter().map(|name| self.0.apply(name)).collect();
                extract_bits(seq, &names)
            }
        }
    }
}

/// Actually performs the sequence processing and flag extraction.
fn extract_bits<'de, A, T, S>(mut seq: A, names: &[S]) -> Result<T, A::Error>
where
    A: SeqAccess<'de>,
    T: OptionSet,
    S: Deref<Target = str>,
{
    use serde::de::Error;

    let mut flags = T::default();

    while let Some(elem) = seq.next_element::<Str<'de>>()? {
        let mut iter = T::VARIANTS.iter().zip(names);

        match iter.find(|&(_, name)| **name == *elem) {
            Some((&flag, _)) => flags |= flag,
            None => Err(A::Error::unknown_variant(&elem, T::NAMES))?,
        }
    }

    Ok(flags)
}

/// Equivalent of `Cow<'a, str>` except that this
/// type can deserialize from a borrowed string.
#[derive(Debug)]
enum Str<'a> {
    /// Owned.
    String(String),
    /// Borrowed.
    Str(&'a str),
}

impl<'a> Deref for Str<'a> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        match *self {
            Str::Str(s) => s,
            Str::String(ref s) => s,
        }
    }
}

/// Visitor for deserializing a `Str<'a>`.
struct StrVisitor;

impl<'a> Visitor<'a> for StrVisitor {
    type Value = Str<'a>;

    fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
        formatter.write_str("a string")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        self.visit_string(v.to_owned())
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Str::String(v))
    }

    fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Str::Str(v))
    }
}

impl<'de> Deserialize<'de> for Str<'de> {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(StrVisitor)
    }
}