Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prepare core for no_std support #90

Merged
merged 7 commits into from
Feb 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async-std = "1.2.0"
futures = "0.3.1"
log = "0.4"
parking_lot = "0.10"
jsonrpsee-core = { path = "core" }
jsonrpsee-core = { path = "core", default-features = false, features = ["std"] }
jsonrpsee-http = { path = "http", optional = true }
jsonrpsee-proc-macros = { path = "proc-macros" }
jsonrpsee-ws = { path = "ws", optional = true }
Expand Down
14 changes: 9 additions & 5 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@ authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>"]
license = "MIT"
edition = "2018"

[features]
default = ["std"]
std = ["futures/std"]

[dependencies]
bs58 = "0.3.0"
fnv = "1.0"
futures = "0.3.1"
futures = { version = "0.3.4", default-features = false, features = ["async-await"] }
hashbrown = "0.7.0"
log = "0.4"
rand = "0.7"
serde = { version = "1.0.40", features = ["derive"] }
serde_json = "1.0.40"
smallvec = "1.2.0"
thiserror = "1.0"
serde = { version = "1.0.101", default-features = false, features = ["derive"] }
serde_json = { version = "1.0.48", default-features = false, features = ["alloc"] }
smallvec = { version = "1.2.0", default-features = false }

[dev-dependencies]
async-std = "1.2.0"
30 changes: 16 additions & 14 deletions core/src/client/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,10 @@
// DEALINGS IN THE SOFTWARE.

use crate::{client::raw::TransportClient, common};
use fnv::FnvHashMap;
use std::{
collections::{hash_map::Entry, HashMap, VecDeque},
error, fmt,
future::Future,
};

use alloc::{collections::VecDeque, string::String, vec};
use core::{fmt, future::Future};
use hashbrown::{hash_map::Entry, HashMap};

/// Wraps around a [`TransportClient`](crate::TransportClient) and analyzes everything correctly.
///
Expand All @@ -44,7 +42,7 @@ pub struct RawClient<R> {

/// List of requests and subscription requests that have been sent out and that are waiting
/// for a response.
requests: FnvHashMap<RawClientRequestId, Request>,
requests: HashMap<RawClientRequestId, Request, fnv::FnvBuildHasher>,

/// List of active subscriptions by ID (ID is chosen by the server). Note that this doesn't
/// cover subscription requests that have been sent out but not answered yet, as these are in
Expand Down Expand Up @@ -197,7 +195,7 @@ impl<R> RawClient<R> {
RawClient {
inner,
next_request_id: RawClientRequestId(0),
requests: FnvHashMap::default(),
requests: HashMap::default(),
subscriptions: HashMap::default(),
events_queue: VecDeque::with_capacity(16),
events_queue_max_size: 64,
Expand Down Expand Up @@ -700,11 +698,13 @@ where
}
}

impl<E> error::Error for RawClientError<E>
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<E> std::error::Error for RawClientError<E>
where
E: error::Error + 'static,
E: std::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
RawClientError::Inner(ref err) => Some(err),
RawClientError::RequestError(ref err) => Some(err),
Expand Down Expand Up @@ -741,11 +741,13 @@ where
}
}

impl<E> error::Error for CloseError<E>
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<E> std::error::Error for CloseError<E>
where
E: error::Error + 'static,
E: std::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
CloseError::TransportClient(err) => Some(err),
CloseError::AlreadyClosing => None,
Expand Down
6 changes: 4 additions & 2 deletions core/src/client/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@
//! Traits for implementing request-making capabilities.

use crate::common;

use alloc::boxed::Box;
use core::{fmt, pin::Pin};
use futures::prelude::*;
use std::{error, pin::Pin};

/// Objects that can act as clients.
///
Expand All @@ -42,7 +44,7 @@ use std::{error, pin::Pin};
///
pub trait TransportClient {
/// Error that can happen during a request.
type Error: error::Error;
type Error: fmt::Display;

/// Sends out out a request. Returns a `Future` that finishes when the request has been
/// successfully sent.
Expand Down
14 changes: 11 additions & 3 deletions core/src/common/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,16 @@
// DEALINGS IN THE SOFTWARE.

use super::JsonValue;

use alloc::{
borrow::ToOwned as _,
format,
string::{String, ToString as _},
};
use core::fmt;
use serde::de::Deserializer;
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use std::fmt;

/// JSONRPC error code
#[derive(Debug, PartialEq, Clone)]
Expand Down Expand Up @@ -191,10 +197,12 @@ impl From<ErrorCode> for Error {
}
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {}", self.code.description(), self.message)
}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for Error {}
1 change: 1 addition & 0 deletions core/src/common/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use alloc::string::String;
use serde::{Deserialize, Serialize};

/// Request Id
Expand Down
1 change: 1 addition & 0 deletions core/src/common/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use alloc::{format, string::String, vec::Vec};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json;
Expand Down
2 changes: 2 additions & 0 deletions core/src/common/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
// DEALINGS IN THE SOFTWARE.

use super::{Id, Params, Version};

use alloc::{string::String, vec::Vec};
use serde::{Deserialize, Serialize};

/// Represents jsonrpc request which is a method call.
Expand Down
6 changes: 6 additions & 0 deletions core/src/common/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@
// DEALINGS IN THE SOFTWARE.

use super::{Error, Id, JsonValue, Version};

use alloc::{
string::{String, ToString as _},
vec,
vec::Vec,
};
use serde::{Deserialize, Serialize};

/// Synchronous response
Expand Down
2 changes: 1 addition & 1 deletion core/src/common/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use core::fmt;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

/// Protocol version.
#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq)]
Expand Down
5 changes: 5 additions & 0 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,14 @@
#![deny(unsafe_code)]
#![deny(intra_doc_link_resolution_failure)]
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

pub use crate::client::raw::TransportClient;
pub use crate::client::{RawClient, RawClientError, RawClientEvent, RawClientRequestId};
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub use crate::local::local_transport;
pub use crate::server::raw::{TransportServer, TransportServerEvent};
pub use crate::server::{RawServer, RawServerEvent, RawServerRequestId, RawServerSubscriptionId};
Expand Down
21 changes: 17 additions & 4 deletions core/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,15 @@
//! ```
//!

#![cfg(feature = "std")]
#![cfg_attr(docsrs, doc(cfg(feature = "std")))]

use crate::{common, TransportClient, TransportServer, TransportServerEvent};

use core::{fmt, pin::Pin};
use fnv::FnvHashSet;
use futures::{channel::mpsc, prelude::*};
use std::{fmt, pin::Pin};
use thiserror::Error;
use std::error;

/// Builds a new client and a new server that are connected to each other.
pub fn local_transport() -> (LocalTransportClient, LocalTransportServer) {
Expand Down Expand Up @@ -107,10 +111,9 @@ pub struct LocalTransportServer {
}

/// Error that can happen on the client side.
#[derive(Debug, Error)]
#[derive(Debug)]
pub enum LocalTransportClientErr {
/// The [`LocalTransportServer`] no longer exists.
#[error("Server has been closed")]
ServerClosed,
}

Expand Down Expand Up @@ -226,3 +229,13 @@ impl fmt::Debug for LocalTransportServer {
f.debug_struct("LocalTransportServer").finish()
}
}

impl error::Error for LocalTransportClientErr {}

impl fmt::Display for LocalTransportClientErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
LocalTransportClientErr::ServerClosed => write!(f, "Server has been closed"),
}
}
}
4 changes: 3 additions & 1 deletion core/src/server/batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@
// DEALINGS IN THE SOFTWARE.

use crate::{common, server::Notification, server::Params};

use alloc::vec::Vec;
use core::{fmt, iter};
use smallvec::SmallVec;
use std::{fmt, iter};

/// Batch corresponding to a request from a [`TransportServer`](crate::TransportServer).
///
Expand Down
10 changes: 6 additions & 4 deletions core/src/server/batches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@
// DEALINGS IN THE SOFTWARE.

use crate::{common, server::batch, server::params::Params, server::Notification};
use fnv::FnvHashMap;
use std::{collections::hash_map::Entry, fmt};

use alloc::vec::Vec;
use core::fmt;
use hashbrown::{hash_map::Entry, HashMap};

/// Collection of multiple batches.
///
Expand All @@ -52,7 +54,7 @@ pub struct BatchesState<T> {
///
/// The identifier is lineraly increasing and is never leaked on the wire or outside of this
/// module. Therefore there is no risk of hash collision.
batches: FnvHashMap<u64, (batch::BatchState, T)>,
batches: HashMap<u64, (batch::BatchState, T), fnv::FnvBuildHasher>,
}

/// Event generated by [`next_event`](BatchesState::next_event).
Expand Down Expand Up @@ -105,7 +107,7 @@ impl<T> BatchesState<T> {
pub fn new() -> BatchesState<T> {
BatchesState {
next_batch_id: 0,
batches: FnvHashMap::with_capacity_and_hasher(BATCHES_MIN_CAPACITY, Default::default()),
batches: HashMap::with_capacity_and_hasher(BATCHES_MIN_CAPACITY, Default::default()),
}
}

Expand Down
32 changes: 22 additions & 10 deletions core/src/server/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,10 @@ use crate::common::{self, JsonValue};
use crate::server::{
batches, raw::TransportServer, raw::TransportServerEvent, Notification, Params,
};
use fnv::FnvHashMap;
use std::{
collections::hash_map::Entry, collections::HashMap, fmt, hash::Hash, num::NonZeroUsize, vec,
};
use thiserror::Error;

use alloc::{borrow::ToOwned as _, string::String, vec, vec::Vec};
use core::{fmt, hash::Hash, num::NonZeroUsize};
use hashbrown::{hash_map::Entry, HashMap};

/// Wraps around a "raw server" and adds capabilities.
///
Expand All @@ -50,7 +49,7 @@ pub struct RawServer<R, I> {
/// List of active subscriptions.
/// The identifier is chosen randomly and uniformy distributed. It is never decided by the
/// client. There is therefore no risk of hash collision attack.
subscriptions: FnvHashMap<[u8; 32], SubscriptionState<I>>,
subscriptions: HashMap<[u8; 32], SubscriptionState<I>, fnv::FnvBuildHasher>,

/// For each raw request ID (i.e. client connection), the number of active subscriptions
/// that are using it.
Expand Down Expand Up @@ -101,7 +100,7 @@ pub struct RawServerRequest<'a, R, I> {
raw: &'a mut R,

/// Reference to the corresponding field in `RawServer`.
subscriptions: &'a mut FnvHashMap<[u8; 32], SubscriptionState<I>>,
subscriptions: &'a mut HashMap<[u8; 32], SubscriptionState<I>, fnv::FnvBuildHasher>,

/// Reference to the corresponding field in `RawServer`.
num_subscriptions: &'a mut HashMap<I, NonZeroUsize>,
Expand All @@ -117,13 +116,11 @@ pub struct ServerSubscription<'a, R, I> {
}

/// Error that can happen when calling `into_subscription`.
#[derive(Debug, Error)]
#[derive(Debug)]
pub enum IntoSubscriptionErr {
/// Underlying server doesn't support subscriptions.
#[error("Underlying server doesn't support subscriptions")]
NotSupported,
/// Request has already been closed by the client.
#[error("Request is already closed")]
Closed,
}

Expand Down Expand Up @@ -523,6 +520,21 @@ where
}
}

impl fmt::Display for IntoSubscriptionErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
IntoSubscriptionErr::NotSupported => {
write!(f, "Underlying server doesn't support subscriptions")
}
IntoSubscriptionErr::Closed => write!(f, "Request is already closed"),
}
}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for IntoSubscriptionErr {}

impl Iterator for SubscriptionsReadyIter {
type Item = RawServerSubscriptionId;

Expand Down
2 changes: 1 addition & 1 deletion core/src/server/notification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

use crate::common;
use crate::server::Params;
use std::fmt;
use core::fmt;

/// Notification received on a server.
///
Expand Down
4 changes: 3 additions & 1 deletion core/src/server/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
// DEALINGS IN THE SOFTWARE.

use crate::common;
use std::fmt;

use alloc::string::String;
use core::fmt;

/// Access to the parameters of a request.
#[derive(Copy, Clone)]
Expand Down
Loading