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
//! Representations of activity linked or textual buttons.

use serde::{
    de::{Deserializer, Error as DeError, IgnoredAny, MapAccess, Visitor},
    ser::{SerializeStruct, Serializer},
    Deserialize, Serialize,
};
use std::fmt::{Formatter, Result as FmtResult};

/// Button used in an activity.
///
/// # serde
///
/// Activity buttons with a URL deserialize and serialize as a struct:
///
/// ```
/// use twilight_model::gateway::presence::activity_button::{
///     ActivityButtonLink,
///     ActivityButton,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// const JSON: &str = r#"{
///     "label": "a",
///     "url": "b"
/// }"#;
///
/// assert_eq!(
///     ActivityButton::Link(ActivityButtonLink {
///         label: "a".to_owned(),
///         url: "b".to_owned(),
///     }),
///     serde_json::from_str(JSON)?,
/// );
/// # Ok(()) }
/// ```
///
/// An activity button without a URL - an [`ActivityButtonText`] - will
/// deserialize and serialize as a string. This means that a textual activity
/// button with a label of "test" will serialize as simply the string "test" and
/// vice versa.
///
/// ```
/// use twilight_model::gateway::presence::activity_button::{
///     ActivityButtonText,
///     ActivityButton,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// assert_eq!(
///     ActivityButton::Text(ActivityButtonText {
///         label: "test".to_owned(),
///     }),
///     serde_json::from_str(r#""test""#)?,
/// );
/// # Ok(()) }
/// ```
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum ActivityButton {
    /// Activity button is a link.
    Link(ActivityButtonLink),
    /// Activity button is textual.
    Text(ActivityButtonText),
}

impl ActivityButton {
    /// Whether the variant is a link button.
    pub const fn is_link(&self) -> bool {
        matches!(self, Self::Link(_))
    }

    /// Whether the variant is a text button.
    pub const fn is_text(&self) -> bool {
        matches!(self, Self::Text(_))
    }

    /// Retrieve an immutable reference to the label.
    pub fn label(&self) -> &str {
        match self {
            Self::Link(link) => &link.label,
            Self::Text(text) => &text.label,
        }
    }

    /// Retrieve an immutable reference to the URL if this is a link activity
    /// button.
    pub fn url(&self) -> Option<&str> {
        if let Self::Link(link) = self {
            Some(&link.url)
        } else {
            None
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum ActivityButtonField {
    Label,
    Url,
}

struct ActivityButtonVisitor;

impl<'de> Visitor<'de> for ActivityButtonVisitor {
    type Value = ActivityButton;

    fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("activity button struct or string")
    }

    fn visit_string<E: DeError>(self, v: String) -> Result<Self::Value, E> {
        Ok(ActivityButton::Text(ActivityButtonText { label: v }))
    }

    fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {
        Ok(ActivityButton::Text(ActivityButtonText {
            label: v.to_owned(),
        }))
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
        let mut label = None;
        let mut url = None;

        let span = tracing::trace_span!("deserializing activity button");
        let _span_enter = span.enter();

        loop {
            let span_child = tracing::trace_span!("iterating over element");
            let _span_child_enter = span_child.enter();

            let key = match map.next_key() {
                Ok(Some(key)) => {
                    tracing::trace!(?key, "found key");

                    key
                }
                Ok(None) => break,
                Err(why) => {
                    // Encountered when we run into an unknown key.
                    map.next_value::<IgnoredAny>()?;

                    tracing::trace!("ran into an unknown key: {:?}", why);

                    continue;
                }
            };

            match key {
                ActivityButtonField::Label => {
                    if label.is_some() {
                        return Err(DeError::duplicate_field("label"));
                    }

                    label = Some(map.next_value()?);
                }
                ActivityButtonField::Url => {
                    if url.is_some() {
                        return Err(DeError::duplicate_field("url"));
                    }

                    url = Some(map.next_value()?);
                }
            }
        }

        let label = label.ok_or_else(|| DeError::missing_field("label"))?;
        let url = url.ok_or_else(|| DeError::missing_field("url"))?;

        tracing::trace!(
            %label,
            ?url,
        );

        Ok(ActivityButton::Link(ActivityButtonLink { label, url }))
    }
}

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

impl Serialize for ActivityButton {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Link(link) => {
                let mut state = serializer.serialize_struct("ActivityButton", 2)?;

                state.serialize_field("label", &link.label)?;
                state.serialize_field("url", &link.url)?;

                state.end()
            }
            Self::Text(text) => serializer.serialize_str(&text.label),
        }
    }
}

/// Button used in an activity with a URL.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ActivityButtonLink {
    /// Text shown on the button.
    pub label: String,
    /// URL opened when clicking the button.
    pub url: String,
}

/// Button used in an activity without a URL.
///
/// # serde
///
/// Textual activity buttons deserialize and serialize as a string. This means
/// that a textual activity button with a label of "test" will serialize as
/// simply the string "test" and vice versa.
///
/// ```ignore
/// use twilight_model::gateway::presence::activity_button::ActivityButtonText;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// assert_eq!(
///     ActivityButtonText { label: "test".to_owned() },
///     serde_json::from_str(r#""test""#)?,
/// );
/// # Ok(()) }
/// ```
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ActivityButtonText {
    /// Text shown on the button.
    pub label: String,
}
#[derive(Debug, Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum ActivityButtonTextField {
    Label,
}

struct ActivityButtonTextVisitor;

impl<'de> Visitor<'de> for ActivityButtonTextVisitor {
    type Value = ActivityButtonText;

    fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("activity button string")
    }

    fn visit_string<E: DeError>(self, v: String) -> Result<Self::Value, E> {
        Ok(ActivityButtonText { label: v })
    }

    fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {
        Ok(ActivityButtonText {
            label: v.to_owned(),
        })
    }
}

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

impl Serialize for ActivityButtonText {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.label)
    }
}

#[cfg(test)]
mod tests {
    use super::{ActivityButton, ActivityButtonLink, ActivityButtonText};
    use serde::{Deserialize, Serialize};
    use serde_test::Token;
    use static_assertions::{assert_fields, assert_impl_all};
    use std::fmt::Debug;

    assert_fields!(ActivityButtonLink: label, url);
    assert_impl_all!(
        ActivityButtonLink: Clone,
        Debug,
        Deserialize<'static>,
        Eq,
        PartialEq,
        Serialize
    );
    assert_fields!(ActivityButtonText: label);
    assert_impl_all!(
        ActivityButtonText: Clone,
        Debug,
        Deserialize<'static>,
        Eq,
        PartialEq,
        Serialize
    );
    assert_impl_all!(
        ActivityButton: Clone,
        Debug,
        Deserialize<'static>,
        Eq,
        PartialEq,
        Serialize
    );

    fn link() -> ActivityButtonLink {
        ActivityButtonLink {
            label: "a".to_owned(),
            url: "b".to_owned(),
        }
    }

    fn text() -> ActivityButtonText {
        ActivityButtonText {
            label: "a".to_owned(),
        }
    }

    #[test]
    fn test_activity_button_link() {
        serde_test::assert_de_tokens(
            &link(),
            &[
                Token::Struct {
                    name: "ActivityButtonLink",
                    len: 2,
                },
                Token::Str("label"),
                Token::Str("a"),
                Token::Str("url"),
                Token::Str("b"),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_activity_button_text() {
        serde_test::assert_de_tokens(&text(), &[Token::Str("a")]);
    }

    #[test]
    fn test_activity_button_with_url() {
        serde_test::assert_tokens(
            &ActivityButton::Link(link()),
            &[
                Token::Struct {
                    name: "ActivityButton",
                    len: 2,
                },
                Token::Str("label"),
                Token::Str("a"),
                Token::Str("url"),
                Token::Str("b"),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn test_activity_button_without_url() {
        serde_test::assert_tokens(&ActivityButton::Text(text()), &[Token::Str("a")]);
    }
}