Skip to main content

djs_model/util/
patch.rs

1//! [`Patch`], the value of a request field that can be left unchanged, cleared or set.
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4
5/// A field of a modify request that can be left unchanged, cleared or set (D-083, D-101).
6///
7/// Discord's `PATCH` endpoints distinguish three cases for nullable fields: a field that is
8/// left out keeps its current value, `null` clears it, and a value sets it. `Patch` names
9/// these cases after what they do:
10///
11/// | Variant | Sent as | Effect |
12/// |---|---|---|
13/// | [`Keep`](Self::Keep) (default) | *(field left out)* | the value stays as it is |
14/// | [`Clear`](Self::Clear) | `null` | the value is removed or reset |
15/// | [`Set`](Self::Set) | the value | the value is replaced |
16///
17/// Request bodies skip `Keep` fields with `#[serde(skip_serializing_if = "Patch::is_keep")]`.
18/// Serializing a `Keep` on its own is an error, because no JSON value means "leave out".
19///
20/// discord.js counterpart: passing `undefined`, `null` or a value in the options of an edit
21/// method.
22///
23/// # Examples
24///
25/// ```
26/// use djs_model::util::Patch;
27///
28/// let mut nickname: Patch<String> = Patch::default();
29/// assert!(nickname.is_keep());
30///
31/// nickname = "Ferris".to_owned().into();
32/// assert_eq!(nickname, Patch::Set("Ferris".to_owned()));
33///
34/// // `None` clears, `Some` sets.
35/// assert_eq!(Patch::<u32>::from(None), Patch::Clear);
36/// assert_eq!(Patch::from(Some(5)), Patch::Set(5));
37///
38/// assert_eq!(serde_json::to_string(&Patch::<u32>::Clear).unwrap(), "null");
39/// assert_eq!(serde_json::to_string(&Patch::Set(5)).unwrap(), "5");
40/// ```
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42pub enum Patch<T> {
43    /// Leave the current value unchanged: the field is not sent.
44    #[default]
45    Keep,
46    /// Clear the value: the field is sent as `null`.
47    Clear,
48    /// Set the value.
49    Set(T),
50}
51
52impl<T> Patch<T> {
53    /// Returns `true` for [`Keep`](Self::Keep) (used to skip the field when serializing).
54    ///
55    /// discord.js counterpart: none (an omitted option in discord.js).
56    #[must_use]
57    pub const fn is_keep(&self) -> bool {
58        matches!(self, Self::Keep)
59    }
60
61    /// Returns `true` for [`Clear`](Self::Clear).
62    ///
63    /// discord.js counterpart: none (a `null` option in discord.js).
64    #[must_use]
65    pub const fn is_clear(&self) -> bool {
66        matches!(self, Self::Clear)
67    }
68
69    /// Returns `true` for [`Set`](Self::Set).
70    ///
71    /// discord.js counterpart: none (a given option in discord.js).
72    #[must_use]
73    pub const fn is_set(&self) -> bool {
74        matches!(self, Self::Set(_))
75    }
76
77    /// Returns the value of [`Set`](Self::Set), if any.
78    ///
79    /// discord.js counterpart: none (a given option in discord.js).
80    #[must_use]
81    pub fn into_set(self) -> Option<T> {
82        match self {
83            Self::Set(value) => Some(value),
84            Self::Keep | Self::Clear => None,
85        }
86    }
87
88    /// Borrows the value: `Patch<&T>`.
89    ///
90    /// discord.js counterpart: none (options are plain objects in discord.js).
91    #[must_use]
92    pub const fn as_ref(&self) -> Patch<&T> {
93        match self {
94            Self::Keep => Patch::Keep,
95            Self::Clear => Patch::Clear,
96            Self::Set(value) => Patch::Set(value),
97        }
98    }
99
100    /// Converts the value of [`Set`](Self::Set) with `f`, keeping `Keep` and `Clear`.
101    ///
102    /// discord.js counterpart: none (options are plain objects in discord.js).
103    #[must_use]
104    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Patch<U> {
105        match self {
106            Self::Keep => Patch::Keep,
107            Self::Clear => Patch::Clear,
108            Self::Set(value) => Patch::Set(f(value)),
109        }
110    }
111}
112
113impl<T> From<T> for Patch<T> {
114    /// Sets the value.
115    fn from(value: T) -> Self {
116        Self::Set(value)
117    }
118}
119
120impl<T> From<Option<T>> for Patch<T> {
121    /// `Some` sets the value, `None` clears it.
122    fn from(value: Option<T>) -> Self {
123        value.map_or(Self::Clear, Self::Set)
124    }
125}
126
127impl<T: Serialize> Serialize for Patch<T> {
128    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
129        match self {
130            Self::Set(value) => value.serialize(serializer),
131            Self::Clear => serializer.serialize_none(),
132            Self::Keep => Err(serde::ser::Error::custom(
133                "`Patch::Keep` has no JSON value; skip the field with \
134                 `#[serde(skip_serializing_if = \"Patch::is_keep\")]`",
135            )),
136        }
137    }
138}
139
140impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch<T> {
141    /// `null` is [`Clear`](Self::Clear) and a value is [`Set`](Self::Set); a missing field
142    /// becomes [`Keep`](Self::Keep) with `#[serde(default)]`.
143    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
144        Option::<T>::deserialize(deserializer).map(Self::from)
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[derive(Serialize, Deserialize, Debug, PartialEq)]
153    struct Body {
154        #[serde(default, skip_serializing_if = "Patch::is_keep")]
155        nick: Patch<String>,
156        #[serde(default, skip_serializing_if = "Patch::is_keep")]
157        channel_id: Patch<u64>,
158    }
159
160    #[test]
161    fn fields_are_left_out_cleared_or_set() {
162        let body = Body {
163            nick: Patch::Set("Ferris".into()),
164            channel_id: Patch::Clear,
165        };
166        let json = serde_json::to_string(&body).unwrap();
167        assert_eq!(json, r#"{"nick":"Ferris","channel_id":null}"#);
168        assert_eq!(serde_json::from_str::<Body>(&json).unwrap(), body);
169
170        let unchanged = Body {
171            nick: Patch::Keep,
172            channel_id: Patch::Keep,
173        };
174        assert_eq!(serde_json::to_string(&unchanged).unwrap(), "{}");
175        assert_eq!(serde_json::from_str::<Body>("{}").unwrap(), unchanged);
176    }
177
178    #[test]
179    fn keep_alone_cannot_be_serialized() {
180        let error = serde_json::to_string(&Patch::<u8>::Keep).unwrap_err();
181        assert!(error.to_string().contains("skip_serializing_if"), "{error}");
182    }
183
184    #[test]
185    fn helpers() {
186        let set = Patch::Set(2);
187        assert!(set.is_set() && !set.is_keep() && !set.is_clear());
188        assert_eq!(set.map(|value| value * 2), Patch::Set(4));
189        assert_eq!(set.as_ref(), Patch::Set(&2));
190        assert_eq!(set.into_set(), Some(2));
191        assert_eq!(Patch::<u8>::Clear.into_set(), None);
192        assert_eq!(Patch::<u8>::Clear.map(u16::from), Patch::Clear);
193        assert_eq!(Patch::<u8>::Keep.map(u16::from), Patch::Keep);
194    }
195}