alloy_json_rpc/
common.rs

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
use serde::{de::Visitor, Deserialize, Serialize};
use std::fmt::Display;

/// A JSON-RPC 2.0 ID object. This may be a number, a string, or null.
///
/// ### Ordering
///
/// This type implements [`PartialOrd`], [`Ord`], [`PartialEq`], and [`Eq`] so
/// that it can be used as a key in a [`BTreeMap`] or an item in a
/// [`BTreeSet`]. The ordering is as follows:
///
/// 1. Numbers are less than strings.
/// 2. Strings are less than null.
/// 3. Null is equal to null.
///
/// ### Hash
///
/// This type implements [`Hash`] so that it can be used as a key in a
/// [`HashMap`] or an item in a [`HashSet`].
///
/// [`BTreeMap`]: std::collections::BTreeMap
/// [`BTreeSet`]: std::collections::BTreeSet
/// [`HashMap`]: std::collections::HashMap
/// [`HashSet`]: std::collections::HashSet
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Id {
    /// A number.
    Number(u64),
    /// A string.
    String(String),
    /// Null.
    None,
}

impl From<u64> for Id {
    fn from(value: u64) -> Self {
        Self::Number(value)
    }
}

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

impl Display for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Number(n) => write!(f, "{n}"),
            Self::String(s) => f.write_str(s),
            Self::None => f.write_str("null"),
        }
    }
}

impl Serialize for Id {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Number(n) => serializer.serialize_u64(*n),
            Self::String(s) => serializer.serialize_str(s),
            Self::None => serializer.serialize_none(),
        }
    }
}

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

        impl Visitor<'_> for IdVisitor {
            type Value = Id;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(formatter, "a string, a number, or null")
            }

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

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

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(Id::None)
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(Id::None)
            }
        }

        deserializer.deserialize_any(IdVisitor)
    }
}

impl PartialOrd for Id {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Id {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // numbers < strings
        // strings < null
        // null == null
        match (self, other) {
            (Self::Number(a), Self::Number(b)) => a.cmp(b),
            (Self::Number(_), _) => std::cmp::Ordering::Less,

            (Self::String(_), Self::Number(_)) => std::cmp::Ordering::Greater,
            (Self::String(a), Self::String(b)) => a.cmp(b),
            (Self::String(_), Self::None) => std::cmp::Ordering::Less,

            (Self::None, Self::None) => std::cmp::Ordering::Equal,
            (Self::None, _) => std::cmp::Ordering::Greater,
        }
    }
}

impl Id {
    /// Returns `true` if the ID is a number.
    pub const fn is_number(&self) -> bool {
        matches!(self, Self::Number(_))
    }

    /// Returns `true` if the ID is a string.
    pub const fn is_string(&self) -> bool {
        matches!(self, Self::String(_))
    }

    /// Returns `true` if the ID is `None`.
    pub const fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    /// Returns the ID as a number, if it is one.
    pub const fn as_number(&self) -> Option<u64> {
        match self {
            Self::Number(n) => Some(*n),
            _ => None,
        }
    }

    /// Returns the ID as a string, if it is one.
    pub fn as_string(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }
}

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

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct TestCase {
        id: Id,
    }

    #[test]
    fn it_serializes_and_deserializes() {
        let cases = [
            (TestCase { id: Id::Number(1) }, r#"{"id":1}"#),
            (TestCase { id: Id::String("foo".to_string()) }, r#"{"id":"foo"}"#),
            (TestCase { id: Id::None }, r#"{"id":null}"#),
        ];
        for (case, expected) in cases {
            let serialized = serde_json::to_string(&case).unwrap();
            assert_eq!(serialized, expected);

            let deserialized: TestCase = serde_json::from_str(expected).unwrap();
            assert_eq!(deserialized, case);
        }
    }
}