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
use log::warn;
use serde::{Deserialize, Serialize};

use crate::util::f64_to_i64_safe;

/// FlagValue represents any of the data types supported by JSON, all of which can be used for a
/// LaunchDarkly feature flag variation or a custom user attribute.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum FlagValue {
    /// Used when the value is a boolean.
    Bool(bool),
    /// Used when the value is a string.
    Str(String),
    /// Used when the value is a number.
    Number(f64),
    /// Used when the value is an arbitrary JSON value.
    Json(serde_json::Value),
}

impl From<bool> for FlagValue {
    fn from(b: bool) -> FlagValue {
        FlagValue::Bool(b)
    }
}

impl From<String> for FlagValue {
    fn from(s: String) -> FlagValue {
        FlagValue::Str(s)
    }
}

impl From<f64> for FlagValue {
    fn from(f: f64) -> FlagValue {
        FlagValue::Number(f)
    }
}

impl From<i64> for FlagValue {
    fn from(i: i64) -> FlagValue {
        FlagValue::Number(i as f64)
    }
}

impl From<serde_json::Value> for FlagValue {
    fn from(v: serde_json::Value) -> Self {
        use serde_json::Value;
        match v {
            Value::Bool(b) => b.into(),
            Value::Number(n) => {
                if let Some(f) = n.as_f64() {
                    f.into()
                } else {
                    warn!("unrepresentable number {}, converting to string", n);
                    FlagValue::Json(format!("{}", n).into())
                }
            }
            Value::String(s) => s.into(),
            Value::Null | Value::Object(_) | Value::Array(_) => FlagValue::Json(v),
        }
    }
}

impl FlagValue {
    /// Attempts to convert the FlagValue into a boolean representation, returning None if the
    /// conversion is invalid.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            FlagValue::Bool(b) => Some(*b),
            _ => {
                warn!("variation type is not bool but {:?}", self);
                None
            }
        }
    }

    /// Attempts to convert the FlagValue into a string representation, returning None if the
    /// conversion is invalid.
    pub fn as_string(&self) -> Option<String> {
        match self {
            FlagValue::Str(s) => Some(s.clone()),
            _ => {
                warn!("variation type is not str but {:?}", self);
                None
            }
        }
    }

    /// Attempts to convert the FlagValue into a float representation, returning None if the
    /// conversion is invalid.
    pub fn as_float(&self) -> Option<f64> {
        match self {
            FlagValue::Number(f) => Some(*f),
            _ => {
                warn!("variation type is not number but {:?}", self);
                None
            }
        }
    }

    /// Attempts to convert the FlagValue into a integer representation, returning None if the
    /// conversion is invalid.
    pub fn as_int(&self) -> Option<i64> {
        match self {
            FlagValue::Number(f) => f64_to_i64_safe(*f),
            _ => {
                warn!("variation type is not number but {:?}", self);
                None
            }
        }
    }

    /// Attempts to convert the FlagValue into an arbitrary JSON representation, returning None if the
    /// conversion is invalid.
    pub fn as_json(&self) -> Option<serde_json::Value> {
        use serde_json::Value;
        match self {
            FlagValue::Bool(b) => Some(Value::from(*b)),
            FlagValue::Str(s) => Some(Value::from(s.as_str())),
            FlagValue::Number(f) => Some(Value::from(*f)),
            FlagValue::Json(v) => Some(v.clone()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use spectral::prelude::*;

    #[test]
    fn float_bounds() {
        let test_cases = vec![
            (1.99, Some(1)),
            (9007199254740990.0, Some(9007199254740990)),
            (9007199254740991.0, Some(9007199254740991)),
            (9007199254740992.0, None),
            (-1.99, Some(-1)),
            (-9007199254740990.0, Some(-9007199254740990)),
            (-9007199254740991.0, Some(-9007199254740991)),
            (-9007199254740992.0, None),
        ];
        for (have, expect) in test_cases {
            assert_that!(FlagValue::Number(have).as_int()).is_equal_to(expect);
        }
    }

    #[test]
    fn deserialization() {
        fn test_case(json: &str, expected: FlagValue) {
            assert_eq!(serde_json::from_str::<FlagValue>(json).unwrap(), expected);
        }

        test_case("1.0", FlagValue::Number(1.0));
        test_case("1", FlagValue::Number(1.0));
        test_case("true", FlagValue::Bool(true));
        test_case("\"foo\"", FlagValue::Str("foo".to_string()));
        test_case("{}", FlagValue::Json(json!({})));
    }
}