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
#![allow(clippy::use_self)]

use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens, TokenStreamExt};
use strum_macros::Display;

#[derive(Copy, Clone, Debug, Display, Eq, PartialEq)]
pub enum SerdeFormat {
    #[cfg(any(serde_default, feature = "__serde_bincode"))]
    Bincode,
    #[cfg(feature = "__serde_cbor")]
    Cbor,
    #[cfg(feature = "__serde_cbor4ii")]
    Cbor4ii,
}

#[allow(clippy::vec_init_then_push)]
#[must_use]
pub fn serde_format() -> SerdeFormat {
    let mut formats = vec![];
    #[cfg(any(serde_default, feature = "__serde_bincode"))]
    formats.push(SerdeFormat::Bincode);
    #[cfg(feature = "__serde_cbor")]
    formats.push(SerdeFormat::Cbor);
    #[cfg(feature = "__serde_cbor4ii")]
    formats.push(SerdeFormat::Cbor4ii);
    assert!(
        formats.len() <= 1,
        "{}",
        "Multiple serde formats selected: {formats:?}"
    );
    formats.pop().expect("No serde format selected")
}

impl SerdeFormat {
    #[must_use]
    pub fn as_feature(self) -> &'static str {
        match self {
            #[cfg(any(serde_default, feature = "__serde_bincode"))]
            Self::Bincode => "serde_bincode",
            #[cfg(feature = "__serde_cbor")]
            Self::Cbor => "serde_cbor",
            #[cfg(feature = "__serde_cbor4ii")]
            Self::Cbor4ii => "serde_cbor4ii",
        }
    }
}

impl ToTokens for SerdeFormat {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let ident = Ident::new(&self.to_string(), Span::call_site());
        tokens.append_all(quote! {
            test_fuzz::SerdeFormat::#ident
        });
    }
}