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

#[derive(Deserialize, Debug)]
/// An identifier
pub struct Identifier(pub String);

impl fmt::Display for Identifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged)]
/// A string or an array
pub enum StringOrArray {
    /// A String
    String(String),
    /// An array of strings
    Array(Vec<String>),
}

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

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

impl StringOrArray {
    /// Turn this into a slice of string
    pub fn as_slice(&self) -> &[String] {
        match self {
            StringOrArray::String(s) => std::slice::from_ref(s),
            StringOrArray::Array(s) => s,
        }
    }
}

/// Any scalar YAML value
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AnyScalar {
    /// null
    Null,
    /// Boolean
    Bool(bool),
    /// string
    String(String),
    /// integer
    UInt(u64),
}

struct AnyScalarVisitor;

impl<'de> serde::de::Visitor<'de> for AnyScalarVisitor {
    type Value = AnyScalar;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "any scalar")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(AnyScalar::String(v.to_string()))
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(AnyScalar::String(v))
    }

    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(AnyScalar::Bool(v))
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(AnyScalar::UInt(v))
    }
}

impl<'de> Deserialize<'de> for AnyScalar {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_any(AnyScalarVisitor)
    }
}