diff --git a/ci/runtests.sh b/ci/runtests.sh index 16b0d65..6ddb4d2 100755 --- a/ci/runtests.sh +++ b/ci/runtests.sh @@ -6,7 +6,7 @@ set -e export CARGO_TARGET_DIR=target/ci rustup target add thumbv7em-none-eabihf -rustup component add rustfmt +rustup component add rustfmt clippy export RUSTDOCFLAGS='-D warnings' export RUSTFLAGS="-D warnings" @@ -15,6 +15,7 @@ cargo fmt -- --check # Check everything first cargo check --all-targets --locked +cargo clippy --all-targets # stable, std cargo build --release --features mctp-estack/log diff --git a/mctp-estack/src/serial.rs b/mctp-estack/src/serial.rs index dc59e08..f3cf31a 100644 --- a/mctp-estack/src/serial.rs +++ b/mctp-estack/src/serial.rs @@ -253,7 +253,6 @@ impl Default for MctpSerialHandler { #[cfg(test)] mod tests { - use crate::serial::*; use crate::*; use embedded_io_adapters::futures_03::FromFutures; @@ -269,7 +268,7 @@ mod tests { async fn do_roundtrip(payload: &[u8]) { let mut esc = vec![]; let mut s = FromFutures::new(&mut esc); - MctpSerialHandler::frame_to_serial(&payload, &mut s) + MctpSerialHandler::frame_to_serial(payload, &mut s) .await .unwrap(); debug!("{:02x?}", payload); diff --git a/mctp-linux/examples/mctp-req.rs b/mctp-linux/examples/mctp-req.rs index 6bc9b7d..824b1cf 100644 --- a/mctp-linux/examples/mctp-req.rs +++ b/mctp-linux/examples/mctp-req.rs @@ -27,7 +27,7 @@ fn main() -> std::io::Result<()> { let mut rx_buf = vec![0u8; 16]; let (typ, ic, rx_buf) = ep.recv(&mut rx_buf)?; - println!("response type {}, ic {:?}: {:x?}", typ, ic, rx_buf); + println!("response type {typ}, ic {ic:?}: {rx_buf:x?}"); Ok(()) } diff --git a/mctp/src/lib.rs b/mctp/src/lib.rs index d17693b..829d15a 100644 --- a/mctp/src/lib.rs +++ b/mctp/src/lib.rs @@ -196,8 +196,8 @@ impl core::fmt::Display for Error { fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result { match self { #[cfg(feature = "std")] - Self::Io(i) => write!(fmt, "MCTP IO Error: {}", i), - _ => write!(fmt, "MCTP Error: {:?}", self), + Self::Io(i) => write!(fmt, "MCTP IO Error: {i}"), + _ => write!(fmt, "MCTP Error: {self:?}"), } } } diff --git a/pldm-fw-cli/src/bin/pldm-fw.rs b/pldm-fw-cli/src/bin/pldm-fw.rs index f9ac5e5..3671e78 100644 --- a/pldm-fw-cli/src/bin/pldm-fw.rs +++ b/pldm-fw-cli/src/bin/pldm-fw.rs @@ -26,7 +26,7 @@ fn print_device_info( dev: &pldm_fw::DeviceIdentifiers, fwp: &pldm_fw::FirmwareParameters, ) { - println!("Device: {}", dev); + println!("Device: {dev}"); println!("Firmware Parameters:"); println!(" Active version: {}", fwp.active); println!(" Pending version: {}", fwp.pending); @@ -47,7 +47,7 @@ fn print_device_info( } ); for (idx, comp) in fwp.components.iter().enumerate() { - println!(" [{}]", idx); + println!(" [{idx}]"); println!(" Classification: {:?}", comp.classification); println!(" Index: {:?}", comp.classificationindex); println!(" Identifier: 0x{:04x}", comp.identifier); @@ -79,7 +79,7 @@ fn print_package(pkg: &pldm_fw::pkg::Package) { } println!(" Components:"); for (idx, cmp) in pkg.components.iter().enumerate() { - println!(" {:2}:", idx); + println!(" {idx:2}:"); println!(" classification: {:?}", cmp.classification); println!(" identifier: 0x{:04x}", cmp.identifier); println!(" version: {}", cmp.version); @@ -91,7 +91,7 @@ fn print_package(pkg: &pldm_fw::pkg::Package) { } fn print_device(dev: &pldm_fw::DeviceIdentifiers) { - println!("Device: {}", dev); + println!("Device: {dev}"); } fn print_update(update: &pldm_fw::ua::Update) { @@ -119,9 +119,9 @@ fn extract_component( let fname = format!("component-{}.{:04x}.bin", idx, comp.identifier); let mut f = std::fs::File::create(&fname) - .with_context(|| format!("Can't open output file {}", fname))?; + .with_context(|| format!("Can't open output file {fname}"))?; - println!("extracting component {} to {}", idx, fname); + println!("extracting component {idx} to {fname}"); let mut buf = vec![0u8; comp.file_size]; pkg.read_component(comp, 0, &mut buf)?; @@ -142,15 +142,15 @@ fn confirm_update() -> bool { return false; } - line.trim().to_ascii_lowercase() == "y" + line.trim().eq_ignore_ascii_case("y") } fn open_package(fname: String) -> anyhow::Result { let f = std::fs::File::open(&fname) - .with_context(|| format!("Can't open PLDM package {}", fname))?; + .with_context(|| format!("Can't open PLDM package {fname}"))?; let pkg = pldm_fw::pkg::Package::parse(f) - .with_context(|| format!("Can't parse PLDM package {}", fname))?; + .with_context(|| format!("Can't parse PLDM package {fname}"))?; Ok(pkg) } @@ -263,7 +263,7 @@ fn duration_str(d: &chrono::Duration) -> String { s -= h * 3600; let m = s / 60; s -= m * 60; - format!("{:02}:{:02}:{:02}", h, m, s) + format!("{h:02}:{m:02}:{s:02}") } } @@ -278,7 +278,7 @@ fn bps_str(bps: f32) -> String { } else if bps > (B_PER_kB * threshold) { format!("{:.2} kB/sec", bps / B_PER_kB) } else { - format!("{:.0} B/sec", bps) + format!("{bps:.0} B/sec") } } @@ -375,7 +375,7 @@ fn main() -> anyhow::Result<()> { for idx in e.components { let res = extract_component(&pkg, idx); if let Err(e) = res { - println!("Error extracting: {:?}", e); + println!("Error extracting: {e:?}"); } } } diff --git a/pldm-fw/src/fd.rs b/pldm-fw/src/fd.rs index c10a611..bba10ab 100644 --- a/pldm-fw/src/fd.rs +++ b/pldm-fw/src/fd.rs @@ -126,6 +126,7 @@ impl Responder { /// Update mode idle timeout, 120 seconds pub const FD_T1_TIMEOUT: u64 = 120_000; + #[allow(clippy::new_without_default)] pub fn new() -> Self { Self { ua_eid: None, @@ -155,7 +156,7 @@ impl Responder { let Some(cmd) = Cmd::from_u8(req.cmd) else { self.reply_error( - &req, + req, &mut comm, CCode::ERROR_UNSUPPORTED_PLDM_CMD as u8, ); @@ -176,7 +177,7 @@ impl Responder { _ => { if self.ua_eid != Some(eid) { debug!("Ignoring {cmd:?} from mismatching EID {eid}, expected {:?}", self.ua_eid); - self.reply_error(&req, &mut comm, + self.reply_error(req, &mut comm, CCode::ERROR_NOT_READY as u8, ); } @@ -193,25 +194,25 @@ impl Responder { // Handlers will return Ok if they have replied let r = match cmd { - Cmd::QueryDeviceIdentifiers => self.cmd_qdi(&req, &mut comm, d), - Cmd::GetFirmwareParameters => self.cmd_fwparams(&req, &mut comm, d), - Cmd::RequestUpdate => self.cmd_update(&req, eid, &mut comm, d), + Cmd::QueryDeviceIdentifiers => self.cmd_qdi(req, &mut comm, d), + Cmd::GetFirmwareParameters => self.cmd_fwparams(req, &mut comm, d), + Cmd::RequestUpdate => self.cmd_update(req, eid, &mut comm, d), Cmd::PassComponentTable => { - self.cmd_pass_components(&req, &mut comm, d) + self.cmd_pass_components(req, &mut comm, d) } Cmd::UpdateComponent => { - return self.cmd_update_component(&req, comm, d) + return self.cmd_update_component(req, comm, d) } - Cmd::ActivateFirmware => self.cmd_activate(&req, &mut comm, d), - Cmd::CancelUpdate => self.cmd_cancel_update(&req, &mut comm, d), + Cmd::ActivateFirmware => self.cmd_activate(req, &mut comm, d), + Cmd::CancelUpdate => self.cmd_cancel_update(req, &mut comm, d), Cmd::CancelUpdateComponent => { - self.cmd_cancel_update_component(&req, &mut comm, d) + self.cmd_cancel_update_component(req, &mut comm, d) } - Cmd::GetStatus => self.cmd_get_status(&req, &mut comm, d), + Cmd::GetStatus => self.cmd_get_status(req, &mut comm, d), _ => { trace!("unhandled command {cmd:?}"); self.reply_error( - &req, + req, &mut comm, CCode::ERROR_UNSUPPORTED_PLDM_CMD as u8, ); @@ -221,7 +222,7 @@ impl Responder { if let Err(e) = &r { debug!("Error handling {cmd:?}: {e:?}"); - self.reply_error(&req, &mut comm, CCode::ERROR as u8); + self.reply_error(req, &mut comm, CCode::ERROR as u8); } Ok(()) } @@ -434,7 +435,7 @@ impl Responder { if found { dev.update_component(update, up) } else { - return ComponentResponseCode::NotSupported as u8; + ComponentResponseCode::NotSupported as u8 } } @@ -491,7 +492,7 @@ impl Responder { // Special case for zero size component. It will immediately send TransferComplete // instead of RequestFirmwareData. let transfer_result = - (details.size == 0).then(|| TransferResult::Success); + (details.size == 0).then_some(TransferResult::Success); let req_comm = comm.req_channel()?; @@ -589,7 +590,9 @@ impl Responder { resp.cc = CCode::SUCCESS as u8; pldm_tx_resp(comm, &resp)?; - details.map(|d| dev.cancel_component(d)); + if let Some(details) = details { + dev.cancel_component(details); + } self.set_idle(PldmIdleReason::Cancel); Ok(()) @@ -629,7 +632,7 @@ impl Responder { resp.cc = CCode::SUCCESS as u8; pldm_tx_resp(comm, &resp)?; - dev.cancel_component(&details); + dev.cancel_component(details); self.set_state(State::ReadyXfer); Ok(()) @@ -1194,7 +1197,7 @@ pub trait Device { /// or a ComponentResponseCode otherwise (see PLDM FW specification). /// When `update == false` a response may indicate conditional success, /// such as requiring update flags to be set. - + // // fd shouldn't call this directly, instead use check_update_component() // which checks that comp exists in the component list. fn update_component(&mut self, update: bool, comp: &UpdateComponent) -> u8; diff --git a/pldm-fw/src/lib.rs b/pldm-fw/src/lib.rs index 5b482c8..2907411 100644 --- a/pldm-fw/src/lib.rs +++ b/pldm-fw/src/lib.rs @@ -152,15 +152,15 @@ impl Cmd { } pub const fn is_fd(&self) -> bool { - match self { + matches!( + self, Self::GetPackageData - | Self::RequestFirmwareData - | Self::TransferComplete - | Self::VerifyComplete - | Self::ApplyComplete - | Self::GetMetaData => true, - _ => false, - } + | Self::RequestFirmwareData + | Self::TransferComplete + | Self::VerifyComplete + | Self::ApplyComplete + | Self::GetMetaData + ) } } @@ -360,15 +360,11 @@ impl fmt::Display for DescriptorString { let trim_chars = ['\0', ' ']; match self { Self::String(s) => { - write!( - f, - "{}", - s.trim_end_matches(&trim_chars).escape_default() - ) + write!(f, "{}", s.trim_end_matches(trim_chars).escape_default()) } Self::Bytes(bs) => { for b in bs.iter() { - write!(f, "{:02x}", b)?; + write!(f, "{b:02x}")?; } Ok(()) } @@ -426,7 +422,7 @@ impl DescriptorString { } pub fn new_str(s: &str) -> Option { - if s.as_bytes().len() > 0xff { + if s.len() > 0xff { return None; } Some(Self::String(s.to_string())) @@ -634,20 +630,20 @@ impl Descriptor { impl fmt::Display for Descriptor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::PciVid(id) => write!(f, "pci-vendor:{:04x}", id), - Self::Iana(id) => write!(f, "iana:{:08x}", id), - Self::Uuid(id) => write!(f, "uuid:{}", id), - Self::PciDid(id) => write!(f, "pci-device:{:04x}", id), - Self::PciSubVid(id) => write!(f, "pci-subsys-vendor:{:04x}", id), - Self::PciSubDid(id) => write!(f, "pci-subsys-device:{:04x}", id), + Self::PciVid(id) => write!(f, "pci-vendor:{id:04x}"), + Self::Iana(id) => write!(f, "iana:{id:08x}"), + Self::Uuid(id) => write!(f, "uuid:{id}"), + Self::PciDid(id) => write!(f, "pci-device:{id:04x}"), + Self::PciSubVid(id) => write!(f, "pci-subsys-vendor:{id:04x}"), + Self::PciSubDid(id) => write!(f, "pci-subsys-device:{id:04x}"), Self::Vendor { title, data } => { match title { - Some(t) => write!(f, "vendor:{}", t)?, + Some(t) => write!(f, "vendor:{t}")?, None => write!(f, "vendor:")?, } write!(f, "[")?; for b in data { - write!(f, "{:02x}", b)?; + write!(f, "{b:02x}")?; } write!(f, "]")?; Ok(()) @@ -774,7 +770,7 @@ impl fmt::Display for ComponentVersion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.version)?; if let Some(d) = self.date { - write!(f, " ({:?})", d)?; + write!(f, " ({d:?})")?; } if self.stamp != 0 { write!(f, " [{:08x}]", self.stamp)?; @@ -1079,9 +1075,7 @@ impl UpdateComponent { comparisonstamp, version, ), - ) = tuple((le_u16, le_u16, le_u8, le_u32, parse_string_adjacent))( - &buf, - )?; + ) = tuple((le_u16, le_u16, le_u8, le_u32, parse_string_adjacent))(buf)?; let s = Self { classification: classification.into(), @@ -1114,7 +1108,7 @@ impl UpdateComponent { le_u32, le_u32, parse_string_adjacent, - ))(&buf)?; + ))(buf)?; let s = Self { classification: classification.into(), diff --git a/pldm-fw/src/pkg.rs b/pldm-fw/src/pkg.rs index 6b36c64..ca27a25 100644 --- a/pldm-fw/src/pkg.rs +++ b/pldm-fw/src/pkg.rs @@ -56,7 +56,7 @@ impl<'a> ComponentBitmap { pub fn parse( component_bits: u16, ) -> impl FnMut(&'a [u8]) -> VResult<&'a [u8], Self> { - let bytes = (component_bits + 7) / 8; + let bytes = component_bits.div_ceil(8); map(take(bytes), move |b: &[u8]| ComponentBitmap { n_bits: component_bits as usize, bits: b.to_vec(), @@ -248,8 +248,7 @@ impl Package { } _ => { return Err(PldmPackageError::new_format(&format!( - "unknown package UUID {}", - identifier + "unknown package UUID {identifier}" ))) } }; diff --git a/pldm-fw/src/ua.rs b/pldm-fw/src/ua.rs index 6d6d485..88897ab 100644 --- a/pldm-fw/src/ua.rs +++ b/pldm-fw/src/ua.rs @@ -266,8 +266,7 @@ pub fn pass_component_table( } x => { return Err(PldmUpdateError::new_proto(format!( - "unknown PCT response {:02x}", - x + "unknown PCT response {x:02x}" ))) } } @@ -390,7 +389,7 @@ where let rate = elapsed / sz_done as i32; // time per byte /* blocks may be repeated */ - let sz_left = if sz_done <= sz { sz - sz_done } else { 0 }; + let sz_left = sz.saturating_sub(sz_done); remaining = rate * sz_left as i32; // OK unwrap, overflows after 200k years diff --git a/pldm/src/lib.rs b/pldm/src/lib.rs index 9e3fd8a..3bf1acc 100644 --- a/pldm/src/lib.rs +++ b/pldm/src/lib.rs @@ -432,9 +432,9 @@ pub fn pldm_xfer_buf<'buf>( /// Responder implementations will typically want to respond via /// [`pldm_tx_resp`]. #[cfg(feature = "alloc")] -pub fn pldm_rx_req<'lis, L>( - listener: &'lis mut L, -) -> Result<(PldmRequest<'static>, L::RespChannel<'lis>)> +pub fn pldm_rx_req( + listener: &mut L, +) -> Result<(PldmRequest<'static>, L::RespChannel<'_>)> where L: mctp::Listener, { diff --git a/standalone/examples/req.rs b/standalone/examples/req.rs index cd49b76..bda29ec 100644 --- a/standalone/examples/req.rs +++ b/standalone/examples/req.rs @@ -106,11 +106,9 @@ fn req(ch: &mut impl ReqChannel, payload: &[u8], fatal: bool) -> Result<()> { info!("Reply {rep:02x?}"); - if fatal { - if rep != payload || typ != rep_typ { - info!("rep_typ 0x{rep_typ:x?}"); - bail!("Response mismatch)") - } + if fatal && (rep != payload || typ != rep_typ) { + info!("rep_typ 0x{rep_typ:x?}"); + bail!("Response mismatch)") } assert!(rep == payload); Ok(())