Skip to content

Commit

Permalink
Remove explicit reference to serde_json elsewhere in serenity
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrasnitski committed Oct 13, 2023
1 parent 2c0b5a1 commit 5e06f7b
Show file tree
Hide file tree
Showing 14 changed files with 67 additions and 77 deletions.
10 changes: 5 additions & 5 deletions src/builder/create_components.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::Serialize;

use crate::json::json;
use crate::json::{self, json};
use crate::model::prelude::*;

/// A builder for creating a components action row in a message.
Expand All @@ -19,12 +19,12 @@ impl serde::Serialize for CreateActionRow {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::Error as _;

serde_json::json!({
json!({
"type": 1,
"components": match self {
Self::Buttons(x) => serde_json::to_value(x).map_err(S::Error::custom)?,
Self::SelectMenu(x) => serde_json::to_value(vec![x]).map_err(S::Error::custom)?,
Self::InputText(x) => serde_json::to_value(vec![x]).map_err(S::Error::custom)?,
Self::Buttons(x) => json::to_value(x).map_err(S::Error::custom)?,
Self::SelectMenu(x) => json::to_value(vec![x]).map_err(S::Error::custom)?,
Self::InputText(x) => json::to_value(vec![x]).map_err(S::Error::custom)?,
}
})
.serialize(serializer)
Expand Down
17 changes: 9 additions & 8 deletions src/builder/create_interaction_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::constants;
#[cfg(feature = "http")]
use crate::http::CacheHttp;
use crate::internal::prelude::*;
use crate::json::{self, json};
use crate::model::prelude::*;

/// [Discord docs](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object).
Expand Down Expand Up @@ -57,7 +58,7 @@ impl serde::Serialize for CreateInteractionResponse {
use serde::ser::Error as _;

#[allow(clippy::match_same_arms)] // hurts readability
serde_json::json!({
json!({
"type": match self {
Self::Pong { .. } => 1,
Self::Message { .. } => 4,
Expand All @@ -68,13 +69,13 @@ impl serde::Serialize for CreateInteractionResponse {
Self::Modal { .. } => 9,
},
"data": match self {
Self::Pong => serde_json::Value::Null,
Self::Message(x) => serde_json::to_value(x).map_err(S::Error::custom)?,
Self::Defer(x) => serde_json::to_value(x).map_err(S::Error::custom)?,
Self::Acknowledge => serde_json::Value::Null,
Self::UpdateMessage(x) => serde_json::to_value(x).map_err(S::Error::custom)?,
Self::Autocomplete(x) => serde_json::to_value(x).map_err(S::Error::custom)?,
Self::Modal(x) => serde_json::to_value(x).map_err(S::Error::custom)?,
Self::Pong => json::NULL,
Self::Message(x) => json::to_value(x).map_err(S::Error::custom)?,
Self::Defer(x) => json::to_value(x).map_err(S::Error::custom)?,
Self::Acknowledge => json::NULL,
Self::UpdateMessage(x) => json::to_value(x).map_err(S::Error::custom)?,
Self::Autocomplete(x) => json::to_value(x).map_err(S::Error::custom)?,
Self::Modal(x) => json::to_value(x).map_err(S::Error::custom)?,
}
})
.serialize(serializer)
Expand Down
2 changes: 1 addition & 1 deletion src/cache/cache_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use super::Cache;
/// Some(old_user)
/// },
/// Entry::Vacant(entry) => {
/// // We can convert a [`serde_json::Value`] to a User for test
/// // We can convert a [`json::Value`] to a User for test
/// // purposes.
/// let user = from_value::<User>(json!({
/// "id": self.user_id,
Expand Down
17 changes: 3 additions & 14 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use std::io::Error as IoError;

#[cfg(feature = "http")]
use reqwest::{header::InvalidHeaderValue, Error as ReqwestError};
use serde_json::Error as JsonError;
#[cfg(feature = "gateway")]
use tokio_tungstenite::tungstenite::error::Error as TungsteniteError;
use tracing::instrument;
Expand All @@ -16,6 +15,7 @@ use crate::gateway::GatewayError;
#[cfg(feature = "http")]
use crate::http::HttpError;
use crate::internal::prelude::*;
use crate::json::JsonError;
use crate::model::ModelError;

/// The common result type between most library functions.
Expand All @@ -38,11 +38,9 @@ pub enum Error {
Format(FormatError),
/// An [`std::io`] error.
Io(IoError),
/// An error from the [`serde_json`] crate.
#[cfg_attr(not(feature = "simd_json"), doc = "An error from the [`serde_json`] crate.")]
#[cfg_attr(feature = "simd_json", doc = "An error from the [`simd_json`] crate.")]
Json(JsonError),
#[cfg(feature = "simd-json")]
/// An error from the `simd_json` crate.
SimdJson(simd_json::Error),
/// An error from the [`model`] module.
///
/// [`model`]: crate::model
Expand Down Expand Up @@ -90,13 +88,6 @@ pub enum Error {
Tungstenite(TungsteniteError),
}

#[cfg(feature = "simd-json")]
impl From<simd_json::Error> for Error {
fn from(e: simd_json::Error) -> Self {
Error::SimdJson(e)
}
}

impl From<FormatError> for Error {
fn from(e: FormatError) -> Error {
Error::Format(e)
Expand Down Expand Up @@ -167,8 +158,6 @@ impl fmt::Display for Error {
Self::Json(inner) => fmt::Display::fmt(&inner, f),
Self::Model(inner) => fmt::Display::fmt(&inner, f),
Self::Url(msg) => f.write_str(msg),
#[cfg(feature = "simd-json")]
Error::SimdJson(inner) => fmt::Display::fmt(&inner, f),
#[cfg(feature = "client")]
Self::Client(inner) => fmt::Display::fmt(&inner, f),
#[cfg(feature = "gateway")]
Expand Down
2 changes: 1 addition & 1 deletion src/http/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use serde::de::{Deserialize, Deserializer, Error as _};
use url::ParseError as UrlError;

use crate::internal::prelude::*;
use crate::json::decode_resp;
use crate::json::*;

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[non_exhaustive]
Expand Down
3 changes: 0 additions & 3 deletions src/internal/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
pub use std::result::Result as StdResult;

#[cfg(feature = "simd-json")]
pub use simd_json::{Mutable, Value as ValueTrait, ValueAccess};

#[cfg(feature = "client")]
pub use crate::client::ClientError;
pub use crate::error::{Error, Result};
Expand Down
51 changes: 27 additions & 24 deletions src/model/application/command_interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::client::Context;
#[cfg(feature = "model")]
use crate::http::{CacheHttp, Http};
use crate::internal::prelude::*;
use crate::json::{self, JsonError};
use crate::model::application::{CommandOptionType, CommandType};
use crate::model::channel::{Attachment, Message, PartialChannel};
use crate::model::guild::{Member, PartialMember, Role};
Expand Down Expand Up @@ -529,19 +530,20 @@ struct RawCommandDataOption {
#[serde(rename = "type")]
kind: CommandOptionType,
#[serde(skip_serializing_if = "Option::is_none")]
value: Option<serde_json::Value>,
value: Option<json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
options: Option<Vec<RawCommandDataOption>>,
#[serde(skip_serializing_if = "Option::is_none")]
focused: Option<bool>,
}

fn option_from_raw<E: DeError>(raw: RawCommandDataOption) -> StdResult<CommandDataOption, E> {
fn option_from_raw(raw: RawCommandDataOption) -> Result<CommandDataOption> {
macro_rules! value {
() => {
serde_json::from_value(raw.value.ok_or_else(|| DeError::missing_field("value"))?)
.map_err(DeError::custom)?
};
() => {{
json::from_value(
raw.value.ok_or_else::<JsonError, _>(|| DeError::missing_field("value"))?,
)?
}};
}

let value = match raw.kind {
Expand All @@ -554,13 +556,15 @@ fn option_from_raw<E: DeError>(raw: RawCommandDataOption) -> StdResult<CommandDa
CommandOptionType::Number => CommandDataOptionValue::Number(value!()),
CommandOptionType::String => CommandDataOptionValue::String(value!()),
CommandOptionType::SubCommand => {
let options = raw.options.ok_or_else(|| DeError::missing_field("options"))?;
let options = options.into_iter().map(option_from_raw).collect::<StdResult<_, E>>()?;
let options =
raw.options.ok_or_else::<JsonError, _>(|| DeError::missing_field("options"))?;
let options = options.into_iter().map(option_from_raw).collect::<Result<_>>()?;
CommandDataOptionValue::SubCommand(options)
},
CommandOptionType::SubCommandGroup => {
let options = raw.options.ok_or_else(|| DeError::missing_field("options"))?;
let options = options.into_iter().map(option_from_raw).collect::<StdResult<_, E>>()?;
let options =
raw.options.ok_or_else::<JsonError, _>(|| DeError::missing_field("options"))?;
let options = options.into_iter().map(option_from_raw).collect::<Result<_>>()?;
CommandDataOptionValue::SubCommandGroup(options)
},
CommandOptionType::Attachment => CommandDataOptionValue::Attachment(value!()),
Expand All @@ -577,7 +581,7 @@ fn option_from_raw<E: DeError>(raw: RawCommandDataOption) -> StdResult<CommandDa
})
}

fn option_to_raw(option: &CommandDataOption) -> StdResult<RawCommandDataOption, serde_json::Error> {
fn option_to_raw(option: &CommandDataOption) -> Result<RawCommandDataOption> {
let mut raw = RawCommandDataOption {
name: option.name.clone(),
kind: option.kind(),
Expand All @@ -591,22 +595,21 @@ fn option_to_raw(option: &CommandDataOption) -> StdResult<RawCommandDataOption,
kind: _,
value,
} => {
raw.value = Some(serde_json::to_value(value)?);
raw.value = Some(json::to_value(value)?);
raw.focused = Some(true);
},
CommandDataOptionValue::Boolean(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::Integer(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::Number(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::String(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::Boolean(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::Integer(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::Number(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::String(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::SubCommand(o) | CommandDataOptionValue::SubCommandGroup(o) => {
raw.options =
Some(o.iter().map(option_to_raw).collect::<StdResult<_, serde_json::Error>>()?);
raw.options = Some(o.iter().map(option_to_raw).collect::<Result<_>>()?);
},
CommandDataOptionValue::Attachment(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::Channel(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::Mentionable(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::Role(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::User(v) => raw.value = Some(serde_json::to_value(v)?),
CommandDataOptionValue::Attachment(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::Channel(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::Mentionable(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::Role(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::User(v) => raw.value = Some(json::to_value(v)?),
CommandDataOptionValue::Unknown(_) => {},
}

Expand All @@ -616,7 +619,7 @@ fn option_to_raw(option: &CommandDataOption) -> StdResult<RawCommandDataOption,
// Manual impl needed to emulate integer enum tags
impl<'de> Deserialize<'de> for CommandDataOption {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
option_from_raw(RawCommandDataOption::deserialize(deserializer)?)
option_from_raw(RawCommandDataOption::deserialize(deserializer)?).map_err(D::Error::custom)
}
}

Expand Down
23 changes: 11 additions & 12 deletions src/model/application/component_interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::client::Context;
#[cfg(feature = "model")]
use crate::http::{CacheHttp, Http};
use crate::internal::prelude::*;
use crate::json::{self, json};
use crate::model::prelude::*;
#[cfg(all(feature = "collector", feature = "utils"))]
use crate::utils::{CreateQuickModal, QuickModalResponse};
Expand Down Expand Up @@ -256,16 +257,14 @@ impl<'de> Deserialize<'de> for ComponentInteractionDataKind {
#[derive(Deserialize)]
struct Json {
component_type: ComponentType,
values: Option<serde_json::Value>,
values: Option<json::Value>,
}
let json = Json::deserialize(deserializer)?;

macro_rules! parse_values {
() => {
serde_json::from_value(
json.values.ok_or_else(|| D::Error::missing_field("values"))?,
)
.map_err(D::Error::custom)?
json::from_value(json.values.ok_or_else(|| D::Error::missing_field("values"))?)
.map_err(D::Error::custom)?
};
}

Expand Down Expand Up @@ -298,7 +297,7 @@ impl<'de> Deserialize<'de> for ComponentInteractionDataKind {

impl Serialize for ComponentInteractionDataKind {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> StdResult<S::Ok, S::Error> {
serde_json::json!({
json!({
"component_type": match self {
Self::Button { .. } => 2,
Self::StringSelect { .. } => 3,
Expand All @@ -309,12 +308,12 @@ impl Serialize for ComponentInteractionDataKind {
Self::Unknown(x) => *x,
},
"values": match self {
Self::StringSelect { values } => serde_json::to_value(values).map_err(S::Error::custom)?,
Self::UserSelect { values } => serde_json::to_value(values).map_err(S::Error::custom)?,
Self::RoleSelect { values } => serde_json::to_value(values).map_err(S::Error::custom)?,
Self::MentionableSelect { values } => serde_json::to_value(values).map_err(S::Error::custom)?,
Self::ChannelSelect { values } => serde_json::to_value(values).map_err(S::Error::custom)?,
Self::Button | Self::Unknown(_) => serde_json::Value::Null,
Self::StringSelect { values } => json::to_value(values).map_err(S::Error::custom)?,
Self::UserSelect { values } => json::to_value(values).map_err(S::Error::custom)?,
Self::RoleSelect { values } => json::to_value(values).map_err(S::Error::custom)?,
Self::MentionableSelect { values } => json::to_value(values).map_err(S::Error::custom)?,
Self::ChannelSelect { values } => json::to_value(values).map_err(S::Error::custom)?,
Self::Button | Self::Unknown(_) => json::NULL,
},
})
.serialize(serializer)
Expand Down
2 changes: 1 addition & 1 deletion src/model/colour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
/// Passing in a role's colour, and then retrieving its green component via [`Self::g`]:
///
/// ```rust
/// # use serde_json::{json, from_value};
/// # use serenity::json::{json, from_value};
/// # use serenity::model::guild::Role;
/// # use serenity::model::id::RoleId;
/// # use serenity::model::id::GuildId;
Expand Down
4 changes: 2 additions & 2 deletions src/model/guild/audit_log/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ mod tests {

#[test]
fn action_serde() {
use serde_json::json;
use crate::json::{self, json};

#[derive(Debug, Deserialize, Serialize)]
struct T {
Expand All @@ -429,7 +429,7 @@ mod tests {
"action": 234,
});

let value = serde_json::from_value::<T>(value).unwrap();
let value = json::from_value::<T>(value).unwrap();
assert_eq!(value.action.num(), 234);

assert!(matches!(value.action, Action::Unknown(234)));
Expand Down
2 changes: 1 addition & 1 deletion src/model/guild/emoji.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl Emoji {
/// Delete a given emoji:
///
/// ```rust,no_run
/// # use serde_json::{json, from_value};
/// # use serenity::json::{json, from_value};
/// # use serenity::framework::standard::{CommandResult, macros::command};
/// # use serenity::client::Context;
/// # use serenity::model::prelude::{EmojiId, Emoji};
Expand Down
5 changes: 3 additions & 2 deletions src/model/guild/guild_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1205,9 +1205,10 @@ impl GuildId {
"position": pos,
})
})
.collect::<Vec<_>>();
.collect::<Vec<_>>()
.into();

http.as_ref().edit_guild_channel_positions(self, &Value::from(items)).await
http.as_ref().edit_guild_channel_positions(self, &items).await
}

/// Returns a list of [`Member`]s in a [`Guild`] whose username or nickname starts with a
Expand Down
4 changes: 2 additions & 2 deletions src/model/invite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ impl Invite {
/// Retrieve the URL for an invite with the code `WxZumR`:
///
/// ```rust
/// # use serde_json::{json, from_value};
/// # use serenity::json::{json, from_value};
/// # use serenity::model::prelude::*;
/// #
/// # fn main() {
Expand Down Expand Up @@ -345,7 +345,7 @@ impl RichInvite {
/// Retrieve the URL for an invite with the code `WxZumR`:
///
/// ```rust
/// # use serde_json::{json, from_value};
/// # use serenity::json::{json, from_value};
/// # use serenity::model::prelude::*;
/// #
/// # fn main() {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/message_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl MessageBuilder {
/// Mention an emoji in a message's content:
///
/// ```rust
/// # use serde_json::{json, from_value};
/// # use serenity::json::{json, from_value};
/// # use serenity::model::guild::Emoji;
/// # use serenity::model::id::EmojiId;
/// # use serenity::utils::MessageBuilder;
Expand Down

0 comments on commit 5e06f7b

Please sign in to comment.