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

Add clippy to CI and fix several clippy warnings #625

Merged
merged 7 commits into from
Jul 8, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ checkstyle-linux-stable:
<<: *only
<<: *docker-env
script:
- rustup component add rustfmt
- rustup component add rustfmt clippy
- cargo fmt --all -- --check
- cargo clippy
allow_failure: true

# test rust stable
Expand Down
2 changes: 1 addition & 1 deletion core-client/transports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ impl<T: DeserializeOwned + Unpin + 'static> Stream for TypedSubscriptionStream<T
.map_err(|error| RpcError::ParseError(self.returns.into(), Box::new(error))),
),
None => None,
Some(Err(err)) => Some(Err(err.into())),
Some(Err(err)) => Some(Err(err)),
}
.into()
}
Expand Down
2 changes: 1 addition & 1 deletion core-client/transports/src/transports/duplex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ where
}
match self.outgoing.pop_front() {
Some(request) => {
if let Err(_) = self.sink.as_mut().start_send(request) {
if self.sink.as_mut().start_send(request).is_err() {
// the channel is disconnected.
return err().into();
}
Expand Down
2 changes: 1 addition & 1 deletion core-client/transports/src/transports/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl From<ClientResponse> for Result<Value, Error> {
(Some(_), _, Some(error)) => {
let error = serde_json::from_value::<Error>(error.to_owned())
.ok()
.unwrap_or_else(|| Error::parse_error());
.unwrap_or_else(Error::parse_error);
Err(error)
}
_ => Ok(n.params.into()),
Expand Down
8 changes: 2 additions & 6 deletions core/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use std::pin::Pin;
use std::sync::Arc;

use futures_util::{self, future, FutureExt};
use serde_json;

use crate::calls::{
Metadata, RemoteProcedure, RpcMethod, RpcMethodSimple, RpcMethodSync, RpcNotification, RpcNotificationSimple,
Expand Down Expand Up @@ -208,10 +207,7 @@ impl<T: Metadata, S: Middleware<T>> MetaIoHandler<T, S> {
use self::future::Either::{Left, Right};
fn as_string(response: Option<Response>) -> Option<String> {
let res = response.map(write_response);
debug!(target: "rpc", "Response: {}.", match res {
Some(ref res) => res,
None => "None",
});
debug!(target: "rpc", "Response: {}.", res.as_ref().unwrap_or(&"None".to_string()));
res
}

Expand All @@ -237,7 +233,7 @@ impl<T: Metadata, S: Middleware<T>> MetaIoHandler<T, S> {
}

fn outputs_as_batch(outs: Vec<Option<Output>>) -> Option<Response> {
let outs: Vec<_> = outs.into_iter().filter_map(|v| v).collect();
let outs: Vec<_> = outs.into_iter().flatten().collect();
if outs.is_empty() {
None
} else {
Expand Down
20 changes: 9 additions & 11 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,17 @@
//! Right now it supports only server side handling requests.
//!
//! ```rust
//! use jsonrpc_core::*;
//! use jsonrpc_core::IoHandler;
//! use jsonrpc_core::Value;
//! let mut io = IoHandler::new();
//! io.add_sync_method("say_hello", |_| {
//! Ok(Value::String("Hello World!".into()))
//! });
//!
//! fn main() {
//! let mut io = IoHandler::new();
//! io.add_sync_method("say_hello", |_| {
//! Ok(Value::String("Hello World!".into()))
//! });
//! let request = r#"{"jsonrpc": "2.0", "method": "say_hello", "params": [42, 23], "id": 1}"#;
//! let response = r#"{"jsonrpc":"2.0","result":"Hello World!","id":1}"#;
//!
//! let request = r#"{"jsonrpc": "2.0", "method": "say_hello", "params": [42, 23], "id": 1}"#;
//! let response = r#"{"jsonrpc":"2.0","result":"Hello World!","id":1}"#;
//!
//! assert_eq!(io.handle_request_sync(request), Some(response.to_string()));
//! }
//! assert_eq!(io.handle_request_sync(request), Some(response.to_string()));
//! ```

#![deny(missing_docs)]
Expand Down
1 change: 0 additions & 1 deletion core/src/types/params.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! jsonrpc params field

use serde::de::DeserializeOwned;
use serde_json;
use serde_json::value::from_value;

use super::{Error, Value};
Expand Down
4 changes: 2 additions & 2 deletions core/src/types/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ impl Output {
/// Creates new output given `Result`, `Id` and `Version`.
pub fn from(result: CoreResult<Value>, id: Id, jsonrpc: Option<Version>) -> Self {
match result {
Ok(result) => Output::Success(Success { id, jsonrpc, result }),
Err(error) => Output::Failure(Failure { id, jsonrpc, error }),
Ok(result) => Output::Success(Success { jsonrpc, result, id }),
Err(error) => Output::Failure(Failure { jsonrpc, error, id }),
}
}

Expand Down
211 changes: 105 additions & 106 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,42 @@
//! Example
//!
//! ```
//! use jsonrpc_derive::rpc;
//! use jsonrpc_core::{IoHandler, Result, BoxFuture};
//! use jsonrpc_core::futures::future;
//! use jsonrpc_derive::rpc;
//!
//! #[rpc(server)]
//! pub trait Rpc {
//! #[rpc(name = "protocolVersion")]
//! fn protocol_version(&self) -> Result<String>;
//! #[rpc(name = "protocolVersion")]
//! fn protocol_version(&self) -> Result<String>;
//!
//! #[rpc(name = "add")]
//! fn add(&self, a: u64, b: u64) -> Result<u64>;
//! #[rpc(name = "add")]
//! fn add(&self, a: u64, b: u64) -> Result<u64>;
//!
//! #[rpc(name = "callAsync")]
//! fn call(&self, a: u64) -> BoxFuture<Result<String>>;
//! #[rpc(name = "callAsync")]
//! fn call(&self, a: u64) -> BoxFuture<Result<String>>;
//! }
//!
//! struct RpcImpl;
//! impl Rpc for RpcImpl {
//! fn protocol_version(&self) -> Result<String> {
//! Ok("version1".into())
//! }
//! fn protocol_version(&self) -> Result<String> {
//! Ok("version1".into())
//! }
//!
//! fn add(&self, a: u64, b: u64) -> Result<u64> {
//! Ok(a + b)
//! }
//! fn add(&self, a: u64, b: u64) -> Result<u64> {
//! Ok(a + b)
//! }
//!
//! fn call(&self, _: u64) -> BoxFuture<Result<String>> {
//! Box::pin(future::ready(Ok("OK".to_owned()).into()))
//! }
//! fn call(&self, _: u64) -> BoxFuture<Result<String>> {
//! Box::pin(future::ready(Ok("OK".to_owned()).into()))
//! }
//! }
//!
//! fn main() {
//! let mut io = IoHandler::new();
//! let rpc = RpcImpl;
//! let mut io = IoHandler::new();
//! let rpc = RpcImpl;
//!
//! io.extend_with(rpc.to_delegate());
//! io.extend_with(rpc.to_delegate());
//! }
//! ```
//!
Expand All @@ -51,7 +51,6 @@
//! have a matching unique subscription name.
//!
//! ```
//! use std::thread;
//! use std::sync::{atomic, Arc, RwLock};
//! use std::collections::HashMap;
//!
Expand All @@ -61,80 +60,80 @@
//!
//! #[rpc]
//! pub trait Rpc {
//! type Metadata;
//!
//! /// Hello subscription
//! #[pubsub(
//! subscription = "hello",
//! subscribe,
//! name = "hello_subscribe",
//! alias("hello_sub")
//! )]
//! fn subscribe(&self, _: Self::Metadata, _: Subscriber<String>, param: u64);
//!
//! /// Unsubscribe from hello subscription.
//! #[pubsub(
//! subscription = "hello",
//! unsubscribe,
//! name = "hello_unsubscribe"
//! )]
//! fn unsubscribe(&self, _: Option<Self::Metadata>, _: SubscriptionId) -> Result<bool>;
//! type Metadata;
//!
//! /// Hello subscription
//! #[pubsub(
//! subscription = "hello",
//! subscribe,
//! name = "hello_subscribe",
//! alias("hello_sub")
//! )]
//! fn subscribe(&self, _: Self::Metadata, _: Subscriber<String>, param: u64);
//!
//! /// Unsubscribe from hello subscription.
//! #[pubsub(
//! subscription = "hello",
//! unsubscribe,
//! name = "hello_unsubscribe"
//! )]
//! fn unsubscribe(&self, _: Option<Self::Metadata>, _: SubscriptionId) -> Result<bool>;
//! }
//!
//!
//! #[derive(Default)]
//! struct RpcImpl {
//! uid: atomic::AtomicUsize,
//! active: Arc<RwLock<HashMap<SubscriptionId, Sink<String>>>>,
//! uid: atomic::AtomicUsize,
//! active: Arc<RwLock<HashMap<SubscriptionId, Sink<String>>>>,
//! }
//! impl Rpc for RpcImpl {
//! type Metadata = Arc<Session>;
//!
//! fn subscribe(&self, _meta: Self::Metadata, subscriber: Subscriber<String>, param: u64) {
//! if param != 10 {
//! subscriber.reject(Error {
//! code: ErrorCode::InvalidParams,
//! message: "Rejecting subscription - invalid parameters provided.".into(),
//! data: None,
//! }).unwrap();
//! return;
//! }
//!
//! let id = self.uid.fetch_add(1, atomic::Ordering::SeqCst);
//! let sub_id = SubscriptionId::Number(id as u64);
//! let sink = subscriber.assign_id(sub_id.clone()).unwrap();
//! self.active.write().unwrap().insert(sub_id, sink);
//! }
//!
//! fn unsubscribe(&self, _meta: Option<Self::Metadata>, id: SubscriptionId) -> Result<bool> {
//! let removed = self.active.write().unwrap().remove(&id);
//! if removed.is_some() {
//! Ok(true)
//! } else {
//! Err(Error {
//! code: ErrorCode::InvalidParams,
//! message: "Invalid subscription.".into(),
//! data: None,
//! })
//! }
//! }
//! type Metadata = Arc<Session>;
//!
//! fn subscribe(&self, _meta: Self::Metadata, subscriber: Subscriber<String>, param: u64) {
//! if param != 10 {
//! subscriber.reject(Error {
//! code: ErrorCode::InvalidParams,
//! message: "Rejecting subscription - invalid parameters provided.".into(),
//! data: None,
//! }).unwrap();
//! return;
//! }
//!
//! let id = self.uid.fetch_add(1, atomic::Ordering::SeqCst);
//! let sub_id = SubscriptionId::Number(id as u64);
//! let sink = subscriber.assign_id(sub_id.clone()).unwrap();
//! self.active.write().unwrap().insert(sub_id, sink);
//! }
//!
//! fn unsubscribe(&self, _meta: Option<Self::Metadata>, id: SubscriptionId) -> Result<bool> {
//! let removed = self.active.write().unwrap().remove(&id);
//! if removed.is_some() {
//! Ok(true)
//! } else {
//! Err(Error {
//! code: ErrorCode::InvalidParams,
//! message: "Invalid subscription.".into(),
//! data: None,
//! })
//! }
//! }
//! }
//!
//! fn main() {
//! let mut io = jsonrpc_core::MetaIoHandler::default();
//! io.extend_with(RpcImpl::default().to_delegate());
//! let mut io = jsonrpc_core::MetaIoHandler::default();
//! io.extend_with(RpcImpl::default().to_delegate());
//!
//! let server_builder = jsonrpc_tcp_server::ServerBuilder::with_meta_extractor(
//! io,
//! |request: &jsonrpc_tcp_server::RequestContext| Arc::new(Session::new(request.sender.clone()))
//! );
//! let server = server_builder
//! .start(&"127.0.0.1:3030".parse().unwrap())
//! .expect("Unable to start TCP server");
//! let server_builder = jsonrpc_tcp_server::ServerBuilder::with_meta_extractor(
//! io,
//! |request: &jsonrpc_tcp_server::RequestContext| Arc::new(Session::new(request.sender.clone()))
//! );
//! let server = server_builder
//! .start(&"127.0.0.1:3030".parse().unwrap())
//! .expect("Unable to start TCP server");
//!
//! // The server spawns a separate thread. Dropping the `server` handle causes it to close.
//! // Uncomment the line below to keep the server running in your example.
//! // server.wait();
//! // server.wait();
//! }
//! ```
//!
Expand All @@ -149,47 +148,47 @@
//! /// Rpc trait
//! #[rpc]
//! pub trait Rpc {
//! /// Returns a protocol version
//! #[rpc(name = "protocolVersion")]
//! fn protocol_version(&self) -> Result<String>;
//! /// Returns a protocol version
//! #[rpc(name = "protocolVersion")]
//! fn protocol_version(&self) -> Result<String>;
//!
//! /// Adds two numbers and returns a result
//! #[rpc(name = "add", alias("callAsyncMetaAlias"))]
//! fn add(&self, a: u64, b: u64) -> Result<u64>;
//! /// Adds two numbers and returns a result
//! #[rpc(name = "add", alias("callAsyncMetaAlias"))]
//! fn add(&self, a: u64, b: u64) -> Result<u64>;
//!
//! /// Performs asynchronous operation
//! #[rpc(name = "callAsync")]
//! fn call(&self, a: u64) -> BoxFuture<Result<String>>;
//! /// Performs asynchronous operation
//! #[rpc(name = "callAsync")]
//! fn call(&self, a: u64) -> BoxFuture<Result<String>>;
//! }
//!
//! struct RpcImpl;
//!
//! impl Rpc for RpcImpl {
//! fn protocol_version(&self) -> Result<String> {
//! Ok("version1".into())
//! }
//! fn protocol_version(&self) -> Result<String> {
//! Ok("version1".into())
//! }
//!
//! fn add(&self, a: u64, b: u64) -> Result<u64> {
//! Ok(a + b)
//! }
//! fn add(&self, a: u64, b: u64) -> Result<u64> {
//! Ok(a + b)
//! }
//!
//! fn call(&self, _: u64) -> BoxFuture<Result<String>> {
//! Box::pin(future::ready(Ok("OK".to_owned())))
//! }
//! fn call(&self, _: u64) -> BoxFuture<Result<String>> {
//! Box::pin(future::ready(Ok("OK".to_owned())))
//! }
//! }
//!
//! fn main() {
//! let exec = futures::executor::ThreadPool::new().unwrap();
//! exec.spawn_ok(run())
//! let exec = futures::executor::ThreadPool::new().unwrap();
//! exec.spawn_ok(run())
//! }
//! async fn run() {
//! let mut io = IoHandler::new();
//! io.extend_with(RpcImpl.to_delegate());
//! let mut io = IoHandler::new();
//! io.extend_with(RpcImpl.to_delegate());
//!
//! let (client, server) = local::connect::<RpcClient, _, _>(io);
//! let res = client.add(5, 6).await.unwrap();
//! println!("5 + 6 = {}", res);
//! server.await.unwrap()
//! let (client, server) = local::connect::<RpcClient, _, _>(io);
//! let res = client.add(5, 6).await.unwrap();
//! println!("5 + 6 = {}", res);
//! server.await.unwrap()
//! }
//!
//! ```
Expand Down