Przeglądaj źródła

Fix clippy warnings (#62)

César D. Rodas 1 rok temu
rodzic
commit
3696f397d6

+ 1 - 0
redis-config-parser/src/lib.rs

@@ -1,2 +1,3 @@
+#![deny(warnings)]
 pub mod de;
 pub mod parser;

+ 6 - 6
redis-config-parser/src/parser.rs

@@ -58,16 +58,16 @@ macro_rules! read_until {
 }
 
 pub fn parse(bytes: &'_ [u8]) -> Result<(&'_ [u8], ConfigValue<'_>), Error> {
-    let bytes = skip!(bytes, vec![b' ', b'\t', b'\r', b'\n']);
+    let bytes = skip!(bytes, [b' ', b'\t', b'\r', b'\n']);
     let bytes = if bytes.first() == Some(&b'#') {
         // The entire line is a comment, skip the whole line
-        let (bytes, _) = read_until!(bytes, vec![b'\n']);
-        skip!(bytes, vec![b' ', b'\t', b'\r', b'\n'])
+        let (bytes, _) = read_until!(bytes, [b'\n']);
+        skip!(bytes, [b' ', b'\t', b'\r', b'\n'])
     } else {
         bytes
     };
-    let (bytes, name) = read_until!(bytes, vec![b' ', b'\t', b'\r']);
-    let bytes = skip!(bytes, vec![b' ', b'\t', b'\r']);
+    let (bytes, name) = read_until!(bytes, [b' ', b'\t', b'\r']);
+    let bytes = skip!(bytes, [b' ', b'\t', b'\r']);
 
     let mut args = vec![];
     let len = bytes.len();
@@ -86,7 +86,7 @@ pub fn parse(bytes: &'_ [u8]) -> Result<(&'_ [u8], ConfigValue<'_>), Error> {
                 break;
             }
             b'#' => {
-                let (_, skipped) = read_until!(bytes, vec![b'\n']);
+                let (_, skipped) = read_until!(bytes, [b'\n']);
                 i += skipped.len() + 1;
                 break;
             }

+ 3 - 3
src/cmd/client.rs

@@ -42,7 +42,7 @@ pub async fn client(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Valu
         }
         "unblock" => {
             let reason = match args.get(1) {
-                Some(x) => match String::from_utf8_lossy(&x).to_uppercase().as_str() {
+                Some(x) => match String::from_utf8_lossy(x).to_uppercase().as_str() {
                     "TIMEOUT" => UnblockReason::Timeout,
                     "ERROR" => UnblockReason::Error,
                     _ => return Err(Error::Syntax),
@@ -102,7 +102,7 @@ pub async fn ping(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value,
     if conn.status() == ConnectionStatus::Pubsub {
         return Ok(Value::Array(vec![
             "pong".into(),
-            args.pop_front().map(|p| Value::Blob(p)).unwrap_or_default(),
+            args.pop_front().map(Value::Blob).unwrap_or_default(),
         ]));
     }
     match args.len() {
@@ -286,7 +286,7 @@ mod test {
     async fn client_unblock_4() {
         let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
         let c1 = create_connection();
-        let (mut c2_recv, c2) = c1.all_connections().new_connection(c1.db(), addr);
+        let (_, c2) = c1.all_connections().new_connection(c1.db(), addr);
         // block c2
         c2.block();
 

+ 4 - 10
src/cmd/hash.rs

@@ -3,17 +3,11 @@ use crate::{
     check_arg,
     connection::Connection,
     error::Error,
-    value::Value,
-    value::{self, bytes_to_number, float::Float},
+    value::{bytes_to_number, float::Float, Value},
 };
 use bytes::Bytes;
 use rand::Rng;
-use std::{
-    collections::{BTreeMap, HashMap, VecDeque},
-    convert::TryFrom,
-    ops::AddAssign,
-    str::FromStr,
-};
+use std::collections::{BTreeMap, HashMap, VecDeque};
 
 /// Removes the specified fields from the hash stored at key. Specified fields that do not exist
 /// within this hash are ignored. If key does not exist, it is treated as an empty hash and this
@@ -77,7 +71,7 @@ pub async fn hget(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Err
 
 /// Returns all fields and values of the hash stored at key. In the returned value, every field
 /// name is followed by its value, so the length of the reply is twice the size of the hash.
-pub async fn hgetall(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
+pub async fn hgetall(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
     conn.db().get_map(&args[0], |v| match v {
         Some(Value::Hash(h)) => {
             let mut ret = vec![];
@@ -263,7 +257,7 @@ pub async fn hmset(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
                 let value = args.pop_front().ok_or(Error::Syntax)?;
                 h.insert(key, value);
             }
-            let len = h.len();
+            let _len = h.len();
             conn.db().set(key.clone(), h.into(), None);
             Ok(Value::Ok)
         }

+ 12 - 17
src/cmd/key.rs

@@ -3,20 +3,15 @@ use super::now;
 use crate::{
     check_arg,
     connection::Connection,
-    db::{scan::Scan, utils::ExpirationOpts},
+    db::scan::Scan,
     error::Error,
     value::{
         bytes_to_int, bytes_to_number, cursor::Cursor, expiration::Expiration, typ::Typ, Value,
     },
 };
 use bytes::Bytes;
-use std::{
-    collections::VecDeque,
-    convert::TryInto,
-    str::FromStr,
-    time::{SystemTime, UNIX_EPOCH},
-};
-use tokio::time::{Duration, Instant};
+use std::{collections::VecDeque, convert::TryInto, str::FromStr};
+use tokio::time::Instant;
 
 /// This command copies the value stored at the source key to the destination
 /// key.
@@ -68,13 +63,13 @@ pub async fn copy(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value,
 }
 
 /// Removes the specified keys. A key is ignored if it does not exist.
-pub async fn del(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
+pub async fn del(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
     let keys = args.into_iter().collect::<Vec<_>>();
     Ok(conn.db().del(&keys))
 }
 
 /// Returns if key exists.
-pub async fn exists(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
+pub async fn exists(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
     let keys = args.into_iter().collect::<Vec<_>>();
     Ok(conn.db().exists(&keys).into())
 }
@@ -247,7 +242,7 @@ pub async fn object(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, E
 
     if expected_args != args.len() {
         return Err(Error::SubCommandNotFound(
-            subcommand.into(),
+            subcommand,
             String::from_utf8_lossy(&args[0]).into(),
         ));
     }
@@ -260,7 +255,7 @@ pub async fn object(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, E
             Value::Null
         }),
         _ => Err(Error::SubCommandNotFound(
-            subcommand.into(),
+            subcommand,
             String::from_utf8_lossy(&args[0]).into(),
         )),
     }
@@ -620,7 +615,7 @@ mod test {
     #[tokio::test]
     async fn scan_no_args() {
         let c = create_connection();
-        for i in (1..100) {
+        for i in 1..100 {
             assert_eq!(
                 Ok(1.into()),
                 run_command(&c, &["incr", &format!("foo-{}", i)]).await
@@ -641,7 +636,7 @@ mod test {
     #[tokio::test]
     async fn scan_with_count_match() {
         let c = create_connection();
-        for i in (1..100) {
+        for i in 1..100 {
             assert_eq!(
                 Ok(1.into()),
                 run_command(&c, &["incr", &format!("foo-{}", i)]).await
@@ -662,7 +657,7 @@ mod test {
     #[tokio::test]
     async fn scan_with_type_1() {
         let c = create_connection();
-        for i in (1..100) {
+        for i in 1..100 {
             assert_eq!(
                 Ok(1.into()),
                 run_command(&c, &["incr", &format!("foo-{}", i)]).await
@@ -683,7 +678,7 @@ mod test {
     #[tokio::test]
     async fn scan_with_type_2() {
         let c = create_connection();
-        for i in (1..100) {
+        for i in 1..100 {
             assert_eq!(
                 Ok(1.into()),
                 run_command(&c, &["incr", &format!("foo-{}", i)]).await
@@ -704,7 +699,7 @@ mod test {
     #[tokio::test]
     async fn scan_with_count() {
         let c = create_connection();
-        for i in (1..100) {
+        for i in 1..100 {
             assert_eq!(
                 Ok(1.into()),
                 run_command(&c, &["incr", &format!("foo-{}", i)]).await

+ 41 - 45
src/cmd/list.rs

@@ -1,7 +1,7 @@
 //! # List command handlers
 use crate::{
     check_arg,
-    connection::{Connection, ConnectionStatus, UnblockReason},
+    connection::{Connection, UnblockReason},
     db::utils::far_future,
     error::Error,
     try_get_arg, try_get_arg_str,
@@ -11,9 +11,9 @@ use crate::{
 };
 use bytes::Bytes;
 use futures::{stream::FuturesUnordered, Future, StreamExt};
-use std::{collections::VecDeque, ops::Deref, sync::Arc};
+use std::{collections::VecDeque, sync::Arc};
 use tokio::{
-    sync::broadcast::{self, error::RecvError, Receiver},
+    sync::broadcast::{self, Receiver},
     time::{sleep, Duration, Instant},
 };
 
@@ -74,9 +74,8 @@ fn remove_element(
 }
 
 #[inline]
-async fn wait_for_event(receiver: &mut Receiver<()>) -> () {
+async fn wait_for_event(receiver: &mut Receiver<()>) {
     let _ = receiver.recv().await;
-    ()
 }
 
 #[inline]
@@ -93,10 +92,10 @@ async fn schedule_blocking_task<F, T>(
     conn.block();
 
     let mut timeout_rx = if let Some(timeout) = timeout {
-        let (mut timeout_sx, timeout_rx) = broadcast::channel::<()>(1);
+        let (timeout_sx, timeout_rx) = broadcast::channel::<()>(1);
         // setup timeout triggering event
         let conn_for_timeout = conn.clone();
-        let keys_to_watch_for_timeout = keys_to_watch.clone();
+        let _keys_to_watch_for_timeout = keys_to_watch.clone();
         let block_id = conn.get_block_id();
         tokio::spawn(async move {
             sleep(timeout - Instant::now()).await;
@@ -107,7 +106,7 @@ async fn schedule_blocking_task<F, T>(
             conn_for_timeout.unblock(UnblockReason::Timeout);
             conn_for_timeout.append_response(Value::Null);
             // Notify timeout event to the worker thread
-            timeout_sx.send(());
+            let _ = timeout_sx.send(());
         });
         Some(timeout_rx)
     } else {
@@ -144,7 +143,7 @@ async fn schedule_blocking_task<F, T>(
 
             let mut futures = changes_watchers
                 .iter_mut()
-                .map(|c| wait_for_event(c))
+                .map(wait_for_event)
                 .collect::<FuturesUnordered<_>>();
 
             if let Some(ref mut timeout_rx) = &mut timeout_rx {
@@ -202,12 +201,12 @@ pub async fn blpop(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
     };
 
     if conn.is_executing_tx() {
-        return blpop_task(conn.clone(), args, 1).await;
+        return blpop_task(conn.get_connection(), args, 1).await;
     }
 
     let timeout = parse_timeout(&args.pop_back().ok_or(Error::Syntax)?)?;
-    let conn = conn.clone();
-    let keys_to_watch = args.iter().map(|c| c.clone()).collect::<Vec<_>>();
+    let conn = conn.get_connection();
+    let keys_to_watch = args.iter().cloned().collect::<Vec<_>>();
 
     conn.block();
 
@@ -229,14 +228,14 @@ pub async fn blpop(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
 /// See LMOVE for more information.
 pub async fn blmove(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
     if conn.is_executing_tx() {
-        return lmove(&conn, args).await;
+        return lmove(conn, args).await;
     }
 
     let timeout = parse_timeout(&args.pop_back().ok_or(Error::Syntax)?)?;
     let keys_to_watch = vec![args[0].clone(), args[1].clone()];
 
     schedule_blocking_task(
-        conn.clone(),
+        conn.get_connection(),
         keys_to_watch,
         |conn, args, _| async move { lmove(&conn, args).await },
         args,
@@ -288,13 +287,20 @@ pub async fn brpop(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
     };
 
     if conn.is_executing_tx() {
-        return brpop_task(conn.clone(), args, 1).await;
+        return brpop_task(conn.get_connection(), args, 1).await;
     }
 
     let timeout = parse_timeout(&args.pop_back().ok_or(Error::Syntax)?)?;
     let keys_to_watch = args.iter().cloned().collect();
 
-    schedule_blocking_task(conn.clone(), keys_to_watch, brpop_task, args, timeout).await;
+    schedule_blocking_task(
+        conn.get_connection(),
+        keys_to_watch,
+        brpop_task,
+        args,
+        timeout,
+    )
+    .await;
 
     Ok(Value::Ignore)
 }
@@ -306,13 +312,11 @@ pub async fn brpop(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
 pub async fn lindex(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
     conn.db().get_map(&args[0], |v| match v {
         Some(Value::List(x)) => {
-            let mut index: i64 = bytes_to_number(&args[1])?;
+            let index: i64 = bytes_to_number(&args[1])?;
             let x = x.read();
 
             let index = if index < 0 {
-                x.len()
-                    .checked_sub((index * -1) as usize)
-                    .unwrap_or(x.len())
+                x.len().checked_sub(-index as usize).unwrap_or(x.len())
             } else {
                 index as usize
             };
@@ -357,7 +361,7 @@ pub async fn linsert(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Val
                     if id > x.len() {
                         x.push_back(value);
                     } else {
-                        x.insert(id as usize, value);
+                        x.insert(id, value);
                     }
 
                     found = true;
@@ -416,7 +420,7 @@ pub async fn lmove(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
 
     let db = conn.db();
 
-    /// Lock keys to alter exclusively
+    // Lock keys to alter exclusively
     db.lock_keys(&to_lock);
 
     let mut to_create = None;
@@ -470,7 +474,7 @@ pub async fn lmove(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
         conn.db().set(destination.clone(), to_create.into(), None);
     }
 
-    /// release the lock on keys
+    // release the lock on keys
     db.unlock_keys(&to_lock);
 
     if result != Ok(Value::Null) {
@@ -488,7 +492,7 @@ pub async fn lmove(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value
 /// the list's length.
 pub async fn lpop(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
     let count = match args.get(1) {
-        Some(v) => Some(bytes_to_number(&v)?),
+        Some(v) => Some(bytes_to_number(v)?),
         None => None,
     };
 
@@ -513,9 +517,9 @@ pub async fn lpos(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Err
 
         let next = try_get_arg!(args, index + 1);
         match try_get_arg_str!(args, index).to_uppercase().as_str() {
-            "RANK" => rank = Some(bytes_to_number::<i64>(&next)?),
-            "COUNT" => count = Some(bytes_to_number::<usize>(&next)?),
-            "MAXLEN" => max_len = Some(bytes_to_number::<usize>(&next)?),
+            "RANK" => rank = Some(bytes_to_number::<i64>(next)?),
+            "COUNT" => count = Some(bytes_to_number::<usize>(next)?),
+            "MAXLEN" => max_len = Some(bytes_to_number::<usize>(next)?),
             _ => return Err(Error::Syntax),
         }
 
@@ -527,7 +531,7 @@ pub async fn lpos(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Err
             return Err(Error::InvalidRank("RANK".to_owned()));
         }
         if rank < 0 {
-            (true, Some((rank * -1) as usize))
+            (true, Some(-rank as usize))
         } else {
             (false, Some(rank as usize))
         }
@@ -583,23 +587,19 @@ pub async fn lpos(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Err
                 let rank = rank - 1;
 
                 let result = if rank < result.len() {
-                    (&result[rank..]).to_vec()
+                    result[rank..].to_vec()
                 } else {
                     vec![]
                 };
 
                 return Ok(if let Some(count) = count {
                     if count > 0 && count < result.len() {
-                        (&result[0..count]).to_vec().into()
+                        result[0..count].to_vec().into()
                     } else {
                         result.to_vec().into()
                     }
                 } else {
-                    result
-                        .to_vec()
-                        .get(0)
-                        .map(|c| c.clone())
-                        .unwrap_or_default()
+                    result.to_vec().first().cloned().unwrap_or_default()
                 });
             }
 
@@ -666,9 +666,7 @@ pub async fn lpushx(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Valu
             }
             Ok(x.len().into())
         }
-        None => {
-            return Ok(0.into());
-        }
+        None => Ok(0.into()),
         _ => Err(Error::WrongType),
     })?;
 
@@ -691,18 +689,16 @@ pub async fn lrange(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, E
             let x = x.read();
 
             let start = if start < 0 {
-                x.len()
-                    .checked_sub((start * -1) as usize)
-                    .unwrap_or_default()
+                x.len().checked_sub(-start as usize).unwrap_or_default()
             } else {
-                (start as usize)
+                start as usize
             };
 
             let end = if end < 0 {
-                if let Some(x) = x.len().checked_sub((end * -1) as usize) {
+                if let Some(x) = x.len().checked_sub(-end as usize) {
                     x
                 } else {
-                    return Ok(Value::Array((vec![])));
+                    return Ok(Value::Array(vec![]));
                 }
             } else {
                 end as usize
@@ -847,7 +843,7 @@ pub async fn ltrim(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Er
 /// list's length.
 pub async fn rpop(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
     let count = match args.get(1) {
-        Some(v) => Some(bytes_to_number(&v)?),
+        Some(v) => Some(bytes_to_number(v)?),
         None => None,
     };
 

+ 1 - 1
src/cmd/mod.rs

@@ -1,6 +1,6 @@
 //! # All commands handlers
 use std::time::{SystemTime, UNIX_EPOCH};
-use tokio::time::{Duration, Instant};
+use tokio::time::Duration;
 
 pub mod client;
 pub mod hash;

+ 7 - 8
src/cmd/pubsub.rs

@@ -1,7 +1,7 @@
 //! # Pubsub command handlers
 use std::collections::VecDeque;
 
-use crate::{check_arg, connection::Connection, error::Error, value::Value};
+use crate::{connection::Connection, error::Error, value::Value};
 use bytes::Bytes;
 use glob::Pattern;
 
@@ -20,7 +20,7 @@ pub async fn pubsub(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Valu
             conn.pubsub()
                 .channels()
                 .iter()
-                .map(|v| Value::new(&v))
+                .map(|v| Value::new(v))
                 .collect(),
         )),
         "help" => super::help::pubsub(),
@@ -29,8 +29,7 @@ pub async fn pubsub(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Valu
             .pubsub()
             .get_number_of_subscribers(&args)
             .iter()
-            .map(|(channel, subs)| vec![Value::new(channel), (*subs).into()])
-            .flatten()
+            .flat_map(|(channel, subs)| vec![Value::new(channel), (*subs).into()])
             .collect::<Vec<Value>>()
             .into()),
         cmd => Err(Error::SubCommandNotFound(cmd.into(), "pubsub".into())),
@@ -53,7 +52,7 @@ pub async fn psubscribe(conn: &Connection, args: VecDeque<Bytes>) -> Result<Valu
 
 /// Unsubscribes the client from the given patterns, or from all of them if none is given.
 pub async fn punsubscribe(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
-    let channels = if args.len() == 0 {
+    let channels = if args.is_empty() {
         conn.pubsub_client().psubscriptions()
     } else {
         args.into_iter()
@@ -64,20 +63,20 @@ pub async fn punsubscribe(conn: &Connection, args: VecDeque<Bytes>) -> Result<Va
             .collect::<Result<Vec<Pattern>, Error>>()?
     };
 
-    let _ = conn.pubsub_client().punsubscribe(&channels, conn);
+    conn.pubsub_client().punsubscribe(&channels, conn);
 
     Ok(Value::Ignore)
 }
 
 /// Unsubscribes the client from the given channels, or from all of them if none is given.
 pub async fn unsubscribe(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
-    let channels = if args.len() == 0 {
+    let channels = if args.is_empty() {
         conn.pubsub_client().subscriptions()
     } else {
         args.into_iter().collect()
     };
 
-    let _ = conn.pubsub_client().unsubscribe(&channels, conn);
+    conn.pubsub_client().unsubscribe(&channels, conn);
     Ok(Value::Ignore)
 }
 

+ 4 - 10
src/cmd/server.rs

@@ -1,22 +1,16 @@
 //! # Server command handlers
-use crate::{
-    check_arg, connection::Connection, error::Error, try_get_arg, value::bytes_to_number,
-    value::Value,
-};
+use crate::{connection::Connection, error::Error, value::Value};
 use bytes::Bytes;
 use git_version::git_version;
 use std::{
     collections::VecDeque,
-    convert::TryInto,
-    ops::Neg,
     time::{SystemTime, UNIX_EPOCH},
 };
-use tokio::time::Duration;
 
 /// Returns Array reply of details about all Redis commands.
 pub async fn command(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
     let dispatcher = conn.all_connections().get_dispatcher();
-    if args.len() == 0 {
+    if args.is_empty() {
         return Ok(Value::Array(
             dispatcher
                 .get_all_commands()
@@ -47,7 +41,7 @@ pub async fn command(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Val
             Ok(Value::Array(result))
         }
         "getkeys" => {
-            if args.len() == 0 {
+            if args.is_empty() {
                 return Err(Error::SubCommandNotFound(
                     String::from_utf8_lossy(&sub_command).into(),
                     "command".into(),
@@ -59,7 +53,7 @@ pub async fn command(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Val
                 command
                     .get_keys(&args, false)
                     .into_iter()
-                    .map(|p| Value::Blob(p))
+                    .map(Value::Blob)
                     .collect(),
             ))
         }

+ 8 - 8
src/cmd/set.rs

@@ -60,7 +60,7 @@ where
 
             Ok(all_entries
                 .iter()
-                .map(|entry| Value::new(&entry))
+                .map(|entry| Value::new(entry))
                 .collect::<Vec<Value>>()
                 .into())
         }
@@ -86,7 +86,7 @@ where
 
             Ok(all_entries
                 .iter()
-                .map(|entry| Value::new(&entry))
+                .map(|entry| Value::new(entry))
                 .collect::<Vec<Value>>()
                 .into())
         }
@@ -168,7 +168,7 @@ pub async fn sdiff(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Er
 pub async fn sdiffstore(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
     let key_name = args.pop_front().ok_or(Error::Syntax)?;
     if let Value::Array(values) = sdiff(conn, args).await? {
-        if values.len() > 0 {
+        if !values.is_empty() {
             Ok(store_key_values(conn, key_name, values).into())
         } else {
             let _ = conn.db().del(&[key_name]);
@@ -221,7 +221,7 @@ pub async fn sintercard(conn: &Connection, args: VecDeque<Bytes>) -> Result<Valu
 pub async fn sinterstore(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
     let key_name = args.pop_front().ok_or(Error::Syntax)?;
     if let Value::Array(values) = sinter(conn, args).await? {
-        if values.len() > 0 {
+        if !values.is_empty() {
             Ok(store_key_values(conn, key_name, values).into())
         } else {
             let _ = conn.db().del(&[key_name]);
@@ -427,12 +427,12 @@ pub async fn srandmember(conn: &Connection, args: VecDeque<Bytes>) -> Result<Val
                     let len: usize = min(items.len(), len as usize);
                     Ok(items[0..len]
                         .iter()
-                        .map(|item| Value::new(&item.0))
+                        .map(|item| Value::new(item.0))
                         .collect::<Vec<Value>>()
                         .into())
                 } else {
                     // duplicated results are allowed and the requested number must be returned
-                    let len = (len * -1) as usize;
+                    let len = -len as usize;
                     let total = items.len() - 1;
                     let mut i = 0;
                     let items = (0..len)
@@ -444,7 +444,7 @@ pub async fn srandmember(conn: &Connection, args: VecDeque<Bytes>) -> Result<Val
                         .collect::<Vec<(&Bytes, i128)>>();
                     Ok(items
                         .iter()
-                        .map(|item| Value::new(&item.0))
+                        .map(|item| Value::new(item.0))
                         .collect::<Vec<Value>>()
                         .into())
                 }
@@ -505,7 +505,7 @@ pub async fn sunion(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, E
 pub async fn sunionstore(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
     let key_name = args.pop_front().ok_or(Error::Syntax)?;
     if let Value::Array(values) = sunion(conn, args).await? {
-        if values.len() > 0 {
+        if !values.is_empty() {
             Ok(store_key_values(conn, key_name, values).into())
         } else {
             let _ = conn.db().del(&[key_name]);

+ 3 - 6
src/cmd/string.rs

@@ -1,22 +1,19 @@
 //! # String command handlers
-use super::now;
+
 use crate::{
     check_arg,
     connection::Connection,
     db::utils::Override,
     error::Error,
-    try_get_arg,
-    value::{bytes_to_int, bytes_to_number, expiration::Expiration, float::Float, Value},
+    value::{bytes_to_number, expiration::Expiration, float::Float, Value},
 };
 use bytes::Bytes;
 use std::{
     cmp::min,
     collections::VecDeque,
     convert::TryInto,
-    f32::consts::E,
     ops::{Bound, Neg},
 };
-use tokio::time::Duration;
 
 /// If key already exists and is a string, this command appends the value at the
 /// end of the string. If key does not exist it is created and set as an empty
@@ -753,7 +750,7 @@ mod test {
         );
         assert_eq!(
             Ok(Value::BlobRw(
-                ("\0\0xxx\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0xxx\0\0\0\0\0\0\0xxx".into())
+                "\0\0xxx\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0xxx\0\0\0\0\0\0\0xxx".into()
             )),
             run_command(&c, &["get", "foo"]).await,
         );

+ 1 - 1
src/cmd/transaction.rs

@@ -31,7 +31,7 @@ pub async fn exec(conn: &Connection, _: VecDeque<Bytes>) -> Result<Value, Error>
     match conn.status() {
         ConnectionStatus::Multi => Ok(()),
         ConnectionStatus::FailedTx => {
-            conn.stop_transaction();
+            let _ = conn.stop_transaction();
             Err(Error::TxAborted)
         }
         _ => Err(Error::NotInTx),

+ 1 - 1
src/config.rs

@@ -120,7 +120,7 @@ activerehashing yes
 unixsocket /Users/crodas/projects/rust/microredis/tests/tmp/server.43948.1/socket
 ";
 
-        let config: Config = from_str(&config).unwrap();
+        let config: Config = from_str(config).unwrap();
         assert!(!config.daemonize);
         assert_eq!(21111, config.port);
         assert_eq!(vec!["127.0.0.1"], config.bind);

+ 5 - 10
src/connection/mod.rs

@@ -14,7 +14,7 @@ pub mod pubsub_connection;
 pub mod pubsub_server;
 
 /// Possible status of connections
-#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
 pub enum ConnectionStatus {
     /// The connection is in a MULTI stage and commands are being queued
     Multi,
@@ -25,15 +25,10 @@ pub enum ConnectionStatus {
     /// The connection is in pub-sub only mode
     Pubsub,
     /// The connection is a normal conection
+    #[default]
     Normal,
 }
 
-impl Default for ConnectionStatus {
-    fn default() -> Self {
-        ConnectionStatus::Normal
-    }
-}
-
 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
 /// Reason while a client was unblocked
 pub enum UnblockReason {
@@ -100,7 +95,7 @@ impl Connection {
     }
 
     /// Creates a clone connection
-    pub fn clone(&self) -> Arc<Connection> {
+    pub fn get_connection(&self) -> Arc<Connection> {
         self.all_connections
             .get_by_conn_id(self.id)
             .expect("Connection must be registered")
@@ -170,7 +165,7 @@ impl Connection {
     pub fn unblock(&self, reason: UnblockReason) -> bool {
         let mut info = self.info.write();
         if info.is_blocked {
-            let notification = info.blocked_notification.as_ref().map(|s| s.clone());
+            let notification = info.blocked_notification.as_ref().cloned();
             info.is_blocked = false;
             info.unblock_reason = Some(reason);
             info.blocked_notification = None;
@@ -178,7 +173,7 @@ impl Connection {
 
             if let Some(s) = notification {
                 // Notify connection about this change
-                s.send(());
+                let _ = s.send(());
             }
 
             true

+ 10 - 5
src/connection/pubsub_server.rs

@@ -2,7 +2,7 @@
 //!
 //! There is one instance of this mod active per server instance.
 use crate::{connection::Connection, error::Error, value::Value};
-use bytes::{Bytes, BytesMut};
+use bytes::Bytes;
 use glob::Pattern;
 use parking_lot::RwLock;
 use std::collections::{HashMap, VecDeque};
@@ -18,6 +18,12 @@ pub struct Pubsub {
     psubscriptions: RwLock<HashMap<Pattern, Subscription>>,
 }
 
+impl Default for Pubsub {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 impl Pubsub {
     /// Creates a new Pubsub instance
     pub fn new() -> Self {
@@ -97,8 +103,8 @@ impl Pubsub {
                 if sender
                     .try_send(Value::Array(vec![
                         "message".into(),
-                        Value::new(&channel),
-                        Value::new(&message),
+                        Value::new(channel),
+                        Value::new(message),
                     ]))
                     .is_ok()
                 {
@@ -163,7 +169,6 @@ impl Pubsub {
     /// Subscribe connection to channels
     pub fn subscribe(&self, channels: VecDeque<Bytes>, conn: &Connection) {
         let mut subscriptions = self.subscriptions.write();
-        let total_psubs = self.psubscriptions.read().len();
 
         channels
             .into_iter()
@@ -213,7 +218,7 @@ impl Pubsub {
                 if notify {
                     conn.append_response(Value::Array(vec![
                         "unsubscribe".into(),
-                        Value::new(&channel),
+                        Value::new(channel),
                         (all_subs.len() + total_psubs).into(),
                     ]));
                 }

+ 1 - 1
src/db/entry.rs

@@ -41,7 +41,7 @@ impl Entry {
     }
 
     pub fn clone(&self) -> Self {
-        Self::new(self.value.clone(), self.expires_at.clone())
+        Self::new(self.value.clone(), self.expires_at)
     }
 
     pub fn get_ttl(&self) -> Option<Instant> {

+ 32 - 34
src/db/mod.rs

@@ -5,18 +5,13 @@
 use self::utils::{far_future, ExpirationOpts, Override};
 use crate::{
     error::Error,
-    value::{
-        bytes_to_number,
-        cursor::Cursor,
-        typ::{Typ, ValueTyp},
-        VDebug, Value,
-    },
+    value::{bytes_to_number, cursor::Cursor, typ::Typ, VDebug, Value},
 };
 use bytes::{BufMut, Bytes, BytesMut};
-use core::num;
+
 use entry::{new_version, Entry};
 use expiration::ExpirationDb;
-use futures::Future;
+
 use glob::Pattern;
 use log::trace;
 use num_traits::CheckedAdd;
@@ -26,7 +21,6 @@ use seahash::hash;
 use std::{
     collections::{HashMap, VecDeque},
     convert::{TryFrom, TryInto},
-    ops::{AddAssign, Deref},
     str::FromStr,
     sync::Arc,
     thread,
@@ -234,7 +228,7 @@ impl Db {
                 Value::new(
                     slot.get(key)
                         .filter(|v| v.is_valid())
-                        .map(|v| hex::encode(&v.value.digest()))
+                        .map(|v| hex::encode(v.value.digest()))
                         .unwrap_or("00000".into())
                         .as_bytes(),
                 )
@@ -255,6 +249,17 @@ impl Db {
         Ok(Value::Ok)
     }
 
+    /// Checks if the database is empty
+    pub fn is_empty(&self) -> bool {
+        for slot in self.slots.iter() {
+            if slot.read().len() > 0 {
+                return false;
+            }
+        }
+
+        true
+    }
+
     /// Returns the number of elements in the database
     pub fn len(&self) -> Result<usize, Error> {
         self.purge();
@@ -285,7 +290,7 @@ impl Db {
 
     // Converts a given number to a correct Value, it should be used with Self::round_numbers()
     fn number_to_value(number: &[u8]) -> Result<Value, Error> {
-        if number.iter().find(|x| **x == b'.').is_some() {
+        if number.iter().any(|x| *x == b'.') {
             Ok(Value::new(number))
         } else {
             Ok(Value::Integer(bytes_to_number(number)?))
@@ -397,11 +402,11 @@ impl Db {
         expires_in: Duration,
         opts: ExpirationOpts,
     ) -> Result<Value, Error> {
-        if (opts.NX && opts.XX) || (opts.NX && opts.GT) || (opts.NX && opts.LT) {
+        if opts.if_none && (opts.replace_only || opts.greater_than || opts.lower_than) {
             return Err(Error::OptsNotCompatible("NX and XX, GT or LT".to_owned()));
         }
 
-        if opts.GT && opts.LT {
+        if opts.greater_than && opts.lower_than {
             return Err(Error::OptsNotCompatible("GT and LT".to_owned()));
         }
 
@@ -415,13 +420,13 @@ impl Db {
             .filter(|x| x.is_valid())
             .map_or(0.into(), |x| {
                 let current_expire = x.get_ttl();
-                if opts.NX && current_expire.is_some() {
+                if opts.if_none && current_expire.is_some() {
                     return 0.into();
                 }
-                if opts.XX && current_expire.is_none() {
+                if opts.replace_only && current_expire.is_none() {
                     return 0.into();
                 }
-                if opts.GT {
+                if opts.greater_than {
                     if let Some(current_expire) = current_expire {
                         if expires_at <= current_expire {
                             return 0.into();
@@ -431,7 +436,7 @@ impl Db {
                     }
                 }
 
-                if opts.LT {
+                if opts.lower_than {
                     if let Some(current_expire) = current_expire {
                         if expires_at >= current_expire {
                             return 0.into();
@@ -488,7 +493,7 @@ impl Db {
                 Ok(bytes.len().into())
             }
             None => {
-                if data.len() == 0 {
+                if data.is_empty() {
                     return Ok(0.into());
                 }
                 let mut bytes = BytesMut::new();
@@ -587,21 +592,19 @@ impl Db {
         let mut candidates = self
             .slots
             .iter()
-            .map(|slot| {
+            .filter_map(|slot| {
                 let slot = slot.read();
                 if slot.is_empty() {
                     None
                 } else {
                     slot.iter()
-                        .skip(rng.gen_range((0..slot.len())))
-                        .next()
-                        .map(|(k, v)| k.clone())
+                        .nth(rng.gen_range(0..slot.len()))
+                        .map(|(k, _v)| k.clone())
                 }
             })
-            .filter_map(|v| v)
             .collect::<Vec<Bytes>>();
         candidates.shuffle(&mut rng);
-        Ok(candidates.get(0).into())
+        Ok(candidates.first().into())
     }
 
     /// Renames a key
@@ -671,7 +674,7 @@ impl Db {
         Ok(self
             .slots
             .iter()
-            .map(|slot| {
+            .flat_map(|slot| {
                 slot.read()
                     .keys()
                     .filter(|key| {
@@ -681,7 +684,6 @@ impl Db {
                     .map(|key| Value::new(key))
                     .collect::<Vec<Value>>()
             })
-            .flatten()
             .collect())
     }
 
@@ -854,7 +856,6 @@ impl Db {
     /// Set a key, value with an optional expiration time
     pub fn append(&self, key: &Bytes, value_to_append: &Bytes) -> Result<Value, Error> {
         let mut slot = self.slots[self.get_slot(key)].write();
-        let mut entry = slot.get_mut(key).filter(|x| x.is_valid());
 
         if let Some(entry) = slot.get_mut(key).filter(|x| x.is_valid()) {
             if let Value::Blob(data) = entry.get() {
@@ -1002,8 +1003,8 @@ impl Db {
         if let Some(expires_at) = expires_at {
             self.expirations.lock().add(&key, expires_at);
         } else {
-            /// Make sure to remove the new key (or replaced) from the
-            /// expiration table (from any possible past value).
+            // Make sure to remove the new key (or replaced) from the
+            // expiration table (from any possible past value).
             self.expirations.lock().remove(&key);
         }
 
@@ -1218,10 +1219,7 @@ mod test {
         assert_eq!(None, db.ttl(&bytes!(b"expired")));
         assert_eq!(None, db.ttl(&bytes!(b"not_existing_key")));
         assert_eq!(Some(None), db.ttl(&bytes!(b"valid")));
-        assert!(match db.ttl(&bytes!(b"expiring")) {
-            Some(Some(_)) => true,
-            _ => false,
-        });
+        assert!(matches!(db.ttl(&bytes!(b"expiring")), Some(Some(_))));
     }
 
     #[test]
@@ -1338,7 +1336,7 @@ mod test {
         let shared1 = shared.clone();
         let shared2 = shared.clone();
         let shared3 = shared.clone();
-        tokio::join!(
+        let _ = tokio::join!(
             tokio::spawn(async move {
                 db1.lock_keys(&["test".into()]);
                 let mut x = shared1.write();

+ 1 - 1
src/db/pool.rs

@@ -34,7 +34,7 @@ impl Databases {
     pub fn get(&self, db: usize) -> Result<Arc<Db>, Error> {
         self.databases
             .get(db)
-            .map(|db| db.clone())
+            .cloned()
             .ok_or(Error::NotSuchDatabase)
     }
 }

+ 16 - 16
src/db/utils.rs

@@ -38,13 +38,13 @@ impl Default for Override {
 #[derive(PartialEq, Debug, Clone, Copy, Default)]
 pub struct ExpirationOpts {
     /// Set expiry only when the key has no expiry
-    pub NX: bool,
+    pub if_none: bool,
     /// Set expiry only when the key has an existing expiry
-    pub XX: bool,
+    pub replace_only: bool,
     /// Set expiry only when the new expiry is greater than current one
-    pub GT: bool,
+    pub greater_than: bool,
     /// Set expiry only when the new expiry is less than current one
-    pub LT: bool,
+    pub lower_than: bool,
 }
 
 impl TryFrom<Vec<Bytes>> for ExpirationOpts {
@@ -62,10 +62,10 @@ impl TryFrom<&[Bytes]> for ExpirationOpts {
         let mut expiration_opts = Self::default();
         for arg in args.iter() {
             match String::from_utf8_lossy(arg).to_uppercase().as_str() {
-                "NX" => expiration_opts.NX = true,
-                "XX" => expiration_opts.XX = true,
-                "GT" => expiration_opts.GT = true,
-                "LT" => expiration_opts.LT = true,
+                "NX" => expiration_opts.if_none = true,
+                "XX" => expiration_opts.replace_only = true,
+                "GT" => expiration_opts.greater_than = true,
+                "LT" => expiration_opts.lower_than = true,
                 invalid => return Err(Error::UnsupportedOption(invalid.to_owned())),
             }
         }
@@ -87,10 +87,10 @@ mod test {
             Bytes::copy_from_slice(b"lT"),
         ];
         let x: ExpirationOpts = opts.as_slice().try_into().unwrap();
-        assert!(x.NX);
-        assert!(x.XX);
-        assert!(x.GT);
-        assert!(x.LT);
+        assert!(x.if_none);
+        assert!(x.replace_only);
+        assert!(x.greater_than);
+        assert!(x.lower_than);
     }
 
     #[test]
@@ -98,10 +98,10 @@ mod test {
         let opts = vec![Bytes::copy_from_slice(b"nx")];
         let x: ExpirationOpts = opts.as_slice().try_into().unwrap();
 
-        assert!(x.NX);
-        assert!(!x.XX);
-        assert!(!x.GT);
-        assert!(!x.LT);
+        assert!(x.if_none);
+        assert!(!x.replace_only);
+        assert!(!x.greater_than);
+        assert!(!x.lower_than);
     }
 
     #[test]

+ 7 - 11
src/dispatcher/command.rs

@@ -5,12 +5,7 @@
 //!
 //! Each command is defined with the dispatcher macro, which generates efficient and developer
 //! friendly code.
-use crate::{
-    connection::{Connection, ConnectionStatus},
-    dispatcher,
-    error::Error,
-    value::Value,
-};
+use crate::value::Value;
 use bytes::Bytes;
 use metered::{ErrorCount, HitCount, InFlight, ResponseTime, Throughput};
 use std::{collections::VecDeque, convert::TryInto};
@@ -100,6 +95,7 @@ pub struct Metrics {
 }
 
 impl Command {
+    #[allow(clippy::too_many_arguments)]
     /// Creates a new comamnd
     pub fn new(
         name: &'static str,
@@ -170,10 +166,10 @@ impl Command {
 
     /// Checks if a given number of args is expected by this command
     pub fn check_number_args(&self, n: usize) -> bool {
-        if (self.min_args >= 0) {
-            n == (self.min_args as i32).try_into().unwrap_or(0)
+        if self.min_args >= 0 {
+            n == self.min_args.try_into().unwrap_or(0)
         } else {
-            let s: usize = (self.min_args as i32).abs().try_into().unwrap_or(0);
+            let s: usize = self.min_args.abs().try_into().unwrap_or(0);
             n >= s
         }
     }
@@ -225,11 +221,11 @@ impl Command {
 
     /// Command group
     pub fn group(&self) -> &'static str {
-        &self.group
+        self.group
     }
 
     /// Command name
     pub fn name(&self) -> &'static str {
-        &self.name
+        self.name
     }
 }

+ 1 - 2
src/dispatcher/mod.rs

@@ -14,11 +14,10 @@ use crate::{
 };
 use bytes::Bytes;
 use command::Flag;
-use std::convert::TryInto;
 
 pub mod command;
 
-/// Returns the server time
+// Returns the server time
 dispatcher! {
     set {
         SADD {

+ 1 - 1
src/lib.rs

@@ -2,7 +2,7 @@
 //!
 //! In-memory database compatible with Redis.
 #![deny(missing_docs)]
-#![allow(warnings)]
+#![deny(warnings)]
 
 pub mod cmd;
 pub mod config;

+ 7 - 0
src/macros.rs

@@ -30,6 +30,7 @@ macro_rules! dispatcher {
 
         /// Metrics for all defined commands
         #[derive(serde::Serialize)]
+        #[allow(non_snake_case, non_camel_case_types)]
         pub struct ServiceMetricRegistry<'a> {
             $($(
             $command: &'a command::Metrics,
@@ -47,6 +48,12 @@ macro_rules! dispatcher {
             )+)+
         }
 
+        impl Default for Dispatcher {
+            fn default() -> Self {
+                Self::new()
+            }
+        }
+
         impl Dispatcher {
             /// Creates a new dispatcher.
             pub fn new() -> Self {

+ 7 - 12
src/server.rs

@@ -4,22 +4,22 @@
 //! metrics.
 use crate::{
     config::Config,
-    connection::{connections::Connections, Connection, ConnectionStatus},
+    connection::{connections::Connections, Connection},
     db::{pool::Databases, Db},
     dispatcher::Dispatcher,
     error::Error,
     value::Value,
 };
 use bytes::{Buf, Bytes, BytesMut};
-use futures::{channel::mpsc::Receiver, future, SinkExt};
+use futures::{future, SinkExt};
 use log::{info, trace, warn};
 use redis_zero_protocol_parser::{parse_server, Error as RedisError};
-use std::{collections::VecDeque, io, net::SocketAddr, sync::Arc};
+use std::{collections::VecDeque, io, sync::Arc};
 #[cfg(unix)]
 use tokio::net::UnixListener;
 use tokio::{
     io::{AsyncReadExt, AsyncWriteExt},
-    net::{TcpListener, TcpStream},
+    net::TcpListener,
     time::{sleep, Duration},
 };
 use tokio_stream::StreamExt;
@@ -105,8 +105,6 @@ async fn server_metrics(all_connections: Arc<Connections>) -> Result<(), Error>
         let _ = stream.write_all(response.as_bytes()).await;
         let _ = stream.flush().await;
     }
-
-    Ok(())
 }
 
 /// Spawn the TCP/IP micro-redis server.
@@ -121,7 +119,7 @@ async fn serve_tcp(
     loop {
         match listener.accept().await {
             Ok((socket, addr)) => {
-                let mut transport = Framed::new(socket, RedisParser);
+                let transport = Framed::new(socket, RedisParser);
                 let all_connections = all_connections.clone();
                 let default_db = default_db.clone();
 
@@ -132,8 +130,6 @@ async fn serve_tcp(
             Err(e) => println!("error accepting socket; error = {:?}", e),
         }
     }
-
-    Ok(())
 }
 
 #[cfg(unix)]
@@ -150,7 +146,7 @@ async fn serve_unixsocket(
     loop {
         match listener.accept().await {
             Ok((socket, addr)) => {
-                let mut transport = Framed::new(socket, RedisParser);
+                let transport = Framed::new(socket, RedisParser);
                 let all_connections = all_connections.clone();
                 let default_db = default_db.clone();
 
@@ -169,7 +165,6 @@ async fn serve_unixsocket(
             Err(e) => println!("error accepting socket; error = {:?}", e),
         }
     }
-    Ok(())
 }
 
 #[inline]
@@ -178,7 +173,7 @@ async fn execute_command(
     dispatcher: &Dispatcher,
     args: VecDeque<Bytes>,
 ) -> Option<Value> {
-    match dispatcher.execute(&conn, args).await {
+    match dispatcher.execute(conn, args).await {
         Ok(result) => Some(result),
         Err(Error::EmptyLine) => Some(Value::Ignore),
         Err(Error::Quit) => None,

+ 2 - 6
src/value/cursor.rs

@@ -3,12 +3,7 @@
 use byteorder::{LittleEndian, WriteBytesExt};
 use bytes::Bytes;
 use crc32fast::Hasher as Crc32Hasher;
-use std::{
-    convert::TryFrom,
-    io,
-    num::{IntErrorKind, ParseIntError},
-    str::FromStr,
-};
+use std::{convert::TryFrom, num::ParseIntError, str::FromStr};
 use thiserror::Error;
 
 /// Error
@@ -101,6 +96,7 @@ impl ToString for Cursor {
 mod test {
     use super::*;
 
+    #[test]
     fn serialize_end() {
         let x = Cursor::new(0, 0).unwrap();
         assert_eq!("0", x.to_string());

+ 2 - 2
src/value/expiration.rs

@@ -1,6 +1,6 @@
 //! # Expiration timestamp struct
 
-use super::{bytes_to_int, typ};
+use super::bytes_to_int;
 use crate::{cmd::now, error::Error};
 use std::{convert::TryInto, time::Duration};
 
@@ -48,7 +48,7 @@ impl Expiration {
         };
 
         Ok(Expiration {
-            millis: millis.abs() as u64,
+            millis: millis.unsigned_abs(),
             is_negative: millis.is_negative(),
             command: command.to_string(),
         })

+ 3 - 3
src/value/float.rs

@@ -36,9 +36,9 @@ impl TryFrom<&Value> for Float {
     }
 }
 
-impl Into<Value> for Float {
-    fn into(self) -> Value {
-        Value::Float(self.0)
+impl From<Float> for Value {
+    fn from(val: Float) -> Self {
+        Value::Float(val.0)
     }
 }
 

+ 8 - 12
src/value/mod.rs

@@ -8,7 +8,7 @@ pub mod float;
 pub mod locked;
 pub mod typ;
 
-use crate::{cmd::now, error::Error, value_try_from, value_vec_try_from};
+use crate::{error::Error, value_try_from, value_vec_try_from};
 use bytes::{Bytes, BytesMut};
 use redis_zero_protocol_parser::Value as ParsedValue;
 use sha2::{Digest, Sha256};
@@ -16,7 +16,6 @@ use std::{
     collections::{HashMap, HashSet, VecDeque},
     convert::{TryFrom, TryInto},
     str::FromStr,
-    time::Duration,
 };
 
 /// Redis Value.
@@ -104,10 +103,7 @@ impl Value {
 
     /// Is the current value an error?
     pub fn is_err(&self) -> bool {
-        match self {
-            Self::Err(..) => true,
-            _ => false,
-        }
+        matches!(self, Self::Err(..))
     }
 
     /// Return debug information for the type
@@ -146,14 +142,14 @@ impl From<&Value> for Vec<u8> {
             Value::Float(x) => format!(",{}\r\n", x).into(),
             Value::BlobRw(x) => {
                 let s = format!("${}\r\n", x.len());
-                let mut s: BytesMut = s.as_str().as_bytes().into();
+                let mut s: BytesMut = s.as_bytes().into();
                 s.extend_from_slice(x);
                 s.extend_from_slice(b"\r\n");
                 s.to_vec()
             }
             Value::Blob(x) => {
                 let s = format!("${}\r\n", x.len());
-                let mut s: BytesMut = s.as_str().as_bytes().into();
+                let mut s: BytesMut = s.as_bytes().into();
                 s.extend_from_slice(x);
                 s.extend_from_slice(b"\r\n");
                 s.to_vec()
@@ -181,7 +177,7 @@ impl TryFrom<&Value> for i64 {
         match val {
             Value::BigInteger(x) => (*x).try_into().map_err(|_| Error::NotANumber),
             Value::Integer(x) => Ok(*x),
-            Value::Blob(x) => bytes_to_number::<i64>(&x),
+            Value::Blob(x) => bytes_to_number::<i64>(x),
             Value::String(x) => x.parse::<i64>().map_err(|_| Error::NotANumber),
             _ => Err(Error::NotANumber),
         }
@@ -222,7 +218,7 @@ impl<'a> From<&ParsedValue<'a>> for Value {
     fn from(value: &ParsedValue) -> Self {
         match value {
             ParsedValue::String(x) => Self::String((*x).to_string()),
-            ParsedValue::Blob(x) => Self::new(*x),
+            ParsedValue::Blob(x) => Self::new(x),
             ParsedValue::Array(x) => Self::Array(x.iter().map(|x| x.into()).collect()),
             ParsedValue::Boolean(x) => Self::Boolean(*x),
             ParsedValue::BigInteger(x) => Self::BigInteger(*x),
@@ -326,7 +322,7 @@ mod test {
         ($name:ty, $x:expr, $str:expr) => {
             paste! {
                 #[test]
-                fn [<serialize_and_deserialize_ $name>]() {
+                fn [<serialize_and_deserialize $name>]() {
                     let raw_bytes: Vec<u8> = $x.into();
                     let parsed: ParsedValue = redis_zero_protocol_parser::parse(&raw_bytes).unwrap().1;
                     assert_eq!(Value::String($str.to_owned()), (&parsed).into());
@@ -336,7 +332,7 @@ mod test {
         ($name:ty, $x:expr) => {
             paste! {
                 #[test]
-                fn [<serialize_and_deserialize_ $name>]() {
+                fn [<serialize_and_deserialize $name>]() {
                     let raw_bytes: Vec<u8> = $x.into();
                     let parsed: ParsedValue = redis_zero_protocol_parser::parse(&raw_bytes).unwrap().1;
                     assert_eq!($x, (&parsed).into());

+ 2 - 2
src/value/typ.rs

@@ -57,9 +57,9 @@ impl Typ {
 impl FromStr for Typ {
     type Err = strum::ParseError;
     fn from_str(input: &str) -> Result<Self, Self::Err> {
-        if input.chars().next() == Some('!') {
+        if let Some(stripped_input) = input.strip_prefix('!') {
             Ok(Self {
-                typ: ValueTyp::from_str(&input[1..])?,
+                typ: ValueTyp::from_str(stripped_input)?,
                 is_negated: true,
             })
         } else {