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
use std::convert::Into;
use std::default;
use std::fmt;
use std::marker::PhantomData;
use std::str::FromStr;

use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer};

#[derive(Debug, Clone, Copy)]
pub struct FloatOrString(f64);

impl<'de> Deserialize<'de> for FloatOrString {
    fn deserialize<D>(deserializer: D) -> Result<FloatOrString, D::Error>
    where
        D: Deserializer<'de>,
    {
        // This is a Visitor that forwards string types to T's `FromStr` impl and
        // forwards number types to T's `Deserialize` impl. The `PhantomData` is to
        // keep the compiler from complaining about T being an unused generic type
        // parameter. We need T in order to know the Value type for the Visitor
        // impl.
        struct StringOrNum<T>(PhantomData<fn() -> T>);

        impl<'de, T> Visitor<'de> for StringOrNum<T>
        where
            T: Deserialize<'de>
                + FromStr<Err = <f64 as FromStr>::Err>
                + From<u64>
                + From<i64>
                + From<f64>,
        {
            type Value = T;

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

            fn visit_str<E>(self, value: &str) -> Result<T, E>
            where
                E: de::Error,
            {
                Ok(FromStr::from_str(value).unwrap())
            }

            fn visit_u64<E>(self, value: u64) -> Result<T, E>
            where
                E: de::Error,
            {
                Ok(From::from(value))
            }

            fn visit_i64<E>(self, value: i64) -> Result<T, E>
            where
                E: de::Error,
            {
                Ok(From::from(value))
            }

            fn visit_f64<E>(self, value: f64) -> Result<T, E>
            where
                E: de::Error,
            {
                Ok(From::from(value))
            }

            fn visit_unit<E>(self) -> Result<T, E>
            where
                E: de::Error,
            {
                Ok(From::from(std::f64::NAN))
            }

        }

        deserializer.deserialize_any(StringOrNum(PhantomData))
    }
}

// The `string_or_num` function uses this impl to instantiate a `FloatOrString` if
// the input file contains a string and not a number.
impl FromStr for FloatOrString {
    type Err = <f64 as FromStr>::Err;

    fn from_str(s: &str) -> Result<FloatOrString, Self::Err> {
        if s == "" {
            Ok(FloatOrString { 0: 0.0 })
        } else {
            // remove commas as thousands separator
            let s = s.replace(",", "");
            match s.parse::<f64>() {
                Ok(num) => Ok(FloatOrString { 0: num }),
                // If string can not be parsed, set value to NaN
                _ => Ok(FloatOrString { 0: std::f64::NAN }),
            }
        }
    }
}

impl Into<f64> for FloatOrString {
    fn into(self) -> f64 {
        return self.0;
    }
}

impl From<u64> for FloatOrString {
    fn from(val: u64) -> FloatOrString {
        FloatOrString { 0: val as f64 }
    }
}

impl From<i64> for FloatOrString {
    fn from(val: i64) -> FloatOrString {
        FloatOrString { 0: val as f64 }
    }
}

impl From<f64> for FloatOrString {
    fn from(val: f64) -> FloatOrString {
        FloatOrString { 0: val }
    }
}

// Manual implementation of Display trait for nice printouts
impl fmt::Display for FloatOrString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Implement default instantiation
impl default::Default for FloatOrString {
    fn default() -> FloatOrString {
        FloatOrString { 0: std::f64::NAN }
    }
}

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

    #[derive(Deserialize, Debug)]
    struct DoubleNum {
        x: FloatOrString,
        y: FloatOrString,
        z: FloatOrString,
    }

    #[derive(Deserialize, Debug)]
    struct DoubleNumOpt {
        pub x: Option<FloatOrString>,
    }

    #[test]
    fn convert_str_num() {
        let str_num = "2".to_string();
        let num: f64 = str_num.parse().unwrap();
        assert_eq!(num, 2.0);

        let json: serde_json::Value =
            serde_json::from_str("{\"x\":\"2.1\",\"y\":3,\"z\":3.4}").unwrap();
        let d_num: DoubleNum = serde_json::from_value(json).unwrap();
        assert_eq!(d_num.x.0, 2.1);
        assert_eq!(d_num.y.0, 3.0);
        assert_eq!(d_num.z.0, 3.4);
    }

    #[test]
    fn convert_null_str_num() {
        let json: serde_json::Value =
            serde_json::from_str("{\"x\":null, \"y\":1, \"z\":null}").unwrap();
        let d_num: DoubleNumOpt = serde_json::from_value(json).unwrap();
        assert!(d_num.x.is_none());
    }

    #[test]
    fn convert_vec_on_str_num() {
        let json: serde_json::Value = serde_json::from_str("[\"2.1\",3,3.4]").unwrap();
        let v: Vec<FloatOrString> = serde_json::from_value(json).unwrap();
        assert_eq!(v[0].0, 2.1);
        assert_eq!(v[1].0, 3.0);
        assert_eq!(v[2].0, 3.4);
    }

    #[test]
    fn print_str_num() {
        let str_num = FloatOrString { 0: 2.3 };
        let num_as_str = format!("{}", str_num);
        assert_eq!(num_as_str, "2.3");
    }

    #[test]
    fn float_string_to_f64() {
        let str_num = FloatOrString { 0: 2.3 };
        let num: f64 = str_num.into();
        assert_eq!(num, 2.3);
    }
}