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
use std::collections::HashMap;

/// Hold a value in the evaluation result of supported types.
#[derive(Clone, PartialEq, Debug)]
#[allow(missing_docs)]
pub enum Value {
    Bool(bool),
    Int(i64),
    Float(f64),
    String(String),
    Array(Vec<Value>),
    Struct(StructValue),
}

/// Represent a structure value as defined in the
/// [spec](https://openfeature.dev/specification/types#structure).
#[derive(Clone, Default, PartialEq, Debug)]
pub struct StructValue {
    /// The fields of struct as key-value pairs.
    pub fields: HashMap<String, Value>,
}

impl Value {
    /// Return `true` if this is a bool value.
    pub fn is_bool(&self) -> bool {
        matches!(self, Self::Bool(_))
    }

    /// Try to convert `self` to bool.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            _ => None,
        }
    }

    /// Return `true` if this is an int value.
    pub fn is_i64(&self) -> bool {
        matches!(self, Self::Int(_))
    }

    /// Try to convert `self` to int.
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Self::Int(value) => Some(*value),
            _ => None,
        }
    }

    /// Return `true` if this is a float value.
    pub fn is_f64(&self) -> bool {
        matches!(self, Self::Float(_))
    }

    /// Try to convert `self` to float.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Float(value) => Some(*value),
            _ => None,
        }
    }

    /// Return `true` if this is a string value.
    pub fn is_str(&self) -> bool {
        matches!(self, Self::String(_))
    }

    /// Try to convert `self` to str.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            _ => None,
        }
    }

    /// Return `true` if this is an array.
    pub fn is_array(&self) -> bool {
        matches!(self, Self::Array(_))
    }

    /// Try to convert `self` to vector.
    pub fn as_array(&self) -> Option<&Vec<Value>> {
        match self {
            Self::Array(value) => Some(value),
            _ => None,
        }
    }

    /// Return `true` if this is a struct.
    pub fn is_struct(&self) -> bool {
        matches!(self, Self::Struct(_))
    }

    /// Try to convert `self` to [`StructValue`].
    pub fn as_struct(&self) -> Option<&StructValue> {
        match self {
            Self::Struct(value) => Some(value),
            _ => None,
        }
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<i8> for Value {
    fn from(value: i8) -> Self {
        Self::Int(value.into())
    }
}

impl From<i16> for Value {
    fn from(value: i16) -> Self {
        Self::Int(value.into())
    }
}

impl From<i32> for Value {
    fn from(value: i32) -> Self {
        Self::Int(value.into())
    }
}

impl From<i64> for Value {
    fn from(value: i64) -> Self {
        Self::Int(value)
    }
}

impl From<u8> for Value {
    fn from(value: u8) -> Self {
        Self::Int(value.into())
    }
}

impl From<u16> for Value {
    fn from(value: u16) -> Self {
        Self::Int(value.into())
    }
}

impl From<u32> for Value {
    fn from(value: u32) -> Self {
        Self::Int(value.into())
    }
}

impl From<f32> for Value {
    fn from(value: f32) -> Self {
        Self::Float(value.into())
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        Self::String(value.to_string())
    }
}

impl<T> From<Vec<T>> for Value
where
    T: Into<Value>,
{
    fn from(value: Vec<T>) -> Self {
        Self::Array(value.into_iter().map(Into::into).collect())
    }
}

impl From<StructValue> for Value {
    fn from(value: StructValue) -> Self {
        Self::Struct(value)
    }
}

impl StructValue {
    /// Append given `key` and `value` to `self` and return it.
    #[must_use]
    pub fn with_field(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.add_field(key, value);
        self
    }

    /// Append given `key` and `value` to `self` in place.
    pub fn add_field(&mut self, key: impl Into<String>, value: impl Into<Value>) {
        self.fields.insert(key.into(), value.into());
    }
}

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

    #[test]
    fn build_value() {
        let alex = StructValue::default()
            .with_field("is_male", false)
            .with_field("id", 100)
            .with_field("grade", 97.5)
            .with_field("name", "Alex")
            .with_field("friends", vec!["Bob", "Carl"])
            .with_field(
                "other",
                StructValue::default().with_field("description", "A student"),
            );

        let is_male = alex.fields.get("is_male").unwrap();
        assert!(is_male.is_bool());
        assert_eq!(false, is_male.as_bool().unwrap());

        let id = alex.fields.get("id").unwrap();
        assert!(id.is_i64());
        assert_eq!(100, id.as_i64().unwrap());

        let grade = alex.fields.get("grade").unwrap();
        assert!(grade.is_f64());
        assert_eq!(97.5, grade.as_f64().unwrap());

        let name = alex.fields.get("name").unwrap();
        assert!(name.is_str());
        assert_eq!("Alex", alex.fields.get("name").unwrap().as_str().unwrap());

        let friends = alex.fields.get("friends").unwrap();
        assert!(friends.is_array());
        assert_eq!(
            vec![
                Value::String("Bob".to_string()),
                Value::String("Carl".to_string())
            ],
            *friends.as_array().unwrap()
        );

        let other = alex.fields.get("other").unwrap();
        assert!(other.is_struct());
        assert_eq!(
            "A student",
            other
                .as_struct()
                .unwrap()
                .fields
                .get("description")
                .unwrap()
                .as_str()
                .unwrap()
        );
    }
}