Skip to content

Commit

Permalink
fmt: sync with core (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes authored Nov 13, 2023
1 parent dfc30e3 commit 848f918
Show file tree
Hide file tree
Showing 40 changed files with 241 additions and 604 deletions.
4 changes: 1 addition & 3 deletions crates/json-rpc/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,7 @@ mod test {
fn it_serializes_and_deserializes() {
let cases = [
TestCase { id: Id::Number(1) },
TestCase {
id: Id::String("foo".to_string()),
},
TestCase { id: Id::String("foo".to_string()) },
TestCase { id: Id::None },
];

Expand Down
15 changes: 7 additions & 8 deletions crates/json-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,13 @@
//! actual data being passed to and from the RPC. We can achieve partial
//! (de)serialization by making them generic over a `serde_json::RawValue`.
//!
//! - For [`Request`] - [`PartiallySerializedRequest`] is a
//! `Request<Box<RawValue>`. It represents a `Request` whose parameters have
//! been serialized. [`SerializedRequest`], on the other hand is a request
//! that has been totally serialized. For client-development purposes, its
//! [`Id`] and method have been preserved.
//! - For [`Response`] - [`BorrowedResponse`] is a `Response<&RawValue>`. It
//! represents a Response whose [`Id`] and return status (success or failure)
//! have been deserialized, but whose payload has not.
//! - For [`Request`] - [`PartiallySerializedRequest`] is a `Request<Box<RawValue>`. It represents a
//! `Request` whose parameters have been serialized. [`SerializedRequest`], on the other hand is a
//! request that has been totally serialized. For client-development purposes, its [`Id`] and
//! method have been preserved.
//! - For [`Response`] - [`BorrowedResponse`] is a `Response<&RawValue>`. It represents a Response
//! whose [`Id`] and return status (success or failure) have been deserialized, but whose payload
//! has not.
//!
//! Allowing partial serialization lets us include many unlike [`Request`]
//! objects in collections (e.g. in a batch request). This is useful for
Expand Down
20 changes: 8 additions & 12 deletions crates/json-rpc/src/packet.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use std::collections::HashSet;

use serde::{ser::SerializeSeq, Deserialize, Serialize};
use serde_json::value::RawValue;

use crate::{Id, Response, SerializedRequest};
use serde::{
de::{self, Deserializer, MapAccess, SeqAccess, Visitor},
ser::SerializeSeq,
Deserialize, Serialize,
};
use serde_json::value::RawValue;
use std::{collections::HashSet, fmt, marker::PhantomData};

/// A [`RequestPacket`] is a [`SerializedRequest`] or a batch of serialized
/// request.
Expand Down Expand Up @@ -145,10 +147,6 @@ impl<Payload, ErrData> From<Vec<Response<Payload, ErrData>>> for ResponsePacket<
}
}

use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
use std::fmt;
use std::marker::PhantomData;

impl<'de, Payload, ErrData> Deserialize<'de> for ResponsePacket<Payload, ErrData>
where
Payload: Deserialize<'de>,
Expand Down Expand Up @@ -196,9 +194,7 @@ where
}
}

deserializer.deserialize_any(ResponsePacketVisitor {
marker: PhantomData,
})
deserializer.deserialize_any(ResponsePacketVisitor { marker: PhantomData })
}
}

Expand Down
5 changes: 1 addition & 4 deletions crates/json-rpc/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,7 @@ where
/// Serialize the request, including the request parameters.
pub fn serialize(self) -> serde_json::Result<SerializedRequest> {
let request = serde_json::to_string(&self)?;
Ok(SerializedRequest {
meta: self.meta,
request: RawValue::from_string(request)?,
})
Ok(SerializedRequest { meta: self.meta, request: RawValue::from_string(request)? })
}
}

Expand Down
21 changes: 7 additions & 14 deletions crates/json-rpc/src/response/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,30 +151,23 @@ where
/// # Returns
///
/// - `None` if the error has no `data` field.
/// - `Some(Ok(data))` if the error has a `data` field that can be
/// deserialized.
/// - `Some(Err(err))` if the error has a `data` field that can't be
/// deserialized.
/// - `Some(Ok(data))` if the error has a `data` field that can be deserialized.
/// - `Some(Err(err))` if the error has a `data` field that can't be deserialized.
pub fn try_data_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
self.data
.as_ref()
.map(|data| serde_json::from_str(data.borrow().get()))
self.data.as_ref().map(|data| serde_json::from_str(data.borrow().get()))
}

/// Attempt to deserialize the data field.
///
/// # Returns
///
/// - `Ok(ErrorPayload<T>)` if the data field can be deserialized
/// - `Err(self)` if the data field can't be deserialized, or if there
/// is no data field.
/// - `Err(self)` if the data field can't be deserialized, or if there is no data field.
pub fn deser_data<T: DeserializeOwned>(self) -> Result<ErrorPayload<T>, Self> {
match self.try_data_as::<T>() {
Some(Ok(data)) => Ok(ErrorPayload {
code: self.code,
message: self.message,
data: Some(data),
}),
Some(Ok(data)) => {
Ok(ErrorPayload { code: self.code, message: self.message, data: Some(data) })
}
_ => Err(self),
}
}
Expand Down
68 changes: 21 additions & 47 deletions crates/json-rpc/src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,7 @@ impl BorrowedResponse<'_> {
/// Convert this borrowed response to an owned response by copying the data
/// from the deserializer (if necessary).
pub fn into_owned(self) -> Response {
Response {
id: self.id.clone(),
payload: self.payload.into_owned(),
}
Response { id: self.id.clone(), payload: self.payload.into_owned() }
}
}

Expand Down Expand Up @@ -75,19 +72,13 @@ where
///
/// # Returns
///
/// - `Ok(Response<T, ErrData>)` if the payload is a success and can be
/// deserialized as T, or if the payload is an error.
/// - `Ok(Response<T, ErrData>)` if the payload is a success and can be deserialized as T, or if
/// the payload is an error.
/// - `Err(self)` if the payload is a success and can't be deserialized.
pub fn deser_success<T: DeserializeOwned>(self) -> Result<Response<T, ErrData>, Self> {
match self.payload.deserialize_success() {
Ok(payload) => Ok(Response {
id: self.id,
payload,
}),
Err(payload) => Err(Response {
id: self.id,
payload,
}),
Ok(payload) => Ok(Response { id: self.id, payload }),
Err(payload) => Err(Response { id: self.id, payload }),
}
}
}
Expand All @@ -108,19 +99,13 @@ where
///
/// # Returns
///
/// - `Ok(Response<Payload, T>)` if the payload is an error and can be
/// deserialized as `T`, or if the payload is a success.
/// - `Ok(Response<Payload, T>)` if the payload is an error and can be deserialized as `T`, or
/// if the payload is a success.
/// - `Err(self)` if the payload is an error and can't be deserialized.
pub fn deser_err<T: DeserializeOwned>(self) -> Result<Response<Payload, T>, Self> {
match self.payload.deserialize_error() {
Ok(payload) => Ok(Response {
id: self.id,
payload,
}),
Err(payload) => Err(Response {
id: self.id,
payload,
}),
Ok(payload) => Ok(Response { id: self.id, payload }),
Err(payload) => Err(Response { id: self.id, payload }),
}
}
}
Expand Down Expand Up @@ -222,18 +207,16 @@ where
let id = id.unwrap_or(Id::None);

match (result, error) {
(Some(result), None) => Ok(Response {
id,
payload: ResponsePayload::Success(result),
}),
(None, Some(error)) => Ok(Response {
id,
payload: ResponsePayload::Failure(error),
}),
(Some(result), None) => {
Ok(Response { id, payload: ResponsePayload::Success(result) })
}
(None, Some(error)) => {
Ok(Response { id, payload: ResponsePayload::Failure(error) })
}
(None, None) => Err(serde::de::Error::missing_field("result or error")),
(Some(_), Some(_)) => Err(serde::de::Error::custom(
"result and error are mutually exclusive",
)),
(Some(_), Some(_)) => {
Err(serde::de::Error::custom("result and error are mutually exclusive"))
}
}
}
}
Expand All @@ -253,10 +236,7 @@ mod test {
}"#;
let response: super::Response = serde_json::from_str(response).unwrap();
assert_eq!(response.id, super::Id::Number(1));
assert!(matches!(
response.payload,
super::ResponsePayload::Success(_)
));
assert!(matches!(response.payload, super::ResponsePayload::Success(_)));
}

#[test]
Expand All @@ -271,10 +251,7 @@ mod test {
}"#;
let response: super::Response = serde_json::from_str(response).unwrap();
assert_eq!(response.id, super::Id::None);
assert!(matches!(
response.payload,
super::ResponsePayload::Failure(_)
));
assert!(matches!(response.payload, super::ResponsePayload::Failure(_)));
}

#[test]
Expand All @@ -291,10 +268,7 @@ mod test {
}"#;
let response: super::Response = serde_json::from_str(response).unwrap();
assert_eq!(response.id, super::Id::None);
assert!(matches!(
response.payload,
super::ResponsePayload::Success(_)
));
assert!(matches!(response.payload, super::ResponsePayload::Success(_)));
}
}

Expand Down
18 changes: 8 additions & 10 deletions crates/json-rpc/src/response/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,18 @@ where
/// # Returns
/// - `None` if the payload is an error
/// - `Some(Ok(T))` if the payload is a success and can be deserialized
/// - `Some(Err(serde_json::Error))` if the payload is a success and can't
/// be deserialized as `T`
/// - `Some(Err(serde_json::Error))` if the payload is a success and can't be deserialized as
/// `T`
pub fn try_success_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
self.as_success()
.map(|payload| serde_json::from_str(payload.as_ref().get()))
self.as_success().map(|payload| serde_json::from_str(payload.as_ref().get()))
}

/// Deserialize a Success payload, if possible, transforming this type.
///
/// # Returns
///
/// - `Ok(ResponsePayload<T>)` if the payload is an error, or if the
/// payload is a success and can be deserialized as `T`
/// - `Ok(ResponsePayload<T>)` if the payload is an error, or if the payload is a success and
/// can be deserialized as `T`
/// - `Err(self)` if the payload is a success and can't be deserialized
pub fn deserialize_success<T: DeserializeOwned>(
self,
Expand All @@ -122,8 +121,7 @@ where
/// # Returns
/// - `None` if the payload is a success
/// - `Some(Ok(T))` if the payload is an error and can be deserialized
/// - `Some(Err(serde_json::Error))` if the payload is an error and can't
/// be deserialized as `T`
/// - `Some(Err(serde_json::Error))` if the payload is an error and can't be deserialized as `T`
pub fn try_error_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
self.as_error().and_then(|error| error.try_data_as::<T>())
}
Expand All @@ -132,8 +130,8 @@ where
///
/// # Returns
///
/// - `Ok(ResponsePayload<Payload, T>)` if the payload is an error, or if
/// the payload is an error and can be deserialized as `T`.
/// - `Ok(ResponsePayload<Payload, T>)` if the payload is an error, or if the payload is an
/// error and can be deserialized as `T`.
/// - `Err(self)` if the payload is an error and can't be deserialized.
pub fn deserialize_error<T: DeserializeOwned>(
self,
Expand Down
27 changes: 10 additions & 17 deletions crates/json-rpc/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,9 @@ where
///
/// # Returns
/// - `None` if the response is not `Success`.
/// - `Some(Ok(Resp))` if the response is `Success` and the
/// `result` field can be deserialized.
/// - `Some(Err(err))` if the response is `Success` and the `result` field
/// can't be deserialized.
/// - `Some(Ok(Resp))` if the response is `Success` and the `result` field can be deserialized.
/// - `Some(Err(err))` if the response is `Success` and the `result` field can't be
/// deserialized.
pub fn try_success_as<'a, Resp: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<Resp>> {
match self {
Self::Success(val) => Some(serde_json::from_str(val.borrow().get())),
Expand Down Expand Up @@ -246,10 +245,9 @@ where
///
/// # Returns
/// - `None` if the response is not `Failure`
/// - `Some(Ok(ErrorPayload))` if the response is `Failure` and the
/// `data` field can be deserialized.
/// - `Some(Err(err))` if the response is `Failure` and the `data` field
/// can't be deserialized.
/// - `Some(Ok(ErrorPayload))` if the response is `Failure` and the `data` field can be
/// deserialized.
/// - `Some(Err(err))` if the response is `Failure` and the `data` field can't be deserialized.
pub fn try_failure_as<'a, ErrData: Deserialize<'a>>(
&'a self,
) -> Option<serde_json::Result<ErrData>> {
Expand All @@ -264,10 +262,9 @@ where
pub fn deserialize_failure<ErrData: RpcReturn>(self) -> Result<RpcResult<T, ErrData, E>, Self> {
match self {
RpcResult::Success(ok) => Ok(RpcResult::Success(ok)),
RpcResult::Failure(err_resp) => err_resp
.deser_data::<ErrData>()
.map(RpcResult::Failure)
.map_err(RpcResult::Failure),
RpcResult::Failure(err_resp) => {
err_resp.deser_data::<ErrData>().map(RpcResult::Failure).map_err(RpcResult::Failure)
}
RpcResult::Err(err) => Ok(RpcResult::Err(err)),
}
}
Expand Down Expand Up @@ -297,11 +294,7 @@ where
data: Some(data),
})),
Some(Err(e)) => {
let text = err_resp
.data
.as_ref()
.map(|d| d.borrow().get())
.unwrap_or("");
let text = err_resp.data.as_ref().map(|d| d.borrow().get()).unwrap_or("");
Err(f(e, text))
}
},
Expand Down
12 changes: 2 additions & 10 deletions crates/providers/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ pub struct Stack<T, Inner, Outer> {
impl<T, Inner, Outer> Stack<T, Inner, Outer> {
/// Create a new `Stack`.
pub fn new(inner: Inner, outer: Outer) -> Self {
Stack {
inner,
outer,
_pd: std::marker::PhantomData,
}
Stack { inner, outer, _pd: std::marker::PhantomData }
}
}

Expand Down Expand Up @@ -94,11 +90,7 @@ impl<L, N, T> ProviderBuilder<L, N, T> {
/// builder.network::<Arbitrum>()
/// ```
pub fn network<Net: Network>(self) -> ProviderBuilder<L, Net, T> {
ProviderBuilder {
layer: self.layer,
transport: self.transport,
network: PhantomData,
}
ProviderBuilder { layer: self.layer, transport: self.transport, network: PhantomData }
}

/// Finish the layer stack by providing a root [`RpcClient`], outputting
Expand Down
5 changes: 1 addition & 4 deletions crates/providers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ where
T: Transport,
{
fn from(client: RpcClient<T>) -> Self {
Self {
network: PhantomData,
client,
}
Self { network: PhantomData, client }
}
}

Expand Down
Loading

0 comments on commit 848f918

Please sign in to comment.