# Rust and Alloy-RS Learning Rust and Alloy-RS ## Checksum an Address ### Before ```rust use std::str::FromStr; use alloy_primitives::{Address, U256}; pub fn checksum(address: &str) -> String { match Address::from_str(address) { Ok(addr) => addr.to_checksum(None), Err(_) => { tracing::error!("Invalid address: {}", address); address.to_string() } } } ``` ### After ```rust use std::str::FromStr; use alloy_primitives::{Address, U256}; pub fn checksum(address: &str) -> String { Address::from_str(address) .map(|addr| addr.to_checksum(None)) .unwrap_or_else(|_| { tracing::error!("Invalid address: {}", address); address.to_string() }) } ``` ### Diff ```diff ------ checksum.rs ++++++ checksum.rs @|-1,14 +1,13 ============================================================ |use std::str::FromStr; | |use alloy_primitives::{Address, U256}; | | |pub fn checksum(address: &str) -> String { -| match Address::from_str(address) { -| Ok(addr) => addr.to_checksum(None), -| Err(_) => { +| Address::from_str(address) +| .map(|addr| addr.to_checksum(None)) +| .unwrap_or_else(|_| { | tracing::error!("Invalid address: {}", address); | address.to_string() -| } -| } +| }) |} ``` ## Hash to Name ### Before ```rust pub fn hash_to_name(hash: &str) -> String { if !hash.starts_with("0x0000") { return hash[1..6].to_lowercase(); } let len = hash.len(); let trimmed = hash.trim_start_matches("0x").trim_start_matches('0'); let trimmed = if trimmed.len() < 4 { &hash[len - 4..] } else { trimmed }; format!("x{}", &trimmed[..4].to_lowercase()) } ``` ### After ```rust pub fn hash_to_name(hash: &str) -> String { if !hash.starts_with("0x0000") { return hash[1..6].to_lowercase(); } let trimmed = hash.trim_start_matches("0x").trim_start_matches('0'); let slice = if trimmed.len() < 4 { &hash[hash.len().saturating_sub(4)..] } else { &trimmed[..4] }; format!("x{}", slice.to_lowercase()) } ```