From c5a522e05f1fbf9ac47fe94bab8df82581d89b51 Mon Sep 17 00:00:00 2001 From: ArtemIsmagilov <118372045+ArtemIsmagilov@users.noreply.github.com> Date: Sat, 9 Nov 2024 21:51:32 +0400 Subject: [PATCH] auto formated code, stable cargo 1.82.0 (#76) --- benches/pipeline.rs | 12 ++- examples/actix_crud.rs | 9 +-- examples/actix_long_polling_pubsub.rs | 2 +- examples/simple.rs | 10 ++- src/client/client_state.rs | 4 +- src/client/config.rs | 11 ++- src/client/prepared_command.rs | 8 +- src/client/pub_sub_stream.rs | 29 ++++--- src/commands/bitmap_commands.rs | 21 +++-- src/commands/blocking_commands.rs | 12 ++- src/commands/cluster_commands.rs | 2 +- src/commands/cuckoo_commands.rs | 6 +- src/commands/geo_commands.rs | 10 ++- src/commands/graph_cache.rs | 99 ++++++++++++++--------- src/commands/graph_commands.rs | 32 +++++--- src/commands/graph_value.rs | 19 ++++- src/commands/internal_pub_sub_commands.rs | 6 +- src/commands/mod.rs | 6 +- src/commands/scripting_commands.rs | 7 +- src/commands/search_commands.rs | 4 +- src/commands/string_commands.rs | 6 +- src/commands/t_disgest_commands.rs | 6 +- src/commands/time_series_commands.rs | 38 +++++++-- src/commands/top_k_commands.rs | 12 ++- src/lib.rs | 6 +- src/network/command_info_manager.rs | 18 +++-- src/network/connection.rs | 2 +- src/network/network_handler.rs | 9 ++- src/network/sentinel_connection.rs | 10 ++- src/network/standalone_connection.rs | 2 +- src/network/util.rs | 4 +- src/network/version.rs | 18 ++++- src/resp/buffer_decoder.rs | 6 +- src/resp/bulk_string.rs | 8 +- src/resp/command.rs | 4 +- src/resp/command_encoder.rs | 14 +++- src/resp/resp_batch_deserializer.rs | 4 +- src/resp/resp_serializer.rs | 16 ++-- src/resp/to_args.rs | 4 +- src/resp/util.rs | 4 +- src/resp/value_deserialize.rs | 5 +- src/tests/bitmap_commands.rs | 10 +-- src/tests/bloom_commands.rs | 6 +- src/tests/buffer_decoder.rs | 18 +++-- src/tests/client.rs | 14 +++- src/tests/config.rs | 15 +--- src/tests/connection_commands.rs | 3 +- src/tests/cuckoo_commands.rs | 8 +- src/tests/hash_commands.rs | 20 ++++- src/tests/mod.rs | 2 +- src/tests/pipeline.rs | 5 +- src/tests/resp_deserializer.rs | 13 ++- src/tests/resp_serializer.rs | 10 ++- src/tests/scripting_commands.rs | 22 ++--- src/tests/set_commands.rs | 6 +- src/tests/tls.rs | 2 +- src/tests/transaction.rs | 10 ++- 57 files changed, 422 insertions(+), 247 deletions(-) diff --git a/benches/pipeline.rs b/benches/pipeline.rs index 75ab505..c803ee2 100644 --- a/benches/pipeline.rs +++ b/benches/pipeline.rs @@ -109,7 +109,9 @@ fn bench_redis_async_long_pipeline(b: &mut Bencher) { let client = get_redis_client(); let runtime = current_thread_runtime(); - let mut con = runtime.block_on(client.get_multiplexed_async_connection()).unwrap(); + let mut con = runtime + .block_on(client.get_multiplexed_async_connection()) + .unwrap(); b.iter(|| { runtime @@ -136,7 +138,7 @@ fn bench_redis_multiplexed_async_long_pipeline(b: &mut Bencher) { let mut con = runtime .block_on(client.get_multiplexed_tokio_connection()) .unwrap(); - + b.iter(|| { runtime .block_on(async { @@ -165,7 +167,9 @@ fn bench_fred_long_pipeline(b: &mut Bencher) { .block_on(async { let pipeline = client.pipeline(); for i in 0..PIPELINE_QUERIES { - pipeline.set(format!("foo{}", i), "bar", None, None, false).await?; + pipeline + .set(format!("foo{}", i), "bar", None, None, false) + .await?; } let _result: Vec = pipeline.all().await?; @@ -213,7 +217,7 @@ fn bench_simple(c: &mut Criterion) { .bench_function( "rustis_simple_getsetdel_pipeline", bench_rustis_simple_getsetdel_pipeline, - ); + ); group.finish(); } diff --git a/examples/actix_crud.rs b/examples/actix_crud.rs index fe38d90..af49b57 100644 --- a/examples/actix_crud.rs +++ b/examples/actix_crud.rs @@ -1,4 +1,6 @@ -use actix_web::{delete, get, http::StatusCode, post, web, App, HttpServer, HttpResponse, Responder}; +use actix_web::{ + delete, get, http::StatusCode, post, web, App, HttpResponse, HttpServer, Responder, +}; use rustis::{ client::Client, commands::{GenericCommands, StringCommands}, @@ -28,10 +30,7 @@ async fn main() -> std::io::Result<()> { } #[get("/{key}")] -async fn read( - redis: web::Data, - key: web::Path, -) -> Result { +async fn read(redis: web::Data, key: web::Path) -> Result { let key = key.into_inner(); let value: Option = redis.get(&key).await?; value.ok_or_else(|| { diff --git a/examples/actix_long_polling_pubsub.rs b/examples/actix_long_polling_pubsub.rs index bb87ace..62749aa 100644 --- a/examples/actix_long_polling_pubsub.rs +++ b/examples/actix_long_polling_pubsub.rs @@ -87,7 +87,7 @@ async fn publish( return Err(ServiceError::new( StatusCode::BAD_REQUEST, "Message not provided", - )) + )); }; let channel = channel.into_inner(); diff --git a/examples/simple.rs b/examples/simple.rs index 2af4d0c..18d0307 100644 --- a/examples/simple.rs +++ b/examples/simple.rs @@ -1,4 +1,8 @@ -use rustis::{client::Client, Result, commands::{StringCommands, GenericCommands}}; +use rustis::{ + client::Client, + commands::{GenericCommands, StringCommands}, + Result, +}; #[tokio::main] async fn main() -> Result<()> { @@ -9,7 +13,7 @@ async fn main() -> Result<()> { client.set(key, 42.423456).await?; let _: f64 = client.get(key).await?; client.del(key).await?; - } + } Ok(()) -} \ No newline at end of file +} diff --git a/src/client/client_state.rs b/src/client/client_state.rs index a9dfb9d..0dec523 100644 --- a/src/client/client_state.rs +++ b/src/client/client_state.rs @@ -34,7 +34,9 @@ impl ClientState { match self.cache.get(key) { Some(cache_entry) => match cache_entry.downcast_ref::() { Some(cache_entry) => Ok(Some(cache_entry)), - None => Err(Error::Client(format!("Cannot downcast cache entry '{key}'"))), + None => Err(Error::Client(format!( + "Cannot downcast cache entry '{key}'" + ))), }, None => Ok(None), } diff --git a/src/client/config.rs b/src/client/config.rs index 2a79a85..ef8a4f6 100644 --- a/src/client/config.rs +++ b/src/client/config.rs @@ -1,7 +1,12 @@ use crate::{Error, Result}; #[cfg(feature = "tls")] use native_tls::{Certificate, Identity, Protocol, TlsConnector, TlsConnectorBuilder}; -use std::{collections::HashMap, fmt::{self, Display, Write}, str::FromStr, time::Duration}; +use std::{ + collections::HashMap, + fmt::{self, Display, Write}, + str::FromStr, + time::Duration, +}; use url::Url; const DEFAULT_PORT: u16 = 6379; @@ -600,7 +605,9 @@ impl Display for Config { } else { f.write_char('&')?; } - f.write_fmt(format_args!("wait_between_failures={wait_between_failures}"))?; + f.write_fmt(format_args!( + "wait_between_failures={wait_between_failures}" + ))?; } if let Some(username) = username { if !query_separator { diff --git a/src/client/prepared_command.rs b/src/client/prepared_command.rs index 2511d16..d98eae8 100644 --- a/src/client/prepared_command.rs +++ b/src/client/prepared_command.rs @@ -5,8 +5,7 @@ use crate::{ }; use std::marker::PhantomData; -type CustomConverter<'a, R> = - dyn Fn(RespBuf, Command, &'a Client) -> Future<'a, R> + Send + Sync; +type CustomConverter<'a, R> = dyn Fn(RespBuf, Command, &'a Client) -> Future<'a, R> + Send + Sync; /// Wrapper around a command about to be send with a marker for the response type /// and a few options to decide how the response send back by Redis should be processed. @@ -64,6 +63,9 @@ where } /// Shortcut function to creating a [`PreparedCommand`](PreparedCommand). -pub(crate) fn prepare_command<'a, E, R: Response>(executor: E, command: Command) -> PreparedCommand<'a, E, R> { +pub(crate) fn prepare_command<'a, E, R: Response>( + executor: E, + command: Command, +) -> PreparedCommand<'a, E, R> { PreparedCommand::new(executor, command) } diff --git a/src/client/pub_sub_stream.rs b/src/client/pub_sub_stream.rs index f81078e..30ba58f 100644 --- a/src/client/pub_sub_stream.rs +++ b/src/client/pub_sub_stream.rs @@ -1,5 +1,9 @@ use crate::{ - client::{Client, ClientPreparedCommand}, commands::InternalPubSubCommands, network::PubSubSender, resp::{ByteBufSeed, CommandArgs, SingleArg, SingleArgCollection}, Error, PubSubReceiver, Result + client::{Client, ClientPreparedCommand}, + commands::InternalPubSubCommands, + network::PubSubSender, + resp::{ByteBufSeed, CommandArgs, SingleArg, SingleArgCollection}, + Error, PubSubReceiver, Result, }; use futures_util::{Stream, StreamExt}; use serde::{ @@ -102,7 +106,10 @@ impl PubSubSplitSink { for channel in &channels { if self.channels.iter().any(|c| c == channel) { - return Err(Error::Client(format!("pub sub stream already subscribed to channel `{}`", String::from_utf8_lossy(channel)))); + return Err(Error::Client(format!( + "pub sub stream already subscribed to channel `{}`", + String::from_utf8_lossy(channel) + ))); } } @@ -125,7 +132,10 @@ impl PubSubSplitSink { for pattern in &patterns { if self.patterns.iter().any(|p| p == pattern) { - return Err(Error::Client(format!("pub sub stream already subscribed to pattern `{}`", String::from_utf8_lossy(pattern)))); + return Err(Error::Client(format!( + "pub sub stream already subscribed to pattern `{}`", + String::from_utf8_lossy(pattern) + ))); } } @@ -148,7 +158,10 @@ impl PubSubSplitSink { for shardchannel in &shardchannels { if self.shardchannels.iter().any(|c| c == shardchannel) { - return Err(Error::Client(format!("pub sub stream already subscribed to shard channel `{}`", String::from_utf8_lossy(shardchannel)))); + return Err(Error::Client(format!( + "pub sub stream already subscribed to shard channel `{}`", + String::from_utf8_lossy(shardchannel) + ))); } } @@ -321,11 +334,7 @@ pub struct PubSubStream { } impl PubSubStream { - pub(crate) fn new( - sender: PubSubSender, - receiver: PubSubReceiver, - client: Client, - ) -> Self { + pub(crate) fn new(sender: PubSubSender, receiver: PubSubReceiver, client: Client) -> Self { Self { split_sink: PubSubSplitSink { closed: false, @@ -451,7 +460,7 @@ impl PubSubStream { } /// Splits this object into separate [`Sink`](PubSubSplitSink) and [`Stream`](PubSubSplitStream) objects. - /// This can be useful when you want to split ownership between tasks. + /// This can be useful when you want to split ownership between tasks. pub fn split(self) -> (PubSubSplitSink, PubSubSplitStream) { (self.split_sink, self.split_stream) } diff --git a/src/commands/bitmap_commands.rs b/src/commands/bitmap_commands.rs index f8e9bd2..7a81195 100644 --- a/src/commands/bitmap_commands.rs +++ b/src/commands/bitmap_commands.rs @@ -1,8 +1,6 @@ use crate::{ client::{prepare_command, PreparedCommand}, - resp::{ - cmd, CommandArgs, MultipleArgsCollection, SingleArg, SingleArgCollection, ToArgs, - }, + resp::{cmd, CommandArgs, MultipleArgsCollection, SingleArg, SingleArgCollection, ToArgs}, }; /// A group of Redis commands related to [`Bitmaps`](https://redis.io/docs/data-types/bitmaps/) @@ -244,9 +242,16 @@ where fn write_args(&self, args: &mut CommandArgs) { match self { BitFieldSubCommand::Get(g) => args.arg_ref(g), - BitFieldSubCommand::Set(encoding, offset, value) => - args.arg("SET").arg_ref(encoding).arg_ref(offset).arg(*value), - BitFieldSubCommand::IncrBy(encoding, offset, increment) => args.arg("INCRBY").arg_ref(encoding).arg_ref(offset).arg(*increment), + BitFieldSubCommand::Set(encoding, offset, value) => args + .arg("SET") + .arg_ref(encoding) + .arg_ref(offset) + .arg(*value), + BitFieldSubCommand::IncrBy(encoding, offset, increment) => args + .arg("INCRBY") + .arg_ref(encoding) + .arg_ref(offset) + .arg(*increment), BitFieldSubCommand::Overflow(overflow) => args.arg("OVERFLOW").arg_ref(overflow), }; } @@ -279,7 +284,9 @@ where O: SingleArg, { fn write_args(&self, args: &mut CommandArgs) { - args.arg("GET").arg_ref(&self.encoding).arg_ref(&self.offset); + args.arg("GET") + .arg_ref(&self.encoding) + .arg_ref(&self.offset); } } diff --git a/src/commands/blocking_commands.rs b/src/commands/blocking_commands.rs index 4bc2c62..8a33348 100644 --- a/src/commands/blocking_commands.rs +++ b/src/commands/blocking_commands.rs @@ -150,7 +150,11 @@ pub trait BlockingCommands<'a> { /// # See Also /// [](https://redis.io/commands/blpop/) #[must_use] - fn blpop(self, keys: KK, timeout: f64) -> PreparedCommand<'a, Self, Option<(K1, V)>> + fn blpop( + self, + keys: KK, + timeout: f64, + ) -> PreparedCommand<'a, Self, Option<(K1, V)>> where Self: Sized, K: SingleArg, @@ -177,7 +181,11 @@ pub trait BlockingCommands<'a> { /// # See Also /// [](https://redis.io/commands/brpop/) #[must_use] - fn brpop(self, keys: KK, timeout: f64) -> PreparedCommand<'a, Self, Option<(K1, V)>> + fn brpop( + self, + keys: KK, + timeout: f64, + ) -> PreparedCommand<'a, Self, Option<(K1, V)>> where Self: Sized, K: SingleArg, diff --git a/src/commands/cluster_commands.rs b/src/commands/cluster_commands.rs index ed8b7dd..5e58563 100644 --- a/src/commands/cluster_commands.rs +++ b/src/commands/cluster_commands.rs @@ -886,7 +886,7 @@ impl<'de> Deserialize<'de> for LegacyClusterNodeResult { preferred_endpoint, ip, hostname, - port + port, }) } } diff --git a/src/commands/cuckoo_commands.rs b/src/commands/cuckoo_commands.rs index cb8e228..9ce7605 100644 --- a/src/commands/cuckoo_commands.rs +++ b/src/commands/cuckoo_commands.rs @@ -443,7 +443,11 @@ impl CfReserveOptions { /// The default value is 20. pub fn maxiterations(mut self, maxiterations: usize) -> Self { Self { - command_args: self.command_args.arg("MAXITERATIONS").arg(maxiterations).build(), + command_args: self + .command_args + .arg("MAXITERATIONS") + .arg(maxiterations) + .build(), } } diff --git a/src/commands/geo_commands.rs b/src/commands/geo_commands.rs index 8a30b0c..5e6406a 100644 --- a/src/commands/geo_commands.rs +++ b/src/commands/geo_commands.rs @@ -414,11 +414,17 @@ where E: de::Error, { let Ok(distance) = std::str::from_utf8(v) else { - return Err(de::Error::invalid_value(Unexpected::Bytes(v), &"A valid f64 encoded in an UTF8 string")); + return Err(de::Error::invalid_value( + Unexpected::Bytes(v), + &"A valid f64 encoded in an UTF8 string", + )); }; let Ok(distance) = distance.parse::() else { - return Err(de::Error::invalid_value(Unexpected::Bytes(v), &"A valid f64 encoded in an UTF8 string")); + return Err(de::Error::invalid_value( + Unexpected::Bytes(v), + &"A valid f64 encoded in an UTF8 string", + )); }; Ok(GeoSearchResultField::Distance(distance)) diff --git a/src/commands/graph_cache.rs b/src/commands/graph_cache.rs index ba8f74e..7b1ca62 100644 --- a/src/commands/graph_cache.rs +++ b/src/commands/graph_cache.rs @@ -1,7 +1,7 @@ -use crate::{commands::GraphValueType}; +use crate::commands::GraphValueType; use serde::{ - de::{self, DeserializeSeed, Visitor, IgnoredAny}, - Deserializer, Deserialize + de::{self, DeserializeSeed, IgnoredAny, Visitor}, + Deserialize, Deserializer, }; use std::{fmt, marker::PhantomData}; @@ -49,7 +49,6 @@ impl GraphCache { pub fn check_for_result<'de, D: Deserializer<'de>>(&self, result: D) -> Result { CheckCacheForResultSetSeed::new(self).deserialize(result) } - } macro_rules! impl_deserialize_seq_for_seed { @@ -75,9 +74,7 @@ macro_rules! impl_check_cache_factory { ($struct_name:ident) => { impl<'a> CheckCacheFactory<'a> for $struct_name<'a> { fn new(cache: &'a GraphCache) -> Self { - Self { - cache, - } + Self { cache } } } }; @@ -85,7 +82,7 @@ macro_rules! impl_check_cache_factory { struct CheckCacheIteratorSeed<'a, ItemSeed> { phantom: PhantomData, - cache: &'a GraphCache + cache: &'a GraphCache, } impl<'a, ItemSeed> CheckCacheFactory<'a> for CheckCacheIteratorSeed<'a, ItemSeed> { @@ -136,7 +133,7 @@ where } struct CheckCacheForResultSetSeed<'a> { - cache: &'a GraphCache + cache: &'a GraphCache, } impl_check_cache_factory!(CheckCacheForResultSetSeed); @@ -163,8 +160,10 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForResultSetSeed<'a> { return Err(de::Error::invalid_length(0, &"more elements in sequence")); }; - let Some(check_rows) = - seq.next_element_seed(CheckCacheIteratorSeed::>::new(self.cache))? else { + let Some(check_rows) = seq.next_element_seed(CheckCacheIteratorSeed::< + CheckCacheIteratorSeed, + >::new(self.cache))? + else { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; @@ -190,10 +189,7 @@ impl<'a> CheckCacheFactory<'a> for CheckCacheForValueSeed<'a> { impl<'a> CheckCacheForValueSeed<'a> { #[inline] fn with_value_type(value_type: GraphValueType, cache: &'a GraphCache) -> Self { - Self { - value_type, - cache, - } + Self { value_type, cache } } } @@ -212,7 +208,10 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForValueSeed<'a> { return Err(de::Error::invalid_length(0, &"more elements in sequence")); }; - let Some(check_value) = seq.next_element_seed(CheckCacheForValueSeed::with_value_type(value_type, self.cache))? else { + let Some(check_value) = seq.next_element_seed(CheckCacheForValueSeed::with_value_type( + value_type, self.cache, + ))? + else { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; @@ -228,44 +227,51 @@ impl<'de, 'a> DeserializeSeed<'de> for CheckCacheForValueSeed<'a> { D: Deserializer<'de>, { match self.value_type { - GraphValueType::Unknown => { - deserializer.deserialize_seq(self) - }, + GraphValueType::Unknown => deserializer.deserialize_seq(self), GraphValueType::Null => { <()>::deserialize(deserializer)?; Ok(true) - }, + } GraphValueType::String => { let _string = <&str>::deserialize(deserializer)?; Ok(true) - }, + } GraphValueType::Integer => { let _integer = i64::deserialize(deserializer)?; Ok(true) - }, + } GraphValueType::Boolean => { let _boolean = bool::deserialize(deserializer)?; Ok(true) - }, + } GraphValueType::Double => { let _double = f64::deserialize(deserializer)?; Ok(true) - }, - GraphValueType::Array => CheckCacheIteratorSeed::::new(self.cache).deserialize(deserializer), + } + GraphValueType::Array => { + CheckCacheIteratorSeed::::new(self.cache) + .deserialize(deserializer) + } GraphValueType::Map => CheckCacheForMapSeed::new(self.cache).deserialize(deserializer), - GraphValueType::Edge => CheckCacheForEdgeSeed::new(self.cache).deserialize(deserializer), - GraphValueType::Node => CheckCacheForNodeSeed::new(self.cache).deserialize(deserializer), - GraphValueType::Path => CheckCacheForPathSeed::new(self.cache).deserialize(deserializer), + GraphValueType::Edge => { + CheckCacheForEdgeSeed::new(self.cache).deserialize(deserializer) + } + GraphValueType::Node => { + CheckCacheForNodeSeed::new(self.cache).deserialize(deserializer) + } + GraphValueType::Path => { + CheckCacheForPathSeed::new(self.cache).deserialize(deserializer) + } GraphValueType::Point => { let _point = <(f32, f32)>::deserialize(deserializer)?; Ok(true) - }, + } } } } struct CheckCacheForMapSeed<'a> { - cache: &'a GraphCache + cache: &'a GraphCache, } impl_check_cache_factory!(CheckCacheForMapSeed); @@ -284,7 +290,9 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForMapSeed<'a> { { // ignore key while seq.next_element::()?.is_some() { - let Some(check_value) = seq.next_element_seed(CheckCacheForValueSeed::new(self.cache))? else { + let Some(check_value) = + seq.next_element_seed(CheckCacheForValueSeed::new(self.cache))? + else { return Err(de::Error::custom("Cannot parse GraphValue::Map value")); }; @@ -298,7 +306,7 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForMapSeed<'a> { } struct CheckCacheForNodeSeed<'a> { - cache: &'a GraphCache + cache: &'a GraphCache, } impl_check_cache_factory!(CheckCacheForNodeSeed); @@ -329,7 +337,10 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForNodeSeed<'a> { return Ok(false); } - let Some(check_properties) = seq.next_element_seed(CheckCacheIteratorSeed::::new(self.cache))? else { + let Some(check_properties) = seq.next_element_seed(CheckCacheIteratorSeed::< + CheckCacheForPropertySeed, + >::new(self.cache))? + else { return Err(de::Error::invalid_length(2, &"more elements in sequence")); }; @@ -338,7 +349,7 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForNodeSeed<'a> { } struct CheckCacheForEdgeSeed<'a> { - cache: &'a GraphCache + cache: &'a GraphCache, } impl_check_cache_factory!(CheckCacheForEdgeSeed); @@ -378,7 +389,10 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForEdgeSeed<'a> { return Err(de::Error::invalid_length(3, &"more elements in sequence")); }; - let Some(check_properties) = seq.next_element_seed(CheckCacheIteratorSeed::::new(self.cache))? else { + let Some(check_properties) = seq.next_element_seed(CheckCacheIteratorSeed::< + CheckCacheForPropertySeed, + >::new(self.cache))? + else { return Err(de::Error::invalid_length(4, &"more elements in sequence")); }; @@ -387,7 +401,7 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForEdgeSeed<'a> { } struct CheckCacheForPathSeed<'a> { - cache: &'a GraphCache + cache: &'a GraphCache, } impl_check_cache_factory!(CheckCacheForPathSeed); @@ -404,7 +418,8 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForPathSeed<'a> { where A: serde::de::SeqAccess<'de>, { - let Some(check_nodes) = seq.next_element_seed(CheckCacheForValueSeed::new(self.cache))? else { + let Some(check_nodes) = seq.next_element_seed(CheckCacheForValueSeed::new(self.cache))? + else { return Err(de::Error::invalid_length(0, &"more elements in sequence")); }; @@ -412,7 +427,8 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForPathSeed<'a> { return Ok(false); } - let Some(check_edges) = seq.next_element_seed(CheckCacheForValueSeed::new(self.cache))? else { + let Some(check_edges) = seq.next_element_seed(CheckCacheForValueSeed::new(self.cache))? + else { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; @@ -421,7 +437,7 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForPathSeed<'a> { } struct CheckCacheForPropertySeed<'a> { - cache: &'a GraphCache + cache: &'a GraphCache, } impl_check_cache_factory!(CheckCacheForPropertySeed); @@ -450,7 +466,10 @@ impl<'de, 'a> Visitor<'de> for CheckCacheForPropertySeed<'a> { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; - let Some(check_value) = seq.next_element_seed(CheckCacheForValueSeed::with_value_type(value_type, self.cache))? else { + let Some(check_value) = seq.next_element_seed(CheckCacheForValueSeed::with_value_type( + value_type, self.cache, + ))? + else { return Err(de::Error::invalid_length(2, &"more elements in sequence")); }; diff --git a/src/commands/graph_commands.rs b/src/commands/graph_commands.rs index 0ae68f4..eff1d44 100644 --- a/src/commands/graph_commands.rs +++ b/src/commands/graph_commands.rs @@ -273,11 +273,15 @@ impl GraphResultSet { client: &Client, ) -> Future { let Some(graph_name) = command.args.iter().next() else { - return Box::pin(future::ready(Err(Error::Client("Cannot parse graph command".to_owned())))); + return Box::pin(future::ready(Err(Error::Client( + "Cannot parse graph command".to_owned(), + )))); }; let Ok(graph_name) = std::str::from_utf8(graph_name) else { - return Box::pin(future::ready(Err(Error::Client("Cannot parse graph command".to_owned())))); + return Box::pin(future::ready(Err(Error::Client( + "Cannot parse graph command".to_owned(), + )))); }; let graph_name = graph_name.to_owned(); @@ -373,7 +377,9 @@ impl GraphResultSet { A: de::SeqAccess<'de>, { let Some(size) = seq.size_hint() else { - return Err(de::Error::custom("size hint is mandatory for GraphResultSet")); + return Err(de::Error::custom( + "size hint is mandatory for GraphResultSet", + )); }; if size == 1 { @@ -392,7 +398,8 @@ impl GraphResultSet { }; let client_state = self.client.get_client_state(); - let Ok(Some(cache)) = client_state.get_state::(self.cache_key) else { + let Ok(Some(cache)) = client_state.get_state::(self.cache_key) + else { return Err(de::Error::custom("Cannot find graph cache")); }; @@ -502,7 +509,10 @@ impl<'de> Deserialize<'de> for MappingsResult { A: de::SeqAccess<'de>, { let Some(mapping) = seq.next_element::()? else { - return Err(de::Error::invalid_length(0, &"more elements in sequence")); + return Err(de::Error::invalid_length( + 0, + &"more elements in sequence", + )); }; Ok(mapping) @@ -557,7 +567,7 @@ impl<'de> Deserialize<'de> for MappingsResult { where A: serde::de::SeqAccess<'de>, { - let Some(_header) = seq.next_element::>()? else { + let Some(_header) = seq.next_element::>()? else { return Err(de::Error::invalid_length(0, &"more elements in sequence")); }; @@ -565,7 +575,7 @@ impl<'de> Deserialize<'de> for MappingsResult { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; - let Some(_stats) = seq.next_element::>()? else { + let Some(_stats) = seq.next_element::>()? else { return Err(de::Error::invalid_length(2, &"more elements in sequence")); }; @@ -721,8 +731,10 @@ impl<'de> Deserialize<'de> for GraphQueryStatistics { where A: de::SeqAccess<'de>, { - let Some((value, _milliseconds))= value.split_once(' ') else { - return Err(de::Error::custom("Cannot parse GraphQueryStatistics (query exuction time)")); + let Some((value, _milliseconds)) = value.split_once(' ') else { + return Err(de::Error::custom( + "Cannot parse GraphQueryStatistics (query exuction time)", + )); }; match value.parse::() { @@ -736,7 +748,7 @@ impl<'de> Deserialize<'de> for GraphQueryStatistics { let mut stats = GraphQueryStatistics::default(); while let Some(str) = seq.next_element::<&str>()? { - let Some((name, value))= str.split_once(": ") else { + let Some((name, value)) = str.split_once(": ") else { return Err(de::Error::custom("Cannot parse GraphQueryStatistics")); }; diff --git a/src/commands/graph_value.rs b/src/commands/graph_value.rs index 31e330d..25d9cb5 100644 --- a/src/commands/graph_value.rs +++ b/src/commands/graph_value.rs @@ -196,7 +196,12 @@ where _ => return Err(de::Error::custom("expected GraphValueType::Array (6)")), } - let Some(vec) = seq.next_element_seed(SubVecSeed { phantom: PhantomData, cache: self.cache, value_type: self.value_type })? else { + let Some(vec) = seq.next_element_seed(SubVecSeed { + phantom: PhantomData, + cache: self.cache, + value_type: self.value_type, + })? + else { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; @@ -345,7 +350,9 @@ impl<'de, 'a> DeserializeSeed<'de> for GraphValueSeed<'a> { return Err(de::Error::invalid_length(0, &"more elements in sequence")); }; - let Some(value) = seq.next_element_seed(GraphValueSeed::new(value_type, self.cache))? else { + let Some(value) = + seq.next_element_seed(GraphValueSeed::new(value_type, self.cache))? + else { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; @@ -576,11 +583,15 @@ impl<'de> GraphObjectVisitor<'de> for GraphPath { where A: de::SeqAccess<'de>, { - let Some(nodes) = seq.next_element_seed(GraphNode::into_vec_seed(cache, GraphValueType::Node))? else { + let Some(nodes) = + seq.next_element_seed(GraphNode::into_vec_seed(cache, GraphValueType::Node))? + else { return Err(de::Error::invalid_length(0, &"more elements in sequence")); }; - let Some(edges) = seq.next_element_seed(GraphEdge::into_vec_seed(cache, GraphValueType::Edge))? else { + let Some(edges) = + seq.next_element_seed(GraphEdge::into_vec_seed(cache, GraphValueType::Edge))? + else { return Err(de::Error::invalid_length(1, &"more elements in sequence")); }; diff --git a/src/commands/internal_pub_sub_commands.rs b/src/commands/internal_pub_sub_commands.rs index df1f285..1295a27 100644 --- a/src/commands/internal_pub_sub_commands.rs +++ b/src/commands/internal_pub_sub_commands.rs @@ -11,7 +11,7 @@ pub(crate) trait InternalPubSubCommands<'a> { where Self: Sized, P: SingleArg, - PP: SingleArgCollection

+ PP: SingleArgCollection

, { prepare_command(self, cmd("PSUBSCRIBE").arg(patterns)) } @@ -33,7 +33,7 @@ pub(crate) trait InternalPubSubCommands<'a> { where Self: Sized, C: SingleArg, - CC: SingleArgCollection + CC: SingleArgCollection, { prepare_command(self, cmd("SSUBSCRIBE").arg(shardchannels)) } @@ -42,7 +42,7 @@ pub(crate) trait InternalPubSubCommands<'a> { where Self: Sized, C: SingleArg, - CC: SingleArgCollection + CC: SingleArgCollection, { prepare_command(self, cmd("SUBSCRIBE").arg(channels)) } diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 7c17867..cfe8948 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -51,7 +51,7 @@ Commands can be directly awaited or [forgotten](crate::client::ClientPreparedCom ``` use rustis::{ - client::{Client, ClientPreparedCommand}, + client::{Client, ClientPreparedCommand}, commands::{ListCommands, SortedSetCommands, ZAddOptions}, Result, }; @@ -77,8 +77,8 @@ async fn main() -> Result<()> { # Documentation disclaimer -The commands traits documentation is directly adapated from the official Redis -documentation found [here](https://github.com/redis/redis-doc) with the +The commands traits documentation is directly adapated from the official Redis +documentation found [here](https://github.com/redis/redis-doc) with the following [COPYRIGHT](https://github.com/redis/redis-doc/blob/master/COPYRIGHT). */ diff --git a/src/commands/scripting_commands.rs b/src/commands/scripting_commands.rs index 7074148..8730288 100644 --- a/src/commands/scripting_commands.rs +++ b/src/commands/scripting_commands.rs @@ -2,8 +2,8 @@ use crate::{ client::{prepare_command, PreparedCommand}, commands::FlushingMode, resp::{ - cmd, deserialize_byte_buf, CommandArgs, PrimitiveResponse, SingleArg, SingleArgCollection, - ToArgs, Response, + cmd, deserialize_byte_buf, CommandArgs, PrimitiveResponse, Response, SingleArg, + SingleArgCollection, ToArgs, }, }; use serde::Deserialize; @@ -424,8 +424,7 @@ impl Default for FunctionRestorePolicy { impl ToArgs for FunctionRestorePolicy { fn write_args(&self, args: &mut CommandArgs) { match self { - FunctionRestorePolicy::Default => { - } + FunctionRestorePolicy::Default => {} FunctionRestorePolicy::Append => { args.arg("APPEND"); } diff --git a/src/commands/search_commands.rs b/src/commands/search_commands.rs index 0958076..a134597 100644 --- a/src/commands/search_commands.rs +++ b/src/commands/search_commands.rs @@ -2322,7 +2322,9 @@ impl<'de> Deserialize<'de> for FtSearchResult { }; let Some(seq_size) = seq.size_hint() else { - return Err(de::Error::custom("sequence `size_hint` is expected for FtSearchResult")); + return Err(de::Error::custom( + "sequence `size_hint` is expected for FtSearchResult", + )); }; if total_results == 0 { diff --git a/src/commands/string_commands.rs b/src/commands/string_commands.rs index e14a0f6..e101490 100644 --- a/src/commands/string_commands.rs +++ b/src/commands/string_commands.rs @@ -79,9 +79,9 @@ pub trait StringCommands<'a> { /// Get the value of key. /// - /// Get the value of key. If the key does not exist the special - /// value nil is returned. An error is returned if the value - /// stored at key is not a string, because GET only handles + /// Get the value of key. If the key does not exist the special + /// value nil is returned. An error is returned if the value + /// stored at key is not a string, because GET only handles /// string values. /// /// # Return diff --git a/src/commands/t_disgest_commands.rs b/src/commands/t_disgest_commands.rs index 0a34623..db42b6b 100644 --- a/src/commands/t_disgest_commands.rs +++ b/src/commands/t_disgest_commands.rs @@ -445,7 +445,11 @@ impl TDigestMergeOptions { #[must_use] pub fn compression(mut self, compression: usize) -> Self { Self { - command_args: self.command_args.arg("COMPRESSION").arg(compression).build(), + command_args: self + .command_args + .arg("COMPRESSION") + .arg(compression) + .build(), } } diff --git a/src/commands/time_series_commands.rs b/src/commands/time_series_commands.rs index d4cd011..1f03e40 100644 --- a/src/commands/time_series_commands.rs +++ b/src/commands/time_series_commands.rs @@ -637,7 +637,11 @@ impl TsAddOptions { #[must_use] pub fn retention(mut self, retention_period: u64) -> Self { Self { - command_args: self.command_args.arg("RETENTION").arg(retention_period).build(), + command_args: self + .command_args + .arg("RETENTION") + .arg(retention_period) + .build(), } } @@ -780,7 +784,11 @@ impl TsCreateOptions { #[must_use] pub fn retention(mut self, retention_period: u64) -> Self { Self { - command_args: self.command_args.arg("RETENTION").arg(retention_period).build(), + command_args: self + .command_args + .arg("RETENTION") + .arg(retention_period) + .build(), } } @@ -823,7 +831,11 @@ impl TsCreateOptions { #[must_use] pub fn duplicate_policy(mut self, policy: TsDuplicatePolicy) -> Self { Self { - command_args: self.command_args.arg("DUPLICATE_POLICY").arg(policy).build(), + command_args: self + .command_args + .arg("DUPLICATE_POLICY") + .arg(policy) + .build(), } } @@ -978,7 +990,11 @@ impl TsIncrByDecrByOptions { #[must_use] pub fn retention(mut self, retention_period: u64) -> Self { Self { - command_args: self.command_args.arg("RETENTION").arg(retention_period).build(), + command_args: self + .command_args + .arg("RETENTION") + .arg(retention_period) + .build(), } } @@ -1272,7 +1288,12 @@ impl TsMRangeOptions { #[must_use] pub fn filter_by_value(mut self, min: f64, max: f64) -> Self { Self { - command_args: self.command_args.arg("FILTER_BY_VALUE").arg(min).arg(max).build(), + command_args: self + .command_args + .arg("FILTER_BY_VALUE") + .arg(min) + .arg(max) + .build(), } } @@ -1469,7 +1490,12 @@ impl TsRangeOptions { #[must_use] pub fn filter_by_value(mut self, min: f64, max: f64) -> Self { Self { - command_args: self.command_args.arg("FILTER_BY_VALUE").arg(min).arg(max).build(), + command_args: self + .command_args + .arg("FILTER_BY_VALUE") + .arg(min) + .arg(max) + .build(), } } diff --git a/src/commands/top_k_commands.rs b/src/commands/top_k_commands.rs index 4a67944..4cb84d4 100644 --- a/src/commands/top_k_commands.rs +++ b/src/commands/top_k_commands.rs @@ -3,8 +3,8 @@ use std::marker::PhantomData; use crate::{ client::{prepare_command, PreparedCommand}, resp::{ - cmd, deserialize_vec_of_pairs, PrimitiveResponse, CollectionResponse, KeyValueArgsCollection, - SingleArg, SingleArgCollection, + cmd, deserialize_vec_of_pairs, CollectionResponse, KeyValueArgsCollection, + PrimitiveResponse, SingleArg, SingleArgCollection, }, }; use serde::{de::DeserializeOwned, Deserialize}; @@ -60,7 +60,11 @@ pub trait TopKCommands<'a> { /// # See Also /// * [](https://redis.io/commands/topk.incrby/) #[must_use] - fn topk_incrby>( + fn topk_incrby< + I: SingleArg, + R: PrimitiveResponse + DeserializeOwned, + RR: CollectionResponse, + >( self, key: impl SingleArg, items: impl KeyValueArgsCollection, @@ -224,7 +228,7 @@ where { Ok(TopKListWithCountResult { phantom: PhantomData, - items: deserialize_vec_of_pairs(deserializer)? + items: deserialize_vec_of_pairs(deserializer)?, }) } } diff --git a/src/lib.rs b/src/lib.rs index 9f27a10..feca211 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,7 +50,7 @@ rustis is a Redis client for Rust. ``` use rustis::{ - client::Client, + client::Client, commands::{FlushingMode, ServerCommands, StringCommands}, Result, }; @@ -76,7 +76,7 @@ async fn main() -> Result<()> { ``` # Client -See the module [`client`] to discover which are the 3 +See the module [`client`] to discover which are the 3 usages of the [`Client`](client::Client) struct and how to configure it. You will also learn how to use pipeline, pub/sub and transactions. @@ -84,7 +84,7 @@ You will also learn how to use pipeline, pub/sub and transactions. # RESP RESP is the [Redis Serialization Protocol](https://redis.io/docs/reference/protocol-spec/). -See the module [`resp`] to discover how **rustis** +See the module [`resp`] to discover how **rustis** allows programmers to communicate with Redis in a Rust idiomatic way. You will learn how to: diff --git a/src/network/command_info_manager.rs b/src/network/command_info_manager.rs index 1f11a8a..5902282 100644 --- a/src/network/command_info_manager.rs +++ b/src/network/command_info_manager.rs @@ -90,13 +90,17 @@ impl CommandInfoManager { }; slice = &slice[..stop_index]; - let keys = slice.iter().step_by(command_info.step).filter_map(|bs| { - if bs.is_empty() { - None - } else { - String::from_utf8(bs.clone()).ok() - } - }).collect(); + let keys = slice + .iter() + .step_by(command_info.step) + .filter_map(|bs| { + if bs.is_empty() { + None + } else { + String::from_utf8(bs.clone()).ok() + } + }) + .collect(); return Ok(keys); } } diff --git a/src/network/connection.rs b/src/network/connection.rs index d836b12..c424dce 100644 --- a/src/network/connection.rs +++ b/src/network/connection.rs @@ -43,7 +43,7 @@ impl Connection { #[inline] pub async fn write_batch( &mut self, - commands: SmallVec::<[&mut Command; 10]>, + commands: SmallVec<[&mut Command; 10]>, retry_reasons: &[RetryReason], ) -> Result<()> { match self { diff --git a/src/network/network_handler.rs b/src/network/network_handler.rs index fa358d5..c81eb71 100644 --- a/src/network/network_handler.rs +++ b/src/network/network_handler.rs @@ -595,10 +595,11 @@ impl NetworkHandler { if let Err(e) = pub_sub_sender.unbounded_send(value) { let error_desc = e.to_string(); if let Ok(ref_value) = &e.into_inner() { - if let Some(RefPubSubMessage::Message(channel_or_pattern, _)| RefPubSubMessage::SMessage( - channel_or_pattern, - _, - )) = RefPubSubMessage::from_resp(ref_value) { + if let Some( + RefPubSubMessage::Message(channel_or_pattern, _) + | RefPubSubMessage::SMessage(channel_or_pattern, _), + ) = RefPubSubMessage::from_resp(ref_value) + { warn!( "[{}] Cannot send pub/sub message to caller from channel `{}`: {error_desc}", self.tag, diff --git a/src/network/sentinel_connection.rs b/src/network/sentinel_connection.rs index 2513eb4..43eb948 100644 --- a/src/network/sentinel_connection.rs +++ b/src/network/sentinel_connection.rs @@ -22,7 +22,7 @@ impl SentinelConnection { #[inline] pub async fn write_batch( &mut self, - commands: SmallVec::<[&mut Command; 10]>, + commands: SmallVec<[&mut Command; 10]>, retry_reasons: &[RetryReason], ) -> Result<()> { self.inner_connection @@ -70,8 +70,12 @@ impl SentinelConnection { let mut unreachable_sentinel = true; let mut sentinel_node_config = config.clone(); - sentinel_node_config.username.clone_from(&sentinel_config.username); - sentinel_node_config.password.clone_from(&sentinel_config.password); + sentinel_node_config + .username + .clone_from(&sentinel_config.username); + sentinel_node_config + .password + .clone_from(&sentinel_config.password); loop { for sentinel_instance in &sentinel_config.instances { diff --git a/src/network/standalone_connection.rs b/src/network/standalone_connection.rs index 658d84a..9b4dfdb 100644 --- a/src/network/standalone_connection.rs +++ b/src/network/standalone_connection.rs @@ -100,7 +100,7 @@ impl StandaloneConnection { pub async fn write_batch( &mut self, - commands: SmallVec::<[&mut Command; 10]>, + commands: SmallVec<[&mut Command; 10]>, _retry_reasons: &[RetryReason], ) -> Result<()> { self.buffer.clear(); diff --git a/src/network/util.rs b/src/network/util.rs index 35babb0..56a4d8b 100644 --- a/src/network/util.rs +++ b/src/network/util.rs @@ -130,7 +130,9 @@ impl<'a> RefPubSubMessage<'a> { if resp_buffer.is_push_message() { let mut deserializer = RespDeserializer::new(resp_buffer); - deserializer.deserialize_seq(RefPubSubMessageVisitor).unwrap_or_default() + deserializer + .deserialize_seq(RefPubSubMessageVisitor) + .unwrap_or_default() } else { None } diff --git a/src/network/version.rs b/src/network/version.rs index 3397be5..a4991b4 100644 --- a/src/network/version.rs +++ b/src/network/version.rs @@ -14,12 +14,22 @@ impl TryFrom<&str> for Version { fn try_from(value: &str) -> std::result::Result { let mut split = value.split('.'); - let (Some(major), Some(minor), Some(revision), None) = (split.next(), split.next(), split.next(), split.next()) else { - return Err(Error::Client("Cannot parse Redis server version".to_owned())); + let (Some(major), Some(minor), Some(revision), None) = + (split.next(), split.next(), split.next(), split.next()) + else { + return Err(Error::Client( + "Cannot parse Redis server version".to_owned(), + )); }; - let (Some(major), Some(minor), Some(revision)) = (atoi::atoi(major.as_bytes()), atoi::atoi(minor.as_bytes()), atoi::atoi(revision.as_bytes())) else { - return Err(Error::Client("Cannot parse Redis server version".to_owned())); + let (Some(major), Some(minor), Some(revision)) = ( + atoi::atoi(major.as_bytes()), + atoi::atoi(minor.as_bytes()), + atoi::atoi(revision.as_bytes()), + ) else { + return Err(Error::Client( + "Cannot parse Redis server version".to_owned(), + )); }; Ok(Version { diff --git a/src/resp/buffer_decoder.rs b/src/resp/buffer_decoder.rs index d546f17..5b3cfb5 100644 --- a/src/resp/buffer_decoder.rs +++ b/src/resp/buffer_decoder.rs @@ -19,8 +19,10 @@ impl Decoder for BufferDecoder { let mut deserializer = RespDeserializer::new(bytes); let result = IgnoredAny::deserialize(&mut deserializer); match result { - Ok(_) => Ok(Some(RespBuf::new(src.split_to(deserializer.get_pos()).freeze()))), - Err(Error::EOF) => { Ok(None) }, + Ok(_) => Ok(Some(RespBuf::new( + src.split_to(deserializer.get_pos()).freeze(), + ))), + Err(Error::EOF) => Ok(None), Err(e) => Err(e), } } diff --git a/src/resp/bulk_string.rs b/src/resp/bulk_string.rs index 7095d3e..104fe83 100644 --- a/src/resp/bulk_string.rs +++ b/src/resp/bulk_string.rs @@ -4,7 +4,13 @@ use std::{fmt, ops::Deref}; /// Represents the [Bulk String](https://redis.io/docs/reference/protocol-spec/#resp-bulk-strings) RESP type #[derive(Deserialize, Serialize)] -pub struct BulkString(#[serde(deserialize_with = "deserialize_byte_buf", serialize_with = "serialize_byte_buf")] Vec); +pub struct BulkString( + #[serde( + deserialize_with = "deserialize_byte_buf", + serialize_with = "serialize_byte_buf" + )] + Vec, +); impl BulkString { /// Constructs a new `BulkString` from a bytes buffer diff --git a/src/resp/command.rs b/src/resp/command.rs index c478c10..1a515b0 100644 --- a/src/resp/command.rs +++ b/src/resp/command.rs @@ -29,7 +29,7 @@ pub struct Command { pub kill_connection_on_write: usize, #[cfg(debug_assertions)] #[allow(unused)] - pub (crate) command_seq: usize, + pub(crate) command_seq: usize, } impl Command { @@ -68,7 +68,7 @@ impl Command { A: ToArgs, { if condition { - arg.write_args(&mut self.args); + arg.write_args(&mut self.args); } self } diff --git a/src/resp/command_encoder.rs b/src/resp/command_encoder.rs index 4a343d2..647b9b4 100644 --- a/src/resp/command_encoder.rs +++ b/src/resp/command_encoder.rs @@ -27,17 +27,25 @@ impl Encoder<&Command> for CommandEncoder { fn calculate_buf_size(command: &Command) -> usize { let mut buf_size = 0; - // *\r\n + // *\r\n let num_args = command.args.len() + 1; buf_size += if num_args <= 9 { 4 } else { 5 }; // $\r\n\r\n let name = command.name.as_bytes(); - buf_size += if name.len() <= 9 { 6 + name.len() } else { 7 + name.len() }; + buf_size += if name.len() <= 9 { + 6 + name.len() + } else { + 7 + name.len() + }; for arg in &command.args { // $\r\n\r\n - buf_size += if arg.len() <= 9 { 6 + arg.len() } else { 7 + arg.len() }; + buf_size += if arg.len() <= 9 { + 6 + arg.len() + } else { + 7 + arg.len() + }; } buf_size diff --git a/src/resp/resp_batch_deserializer.rs b/src/resp/resp_batch_deserializer.rs index d366b9c..84ea2f2 100644 --- a/src/resp/resp_batch_deserializer.rs +++ b/src/resp/resp_batch_deserializer.rs @@ -72,9 +72,7 @@ impl<'de> serde::de::SeqAccess<'de> for SeqAccess<'de> { T: DeserializeSeed<'de>, { match self.iter.next() { - Some(buf) => { - seed.deserialize(&mut RespDeserializer::new(buf)).map(Some) - } + Some(buf) => seed.deserialize(&mut RespDeserializer::new(buf)).map(Some), None => Ok(None), } } diff --git a/src/resp/resp_serializer.rs b/src/resp/resp_serializer.rs index a658cc5..414b0fe 100644 --- a/src/resp/resp_serializer.rs +++ b/src/resp/resp_serializer.rs @@ -221,7 +221,9 @@ impl<'a> Serializer for &'a mut RespSerializer { fn serialize_seq(self, len: Option) -> Result { let Some(len) = len else { - return Err(ser::Error::custom("expecting len on sequence serialization")); + return Err(ser::Error::custom( + "expecting len on sequence serialization", + )); }; self.output.put_u8(ARRAY_TAG); @@ -405,11 +407,7 @@ impl<'a> SerializeStruct for &'a mut RespSerializer { type Error = Error; #[inline] - fn serialize_field( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), Self::Error> + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { @@ -428,11 +426,7 @@ impl<'a> SerializeStructVariant for &'a mut RespSerializer { type Error = Error; #[inline] - fn serialize_field( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), Self::Error> + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> where T: serde::Serialize + ?Sized, { diff --git a/src/resp/to_args.rs b/src/resp/to_args.rs index 613a05a..5137264 100644 --- a/src/resp/to_args.rs +++ b/src/resp/to_args.rs @@ -10,8 +10,8 @@ use std::{ /// Types compatible with command args pub trait ToArgs { /// Write this Rust type as one ore multiple args into CommandArgs. - /// - /// Primitives Rust types will generate a single argument + /// + /// Primitives Rust types will generate a single argument /// whereas collections and tuples will generate multiple arguments fn write_args(&self, args: &mut CommandArgs); diff --git a/src/resp/util.rs b/src/resp/util.rs index 96c4eea..f1db3e4 100644 --- a/src/resp/util.rs +++ b/src/resp/util.rs @@ -149,7 +149,7 @@ where /// Serialize a byte buffer (&\[u8\]) pub fn serialize_byte_buf(bytes: &[u8], serializer: S) -> Result where - S: Serializer + S: Serializer, { serializer.serialize_bytes(bytes) } @@ -195,7 +195,7 @@ where pub(crate) struct BytesSeed; impl<'de> DeserializeSeed<'de> for BytesSeed { - type Value = &'de [u8]; + type Value = &'de [u8]; fn deserialize(self, deserializer: D) -> std::result::Result where diff --git a/src/resp/value_deserialize.rs b/src/resp/value_deserialize.rs index db2c4de..c7eb726 100644 --- a/src/resp/value_deserialize.rs +++ b/src/resp/value_deserialize.rs @@ -206,10 +206,7 @@ impl<'de> Visitor<'de> for PushOrKeyVisitor { } #[inline] - fn visit_bytes( - self, - v: &[u8], - ) -> std::result::Result { + fn visit_bytes(self, v: &[u8]) -> std::result::Result { let value_visitor = ValueVisitor; value_visitor.visit_bytes(v).map(PushOrKey::Key) } diff --git a/src/tests/bitmap_commands.rs b/src/tests/bitmap_commands.rs index ad7436d..7ef6c77 100644 --- a/src/tests/bitmap_commands.rs +++ b/src/tests/bitmap_commands.rs @@ -136,7 +136,7 @@ async fn bitop() -> Result<()> { assert_eq!("`bc`ab", value); client.close().await?; - + Ok(()) } @@ -146,16 +146,12 @@ async fn bitop() -> Result<()> { async fn bitpos() -> Result<()> { let client = get_test_client().await?; - client - .set("mykey", vec![0xFFu8, 0xF0u8, 0x00u8]) - .await?; + client.set("mykey", vec![0xFFu8, 0xF0u8, 0x00u8]).await?; let pos = client.bitpos("mykey", 1, BitRange::default()).await?; assert_eq!(0, pos); - client - .set("mykey", vec![0x00u8, 0xFFu8, 0xF0u8]) - .await?; + client.set("mykey", vec![0x00u8, 0xFFu8, 0xF0u8]).await?; let pos = client.bitpos("mykey", 0, BitRange::range(0, -1)).await?; assert_eq!(0, pos); diff --git a/src/tests/bloom_commands.rs b/src/tests/bloom_commands.rs index 406e5f2..2593e6d 100644 --- a/src/tests/bloom_commands.rs +++ b/src/tests/bloom_commands.rs @@ -162,11 +162,7 @@ async fn bf_reserve_loadchunk_scandump() -> Result<()> { while let Some(dump_result) = chunks.pop_front() { client - .bf_loadchunk( - "bf", - dump_result.iterator, - dump_result.data, - ) + .bf_loadchunk("bf", dump_result.iterator, dump_result.data) .await?; } diff --git a/src/tests/buffer_decoder.rs b/src/tests/buffer_decoder.rs index 17cd15f..80995a5 100644 --- a/src/tests/buffer_decoder.rs +++ b/src/tests/buffer_decoder.rs @@ -1,4 +1,4 @@ -use bytes::{BytesMut}; +use bytes::BytesMut; use tokio_util::codec::Decoder; use crate::{resp::BufferDecoder, Result}; @@ -6,7 +6,9 @@ use crate::{resp::BufferDecoder, Result}; fn decode(str: &str) -> Result>> { let mut buffer_decoder = BufferDecoder; let mut buf: BytesMut = str.into(); - buffer_decoder.decode(&mut buf).map(|b| b.map(|b| b.to_vec())) + buffer_decoder + .decode(&mut buf) + .map(|b| b.map(|b| b.to_vec())) } #[test] @@ -137,7 +139,10 @@ fn bulk_string() -> Result<()> { #[test] fn array() -> Result<()> { let result = decode("*2\r\n$5\r\nhello\r\n$5\r\nworld\r\n")?; - assert_eq!(Some("*2\r\n$5\r\nhello\r\n$5\r\nworld\r\n".as_bytes().to_vec()), result); + assert_eq!( + Some("*2\r\n$5\r\nhello\r\n$5\r\nworld\r\n".as_bytes().to_vec()), + result + ); let result = decode("*2")?; assert_eq!(None, result); @@ -172,7 +177,10 @@ fn array() -> Result<()> { #[test] fn map() -> Result<()> { let result = decode("%1\r\n$5\r\nhello\r\n$5\r\nworld\r\n")?; - assert_eq!(Some("%1\r\n$5\r\nhello\r\n$5\r\nworld\r\n".as_bytes().to_vec()), result); + assert_eq!( + Some("%1\r\n$5\r\nhello\r\n$5\r\nworld\r\n".as_bytes().to_vec()), + result + ); let result = decode("%1")?; assert_eq!(None, result); @@ -202,4 +210,4 @@ fn map() -> Result<()> { assert_eq!(None, result); Ok(()) -} \ No newline at end of file +} diff --git a/src/tests/client.rs b/src/tests/client.rs index 133080a..3e8f612 100644 --- a/src/tests/client.rs +++ b/src/tests/client.rs @@ -75,13 +75,13 @@ async fn command_timeout() -> Result<()> { log_try_init(); let client = get_test_client().await?; - + client.flushall(FlushingMode::Sync).await?; // create an empty list client.lpush("key", "value").await?; let _result: Vec = client.lpop("key", 1).await?; - + client.close().await?; let mut config = get_default_addr().into_config()?; @@ -151,7 +151,15 @@ async fn mget_mset() -> Result<()> { .await? .to()?; - assert_eq!(vec!["value1".to_owned(), "value2".to_owned(), "value3".to_owned(), "value4".to_owned()], values); + assert_eq!( + vec![ + "value1".to_owned(), + "value2".to_owned(), + "value3".to_owned(), + "value4".to_owned() + ], + values + ); Ok(()) } diff --git a/src/tests/config.rs b/src/tests/config.rs index 865fa2a..615f9a6 100644 --- a/src/tests/config.rs +++ b/src/tests/config.rs @@ -1,6 +1,6 @@ use crate::{ client::{Client, IntoConfig}, - commands::{ClientKillOptions, ConnectionCommands, ServerCommands, FlushingMode}, + commands::{ClientKillOptions, ConnectionCommands, FlushingMode, ServerCommands}, tests::{get_default_host, get_default_port, get_test_client, log_try_init}, Result, }; @@ -49,11 +49,7 @@ async fn password() -> Result<()> { #[serial] async fn reconnection() -> Result<()> { log_try_init(); - let uri = format!( - "redis://{}:{}/1", - get_default_host(), - get_default_port() - ); + let uri = format!("redis://{}:{}/1", get_default_host(), get_default_port()); let client = Client::connect(uri.clone()).await?; // kill client connection from another client to force reconnection @@ -71,10 +67,7 @@ async fn reconnection() -> Result<()> { #[test] fn into_config() -> Result<()> { - assert_eq!( - "redis://127.0.0.1", - "127.0.0.1".into_config()?.to_string() - ); + assert_eq!("redis://127.0.0.1", "127.0.0.1".into_config()?.to_string()); assert_eq!( "redis://127.0.0.1", "127.0.0.1:6379".into_config()?.to_string() @@ -108,7 +101,7 @@ fn into_config() -> Result<()> { "redis://username:pwd@127.0.0.1/1" .into_config()? .to_string() - ); + ); #[cfg(feature = "tls")] assert_eq!( "rediss://username:pwd@127.0.0.1/1", diff --git a/src/tests/connection_commands.rs b/src/tests/connection_commands.rs index 755a504..f016cb5 100644 --- a/src/tests/connection_commands.rs +++ b/src/tests/connection_commands.rs @@ -3,8 +3,7 @@ use crate::{ commands::{ ClientCachingMode, ClientKillOptions, ClientListOptions, ClientPauseMode, ClientReplyMode, ClientTrackingOptions, ClientTrackingStatus, ClientUnblockMode, ConnectionCommands, - FlushingMode, GenericCommands, HelloOptions, PingOptions, ServerCommands, - StringCommands, + FlushingMode, GenericCommands, HelloOptions, PingOptions, ServerCommands, StringCommands, }, network::spawn, sleep, diff --git a/src/tests/cuckoo_commands.rs b/src/tests/cuckoo_commands.rs index b19b708..e805c46 100644 --- a/src/tests/cuckoo_commands.rs +++ b/src/tests/cuckoo_commands.rs @@ -1,7 +1,7 @@ use crate::{ commands::{ - CfInsertOptions, CfReserveOptions, CuckooCommands, FlushingMode, ServerCommands, - StringCommands, CfScanDumpResult, + CfInsertOptions, CfReserveOptions, CfScanDumpResult, CuckooCommands, FlushingMode, + ServerCommands, StringCommands, }, tests::get_redis_stack_test_client, Error, RedisError, RedisErrorKind, Result, @@ -216,9 +216,7 @@ async fn cf_reserve_loadchunk_scandump() -> Result<()> { client.flushall(FlushingMode::Sync).await?; while let Some(dump) = chunks.pop_front() { - client - .cf_loadchunk("cf", dump.iterator, dump.data) - .await?; + client.cf_loadchunk("cf", dump.iterator, dump.data).await?; } let result = client.cf_exists("cf", "item1").await?; diff --git a/src/tests/hash_commands.rs b/src/tests/hash_commands.rs index e2393b8..e92ede8 100644 --- a/src/tests/hash_commands.rs +++ b/src/tests/hash_commands.rs @@ -246,10 +246,22 @@ async fn hscan() -> Result<()> { assert_eq!(0, result.cursor); assert_eq!(20, result.elements.len()); - assert_eq!(("field1".to_owned(), "value1".to_owned()), result.elements[0]); - assert_eq!(("field2".to_owned(), "value2".to_owned()), result.elements[1]); - assert_eq!(("field3".to_owned(), "value3".to_owned()), result.elements[2]); - assert_eq!(("field4".to_owned(), "value4".to_owned()), result.elements[3]); + assert_eq!( + ("field1".to_owned(), "value1".to_owned()), + result.elements[0] + ); + assert_eq!( + ("field2".to_owned(), "value2".to_owned()), + result.elements[1] + ); + assert_eq!( + ("field3".to_owned(), "value3".to_owned()), + result.elements[2] + ); + assert_eq!( + ("field4".to_owned(), "value4".to_owned()), + result.elements[3] + ); Ok(()) } diff --git a/src/tests/mod.rs b/src/tests/mod.rs index 8b8261c..fba498b 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -13,6 +13,7 @@ mod connection_commands; mod count_min_sktech_commands; #[cfg(feature = "redis-bloom")] mod cuckoo_commands; +mod debug_commands; mod error; mod from_value; mod generic_commands; @@ -41,7 +42,6 @@ mod set_commands; mod sorted_set_commands; mod stream_commands; mod string_commands; -mod debug_commands; #[cfg(feature = "redis-bloom")] mod t_disgest_commands; #[cfg(feature = "redis-time-series")] diff --git a/src/tests/pipeline.rs b/src/tests/pipeline.rs index d2e12ed..1765c72 100644 --- a/src/tests/pipeline.rs +++ b/src/tests/pipeline.rs @@ -2,7 +2,7 @@ use crate::{ client::BatchPreparedCommand, commands::{FlushingMode, ServerCommands, StringCommands}, resp::{cmd, Value}, - tests::{get_test_client, get_cluster_test_client}, + tests::{get_cluster_test_client, get_test_client}, Result, }; use serial_test::serial; @@ -47,7 +47,6 @@ async fn error() -> Result<()> { Ok(()) } - #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[serial] @@ -66,4 +65,4 @@ async fn pipeline_on_cluster() -> Result<()> { assert_eq!("value2", value2); Ok(()) -} \ No newline at end of file +} diff --git a/src/tests/resp_deserializer.rs b/src/tests/resp_deserializer.rs index f6b7e6c..b0a4fec 100644 --- a/src/tests/resp_deserializer.rs +++ b/src/tests/resp_deserializer.rs @@ -228,10 +228,10 @@ fn option() -> Result<()> { let result: Option = deserialize("_\r\n")?; // null assert_eq!(None, result); - let result: Option::> = deserialize("*1\r\n:12\r\n")?; // [12] + let result: Option> = deserialize("*1\r\n:12\r\n")?; // [12] assert_eq!(Some(vec![12]), result); - let result: Option::> = deserialize("*0\r\n")?; // [] + let result: Option> = deserialize("*0\r\n")?; // [] assert_eq!(None, result); Ok(()) @@ -556,7 +556,14 @@ fn array_chunks() -> Result<()> { let mut deserializer = RespDeserializer::new(resp.as_bytes()); let chunks = deserializer.array_chunks()?.collect::>(); - assert_eq!(vec![":1\r\n".as_bytes(), ":12\r\n".as_bytes(), ":123\r\n".as_bytes()], chunks); + assert_eq!( + vec![ + ":1\r\n".as_bytes(), + ":12\r\n".as_bytes(), + ":123\r\n".as_bytes() + ], + chunks + ); Ok(()) } diff --git a/src/tests/resp_serializer.rs b/src/tests/resp_serializer.rs index 0ad8bec..8d00831 100644 --- a/src/tests/resp_serializer.rs +++ b/src/tests/resp_serializer.rs @@ -201,7 +201,10 @@ fn map() -> Result<()> { log_try_init(); let result = serialize(HashMap::from([(12, 13), (14, 15)]))?; - assert!(result == "%2\r\n:12\r\n:13\r\n:14\r\n:15\r\n" || result == "%2\r\n:14\r\n:15\r\n:12\r\n:13\r\n"); + assert!( + result == "%2\r\n:12\r\n:13\r\n:14\r\n:15\r\n" + || result == "%2\r\n:14\r\n:15\r\n:12\r\n:13\r\n" + ); Ok(()) } @@ -251,7 +254,10 @@ fn _enum() -> Result<()> { g: 13, b: 14, })?; - assert_eq!("%1\r\n+D\r\n%3\r\n+r\r\n:12\r\n+g\r\n:13\r\n+b\r\n:14\r\n", result); + assert_eq!( + "%1\r\n+D\r\n%3\r\n+r\r\n:12\r\n+g\r\n:13\r\n+b\r\n:14\r\n", + result + ); Ok(()) } diff --git a/src/tests/scripting_commands.rs b/src/tests/scripting_commands.rs index 9f257a0..dce8fcf 100644 --- a/src/tests/scripting_commands.rs +++ b/src/tests/scripting_commands.rs @@ -4,13 +4,10 @@ use crate::{ CallBuilder, FlushingMode, FunctionListOptions, LibraryInfo, ScriptingCommands, ServerCommands, StringCommands, }, + error::{Error, RedisErrorKind}, sleep, spawn, tests::get_test_client, Result, - error::{ - Error, - RedisErrorKind - }, }; use serial_test::serial; @@ -44,7 +41,6 @@ async fn eval() -> Result<()> { Ok(()) } - #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[serial] @@ -59,11 +55,7 @@ redis.call("DEL", "key"); return { ARGV[1], ARGV[2], 42, arr } "#; let result: (String, String, i32, Vec) = client - .eval( - CallBuilder::script(lua_script) - .args("Hello") - .args("world"), - ) + .eval(CallBuilder::script(lua_script).args("Hello").args("world")) .await?; assert_eq!(result.0, "Hello"); @@ -82,7 +74,9 @@ async fn evalsha_noscript() -> Result<()> { // SHA1("") == da39a3ee5e6b4b0d3255bfef95601890afd80709 let result = client - .evalsha::<()>(CallBuilder::sha1("da39a3ee5e6b4b0d3255bfef95601890afd80709")) + .evalsha::<()>(CallBuilder::sha1( + "da39a3ee5e6b4b0d3255bfef95601890afd80709", + )) .await .unwrap_err(); @@ -146,11 +140,7 @@ end) let library: String = client.function_load(true, lua_lib).await?; assert_eq!("mylib", library); let result: (String, String, i32, Vec) = client - .fcall( - CallBuilder::function("myfunc") - .args("Hello") - .args("world"), - ) + .fcall(CallBuilder::function("myfunc").args("Hello").args("world")) .await?; assert_eq!(result.0, "Hello"); diff --git a/src/tests/set_commands.rs b/src/tests/set_commands.rs index 67613e3..9fdfc09 100644 --- a/src/tests/set_commands.rs +++ b/src/tests/set_commands.rs @@ -1,6 +1,10 @@ use std::collections::HashSet; -use crate::{tests::get_test_client, commands::{GenericCommands, SScanOptions, SetCommands}, Result}; +use crate::{ + commands::{GenericCommands, SScanOptions, SetCommands}, + tests::get_test_client, + Result, +}; use serial_test::serial; #[cfg_attr(feature = "tokio-runtime", tokio::test)] diff --git a/src/tests/tls.rs b/src/tests/tls.rs index bc9037f..45cfa38 100644 --- a/src/tests/tls.rs +++ b/src/tests/tls.rs @@ -1,5 +1,5 @@ #[cfg(feature = "tls")] -use crate::{tests::get_tls_test_client, commands::StringCommands, Result}; +use crate::{commands::StringCommands, tests::get_tls_test_client, Result}; #[cfg(feature = "tls")] use serial_test::serial; diff --git a/src/tests/transaction.rs b/src/tests/transaction.rs index bb0d29d..cb644d7 100644 --- a/src/tests/transaction.rs +++ b/src/tests/transaction.rs @@ -2,7 +2,7 @@ use crate::{ client::BatchPreparedCommand, commands::{FlushingMode, ListCommands, ServerCommands, StringCommands, TransactionCommands}, resp::cmd, - tests::{get_test_client, get_cluster_test_client}, + tests::{get_cluster_test_client, get_test_client}, Error, RedisError, RedisErrorKind, Result, }; use serial_test::serial; @@ -170,7 +170,9 @@ async fn transaction_on_cluster_connection_with_keys_with_same_slot() -> Result< let mut transaction = client.create_transaction(); - transaction.mset([("{hash}key1", "value1"), ("{hash}key2", "value2")]).queue(); + transaction + .mset([("{hash}key1", "value1"), ("{hash}key2", "value2")]) + .queue(); transaction.get::<_, String>("{hash}key1").queue(); transaction.get::<_, String>("{hash}key2").queue(); let ((), val1, val2): ((), String, String) = transaction.execute().await.unwrap(); @@ -189,7 +191,9 @@ async fn transaction_on_cluster_connection_with_keys_with_different_slots() -> R let mut transaction = client.create_transaction(); - transaction.mset([("key1", "value1"), ("key2", "value2")]).queue(); + transaction + .mset([("key1", "value1"), ("key2", "value2")]) + .queue(); transaction.get::<_, String>("key1").queue(); transaction.get::<_, String>("key2").queue(); let result: Result<((), String, String)> = transaction.execute().await;