Przeglądaj źródła

Fixed clippy issues

Cesar Rodas 7 miesięcy temu
rodzic
commit
6a6b54d1df

+ 1 - 1
src/main.rs

@@ -59,7 +59,7 @@ async fn main() -> std::io::Result<()> {
         .route("/tx", post(tx::handler))
         .route("/:id", post(update::handler))
         .route("/:id", get(get::handler))
-        .with_state(Context { ledger: ledger });
+        .with_state(Context { ledger });
 
     let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
     let listener = tokio::net::TcpListener::bind(addr).await.unwrap();

+ 1 - 1
src/subscribe.rs

@@ -46,7 +46,7 @@ impl Stream for SubscriberStream {
                 // Send a heartbeat message
                 self.ping += 1;
                 let message = format!("{}\"ping\":{}{}\n", "{", self.ping, "}");
-                let heartbeat_bytes = Bytes::copy_from_slice(&message.as_bytes());
+                let heartbeat_bytes = Bytes::copy_from_slice(message.as_bytes());
                 return Poll::Ready(Some(Ok(heartbeat_bytes)));
             }
             Poll::Pending => {}

+ 6 - 3
utxo/src/amount.rs

@@ -1,3 +1,5 @@
+use std::fmt::Display;
+
 use crate::Asset;
 use serde::{de, ser::SerializeStruct, Deserialize, Serialize, Serializer};
 
@@ -127,9 +129,10 @@ impl Amount {
     }
 }
 
-impl ToString for Amount {
-    fn to_string(&self) -> String {
-        self.try_into().unwrap()
+impl Display for Amount {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        let s: String = self.try_into().unwrap_or_default();
+        write!(f, "{}", s)
     }
 }
 

+ 5 - 5
utxo/src/id/binary.rs

@@ -78,7 +78,7 @@ macro_rules! BinaryId {
                 let (hrp, bytes) = bech32::decode(&value)?;
                 let hrp = hrp.to_string();
                 if hrp != $suffix {
-                    return Err(crate::id::Error::InvalidPrefix(
+                    return Err($crate::id::Error::InvalidPrefix(
                         stringify!($id).to_owned(),
                         $suffix.to_owned(),
                         hrp,
@@ -90,11 +90,11 @@ macro_rules! BinaryId {
         }
 
         impl TryFrom<&[u8]> for $id {
-            type Error = crate::id::Error;
+            type Error = $crate::id::Error;
 
             fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
                 if value.len() != 32 {
-                    return Err(crate::id::Error::InvalidLength(
+                    return Err($crate::id::Error::InvalidLength(
                         stringify!($id).to_owned(),
                         value.len(),
                         32,
@@ -107,11 +107,11 @@ macro_rules! BinaryId {
         }
 
         impl TryFrom<Vec<u8>> for $id {
-            type Error = crate::id::Error;
+            type Error = $crate::id::Error;
 
             fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
                 if value.len() != 32 {
-                    return Err(crate::id::Error::InvalidLength(
+                    return Err($crate::id::Error::InvalidLength(
                         stringify!($id).to_owned(),
                         value.len(),
                         32,

+ 8 - 4
utxo/src/id/payment.rs

@@ -1,6 +1,10 @@
 use crate::{id::Error, TxId};
 use serde::{de, Serialize, Serializer};
-use std::{fmt, ops::Deref, str::FromStr};
+use std::{
+    fmt::{self, Display},
+    ops::Deref,
+    str::FromStr,
+};
 
 #[derive(
     Clone,
@@ -68,9 +72,9 @@ impl Serialize for PaymentId {
     }
 }
 
-impl ToString for PaymentId {
-    fn to_string(&self) -> String {
-        format!("{}:{}", self.transaction, self.position)
+impl Display for PaymentId {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "{}:{}", self.transaction, self.position)
     }
 }
 

+ 22 - 9
utxo/src/storage/mod.rs

@@ -1,4 +1,6 @@
 //! Storage layer trait
+use std::fmt::{self, Display};
+
 use crate::{
     amount::AmountCents, payment::PaymentTo, transaction::Type, AccountId, Amount, Asset, BaseTx,
     Filter, PaymentFrom, PaymentId, ReplayProtection, RevId, Revision, Tag, Transaction, TxId,
@@ -38,12 +40,16 @@ pub enum AccountTransactionType {
     Receives,
 }
 
-impl ToString for AccountTransactionType {
-    fn to_string(&self) -> String {
-        match self {
-            AccountTransactionType::Spends => "spends".to_string(),
-            AccountTransactionType::Receives => "receives".to_string(),
-        }
+impl Display for AccountTransactionType {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(
+            f,
+            "{}",
+            match self {
+                AccountTransactionType::Spends => "spends".to_string(),
+                AccountTransactionType::Receives => "receives".to_string(),
+            }
+        )
     }
 }
 
@@ -1050,7 +1056,9 @@ pub mod test {
         .into_iter()
         .enumerate()
         {
-            let transaction_id: TxId = vec![i as u8; 32].try_into().expect("valid tx id");
+            let transaction_id: TxId = vec![u8::try_from(i).expect("valid index"); 32]
+                .try_into()
+                .expect("valid tx id");
 
             writer
                 .create_payments(
@@ -1098,7 +1106,9 @@ pub mod test {
             .into_iter()
             .enumerate()
         {
-            let transaction_id: TxId = vec![i as u8; 32].try_into().expect("valid tx id");
+            let transaction_id: TxId = vec![u8::try_from(i).expect("valid index"); 32]
+                .try_into()
+                .expect("valid tx id");
 
             writer
                 .create_payments(
@@ -1134,6 +1144,7 @@ pub mod test {
         }
     }
 
+    #[allow(clippy::arithmetic_side_effects)]
     pub async fn payments_always_include_negative_amounts<T>(storage: T)
     where
         T: Storage + Send + Sync,
@@ -1150,7 +1161,9 @@ pub mod test {
         let mut negative_payments_per_account = HashMap::new();
 
         for (index, account) in accounts.iter().enumerate() {
-            let transaction_id: TxId = vec![index as u8; 32].try_into().expect("valid tx id");
+            let transaction_id: TxId = vec![u8::try_from(index).expect("valid index"); 32]
+                .try_into()
+                .expect("valid tx id");
             let mut negative_payments: usize = 0;
             let recipients = (0..target_inputs_per_account)
                 .map(|_| {

+ 2 - 2
utxo/src/token.rs

@@ -59,7 +59,7 @@ impl TokenManager {
         mac.update(update_token.deref());
 
         let result = mac.finalize().into_bytes();
-        if &result[..] != *token.signature {
+        if result[..] != *token.signature {
             Err(Error::InvalidSignature)
         } else {
             Ok(())
@@ -81,7 +81,7 @@ impl TokenManager {
             // The token cannot be altered once it is commited, as the revision ID is the hash of
             // the entire content, therefore it is safer to only HMAC the
             Token {
-                expires_at: Utc::now() + duration,
+                expires_at: Utc::now().checked_add_signed(duration).unwrap(),
                 owner,
                 signature: signature.into(),
             },

+ 14 - 8
utxo/src/transaction/typ.rs

@@ -1,3 +1,5 @@
+use std::fmt::Display;
+
 use serde::{Deserialize, Serialize};
 
 #[derive(thiserror::Error, Debug)]
@@ -44,14 +46,18 @@ impl Type {
     }
 }
 
-impl ToString for Type {
-    fn to_string(&self) -> String {
-        match self {
-            Type::Transaction => "transaction".to_string(),
-            Type::Deposit => "deposit".to_string(),
-            Type::Withdrawal => "withdrawal".to_string(),
-            Type::Exchange => "exchange".to_string(),
-        }
+impl Display for Type {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(
+            f,
+            "{}",
+            match self {
+                Type::Transaction => "transaction".to_string(),
+                Type::Deposit => "deposit".to_string(),
+                Type::Withdrawal => "withdrawal".to_string(),
+                Type::Exchange => "exchange".to_string(),
+            }
+        )
     }
 }
 

+ 4 - 4
utxo/tests/ledger.rs

@@ -228,12 +228,12 @@ async fn check_balance(world: &mut LedgerWorld, account: String, amount: String,
         .collect::<Vec<_>>();
 
     assert_eq!(1, balances.len(), "{} is found", asset);
-    assert_eq!(balances.get(0), Some(&amount));
+    assert_eq!(balances.first(), Some(&amount));
 }
 
-fn find_features<'a, A: AsRef<Path> + Send + Sync>(
-    dir_path: &'a A,
-) -> BoxFuture<'a, io::Result<Vec<PathBuf>>> {
+fn find_features<A: AsRef<Path> + Send + Sync>(
+    dir_path: &A,
+) -> BoxFuture<'_, io::Result<Vec<PathBuf>>> {
     Box::pin(async move {
         let mut entries = fs::read_dir(dir_path).await?;
         let mut paths = vec![];