aboutsummaryrefslogtreecommitdiff
path: root/src/utils
diff options
context:
space:
mode:
authorZeyla Hellyer <[email protected]>2017-04-11 08:15:37 -0700
committerZeyla Hellyer <[email protected]>2017-04-11 10:52:43 -0700
commitf6b27eb39c042e6779edc2d5d4b6e6c27d133eaf (patch)
treea6169fee3bf9ea75391101577dcb2982e3daa388 /src/utils
parentClippy lints + permission byte literals (diff)
downloadserenity-f6b27eb39c042e6779edc2d5d4b6e6c27d133eaf.tar.xz
serenity-f6b27eb39c042e6779edc2d5d4b6e6c27d133eaf.zip
Switch to using serde for deserialization
The current build system is rudimentary, incomplete, and rigid, offering little in the way of customizing decoding options. To solve this, switch to using serde-derive with custom Deserialization implementations. This allows very simple deserialization when special logic does not need to be applied, yet allows us to implement our own deserialization logic when required. The problem with the build system was that it built enums and structs from YAML files. This is not so good, because it requires creating a custom build system (which was rudimentary), creating "special struct configs" when logic needed to be ever so slightly extended (rigid), and if special logic needed to be applied, a custom deserialization method would have been needed to be made anyway (incomplete). To solve this, switch to serde-derive and implementing Deserialize ourselves where required. This reduces YAML definitions that might look like: ```yaml --- name: Group description: > A group channel, potentially including other users, separate from a [`Guild`]. [`Guild`]: struct.Guild.html fields: - name: channel_id description: The Id of the group channel. from: id type: ChannelId - name: icon description: The optional icon of the group channel. optional: true type: string - name: last_message_id description: The Id of the last message sent. optional: true type: MessageId - name: last_pin_timestamp description: Timestamp of the latest pinned message. optional: true type: string - name: name description: The name of the group channel. optional: true type: string - name: owner_id description: The Id of the group channel creator. type: UserId - name: recipients description: Group channel's members. custom: decode_users t: UserId, Arc<RwLock<User>> type: hashmap ``` to: ```rs /// A group channel - potentially including other [`User`]s - separate from a /// [`Guild`]. /// /// [`Guild`]: struct.Guild.html /// [`User`]: struct.User.html pub struct Group { /// The Id of the group channel. #[serde(rename="id")] pub channel_id: ChannelId, /// The optional icon of the group channel. pub icon: Option<String>, /// The Id of the last message sent. pub last_message_id: Option<MessageId>, /// Timestamp of the latest pinned message. pub last_pin_timestamp: Option<String>, /// The name of the group channel. pub name: Option<String>, /// The Id of the group owner. pub owner_id: UserId, /// A map of the group's recipients. #[serde(deserialize_with="deserialize_users")] pub recipients: HashMap<UserId, Arc<RwLock<User>>>, } ``` This is much simpler and does not have as much boilerplate. There should not be any backwards incompatible changes other than the old, public - yet undocumented (and hidden from documentation) - decode methods being removed. Due to the nature of this commit, field names may be incorrect, and will need to be corrected as deserialization errors are found.
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/builder/create_embed.rs105
-rw-r--r--src/utils/builder/create_invite.rs33
-rw-r--r--src/utils/builder/create_message.rs8
-rw-r--r--src/utils/builder/edit_channel.rs41
-rw-r--r--src/utils/builder/edit_guild.rs74
-rw-r--r--src/utils/builder/edit_member.rs44
-rw-r--r--src/utils/builder/edit_profile.rs46
-rw-r--r--src/utils/builder/edit_role.rs76
-rw-r--r--src/utils/builder/execute_webhook.rs39
-rw-r--r--src/utils/colour.rs14
-rw-r--r--src/utils/macros.rs55
-rw-r--r--src/utils/mod.rs13
12 files changed, 324 insertions, 224 deletions
diff --git a/src/utils/builder/create_embed.rs b/src/utils/builder/create_embed.rs
index 86d5b11..7c1c606 100644
--- a/src/utils/builder/create_embed.rs
+++ b/src/utils/builder/create_embed.rs
@@ -15,11 +15,10 @@
//! [`ExecuteWebhook::embeds`]: struct.ExecuteWebhook.html#method.embeds
//! [here]: https://discordapp.com/developers/docs/resources/channel#embed-object
-use serde_json::builder::ObjectBuilder;
use serde_json::Value;
-use std::collections::BTreeMap;
use std::default::Default;
use time::Tm;
+use ::internal::prelude::*;
use ::model::Embed;
use ::utils::Colour;
@@ -34,7 +33,7 @@ use ::utils::Colour;
/// [`Context::send_message`]: ../../client/struct.Context.html#method.send_message
/// [`Embed`]: ../../model/struct.Embed.html
/// [`ExecuteWebhook::embeds`]: struct.ExecuteWebhook.html#method.embeds
-pub struct CreateEmbed(pub BTreeMap<String, Value>);
+pub struct CreateEmbed(pub Map<String, Value>);
impl CreateEmbed {
/// Set the author of the embed.
@@ -45,9 +44,9 @@ impl CreateEmbed {
/// [`CreateEmbedAuthor`]: struct.CreateEmbedAuthor.html
pub fn author<F>(mut self, f: F) -> Self
where F: FnOnce(CreateEmbedAuthor) -> CreateEmbedAuthor {
- let author = f(CreateEmbedAuthor::default()).0.build();
+ let author = f(CreateEmbedAuthor::default()).0;
- self.0.insert("author".to_owned(), author);
+ self.0.insert("author".to_owned(), Value::Object(author));
CreateEmbed(self.0)
}
@@ -63,7 +62,7 @@ impl CreateEmbed {
/// Set the colour of the left-hand side of the embed.
pub fn colour<C: Into<Colour>>(mut self, colour: C) -> Self {
- self.0.insert("color".to_owned(), Value::U64(colour.into().0 as u64));
+ self.0.insert("color".to_owned(), Value::Number(Number::from(colour.into().0 as u64)));
CreateEmbed(self.0)
}
@@ -89,7 +88,7 @@ impl CreateEmbed {
/// [`CreateEmbedField`]: struct.CreateEmbedField.html
pub fn field<F>(mut self, f: F) -> Self
where F: FnOnce(CreateEmbedField) -> CreateEmbedField {
- let field = f(CreateEmbedField::default()).0.build();
+ let field = f(CreateEmbedField::default()).0;
{
let key = "fields".to_owned();
@@ -106,7 +105,7 @@ impl CreateEmbed {
return CreateEmbed(self.0);
},
};
- arr.push(field);
+ arr.push(Value::Object(field));
self.0.insert("fields".to_owned(), Value::Array(arr));
}
@@ -122,18 +121,18 @@ impl CreateEmbed {
/// [`CreateEmbedFooter`]: struct.CreateEmbedFooter.html
pub fn footer<F>(mut self, f: F) -> Self
where F: FnOnce(CreateEmbedFooter) -> CreateEmbedFooter {
- let footer = f(CreateEmbedFooter::default()).0.build();
+ let footer = f(CreateEmbedFooter::default()).0;
- self.0.insert("footer".to_owned(), footer);
+ self.0.insert("footer".to_owned(), Value::Object(footer));
CreateEmbed(self.0)
}
/// Set the image associated with the embed. This only supports HTTP(S).
pub fn image(mut self, url: &str) -> Self {
- let image = ObjectBuilder::new()
- .insert("url".to_owned(), url.to_owned())
- .build();
+ let image = json!({
+ "url": url.to_owned()
+ });
self.0.insert("image".to_owned(), image);
@@ -142,9 +141,9 @@ impl CreateEmbed {
/// Set the thumbnail of the embed. This only supports HTTP(S).
pub fn thumbnail(mut self, url: &str) -> Self {
- let thumbnail = ObjectBuilder::new()
- .insert("url".to_owned(), url.to_owned())
- .build();
+ let thumbnail = json!({
+ "url": url.to_owned(),
+ });
self.0.insert("thumbnail".to_owned(), thumbnail);
@@ -198,7 +197,7 @@ impl CreateEmbed {
impl Default for CreateEmbed {
/// Creates a builder with default values, setting the `type` to `rich`.
fn default() -> CreateEmbed {
- let mut map = BTreeMap::new();
+ let mut map = Map::new();
map.insert("type".to_owned(), Value::String("rich".to_owned()));
CreateEmbed(map)
@@ -233,13 +232,11 @@ impl From<Embed> for CreateEmbed {
b = b.description(&description);
}
- if let Some(fields) = embed.fields {
- for field in fields {
- b = b.field(move |f| f
- .inline(field.inline)
- .name(&field.name)
- .value(&field.value));
- }
+ for field in embed.fields {
+ b = b.field(move |f| f
+ .inline(field.inline)
+ .name(&field.name)
+ .value(&field.value));
}
if let Some(image) = embed.image {
@@ -266,7 +263,6 @@ impl From<Embed> for CreateEmbed {
}
}
-
/// A builder to create a fake [`Embed`] object's author, for use with the
/// [`CreateEmbed::author`] method.
///
@@ -276,22 +272,28 @@ impl From<Embed> for CreateEmbed {
/// [`CreateEmbed::author`]: struct.CreateEmbed.html#method.author
/// [`name`]: #method.name
#[derive(Default)]
-pub struct CreateEmbedAuthor(pub ObjectBuilder);
+pub struct CreateEmbedAuthor(pub Map<String, Value>);
impl CreateEmbedAuthor {
/// Set the URL of the author's icon.
- pub fn icon_url(self, icon_url: &str) -> Self {
- CreateEmbedAuthor(self.0.insert("icon_url", icon_url))
+ pub fn icon_url(mut self, icon_url: &str) -> Self {
+ self.0.insert("icon_url".to_owned(), Value::String(icon_url.to_owned()));
+
+ self
}
/// Set the author's name.
- pub fn name(self, name: &str) -> Self {
- CreateEmbedAuthor(self.0.insert("name", name))
+ pub fn name(mut self, name: &str) -> Self {
+ self.0.insert("name".to_owned(), Value::String(name.to_owned()));
+
+ self
}
/// Set the author's URL.
- pub fn url(self, url: &str) -> Self {
- CreateEmbedAuthor(self.0.insert("url", url))
+ pub fn url(mut self, url: &str) -> Self {
+ self.0.insert("url".to_owned(), Value::String(url.to_owned()));
+
+ self
}
}
@@ -303,22 +305,28 @@ impl CreateEmbedAuthor {
///
/// [`Embed`]: ../../model/struct.Embed.html
/// [`CreateEmbed::field`]: struct.CreateEmbed.html#method.field
-pub struct CreateEmbedField(pub ObjectBuilder);
+pub struct CreateEmbedField(pub Map<String, Value>);
impl CreateEmbedField {
/// Set whether the field is inlined. Set to true by default.
- pub fn inline(self, inline: bool) -> Self {
- CreateEmbedField(self.0.insert("inline", inline))
+ pub fn inline(mut self, inline: bool) -> Self {
+ self.0.insert("inline".to_owned(), Value::Bool(inline));
+
+ self
}
/// Set the field's name. It can't be longer than 256 characters.
- pub fn name(self, name: &str) -> Self {
- CreateEmbedField(self.0.insert("name", name))
+ pub fn name(mut self, name: &str) -> Self {
+ self.0.insert("name".to_owned(), Value::String(name.to_owned()));
+
+ self
}
/// Set the field's value. It can't be longer than 1024 characters.
- pub fn value(self, value: &str) -> Self {
- CreateEmbedField(self.0.insert("value", value))
+ pub fn value(mut self, value: &str) -> Self {
+ self.0.insert("value".to_owned(), Value::String(value.to_owned()));
+
+ self
}
}
@@ -326,7 +334,10 @@ impl Default for CreateEmbedField {
/// Creates a builder with default values, setting the value of `inline` to
/// `true`.
fn default() -> CreateEmbedField {
- CreateEmbedField(ObjectBuilder::new().insert("inline", true))
+ let mut map = Map::new();
+ map.insert("inline".to_owned(), Value::Bool(true));
+
+ CreateEmbedField(map)
}
}
@@ -338,17 +349,21 @@ impl Default for CreateEmbedField {
/// [`Embed`]: ../../model/struct.Embed.html
/// [`CreateEmbed::footer`]: struct.CreateEmbed.html#method.footer
#[derive(Default)]
-pub struct CreateEmbedFooter(pub ObjectBuilder);
+pub struct CreateEmbedFooter(pub Map<String, Value>);
impl CreateEmbedFooter {
/// Set the icon URL's value. This only supports HTTP(S).
- pub fn icon_url(self, icon_url: &str) -> Self {
- CreateEmbedFooter(self.0.insert("icon_url", icon_url))
+ pub fn icon_url(mut self, icon_url: &str) -> Self {
+ self.0.insert("icon_url".to_owned(), Value::String(icon_url.to_owned()));
+
+ self
}
/// Set the footer's text.
- pub fn text(self, text: &str) -> Self {
- CreateEmbedFooter(self.0.insert("text", text))
+ pub fn text(mut self, text: &str) -> Self {
+ self.0.insert("text".to_owned(), Value::String(text.to_owned()));
+
+ self
}
}
diff --git a/src/utils/builder/create_invite.rs b/src/utils/builder/create_invite.rs
index 99125b3..d7595cd 100644
--- a/src/utils/builder/create_invite.rs
+++ b/src/utils/builder/create_invite.rs
@@ -1,6 +1,6 @@
-use serde_json::builder::ObjectBuilder;
use serde_json::Value;
use std::default::Default;
+use ::internal::prelude::*;
/// A builder to create a [`RichInvite`] for use via [`Context::create_invite`].
///
@@ -28,7 +28,7 @@ use std::default::Default;
///
/// [`Context::create_invite`]: ../../client/struct.Context.html#method.create_invite
/// [`RichInvite`]: ../../model/struct.Invite.html
-pub struct CreateInvite(pub ObjectBuilder);
+pub struct CreateInvite(pub JsonMap);
impl CreateInvite {
/// The duration that the invite will be valid for.
@@ -36,8 +36,10 @@ impl CreateInvite {
/// Set to `0` for an invite which does not expire after an amount of time.
///
/// Defaults to `86400`, or 24 hours.
- pub fn max_age(self, max_age: u64) -> Self {
- CreateInvite(self.0.insert("max_age", max_age))
+ pub fn max_age(mut self, max_age: u64) -> Self {
+ self.0.insert("max_age".to_owned(), Value::Number(Number::from(max_age)));
+
+ self
}
/// The number of uses that the invite will be valid for.
@@ -45,28 +47,37 @@ impl CreateInvite {
/// Set to `0` for an invite which does not expire after a number of uses.
///
/// Defaults to `0`.
- pub fn max_uses(self, max_uses: u64) -> Self {
- CreateInvite(self.0.insert("max_uses", max_uses))
+ pub fn max_uses(mut self, max_uses: u64) -> Self {
+ self.0.insert("max_uses".to_owned(), Value::Number(Number::from(max_uses)));
+
+ self
}
/// Whether an invite grants a temporary membership.
///
/// Defaults to `false`.
- pub fn temporary(self, temporary: bool) -> Self {
- CreateInvite(self.0.insert("temporary", temporary))
+ pub fn temporary(mut self, temporary: bool) -> Self {
+ self.0.insert("temporary".to_owned(), Value::Bool(temporary));
+
+ self
}
/// Whether or not to try to reuse a similar invite.
///
/// Defaults to `false`.
- pub fn unique(self, unique: bool) -> Self {
- CreateInvite(self.0.insert("unique", unique))
+ pub fn unique(mut self, unique: bool) -> Self {
+ self.0.insert("unique".to_owned(), Value::Bool(unique));
+
+ self
}
}
impl Default for CreateInvite {
/// Creates a builder with default values, setting `validate` to `null`.
fn default() -> CreateInvite {
- CreateInvite(ObjectBuilder::new().insert("validate", Value::Null))
+ let mut map = Map::new();
+ map.insert("validate".to_owned(), Value::Null);
+
+ CreateInvite(map)
}
}
diff --git a/src/utils/builder/create_message.rs b/src/utils/builder/create_message.rs
index 8aed477..2dbbd79 100644
--- a/src/utils/builder/create_message.rs
+++ b/src/utils/builder/create_message.rs
@@ -1,7 +1,5 @@
-use serde_json::Value;
-use std::collections::BTreeMap;
-use std::default::Default;
use super::CreateEmbed;
+use ::internal::prelude::*;
/// A builder to specify the contents of an [`rest::send_message`] request,
/// primarily meant for use through [`Context::send_message`].
@@ -38,7 +36,7 @@ use super::CreateEmbed;
/// [`content`]: #method.content
/// [`embed`]: #method.embed
/// [`rest::send_message`]: ../../client/rest/fn.send_message.html
-pub struct CreateMessage(pub BTreeMap<String, Value>);
+pub struct CreateMessage(pub Map<String, Value>);
impl CreateMessage {
/// Set the content of the message.
@@ -79,7 +77,7 @@ impl Default for CreateMessage {
/// [`Message`]: ../../model/struct.Message.html
/// [`tts`]: #method.tts
fn default() -> CreateMessage {
- let mut map = BTreeMap::default();
+ let mut map = Map::default();
map.insert("tts".to_owned(), Value::Bool(false));
CreateMessage(map)
diff --git a/src/utils/builder/edit_channel.rs b/src/utils/builder/edit_channel.rs
index e136cbf..2fa61a5 100644
--- a/src/utils/builder/edit_channel.rs
+++ b/src/utils/builder/edit_channel.rs
@@ -1,5 +1,4 @@
-use serde_json::builder::ObjectBuilder;
-use std::default::Default;
+use ::internal::prelude::*;
/// A builder to edit a [`GuildChannel`] for use via one of a couple methods.
///
@@ -24,7 +23,8 @@ use std::default::Default;
/// [`Context::edit_channel`]: ../client/struct.Context.html#method.edit_channel
/// [`GuildChannel`]: ../model/struct.GuildChannel.html
/// [`GuildChannel::edit`]: ../model/struct.GuildChannel.html#method.edit
-pub struct EditChannel(pub ObjectBuilder);
+#[derive(Default)]
+pub struct EditChannel(pub JsonMap);
impl EditChannel {
/// The bitrate of the channel in bits.
@@ -32,20 +32,26 @@ impl EditChannel {
/// This is for [voice] channels only.
///
/// [voice]: ../../model/enum.ChannelType.html#variant.Voice
- pub fn bitrate(self, bitrate: u64) -> Self {
- EditChannel(self.0.insert("bitrate", bitrate))
+ pub fn bitrate(mut self, bitrate: u64) -> Self {
+ self.0.insert("bitrate".to_owned(), Value::Number(Number::from(bitrate)));
+
+ self
}
/// The name of the channel.
///
/// Must be between 2 and 100 characters long.
- pub fn name(self, name: &str) -> Self {
- EditChannel(self.0.insert("name", name))
+ pub fn name(mut self, name: &str) -> Self {
+ self.0.insert("name".to_owned(), Value::String(name.to_owned()));
+
+ self
}
/// The position of the channel in the channel list.
- pub fn position(self, position: u64) -> Self {
- EditChannel(self.0.insert("position", position))
+ pub fn position(mut self, position: u64) -> Self {
+ self.0.insert("position".to_owned(), Value::Number(Number::from(position)));
+
+ self
}
/// The topic of the channel. Can be empty.
@@ -55,8 +61,10 @@ impl EditChannel {
/// This is for [text] channels only.
///
/// [text]: ../../model/enum.ChannelType.html#variant.Text
- pub fn topic(self, topic: &str) -> Self {
- EditChannel(self.0.insert("topic", topic))
+ pub fn topic(mut self, topic: &str) -> Self {
+ self.0.insert("topic".to_owned(), Value::String(topic.to_owned()));
+
+ self
}
/// The number of users that may be in the channel simultaneously.
@@ -64,14 +72,9 @@ impl EditChannel {
/// This is for [voice] channels only.
///
/// [voice]: ../../model/enum.ChannelType.html#variant.Voice
- pub fn user_limit(self, user_limit: u64) -> Self {
- EditChannel(self.0.insert("user_limit", user_limit))
- }
-}
+ pub fn user_limit(mut self, user_limit: u64) -> Self {
+ self.0.insert("user_limit".to_owned(), Value::Number(Number::from(user_limit)));
-impl Default for EditChannel {
- /// Creates a builder with no default parameters.
- fn default() -> EditChannel {
- EditChannel(ObjectBuilder::new())
+ self
}
}
diff --git a/src/utils/builder/edit_guild.rs b/src/utils/builder/edit_guild.rs
index 83d5016..bd94efa 100644
--- a/src/utils/builder/edit_guild.rs
+++ b/src/utils/builder/edit_guild.rs
@@ -1,6 +1,4 @@
-use serde_json::builder::ObjectBuilder;
-use serde_json::Value;
-use std::default::Default;
+use ::internal::prelude::*;
use ::model::{ChannelId, Region, UserId, VerificationLevel};
/// A builder to optionally edit certain fields of a [`Guild`]. This is meant
@@ -13,7 +11,8 @@ use ::model::{ChannelId, Region, UserId, VerificationLevel};
/// [`Guild`]: ../../model/struct.Guild.html
/// [`LiveGuild::edit`]: ../../model/struct.LiveGuild.html#method.edit
/// [Manage Guild]: ../../model/permissions/constant.MANAGE_GUILD.html
-pub struct EditGuild(pub ObjectBuilder);
+#[derive(Default)]
+pub struct EditGuild(pub Map<String, Value>);
impl EditGuild {
/// Set the "AFK voice channel" that users are to move to if they have been
@@ -24,19 +23,23 @@ impl EditGuild {
/// valid.
///
/// [`afk_timeout`]: #method.afk_timeout
- pub fn afk_channel<C: Into<ChannelId>>(self, channel: Option<C>) -> Self {
- EditGuild(self.0.insert("afk_channel_id", match channel {
- Some(channel) => Value::U64(channel.into().0),
+ pub fn afk_channel<C: Into<ChannelId>>(mut self, channel: Option<C>) -> Self {
+ self.0.insert("afk_channel_id".to_owned(), match channel {
+ Some(channel) => Value::Number(Number::from(channel.into().0)),
None => Value::Null,
- }))
+ });
+
+ self
}
/// Set the amount of time a user is to be moved to the AFK channel -
/// configured via [`afk_channel`] - after being AFK.
///
/// [`afk_channel`]: #method.afk_channel
- pub fn afk_timeout(self, timeout: u64) -> Self {
- EditGuild(self.0.insert("afk_timeout", timeout))
+ pub fn afk_timeout(mut self, timeout: u64) -> Self {
+ self.0.insert("afk_timeout".to_owned(), Value::Number(Number::from(timeout)));
+
+ self
}
/// Set the icon of the guild. Pass `None` to remove the icon.
@@ -58,25 +61,28 @@ impl EditGuild {
/// ```
///
/// [`utils::read_image`]: ../../utils/fn.read_image.html
- pub fn icon(self, icon: Option<&str>) -> Self {
- EditGuild(self.0
- .insert("icon",
- icon.map_or_else(|| Value::Null,
- |x| Value::String(x.to_owned()))))
+ pub fn icon(mut self, icon: Option<&str>) -> Self {
+ self.0.insert("icon".to_owned(), icon.map_or_else(|| Value::Null, |x| Value::String(x.to_owned())));
+
+ self
}
/// Set the name of the guild.
///
/// **Note**: Must be between (and including) 2-100 chracters.
- pub fn name(self, name: &str) -> Self {
- EditGuild(self.0.insert("name", name))
+ pub fn name(mut self, name: &str) -> Self {
+ self.0.insert("name".to_owned(), Value::String(name.to_owned()));
+
+ self
}
/// Transfers the ownership of the guild to another user by Id.
///
/// **Note**: The current user must be the owner of the guild.
- pub fn owner<U: Into<UserId>>(self, user_id: U) -> Self {
- EditGuild(self.0.insert("owner_id", user_id.into().0))
+ pub fn owner<U: Into<UserId>>(mut self, user_id: U) -> Self {
+ self.0.insert("owner_id".to_owned(), Value::Number(Number::from(user_id.into().0)));
+
+ self
}
/// Set the voice region of the server.
@@ -96,8 +102,10 @@ impl EditGuild {
/// ```
///
/// [`Region::UsWest`]: ../../model/enum.Region.html#variant.UsWest
- pub fn region(self, region: Region) -> Self {
- EditGuild(self.0.insert("region", region.name()))
+ pub fn region(mut self, region: Region) -> Self {
+ self.0.insert("region".to_owned(), Value::String(region.name().to_owned()));
+
+ self
}
/// Set the splash image of the guild on the invitation page.
@@ -107,11 +115,12 @@ impl EditGuild {
///
/// [`InviteSplash`]: ../../model/enum.Feature.html#variant.InviteSplash
/// [`features`]: ../../model/struct.LiveGuild.html#structfield.features
- pub fn splash(self, splash: Option<&str>) -> Self {
- EditGuild(self.0
- .insert("splash",
- splash.map_or_else(|| Value::Null,
- |x| Value::String(x.to_owned()))))
+ pub fn splash(mut self, splash: Option<&str>) -> Self {
+ let splash = splash.map_or(Value::Null, |x| Value::String(x.to_owned()));
+
+ self.0.insert("splash".to_owned(), splash);
+
+ self
}
/// Set the verification level of the guild. This can restrict what a
@@ -145,15 +154,12 @@ impl EditGuild {
///
/// [`VerificationLevel`]: ../../model/enum.VerificationLevel.html
/// [`VerificationLevel::High`]: ../../model/enum.VerificationLevel.html#variant.High
- pub fn verification_level<V>(self, verification_level: V) -> Self
+ pub fn verification_level<V>(mut self, verification_level: V) -> Self
where V: Into<VerificationLevel> {
- EditGuild(self.0.insert("verification_level",
- verification_level.into().num()))
- }
-}
+ let num = Value::Number(Number::from(verification_level.into().num()));
+
+ self.0.insert("verification_level".to_owned(), num);
-impl Default for EditGuild {
- fn default() -> EditGuild {
- EditGuild(ObjectBuilder::new())
+ self
}
}
diff --git a/src/utils/builder/edit_member.rs b/src/utils/builder/edit_member.rs
index cb67214..58f260a 100644
--- a/src/utils/builder/edit_member.rs
+++ b/src/utils/builder/edit_member.rs
@@ -1,6 +1,5 @@
-use serde_json::builder::ObjectBuilder;
-use std::default::Default;
use ::model::{ChannelId, RoleId};
+use ::internal::prelude::*;
/// A builder which edits the properties of a [`Member`], to be used in
/// conjunction with [`Context::edit_member`] and [`Member::edit`].
@@ -8,7 +7,8 @@ use ::model::{ChannelId, RoleId};
/// [`Context::edit_member`]: ../../client/struct.Context.html#method.edit_member
/// [`Member`]: ../../model/struct.Member.html
/// [`Member::edit`]: ../../model/struct.Member.html#method.edit
-pub struct EditMember(pub ObjectBuilder);
+#[derive(Default)]
+pub struct EditMember(pub JsonMap);
impl EditMember {
/// Whether to deafen the member.
@@ -16,8 +16,10 @@ impl EditMember {
/// Requires the [Deafen Members] permission.
///
/// [Deafen Members]: ../../model/permissions/constant.DEAFEN_MEMBERS.html
- pub fn deafen(self, deafen: bool) -> Self {
- EditMember(self.0.insert("deaf", deafen))
+ pub fn deafen(mut self, deafen: bool) -> Self {
+ self.0.insert("deaf".to_owned(), Value::Bool(deafen));
+
+ self
}
/// Whether to mute the member.
@@ -25,8 +27,10 @@ impl EditMember {
/// Requires the [Mute Members] permission.
///
/// [Mute Members]: ../../model/permissions/constant.MUTE_MEMBERS.html
- pub fn mute(self, mute: bool) -> Self {
- EditMember(self.0.insert("mute", mute))
+ pub fn mute(mut self, mute: bool) -> Self {
+ self.0.insert("mute".to_owned(), Value::Bool(mute));
+
+ self
}
/// Changes the member's nickname. Pass an empty string to reset the
@@ -35,8 +39,10 @@ impl EditMember {
/// Requires the [Manage Nicknames] permission.
///
/// [Manage Nicknames]: ../../model/permissions/constant.MANAGE_NICKNAMES.html
- pub fn nickname(self, nickname: &str) -> Self {
- EditMember(self.0.insert("nick", nickname))
+ pub fn nickname(mut self, nickname: &str) -> Self {
+ self.0.insert("nick".to_owned(), Value::String(nickname.to_owned()));
+
+ self
}
/// Set the list of roles that the member should have.
@@ -44,10 +50,12 @@ impl EditMember {
/// Requires the [Manage Roles] permission to modify.
///
/// [Manage Roles]: ../../model/permissions/constant.MANAGE_ROLES.html
- pub fn roles(self, roles: &[RoleId]) -> Self {
- EditMember(self.0
- .insert_array("roles",
- |a| roles.iter().fold(a, |a, id| a.push(id.0))))
+ pub fn roles(mut self, roles: &[RoleId]) -> Self {
+ let role_ids = roles.iter().map(|x| Value::Number(Number::from(x.0))).collect();
+
+ self.0.insert("roles".to_owned(), Value::Array(role_ids));
+
+ self
}
/// The Id of the voice channel to move the member to.
@@ -55,13 +63,9 @@ impl EditMember {
/// Requires the [Move Members] permission.
///
/// [Move Members]: ../../model/permissions/constant.MOVE_MEMBERS.html
- pub fn voice_channel<C: Into<ChannelId>>(self, channel_id: C) -> Self {
- EditMember(self.0.insert("channel_id", channel_id.into().0))
- }
-}
+ pub fn voice_channel<C: Into<ChannelId>>(mut self, channel_id: C) -> Self {
+ self.0.insert("channel_id".to_owned(), Value::Number(Number::from(channel_id.into().0)));
-impl Default for EditMember {
- fn default() -> EditMember {
- EditMember(ObjectBuilder::new())
+ self
}
}
diff --git a/src/utils/builder/edit_profile.rs b/src/utils/builder/edit_profile.rs
index 83f1da2..680a371 100644
--- a/src/utils/builder/edit_profile.rs
+++ b/src/utils/builder/edit_profile.rs
@@ -1,12 +1,11 @@
-use serde_json::builder::ObjectBuilder;
-use serde_json::Value;
-use std::default::Default;
+use ::internal::prelude::*;
/// A builder to edit the current user's settings, to be used in conjunction
/// with [`Context::edit_profile`].
///
/// [`Context::edit_profile`]: ../../client/struct.Context.html#method.edit_profile
-pub struct EditProfile(pub ObjectBuilder);
+#[derive(Default)]
+pub struct EditProfile(pub JsonMap);
impl EditProfile {
/// Sets the avatar of the current user. `None` can be passed to remove an
@@ -33,11 +32,12 @@ impl EditProfile {
/// ```
///
/// [`utils::read_image`]: ../fn.read_image.html
- pub fn avatar(self, icon: Option<&str>) -> Self {
- EditProfile(self.0
- .insert("avatar",
- icon.map_or_else(|| Value::Null,
- |x| Value::String(x.to_owned()))))
+ pub fn avatar(mut self, avatar: Option<&str>) -> Self {
+ let avatar = avatar.map_or(Value::Null, |x| Value::String(x.to_owned()));
+
+ self.0.insert("avatar".to_owned(), avatar);
+
+ self
}
/// Modifies the current user's email address.
@@ -50,8 +50,10 @@ impl EditProfile {
/// **Note**: This can only be used by user accounts.
///
/// [provided]: #method.password
- pub fn email(self, email: &str) -> Self {
- EditProfile(self.0.insert("email", email))
+ pub fn email(mut self, email: &str) -> Self {
+ self.0.insert("email".to_owned(), Value::String(email.to_owned()));
+
+ self
}
/// Modifies the current user's password.
@@ -60,8 +62,10 @@ impl EditProfile {
/// [provided].
///
/// [provided]: #method.password
- pub fn new_password(self, new_password: &str) -> Self {
- EditProfile(self.0.insert("new_password", new_password))
+ pub fn new_password(mut self, new_password: &str) -> Self {
+ self.0.insert("new_password".to_owned(), Value::String(new_password.to_owned()));
+
+ self
}
/// Used for providing the current password as verification when
@@ -69,8 +73,10 @@ impl EditProfile {
///
/// [modifying the password]: #method.new_password
/// [modifying the associated email address]: #method.email
- pub fn password(self, password: &str) -> Self {
- EditProfile(self.0.insert("password", password))
+ pub fn password(mut self, password: &str) -> Self {
+ self.0.insert("password".to_owned(), Value::String(password.to_owned()));
+
+ self
}
/// Modifies the current user's username.
@@ -79,13 +85,9 @@ impl EditProfile {
/// and current discriminator, a new unique discriminator will be assigned.
/// If there are no available discriminators with the requested username,
/// an error will occur.
- pub fn username(self, username: &str) -> Self {
- EditProfile(self.0.insert("username", username))
- }
-}
+ pub fn username(mut self, username: &str) -> Self {
+ self.0.insert("username".to_owned(), Value::String(username.to_owned()));
-impl Default for EditProfile {
- fn default() -> EditProfile {
- EditProfile(ObjectBuilder::new())
+ self
}
}
diff --git a/src/utils/builder/edit_role.rs b/src/utils/builder/edit_role.rs
index e9b86e9..de8efc7 100644
--- a/src/utils/builder/edit_role.rs
+++ b/src/utils/builder/edit_role.rs
@@ -1,5 +1,5 @@
-use serde_json::builder::ObjectBuilder;
use std::default::Default;
+use ::internal::prelude::*;
use ::model::{Permissions, Role, permissions};
/// A builer to create or edit a [`Role`] for use via a number of model and
@@ -31,53 +31,67 @@ use ::model::{Permissions, Role, permissions};
/// [`Guild::create_role`]: ../../model/struct.Guild.html#method.create_role
/// [`Role`]: ../../model/struct.Role.html
/// [`Role::edit`]: ../../model/struct.Role.html#method.edit
-pub struct EditRole(pub ObjectBuilder);
+pub struct EditRole(pub JsonMap);
impl EditRole {
/// Creates a new builder with the values of the given [`Role`].
///
/// [`Role`]: ../../model/struct.Role.html
pub fn new(role: &Role) -> Self {
- EditRole(ObjectBuilder::new()
- .insert("color", role.colour.0)
- .insert("hoist", role.hoist)
- .insert("managed", role.managed)
- .insert("mentionable", role.mentionable)
- .insert("name", &role.name)
- .insert("permissions", role.permissions.bits())
- .insert("position", role.position))
+ let mut map = Map::new();
+ map.insert("color".to_owned(), Value::Number(Number::from(role.colour.0)));
+ map.insert("hoist".to_owned(), Value::Bool(role.hoist));
+ map.insert("managed".to_owned(), Value::Bool(role.managed));
+ map.insert("mentionable".to_owned(), Value::Bool(role.mentionable));
+ map.insert("name".to_owned(), Value::String(role.name.clone()));
+ map.insert("permissions".to_owned(), Value::Number(Number::from(role.permissions.bits())));
+ map.insert("position".to_owned(), Value::Number(Number::from(role.position)));
+
+ EditRole(map)
}
/// Sets the colour of the role.
- pub fn colour(self, colour: u64) -> Self {
- EditRole(self.0.insert("color", colour))
+ pub fn colour(mut self, colour: u64) -> Self {
+ self.0.insert("color".to_owned(), Value::Number(Number::from(colour)));
+
+ self
}
/// Whether or not to hoist the role above lower-positioned role in the user
/// list.
- pub fn hoist(self, hoist: bool) -> Self {
- EditRole(self.0.insert("hoist", hoist))
+ pub fn hoist(mut self, hoist: bool) -> Self {
+ self.0.insert("hoist".to_owned(), Value::Bool(hoist));
+
+ self
}
/// Whether or not to make the role mentionable, notifying its users.
- pub fn mentionable(self, mentionable: bool) -> Self {
- EditRole(self.0.insert("mentionable", mentionable))
+ pub fn mentionable(mut self, mentionable: bool) -> Self {
+ self.0.insert("mentionable".to_owned(), Value::Bool(mentionable));
+
+ self
}
/// The name of the role to set.
- pub fn name(self, name: &str) -> Self {
- EditRole(self.0.insert("name", name))
+ pub fn name(mut self, name: &str) -> Self {
+ self.0.insert("name".to_owned(), Value::String(name.to_owned()));
+
+ self
}
/// The set of permissions to assign the role.
- pub fn permissions(self, permissions: Permissions) -> Self {
- EditRole(self.0.insert("permissions", permissions.bits()))
+ pub fn permissions(mut self, permissions: Permissions) -> Self {
+ self.0.insert("permissions".to_owned(), Value::Number(Number::from(permissions.bits())));
+
+ self
}
/// The position to assign the role in the role list. This correlates to the
/// role's position in the user list.
- pub fn position(self, position: u8) -> Self {
- EditRole(self.0.insert("position", position))
+ pub fn position(mut self, position: u8) -> Self {
+ self.0.insert("position".to_owned(), Value::Number(Number::from(position)));
+
+ self
}
}
@@ -95,12 +109,16 @@ impl Default for EditRole {
///
/// [general permissions set]: ../../model/permissions/fn.general.html
fn default() -> EditRole {
- EditRole(ObjectBuilder::new()
- .insert("color", 10070709)
- .insert("hoist", false)
- .insert("mentionable", false)
- .insert("name", "new role".to_owned())
- .insert("permissions", permissions::general().bits())
- .insert("position", 1))
+ let mut map = Map::new();
+ let permissions = Number::from(permissions::general().bits());
+
+ map.insert("color".to_owned(), Value::Number(Number::from(10070709)));
+ map.insert("hoist".to_owned(), Value::Bool(false));
+ map.insert("mentionable".to_owned(), Value::Bool(false));
+ map.insert("name".to_owned(), Value::String("new role".to_owned()));
+ map.insert("permissions".to_owned(), Value::Number(permissions));
+ map.insert("position".to_owned(), Value::Number(Number::from(1)));
+
+ EditRole(map)
}
}
diff --git a/src/utils/builder/execute_webhook.rs b/src/utils/builder/execute_webhook.rs
index 073dcb3..5e79f31 100644
--- a/src/utils/builder/execute_webhook.rs
+++ b/src/utils/builder/execute_webhook.rs
@@ -1,6 +1,6 @@
-use serde_json::builder::ObjectBuilder;
use serde_json::Value;
use std::default::Default;
+use ::internal::prelude::*;
/// A builder to create the inner content of a [`Webhook`]'s execution.
///
@@ -52,12 +52,14 @@ use std::default::Default;
/// [`Webhook`]: ../../model/struct.Webhook.html
/// [`Webhook::execute`]: ../../model/struct.Webhook.html#method.execute
/// [`execute_webhook`]: ../../client/rest/fn.execute_webhook.html
-pub struct ExecuteWebhook(pub ObjectBuilder);
+pub struct ExecuteWebhook(pub JsonMap);
impl ExecuteWebhook {
/// Override the default avatar of the webhook with an image URL.
- pub fn avatar_url(self, avatar_url: &str) -> Self {
- ExecuteWebhook(self.0.insert("avatar_url", avatar_url))
+ pub fn avatar_url(mut self, avatar_url: &str) -> Self {
+ self.0.insert("avatar_url".to_owned(), Value::String(avatar_url.to_owned()));
+
+ self
}
/// Set the content of the message.
@@ -66,8 +68,10 @@ impl ExecuteWebhook {
/// omitted.
///
/// [`embeds`]: #method.embeds
- pub fn content(self, content: &str) -> Self {
- ExecuteWebhook(self.0.insert("content", content))
+ pub fn content(mut self, content: &str) -> Self {
+ self.0.insert("content".to_owned(), Value::String(content.to_owned()));
+
+ self
}
/// Set the embeds associated with the message.
@@ -83,20 +87,26 @@ impl ExecuteWebhook {
/// [`Embed::fake`]: ../../model/struct.Embed.html#method.fake
/// [`Webhook::execute`]: ../../model/struct.Webhook.html#method.execute
/// [struct-level documentation]: #examples
- pub fn embeds(self, embeds: Vec<Value>) -> Self {
- ExecuteWebhook(self.0.insert("embeds", embeds))
+ pub fn embeds(mut self, embeds: Vec<Value>) -> Self {
+ self.0.insert("embeds".to_owned(), Value::Array(embeds));
+
+ self
}
/// Whether the message is a text-to-speech message.
///
/// Think carefully before setting this to `true`.
- pub fn tts(self, tts: bool) -> Self {
- ExecuteWebhook(self.0.insert("tts", tts))
+ pub fn tts(mut self, tts: bool) -> Self {
+ self.0.insert("tts".to_owned(), Value::Bool(tts));
+
+ self
}
/// Override the default username of the webhook.
- pub fn username(self, username: &str) -> Self {
- ExecuteWebhook(self.0.insert("username", username))
+ pub fn username(mut self, username: &str) -> Self {
+ self.0.insert("username".to_owned(), Value::String(username.to_owned()));
+
+ self
}
}
@@ -110,6 +120,9 @@ impl Default for ExecuteWebhook {
/// [`Webhook`]: ../../model/struct.Webhook.html
/// [`tts`]: #method.tts
fn default() -> ExecuteWebhook {
- ExecuteWebhook(ObjectBuilder::new().insert("tts", false))
+ let mut map = Map::new();
+ map.insert("tts".to_owned(), Value::Bool(false));
+
+ ExecuteWebhook(map)
}
}
diff --git a/src/utils/colour.rs b/src/utils/colour.rs
index 69f549d..8687db0 100644
--- a/src/utils/colour.rs
+++ b/src/utils/colour.rs
@@ -1,6 +1,3 @@
-use std::default::Default;
-use ::internal::prelude::*;
-
macro_rules! colour {
($(#[$attr:meta] $name:ident, $val:expr;)*) => {
impl Colour {
@@ -64,7 +61,7 @@ macro_rules! colour {
/// [`Role`]: ../model/struct.Role.html
/// [`dark_teal`]: #method.dark_teal
/// [`get_g`]: #method.get_g
-#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Colour(pub u32);
impl Colour {
@@ -123,15 +120,6 @@ impl Colour {
Colour(uint)
}
- #[doc(hidden)]
- pub fn decode(value: Value) -> Result<Colour> {
- match value {
- Value::U64(v) => Ok(Colour(v as u32)),
- Value::I64(v) => Ok(Colour(v as u32)),
- other => Err(Error::Decode("Expected valid colour", other)),
- }
- }
-
/// Returns the red RGB component of this Colour.
///
/// # Examples
diff --git a/src/utils/macros.rs b/src/utils/macros.rs
index 16382b1..be94046 100644
--- a/src/utils/macros.rs
+++ b/src/utils/macros.rs
@@ -114,3 +114,58 @@ macro_rules! feature_voice {
}
}
}
+
+#[macro_export]
+macro_rules! enum_number {
+ (#[$attr_:meta] $name:ident { $(#[$attr:meta] $variant:ident = $value:expr, )* }) => {
+ #[$attr_]
+ #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
+ pub enum $name {
+ $(
+ #[$attr]
+ $variant = $value,
+ )*
+ }
+
+ impl ::serde::Serialize for $name {
+ fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
+ where S: ::serde::Serializer
+ {
+ // Serialize the enum as a u64.
+ serializer.serialize_u64(*self as u64)
+ }
+ }
+
+ impl ::serde::Deserialize for $name {
+ fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
+ where D: ::serde::Deserializer
+ {
+ struct Visitor;
+
+ impl ::serde::de::Visitor for Visitor {
+ type Value = $name;
+
+ fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+ formatter.write_str("positive integer")
+ }
+
+ fn visit_u64<E>(self, value: u64) -> StdResult<$name, E>
+ where E: ::serde::de::Error
+ {
+ // Rust does not come with a simple way of converting a
+ // number to an enum, so use a big `match`.
+ match value {
+ $( $value => Ok($name::$variant), )*
+ _ => Err(E::custom(
+ format!("unknown {} value: {}",
+ stringify!($name), value))),
+ }
+ }
+ }
+
+ // Deserialize the enum from a u64.
+ deserializer.deserialize_u64(Visitor)
+ }
+ }
+ }
+}
diff --git a/src/utils/mod.rs b/src/utils/mod.rs
index ca20b57..235709e 100644
--- a/src/utils/mod.rs
+++ b/src/utils/mod.rs
@@ -22,19 +22,6 @@ use ::model::{EmojiIdentifier, EmojiId};
pub use self::message_builder::MessageBuilder;
-#[doc(hidden)]
-pub fn decode_array<T, F: Fn(Value) -> Result<T>>(value: Value, f: F) -> Result<Vec<T>> {
- into_array(value).and_then(|x| x.into_iter().map(f).collect())
-}
-
-#[doc(hidden)]
-pub fn into_array(value: Value) -> Result<Vec<Value>> {
- match value {
- Value::Array(v) => Ok(v),
- value => Err(Error::Decode("Expected array", value)),
- }
-}
-
/// Retrieves the "code" part of an [invite][`RichInvite`] out of a URL.
///
/// # Examples