Skip to content

Commit

Permalink
Use to_- and as_-methods instead of get and find on Id newtypes
Browse files Browse the repository at this point in the history
  • Loading branch information
Lakelezz authored and zeyla committed Aug 12, 2018
1 parent 0bbe5f5 commit 71edc3a
Show file tree
Hide file tree
Showing 16 changed files with 174 additions and 53 deletions.
2 changes: 1 addition & 1 deletion examples/04_message_builder/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ struct Handler;
impl EventHandler for Handler {
fn message(&self, _: Context, msg: Message) {
if msg.content == "!ping" {
let channel = match msg.channel_id.get() {
let channel = match msg.channel_id.to_channel() {
Ok(channel) => channel,
Err(why) => {
println!("Error getting channel: {:?}", why);
Expand Down
4 changes: 2 additions & 2 deletions src/builder/edit_guild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl EditGuild {
/// # use std::error::Error;
/// #
/// # fn try_main() -> Result<(), Box<Error>> {
/// # let mut guild = GuildId(0).get()?;
/// # let mut guild = GuildId(0).to_partial_guild()?;
/// use serenity::utils;
///
/// // assuming a `guild` has already been bound
Expand Down Expand Up @@ -126,7 +126,7 @@ impl EditGuild {
/// # use std::error::Error;
/// #
/// # fn try_main() -> Result<(), Box<Error>> {
/// # let mut guild = GuildId(0).get()?;
/// # let mut guild = GuildId(0).to_partial_guild()?;
/// use serenity::model::guild::Region;
///
/// // assuming a `guild` has already been bound
Expand Down
4 changes: 2 additions & 2 deletions src/framework/standard/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ impl StandardFramework {
return true;
}

if let Some(guild) = guild_id.find() {
if let Some(guild) = guild_id.to_guild_cached() {
return self.configuration
.blocked_users
.contains(&guild.with(|g| g.owner_id));
Expand Down Expand Up @@ -873,7 +873,7 @@ impl StandardFramework {
///
/// client.with_framework(StandardFramework::new()
/// .before(|_, msg, cmd_name| {
/// if let Ok(channel) = msg.channel_id.get() {
/// if let Ok(channel) = msg.channel_id.to_channel() {
/// // Don't run unless in nsfw channel
/// if !channel.is_nsfw() {
/// return false;
Expand Down
28 changes: 25 additions & 3 deletions src/model/channel/channel_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,14 +285,35 @@ impl ChannelId {

/// Search the cache for the channel with the Id.
#[cfg(feature = "cache")]
pub fn find(&self) -> Option<Channel> { CACHE.read().channel(*self) }
#[deprecated(since = "0.5.8", note = "Use the `to_channel_cached`-method instead.")]
pub fn find(&self) -> Option<Channel> { self.to_channel_cached() }

/// Attempts to find a [`Channel`] by its Id in the cache.
///
/// [`Channel`]: ../channel/enum.Channel.html
#[cfg(feature = "cache")]
#[inline]
pub fn to_channel_cached(self) -> Option<Channel> { CACHE.read().channel(self) }

/// Search the cache for the channel. If it can't be found, the channel is
/// requested over REST.
#[deprecated(since = "0.5.8", note = "Use the `to_channel`-method instead.")]
pub fn get(&self) -> Result<Channel> {
self.to_channel()
}

/// First attempts to find a [`Channel`] by its Id in the cache,
/// upon failure requests it via the REST API.
///
/// **Note**: If the cache is not enabled,
/// REST API will be used only.
///
/// [`Channel`]: ../channel/enum.Channel.html
#[inline]
pub fn to_channel(self) -> Result<Channel> {
#[cfg(feature = "cache")]
{
if let Some(channel) = CACHE.read().channel(*self) {
if let Some(channel) = CACHE.read().channel(self) {
return Ok(channel);
}
}
Expand All @@ -303,6 +324,7 @@ impl ChannelId {
/// Gets all of the channel's invites.
///
/// Requires the [Manage Channels] permission.
///
/// [Manage Channels]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_CHANNELS
#[inline]
pub fn invites(&self) -> Result<Vec<RichInvite>> { http::get_channel_invites(self.0) }
Expand Down Expand Up @@ -363,7 +385,7 @@ impl ChannelId {
use self::Channel::*;

let finding = feature_cache! {{
Some(self.find())
Some(self.to_channel_cached())
} else {
None
}};
Expand Down
4 changes: 2 additions & 2 deletions src/model/channel/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ impl Message {
for id in &self.mention_roles {
let mention = id.mention();

if let Some(role) = id.find() {
if let Some(role) = id.to_role_cached() {
result = result.replace(&mention, &format!("@{}", role.name));
} else {
result = result.replace(&mention, "@deleted-role");
Expand Down Expand Up @@ -429,7 +429,7 @@ impl Message {
///
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [`Emoji`]: ../guild/struct.Emoji.html
/// [Add Reactions]:
/// [Add Reactions]:
/// ../permissions/struct.Permissions.html#associatedconstant.ADD_REACTIONS
/// [permissions]: ../permissions/index.html
#[inline]
Expand Down
30 changes: 26 additions & 4 deletions src/model/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ use http::AttachmentType;
#[cfg(feature = "model")]
use std::fmt::{Display, Formatter, Result as FmtResult};

#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
use std::str::FromStr;
#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
use model::misc::ChannelParseError;
#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
use utils::parse_channel;

/// A container for any channel.
#[derive(Clone, Debug)]
pub enum Channel {
Expand Down Expand Up @@ -74,7 +81,7 @@ impl Channel {
/// #
/// # #[cfg(feature = "model")]
/// # fn main() {
/// # let channel = ChannelId(0).get().unwrap();
/// # let channel = ChannelId(0).to_channel().unwrap();
/// #
/// match channel.group() {
/// Some(group_lock) => {
Expand Down Expand Up @@ -116,7 +123,7 @@ impl Channel {
/// #
/// # #[cfg(feature = "model")]
/// # fn main() {
/// # let channel = ChannelId(0).get().unwrap();
/// # let channel = ChannelId(0).to_channel().unwrap();
/// #
/// match channel.guild() {
/// Some(guild_lock) => {
Expand Down Expand Up @@ -154,7 +161,7 @@ impl Channel {
/// #
/// # #[cfg(feature = "model")]
/// # fn main() {
/// # let channel = ChannelId(0).get().unwrap();
/// # let channel = ChannelId(0).to_channel().unwrap();
/// #
/// match channel.private() {
/// Some(private_lock) => {
Expand Down Expand Up @@ -195,7 +202,7 @@ impl Channel {
/// #
/// # #[cfg(feature = "model")]
/// # fn main() {
/// # let channel = ChannelId(0).get().unwrap();
/// # let channel = ChannelId(0).to_channel().unwrap();
/// #
/// match channel.category() {
/// Some(category_lock) => {
Expand Down Expand Up @@ -793,3 +800,18 @@ mod test {
}
}
}

#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
impl FromStr for Channel {
type Err = ChannelParseError;

fn from_str(s: &str) -> StdResult<Self, Self::Err> {
match parse_channel(s) {
Some(x) => match ChannelId(x).to_channel_cached() {
Some(channel) => Ok(channel),
_ => Err(ChannelParseError::NotPresentInCache),
},
_ => Err(ChannelParseError::InvalidChannel),
}
}
}
4 changes: 2 additions & 2 deletions src/model/channel/reaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl Reaction {
/// [Read Message History]: ../permissions/struct.Permissions.html#associatedconstant.READ_MESSAGE_HISTORY
#[inline]
pub fn channel(&self) -> Result<Channel> {
self.channel_id.get()
self.channel_id.to_channel()
}

/// Deletes the reaction, but only if the current user is the user who made
Expand Down Expand Up @@ -123,7 +123,7 @@ impl Reaction {
/// the REST API for the user.
#[inline]
pub fn user(&self) -> Result<User> {
self.user_id.get()
self.user_id.to_user()
}

/// Retrieves the list of [`User`]s who have reacted to a [`Message`] with a
Expand Down
28 changes: 23 additions & 5 deletions src/model/guild/guild_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,17 +402,35 @@ impl GuildId {
http::edit_role_position(self.0, role_id.0, position)
}


/// Search the cache for the guild.
#[cfg(feature = "cache")]
pub fn find(&self) -> Option<Arc<RwLock<Guild>>> { CACHE.read().guild(*self) }
#[deprecated(since = "0.5.8", note = "Use the `to_guild_cached`-method instead.")]
pub fn find(&self) -> Option<Arc<RwLock<Guild>>> { self.to_guild_cached() }

/// Tries to find the [`Guild`] by its Id in the cache.
///
/// [`Guild`]: ../guild/struct.Guild.html
#[cfg(feature = "cache")]
#[inline]
pub fn to_guild_cached(self) -> Option<Arc<RwLock<Guild>>> { CACHE.read().guild(self) }

/// Requests the guild over REST.
///
/// Note that this will not be a complete guild, as REST does not send
/// all data with a guild retrieval.
#[inline]
pub fn get(&self) -> Result<PartialGuild> { http::get_guild(self.0) }
#[deprecated(since = "0.5.8", note = "Use the `to_partial_guild`-method instead.")]
pub fn get(&self) -> Result<PartialGuild> { self.to_partial_guild() }

/// Requests [`PartialGuild`] over REST API.
///
/// **Note**: This will not be a [`Guild`], as the REST API does not send
/// all data with a guild retrieval.
///
/// [`PartialGuild`]: ../guild/struct.PartialGuild.html
/// [`Guild`]: ../guild/struct.Guild.html
#[inline]
pub fn to_partial_guild(self) -> Result<PartialGuild> { http::get_guild(self.0) }

/// Gets all integration of the guild.
///
Expand Down Expand Up @@ -443,8 +461,8 @@ impl GuildId {
#[inline]
pub fn leave(&self) -> Result<()> { http::leave_guild(self.0) }

/// Gets a user's [`Member`] for the guild by Id.
///
/// Gets a user's [`Member`] for the guild by Id.
///
/// If the cache feature is enabled the cache will be checked
/// first. If not found it will resort to an http request.
///
Expand Down
8 changes: 4 additions & 4 deletions src/model/guild/member.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ impl Member {
/// one returns `None`)
#[cfg(feature = "cache")]
pub fn default_channel(&self) -> Option<Arc<RwLock<GuildChannel>>> {
let guild = match self.guild_id.find() {
let guild = match self.guild_id.to_guild_cached() {
Some(guild) => guild,
None => return None,
};
Expand Down Expand Up @@ -257,7 +257,7 @@ impl Member {
/// role with the lowest ID is the highest.
#[cfg(feature = "cache")]
pub fn highest_role_info(&self) -> Option<(RoleId, i64)> {
let guild = self.guild_id.find()?;
let guild = self.guild_id.to_guild_cached()?;
let reader = guild.try_read()?;

let mut highest = None;
Expand Down Expand Up @@ -356,7 +356,7 @@ impl Member {
/// [`ModelError::ItemMissing`]: ../error/enum.Error.html#variant.ItemMissing
#[cfg(feature = "cache")]
pub fn permissions(&self) -> Result<Permissions> {
let guild = match self.guild_id.find() {
let guild = match self.guild_id.to_guild_cached() {
Some(guild) => guild,
None => return Err(From::from(ModelError::GuildNotFound)),
};
Expand Down Expand Up @@ -427,7 +427,7 @@ impl Member {
pub fn roles(&self) -> Option<Vec<Role>> {
self
.guild_id
.find()
.to_guild_cached()
.map(|g| g
.read()
.roles
Expand Down
4 changes: 2 additions & 2 deletions src/model/guild/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ impl Guild {
///
/// Requires that the current user be in the guild.
#[inline]
pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { guild_id.into().get() }
pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { guild_id.into().to_partial_guild() }

/// Returns which of two [`User`]s has a higher [`Member`] hierarchy.
///
Expand Down Expand Up @@ -1518,7 +1518,7 @@ impl Guild {
///
/// impl EventHandler for Handler {
/// fn message(&self, _: Context, msg: Message) {
/// if let Some(arc) = msg.guild_id().unwrap().find() {
/// if let Some(arc) = msg.guild_id().unwrap().to_guild_cached() {
/// if let Some(role) = arc.read().role_by_name("role_name") {
/// println!("{:?}", role);
/// }
Expand Down
6 changes: 3 additions & 3 deletions src/model/guild/partial_guild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ impl PartialGuild {
///
/// [`Emoji`]: struct.Emoji.html
/// [`Emoji::edit`]: struct.Emoji.html#method.edit
/// [Manage Emojis]:
/// [Manage Emojis]:
/// ../permissions/struct.Permissions.html#associatedconstant.MANAGE_EMOJIS
#[inline]
pub fn edit_emoji<E: Into<EmojiId>>(&self, emoji_id: E, name: &str) -> Result<Emoji> {
Expand Down Expand Up @@ -292,7 +292,7 @@ impl PartialGuild {
///
/// Requires that the current user be in the guild.
#[inline]
pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { guild_id.into().get() }
pub fn get<G: Into<GuildId>>(guild_id: G) -> Result<PartialGuild> { guild_id.into().to_partial_guild() }

/// Kicks a [`Member`] from the guild.
///
Expand Down Expand Up @@ -468,7 +468,7 @@ impl PartialGuild {
///
/// impl EventHandler for Handler {
/// fn message(&self, _: Context, msg: Message) {
/// let guild = msg.guild_id().unwrap().get().unwrap();
/// let guild = msg.guild_id().unwrap().to_partial_guild().unwrap();
/// let possible_role = guild.role_by_name("role_name");
///
/// if let Some(role) = possible_role {
Expand Down
Loading

0 comments on commit 71edc3a

Please sign in to comment.