diff options
| author | acdenisSK <[email protected]> | 2017-08-24 15:26:49 +0200 |
|---|---|---|
| committer | acdenisSK <[email protected]> | 2017-08-24 16:36:01 +0200 |
| commit | b3a5bc89ad1c09290fb1c15ca3b36fe17c3796f3 (patch) | |
| tree | 315e16f7b252d22b5f832302e722a85c9e6a9b6e /src/model | |
| parent | Allow FromStr for User to use REST (#147) (diff) | |
| download | serenity-b3a5bc89ad1c09290fb1c15ca3b36fe17c3796f3.tar.xz serenity-b3a5bc89ad1c09290fb1c15ca3b36fe17c3796f3.zip | |
Revamp `RwLock` usage in the lib
Also not quite sure if they goofed rustfmt or something, but its changes it did were a bit bizarre.
Diffstat (limited to 'src/model')
| -rw-r--r-- | src/model/channel/channel_id.rs | 32 | ||||
| -rw-r--r-- | src/model/channel/group.rs | 22 | ||||
| -rw-r--r-- | src/model/channel/guild_channel.rs | 16 | ||||
| -rw-r--r-- | src/model/channel/message.rs | 29 | ||||
| -rw-r--r-- | src/model/channel/mod.rs | 59 | ||||
| -rw-r--r-- | src/model/channel/private_channel.rs | 13 | ||||
| -rw-r--r-- | src/model/channel/reaction.rs | 51 | ||||
| -rw-r--r-- | src/model/event.rs | 62 | ||||
| -rw-r--r-- | src/model/gateway.rs | 36 | ||||
| -rw-r--r-- | src/model/guild/audit_log.rs | 16 | ||||
| -rw-r--r-- | src/model/guild/guild_id.rs | 10 | ||||
| -rw-r--r-- | src/model/guild/integration.rs | 3 | ||||
| -rw-r--r-- | src/model/guild/member.rs | 35 | ||||
| -rw-r--r-- | src/model/guild/mod.rs | 82 | ||||
| -rw-r--r-- | src/model/guild/partial_guild.rs | 24 | ||||
| -rw-r--r-- | src/model/guild/role.rs | 7 | ||||
| -rw-r--r-- | src/model/invite.rs | 3 | ||||
| -rw-r--r-- | src/model/misc.rs | 33 | ||||
| -rw-r--r-- | src/model/mod.rs | 47 | ||||
| -rw-r--r-- | src/model/user.rs | 104 | ||||
| -rw-r--r-- | src/model/utils.rs | 15 | ||||
| -rw-r--r-- | src/model/webhook.rs | 7 |
22 files changed, 291 insertions, 415 deletions
diff --git a/src/model/channel/channel_id.rs b/src/model/channel/channel_id.rs index d8ccc71..cf9e41c 100644 --- a/src/model/channel/channel_id.rs +++ b/src/model/channel/channel_id.rs @@ -1,5 +1,6 @@ use std::fmt::{Display, Formatter, Result as FmtResult}; use model::*; +use internal::RwLockExt; #[cfg(feature = "model")] use std::borrow::Cow; @@ -99,7 +100,7 @@ impl ChannelId { /// [`Message::delete`]: struct.Message.html#method.delete /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html #[inline] - pub fn delete_message<M: Into<MessageId>>(&self, message_id: M) -> Result<()> { +pub fn delete_message<M: Into<MessageId>>(&self, message_id: M) -> Result<()>{ http::delete_message(self.0, message_id.into().0) } @@ -186,7 +187,7 @@ impl ChannelId { /// [`Channel`]: enum.Channel.html /// [Manage Channel]: permissions/constant.MANAGE_CHANNELS.html #[inline] - pub fn edit<F: FnOnce(EditChannel) -> EditChannel>(&self, f: F) -> Result<GuildChannel> { +pub fn edit<F: FnOnce(EditChannel) -> EditChannel>(&self, f: F) -> Result<GuildChannel>{ http::edit_channel(self.0, &f(EditChannel::default()).0) } @@ -255,13 +256,12 @@ impl ChannelId { /// [Read Message History]: permissions/constant.READ_MESSAGE_HISTORY.html #[inline] pub fn message<M: Into<MessageId>>(&self, message_id: M) -> Result<Message> { - http::get_message(self.0, message_id.into().0).map( - |mut msg| { + http::get_message(self.0, message_id.into().0) + .map(|mut msg| { msg.transform_content(); msg - }, - ) + }) } /// Gets messages from the channel. @@ -306,11 +306,9 @@ impl ChannelId { None => return None, } { Guild(channel) => channel.read().unwrap().name().to_string(), - Group(channel) => { - match channel.read().unwrap().name() { - Cow::Borrowed(name) => name.to_string(), - Cow::Owned(name) => name, - } + Group(channel) => match channel.read().unwrap().name() { + Cow::Borrowed(name) => name.to_string(), + Cow::Owned(name) => name, }, Private(channel) => channel.read().unwrap().name(), }) @@ -512,9 +510,9 @@ impl From<Channel> for ChannelId { /// Gets the Id of a `Channel`. fn from(channel: Channel) -> ChannelId { match channel { - Channel::Group(group) => group.read().unwrap().channel_id, - Channel::Guild(ch) => ch.read().unwrap().id, - Channel::Private(ch) => ch.read().unwrap().id, + Channel::Group(group) => group.with(|g| g.channel_id), + Channel::Guild(ch) => ch.with(|c| c.id), + Channel::Private(ch) => ch.with(|c| c.id), } } } @@ -523,9 +521,9 @@ impl<'a> From<&'a Channel> for ChannelId { /// Gets the Id of a `Channel`. fn from(channel: &Channel) -> ChannelId { match *channel { - Channel::Group(ref group) => group.read().unwrap().channel_id, - Channel::Guild(ref ch) => ch.read().unwrap().id, - Channel::Private(ref ch) => ch.read().unwrap().id, + Channel::Group(ref group) => group.with(|g| g.channel_id), + Channel::Guild(ref ch) => ch.with(|c| c.id), + Channel::Private(ref ch) => ch.with(|c| c.id), } } } diff --git a/src/model/channel/group.rs b/src/model/channel/group.rs index 7007ad6..94483ec 100644 --- a/src/model/channel/group.rs +++ b/src/model/channel/group.rs @@ -1,5 +1,6 @@ use chrono::{DateTime, FixedOffset}; use model::*; +use internal::RwLockExt; #[cfg(feature = "model")] use std::borrow::Cow; @@ -123,11 +124,8 @@ impl Group { reaction_type: R) -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { - self.channel_id.delete_reaction( - message_id, - user_id, - reaction_type, - ) + self.channel_id + .delete_reaction(message_id, user_id, reaction_type) } /// Edits a [`Message`] in the channel given its Id. @@ -208,12 +206,12 @@ impl Group { Some(ref name) => Cow::Borrowed(name), None => { let mut name = match self.recipients.values().nth(0) { - Some(recipient) => recipient.read().unwrap().name.clone(), + Some(recipient) => recipient.with(|c| c.name.clone()), None => return Cow::Borrowed("Empty Group"), }; for recipient in self.recipients.values().skip(1) { - let _ = write!(name, ", {}", recipient.read().unwrap().name); + let _ = write!(name, ", {}", recipient.with(|r| r.name.clone())); } Cow::Owned(name) @@ -245,12 +243,8 @@ impl Group { after: Option<U>) -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.channel_id.reaction_users( - message_id, - reaction_type, - limit, - after, - ) + self.channel_id + .reaction_users(message_id, reaction_type, limit, after) } /// Removes a recipient from the group. If the recipient is already not in @@ -315,7 +309,7 @@ impl Group { /// [`CreateMessage`]: ../builder/struct.CreateMessage.html /// [Send Messages]: permissions/constant.SEND_MESSAGES.html #[inline] - pub fn send_message<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message> { +pub fn send_message<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message>{ self.channel_id.send_message(f) } diff --git a/src/model/channel/guild_channel.rs b/src/model/channel/guild_channel.rs index 3fadd72..620ba93 100644 --- a/src/model/channel/guild_channel.rs +++ b/src/model/channel/guild_channel.rs @@ -300,7 +300,6 @@ impl GuildChannel { /// ``` pub fn edit<F>(&mut self, f: F) -> Result<()> where F: FnOnce(EditChannel) -> EditChannel { - #[cfg(feature = "cache")] { let req = permissions::MANAGE_CHANNELS; @@ -311,10 +310,7 @@ impl GuildChannel { } let mut map = Map::new(); - map.insert( - "name".to_owned(), - Value::String(self.name.clone()), - ); + map.insert("name".to_owned(), Value::String(self.name.clone())); map.insert( "position".to_owned(), Value::Number(Number::from(self.position)), @@ -543,12 +539,8 @@ impl GuildChannel { after: Option<U>) -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.id.reaction_users( - message_id, - reaction_type, - limit, - after, - ) + self.id + .reaction_users(message_id, reaction_type, limit, after) } /// Sends a message with just the given message content in the channel. @@ -607,7 +599,7 @@ impl GuildChannel { /// [`ModelError::MessageTooLong`]: enum.ModelError.html#variant.MessageTooLong /// [`Message`]: struct.Message.html /// [Send Messages]: permissions/constant.SEND_MESSAGES.html - pub fn send_message<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message> { +pub fn send_message<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message>{ #[cfg(feature = "cache")] { let req = permissions::SEND_MESSAGES; diff --git a/src/model/channel/message.rs b/src/model/channel/message.rs index 27f4e31..399d351 100644 --- a/src/model/channel/message.rs +++ b/src/model/channel/message.rs @@ -291,10 +291,9 @@ impl Message { } // And finally replace everyone and here mentions. - result.replace("@everyone", "@\u{200B}everyone").replace( - "@here", - "@\u{200B}here", - ) + result + .replace("@everyone", "@\u{200B}everyone") + .replace("@here", "@\u{200B}here") } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a @@ -320,12 +319,8 @@ impl Message { after: Option<U>) -> Result<Vec<User>> where R: Into<ReactionType>, U: Into<UserId> { - self.channel_id.reaction_users( - self.id, - reaction_type, - limit, - after, - ) + self.channel_id + .reaction_users(self.id, reaction_type, limit, after) } /// Returns the associated `Guild` for the message if one is in the cache. @@ -338,9 +333,8 @@ impl Message { /// [`guild_id`]: #method.guild_id #[cfg(feature = "cache")] pub fn guild(&self) -> Option<Arc<RwLock<Guild>>> { - self.guild_id().and_then(|guild_id| { - CACHE.read().unwrap().guild(guild_id) - }) + self.guild_id() + .and_then(|guild_id| CACHE.read().unwrap().guild(guild_id)) } /// Retrieves the Id of the guild that the message was sent in, if sent in @@ -360,8 +354,7 @@ impl Message { #[cfg(feature = "cache")] pub fn is_private(&self) -> bool { match CACHE.read().unwrap().channel(self.channel_id) { - Some(Channel::Group(_)) | - Some(Channel::Private(_)) => true, + Some(Channel::Group(_)) | Some(Channel::Private(_)) => true, _ => false, } } @@ -378,7 +371,11 @@ impl Message { let count = content.chars().count() as i64; let diff = count - (constants::MESSAGE_CODE_LIMIT as i64); - if diff > 0 { Some(diff as u64) } else { None } + if diff > 0 { + Some(diff as u64) + } else { + None + } } /// Pins this message to its channel. diff --git a/src/model/channel/mod.rs b/src/model/channel/mod.rs index 626f466..0911139 100644 --- a/src/model/channel/mod.rs +++ b/src/model/channel/mod.rs @@ -20,6 +20,7 @@ use serde::de::Error as DeError; use serde_json; use super::utils::deserialize_u64; use model::*; +use internal::RwLockExt; #[cfg(feature = "model")] use std::fmt::{Display, Formatter, Result as FmtResult}; @@ -99,7 +100,7 @@ impl Channel { /// [`Message::delete`]: struct.Message.html#method.delete /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html #[inline] - pub fn delete_message<M: Into<MessageId>>(&self, message_id: M) -> Result<()> { +pub fn delete_message<M: Into<MessageId>>(&self, message_id: M) -> Result<()>{ self.id().delete_message(message_id) } @@ -117,11 +118,8 @@ impl Channel { reaction_type: R) -> Result<()> where M: Into<MessageId>, R: Into<ReactionType> { - self.id().delete_reaction( - message_id, - user_id, - reaction_type, - ) + self.id() + .delete_reaction(message_id, user_id, reaction_type) } /// Edits a [`Message`] in the channel given its Id. @@ -158,9 +156,8 @@ impl Channel { #[inline] pub fn is_nsfw(&self) -> bool { match *self { - Channel::Guild(ref channel) => channel.read().unwrap().is_nsfw(), - Channel::Group(_) | - Channel::Private(_) => false, + Channel::Guild(ref channel) => channel.with(|c| c.is_nsfw()), + Channel::Group(_) | Channel::Private(_) => false, } } @@ -220,12 +217,8 @@ impl Channel { after: Option<U>) -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.id().reaction_users( - message_id, - reaction_type, - limit, - after, - ) + self.id() + .reaction_users(message_id, reaction_type, limit, after) } /// Retrieves the Id of the inner [`Group`], [`GuildChannel`], or @@ -236,9 +229,9 @@ impl Channel { /// [`PrivateChannel`]: struct.PrivateChannel.html pub fn id(&self) -> ChannelId { match *self { - Channel::Group(ref group) => group.read().unwrap().channel_id, - Channel::Guild(ref channel) => channel.read().unwrap().id, - Channel::Private(ref channel) => channel.read().unwrap().id, + Channel::Group(ref group) => group.with(|g| g.channel_id), + Channel::Guild(ref ch) => ch.with(|c| c.id), + Channel::Private(ref ch) => ch.with(|c| c.id), } } @@ -326,21 +319,15 @@ impl<'de> Deserialize<'de> for Channel { }; match kind { - 0 | 2 => { - serde_json::from_value::<GuildChannel>(Value::Object(v)) - .map(|x| Channel::Guild(Arc::new(RwLock::new(x)))) - .map_err(DeError::custom) - }, - 1 => { - serde_json::from_value::<PrivateChannel>(Value::Object(v)) - .map(|x| Channel::Private(Arc::new(RwLock::new(x)))) - .map_err(DeError::custom) - }, - 3 => { - serde_json::from_value::<Group>(Value::Object(v)) - .map(|x| Channel::Group(Arc::new(RwLock::new(x)))) - .map_err(DeError::custom) - }, + 0 | 2 => serde_json::from_value::<GuildChannel>(Value::Object(v)) + .map(|x| Channel::Guild(Arc::new(RwLock::new(x)))) + .map_err(DeError::custom), + 1 => serde_json::from_value::<PrivateChannel>(Value::Object(v)) + .map(|x| Channel::Private(Arc::new(RwLock::new(x)))) + .map_err(DeError::custom), + 3 => serde_json::from_value::<Group>(Value::Object(v)) + .map(|x| Channel::Group(Arc::new(RwLock::new(x)))) + .map_err(DeError::custom), _ => Err(DeError::custom("Unknown channel type")), } } @@ -412,10 +399,8 @@ impl ChannelType { struct PermissionOverwriteData { allow: Permissions, deny: Permissions, - #[serde(deserialize_with = "deserialize_u64")] - id: u64, - #[serde(rename = "type")] - kind: String, + #[serde(deserialize_with = "deserialize_u64")] id: u64, + #[serde(rename = "type")] kind: String, } /// A channel-specific permission overwrite for a member or role. diff --git a/src/model/channel/private_channel.rs b/src/model/channel/private_channel.rs index 30dc01d..e5e14d9 100644 --- a/src/model/channel/private_channel.rs +++ b/src/model/channel/private_channel.rs @@ -2,6 +2,7 @@ use chrono::{DateTime, FixedOffset}; use std::fmt::{Display, Formatter, Result as FmtResult}; use super::deserialize_single_recipient; use model::*; +use internal::RwLockExt; #[cfg(feature = "model")] use builder::{CreateMessage, GetMessages}; @@ -169,7 +170,7 @@ impl PrivateChannel { } /// Returns "DM with $username#discriminator". - pub fn name(&self) -> String { format!("DM with {}", self.recipient.read().unwrap().tag()) } + pub fn name(&self) -> String { format!("DM with {}", self.recipient.with(|r| r.tag())) } /// Gets the list of [`User`]s who have reacted to a [`Message`] with a /// certain [`Emoji`]. @@ -191,12 +192,8 @@ impl PrivateChannel { after: Option<U>) -> Result<Vec<User>> where M: Into<MessageId>, R: Into<ReactionType>, U: Into<UserId> { - self.id.reaction_users( - message_id, - reaction_type, - limit, - after, - ) + self.id + .reaction_users(message_id, reaction_type, limit, after) } /// Pins a [`Message`] to the channel. @@ -262,7 +259,7 @@ impl PrivateChannel { /// [`CreateMessage`]: ../builder/struct.CreateMessage.html /// [`Message`]: struct.Message.html #[inline] - pub fn send_message<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message> { +pub fn send_message<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message>{ self.id.send_message(f) } diff --git a/src/model/channel/reaction.rs b/src/model/channel/reaction.rs index 88fd24c..be5dfb8 100644 --- a/src/model/channel/reaction.rs +++ b/src/model/channel/reaction.rs @@ -46,32 +46,31 @@ impl Reaction { /// [Manage Messages]: permissions/constant.MANAGE_MESSAGES.html /// [permissions]: permissions pub fn delete(&self) -> Result<()> { - let user_id = - feature_cache! {{ - let user = if self.user_id == CACHE.read().unwrap().user.id { - None - } else { - Some(self.user_id.0) - }; - - // If the reaction is one _not_ made by the current user, then ensure - // that the current user has permission* to delete the reaction. - // - // Normally, users can only delete their own reactions. - // - // * The `Manage Messages` permission. - if user.is_some() { - let req = permissions::MANAGE_MESSAGES; - - if !utils::user_has_perms(self.channel_id, req).unwrap_or(true) { - return Err(Error::Model(ModelError::InvalidPermissions(req))); - } - } - - user - } else { - Some(self.user_id.0) - }}; + let user_id = feature_cache! {{ + let user = if self.user_id == CACHE.read().unwrap().user.id { + None + } else { + Some(self.user_id.0) + }; + + // If the reaction is one _not_ made by the current user, then ensure + // that the current user has permission* to delete the reaction. + // + // Normally, users can only delete their own reactions. + // + // * The `Manage Messages` permission. + if user.is_some() { + let req = permissions::MANAGE_MESSAGES; + + if !utils::user_has_perms(self.channel_id, req).unwrap_or(true) { + return Err(Error::Model(ModelError::InvalidPermissions(req))); + } + } + + user + } else { + Some(self.user_id.0) + }}; http::delete_reaction(self.channel_id.0, self.message_id.0, user_id, &self.emoji) } diff --git a/src/model/event.rs b/src/model/event.rs index 22cf649..7881864 100644 --- a/src/model/event.rs +++ b/src/model/event.rs @@ -126,8 +126,7 @@ impl<'de> Deserialize<'de> for GuildDeleteEvent { #[derive(Clone, Debug, Deserialize)] pub struct GuildEmojisUpdateEvent { - #[serde(deserialize_with = "deserialize_emojis")] - pub emojis: HashMap<EmojiId, Emoji>, + #[serde(deserialize_with = "deserialize_emojis")] pub emojis: HashMap<EmojiId, Emoji>, pub guild_id: GuildId, } @@ -153,9 +152,8 @@ impl<'de> Deserialize<'de> for GuildMemberAddEvent { Ok(GuildMemberAddEvent { guild_id: guild_id, - member: Member::deserialize(Value::Object(map)).map_err( - DeError::custom, - )?, + member: Member::deserialize(Value::Object(map)) + .map_err(DeError::custom)?, }) } } @@ -189,9 +187,8 @@ impl<'de> Deserialize<'de> for GuildMembersChunkEvent { .and_then(|v| GuildId::deserialize(v.clone())) .map_err(DeError::custom)?; - let mut members = map.remove("members").ok_or_else(|| { - DeError::custom("missing member chunk members") - })?; + let mut members = map.remove("members") + .ok_or_else(|| DeError::custom("missing member chunk members"))?; if let Some(members) = members.as_array_mut() { let num = Value::Number(Number::from(guild_id.0)); @@ -233,8 +230,7 @@ pub struct GuildRoleUpdateEvent { #[derive(Clone, Debug, Deserialize)] pub struct GuildUnavailableEvent { - #[serde(rename = "id")] - pub guild_id: GuildId, + #[serde(rename = "id")] pub guild_id: GuildId, } #[derive(Clone, Debug)] @@ -272,8 +268,7 @@ pub struct MessageDeleteBulkEvent { #[derive(Clone, Copy, Debug, Deserialize)] pub struct MessageDeleteEvent { pub channel_id: ChannelId, - #[serde(rename = "id")] - pub message_id: MessageId, + #[serde(rename = "id")] pub message_id: MessageId, } #[derive(Clone, Debug, Deserialize)] @@ -307,24 +302,17 @@ impl<'de> Deserialize<'de> for PresenceUpdateEvent { let mut map = JsonMap::deserialize(deserializer)?; let guild_id = match map.remove("guild_id") { - Some(v) => { - serde_json::from_value::<Option<GuildId>>(v).map_err( - DeError::custom, - )? - }, + Some(v) => serde_json::from_value::<Option<GuildId>>(v) + .map_err(DeError::custom)?, None => None, }; let roles = match map.remove("roles") { - Some(v) => { - serde_json::from_value::<Option<Vec<RoleId>>>(v).map_err( - DeError::custom, - )? - }, + Some(v) => serde_json::from_value::<Option<Vec<RoleId>>>(v) + .map_err(DeError::custom)?, None => None, }; - let presence = Presence::deserialize(Value::Object(map)).map_err( - DeError::custom, - )?; + let presence = Presence::deserialize(Value::Object(map)) + .map_err(DeError::custom)?; Ok(Self { guild_id: guild_id, @@ -397,8 +385,7 @@ impl<'de> Deserialize<'de> for ReadyEvent { #[derive(Clone, Debug, Deserialize)] pub struct ResumedEvent { - #[serde(rename = "_trace")] - pub trace: Vec<Option<String>>, + #[serde(rename = "_trace")] pub trace: Vec<Option<String>>, } #[derive(Clone, Debug, Deserialize)] @@ -451,9 +438,8 @@ impl<'de> Deserialize<'de> for VoiceStateUpdateEvent { Ok(VoiceStateUpdateEvent { guild_id: guild_id, - voice_state: VoiceState::deserialize(Value::Object(map)).map_err( - DeError::custom, - )?, + voice_state: VoiceState::deserialize(Value::Object(map)) + .map_err(DeError::custom)?, }) } } @@ -801,20 +787,16 @@ impl VoiceEvent { let mut map = JsonMap::deserialize(value)?; let op = match map.remove("op") { - Some(v) => { - VoiceOpCode::deserialize(v) - .map_err(JsonError::from) - .map_err(Error::from)? - }, + Some(v) => VoiceOpCode::deserialize(v) + .map_err(JsonError::from) + .map_err(Error::from)?, None => return Err(Error::Decode("expected voice event op", Value::Object(map))), }; let d = match map.remove("d") { - Some(v) => { - JsonMap::deserialize(v).map_err(JsonError::from).map_err( - Error::from, - )? - }, + Some(v) => JsonMap::deserialize(v) + .map_err(JsonError::from) + .map_err(Error::from)?, None => { return Err(Error::Decode( "expected voice gateway d", diff --git a/src/model/gateway.rs b/src/model/gateway.rs index 1b3a40b..4edf0b8 100644 --- a/src/model/gateway.rs +++ b/src/model/gateway.rs @@ -106,9 +106,8 @@ impl<'de> Deserialize<'de> for Game { let name = map.remove("name") .and_then(|v| String::deserialize(v).ok()) .unwrap_or_else(String::new); - let url = map.remove("url").and_then(|v| { - serde_json::from_value::<String>(v).ok() - }); + let url = map.remove("url") + .and_then(|v| serde_json::from_value::<String>(v).ok()); Ok(Game { kind: kind, @@ -174,9 +173,8 @@ impl<'de> Deserialize<'de> for Presence { .map_err(DeError::custom)?; let (user_id, user) = if user_map.len() > 1 { - let user = User::deserialize(Value::Object(user_map)).map_err( - DeError::custom, - )?; + let user = User::deserialize(Value::Object(user_map)) + .map_err(DeError::custom)?; (user.id, Some(Arc::new(RwLock::new(user)))) } else { @@ -190,11 +188,8 @@ impl<'de> Deserialize<'de> for Presence { }; let game = match map.remove("game") { - Some(v) => { - serde_json::from_value::<Option<Game>>(v).map_err( - DeError::custom, - )? - }, + Some(v) => serde_json::from_value::<Option<Game>>(v) + .map_err(DeError::custom)?, None => None, }; let last_modified = match map.remove("last_modified") { @@ -202,11 +197,8 @@ impl<'de> Deserialize<'de> for Presence { None => None, }; let nick = match map.remove("nick") { - Some(v) => { - serde_json::from_value::<Option<String>>(v).map_err( - DeError::custom, - )? - }, + Some(v) => serde_json::from_value::<Option<String>>(v) + .map_err(DeError::custom)?, None => None, }; let status = map.remove("status") @@ -229,15 +221,13 @@ impl<'de> Deserialize<'de> for Presence { #[derive(Clone, Debug, Deserialize)] pub struct Ready { pub guilds: Vec<GuildStatus>, - #[serde(deserialize_with = "deserialize_presences")] - pub presences: HashMap<UserId, Presence>, + #[serde(deserialize_with = "deserialize_presences")] pub presences: HashMap<UserId, Presence>, #[serde(deserialize_with = "deserialize_private_channels")] - pub private_channels: HashMap<ChannelId, Channel>, + pub private_channels: + HashMap<ChannelId, Channel>, pub session_id: String, pub shard: Option<[u64; 2]>, - #[serde(default, rename = "_trace")] - pub trace: Vec<String>, + #[serde(default, rename = "_trace")] pub trace: Vec<String>, pub user: CurrentUser, - #[serde(rename = "v")] - pub version: u64, + #[serde(rename = "v")] pub version: u64, } diff --git a/src/model/guild/audit_log.rs b/src/model/guild/audit_log.rs index 962b145..6c24662 100644 --- a/src/model/guild/audit_log.rs +++ b/src/model/guild/audit_log.rs @@ -91,12 +91,9 @@ pub enum ActionEmoji { #[derive(Debug, Deserialize)] pub struct Change { - #[serde(rename = "key")] - pub name: String, - #[serde(rename = "old_value")] - pub old: String, - #[serde(rename = "new_value")] - pub new: String, + #[serde(rename = "key")] pub name: String, + #[serde(rename = "old_value")] pub old: String, + #[serde(rename = "new_value")] pub new: String, } #[derive(Debug)] @@ -126,7 +123,7 @@ pub struct AuditLogEntry { pub id: AuditLogEntryId, } -fn deserialize_target<'de, D: Deserializer<'de>>(de: D) -> Result<Target, D::Error> { +fn deserialize_target<'de, D: Deserializer<'de>>(de: D) -> Result<Target, D::Error>{ struct TargetVisitor; impl<'de> Visitor<'de> for TargetVisitor { @@ -147,7 +144,7 @@ fn deserialize_target<'de, D: Deserializer<'de>>(de: D) -> Result<Target, D::Err de.deserialize_i32(TargetVisitor) } -fn deserialize_action<'de, D: Deserializer<'de>>(de: D) -> Result<Action, D::Error> { +fn deserialize_action<'de, D: Deserializer<'de>>(de: D) -> Result<Action, D::Error>{ struct ActionVisitor; impl<'de> Visitor<'de> for ActionVisitor { @@ -180,8 +177,7 @@ impl<'de> Deserialize<'de> for AuditLogs { #[derive(Deserialize)] #[serde(field_identifier)] enum Field { - #[serde(rename = "audit_log_entries")] - Entries, + #[serde(rename = "audit_log_entries")] Entries, } struct EntriesVisitor; diff --git a/src/model/guild/guild_id.rs b/src/model/guild/guild_id.rs index 4d6ba9b..02775ba 100644 --- a/src/model/guild/guild_id.rs +++ b/src/model/guild/guild_id.rs @@ -48,7 +48,7 @@ impl GuildId { /// [`Guild::ban`]: struct.Guild.html#method.ban /// [`User`]: struct.User.html /// [Ban Members]: permissions/constant.BAN_MEMBERS.html - pub fn ban<U: Into<UserId>, BO: BanOptions>(&self, user: U, ban_options: BO) -> Result<()> { +pub fn ban<U: Into<UserId>, BO: BanOptions>(&self, user: U, ban_options: BO) -> Result<()>{ let dmd = ban_options.dmd(); if dmd > 7 { return Err(Error::Model(ModelError::DeleteMessageDaysAmount(dmd))); @@ -167,7 +167,7 @@ impl GuildId { /// [`Guild::create_role`]: struct.Guild.html#method.create_role /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html #[inline] - pub fn create_role<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role> { +pub fn create_role<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role>{ http::create_role(self.0, &f(EditRole::default()).0) } @@ -199,7 +199,7 @@ impl GuildId { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn delete_integration<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()> { +pub fn delete_integration<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()>{ http::delete_guild_integration(self.0, integration_id.into().0) } @@ -228,7 +228,7 @@ impl GuildId { /// [`Guild::edit`]: struct.Guild.html#method.edit /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn edit<F: FnOnce(EditGuild) -> EditGuild>(&mut self, f: F) -> Result<PartialGuild> { +pub fn edit<F: FnOnce(EditGuild) -> EditGuild>(&mut self, f: F) -> Result<PartialGuild>{ http::edit_guild(self.0, &f(EditGuild::default()).0) } @@ -459,7 +459,7 @@ impl GuildId { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn start_integration_sync<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()> { +pub fn start_integration_sync<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()>{ http::start_integration_sync(self.0, integration_id.into().0) } diff --git a/src/model/guild/integration.rs b/src/model/guild/integration.rs index 18da39d..b903a2c 100644 --- a/src/model/guild/integration.rs +++ b/src/model/guild/integration.rs @@ -6,8 +6,7 @@ pub struct Integration { pub id: IntegrationId, pub account: IntegrationAccount, pub enabled: bool, - #[serde(rename = "expire_behaviour")] - pub expire_behaviour: u64, + #[serde(rename = "expire_behaviour")] pub expire_behaviour: u64, pub expire_grace_period: u64, pub kind: String, pub name: String, diff --git a/src/model/guild/member.rs b/src/model/guild/member.rs index f1a5114..370f555 100644 --- a/src/model/guild/member.rs +++ b/src/model/guild/member.rs @@ -168,9 +168,10 @@ impl Member { let default = Colour::default(); - roles.iter().find(|r| r.colour.0 != default.0).map( - |r| r.colour, - ) + roles + .iter() + .find(|r| r.colour.0 != default.0) + .map(|r| r.colour) } /// Calculates the member's display name. @@ -178,9 +179,10 @@ impl Member { /// The nickname takes priority over the member's username if it exists. #[inline] pub fn display_name(&self) -> Cow<String> { - self.nick.as_ref().map(Cow::Borrowed).unwrap_or_else(|| { - Cow::Owned(self.user.read().unwrap().name.clone()) - }) + self.nick + .as_ref() + .map(Cow::Borrowed) + .unwrap_or_else(|| Cow::Owned(self.user.read().unwrap().name.clone())) } /// Returns the DiscordTag of a Member, taking possible nickname into account. @@ -202,7 +204,7 @@ impl Member { /// [`Guild::edit_member`]: ../model/struct.Guild.html#method.edit_member /// [`EditMember`]: ../builder/struct.EditMember.html #[cfg(feature = "cache")] - pub fn edit<F: FnOnce(EditMember) -> EditMember>(&self, f: F) -> Result<()> { +pub fn edit<F: FnOnce(EditMember) -> EditMember>(&self, f: F) -> Result<()>{ let map = f(EditMember::default()).0; http::edit_member(self.guild_id.0, self.user.read().unwrap().id.0, &map) @@ -246,11 +248,12 @@ impl Member { { let req = permissions::KICK_MEMBERS; - let has_perms = CACHE.read().unwrap().guilds.get(&self.guild_id).map( - |guild| { - guild.read().unwrap().has_perms(req) - }, - ); + let has_perms = CACHE + .read() + .unwrap() + .guilds + .get(&self.guild_id) + .map(|guild| guild.read().unwrap().has_perms(req)); if let Some(Ok(false)) = has_perms { return Err(Error::Model(ModelError::InvalidPermissions(req))); @@ -285,10 +288,10 @@ impl Member { let guild = guild.read().unwrap(); - Ok(guild.permissions_for( - ChannelId(guild.id.0), - self.user.read().unwrap().id, - )) + Ok( + guild + .permissions_for(ChannelId(guild.id.0), self.user.read().unwrap().id), + ) } /// Removes a [`Role`] from the member, editing its roles in-place if the diff --git a/src/model/guild/mod.rs b/src/model/guild/mod.rs index 3fc2a86..7fdd7d4 100644 --- a/src/model/guild/mod.rs +++ b/src/model/guild/mod.rs @@ -168,10 +168,7 @@ impl Guild { None => return Err(Error::Model(ModelError::ItemMissing)), }; - let perms = self.permissions_for( - default_channel.id, - member.user.read().unwrap().id, - ); + let perms = self.permissions_for(default_channel.id, member.user.read().unwrap().id); permissions.remove(perms); Ok(permissions.is_empty()) @@ -445,7 +442,7 @@ impl Guild { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn delete_integration<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()> { +pub fn delete_integration<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()>{ self.id.delete_integration(integration_id) } @@ -629,9 +626,9 @@ impl Guild { /// Returns the formatted URL of the guild's icon, if one exists. pub fn icon_url(&self) -> Option<String> { - self.icon.as_ref().map( - |icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon), - ) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) } /// Gets all integration of the guild. @@ -709,10 +706,8 @@ impl Guild { for (&id, member) in &self.members { match self.presences.get(&id) { - Some(presence) => { - if status == presence.status { - members.push(member); - } + Some(presence) => if status == presence.status { + members.push(member); }, None => continue, } @@ -800,8 +795,8 @@ impl Guild { Some(everyone) => everyone, None => { error!("(╯°□°)╯︵ ┻━┻ @everyone role ({}) missing in '{}'", - self.id, - self.name); + self.id, + self.name); return Permissions::empty(); }, @@ -820,9 +815,9 @@ impl Guild { permissions |= role.permissions; } else { warn!("(╯°□°)╯︵ ┻━┻ {} on {} has non-existent role {:?}", - member.user.read().unwrap().id, - self.id, - role); + member.user.read().unwrap().id, + self.id, + role); } } @@ -836,8 +831,8 @@ impl Guild { // If this is a text channel, then throw out voice permissions. if channel.kind == ChannelType::Text { - permissions &= !(CONNECT | SPEAK | MUTE_MEMBERS | DEAFEN_MEMBERS | MOVE_MEMBERS | - USE_VAD); + permissions &= + !(CONNECT | SPEAK | MUTE_MEMBERS | DEAFEN_MEMBERS | MOVE_MEMBERS | USE_VAD); } // Apply the permission overwrites for the channel for each of the @@ -868,8 +863,8 @@ impl Guild { } } else { warn!("(╯°□°)╯︵ ┻━┻ Guild {} does not contain channel {}", - self.id, - channel_id); + self.id, + channel_id); } // The default channel is always readable. @@ -963,9 +958,9 @@ impl Guild { /// Returns the formatted URL of the guild's splash image, if one exists. pub fn splash_url(&self) -> Option<String> { - self.icon.as_ref().map( - |icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon), - ) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) } /// Starts an integration sync for the given integration Id. @@ -974,7 +969,7 @@ impl Guild { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn start_integration_sync<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()> { +pub fn start_integration_sync<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()>{ self.id.start_integration_sync(integration_id) } @@ -1044,18 +1039,16 @@ impl<'de> Deserialize<'de> for Guild { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> { let mut map = JsonMap::deserialize(deserializer)?; - let id = map.get("id").and_then(|x| x.as_str()).and_then(|x| { - x.parse::<u64>().ok() - }); + let id = map.get("id") + .and_then(|x| x.as_str()) + .and_then(|x| x.parse::<u64>().ok()); if let Some(guild_id) = id { if let Some(array) = map.get_mut("channels").and_then(|x| x.as_array_mut()) { for value in array { if let Some(channel) = value.as_object_mut() { - channel.insert( - "guild_id".to_owned(), - Value::Number(Number::from(guild_id)), - ); + channel + .insert("guild_id".to_owned(), Value::Number(Number::from(guild_id))); } } } @@ -1063,21 +1056,16 @@ impl<'de> Deserialize<'de> for Guild { if let Some(array) = map.get_mut("members").and_then(|x| x.as_array_mut()) { for value in array { if let Some(member) = value.as_object_mut() { - member.insert( - "guild_id".to_owned(), - Value::Number(Number::from(guild_id)), - ); + member + .insert("guild_id".to_owned(), Value::Number(Number::from(guild_id))); } } } } let afk_channel_id = match map.remove("afk_channel_id") { - Some(v) => { - serde_json::from_value::<Option<ChannelId>>(v).map_err( - DeError::custom, - )? - }, + Some(v) => serde_json::from_value::<Option<ChannelId>>(v) + .map_err(DeError::custom)?, None => None, }; let afk_timeout = map.remove("afk_timeout") @@ -1229,9 +1217,9 @@ pub struct GuildInfo { impl GuildInfo { /// Returns the formatted URL of the guild's icon, if the guild has an icon. pub fn icon_url(&self) -> Option<String> { - self.icon.as_ref().map( - |icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon), - ) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) } } @@ -1251,9 +1239,9 @@ impl From<u64> for GuildContainer { impl InviteGuild { /// Returns the formatted URL of the guild's splash image, if one exists. pub fn splash_url(&self) -> Option<String> { - self.icon.as_ref().map( - |icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon), - ) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) } } diff --git a/src/model/guild/partial_guild.rs b/src/model/guild/partial_guild.rs index 799f6b6..1690167 100644 --- a/src/model/guild/partial_guild.rs +++ b/src/model/guild/partial_guild.rs @@ -16,16 +16,14 @@ pub struct PartialGuild { pub default_message_notifications: u64, pub embed_channel_id: Option<ChannelId>, pub embed_enabled: bool, - #[serde(deserialize_with = "deserialize_emojis")] - pub emojis: HashMap<EmojiId, Emoji>, + #[serde(deserialize_with = "deserialize_emojis")] pub emojis: HashMap<EmojiId, Emoji>, pub features: Vec<Feature>, pub icon: Option<String>, pub mfa_level: u64, pub name: String, pub owner_id: UserId, pub region: String, - #[serde(deserialize_with = "deserialize_roles")] - pub roles: HashMap<RoleId, Role>, + #[serde(deserialize_with = "deserialize_roles")] pub roles: HashMap<RoleId, Role>, pub splash: Option<String>, pub verification_level: VerificationLevel, } @@ -152,7 +150,7 @@ impl PartialGuild { /// [`Guild::create_role`]: struct.Guild.html#method.create_role /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html #[inline] - pub fn create_role<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role> { +pub fn create_role<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role>{ self.id.create_role(f) } @@ -180,7 +178,7 @@ impl PartialGuild { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn delete_integration<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()> { +pub fn delete_integration<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()>{ self.id.delete_integration(integration_id) } @@ -317,9 +315,9 @@ impl PartialGuild { /// Returns a formatted URL of the guild's icon, if the guild has an icon. pub fn icon_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| { - format!(cdn!("/icons/{}/{}.webp"), self.id, icon) - }) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/icons/{}/{}.webp"), self.id, icon)) } /// Gets all integration of the guild. @@ -419,9 +417,9 @@ impl PartialGuild { /// Returns the formatted URL of the guild's splash image, if one exists. pub fn splash_url(&self) -> Option<String> { - self.icon.as_ref().map(|icon| { - format!(cdn!("/splashes/{}/{}.webp"), self.id, icon) - }) + self.icon + .as_ref() + .map(|icon| format!(cdn!("/splashes/{}/{}.webp"), self.id, icon)) } /// Starts an integration sync for the given integration Id. @@ -430,7 +428,7 @@ impl PartialGuild { /// /// [Manage Guild]: permissions/constant.MANAGE_GUILD.html #[inline] - pub fn start_integration_sync<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()> { +pub fn start_integration_sync<I: Into<IntegrationId>>(&self, integration_id: I) -> Result<()>{ self.id.start_integration_sync(integration_id) } diff --git a/src/model/guild/role.rs b/src/model/guild/role.rs index 5956113..5a6f75c 100644 --- a/src/model/guild/role.rs +++ b/src/model/guild/role.rs @@ -92,10 +92,9 @@ impl Role { /// [`Role`]: struct.Role.html /// [Manage Roles]: permissions/constant.MANAGE_ROLES.html #[cfg(all(feature = "builder", feature = "cache"))] - pub fn edit<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role> { - self.find_guild().and_then( - |guild_id| guild_id.edit_role(self.id, f), - ) +pub fn edit<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role>{ + self.find_guild() + .and_then(|guild_id| guild_id.edit_role(self.id, f)) } /// Searches the cache for the guild that owns the role. diff --git a/src/model/invite.rs b/src/model/invite.rs index f48ecbc..c066128 100644 --- a/src/model/invite.rs +++ b/src/model/invite.rs @@ -152,8 +152,7 @@ impl Invite { pub struct InviteChannel { pub id: ChannelId, pub name: String, - #[serde(rename = "type")] - pub kind: ChannelType, + #[serde(rename = "type")] pub kind: ChannelType, } /// A minimal amount of information about the guild an invite points to. diff --git a/src/model/misc.rs b/src/model/misc.rs index 0d1f146..3310e4a 100644 --- a/src/model/misc.rs +++ b/src/model/misc.rs @@ -1,4 +1,5 @@ use super::*; +use internal::RwLockExt; #[cfg(all(feature = "model", feature = "utils"))] use std::result::Result as StdResult; @@ -27,9 +28,9 @@ impl Mentionable for ChannelId { impl Mentionable for Channel { fn mention(&self) -> String { match *self { - Channel::Guild(ref x) => format!("<#{}>", x.read().unwrap().id.0), - Channel::Private(ref x) => format!("<#{}>", x.read().unwrap().id.0), - Channel::Group(ref x) => format!("<#{}>", x.read().unwrap().channel_id.0), + Channel::Guild(ref x) => format!("<#{}>", x.with(|x| x.id.0)), + Channel::Private(ref x) => format!("<#{}>", x.with(|x| x.id.0)), + Channel::Group(ref x) => format!("<#{}>", x.with(|x| x.channel_id.0)), } } } @@ -39,7 +40,7 @@ impl Mentionable for Emoji { } impl Mentionable for Member { - fn mention(&self) -> String { format!("<@{}>", self.user.read().unwrap().id.0) } + fn mention(&self) -> String { format!("<@{}>", self.user.with(|u| u.id.0)) } } impl Mentionable for RoleId { @@ -89,11 +90,9 @@ impl FromStr for User { fn from_str(s: &str) -> StdResult<Self, Self::Err> { match utils::parse_username(s) { - Some(x) => { - UserId(x as u64).get().map_err( - |e| UserParseError::Rest(Box::new(e)), - ) - }, + Some(x) => UserId(x as u64) + .get() + .map_err(|e| UserParseError::Rest(Box::new(e))), _ => Err(UserParseError::InvalidUsername), } } @@ -162,11 +161,9 @@ impl FromStr for Role { fn from_str(s: &str) -> StdResult<Self, Self::Err> { match utils::parse_role(s) { - Some(x) => { - match RoleId(x).find() { - Some(user) => Ok(user), - _ => Err(RoleParseError::NotPresentInCache), - } + Some(x) => match RoleId(x).find() { + Some(user) => Ok(user), + _ => Err(RoleParseError::NotPresentInCache), }, _ => Err(RoleParseError::InvalidRole), } @@ -245,11 +242,9 @@ impl FromStr for Channel { fn from_str(s: &str) -> StdResult<Self, ()> { match utils::parse_channel(s) { - Some(x) => { - match ChannelId(x).find() { - Some(channel) => Ok(channel), - _ => Err(()), - } + Some(x) => match ChannelId(x).find() { + Some(channel) => Ok(channel), + _ => Err(()), }, _ => Err(()), } diff --git a/src/model/mod.rs b/src/model/mod.rs index d512ffb..cc8860f 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -198,41 +198,26 @@ pub struct CurrentApplicationInfo { pub id: UserId, pub name: String, pub owner: User, - #[serde(default)] - pub rpc_origins: Vec<String>, + #[serde(default)] pub rpc_origins: Vec<String>, } /// The name of a region that a voice server can be located in. #[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)] pub enum Region { - #[serde(rename = "amsterdam")] - Amsterdam, - #[serde(rename = "brazil")] - Brazil, - #[serde(rename = "eu-central")] - EuCentral, - #[serde(rename = "eu-west")] - EuWest, - #[serde(rename = "frankfurt")] - Frankfurt, - #[serde(rename = "london")] - London, - #[serde(rename = "sydney")] - Sydney, - #[serde(rename = "us-central")] - UsCentral, - #[serde(rename = "us-east")] - UsEast, - #[serde(rename = "us-south")] - UsSouth, - #[serde(rename = "us-west")] - UsWest, - #[serde(rename = "vip-amsterdam")] - VipAmsterdam, - #[serde(rename = "vip-us-east")] - VipUsEast, - #[serde(rename = "vip-us-west")] - VipUsWest, + #[serde(rename = "amsterdam")] Amsterdam, + #[serde(rename = "brazil")] Brazil, + #[serde(rename = "eu-central")] EuCentral, + #[serde(rename = "eu-west")] EuWest, + #[serde(rename = "frankfurt")] Frankfurt, + #[serde(rename = "london")] London, + #[serde(rename = "sydney")] Sydney, + #[serde(rename = "us-central")] UsCentral, + #[serde(rename = "us-east")] UsEast, + #[serde(rename = "us-south")] UsSouth, + #[serde(rename = "us-west")] UsWest, + #[serde(rename = "vip-amsterdam")] VipAmsterdam, + #[serde(rename = "vip-us-east")] VipUsEast, + #[serde(rename = "vip-us-west")] VipUsWest, } impl Region { @@ -260,6 +245,6 @@ use serde::{Deserialize, Deserializer}; use std::result::Result as StdResult; fn deserialize_sync_user<'de, D: Deserializer<'de>>(deserializer: D) - -> StdResult<Arc<RwLock<User>>, D::Error> { +-> StdResult<Arc<RwLock<User>>, D::Error>{ Ok(Arc::new(RwLock::new(User::deserialize(deserializer)?))) } diff --git a/src/model/user.rs b/src/model/user.rs index c32eeb8..c3b131b 100644 --- a/src/model/user.rs +++ b/src/model/user.rs @@ -25,14 +25,11 @@ use http::{self, GuildPagination}; pub struct CurrentUser { pub id: UserId, pub avatar: Option<String>, - #[serde(default)] - pub bot: bool, - #[serde(deserialize_with = "deserialize_u16")] - pub discriminator: u16, + #[serde(default)] pub bot: bool, + #[serde(deserialize_with = "deserialize_u16")] pub discriminator: u16, pub email: Option<String>, pub mfa_enabled: bool, - #[serde(rename = "username")] - pub name: String, + #[serde(rename = "username")] pub name: String, pub verified: bool, } @@ -88,10 +85,7 @@ impl CurrentUser { pub fn edit<F>(&mut self, f: F) -> Result<()> where F: FnOnce(EditProfile) -> EditProfile { let mut map = Map::new(); - map.insert( - "username".to_owned(), - Value::String(self.name.clone()), - ); + map.insert("username".to_owned(), Value::String(self.name.clone())); if let Some(email) = self.email.as_ref() { map.insert("email".to_owned(), Value::String(email.clone())); @@ -116,9 +110,8 @@ impl CurrentUser { /// [`avatar_url`]: #method.avatar_url /// [`default_avatar_url`]: #method.default_avatar_url pub fn face(&self) -> String { - self.avatar_url().unwrap_or_else( - || self.default_avatar_url(), - ) + self.avatar_url() + .unwrap_or_else(|| self.default_avatar_url()) } /// Gets a list of guilds that the current user is in. @@ -329,16 +322,11 @@ enum_number!( /// [`Invisible`]: #variant.Invisible #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)] pub enum OnlineStatus { - #[serde(rename = "dnd")] - DoNotDisturb, - #[serde(rename = "idle")] - Idle, - #[serde(rename = "invisible")] - Invisible, - #[serde(rename = "offline")] - Offline, - #[serde(rename = "online")] - Online, + #[serde(rename = "dnd")] DoNotDisturb, + #[serde(rename = "idle")] Idle, + #[serde(rename = "invisible")] Invisible, + #[serde(rename = "offline")] Offline, + #[serde(rename = "online")] Online, } impl OnlineStatus { @@ -492,36 +480,35 @@ impl User { return Err(Error::Model(ModelError::MessagingBot)); } - let private_channel_id = - feature_cache! {{ - let finding = { - let cache = CACHE.read().unwrap(); - - let finding = cache.private_channels - .values() - .map(|ch| ch.read().unwrap()) - .find(|ch| ch.recipient.read().unwrap().id == self.id) - .map(|ch| ch.id); - - finding - }; - - if let Some(finding) = finding { - finding - } else { - let map = json!({ - "recipient_id": self.id.0, - }); - - http::create_private_channel(&map)?.id - } - } else { - let map = json!({ - "recipient_id": self.id.0, - }); - - http::create_private_channel(&map)?.id - }}; + let private_channel_id = feature_cache! {{ + let finding = { + let cache = CACHE.read().unwrap(); + + let finding = cache.private_channels + .values() + .map(|ch| ch.read().unwrap()) + .find(|ch| ch.recipient.read().unwrap().id == self.id) + .map(|ch| ch.id); + + finding + }; + + if let Some(finding) = finding { + finding + } else { + let map = json!({ + "recipient_id": self.id.0, + }); + + http::create_private_channel(&map)?.id + } + } else { + let map = json!({ + "recipient_id": self.id.0, + }); + + http::create_private_channel(&map)?.id + }}; private_channel_id.send_message(f) } @@ -547,7 +534,7 @@ impl User { /// [direct_message]: #method.direct_message #[cfg(feature = "builder")] #[inline] - pub fn dm<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message> { +pub fn dm<F: FnOnce(CreateMessage) -> CreateMessage>(&self, f: F) -> Result<Message>{ self.direct_message(f) } @@ -560,9 +547,8 @@ impl User { /// [`avatar_url`]: #method.avatar_url /// [`default_avatar_url`]: #method.default_avatar_url pub fn face(&self) -> String { - self.avatar_url().unwrap_or_else( - || self.default_avatar_url(), - ) + self.avatar_url() + .unwrap_or_else(|| self.default_avatar_url()) } /// Check if a user has a [`Role`]. This will retrieve the [`Guild`] from @@ -808,9 +794,7 @@ fn default_avatar_url(discriminator: u16) -> String { #[cfg(feature = "model")] fn static_avatar_url(user_id: UserId, hash: Option<&String>) -> Option<String> { - hash.map( - |hash| cdn!("/avatars/{}/{}.webp?size=1024", user_id, hash), - ) + hash.map(|hash| cdn!("/avatars/{}/{}.webp?size=1024", user_id, hash)) } #[cfg(feature = "model")] diff --git a/src/model/utils.rs b/src/model/utils.rs index 9fed660..b85b58f 100644 --- a/src/model/utils.rs +++ b/src/model/utils.rs @@ -123,11 +123,11 @@ pub fn deserialize_users<'de, D: Deserializer<'de>>( Ok(users) } -pub fn deserialize_u16<'de, D: Deserializer<'de>>(deserializer: D) -> StdResult<u16, D::Error> { +pub fn deserialize_u16<'de, D: Deserializer<'de>>(deserializer: D) -> StdResult<u16, D::Error>{ deserializer.deserialize_u16(U16Visitor) } -pub fn deserialize_u64<'de, D: Deserializer<'de>>(deserializer: D) -> StdResult<u64, D::Error> { +pub fn deserialize_u64<'de, D: Deserializer<'de>>(deserializer: D) -> StdResult<u64, D::Error>{ deserializer.deserialize_u64(U64Visitor) } @@ -156,8 +156,7 @@ pub fn user_has_perms(channel_id: ChannelId, mut permissions: Permissions) -> Re let guild_id = match channel { Channel::Guild(channel) => channel.read().unwrap().guild_id, - Channel::Group(_) | - Channel::Private(_) => { + Channel::Group(_) | Channel::Private(_) => { // Both users in DMs, and all users in groups, will have the same // permissions. // @@ -176,10 +175,10 @@ pub fn user_has_perms(channel_id: ChannelId, mut permissions: Permissions) -> Re None => return Err(Error::Model(ModelError::ItemMissing)), }; - let perms = guild.read().unwrap().permissions_for( - channel_id, - current_user.id, - ); + let perms = guild + .read() + .unwrap() + .permissions_for(channel_id, current_user.id); permissions.remove(perms); diff --git a/src/model/webhook.rs b/src/model/webhook.rs index 39099e0..4725ec1 100644 --- a/src/model/webhook.rs +++ b/src/model/webhook.rs @@ -118,10 +118,7 @@ impl Webhook { } if let Some(name) = name { - map.insert( - "name".to_owned(), - Value::String(name.to_owned()), - ); + map.insert("name".to_owned(), Value::String(name.to_owned())); } match http::edit_webhook_with_token(self.id.0, &self.token, &map) { @@ -185,7 +182,7 @@ impl Webhook { pub fn execute<F: FnOnce(ExecuteWebhook) -> ExecuteWebhook>(&self, wait: bool, f: F) - -> Result<Option<Message>> { +-> Result<Option<Message>>{ http::execute_webhook( self.id.0, &self.token, |