djs-model 0.1.0-alpha.1

Discord API v10 types — users, guilds, channels, messages, interactions and gateway events.
Documentation
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Arbitrary JSON values.

use std::collections::BTreeMap;

use compact_str::CompactString;
use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{
        self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, Unexpected,
        VariantAccess, Visitor,
        value::{MapDeserializer, SeqDeserializer},
    },
    forward_to_deserialize_any,
    ser::{SerializeMap, SerializeSeq},
};

/// Any JSON value, for the places where the API has arbitrary or "mixed" data (D-070, D-072):
/// [audit log change values](crate::audit_log::AuditLogChange) and game-defined metadata.
///
/// Convert it with [`to_type`](Self::to_type) to a concrete type, e.g.
/// [`Permissions`](crate::permissions::Permissions) for a `permissions` change or
/// `Vec<`[`Overwrite`](crate::channel::Overwrite)`>` for `permission_overwrites`:
/// `&JsonValue` is a serde [`Deserializer`] that lends out its strings.
///
/// discord.js counterpart: none (plain JavaScript values in discord.js).
///
/// # Examples
///
/// ```
/// use djs_model::util::JsonValue;
///
/// let value: JsonValue = serde_json::from_str(r#"{"wins":12,"rank":"Gold"}"#).unwrap();
/// let JsonValue::Object(fields) = &value else { panic!() };
/// assert_eq!(fields["wins"].to_type::<u32>(), Ok(12));
/// assert_eq!(fields["rank"].as_str(), Some("Gold"));
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum JsonValue {
    /// `null`.
    Null,
    /// A boolean.
    Bool(bool),
    /// A non-negative integer.
    Unsigned(u64),
    /// A negative integer.
    Signed(i64),
    /// A number with a fraction (or out of the integer ranges).
    Float(f64),
    /// A string (snowflakes, permissions, timestamps and hashes are strings too).
    String(CompactString),
    /// An array.
    Array(Vec<JsonValue>),
    /// An object (keys sorted, D-058).
    Object(BTreeMap<CompactString, JsonValue>),
}

impl JsonValue {
    /// Converts the value to `T` (any type that deserializes from JSON of this shape).
    ///
    /// Enums whose JSON is a string (`str_enum`s) convert from strings; other enums are
    /// decoded through their JSON representation as usual.
    ///
    /// discord.js counterpart: none (plain JavaScript values in discord.js).
    ///
    /// # Errors
    ///
    /// Returns an error if the value does not have the shape of `T`.
    pub fn to_type<'a, T: Deserialize<'a>>(&'a self) -> Result<T, JsonValueError> {
        T::deserialize(self)
    }

    /// Returns the string, if the value is one.
    ///
    /// discord.js counterpart: none (plain JavaScript values in discord.js).
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            _ => None,
        }
    }

    fn unexpected(&self) -> Unexpected<'_> {
        match self {
            Self::Null => Unexpected::Unit,
            Self::Bool(value) => Unexpected::Bool(*value),
            Self::Unsigned(value) => Unexpected::Unsigned(*value),
            Self::Signed(value) => Unexpected::Signed(*value),
            Self::Float(value) => Unexpected::Float(*value),
            Self::String(value) => Unexpected::Str(value),
            Self::Array(_) => Unexpected::Seq,
            Self::Object(_) => Unexpected::Map,
        }
    }
}

impl Serialize for JsonValue {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Null => serializer.serialize_unit(),
            Self::Bool(value) => serializer.serialize_bool(*value),
            Self::Unsigned(value) => serializer.serialize_u64(*value),
            Self::Signed(value) => serializer.serialize_i64(*value),
            Self::Float(value) => serializer.serialize_f64(*value),
            Self::String(value) => serializer.serialize_str(value),
            Self::Array(values) => {
                let mut seq = serializer.serialize_seq(Some(values.len()))?;
                for value in values {
                    seq.serialize_element(value)?;
                }
                seq.end()
            }
            Self::Object(entries) => {
                let mut map = serializer.serialize_map(Some(entries.len()))?;
                for (key, value) in entries {
                    map.serialize_entry(key, value)?;
                }
                map.end()
            }
        }
    }
}

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

        impl<'de> Visitor<'de> for ValueVisitor {
            type Value = JsonValue;

            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_str("any JSON value")
            }

            fn visit_unit<E: de::Error>(self) -> Result<JsonValue, E> {
                Ok(JsonValue::Null)
            }

            fn visit_none<E: de::Error>(self) -> Result<JsonValue, E> {
                Ok(JsonValue::Null)
            }

            fn visit_some<D: Deserializer<'de>>(
                self,
                deserializer: D,
            ) -> Result<JsonValue, D::Error> {
                deserializer.deserialize_any(self)
            }

            fn visit_bool<E: de::Error>(self, value: bool) -> Result<JsonValue, E> {
                Ok(JsonValue::Bool(value))
            }

            fn visit_u64<E: de::Error>(self, value: u64) -> Result<JsonValue, E> {
                Ok(JsonValue::Unsigned(value))
            }

            fn visit_i64<E: de::Error>(self, value: i64) -> Result<JsonValue, E> {
                Ok(u64::try_from(value).map_or(JsonValue::Signed(value), JsonValue::Unsigned))
            }

            fn visit_f64<E: de::Error>(self, value: f64) -> Result<JsonValue, E> {
                Ok(JsonValue::Float(value))
            }

            fn visit_str<E: de::Error>(self, value: &str) -> Result<JsonValue, E> {
                Ok(JsonValue::String(value.into()))
            }

            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<JsonValue, A::Error> {
                let mut values = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(64));
                while let Some(value) = seq.next_element()? {
                    values.push(value);
                }
                Ok(JsonValue::Array(values))
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<JsonValue, A::Error> {
                let mut entries = BTreeMap::new();
                while let Some((key, value)) = map.next_entry::<CompactString, JsonValue>()? {
                    entries.insert(key, value);
                }
                Ok(JsonValue::Object(entries))
            }
        }

        deserializer.deserialize_any(ValueVisitor)
    }
}

/// The error of converting a [`JsonValue`] to a type.
///
/// discord.js counterpart: none (plain JavaScript values in discord.js).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JsonValueError(CompactString);

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

impl core::error::Error for JsonValueError {}

impl de::Error for JsonValueError {
    fn custom<T: core::fmt::Display>(message: T) -> Self {
        Self(compact_str::format_compact!("{message}"))
    }
}

impl<'de> IntoDeserializer<'de, JsonValueError> for &'de JsonValue {
    type Deserializer = Self;

    fn into_deserializer(self) -> Self {
        self
    }
}

impl<'de> Deserializer<'de> for &'de JsonValue {
    type Error = JsonValueError;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self {
            JsonValue::Null => visitor.visit_unit(),
            JsonValue::Bool(value) => visitor.visit_bool(*value),
            JsonValue::Unsigned(value) => visitor.visit_u64(*value),
            JsonValue::Signed(value) => visitor.visit_i64(*value),
            JsonValue::Float(value) => visitor.visit_f64(*value),
            JsonValue::String(value) => visitor.visit_borrowed_str(value),
            JsonValue::Array(values) => {
                let mut seq = SeqDeserializer::new(values.iter());
                let value = visitor.visit_seq(&mut seq)?;
                seq.end()?;
                Ok(value)
            }
            JsonValue::Object(entries) => {
                let mut map =
                    MapDeserializer::new(entries.iter().map(|(key, value)| (key.as_str(), value)));
                let value = visitor.visit_map(&mut map)?;
                map.end()?;
                Ok(value)
            }
        }
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self {
            JsonValue::Null => visitor.visit_none(),
            _ => visitor.visit_some(self),
        }
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_enum<V: Visitor<'de>>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        match self {
            JsonValue::String(variant) => visitor.visit_enum(UnitVariant(variant)),
            other => Err(de::Error::invalid_type(
                other.unexpected(),
                &"a string enum",
            )),
        }
    }

    forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
        unit unit_struct seq tuple tuple_struct map struct identifier ignored_any
    }
}

/// A string as a unit enum variant (externally tagged enums written as `"Variant"`).
struct UnitVariant<'de>(&'de str);

impl<'de> EnumAccess<'de> for UnitVariant<'de> {
    type Error = JsonValueError;
    type Variant = Self;

    fn variant_seed<V: DeserializeSeed<'de>>(
        self,
        seed: V,
    ) -> Result<(V::Value, Self), Self::Error> {
        let variant = seed.deserialize(de::value::BorrowedStrDeserializer::new(self.0))?;
        Ok((variant, self))
    }
}

impl<'de> VariantAccess<'de> for UnitVariant<'de> {
    type Error = JsonValueError;

    fn unit_variant(self) -> Result<(), Self::Error> {
        Ok(())
    }

    fn newtype_variant_seed<T: DeserializeSeed<'de>>(
        self,
        _seed: T,
    ) -> Result<T::Value, Self::Error> {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"a newtype variant",
        ))
    }

    fn tuple_variant<V: Visitor<'de>>(
        self,
        _len: usize,
        _visitor: V,
    ) -> Result<V::Value, Self::Error> {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"a tuple variant",
        ))
    }

    fn struct_variant<V: Visitor<'de>>(
        self,
        _fields: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value, Self::Error> {
        Err(de::Error::invalid_type(
            Unexpected::UnitVariant,
            &"a struct variant",
        ))
    }
}

#[cfg(test)]
mod tests {
    use core::mem::size_of;

    use super::*;

    #[test]
    fn unit_enums_convert_from_strings() {
        #[derive(Debug, PartialEq, Deserialize)]
        enum Kind {
            Text,
            Voice,
        }

        let value = JsonValue::String("Voice".into());
        assert_eq!(value.to_type::<Kind>(), Ok(Kind::Voice));
        assert!(JsonValue::String("Stage".into()).to_type::<Kind>().is_err());
        assert!(JsonValue::Unsigned(1).to_type::<Kind>().is_err());
    }

    #[test]
    fn every_kind_round_trips_through_json() {
        let json =
            r#"{"a":null,"b":true,"c":7,"d":-7,"e":1.5,"f":"text","g":[1,"x",[]],"h":{"z":{}}}"#;
        let value: JsonValue = serde_json::from_str(json).unwrap();
        let JsonValue::Object(fields) = &value else {
            panic!("{value:?}");
        };
        assert_eq!(fields["a"], JsonValue::Null);
        assert_eq!(fields["b"], JsonValue::Bool(true));
        assert_eq!(fields["c"], JsonValue::Unsigned(7));
        assert_eq!(fields["d"], JsonValue::Signed(-7));
        assert_eq!(fields["e"], JsonValue::Float(1.5));
        assert_eq!(fields["f"].as_str(), Some("text"));
        assert_eq!(fields["c"].as_str(), None);
        // Keys are sorted, so the JSON comes back as it was written here.
        assert_eq!(serde_json::to_string(&value).unwrap(), json);
    }

    #[test]
    fn values_convert_to_types() {
        #[derive(Debug, PartialEq, Deserialize)]
        struct Settings {
            name: String,
            limit: Option<u32>,
            tags: Vec<String>,
            ratio: f64,
            unit: (),
        }

        let value: JsonValue = serde_json::from_str(
            r#"{"name":"bot","limit":null,"tags":["a","b"],"ratio":-2,"unit":null}"#,
        )
        .unwrap();
        assert_eq!(
            value.to_type::<Settings>(),
            Ok(Settings {
                name: "bot".into(),
                limit: None,
                tags: vec!["a".into(), "b".into()],
                ratio: -2.0,
                unit: (),
            })
        );
        let some: JsonValue = serde_json::from_str("5").unwrap();
        assert_eq!(some.to_type::<Option<u32>>(), Ok(Some(5)));
        let map: JsonValue = serde_json::from_str(r#"{"x":1}"#).unwrap();
        assert_eq!(map.to_type::<BTreeMap<String, u8>>().unwrap()["x"], 1);
    }

    #[test]
    fn mismatches_are_errors_that_say_what_was_found() {
        #[derive(Debug, Deserialize)]
        #[expect(dead_code, reason = "only the error matters")]
        enum Shape {
            Unit,
            Newtype(u8),
            Tuple(u8, u8),
            Struct { side: u8 },
        }

        let error = JsonValue::Bool(true).to_type::<String>().unwrap_err();
        assert!(error.to_string().contains("boolean"), "{error}");
        let error = JsonValue::Array(Vec::new()).to_type::<Shape>().unwrap_err();
        assert!(error.to_string().contains("string enum"), "{error}");
        for variant in ["Newtype", "Tuple", "Struct"] {
            let error = JsonValue::String(variant.into())
                .to_type::<Shape>()
                .unwrap_err();
            assert!(error.to_string().contains("variant"), "{variant}: {error}");
        }
        let error: JsonValueError = de::Error::custom("custom");
        assert_eq!(error.to_string(), "custom");
    }

    #[test]
    fn size() {
        assert_eq!(size_of::<JsonValue>(), 32);
    }
}