Skip to content

Commit

Permalink
Fall back to str::parse on ChannelId as well
Browse files Browse the repository at this point in the history
Also give an actual error type for `Channel` too.
  • Loading branch information
arqunis committed Dec 6, 2017
1 parent d45d19d commit 0525ede
Showing 1 changed file with 56 additions and 7 deletions.
63 changes: 56 additions & 7 deletions src/model/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,26 +227,75 @@ impl FromStr for EmojiIdentifier {
fn from_str(s: &str) -> StdResult<Self, ()> { utils::parse_emoji(s).ok_or_else(|| ()) }
}

#[cfg(all(feature = "model", feature = "utils"))]
#[derive(Debug)]
pub enum ChannelIdParseError {
InvalidFormat,
}

#[cfg(all(feature = "model", feature = "utils"))]
impl fmt::Display for ChannelIdParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) }
}

#[cfg(all(feature = "model", feature = "utils"))]
impl StdError for ChannelIdParseError {
fn description(&self) -> &str {
use self::ChannelIdParseError::*;

match *self {
InvalidFormat => "invalid channel id format",
}
}
}

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

fn from_str(s: &str) -> StdResult<Self, Self::Err> {
Ok(match utils::parse_channel(s) {
Some(channel) => ChannelId(channel),
None => s.parse::<u64>().map(ChannelId).map_err(|_| ChannelIdParseError::InvalidFormat)?,
})
}
}

#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
#[derive(Debug)]
pub enum ChannelParseError {
NotPresentInCache,
InvalidChannel,
}

#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
impl fmt::Display for ChannelParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) }
}

#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
impl StdError for ChannelParseError {
fn description(&self) -> &str {
use self::ChannelParseError::*;

fn from_str(s: &str) -> StdResult<Self, ()> {
utils::parse_channel(s).ok_or_else(|| ()).map(ChannelId)
match *self {
NotPresentInCache => "not present in cache",
InvalidChannel => "invalid channel",
}
}
}

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

fn from_str(s: &str) -> StdResult<Self, ()> {
fn from_str(s: &str) -> StdResult<Self, Self::Err> {
match utils::parse_channel(s) {
Some(x) => match ChannelId(x).find() {
Some(channel) => Ok(channel),
_ => Err(()),
_ => Err(ChannelParseError::NotPresentInCache),
},
_ => Err(()),
_ => Err(ChannelParseError::InvalidChannel),
}
}
}
Expand Down

0 comments on commit 0525ede

Please sign in to comment.