twilight_model/user/
mod.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
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
mod avatar_decoration_data;
mod connection;
mod connection_visibility;
mod current_user;
mod current_user_guild;
mod flags;
mod premium_type;

pub use self::{
    avatar_decoration_data::AvatarDecorationData, connection::Connection,
    connection_visibility::ConnectionVisibility, current_user::CurrentUser,
    current_user_guild::CurrentUserGuild, flags::UserFlags, premium_type::PremiumType,
};

use crate::{
    id::{marker::UserMarker, Id},
    util::image_hash::ImageHash,
};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter, Result as FmtResult};

pub(crate) mod discriminator {
    use super::DiscriminatorDisplay;
    use serde::{
        de::{Deserializer, Error as DeError, Visitor},
        ser::Serializer,
    };
    use std::fmt::{Formatter, Result as FmtResult};

    struct DiscriminatorVisitor;

    impl<'de> Visitor<'de> for DiscriminatorVisitor {
        type Value = u16;

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

        fn visit_u64<E: DeError>(self, value: u64) -> Result<Self::Value, E> {
            value.try_into().map_err(DeError::custom)
        }

        fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
            value.parse().map_err(DeError::custom)
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u16, D::Error> {
        deserializer.deserialize_any(DiscriminatorVisitor)
    }

    // Allow this lint because taking a reference is required by serde.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    pub fn serialize<S: Serializer>(value: &u16, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(&DiscriminatorDisplay(*value))
    }
}

/// Display formatter for a user discriminator.
///
/// When formatted this will pad a discriminator with zeroes.
///
/// This may be preferable to use instead of using `format!` to avoid a String
/// allocation, and may also be preferable to use rather than defining your own
/// implementations via `format_args!("{discriminator:04}")`.
///
/// # Examples
///
/// Display the discriminator value `16` as a string:
///
/// ```
/// use twilight_model::user::DiscriminatorDisplay;
///
/// let display = DiscriminatorDisplay::new(16);
/// assert_eq!("0016", display.to_string());
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[must_use = "display implementations should be formatted"]
pub struct DiscriminatorDisplay(u16);

impl DiscriminatorDisplay {
    /// Create a new display formatter for a discriminator.
    ///
    /// # Examples
    ///
    /// Display the discriminator value `5` as a string:
    ///
    /// ```
    /// use twilight_model::user::DiscriminatorDisplay;
    ///
    /// let display = DiscriminatorDisplay::new(5);
    /// assert_eq!("0005", display.to_string());
    /// ```
    pub const fn new(discriminator: u16) -> Self {
        Self(discriminator)
    }

    /// Retrieve the inner discriminator value.
    pub const fn get(self) -> u16 {
        self.0
    }
}

impl Display for DiscriminatorDisplay {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        // Pad the formatted value with zeroes depending on the number of
        // digits.
        //
        // If the value is [1000, u16::MAX] then we don't need to pad.
        match self.0 {
            1..=9 => f.write_str("000")?,
            10..=99 => f.write_str("00")?,
            100..=999 => f.write_str("0")?,
            _ => {}
        }

        Display::fmt(&self.0, f)
    }
}

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct User {
    /// Accent color of the user's banner.
    ///
    /// This is an integer representation of a hexadecimal color code.
    pub accent_color: Option<u32>,
    pub avatar: Option<ImageHash>,
    /// Hash of the user's avatar decoration.
    pub avatar_decoration: Option<ImageHash>,
    /// Data for the user's avatar decoration.
    pub avatar_decoration_data: Option<AvatarDecorationData>,
    /// Hash of the user's banner image.
    pub banner: Option<ImageHash>,
    #[serde(default)]
    pub bot: bool,
    /// Discriminator used to differentiate people with the same username.
    ///
    /// Note: Users that have migrated to the new username system will have a
    /// discriminator of `0`.
    ///
    /// # Formatting
    ///
    /// Because discriminators are stored as an integer they're not in the
    /// format of Discord user tags due to a lack of padding with zeros. The
    /// [`discriminator`] method can be used to retrieve a formatter to pad the
    /// discriminator with zeros.
    ///
    /// # serde
    ///
    /// The discriminator field can be deserialized from either a string or an
    /// integer. The field will always serialize into a string due to that being
    /// the type Discord's API uses.
    ///
    /// [`discriminator`]: Self::discriminator
    #[serde(with = "discriminator")]
    pub discriminator: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flags: Option<UserFlags>,
    /// User's global display name, if set. For bots, this is the application name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub global_name: Option<String>,
    pub id: Id<UserMarker>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mfa_enabled: Option<bool>,
    #[serde(rename = "username")]
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub premium_type: Option<PremiumType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_flags: Option<UserFlags>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verified: Option<bool>,
}

impl User {
    /// Create a [`Display`] formatter for a user discriminator that pads the
    /// discriminator with zeros up to 4 digits.
    ///
    /// [`Display`]: core::fmt::Display
    pub const fn discriminator(&self) -> DiscriminatorDisplay {
        DiscriminatorDisplay::new(self.discriminator)
    }
}

#[cfg(test)]
mod tests {
    use super::{DiscriminatorDisplay, PremiumType, User, UserFlags};
    use crate::{id::Id, test::image_hash};
    use serde_test::Token;
    use static_assertions::assert_impl_all;
    use std::{fmt::Debug, hash::Hash};

    assert_impl_all!(
        DiscriminatorDisplay: Clone,
        Copy,
        Debug,
        Eq,
        Hash,
        PartialEq,
        Send,
        Sync
    );

    fn user_tokens(discriminator_token: Token) -> Vec<Token> {
        vec![
            Token::Struct {
                name: "User",
                len: 17,
            },
            Token::Str("accent_color"),
            Token::None,
            Token::Str("avatar"),
            Token::Some,
            Token::Str(image_hash::AVATAR_INPUT),
            Token::Str("avatar_decoration"),
            Token::Some,
            Token::Str(image_hash::AVATAR_DECORATION_INPUT),
            Token::Str("avatar_decoration_data"),
            Token::None,
            Token::Str("banner"),
            Token::Some,
            Token::Str(image_hash::BANNER_INPUT),
            Token::Str("bot"),
            Token::Bool(false),
            Token::Str("discriminator"),
            discriminator_token,
            Token::Str("email"),
            Token::Some,
            Token::Str("address@example.com"),
            Token::Str("flags"),
            Token::Some,
            Token::U64(131_584),
            Token::Str("global_name"),
            Token::Some,
            Token::Str("test"),
            Token::Str("id"),
            Token::NewtypeStruct { name: "Id" },
            Token::Str("1"),
            Token::Str("locale"),
            Token::Some,
            Token::Str("en-us"),
            Token::Str("mfa_enabled"),
            Token::Some,
            Token::Bool(true),
            Token::Str("username"),
            Token::Str("test"),
            Token::Str("premium_type"),
            Token::Some,
            Token::U8(2),
            Token::Str("public_flags"),
            Token::Some,
            Token::U64(131_584),
            Token::Str("verified"),
            Token::Some,
            Token::Bool(true),
            Token::StructEnd,
        ]
    }

    fn user_tokens_complete(discriminator_token: Token) -> Vec<Token> {
        vec![
            Token::Struct {
                name: "User",
                len: 18,
            },
            Token::Str("accent_color"),
            Token::None,
            Token::Str("avatar"),
            Token::Some,
            Token::Str(image_hash::AVATAR_INPUT),
            Token::Str("avatar_decoration"),
            Token::Some,
            Token::Str(image_hash::AVATAR_DECORATION_INPUT),
            Token::Str("avatar_decoration_data"),
            Token::None,
            Token::Str("banner"),
            Token::Some,
            Token::Str(image_hash::BANNER_INPUT),
            Token::Str("bot"),
            Token::Bool(false),
            Token::Str("discriminator"),
            discriminator_token,
            Token::Str("email"),
            Token::Some,
            Token::Str("address@example.com"),
            Token::Str("flags"),
            Token::Some,
            Token::U64(131_584),
            Token::Str("global_name"),
            Token::Some,
            Token::Str("test"),
            Token::Str("id"),
            Token::NewtypeStruct { name: "Id" },
            Token::Str("1"),
            Token::Str("locale"),
            Token::Some,
            Token::Str("en-us"),
            Token::Str("mfa_enabled"),
            Token::Some,
            Token::Bool(true),
            Token::Str("username"),
            Token::Str("test"),
            Token::Str("premium_type"),
            Token::Some,
            Token::U8(2),
            Token::Str("public_flags"),
            Token::Some,
            Token::U64(131_584),
            Token::Str("system"),
            Token::Some,
            Token::Bool(true),
            Token::Str("verified"),
            Token::Some,
            Token::Bool(true),
            Token::StructEnd,
        ]
    }

    #[test]
    fn discriminator_display() {
        assert_eq!(3030, DiscriminatorDisplay::new(3030).get());
        assert_eq!("0003", DiscriminatorDisplay::new(3).to_string());
        assert_eq!("0033", DiscriminatorDisplay::new(33).to_string());
        assert_eq!("0333", DiscriminatorDisplay::new(333).to_string());
        assert_eq!("3333", DiscriminatorDisplay::new(3333).to_string());
        assert_eq!("0", DiscriminatorDisplay::new(0).to_string());
    }

    #[test]
    fn user() {
        let value = User {
            accent_color: None,
            avatar: Some(image_hash::AVATAR),
            avatar_decoration: Some(image_hash::AVATAR_DECORATION),
            avatar_decoration_data: None,
            banner: Some(image_hash::BANNER),
            bot: false,
            discriminator: 1,
            email: Some("address@example.com".to_owned()),
            flags: Some(UserFlags::PREMIUM_EARLY_SUPPORTER | UserFlags::VERIFIED_DEVELOPER),
            global_name: Some("test".to_owned()),
            id: Id::new(1),
            locale: Some("en-us".to_owned()),
            mfa_enabled: Some(true),
            name: "test".to_owned(),
            premium_type: Some(PremiumType::Nitro),
            public_flags: Some(UserFlags::PREMIUM_EARLY_SUPPORTER | UserFlags::VERIFIED_DEVELOPER),
            system: None,
            verified: Some(true),
        };

        // Deserializing a user with a string discriminator (which Discord
        // provides)
        serde_test::assert_tokens(&value, &user_tokens(Token::Str("0001")));

        // Deserializing a user with an integer discriminator. Userland code
        // may have this due to being a more compact memory representation of a
        // discriminator.
        serde_test::assert_de_tokens(&value, &user_tokens(Token::U64(1)));
    }

    #[test]
    fn user_no_discriminator() {
        let value = User {
            accent_color: None,
            avatar: Some(image_hash::AVATAR),
            avatar_decoration: Some(image_hash::AVATAR_DECORATION),
            avatar_decoration_data: None,
            banner: Some(image_hash::BANNER),
            bot: false,
            discriminator: 0,
            email: Some("address@example.com".to_owned()),
            flags: Some(UserFlags::PREMIUM_EARLY_SUPPORTER | UserFlags::VERIFIED_DEVELOPER),
            global_name: Some("test".to_owned()),
            id: Id::new(1),
            locale: Some("en-us".to_owned()),
            mfa_enabled: Some(true),
            name: "test".to_owned(),
            premium_type: Some(PremiumType::Nitro),
            public_flags: Some(UserFlags::PREMIUM_EARLY_SUPPORTER | UserFlags::VERIFIED_DEVELOPER),
            system: None,
            verified: Some(true),
        };

        // Users migrated to the new username system will have a placeholder discriminator of 0,
        // You can check if a user has migrated by seeing if their discriminator is 0.
        // Read more here: https://discord.com/developers/docs/change-log#identifying-migrated-users
        serde_test::assert_tokens(&value, &user_tokens(Token::Str("0")));
        serde_test::assert_de_tokens(&value, &user_tokens(Token::U64(0)));
    }

    #[test]
    fn user_complete() {
        let value = User {
            accent_color: None,
            avatar: Some(image_hash::AVATAR),
            avatar_decoration: Some(image_hash::AVATAR_DECORATION),
            avatar_decoration_data: None,
            banner: Some(image_hash::BANNER),
            bot: false,
            discriminator: 1,
            email: Some("address@example.com".to_owned()),
            flags: Some(UserFlags::PREMIUM_EARLY_SUPPORTER | UserFlags::VERIFIED_DEVELOPER),
            global_name: Some("test".to_owned()),
            id: Id::new(1),
            locale: Some("en-us".to_owned()),
            mfa_enabled: Some(true),
            name: "test".to_owned(),
            premium_type: Some(PremiumType::Nitro),
            public_flags: Some(UserFlags::PREMIUM_EARLY_SUPPORTER | UserFlags::VERIFIED_DEVELOPER),
            system: Some(true),
            verified: Some(true),
        };

        // Deserializing a user with a string discriminator (which Discord
        // provides)
        serde_test::assert_tokens(&value, &user_tokens_complete(Token::Str("0001")));

        // Deserializing a user with an integer discriminator. Userland code
        // may have this due to being a more compact memory representation of a
        // discriminator.
        serde_test::assert_de_tokens(&value, &user_tokens_complete(Token::U64(1)));
    }
}