From 0a3e9229200ec751b517e5f56899bad0f3cc675e Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 6 May 2024 08:50:25 +1000 Subject: [PATCH] Delete .rustfmt.toml In commit `14429b13` I introduced a new config file for rustfmt but did not delete the hidden `.rustfmt.toml` so the new file had no effect. - Delete the old confid `.rustfmt.toml` - Make `rustfmt.toml` mirror the current one in `rust-bitcoin` with the exception of `edition = 2018` - Run `cargo +nightly fmt` Fix: #116 --- .rustfmt.toml | 1 - fuzz/fuzz_targets/minreq_http.rs | 7 +- fuzz/fuzz_targets/simple_http.rs | 7 +- integration_test/src/main.rs | 1 - rustfmt.toml | 4 +- src/client.rs | 32 +++------ src/error.rs | 54 +++++--------- src/http/minreq_http.rs | 47 ++++--------- src/http/simple_http.rs | 117 ++++++++----------------------- src/lib.rs | 24 ++----- src/simple_tcp.rs | 30 ++------ src/simple_uds.rs | 22 ++---- 12 files changed, 91 insertions(+), 255 deletions(-) delete mode 100644 .rustfmt.toml diff --git a/.rustfmt.toml b/.rustfmt.toml deleted file mode 100644 index da5f6e91..00000000 --- a/.rustfmt.toml +++ /dev/null @@ -1 +0,0 @@ -use_small_heuristics = "Off" diff --git a/fuzz/fuzz_targets/minreq_http.rs b/fuzz/fuzz_targets/minreq_http.rs index 1ee87a96..ea358b30 100644 --- a/fuzz/fuzz_targets/minreq_http.rs +++ b/fuzz/fuzz_targets/minreq_http.rs @@ -8,8 +8,7 @@ fn do_test(data: &[u8]) { { use std::io; - use jsonrpc::minreq_http::MinreqHttpTransport; - use jsonrpc::minreq_http::FUZZ_TCP_SOCK; + use jsonrpc::minreq_http::{MinreqHttpTransport, FUZZ_TCP_SOCK}; use jsonrpc::Client; *FUZZ_TCP_SOCK.lock().unwrap() = Some(io::Cursor::new(data.to_vec())); @@ -56,7 +55,5 @@ mod tests { } #[test] - fn duplicate_crash() { - super::do_test(&extend_vec_from_hex("00")); - } + fn duplicate_crash() { super::do_test(&extend_vec_from_hex("00")); } } diff --git a/fuzz/fuzz_targets/simple_http.rs b/fuzz/fuzz_targets/simple_http.rs index 7294b0f4..4dcfb27c 100644 --- a/fuzz/fuzz_targets/simple_http.rs +++ b/fuzz/fuzz_targets/simple_http.rs @@ -8,8 +8,7 @@ fn do_test(data: &[u8]) { { use std::io; - use jsonrpc::simple_http::SimpleHttpTransport; - use jsonrpc::simple_http::FUZZ_TCP_SOCK; + use jsonrpc::simple_http::{SimpleHttpTransport, FUZZ_TCP_SOCK}; use jsonrpc::Client; *FUZZ_TCP_SOCK.lock().unwrap() = Some(io::Cursor::new(data.to_vec())); @@ -56,7 +55,5 @@ mod tests { } #[test] - fn duplicate_crash() { - super::do_test(&extend_vec_from_hex("00")); - } + fn duplicate_crash() { super::do_test(&extend_vec_from_hex("00")); } } diff --git a/integration_test/src/main.rs b/integration_test/src/main.rs index 500f3a49..9d04b8a2 100644 --- a/integration_test/src/main.rs +++ b/integration_test/src/main.rs @@ -20,7 +20,6 @@ use std::time::Duration; use std::{fs, panic}; use backtrace::Backtrace; - use jsonrpc::http::minreq_http; use jsonrpc::{Client, Request}; use serde_json::json; diff --git a/rustfmt.toml b/rustfmt.toml index 6e22ad21..2c104735 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,5 +1,4 @@ ignore = [] - hard_tabs = false tab_spaces = 4 newline_style = "Auto" @@ -50,7 +49,7 @@ enum_discrim_align_threshold = 0 match_arm_blocks = false # Default true match_arm_leading_pipes = "Never" force_multiline_blocks = false -fn_args_layout = "Tall" +fn_params_layout = "Tall" brace_style = "SameLineWhere" control_brace_style = "AlwaysSameLine" trailing_semicolon = true @@ -68,7 +67,6 @@ use_field_init_shorthand = false force_explicit_abi = true condense_wildcard_suffixes = false color = "Auto" -required_version = "1.5.1" unstable_features = false disable_all_formatting = false skip_children = false diff --git a/src/client.rs b/src/client.rs index 1e90f0d5..21042d5d 100644 --- a/src/client.rs +++ b/src/client.rs @@ -39,10 +39,7 @@ pub struct Client { impl Client { /// Creates a new client with the given transport. pub fn with_transport(transport: T) -> Client { - Client { - transport: Box::new(transport), - nonce: atomic::AtomicUsize::new(1), - } + Client { transport: Box::new(transport), nonce: atomic::AtomicUsize::new(1) } } /// Builds a request. @@ -51,12 +48,7 @@ impl Client { /// [`crate::arg`] or [`crate::try_arg`]. pub fn build_request<'a>(&self, method: &'a str, params: Option<&'a RawValue>) -> Request<'a> { let nonce = self.nonce.fetch_add(1, atomic::Ordering::Relaxed); - Request { - method, - params, - id: serde_json::Value::from(nonce), - jsonrpc: Some("2.0"), - } + Request { method, params, id: serde_json::Value::from(nonce), jsonrpc: Some("2.0") } } /// Sends a request to a client. @@ -141,9 +133,7 @@ impl fmt::Debug for crate::Client { } impl From for Client { - fn from(t: T) -> Client { - Client::with_transport(t) - } + fn from(t: T) -> Client { Client::with_transport(t) } } /// Newtype around `Value` which allows hashing for use as hashmap keys, @@ -200,24 +190,18 @@ impl<'a> Hash for HashableValue<'a> { #[cfg(test)] mod tests { - use super::*; - use std::borrow::Cow; use std::collections::HashSet; use std::str::FromStr; use std::sync; + use super::*; + struct DummyTransport; impl Transport for DummyTransport { - fn send_request(&self, _: Request) -> Result { - Err(Error::NonceMismatch) - } - fn send_batch(&self, _: &[Request]) -> Result, Error> { - Ok(vec![]) - } - fn fmt_target(&self, _: &mut fmt::Formatter) -> fmt::Result { - Ok(()) - } + fn send_request(&self, _: Request) -> Result { Err(Error::NonceMismatch) } + fn send_batch(&self, _: &[Request]) -> Result, Error> { Ok(vec![]) } + fn fmt_target(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } #[test] diff --git a/src/error.rs b/src/error.rs index 6798f1c1..39c520f9 100644 --- a/src/error.rs +++ b/src/error.rs @@ -35,15 +35,11 @@ pub enum Error { } impl From for Error { - fn from(e: serde_json::Error) -> Error { - Error::Json(e) - } + fn from(e: serde_json::Error) -> Error { Error::Json(e) } } impl From for Error { - fn from(e: RpcError) -> Error { - Error::Rpc(e) - } + fn from(e: RpcError) -> Error { Error::Rpc(e) } } impl fmt::Display for Error { @@ -136,31 +132,16 @@ pub fn standard_error( data: Option>, ) -> RpcError { match code { - StandardError::ParseError => RpcError { - code: -32700, - message: "Parse error".to_string(), - data, - }, - StandardError::InvalidRequest => RpcError { - code: -32600, - message: "Invalid Request".to_string(), - data, - }, - StandardError::MethodNotFound => RpcError { - code: -32601, - message: "Method not found".to_string(), - data, - }, - StandardError::InvalidParams => RpcError { - code: -32602, - message: "Invalid params".to_string(), - data, - }, - StandardError::InternalError => RpcError { - code: -32603, - message: "Internal error".to_string(), - data, - }, + StandardError::ParseError => + RpcError { code: -32700, message: "Parse error".to_string(), data }, + StandardError::InvalidRequest => + RpcError { code: -32600, message: "Invalid Request".to_string(), data }, + StandardError::MethodNotFound => + RpcError { code: -32601, message: "Method not found".to_string(), data }, + StandardError::InvalidParams => + RpcError { code: -32602, message: "Invalid params".to_string(), data }, + StandardError::InternalError => + RpcError { code: -32603, message: "Internal error".to_string(), data }, } } @@ -179,22 +160,19 @@ pub fn result_to_response( id, jsonrpc: Some(String::from("2.0")), }, - Err(err) => Response { - result: None, - error: Some(err), - id, - jsonrpc: Some(String::from("2.0")), - }, + Err(err) => + Response { result: None, error: Some(err), id, jsonrpc: Some(String::from("2.0")) }, } } #[cfg(test)] mod tests { + use serde_json; + use super::StandardError::{ InternalError, InvalidParams, InvalidRequest, MethodNotFound, ParseError, }; use super::{result_to_response, standard_error}; - use serde_json; #[test] fn test_parse_error() { diff --git a/src/http/minreq_http.rs b/src/http/minreq_http.rs index 067e4795..4195624d 100644 --- a/src/http/minreq_http.rs +++ b/src/http/minreq_http.rs @@ -43,14 +43,10 @@ impl Default for MinreqHttpTransport { impl MinreqHttpTransport { /// Constructs a new [`MinreqHttpTransport`] with default parameters. - pub fn new() -> Self { - MinreqHttpTransport::default() - } + pub fn new() -> Self { MinreqHttpTransport::default() } /// Returns a builder for [`MinreqHttpTransport`]. - pub fn builder() -> Builder { - Builder::new() - } + pub fn builder() -> Builder { Builder::new() } fn request(&self, req: impl serde::Serialize) -> Result where @@ -72,7 +68,7 @@ impl MinreqHttpTransport { let resp = req.send()?; match resp.json() { Ok(json) => Ok(json), - Err(minreq_err) => { + Err(minreq_err) => if resp.status_code != 200 { Err(Error::Http(HttpError { status_code: resp.status_code, @@ -80,8 +76,7 @@ impl MinreqHttpTransport { })) } else { Err(Error::Minreq(minreq_err)) - } - } + }, } } } @@ -95,9 +90,7 @@ impl Transport for MinreqHttpTransport { Ok(self.request(reqs)?) } - fn fmt_target(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.url) - } + fn fmt_target(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.url) } } /// Builder for simple bitcoind [`MinreqHttpTransport`]. @@ -108,11 +101,7 @@ pub struct Builder { impl Builder { /// Constructs a new [`Builder`] with default configuration and the URL to use. - pub fn new() -> Builder { - Builder { - tp: MinreqHttpTransport::new(), - } - } + pub fn new() -> Builder { Builder { tp: MinreqHttpTransport::new() } } /// Sets the timeout after which requests will abort if they aren't finished. pub fn timeout(mut self, timeout: Duration) -> Self { @@ -160,15 +149,11 @@ impl Builder { } /// Builds the final [`MinreqHttpTransport`]. - pub fn build(self) -> MinreqHttpTransport { - self.tp - } + pub fn build(self) -> MinreqHttpTransport { self.tp } } impl Default for Builder { - fn default() -> Self { - Builder::new() - } + fn default() -> Self { Builder::new() } } /// An HTTP error. @@ -225,15 +210,11 @@ impl error::Error for Error { } impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Json(e) - } + fn from(e: serde_json::Error) -> Self { Error::Json(e) } } impl From for Error { - fn from(e: minreq::Error) -> Self { - Error::Minreq(e) - } + fn from(e: minreq::Error) -> Self { Error::Minreq(e) } } impl From for crate::Error { @@ -266,12 +247,8 @@ mod impls { } } impl Write for TcpStream { - fn write(&mut self, buf: &[u8]) -> io::Result { - io::sink().write(buf) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } + fn write(&mut self, buf: &[u8]) -> io::Result { io::sink().write(buf) } + fn flush(&mut self) -> io::Result<()> { Ok(()) } } } diff --git a/src/http/simple_http.rs b/src/http/simple_http.rs index 3789de5a..de104ffc 100644 --- a/src/http/simple_http.rs +++ b/src/http/simple_http.rs @@ -4,8 +4,6 @@ //! round-tripper that works with the bitcoind RPC server. This can be used //! if minimal dependencies are a goal and synchronous communication is ok. -#[cfg(feature = "proxy")] -use socks::Socks5Stream; use std::io::{BufRead, BufReader, Read, Write}; #[cfg(not(jsonrpc_fuzz))] use std::net::TcpStream; @@ -14,6 +12,9 @@ use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use std::{error, fmt, io, net, num}; +#[cfg(feature = "proxy")] +use socks::Socks5Stream; + use crate::client::Transport; use crate::http::DEFAULT_PORT; #[cfg(feature = "proxy")] @@ -69,14 +70,10 @@ impl Default for SimpleHttpTransport { impl SimpleHttpTransport { /// Constructs a new [`SimpleHttpTransport`] with default parameters. - pub fn new() -> Self { - SimpleHttpTransport::default() - } + pub fn new() -> Self { SimpleHttpTransport::default() } /// Returns a builder for [`SimpleHttpTransport`]. - pub fn builder() -> Builder { - Builder::new() - } + pub fn builder() -> Builder { Builder::new() } /// Replaces the URL of the transport. pub fn set_url(&mut self, url: &str) -> Result<(), Error> { @@ -87,9 +84,7 @@ impl SimpleHttpTransport { } /// Replaces only the path part of the URL. - pub fn set_url_path(&mut self, path: String) { - self.path = path; - } + pub fn set_url_path(&mut self, path: String) { self.path = path; } fn request(&self, req: impl serde::Serialize) -> Result where @@ -192,10 +187,7 @@ impl SimpleHttpTransport { } if header_buf.len() < 12 { - return Err(Error::HttpResponseTooShort { - actual: header_buf.len(), - needed: 12, - }); + return Err(Error::HttpResponseTooShort { actual: header_buf.len(), needed: 12 }); } if !header_buf.as_bytes()[..12].is_ascii() { return Err(Error::HttpResponseNonAsciiHello(header_buf.as_bytes()[..12].to_vec())); @@ -362,11 +354,7 @@ pub struct Builder { impl Builder { /// Constructs a new [`Builder`] with default configuration. - pub fn new() -> Builder { - Builder { - tp: SimpleHttpTransport::new(), - } - } + pub fn new() -> Builder { Builder { tp: SimpleHttpTransport::new() } } /// Sets the timeout after which requests will abort if they aren't finished. pub fn timeout(mut self, timeout: Duration) -> Self { @@ -414,15 +402,11 @@ impl Builder { } /// Builds the final [`SimpleHttpTransport`]. - pub fn build(self) -> SimpleHttpTransport { - self.tp - } + pub fn build(self) -> SimpleHttpTransport { self.tp } } impl Default for Builder { - fn default() -> Self { - Builder::new() - } + fn default() -> Self { Builder::new() } } impl crate::Client { @@ -518,10 +502,7 @@ pub enum Error { impl Error { /// Utility method to create [`Error::InvalidUrl`] variants. fn url>(url: U, reason: &'static str) -> Error { - Error::InvalidUrl { - url: url.into(), - reason, - } + Error::InvalidUrl { url: url.into(), reason } } } @@ -530,24 +511,15 @@ impl fmt::Display for Error { use Error::*; match *self { - InvalidUrl { - ref url, - ref reason, - } => write!(f, "invalid URL '{}': {}", url, reason), + InvalidUrl { ref url, ref reason } => write!(f, "invalid URL '{}': {}", url, reason), SocketError(ref e) => write!(f, "Couldn't connect to host: {}", e), - HttpResponseTooShort { - ref actual, - ref needed, - } => { + HttpResponseTooShort { ref actual, ref needed } => { write!(f, "HTTP response too short: length {}, needed {}.", actual, needed) } HttpResponseNonAsciiHello(ref bytes) => { write!(f, "HTTP response started with non-ASCII {:?}", bytes) } - HttpResponseBadHello { - ref actual, - ref expected, - } => { + HttpResponseBadHello { ref actual, ref expected } => { write!(f, "HTTP response started with `{}`; expected `{}`.", actual, expected) } HttpResponseBadStatus(ref status, ref err) => { @@ -556,17 +528,11 @@ impl fmt::Display for Error { HttpResponseBadContentLength(ref len, ref err) => { write!(f, "HTTP response had bad content length `{}`: {}.", len, err) } - HttpResponseContentLengthTooLarge { - length, - max, - } => { + HttpResponseContentLengthTooLarge { length, max } => { write!(f, "HTTP response content length {} exceeds our max {}.", length, max) } HttpErrorCode(c) => write!(f, "unexpected HTTP code: {}", c), - IncompleteResponse { - content_length, - n_read, - } => { + IncompleteResponse { content_length, n_read } => { write!( f, "read {} bytes but HTTP response content-length header was {}.", @@ -586,25 +552,15 @@ impl error::Error for Error { use self::Error::*; match *self { - InvalidUrl { - .. - } - | HttpResponseTooShort { - .. - } + InvalidUrl { .. } + | HttpResponseTooShort { .. } | HttpResponseNonAsciiHello(..) - | HttpResponseBadHello { - .. - } + | HttpResponseBadHello { .. } | HttpResponseBadStatus(..) | HttpResponseBadContentLength(..) - | HttpResponseContentLengthTooLarge { - .. - } + | HttpResponseContentLengthTooLarge { .. } | HttpErrorCode(_) - | IncompleteResponse { - .. - } + | IncompleteResponse { .. } | HttpResponseChunked => None, SocketError(ref e) => Some(e), Json(ref e) => Some(e), @@ -613,15 +569,11 @@ impl error::Error for Error { } impl From for Error { - fn from(e: io::Error) -> Self { - Error::SocketError(e) - } + fn from(e: io::Error) -> Self { Error::SocketError(e) } } impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Json(e) - } + fn from(e: serde_json::Error) -> Self { Error::Json(e) } } impl From for crate::Error { @@ -653,24 +605,14 @@ mod impls { } } impl Write for TcpStream { - fn write(&mut self, buf: &[u8]) -> io::Result { - io::sink().write(buf) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } + fn write(&mut self, buf: &[u8]) -> io::Result { io::sink().write(buf) } + fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl TcpStream { - pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result { - Ok(TcpStream) - } - pub fn set_read_timeout(&self, _: Option) -> io::Result<()> { - Ok(()) - } - pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { - Ok(()) - } + pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result { Ok(TcpStream) } + pub fn set_read_timeout(&self, _: Option) -> io::Result<()> { Ok(()) } + pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { Ok(()) } } } @@ -785,11 +727,12 @@ mod tests { #[cfg(all(not(feature = "proxy"), not(jsonrpc_fuzz)))] #[test] fn request_to_closed_socket() { - use serde_json::{Number, Value}; use std::net::{Shutdown, TcpListener}; use std::sync::mpsc; use std::thread; + use serde_json::{Number, Value}; + let (tx, rx) = mpsc::sync_channel(1); thread::spawn(move || { diff --git a/src/lib.rs b/src/lib.rs index 4d942adf..f6a3c690 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,11 +25,10 @@ pub mod client; pub mod error; pub mod http; -#[cfg(feature = "simple_http")] -pub use http::simple_http; - #[cfg(feature = "minreq_http")] pub use http::minreq_http; +#[cfg(feature = "simple_http")] +pub use http::simple_http; #[cfg(feature = "simple_tcp")] pub mod simple_tcp; @@ -114,19 +113,15 @@ impl Response { } /// Returns whether or not the `result` field is empty. - pub fn is_none(&self) -> bool { - self.result.is_none() - } + pub fn is_none(&self) -> bool { self.result.is_none() } } #[cfg(test)] mod tests { - use super::*; + use serde_json::json; + use serde_json::value::{to_raw_value, RawValue}; - use serde_json::{ - json, - value::{to_raw_value, RawValue}, - }; + use super::*; #[test] fn response_is_none() { @@ -215,12 +210,7 @@ mod tests { struct Test { v: String, } - test_arg!( - Test { - v: String::from("test"), - }, - Test - ); + test_arg!(Test { v: String::from("test") }, Test); } #[test] diff --git a/src/simple_tcp.rs b/src/simple_tcp.rs index f36600b0..9b1ed24d 100644 --- a/src/simple_tcp.rs +++ b/src/simple_tcp.rs @@ -19,12 +19,7 @@ pub struct TcpTransport { impl TcpTransport { /// Creates a new `TcpTransport` without timeouts. - pub fn new(addr: net::SocketAddr) -> TcpTransport { - TcpTransport { - addr, - timeout: None, - } - } + pub fn new(addr: net::SocketAddr) -> TcpTransport { TcpTransport { addr, timeout: None } } fn request(&self, req: impl serde::Serialize) -> Result where @@ -54,9 +49,7 @@ impl Transport for TcpTransport { Ok(self.request(reqs)?) } - fn fmt_target(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.addr) - } + fn fmt_target(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.addr) } } /// Error that can occur while using the TCP transport. @@ -95,15 +88,11 @@ impl error::Error for Error { } impl From for Error { - fn from(e: io::Error) -> Self { - Error::SocketError(e) - } + fn from(e: io::Error) -> Self { Error::SocketError(e) } } impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Json(e) - } + fn from(e: serde_json::Error) -> Self { Error::Json(e) } } impl From for crate::Error { @@ -117,10 +106,8 @@ impl From for crate::Error { #[cfg(test)] mod tests { - use std::{ - io::{Read, Write}, - thread, - }; + use std::io::{Read, Write}; + use std::thread; use super::*; use crate::Client; @@ -148,10 +135,7 @@ mod tests { let dummy_resp_ser = serde_json::to_vec(&dummy_resp).unwrap(); let client_thread = thread::spawn(move || { - let transport = TcpTransport { - addr, - timeout: Some(time::Duration::from_secs(5)), - }; + let transport = TcpTransport { addr, timeout: Some(time::Duration::from_secs(5)) }; let client = Client::with_transport(transport); client.send_request(dummy_req.clone()).unwrap() diff --git a/src/simple_uds.rs b/src/simple_uds.rs index d05c48fd..1a453725 100644 --- a/src/simple_uds.rs +++ b/src/simple_uds.rs @@ -20,10 +20,7 @@ pub struct UdsTransport { impl UdsTransport { /// Creates a new [`UdsTransport`] without timeouts to use. pub fn new>(sockpath: P) -> UdsTransport { - UdsTransport { - sockpath: sockpath.as_ref().to_path_buf(), - timeout: None, - } + UdsTransport { sockpath: sockpath.as_ref().to_path_buf(), timeout: None } } fn request(&self, req: impl serde::Serialize) -> Result @@ -95,15 +92,11 @@ impl error::Error for Error { } impl From for Error { - fn from(e: io::Error) -> Self { - Error::SocketError(e) - } + fn from(e: io::Error) -> Self { Error::SocketError(e) } } impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Json(e) - } + fn from(e: serde_json::Error) -> Self { Error::Json(e) } } impl From for crate::error::Error { @@ -117,12 +110,9 @@ impl From for crate::error::Error { #[cfg(test)] mod tests { - use std::{ - fs, - io::{Read, Write}, - os::unix::net::UnixListener, - process, thread, - }; + use std::io::{Read, Write}; + use std::os::unix::net::UnixListener; + use std::{fs, process, thread}; use super::*; use crate::Client;