Reintroduce macro for enum Display and FromStr impls.

This commit is contained in:
Jimmy Cuadra 2016-10-01 04:25:45 -07:00
parent 1fe0436f0e
commit f3acdfd141
9 changed files with 92 additions and 0 deletions

View File

@ -26,3 +26,10 @@ pub enum SessionDescriptionType {
#[serde(rename="offer")]
Offer,
}
impl_enum! {
SessionDescriptionType {
Answer => "answer",
Offer => "offer",
}
}

View File

@ -16,6 +16,8 @@ use serde::{Deserialize, Deserializer, Error as SerdeError, Serialize, Serialize
use serde::de::Visitor;
use serde_json::Value;
#[macro_use] mod macros;
pub mod call;
pub mod presence;
pub mod receipt;
@ -24,6 +26,9 @@ pub mod stripped;
pub mod tag;
pub mod typing;
/// An error when attempting to convert a string to an enum that only accepts certain values.
pub struct ParseError;
/// The type of an event.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum EventType {

24
src/macros.rs Normal file
View File

@ -0,0 +1,24 @@
macro_rules! impl_enum {
($name:ident { $($variant:ident => $s:expr,)+ }) => {
impl ::std::fmt::Display for $name {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
let variant = match *self {
$($name::$variant => $s,)*
};
write!(f, "{}", variant)
}
}
impl ::std::str::FromStr for $name {
type Err = $crate::ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
$($s => Ok($name::$variant),)*
_ => Err($crate::ParseError),
}
}
}
}
}

View File

@ -54,3 +54,11 @@ pub struct PresenceEventExtraContent {
/// The unique identifier for the event.
pub event_id: EventId,
}
impl_enum! {
PresenceState {
Offline => "offline",
Online => "online",
Unavailable => "unavailable",
}
}

View File

@ -26,3 +26,10 @@ pub enum GuestAccess {
#[serde(rename="forbidden")]
Forbidden,
}
impl_enum! {
GuestAccess {
CanJoin => "can_join",
Forbidden => "forbidden",
}
}

View File

@ -38,3 +38,12 @@ pub enum HistoryVisibility {
#[serde(rename="world_readable")]
WorldReadable,
}
impl_enum! {
HistoryVisibility {
Invited => "invited",
Joined => "joined",
Shared => "shared",
WorldReadable => "world_readable",
}
}

View File

@ -32,3 +32,12 @@ pub enum JoinRule {
#[serde(rename="public")]
Public,
}
impl_enum! {
JoinRule {
Invite => "invite",
Knock => "knock",
Private => "private",
Public => "public",
}
}

View File

@ -67,3 +67,13 @@ pub struct MemberEventExtraContent {
#[serde(skip_serializing_if="Option::is_none")]
pub invite_room_state: Option<Vec<StrippedState>>,
}
impl_enum! {
MembershipState {
Ban => "ban",
Invite => "invite",
Join => "join",
Knock => "knock",
Leave => "leave",
}
}

View File

@ -238,6 +238,19 @@ pub struct VideoInfo {
pub w: Option<u64>,
}
impl_enum! {
MessageType {
Audio => "m.audio",
Emote => "m.emote",
File => "m.file",
Image => "m.image",
Location => "m.location",
Notice => "m.notice",
Text => "m.text",
Video => "m.video",
}
}
impl Serialize for MessageEventContent {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
match *self {