Normalize serde_json imports

This commit is contained in:
Isaiah Inuwa 2020-04-24 06:33:53 -05:00
parent f4b9841590
commit a761d59a4c
20 changed files with 88 additions and 78 deletions

View File

@ -30,6 +30,7 @@ Improvements:
* Add types for User-Interactive Authentication API: `r0::uiaa::{AuthFlow, UiaaInfo, UiaaResponse}` * Add types for User-Interactive Authentication API: `r0::uiaa::{AuthFlow, UiaaInfo, UiaaResponse}`
* Add missing serde attributes to `get_content_thumbnail` query parameters * Add missing serde attributes to `get_content_thumbnail` query parameters
* Add missing `state` response field to `r0::message::get_message_events` * Add missing `state` response field to `r0::message::get_message_events`
* Normalize `serde_json` imports
# 0.7.2 # 0.7.2

View File

@ -99,6 +99,23 @@ use std::convert::TryFrom;
use std::fmt::{Debug, Display, Error as FmtError, Formatter}; use std::fmt::{Debug, Display, Error as FmtError, Formatter};
``` ```
### Serde Imports
When importing methods and types from `serde_json`, methods should be such as
`serde_json::{from,to}_{slice,string,value,vec}` should be imported as
`{from,to}_json_{slice,string,value,vec}`.
For example:
```rust
use serde_json::{
from_value as from_json_value,
to_str as to_json_str,
};
```
Also, `serde_json::Value` should be imported as `JsonValue`.
### Code Formatting and Linting ### Code Formatting and Linting
Use `rustfmt` to format your code and `clippy` to lint your code. Before Use `rustfmt` to format your code and `clippy` to lint your code. Before

View File

@ -4,6 +4,7 @@ use std::fmt::{self, Display, Formatter};
use ruma_api::{error::ResponseDeserializationError, EndpointError}; use ruma_api::{error::ResponseDeserializationError, EndpointError};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::{from_slice as from_json_slice, to_vec as to_json_vec};
use strum::{AsRefStr, Display, EnumString}; use strum::{AsRefStr, Display, EnumString};
/// An enum for the error kind. Items may contain additional information. /// An enum for the error kind. Items may contain additional information.
@ -160,7 +161,7 @@ impl EndpointError for Error {
fn try_from_response( fn try_from_response(
response: http::Response<Vec<u8>>, response: http::Response<Vec<u8>>,
) -> Result<Self, ResponseDeserializationError> { ) -> Result<Self, ResponseDeserializationError> {
match serde_json::from_slice::<ErrorBody>(response.body()) { match from_json_slice::<ErrorBody>(response.body()) {
Ok(error_body) => Ok(error_body.into_error(response.status())), Ok(error_body) => Ok(error_body.into_error(response.status())),
Err(de_error) => Err(ResponseDeserializationError::new(de_error, response)), Err(de_error) => Err(ResponseDeserializationError::new(de_error, response)),
} }
@ -206,7 +207,7 @@ impl From<Error> for http::Response<Vec<u8>> {
http::Response::builder() http::Response::builder()
.header(http::header::CONTENT_TYPE, "application/json") .header(http::header::CONTENT_TYPE, "application/json")
.status(error.status_code) .status(error.status_code)
.body(serde_json::to_vec(&ErrorBody::from(error)).unwrap()) .body(to_json_vec(&ErrorBody::from(error)).unwrap())
.unwrap() .unwrap()
} }
} }

View File

@ -2,7 +2,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value as JsonValue;
use std::collections::BTreeMap; use std::collections::BTreeMap;
ruma_api! { ruma_api! {
@ -39,7 +39,7 @@ pub struct Capabilities {
/// Any other custom capabilities that the server supports outside of the specification, /// Any other custom capabilities that the server supports outside of the specification,
/// labeled using the Java package naming convention and stored as arbitrary JSON values. /// labeled using the Java package naming convention and stored as arbitrary JSON values.
#[serde(flatten)] #[serde(flatten)]
pub custom_capabilities: BTreeMap<String, Value>, pub custom_capabilities: BTreeMap<String, JsonValue>,
} }
/// Information about the m.change_password capability /// Information about the m.change_password capability

View File

@ -2,7 +2,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_identifiers::UserId; use ruma_identifiers::UserId;
use serde_json::Value; use serde_json::Value as JsonValue;
ruma_api! { ruma_api! {
metadata { metadata {
@ -17,7 +17,7 @@ ruma_api! {
request { request {
/// Arbitrary JSON to store as config data. /// Arbitrary JSON to store as config data.
#[ruma_api(body)] #[ruma_api(body)]
pub data: Value, pub data: JsonValue,
/// The event type of the account_data to set. /// The event type of the account_data to set.
/// ///
/// Custom types should be namespaced to avoid clashes. /// Custom types should be namespaced to avoid clashes.

View File

@ -2,7 +2,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_identifiers::{RoomId, UserId}; use ruma_identifiers::{RoomId, UserId};
use serde_json::Value; use serde_json::Value as JsonValue;
ruma_api! { ruma_api! {
metadata { metadata {
@ -17,7 +17,7 @@ ruma_api! {
request { request {
/// Arbitrary JSON to store as config data. /// Arbitrary JSON to store as config data.
#[ruma_api(body)] #[ruma_api(body)]
pub data: Value, pub data: JsonValue,
/// The event type of the account_data to set. /// The event type of the account_data to set.
/// ///
/// Custom types should be namespaced to avoid clashes. /// Custom types should be namespaced to avoid clashes.

View File

@ -9,7 +9,8 @@ use serde::{
ser::SerializeStruct, ser::SerializeStruct,
Deserialize, Deserializer, Serialize, Serializer, Deserialize, Deserializer, Serialize, Serializer,
}; };
use serde_json::Value;
use serde_json::Value as JsonValue;
use super::PublicRoomsChunk; use super::PublicRoomsChunk;
@ -130,7 +131,7 @@ impl<'de> Visitor<'de> for RoomNetworkVisitor {
{ {
let mut include_all_networks = false; let mut include_all_networks = false;
let mut third_party_instance_id = None; let mut third_party_instance_id = None;
while let Some((key, value)) = access.next_entry::<String, Value>()? { while let Some((key, value)) = access.next_entry::<String, JsonValue>()? {
match key.as_str() { match key.as_str() {
"include_all_networks" => { "include_all_networks" => {
include_all_networks = match value.as_bool() { include_all_networks = match value.as_bool() {

View File

@ -305,14 +305,14 @@ impl<'de> Deserialize<'de> for LazyLoadOptions {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use serde_json::json; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::LazyLoadOptions; use super::LazyLoadOptions;
#[test] #[test]
fn test_serializing_disabled_lazy_load() { fn test_serializing_disabled_lazy_load() {
let lazy_load_options = LazyLoadOptions::Disabled; let lazy_load_options = LazyLoadOptions::Disabled;
assert_eq!(serde_json::to_value(lazy_load_options).unwrap(), json!({})); assert_eq!(to_json_value(lazy_load_options).unwrap(), json!({}));
} }
#[test] #[test]
@ -321,7 +321,7 @@ mod tests {
include_redundant_members: false, include_redundant_members: false,
}; };
assert_eq!( assert_eq!(
serde_json::to_value(lazy_load_options).unwrap(), to_json_value(lazy_load_options).unwrap(),
json!({ "lazy_load_members": true }) json!({ "lazy_load_members": true })
); );
} }
@ -332,7 +332,7 @@ mod tests {
include_redundant_members: true, include_redundant_members: true,
}; };
assert_eq!( assert_eq!(
serde_json::to_value(lazy_load_options).unwrap(), to_json_value(lazy_load_options).unwrap(),
json!({ "lazy_load_members": true, "include_redundant_members": true }) json!({ "lazy_load_members": true, "include_redundant_members": true })
); );
} }
@ -341,7 +341,7 @@ mod tests {
fn test_deserializing_no_lazy_load() { fn test_deserializing_no_lazy_load() {
let json = json!({}); let json = json!({});
assert_eq!( assert_eq!(
serde_json::from_value::<LazyLoadOptions>(json).unwrap(), from_json_value::<LazyLoadOptions>(json).unwrap(),
LazyLoadOptions::Disabled, LazyLoadOptions::Disabled,
); );
} }
@ -350,7 +350,7 @@ mod tests {
fn test_deserializing_ignore_redundant_members_when_no_lazy_load() { fn test_deserializing_ignore_redundant_members_when_no_lazy_load() {
let json = json!({ "include_redundant_members": true }); let json = json!({ "include_redundant_members": true });
assert_eq!( assert_eq!(
serde_json::from_value::<LazyLoadOptions>(json).unwrap(), from_json_value::<LazyLoadOptions>(json).unwrap(),
LazyLoadOptions::Disabled, LazyLoadOptions::Disabled,
); );
} }

View File

@ -6,7 +6,7 @@ use std::time::Duration;
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_identifiers::{DeviceId, UserId}; use ruma_identifiers::{DeviceId, UserId};
use serde_json::Value; use serde_json::Value as JsonValue;
use super::{AlgorithmAndDeviceId, KeyAlgorithm, OneTimeKey}; use super::{AlgorithmAndDeviceId, KeyAlgorithm, OneTimeKey};
@ -37,7 +37,7 @@ ruma_api! {
response { response {
/// If any remote homeservers could not be reached, they are recorded here. /// If any remote homeservers could not be reached, they are recorded here.
/// The names of the properties are the names of the unreachable servers. /// The names of the properties are the names of the unreachable servers.
pub failures: BTreeMap<String, Value>, pub failures: BTreeMap<String, JsonValue>,
/// One-time keys for the queried devices. /// One-time keys for the queried devices.
pub one_time_keys: BTreeMap<UserId, BTreeMap<DeviceId, BTreeMap<AlgorithmAndDeviceId, OneTimeKey>>>, pub one_time_keys: BTreeMap<UserId, BTreeMap<DeviceId, BTreeMap<AlgorithmAndDeviceId, OneTimeKey>>>,

View File

@ -4,7 +4,7 @@ use std::{collections::BTreeMap, time::Duration};
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_identifiers::{DeviceId, UserId}; use ruma_identifiers::{DeviceId, UserId};
use serde_json::Value; use serde_json::Value as JsonValue;
use super::DeviceKeys; use super::DeviceKeys;
@ -41,7 +41,7 @@ ruma_api! {
response { response {
/// If any remote homeservers could not be reached, they are recorded here. /// If any remote homeservers could not be reached, they are recorded here.
/// The names of the properties are the names of the unreachable servers. /// The names of the properties are the names of the unreachable servers.
pub failures: BTreeMap<String, Value>, pub failures: BTreeMap<String, JsonValue>,
/// Information on the queried devices. /// Information on the queried devices.
pub device_keys: BTreeMap<UserId, BTreeMap<DeviceId, DeviceKeys>>, pub device_keys: BTreeMap<UserId, BTreeMap<DeviceId, DeviceKeys>>,

View File

@ -3,7 +3,7 @@
use std::time::SystemTime; use std::time::SystemTime;
use ruma_api::ruma_api; use ruma_api::ruma_api;
use serde_json::Value; use serde_json::Value as JsonValue;
ruma_api! { ruma_api! {
metadata { metadata {
@ -31,7 +31,7 @@ ruma_api! {
/// Differences from OpenGraph: the image size in bytes is added to the `matrix:image:size` /// Differences from OpenGraph: the image size in bytes is added to the `matrix:image:size`
/// field, and `og:image` returns the MXC URI to the image, if any. /// field, and `og:image` returns the MXC URI to the image, if any.
#[ruma_api(body)] #[ruma_api(body)]
pub data: Option<Value>, pub data: Option<JsonValue>,
} }
error: crate::Error error: crate::Error

View File

@ -51,14 +51,17 @@ pub enum InvitationRecipient {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::convert::TryFrom;
use ruma_identifiers::UserId;
use serde_json::{from_value as from_json_value, json};
use super::InvitationRecipient; use super::InvitationRecipient;
use crate::r0::{membership::Invite3pid, thirdparty::Medium}; use crate::r0::{membership::Invite3pid, thirdparty::Medium};
use ruma_identifiers::UserId;
use std::convert::TryFrom;
#[test] #[test]
fn deserialize_invite_by_user_id() { fn deserialize_invite_by_user_id() {
let incoming = let incoming =
serde_json::from_str::<InvitationRecipient>(r#" { "user_id": "@carl:example.org" } "#) from_json_value::<InvitationRecipient>(json!({ "user_id": "@carl:example.org" }))
.unwrap(); .unwrap();
let user_id = UserId::try_from("@carl:example.org").unwrap(); let user_id = UserId::try_from("@carl:example.org").unwrap();
let recipient = InvitationRecipient::UserId { user_id }; let recipient = InvitationRecipient::UserId { user_id };
@ -67,16 +70,12 @@ mod tests {
#[test] #[test]
fn deserialize_invite_by_3pid() { fn deserialize_invite_by_3pid() {
let incoming = serde_json::from_str::<InvitationRecipient>( let incoming = from_json_value::<InvitationRecipient>(json!({
r#" "id_server": "example.org",
{ "id_access_token": "abcdefghijklmnop",
"id_server": "example.org", "medium": "email",
"id_access_token": "abcdefghijklmnop", "address": "carl@example.org"
"medium": "email", }))
"address": "carl@example.org"
}
"#,
)
.unwrap(); .unwrap();
let recipient = InvitationRecipient::ThirdPartyId(Invite3pid { let recipient = InvitationRecipient::ThirdPartyId(Invite3pid {
id_server: "example.org".to_string(), id_server: "example.org".to_string(),

View File

@ -4,7 +4,7 @@ use ruma_api::ruma_api;
use ruma_events::{room::power_levels::PowerLevelsEventContent, EventJson}; use ruma_events::{room::power_levels::PowerLevelsEventContent, EventJson};
use ruma_identifiers::{RoomId, UserId}; use ruma_identifiers::{RoomId, UserId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value as JsonValue;
use super::Visibility; use super::Visibility;
use crate::r0::membership::Invite3pid; use crate::r0::membership::Invite3pid;
@ -106,5 +106,5 @@ pub struct InitialStateEvent {
/// `state_key` of the event to be sent. /// `state_key` of the event to be sent.
pub state_key: Option<String>, pub state_key: Option<String>,
/// JSON content of the state event. /// JSON content of the state event.
pub content: Value, pub content: JsonValue,
} }

View File

@ -37,12 +37,14 @@ pub enum LoginType {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use serde_json::{from_value as from_json_value, json};
use super::LoginType; use super::LoginType;
#[test] #[test]
fn deserialize_login_type() { fn deserialize_login_type() {
assert_eq!( assert_eq!(
serde_json::from_str::<LoginType>(r#" {"type": "m.login.password"} "#).unwrap(), from_json_value::<LoginType>(json!({ "type": "m.login.password" })).unwrap(),
LoginType::Password, LoginType::Password,
); );
} }

View File

@ -130,21 +130,17 @@ mod user_serde;
mod tests { mod tests {
use std::convert::TryInto; use std::convert::TryInto;
use serde_json::json; use serde_json::{from_value as from_json_value, json, Value as JsonValue};
use super::{LoginInfo, Medium, Request, UserInfo}; use super::{LoginInfo, Medium, Request, UserInfo};
#[test] #[test]
fn deserialize_login_type() { fn deserialize_login_type() {
assert_eq!( assert_eq!(
serde_json::from_str::<LoginInfo>( from_json_value::<LoginInfo>(json!({
r#" "type": "m.login.password",
{ "password": "ilovebananas"
"type": "m.login.password", }),)
"password": "ilovebananas"
}
"#,
)
.unwrap(), .unwrap(),
LoginInfo::Password { LoginInfo::Password {
password: "ilovebananas".into() password: "ilovebananas".into()
@ -152,14 +148,10 @@ mod tests {
); );
assert_eq!( assert_eq!(
serde_json::from_str::<LoginInfo>( from_json_value::<LoginInfo>(json!({
r#" "type": "m.login.token",
{ "token": "1234567890abcdef"
"type": "m.login.token", }),)
"token": "1234567890abcdef"
}
"#,
)
.unwrap(), .unwrap(),
LoginInfo::Token { LoginInfo::Token {
token: "1234567890abcdef".into() token: "1234567890abcdef".into()
@ -170,16 +162,12 @@ mod tests {
#[test] #[test]
fn deserialize_user() { fn deserialize_user() {
assert_eq!( assert_eq!(
serde_json::from_str::<UserInfo>( from_json_value::<UserInfo>(json!({
r#" "identifier": {
{ "type": "m.id.user",
"identifier": { "user": "cheeky_monkey"
"type": "m.id.user",
"user": "cheeky_monkey"
}
} }
"#, }))
)
.unwrap(), .unwrap(),
UserInfo::MatrixId("cheeky_monkey".into()) UserInfo::MatrixId("cheeky_monkey".into())
); );
@ -201,7 +189,7 @@ mod tests {
.try_into() .try_into()
.unwrap(); .unwrap();
let req_body_value: serde_json::Value = serde_json::from_slice(req.body()).unwrap(); let req_body_value: JsonValue = serde_json::from_slice(req.body()).unwrap();
assert_eq!( assert_eq!(
req_body_value, req_body_value,
json!({ json!({

View File

@ -3,7 +3,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_events::EventType; use ruma_events::EventType;
use ruma_identifiers::{EventId, RoomId}; use ruma_identifiers::{EventId, RoomId};
use serde_json::Value; use serde_json::Value as JsonValue;
ruma_api! { ruma_api! {
metadata { metadata {
@ -24,7 +24,7 @@ ruma_api! {
pub event_type: EventType, pub event_type: EventType,
/// The event's content. /// The event's content.
#[ruma_api(body)] #[ruma_api(body)]
pub data: Value, pub data: JsonValue,
} }
response { response {

View File

@ -3,7 +3,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_events::EventType; use ruma_events::EventType;
use ruma_identifiers::{EventId, RoomId}; use ruma_identifiers::{EventId, RoomId};
use serde_json::Value; use serde_json::Value as JsonValue;
ruma_api! { ruma_api! {
metadata { metadata {
@ -27,7 +27,7 @@ ruma_api! {
pub state_key: String, pub state_key: String,
/// The event's content. /// The event's content.
#[ruma_api(body)] #[ruma_api(body)]
pub data: Value, pub data: JsonValue,
} }
response { response {

View File

@ -3,7 +3,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_events::EventType; use ruma_events::EventType;
use ruma_identifiers::RoomId; use ruma_identifiers::RoomId;
use serde_json::Value; use serde_json::Value as JsonValue;
ruma_api! { ruma_api! {
metadata { metadata {
@ -27,7 +27,7 @@ ruma_api! {
response { response {
/// The content of the state event. /// The content of the state event.
#[ruma_api(body)] #[ruma_api(body)]
pub content: Value, pub content: JsonValue,
} }
error: crate::Error error: crate::Error

View File

@ -3,7 +3,7 @@
use ruma_api::ruma_api; use ruma_api::ruma_api;
use ruma_events::EventType; use ruma_events::EventType;
use ruma_identifiers::RoomId; use ruma_identifiers::RoomId;
use serde_json::Value; use serde_json::Value as JsonValue;
ruma_api! { ruma_api! {
metadata { metadata {
@ -30,7 +30,7 @@ ruma_api! {
response { response {
/// The content of the state event. /// The content of the state event.
#[ruma_api(body)] #[ruma_api(body)]
pub content: Value, pub content: JsonValue,
} }
error: crate::Error error: crate::Error

View File

@ -4,7 +4,7 @@ use std::collections::BTreeMap;
use ruma_api::{error::ResponseDeserializationError, EndpointError}; use ruma_api::{error::ResponseDeserializationError, EndpointError};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue; use serde_json::{from_slice as from_json_slice, to_vec as to_json_vec, Value as JsonValue};
use crate::error::{Error as MatrixError, ErrorBody}; use crate::error::{Error as MatrixError, ErrorBody};
@ -85,7 +85,7 @@ impl EndpointError for UiaaResponse {
response: http::Response<Vec<u8>>, response: http::Response<Vec<u8>>,
) -> Result<Self, ResponseDeserializationError> { ) -> Result<Self, ResponseDeserializationError> {
if response.status() == http::StatusCode::UNAUTHORIZED { if response.status() == http::StatusCode::UNAUTHORIZED {
if let Ok(authentication_info) = serde_json::from_slice::<UiaaInfo>(response.body()) { if let Ok(authentication_info) = from_json_slice::<UiaaInfo>(response.body()) {
return Ok(UiaaResponse::AuthResponse(authentication_info)); return Ok(UiaaResponse::AuthResponse(authentication_info));
} }
} }
@ -100,7 +100,7 @@ impl From<UiaaResponse> for http::Response<Vec<u8>> {
UiaaResponse::AuthResponse(authentication_info) => http::Response::builder() UiaaResponse::AuthResponse(authentication_info) => http::Response::builder()
.header(http::header::CONTENT_TYPE, "application/json") .header(http::header::CONTENT_TYPE, "application/json")
.status(&http::StatusCode::UNAUTHORIZED) .status(&http::StatusCode::UNAUTHORIZED)
.body(serde_json::to_vec(&authentication_info).unwrap()) .body(to_json_vec(&authentication_info).unwrap())
.unwrap(), .unwrap(),
UiaaResponse::MatrixError(error) => http::Response::from(error), UiaaResponse::MatrixError(error) => http::Response::from(error),
} }
@ -113,7 +113,8 @@ mod tests {
use ruma_api::EndpointError; use ruma_api::EndpointError;
use serde_json::{ use serde_json::{
from_value as from_json_value, json, to_value as to_json_value, Value as JsonValue, from_slice as from_json_slice, from_value as from_json_value, json,
to_value as to_json_value, Value as JsonValue,
}; };
use super::{AuthData, AuthFlow, UiaaInfo, UiaaResponse}; use super::{AuthData, AuthFlow, UiaaInfo, UiaaResponse};
@ -286,7 +287,7 @@ mod tests {
UiaaResponse::AuthResponse(uiaa_info.clone()).into(); UiaaResponse::AuthResponse(uiaa_info.clone()).into();
assert_eq!( assert_eq!(
serde_json::from_slice::<UiaaInfo>(uiaa_response.body()).unwrap(), from_json_slice::<UiaaInfo>(uiaa_response.body()).unwrap(),
uiaa_info, uiaa_info,
); );
assert_eq!( assert_eq!(