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

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

#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DataPoint(Box<str>);

impl<'de> Deserialize<'de> for DataPoint {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct DataPointVisitor;

        impl<'de> Visitor<'de> for DataPointVisitor {
            type Value = DataPoint;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a data point as a float, an integer, or a string")
            }

            fn visit_f64<E>(self, data: f64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(DataPoint(data.to_string().into()))
            }

            fn visit_u64<E>(self, data: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(DataPoint(data.to_string().into()))
            }

            fn visit_str<E>(self, data: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(DataPoint(data.into()))
            }
        }

        deserializer.deserialize_any(DataPointVisitor)
    }
}