1use std::collections::BTreeMap;
4
5use compact_str::CompactString;
6use serde::{
7 Deserialize, Deserializer, Serialize, Serializer,
8 de::{
9 self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, Unexpected,
10 VariantAccess, Visitor,
11 value::{MapDeserializer, SeqDeserializer},
12 },
13 forward_to_deserialize_any,
14 ser::{SerializeMap, SerializeSeq},
15};
16
17#[derive(Clone, Debug, PartialEq)]
38pub enum JsonValue {
39 Null,
41 Bool(bool),
43 Unsigned(u64),
45 Signed(i64),
47 Float(f64),
49 String(CompactString),
51 Array(Vec<JsonValue>),
53 Object(BTreeMap<CompactString, JsonValue>),
55}
56
57impl JsonValue {
58 pub fn to_type<'a, T: Deserialize<'a>>(&'a self) -> Result<T, JsonValueError> {
69 T::deserialize(self)
70 }
71
72 #[must_use]
76 pub fn as_str(&self) -> Option<&str> {
77 match self {
78 Self::String(value) => Some(value),
79 _ => None,
80 }
81 }
82
83 fn unexpected(&self) -> Unexpected<'_> {
84 match self {
85 Self::Null => Unexpected::Unit,
86 Self::Bool(value) => Unexpected::Bool(*value),
87 Self::Unsigned(value) => Unexpected::Unsigned(*value),
88 Self::Signed(value) => Unexpected::Signed(*value),
89 Self::Float(value) => Unexpected::Float(*value),
90 Self::String(value) => Unexpected::Str(value),
91 Self::Array(_) => Unexpected::Seq,
92 Self::Object(_) => Unexpected::Map,
93 }
94 }
95}
96
97impl Serialize for JsonValue {
98 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
99 match self {
100 Self::Null => serializer.serialize_unit(),
101 Self::Bool(value) => serializer.serialize_bool(*value),
102 Self::Unsigned(value) => serializer.serialize_u64(*value),
103 Self::Signed(value) => serializer.serialize_i64(*value),
104 Self::Float(value) => serializer.serialize_f64(*value),
105 Self::String(value) => serializer.serialize_str(value),
106 Self::Array(values) => {
107 let mut seq = serializer.serialize_seq(Some(values.len()))?;
108 for value in values {
109 seq.serialize_element(value)?;
110 }
111 seq.end()
112 }
113 Self::Object(entries) => {
114 let mut map = serializer.serialize_map(Some(entries.len()))?;
115 for (key, value) in entries {
116 map.serialize_entry(key, value)?;
117 }
118 map.end()
119 }
120 }
121 }
122}
123
124impl<'de> Deserialize<'de> for JsonValue {
125 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
126 struct ValueVisitor;
127
128 impl<'de> Visitor<'de> for ValueVisitor {
129 type Value = JsonValue;
130
131 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
132 f.write_str("any JSON value")
133 }
134
135 fn visit_unit<E: de::Error>(self) -> Result<JsonValue, E> {
136 Ok(JsonValue::Null)
137 }
138
139 fn visit_none<E: de::Error>(self) -> Result<JsonValue, E> {
140 Ok(JsonValue::Null)
141 }
142
143 fn visit_some<D: Deserializer<'de>>(
144 self,
145 deserializer: D,
146 ) -> Result<JsonValue, D::Error> {
147 deserializer.deserialize_any(self)
148 }
149
150 fn visit_bool<E: de::Error>(self, value: bool) -> Result<JsonValue, E> {
151 Ok(JsonValue::Bool(value))
152 }
153
154 fn visit_u64<E: de::Error>(self, value: u64) -> Result<JsonValue, E> {
155 Ok(JsonValue::Unsigned(value))
156 }
157
158 fn visit_i64<E: de::Error>(self, value: i64) -> Result<JsonValue, E> {
159 Ok(u64::try_from(value).map_or(JsonValue::Signed(value), JsonValue::Unsigned))
160 }
161
162 fn visit_f64<E: de::Error>(self, value: f64) -> Result<JsonValue, E> {
163 Ok(JsonValue::Float(value))
164 }
165
166 fn visit_str<E: de::Error>(self, value: &str) -> Result<JsonValue, E> {
167 Ok(JsonValue::String(value.into()))
168 }
169
170 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<JsonValue, A::Error> {
171 let mut values = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(64));
172 while let Some(value) = seq.next_element()? {
173 values.push(value);
174 }
175 Ok(JsonValue::Array(values))
176 }
177
178 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<JsonValue, A::Error> {
179 let mut entries = BTreeMap::new();
180 while let Some((key, value)) = map.next_entry::<CompactString, JsonValue>()? {
181 entries.insert(key, value);
182 }
183 Ok(JsonValue::Object(entries))
184 }
185 }
186
187 deserializer.deserialize_any(ValueVisitor)
188 }
189}
190
191#[derive(Clone, Debug, PartialEq, Eq)]
195pub struct JsonValueError(CompactString);
196
197impl core::fmt::Display for JsonValueError {
198 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
199 f.write_str(&self.0)
200 }
201}
202
203impl core::error::Error for JsonValueError {}
204
205impl de::Error for JsonValueError {
206 fn custom<T: core::fmt::Display>(message: T) -> Self {
207 Self(compact_str::format_compact!("{message}"))
208 }
209}
210
211impl<'de> IntoDeserializer<'de, JsonValueError> for &'de JsonValue {
212 type Deserializer = Self;
213
214 fn into_deserializer(self) -> Self {
215 self
216 }
217}
218
219impl<'de> Deserializer<'de> for &'de JsonValue {
220 type Error = JsonValueError;
221
222 fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
223 match self {
224 JsonValue::Null => visitor.visit_unit(),
225 JsonValue::Bool(value) => visitor.visit_bool(*value),
226 JsonValue::Unsigned(value) => visitor.visit_u64(*value),
227 JsonValue::Signed(value) => visitor.visit_i64(*value),
228 JsonValue::Float(value) => visitor.visit_f64(*value),
229 JsonValue::String(value) => visitor.visit_borrowed_str(value),
230 JsonValue::Array(values) => {
231 let mut seq = SeqDeserializer::new(values.iter());
232 let value = visitor.visit_seq(&mut seq)?;
233 seq.end()?;
234 Ok(value)
235 }
236 JsonValue::Object(entries) => {
237 let mut map =
238 MapDeserializer::new(entries.iter().map(|(key, value)| (key.as_str(), value)));
239 let value = visitor.visit_map(&mut map)?;
240 map.end()?;
241 Ok(value)
242 }
243 }
244 }
245
246 fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
247 match self {
248 JsonValue::Null => visitor.visit_none(),
249 _ => visitor.visit_some(self),
250 }
251 }
252
253 fn deserialize_newtype_struct<V: Visitor<'de>>(
254 self,
255 _name: &'static str,
256 visitor: V,
257 ) -> Result<V::Value, Self::Error> {
258 visitor.visit_newtype_struct(self)
259 }
260
261 fn deserialize_enum<V: Visitor<'de>>(
262 self,
263 _name: &'static str,
264 _variants: &'static [&'static str],
265 visitor: V,
266 ) -> Result<V::Value, Self::Error> {
267 match self {
268 JsonValue::String(variant) => visitor.visit_enum(UnitVariant(variant)),
269 other => Err(de::Error::invalid_type(
270 other.unexpected(),
271 &"a string enum",
272 )),
273 }
274 }
275
276 forward_to_deserialize_any! {
277 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
278 unit unit_struct seq tuple tuple_struct map struct identifier ignored_any
279 }
280}
281
282struct UnitVariant<'de>(&'de str);
284
285impl<'de> EnumAccess<'de> for UnitVariant<'de> {
286 type Error = JsonValueError;
287 type Variant = Self;
288
289 fn variant_seed<V: DeserializeSeed<'de>>(
290 self,
291 seed: V,
292 ) -> Result<(V::Value, Self), Self::Error> {
293 let variant = seed.deserialize(de::value::BorrowedStrDeserializer::new(self.0))?;
294 Ok((variant, self))
295 }
296}
297
298impl<'de> VariantAccess<'de> for UnitVariant<'de> {
299 type Error = JsonValueError;
300
301 fn unit_variant(self) -> Result<(), Self::Error> {
302 Ok(())
303 }
304
305 fn newtype_variant_seed<T: DeserializeSeed<'de>>(
306 self,
307 _seed: T,
308 ) -> Result<T::Value, Self::Error> {
309 Err(de::Error::invalid_type(
310 Unexpected::UnitVariant,
311 &"a newtype variant",
312 ))
313 }
314
315 fn tuple_variant<V: Visitor<'de>>(
316 self,
317 _len: usize,
318 _visitor: V,
319 ) -> Result<V::Value, Self::Error> {
320 Err(de::Error::invalid_type(
321 Unexpected::UnitVariant,
322 &"a tuple variant",
323 ))
324 }
325
326 fn struct_variant<V: Visitor<'de>>(
327 self,
328 _fields: &'static [&'static str],
329 _visitor: V,
330 ) -> Result<V::Value, Self::Error> {
331 Err(de::Error::invalid_type(
332 Unexpected::UnitVariant,
333 &"a struct variant",
334 ))
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use core::mem::size_of;
341
342 use super::*;
343
344 #[test]
345 fn unit_enums_convert_from_strings() {
346 #[derive(Debug, PartialEq, Deserialize)]
347 enum Kind {
348 Text,
349 Voice,
350 }
351
352 let value = JsonValue::String("Voice".into());
353 assert_eq!(value.to_type::<Kind>(), Ok(Kind::Voice));
354 assert!(JsonValue::String("Stage".into()).to_type::<Kind>().is_err());
355 assert!(JsonValue::Unsigned(1).to_type::<Kind>().is_err());
356 }
357
358 #[test]
359 fn every_kind_round_trips_through_json() {
360 let json =
361 r#"{"a":null,"b":true,"c":7,"d":-7,"e":1.5,"f":"text","g":[1,"x",[]],"h":{"z":{}}}"#;
362 let value: JsonValue = serde_json::from_str(json).unwrap();
363 let JsonValue::Object(fields) = &value else {
364 panic!("{value:?}");
365 };
366 assert_eq!(fields["a"], JsonValue::Null);
367 assert_eq!(fields["b"], JsonValue::Bool(true));
368 assert_eq!(fields["c"], JsonValue::Unsigned(7));
369 assert_eq!(fields["d"], JsonValue::Signed(-7));
370 assert_eq!(fields["e"], JsonValue::Float(1.5));
371 assert_eq!(fields["f"].as_str(), Some("text"));
372 assert_eq!(fields["c"].as_str(), None);
373 assert_eq!(serde_json::to_string(&value).unwrap(), json);
375 }
376
377 #[test]
378 fn values_convert_to_types() {
379 #[derive(Debug, PartialEq, Deserialize)]
380 struct Settings {
381 name: String,
382 limit: Option<u32>,
383 tags: Vec<String>,
384 ratio: f64,
385 unit: (),
386 }
387
388 let value: JsonValue = serde_json::from_str(
389 r#"{"name":"bot","limit":null,"tags":["a","b"],"ratio":-2,"unit":null}"#,
390 )
391 .unwrap();
392 assert_eq!(
393 value.to_type::<Settings>(),
394 Ok(Settings {
395 name: "bot".into(),
396 limit: None,
397 tags: vec!["a".into(), "b".into()],
398 ratio: -2.0,
399 unit: (),
400 })
401 );
402 let some: JsonValue = serde_json::from_str("5").unwrap();
403 assert_eq!(some.to_type::<Option<u32>>(), Ok(Some(5)));
404 let map: JsonValue = serde_json::from_str(r#"{"x":1}"#).unwrap();
405 assert_eq!(map.to_type::<BTreeMap<String, u8>>().unwrap()["x"], 1);
406 }
407
408 #[test]
409 fn mismatches_are_errors_that_say_what_was_found() {
410 #[derive(Debug, Deserialize)]
411 #[expect(dead_code, reason = "only the error matters")]
412 enum Shape {
413 Unit,
414 Newtype(u8),
415 Tuple(u8, u8),
416 Struct { side: u8 },
417 }
418
419 let error = JsonValue::Bool(true).to_type::<String>().unwrap_err();
420 assert!(error.to_string().contains("boolean"), "{error}");
421 let error = JsonValue::Array(Vec::new()).to_type::<Shape>().unwrap_err();
422 assert!(error.to_string().contains("string enum"), "{error}");
423 for variant in ["Newtype", "Tuple", "Struct"] {
424 let error = JsonValue::String(variant.into())
425 .to_type::<Shape>()
426 .unwrap_err();
427 assert!(error.to_string().contains("variant"), "{variant}: {error}");
428 }
429 let error: JsonValueError = de::Error::custom("custom");
430 assert_eq!(error.to_string(), "custom");
431 }
432
433 #[test]
434 fn size() {
435 assert_eq!(size_of::<JsonValue>(), 32);
436 }
437}