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
use serde::{
    de::{DeserializeOwned, Error},
    Deserialize, Deserializer, Serialize, Serializer,
};
use serde_json::{from_value, Value};

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum VariadicValue<T> {
    /// None
    Null,
    /// Single
    Single(T),
    /// List
    Multiple(Vec<T>),
}

impl<T> Into<Option<Vec<T>>> for VariadicValue<T> {
    fn into(self) -> Option<Vec<T>> {
        match self {
            VariadicValue::Null => None,
            VariadicValue::Single(x) => Some(vec![x]),
            VariadicValue::Multiple(xs) => Some(xs),
        }
    }
}

impl<T> VariadicValue<T>
where T: DeserializeOwned
{
    pub fn to_vec(self) -> Vec<T> {
        match self {
            VariadicValue::Null => vec![],
            VariadicValue::Single(x) => vec![x],
            VariadicValue::Multiple(xs) => xs,
        }
    }

    pub fn to_opt(self) -> Option<Vec<T>> {
        match self {
            VariadicValue::Null => None,
            VariadicValue::Single(x) => Some(vec![x]),
            VariadicValue::Multiple(xs) => Some(xs),
        }
    }
}

impl<T> VariadicValue<T> {
    pub fn iter<'a>(&'a self) -> Box<dyn std::iter::Iterator<Item = &T> + 'a> {
        match self {
            VariadicValue::Null => Box::new(std::iter::empty()),
            VariadicValue::Single(x) => Box::new(std::iter::once(x)),
            VariadicValue::Multiple(xs) => Box::new(xs.iter()),
        }
    }
}

impl<T> Serialize for VariadicValue<T>
where T: Serialize
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: Serializer {
        match &self {
            &VariadicValue::Null => serializer.serialize_none(),
            &VariadicValue::Single(x) => x.serialize(serializer),
            &VariadicValue::Multiple(xs) => xs.serialize(serializer),
        }
    }
}

impl<'a, T> Deserialize<'a> for VariadicValue<T>
where T: DeserializeOwned
{
    fn deserialize<D>(deserializer: D) -> Result<VariadicValue<T>, D::Error>
    where D: Deserializer<'a> {
        let v: Value = Deserialize::deserialize(deserializer)?;

        if v.is_null() {
            return Ok(VariadicValue::Null);
        }

        from_value(v.clone())
            .map(VariadicValue::Single)
            .or_else(|_| from_value(v).map(VariadicValue::Multiple))
            .map_err(|err| {
                D::Error::custom(format!(
                    "Invalid variadic value type: {}",
                    err
                ))
            })
    }
}

#[cfg(test)]
mod tests {
    use super::VariadicValue;
    use serde_json;

    #[test]
    fn test_serialize_variadic_value() {
        let value: VariadicValue<u64> = VariadicValue::Null;
        let serialized_value = serde_json::to_string(&value).unwrap();
        assert_eq!(serialized_value, "null");

        let value = VariadicValue::Single(1);
        let serialized_value = serde_json::to_string(&value).unwrap();
        assert_eq!(serialized_value, "1");

        let value = VariadicValue::Multiple(vec![1, 2, 3, 4]);
        let serialized_value = serde_json::to_string(&value).unwrap();
        assert_eq!(serialized_value, "[1,2,3,4]");

        let value = VariadicValue::Multiple(vec![
            VariadicValue::Null,
            VariadicValue::Single(1),
            VariadicValue::Multiple(vec![2, 3]),
            VariadicValue::Single(4),
        ]);
        let serialized_value = serde_json::to_string(&value).unwrap();
        assert_eq!(serialized_value, "[null,1,[2,3],4]");
    }

    #[test]
    fn test_deserialize_variadic_value() {
        let serialized = "null";
        let deserialized_value: VariadicValue<u64> =
            serde_json::from_str(serialized).unwrap();
        assert_eq!(deserialized_value, VariadicValue::Null);

        let serialized = "1";
        let deserialized_value: VariadicValue<u64> =
            serde_json::from_str(serialized).unwrap();
        assert_eq!(deserialized_value, VariadicValue::Single(1));

        let serialized = "[1,2,3,4]";
        let deserialized_value: VariadicValue<u64> =
            serde_json::from_str(serialized).unwrap();
        assert_eq!(
            deserialized_value,
            VariadicValue::Multiple(vec![1, 2, 3, 4])
        );
    }
}