From affa70401055e1ddce9964a4d94e5f0bdb7a0abf Mon Sep 17 00:00:00 2001 From: Dan Alec Date: Fri, 16 Oct 2026 17:43:42 -0300 Subject: [PATCH 1/5] fix(core): make the narrowing conversions explicit and saturating The decoder is `forbid(unsafe_code)` and never panics, so the interesting failure mode is not a crash but a wrong value. This hardens every place where a wider integer was narrowed with an unchecked `as`. - The two CAS-latency derivations (the linter's supported-set check and the vendor-profile rated CL) narrowed a `u32` quotient to `u16`. Safe for decoded bytes, but fragile and non-obvious; they now narrow explicitly and saturate, so a hand-built out-of-range value cannot wrap into a plausible-looking latency. Regression tests cover both, including the case that wrapped to a silent `CL5`. - The supported-CAS mask arithmetic now computes its bit index in one integer domain, with a compile-time check tying the bit count to the byte count it derives from. - The reference-raw-card `Display` no longer casts the alphabet length or array indices. Also, since the crate is `no_std` and meant to be embeddable, every pure decoder and accessor it can is now `const fn`, and two `pub(crate)` markers that were redundant inside private modules became plain `pub` (same effective visibility). Documentation is completed in the same pass: an `# Errors` section on every public `Result`-returning function, identifiers in prose wrapped in backticks, and bit-range notation escaped so it no longer parses as an intra-doc link. No decoded output changes: the golden snapshots pass byte for byte. --- spdr-cli/src/lib.rs | 32 ++++++------ spdr/src/crc.rs | 8 ++- spdr/src/identity.rs | 93 +++++++++++++++++----------------- spdr/src/lib.rs | 2 +- spdr/src/lint.rs | 35 +++++++++++-- spdr/src/manufacturing.rs | 17 ++++--- spdr/src/module.rs | 58 ++++++++++----------- spdr/src/reader.rs | 18 +++++-- spdr/src/timing.rs | 103 +++++++++++++++++++++++++++----------- spdr/src/vendor.rs | 63 +++++++++++++++++++---- spdr/tests/module.rs | 2 +- spdr/tests/robustness.rs | 16 +++--- 12 files changed, 290 insertions(+), 157 deletions(-) diff --git a/spdr-cli/src/lib.rs b/spdr-cli/src/lib.rs index a28299c..4aa26b4 100644 --- a/spdr-cli/src/lib.rs +++ b/spdr-cli/src/lib.rs @@ -93,7 +93,7 @@ impl DecodeResults<'_> { /// is itself a successful decode (`Ok`) and does not make this `false`; /// integrity and consistency are the linter's job (the `lint` subcommand). #[must_use] - pub fn all_decoded(&self) -> bool { + pub const fn all_decoded(&self) -> bool { self.identity.is_ok() && self.crc.is_ok() && self.timings.is_ok() @@ -159,7 +159,7 @@ fn run_decode(args: &DecodeArgs) -> i32 { }; println!("{rendered}"); - if results.all_decoded() { 0 } else { 1 } + i32::from(!results.all_decoded()) } // --- Lint surface ---------------------------------------------------------- @@ -198,7 +198,7 @@ pub fn lint_report(bytes: &[u8]) -> LintReport { /// The lint exit code computed from the findings: `1` if any `Error` or `Warning` /// is present, `0` if there are none or only `Info` advisories. The operational -/// `2` (unreadable file or bad arguments) is handled in [`run_lint`] and by clap, +/// `2` (unreadable file or bad arguments) is handled in `run_lint` and by clap, /// never here. #[must_use] pub fn lint_exit_code(findings: &[Finding]) -> i32 { @@ -241,7 +241,7 @@ fn run_lint(args: &LintArgs) -> i32 { } /// The severity sort rank: errors first, then warnings, then info. -fn severity_rank(severity: Severity) -> u8 { +const fn severity_rank(severity: Severity) -> u8 { match severity { Severity::Error => 0, Severity::Warning => 1, @@ -250,7 +250,7 @@ fn severity_rank(severity: Severity) -> u8 { } /// The lowercase severity label used in both lint renders. -fn severity_label(severity: Severity) -> &'static str { +const fn severity_label(severity: Severity) -> &'static str { match severity { Severity::Error => "error", Severity::Warning => "warning", @@ -613,20 +613,20 @@ fn render_xmp(out: &mut String, xmp: &Xmp) { profile2, } => { vline(out, 2, "Intel XMP 3.0:", "present"); - vline(out, 4, "Header section CRC:", crc_summary(header_crc)); - render_xmp_slot(out, 1, profile1); - render_xmp_slot(out, 2, profile2); + vline(out, 4, "Header section CRC:", crc_summary(*header_crc)); + render_xmp_slot(out, 1, profile1.as_ref()); + render_xmp_slot(out, 2, profile2.as_ref()); } } } -fn render_xmp_slot(out: &mut String, number: u8, slot: &Option) { +fn render_xmp_slot(out: &mut String, number: u8, slot: Option<&XmpProfile>) { match slot { Some(p) => { let name = p.name.unwrap_or("(unnamed)"); vheading(out, 4, &format!("Profile {number}: {name}")); render_rated(out, &p.rated); - vline(out, 6, "Section CRC:", crc_summary(&p.crc)); + vline(out, 6, "Section CRC:", crc_summary(p.crc)); } None => vheading(out, 4, &format!("Profile {number}: (not enabled)")), } @@ -641,14 +641,14 @@ fn render_expo(out: &mut String, expo: &Expo) { profile2, } => { vline(out, 2, "AMD EXPO:", "present"); - vline(out, 4, "Block section CRC:", crc_summary(block_crc)); - render_expo_slot(out, 1, profile1); - render_expo_slot(out, 2, profile2); + vline(out, 4, "Block section CRC:", crc_summary(*block_crc)); + render_expo_slot(out, 1, profile1.as_ref()); + render_expo_slot(out, 2, profile2.as_ref()); } } } -fn render_expo_slot(out: &mut String, number: u8, slot: &Option) { +fn render_expo_slot(out: &mut String, number: u8, slot: Option<&ExpoProfile>) { match slot { Some(p) => { vheading(out, 4, &format!("Profile {number}:")); @@ -707,7 +707,7 @@ fn timing_clocks(t: Picoseconds, cycle_time: Picoseconds) -> String { } /// One-line CRC summary: the computed and stored values and whether they match. -fn crc_summary(crc: &CrcStatus) -> String { +fn crc_summary(crc: CrcStatus) -> String { format!( "computed {:#06X}, stored {:#06X} ({})", crc.computed, @@ -716,7 +716,7 @@ fn crc_summary(crc: &CrcStatus) -> String { ) } -fn yes_no(value: bool) -> &'static str { +const fn yes_no(value: bool) -> &'static str { if value { "yes" } else { "no" } } diff --git a/spdr/src/crc.rs b/spdr/src/crc.rs index 0629216..503cb84 100644 --- a/spdr/src/crc.rs +++ b/spdr/src/crc.rs @@ -57,8 +57,12 @@ pub fn crc16(bytes: &[u8]) -> u16 { /// Computes the CRC over bytes `0..=509`, reads the stored CRC from byte 510 /// (low) and byte 511 (high), and reports both values with whether they match. /// This is a queryable check only: a mismatch is reported, never raised, so it -/// cannot block decoding. Returns [`DecodeError::Truncated`] only if the image -/// is too short to contain the covered range and the stored CRC (512 bytes). +/// cannot block decoding. +/// +/// # Errors +/// +/// Returns [`DecodeError::Truncated`] only if the image is too short to contain +/// the covered range and the stored CRC (512 bytes). pub fn verify_base_crc(bytes: &[u8]) -> Result { let covered = bytes .get(..=CRC_COVERED_END) diff --git a/spdr/src/identity.rs b/spdr/src/identity.rs index dbd5e13..f6b619b 100644 --- a/spdr/src/identity.rs +++ b/spdr/src/identity.rs @@ -154,7 +154,7 @@ impl DensityPerDie { } } -/// SDRAM I/O device width (DQ pins per device), from bits [7:5] of byte 6. +/// SDRAM I/O device width (DQ pins per device), from bits \[7:5\] of byte 6. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum IoWidth { @@ -177,7 +177,7 @@ impl IoWidth { } } -/// Number of bank groups per die, from bits [7:5] of byte 7. +/// Number of bank groups per die, from bits \[7:5\] of byte 7. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum BankGroups { @@ -200,7 +200,7 @@ impl BankGroups { } } -/// Number of banks within each bank group, from bits [2:0] of byte 7. +/// Number of banks within each bank group, from bits \[2:0\] of byte 7. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum BanksPerBankGroup { @@ -221,7 +221,7 @@ impl BanksPerBankGroup { } } -/// SDRAM package construction, from bits [7:5] of byte 4. +/// SDRAM package construction, from bits \[7:5\] of byte 4. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum PackageType { @@ -258,7 +258,7 @@ impl fmt::Display for PackageType { #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct IdentityAndBase { - /// Total addressable size of the SPD device in bytes (byte 0, bits [6:4]). + /// Total addressable size of the SPD device in bytes (byte 0, bits \[6:4\]). pub spd_bytes_total: u16, /// SPD revision (byte 1). pub spd_revision: SpdRevision, @@ -268,34 +268,36 @@ pub struct IdentityAndBase { pub module_type: ModuleType, /// Hybrid-module flag (byte 3, bit 7). pub hybrid: bool, - /// SDRAM density per die (byte 4, bits [4:0]). + /// SDRAM density per die (byte 4, bits \[4:0\]). pub density_per_die: DensityPerDie, - /// SDRAM package construction (byte 4, bits [7:5]). + /// SDRAM package construction (byte 4, bits \[7:5\]). pub package_type: PackageType, - /// Number of dies in the SDRAM package (byte 4, bits [7:5]). + /// Number of dies in the SDRAM package (byte 4, bits \[7:5\]). pub die_count: u8, - /// Number of row address bits (byte 5, bits [4:0], base 16). + /// Number of row address bits (byte 5, bits \[4:0\], base 16). pub row_address_bits: u8, - /// Number of column address bits (byte 5, bits [7:5], base 10). + /// Number of column address bits (byte 5, bits \[7:5\], base 10). pub column_address_bits: u8, - /// SDRAM I/O device width (byte 6, bits [7:5]). + /// SDRAM I/O device width (byte 6, bits \[7:5\]). pub io_width: IoWidth, - /// Bank groups per die (byte 7, bits [7:5]). + /// Bank groups per die (byte 7, bits \[7:5\]). pub bank_groups: BankGroups, - /// Banks per bank group (byte 7, bits [2:0]). + /// Banks per bank group (byte 7, bits \[2:0\]). pub banks_per_bank_group: BanksPerBankGroup, - /// Package ranks per channel (byte 234, bits [5:3], base 1). + /// Package ranks per channel (byte 234, bits \[5:3\], base 1). pub package_ranks_per_channel: u8, /// Whether the rank organization is asymmetric (byte 234, bit 6). pub rank_mix_asymmetric: bool, - /// Number of channels (sub-channels) per DIMM (byte 235, bits [7:5]). + /// Number of channels (sub-channels) per DIMM (byte 235, bits \[7:5\]). pub channels_per_dimm: u8, - /// Primary bus width per channel in bits (byte 235, bits [2:0]). + /// Primary bus width per channel in bits (byte 235, bits \[2:0\]). pub primary_bus_width_bits: u16, } /// Decode the identity and base SDRAM configuration from a raw SPD image. /// +/// # Errors +/// /// Returns [`DecodeError::Truncated`] if the image is shorter than the highest /// byte read (byte 235), or [`DecodeError::UnknownEnum`] if a spec-defined /// enumeration field holds a reserved or undefined value. @@ -354,8 +356,8 @@ pub fn decode_identity_and_base(bytes: &[u8]) -> Result Result { +/// Byte 0, bits \[6:4\]: total addressable size of the SPD device in bytes. +const fn decode_spd_bytes_total(byte0: u8) -> Result { match (byte0 >> 4) & 0x07 { 1 => Ok(256), 2 => Ok(512), @@ -368,8 +370,8 @@ fn decode_spd_bytes_total(byte0: u8) -> Result { } } -/// Byte 1: SPD revision as two plain nibbles, major in [7:4], minor in [3:0]. -fn decode_spd_revision(byte1: u8) -> SpdRevision { +/// Byte 1: SPD revision as two plain nibbles, major in \[7:4\], minor in \[3:0\]. +const fn decode_spd_revision(byte1: u8) -> SpdRevision { SpdRevision { major: byte1 >> 4, minor: byte1 & 0x0F, @@ -377,7 +379,7 @@ fn decode_spd_revision(byte1: u8) -> SpdRevision { } /// Byte 2: whole-byte DRAM device type key. -fn decode_device_type(byte2: u8) -> Result { +const fn decode_device_type(byte2: u8) -> Result { match byte2 { 0x0B => Ok(DeviceType::Ddr3), 0x0C => Ok(DeviceType::Ddr4), @@ -390,11 +392,12 @@ fn decode_device_type(byte2: u8) -> Result { } } -/// Byte 3: base module type in bits [3:0]; hybrid flag in bit 7. +/// Byte 3: base module type in bits \[3:0\]; hybrid flag in bit 7. /// -/// Crate-visible so the module-specific dispatch ([`crate::decode_module_specific`]) -/// routes on the same single decode of byte 3, rather than duplicating it. -pub(crate) fn decode_module_type(byte3: u8) -> Result<(ModuleType, bool), DecodeError> { +/// Crate-visible (this module is private, so `pub` stays crate-internal) so the +/// module-specific dispatch ([`crate::decode_module_specific`]) routes on the +/// same single decode of byte 3, rather than duplicating it. +pub const fn decode_module_type(byte3: u8) -> Result<(ModuleType, bool), DecodeError> { let hybrid = byte3 & 0x80 != 0; let module_type = match byte3 & 0x0F { 0x01 => ModuleType::Rdimm, @@ -417,8 +420,8 @@ pub(crate) fn decode_module_type(byte3: u8) -> Result<(ModuleType, bool), Decode Ok((module_type, hybrid)) } -/// Byte 4, bits [4:0]: SDRAM density per die. -fn decode_density_per_die(byte4: u8) -> Result { +/// Byte 4, bits \[4:0\]: SDRAM density per die. +const fn decode_density_per_die(byte4: u8) -> Result { match byte4 & 0x1F { 0x01 => Ok(DensityPerDie::Gb4), 0x02 => Ok(DensityPerDie::Gb8), @@ -435,8 +438,8 @@ fn decode_density_per_die(byte4: u8) -> Result { } } -/// Byte 4, bits [7:5]: package construction and die count. -fn decode_package(byte4: u8) -> Result<(PackageType, u8), DecodeError> { +/// Byte 4, bits \[7:5\]: package construction and die count. +const fn decode_package(byte4: u8) -> Result<(PackageType, u8), DecodeError> { match (byte4 >> 5) & 0x07 { 0 => Ok((PackageType::Monolithic, 1)), 1 => Ok((PackageType::DualDie, 2)), @@ -451,18 +454,18 @@ fn decode_package(byte4: u8) -> Result<(PackageType, u8), DecodeError> { } } -/// Byte 5, bits [4:0]: number of row address bits, base 16. -fn decode_row_address_bits(byte5: u8) -> u8 { +/// Byte 5, bits \[4:0\]: number of row address bits, base 16. +const fn decode_row_address_bits(byte5: u8) -> u8 { 16 + (byte5 & 0x1F) } -/// Byte 5, bits [7:5]: number of column address bits, base 10. -fn decode_column_address_bits(byte5: u8) -> u8 { +/// Byte 5, bits \[7:5\]: number of column address bits, base 10. +const fn decode_column_address_bits(byte5: u8) -> u8 { 10 + ((byte5 >> 5) & 0x07) } -/// Byte 6, bits [7:5]: SDRAM I/O device width. -fn decode_io_width(byte6: u8) -> Result { +/// Byte 6, bits \[7:5\]: SDRAM I/O device width. +const fn decode_io_width(byte6: u8) -> Result { match (byte6 >> 5) & 0x07 { 0 => Ok(IoWidth::X4), 1 => Ok(IoWidth::X8), @@ -475,8 +478,8 @@ fn decode_io_width(byte6: u8) -> Result { } } -/// Byte 7, bits [7:5]: number of bank groups. -fn decode_bank_groups(byte7: u8) -> Result { +/// Byte 7, bits \[7:5\]: number of bank groups. +const fn decode_bank_groups(byte7: u8) -> Result { match (byte7 >> 5) & 0x07 { 0 => Ok(BankGroups::One), 1 => Ok(BankGroups::Two), @@ -489,8 +492,8 @@ fn decode_bank_groups(byte7: u8) -> Result { } } -/// Byte 7, bits [2:0]: number of banks per bank group. -fn decode_banks_per_bank_group(byte7: u8) -> Result { +/// Byte 7, bits \[2:0\]: number of banks per bank group. +const fn decode_banks_per_bank_group(byte7: u8) -> Result { match byte7 & 0x07 { 0 => Ok(BanksPerBankGroup::One), 1 => Ok(BanksPerBankGroup::Two), @@ -502,16 +505,16 @@ fn decode_banks_per_bank_group(byte7: u8) -> Result (u8, bool) { +const fn decode_package_ranks(byte234: u8) -> (u8, bool) { let ranks = ((byte234 >> 3) & 0x07) + 1; let asymmetric = byte234 & 0x40 != 0; (ranks, asymmetric) } -/// Byte 235, bits [2:0]: primary bus width per channel in bits. -fn decode_primary_bus_width(byte235: u8) -> Result { +/// Byte 235, bits \[2:0\]: primary bus width per channel in bits. +const fn decode_primary_bus_width(byte235: u8) -> Result { match byte235 & 0x07 { 0 => Ok(8), 1 => Ok(16), @@ -524,8 +527,8 @@ fn decode_primary_bus_width(byte235: u8) -> Result { } } -/// Byte 235, bits [7:5]: number of channels (sub-channels) per DIMM. -fn decode_channels_per_dimm(byte235: u8) -> Result { +/// Byte 235, bits \[7:5\]: number of channels (sub-channels) per DIMM. +const fn decode_channels_per_dimm(byte235: u8) -> Result { match (byte235 >> 5) & 0x07 { 0 => Ok(1), 1 => Ok(2), diff --git a/spdr/src/lib.rs b/spdr/src/lib.rs index e917543..e73a5f6 100644 --- a/spdr/src/lib.rs +++ b/spdr/src/lib.rs @@ -18,7 +18,7 @@ //! result, deferred to later phases gated on real fixtures. Phase 5 adds the //! manufacturing information block ([`Manufacturing`], [`decode_manufacturing`]), //! including JEP-106 manufacturer resolution. Phase 8 opens the linter, the -//! validation-beyond-CRC pillar ([`Finding`], [`Severity`], [`lint`]): it reports +//! validation-beyond-CRC pillar ([`Finding`], [`Severity`], [`lint()`]): it reports //! structured findings for values that are internally inconsistent even in a //! CRC-valid SPD, starting with the capacity-consistency rule. Phase 9a decodes //! the vendor overclocking profiles ([`Xmp`], [`Expo`], [`decode_xmp`], diff --git a/spdr/src/lint.rs b/spdr/src/lint.rs index 007ec86..87ce38b 100644 --- a/spdr/src/lint.rs +++ b/spdr/src/lint.rs @@ -16,7 +16,7 @@ //! Phase 8 ships the framework and the first rule, capacity consistency //! ([`Finding::NonIntegerDeviceCount`]). Phase 9b adds the timing-relationship, //! clock-consistency, and speed-bin rules: now that the base JEDEC timings -//! (Phase 3) and the XMP/EXPO rated profiles (Phase 9a) are decoded, [`lint`] +//! (Phase 3) and the XMP/EXPO rated profiles (Phase 9a) are decoded, [`lint()`] //! also decodes them and checks that the timings are internally self-consistent //! and standard where they should be. Each rule runs only where its inputs were //! decoded, so a rule needing a field a vendor profile does not carry simply does @@ -26,7 +26,7 @@ //! reserved-bit rule keys only off regions open references explicitly declare //! reserved and the valid fixture confirms are zero (a region a valid module uses //! is excluded, never flagged), and the consistency rules flag only a definitional -//! incoherence. Every later rule plugs into the same [`lint`] dispatch and the +//! incoherence. Every later rule plugs into the same [`lint()`] dispatch and the //! same [`Finding`] enum. use crate::identity::{IdentityAndBase, PackageType, decode_identity_and_base}; @@ -221,7 +221,7 @@ pub enum Finding { impl Finding { /// The inherent severity of this finding. #[must_use] - pub fn severity(&self) -> Severity { + pub const fn severity(&self) -> Severity { match self { Finding::NonIntegerDeviceCount { .. } | Finding::TrcIdentityMismatch { .. } @@ -238,7 +238,7 @@ impl Finding { /// A stable, kebab-case lint code identifying the rule that produced this /// finding. Stable across versions, so it can be referenced or filtered on. #[must_use] - pub fn code(&self) -> &'static str { + pub const fn code(&self) -> &'static str { match self { Finding::NonIntegerDeviceCount { .. } => "non-integer-device-count", Finding::TrcIdentityMismatch { .. } => "trc-identity-mismatch", @@ -495,7 +495,10 @@ fn check_cas_latency( return; } if let Some(set) = supported { - let cas_latency = (taa.0 / tck_ps) as u16; + // Every decoded tAA and tCK originates from a 16-bit SPD field (see + // `ps_units`/`ps`), so the quotient fits `u16`; the narrowing saturates + // rather than wraps if a caller ever hand-builds out-of-range values. + let cas_latency = u16::try_from(taa.0 / tck_ps).unwrap_or(u16::MAX); if !set.contains(cas_latency) { sink(Finding::CasLatencyNotSupported { cas_latency }); } @@ -812,6 +815,28 @@ mod tests { assert_eq!(clean, 0); } + #[test] + fn cas_latency_saturates_instead_of_wrapping() { + // Unreachable from a decoded image (both fields are 16-bit), so it is + // exercised directly: the narrowing must saturate. 65541 cycles wrapped + // with `as u16` would be reported as CL5, a plausible-looking latency + // that would be silently misreported. + let set = decode_timings(&timing_image(416, 16640, [0x02, 0, 0, 0, 0])) + .unwrap() + .supported_cas_latencies; + for (taa, expected) in [(65_541, u16::MAX), (65_536, u16::MAX), (65_535, 65_535_u16)] { + let (count, last) = + run(|sink| check_cas_latency(Picoseconds(taa), Picoseconds(1), Some(set), sink)); + assert_eq!(count, 1); + assert_eq!( + last.unwrap(), + Finding::CasLatencyNotSupported { + cas_latency: expected + } + ); + } + } + #[test] fn non_integer_clock_timing_is_warning() { // tRCD 12655 ps is not a whole multiple of tCK 333 ps. diff --git a/spdr/src/manufacturing.rs b/spdr/src/manufacturing.rs index 2379852..184b910 100644 --- a/spdr/src/manufacturing.rs +++ b/spdr/src/manufacturing.rs @@ -162,9 +162,14 @@ pub struct Manufacturing<'a> { /// Decode the manufacturing information block from a raw SPD image. /// -/// Reads every byte through [`SpdImage`], so a short image is a typed -/// [`DecodeError::Truncated`], never a panic. A non-ASCII part number is a typed -/// [`DecodeError::NonAscii`]. The `part_number` field borrows from `bytes`. +/// Reads every byte through [`SpdImage`], never panicking. The `part_number` +/// field borrows from `bytes`. +/// +/// # Errors +/// +/// - [`DecodeError::Truncated`] if the image is too short for a required byte. +/// - [`DecodeError::NonAscii`] if the part number holds a byte outside the +/// ASCII range, reported rather than lossily reinterpreted. pub fn decode_manufacturing(bytes: &[u8]) -> Result, DecodeError> { let spd = SpdImage::new(bytes); @@ -207,7 +212,7 @@ pub fn decode_manufacturing(bytes: &[u8]) -> Result, DecodeErr /// byte. Bit 7 of each is odd parity and is stripped: `bank` is the 7-bit /// continuation count plus 1, `code` is the 7-bit manufacturer code. The name is /// resolved from the cited table, or `None` when the pair is absent. -fn decode_manufacturer_id(lsb: u8, msb: u8) -> ManufacturerId { +const fn decode_manufacturer_id(lsb: u8, msb: u8) -> ManufacturerId { let bank = (lsb & 0x7F) + 1; let code = msb & 0x7F; ManufacturerId { @@ -218,7 +223,7 @@ fn decode_manufacturer_id(lsb: u8, msb: u8) -> ManufacturerId { } /// Decode a BCD byte (two decimal digits packed one per nibble) to its value. -fn bcd(byte: u8) -> u8 { +const fn bcd(byte: u8) -> u8 { (byte >> 4) * 10 + (byte & 0x0F) } @@ -267,7 +272,7 @@ const JEP106: &[(u8, u8, &str)] = &[ ]; /// Resolve a JEP-106 `(bank, code)` to a name from the cited table, or `None`. -fn resolve_jep106(bank: u8, code: u8) -> Option<&'static str> { +const fn resolve_jep106(bank: u8, code: u8) -> Option<&'static str> { let mut i = 0; while i < JEP106.len() { let (b, c, name) = JEP106[i]; diff --git a/spdr/src/module.rs b/spdr/src/module.rs index a9038a2..97dd9c0 100644 --- a/spdr/src/module.rs +++ b/spdr/src/module.rs @@ -61,7 +61,7 @@ impl fmt::Display for Millimeters { /// ambiguous letters I, O, Q, S, X, and Z, so the lettering runs A, B, ... H, J, /// K, ... Y, then two-letter cards (AA-style) past index 19. A card code of /// `0x1f` means no reference raw card (rendered "ZZ"); bit 7 extends the code by -/// 31 to reach the two-letter range; bits [6:5] carry the card revision. +/// 31 to reach the two-letter range; bits \[6:5\] carry the card revision. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum ReferenceRawCard { @@ -71,7 +71,7 @@ pub enum ReferenceRawCard { Card { /// Zero-based card index (0 = card "A") with the bit-7 extension applied. index: u8, - /// Card revision, from bits [6:5]. + /// Card revision, from bits \[6:5\]. revision: u8, }, } @@ -84,20 +84,18 @@ impl fmt::Display for ReferenceRawCard { match *self { ReferenceRawCard::NotUsed => f.write_str("ZZ (no reference raw card)"), ReferenceRawCard::Card { index, revision } => { - let n = RRC_ALPHABET.len() as u8; // 20 - if index < n { - write!( - f, - "{} revision {revision}", - RRC_ALPHABET[index as usize] as char - ) + let n = RRC_ALPHABET.len(); + let idx = usize::from(index); + if idx < n { + write!(f, "{} revision {revision}", char::from(RRC_ALPHABET[idx])) } else { - let hi = index / n; - let lo = index % n; + let hi = idx / n; + let lo = idx % n; write!( f, "{}{} revision {revision}", - RRC_ALPHABET[hi as usize] as char, RRC_ALPHABET[lo as usize] as char + char::from(RRC_ALPHABET[hi]), + char::from(RRC_ALPHABET[lo]) ) } } @@ -112,13 +110,13 @@ impl fmt::Display for ReferenceRawCard { #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct UnbufferedModule { - /// Module nominal height (byte 230, bits [4:0] + 15 mm). JEDEC encodes this + /// Module nominal height (byte 230, bits \[4:0\] + 15 mm). JEDEC encodes this /// as the upper bound of a 1 mm range, so a value of 0 means "<= 15 mm". pub nominal_height: Millimeters, - /// Maximum module thickness on the front (byte 231, bits [3:0] + 1 mm), the + /// Maximum module thickness on the front (byte 231, bits \[3:0\] + 1 mm), the /// upper bound of a 1 mm range. pub max_thickness_front: Millimeters, - /// Maximum module thickness on the back (byte 231, bits [7:4] + 1 mm), the + /// Maximum module thickness on the back (byte 231, bits \[7:4\] + 1 mm), the /// upper bound of a 1 mm range. pub max_thickness_back: Millimeters, /// Reference raw card the module is built from (byte 232). @@ -152,10 +150,14 @@ pub enum ModuleSpecific { /// /// Reads the module-type byte (byte 3) through [`SpdImage`] and routes on it: /// the unbuffered case decodes bytes 230..=233 into [`UnbufferedModule`]; any -/// other registered type returns [`ModuleSpecific::NotYetDecoded`]. Returns -/// [`DecodeError::Truncated`] if the image is too short for a byte the chosen -/// path reads, or [`DecodeError::UnknownEnum`] if byte 3 holds a reserved module -/// type. Never panics on malformed input. +/// other registered type returns [`ModuleSpecific::NotYetDecoded`]. Never panics +/// on malformed input. +/// +/// # Errors +/// +/// - [`DecodeError::Truncated`] if the image is too short for a byte the chosen +/// path reads. +/// - [`DecodeError::UnknownEnum`] if byte 3 holds a reserved module type. pub fn decode_module_specific(bytes: &[u8]) -> Result { let spd = SpdImage::new(bytes); let (module_type, _hybrid) = decode_module_type(spd.byte(OFF_MODULE_TYPE)?)?; @@ -186,24 +188,24 @@ fn decode_unbuffered(spd: &SpdImage) -> Result { // Each applies one pinned encoding rule to its byte, so each has a focused unit // test built straight from the rule. -/// Byte 230, bits [4:0]: module nominal height in mm with a 15 mm base. -fn decode_nominal_height(byte230: u8) -> Millimeters { +/// Byte 230, bits \[4:0\]: module nominal height in mm with a 15 mm base. +const fn decode_nominal_height(byte230: u8) -> Millimeters { Millimeters((byte230 & 0x1F) + 15) } -/// Byte 231, bits [3:0]: front maximum thickness in mm with a 1 mm base. -fn decode_thickness_front(byte231: u8) -> Millimeters { +/// Byte 231, bits \[3:0\]: front maximum thickness in mm with a 1 mm base. +const fn decode_thickness_front(byte231: u8) -> Millimeters { Millimeters((byte231 & 0x0F) + 1) } -/// Byte 231, bits [7:4]: back maximum thickness in mm with a 1 mm base. -fn decode_thickness_back(byte231: u8) -> Millimeters { +/// Byte 231, bits \[7:4\]: back maximum thickness in mm with a 1 mm base. +const fn decode_thickness_back(byte231: u8) -> Millimeters { Millimeters(((byte231 >> 4) & 0x0F) + 1) } -/// Byte 232: reference raw card code (bits [4:0]), with the bit-7 extension and -/// the bits [6:5] revision. Code `0x1f` is the defined "no card" value. -fn decode_reference_raw_card(byte232: u8) -> ReferenceRawCard { +/// Byte 232: reference raw card code (bits \[4:0\]), with the bit-7 extension and +/// the bits \[6:5\] revision. Code `0x1f` is the defined "no card" value. +const fn decode_reference_raw_card(byte232: u8) -> ReferenceRawCard { let code = byte232 & 0x1F; if code == 0x1F { return ReferenceRawCard::NotUsed; diff --git a/spdr/src/reader.rs b/spdr/src/reader.rs index d6000fe..d589bce 100644 --- a/spdr/src/reader.rs +++ b/spdr/src/reader.rs @@ -29,12 +29,16 @@ impl<'a> SpdImage<'a> { /// Whether the underlying image is empty. #[must_use] - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.bytes.is_empty() } - /// Read the single byte at `offset`, or [`DecodeError::Truncated`] if the - /// image is too short to contain it. Uses `slice::get`, never indexing. + /// Read the single byte at `offset`. Uses `slice::get`, never indexing. + /// + /// # Errors + /// + /// Returns [`DecodeError::Truncated`] if the image is too short to contain + /// the byte at `offset`. pub fn byte(&self, offset: usize) -> Result { self.bytes .get(offset) @@ -45,11 +49,15 @@ impl<'a> SpdImage<'a> { }) } - /// Borrow `len` bytes starting at `offset`, or [`DecodeError::Truncated`] if - /// the image is too short to contain them. Zero-copy: the returned slice + /// Borrow `len` bytes starting at `offset`. Zero-copy: the returned slice /// borrows the input image for the image's lifetime, so a decoded value can /// hold it without a copy (the part-number `&str` does). Uses `slice::get`, /// never indexing. `len` must be at least 1. + /// + /// # Errors + /// + /// Returns [`DecodeError::Truncated`] if the image is too short to contain + /// `len` bytes at `offset`. pub fn slice(&self, offset: usize, len: usize) -> Result<&'a [u8], DecodeError> { self.bytes .get(offset..offset + len) diff --git a/spdr/src/timing.rs b/spdr/src/timing.rs index 50a624c..7a0bc9b 100644 --- a/spdr/src/timing.rs +++ b/spdr/src/timing.rs @@ -97,15 +97,16 @@ pub struct CasLatencies(u64); impl CasLatencies { const BASE_CL: u16 = 20; - const BIT_COUNT: u32 = (CAS_LATENCY_BYTES * 8) as u32; + /// The number of mask bits in the set: `CAS_LATENCY_BYTES` * 8. + const BIT_COUNT: u16 = 40; /// Whether `cl` is in the supported set. #[must_use] - pub fn contains(self, cl: u16) -> bool { + pub const fn contains(self, cl: u16) -> bool { if cl < Self::BASE_CL || (cl - Self::BASE_CL) % 2 != 0 { return false; } - let bit = u32::from((cl - Self::BASE_CL) / 2); + let bit = (cl - Self::BASE_CL) / 2; bit < Self::BIT_COUNT && (self.0 >> bit) & 1 != 0 } @@ -113,7 +114,7 @@ impl CasLatencies { pub fn iter(self) -> impl Iterator { (0..Self::BIT_COUNT).filter_map(move |bit| { if (self.0 >> bit) & 1 != 0 { - Some(Self::BASE_CL + 2 * bit as u16) + Some(Self::BASE_CL + 2 * bit) } else { None } @@ -121,6 +122,12 @@ impl CasLatencies { } } +// `CasLatencies::BIT_COUNT` is written as a literal so the whole bit-index +// domain stays `u16` (no narrowing anywhere in `contains`/`iter`); this +// compile-time check keeps it from drifting from the byte count it derives +// from. The `as usize` is a lossless widening (const `From` is not stable yet). +const _: () = assert!(CAS_LATENCY_BYTES * 8 == CasLatencies::BIT_COUNT as usize); + impl fmt::Debug for CasLatencies { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.iter()).finish() @@ -156,39 +163,39 @@ pub struct Timings { pub tckavg_max: Picoseconds, /// Supported CAS latencies. pub supported_cas_latencies: CasLatencies, - /// CAS latency time (tAA). + /// CAS latency time (`tAA`). pub taa: Picoseconds, - /// RAS-to-CAS delay (tRCD). + /// RAS-to-CAS delay (`tRCD`). pub trcd: Picoseconds, - /// Row precharge time (tRP). + /// Row precharge time (`tRP`). pub trp: Picoseconds, - /// Active-to-precharge time (tRAS). + /// Active-to-precharge time (`tRAS`). pub tras: Picoseconds, - /// Active-to-active / refresh cycle time (tRC). + /// Active-to-active / refresh cycle time (`tRC`). pub trc: Picoseconds, - /// Write recovery time (tWR). + /// Write recovery time (`tWR`). pub twr: Picoseconds, - /// Normal refresh recovery time (tRFC1). + /// Normal refresh recovery time (`tRFC1`). pub trfc1: Picoseconds, - /// Fine-granularity refresh recovery time (tRFC2). + /// Fine-granularity refresh recovery time (`tRFC2`). pub trfc2: Picoseconds, - /// Same-bank refresh recovery time (tRFCsb). + /// Same-bank refresh recovery time (`tRFCsb`). pub trfcsb: Picoseconds, - /// Activate-to-activate, same bank group (tRRD_L). + /// Activate-to-activate, same bank group (`tRRD_L`). pub trrd_l: TimingPair, - /// CAS-to-CAS, same bank group (tCCD_L). + /// CAS-to-CAS, same bank group (`tCCD_L`). pub tccd_l: TimingPair, - /// Write CAS-to-CAS, same bank group (tCCD_L_WR). + /// Write CAS-to-CAS, same bank group (`tCCD_L_WR`). pub tccd_l_wr: TimingPair, - /// Second-write CAS-to-CAS, same bank group (tCCD_L_WR2). + /// Second-write CAS-to-CAS, same bank group (`tCCD_L_WR2`). pub tccd_l_wr2: TimingPair, - /// Four-activate window (tFAW). + /// Four-activate window (`tFAW`). pub tfaw: TimingPair, - /// Write-to-read, same bank group (tWTR_L). + /// Write-to-read, same bank group (`tWTR_L`). pub twtr_l: TimingPair, - /// Write-to-read, different bank group (tWTR_S). + /// Write-to-read, different bank group (`tWTR_S`). pub twtr_s: TimingPair, - /// Read-to-precharge (tRTP). + /// Read-to-precharge (`tRTP`). pub trtp: TimingPair, } @@ -197,17 +204,20 @@ impl Timings { /// nearest 100. For this fixture this is the base fallback (DDR5-4800), not /// the advertised XMP/EXPO profile rate. #[must_use] - pub fn base_data_rate_mt_s(&self) -> u32 { + pub const fn base_data_rate_mt_s(&self) -> u32 { data_rate_mt_s(self.tckavg_min) } } /// Decode the base JEDEC timing block from a raw SPD image. /// -/// Reads every byte through [`SpdImage`], so a short image yields -/// [`DecodeError::Truncated`] rather than a panic. The base timing parameters -/// are raw integer encodings with no reserved values, so truncation is the only -/// error this can return. +/// Reads every byte through [`SpdImage`], never panicking. The base timing +/// parameters are raw integer encodings with no reserved values. +/// +/// # Errors +/// +/// Returns [`DecodeError::Truncated`] if the image is too short for a required +/// byte — the only error this can return. pub fn decode_timings(bytes: &[u8]) -> Result { let spd = SpdImage::new(bytes); @@ -275,9 +285,10 @@ fn decode_cas_latencies(spd: &SpdImage) -> Result { } /// Data rate in MT/s for a clock period, rounded to the nearest 100; 0 if the -/// period is zero. Crate-visible so the XMP/EXPO profile decode derives its -/// rated data rate through the same rounding rather than duplicating it. -pub(crate) fn data_rate_mt_s(tckavg_min: Picoseconds) -> u32 { +/// period is zero. Crate-visible (this module is private, so `pub` stays +/// crate-internal) so the XMP/EXPO profile decode derives its rated data rate +/// through the same rounding rather than duplicating it. +pub const fn data_rate_mt_s(tckavg_min: Picoseconds) -> u32 { if tckavg_min.0 == 0 { return 0; } @@ -337,6 +348,40 @@ mod tests { assert_eq!(cl.iter().last(), Some(40)); } + #[test] + fn cas_latency_bit_domain_covers_exactly_the_mask() { + // The bit-index arithmetic lives entirely in `u16` (no narrowing), so + // pin the boundary of the domain: the last mask bit is CL98 and nothing + // beyond it is in the set. + let all = CasLatencies(u64::MAX); + assert_eq!(CasLatencies::BIT_COUNT, 40); + assert!(all.contains(CasLatencies::BASE_CL)); + assert!(all.contains(98)); // BASE_CL + 2 * 39, the final bit + assert!(!all.contains(100)); // one past the last bit + assert!(!all.contains(19)); // below BASE_CL + assert_eq!(all.iter().count(), 40); + + // `contains` and `iter` must agree bit for bit across the whole mask, + // including every single-bit set, which is where an off-by-one in the + // index domain would show. + for bit in 0..CasLatencies::BIT_COUNT { + let one = CasLatencies(1 << bit); + assert_eq!(one.iter().count(), 1, "bit {bit}"); + assert_eq!( + one.iter().next(), + Some(CasLatencies::BASE_CL + 2 * bit), + "bit {bit}" + ); + for cl in 20..=100u16 { + assert_eq!( + one.contains(cl), + cl == CasLatencies::BASE_CL + 2 * bit, + "bit {bit}, CL{cl}" + ); + } + } + } + #[test] fn data_rate_rounds_to_nearest_hundred() { // tCKAVGmin 416 ps => 4807 MT/s => DDR5-4800 base. diff --git a/spdr/src/vendor.rs b/spdr/src/vendor.rs index d57db8d..c55d9eb 100644 --- a/spdr/src/vendor.rs +++ b/spdr/src/vendor.rs @@ -253,8 +253,12 @@ pub struct VendorProfiles<'a> { /// Decode both vendor-profile regions (XMP 3.0 and EXPO) from a raw SPD image. /// /// A convenience over [`decode_xmp`] and [`decode_expo`]; see those for the -/// per-region contract. Returns [`DecodeError::Truncated`] if the image is too -/// short for a byte a present region reads; an absent region is not an error. +/// per-region contract. An absent region is not an error. +/// +/// # Errors +/// +/// Returns [`DecodeError::Truncated`] if the image is too short for a byte a +/// present region reads. pub fn decode_vendor_profiles(bytes: &[u8]) -> Result, DecodeError> { Ok(VendorProfiles { xmp: decode_xmp(bytes)?, @@ -266,9 +270,12 @@ pub fn decode_vendor_profiles(bytes: &[u8]) -> Result, Decode /// /// Detects presence by the magic at offset 640. If absent, returns /// [`Xmp::Absent`] and reads nothing further. If present, decodes the header -/// CRC and each enabled profile through [`SpdImage`]. Returns -/// [`DecodeError::Truncated`] only if the image is long enough to hold the magic -/// but too short for a byte a present profile reads. Never panics. +/// CRC and each enabled profile through [`SpdImage`]. Never panics. +/// +/// # Errors +/// +/// Returns [`DecodeError::Truncated`] only if the image is long enough to hold +/// the magic but too short for a byte a present profile reads. pub fn decode_xmp(bytes: &[u8]) -> Result, DecodeError> { let spd = SpdImage::new(bytes); @@ -312,9 +319,12 @@ pub fn decode_xmp(bytes: &[u8]) -> Result, DecodeError> { /// /// Detects presence by the `"EXPO"` magic at offset 832. If absent, returns /// [`Expo::Absent`]. If present, decodes the single block CRC and each populated -/// profile through [`SpdImage`]. Returns [`DecodeError::Truncated`] only if the -/// image is long enough to hold the magic but too short for a byte the present -/// block reads. Never panics. +/// profile through [`SpdImage`]. Never panics. +/// +/// # Errors +/// +/// Returns [`DecodeError::Truncated`] only if the image is long enough to hold +/// the magic but too short for a byte the present block reads. pub fn decode_expo(bytes: &[u8]) -> Result { let spd = SpdImage::new(bytes); @@ -402,6 +412,7 @@ fn decode_expo_profile( } /// The three voltage bytes of a profile, in their raw encoding. +#[derive(Clone, Copy)] struct Voltages { vdd: u8, vddq: u8, @@ -411,6 +422,7 @@ struct Voltages { /// The five timing-field offsets of a profile. XMP and EXPO place these /// differently, so the caller supplies the absolute offsets and this assembles /// the shared [`RatedTimings`]. +#[derive(Clone, Copy)] struct Offsets { tck: usize, taa: usize, @@ -484,13 +496,15 @@ fn voltage(byte: u8) -> Millivolts { /// Derive the rated CAS latency: tAA in whole cycles of the cycle time, rounded /// to nearest. Guards a zero cycle time (returns 0) so malformed input cannot -/// divide by zero. +/// divide by zero. Decoded values are 16-bit picoseconds, so the rounded +/// quotient fits `u16`; the narrowing saturates instead of wrapping if a caller +/// ever hand-builds out-of-range values. fn rated_cas_latency(taa: Picoseconds, cycle_time: Picoseconds) -> u16 { let tck = cycle_time.0; if tck == 0 { return 0; } - ((taa.0 + tck / 2) / tck) as u16 + u16::try_from(taa.0.saturating_add(tck / 2) / tck).unwrap_or(u16::MAX) } /// Read a 16-byte profile name at `off`, trimmed of trailing spaces and NULs. @@ -543,6 +557,33 @@ mod tests { assert_eq!(rated_cas_latency(Picoseconds(12654), Picoseconds(0)), 0); } + #[test] + fn rated_cas_latency_saturates_instead_of_wrapping() { + // Unreachable from a decoded image (both fields are 16-bit), so it is + // exercised directly: the guard must saturate. 65541 cycles wrapped with + // `as u16` would come out as CL5, a plausible-looking latency that + // silently misreports the profile; saturation reports CL65535 instead. + assert_eq!( + rated_cas_latency(Picoseconds(65_541), Picoseconds(1)), + u16::MAX + ); + // The rounding add cannot overflow the way a plain `taa + tck / 2` could. + assert_eq!( + rated_cas_latency(Picoseconds(u32::MAX), Picoseconds(u32::MAX)), + 1 + ); + // One past `u16::MAX` cycles, still saturated rather than wrapped to 0. + assert_eq!( + rated_cas_latency(Picoseconds(65_536), Picoseconds(1)), + u16::MAX + ); + // The last representable count is exact, not clamped. + assert_eq!( + rated_cas_latency(Picoseconds(65_535), Picoseconds(1)), + 65_535 + ); + } + #[test] fn read_le_u16_low_byte_first() { let spd = SpdImage::new(&[0x4D, 0x01]); @@ -686,7 +727,7 @@ mod tests { write_le_u16(img, base + EXPO_TRAS, tras); } - /// A small no_std sink so [`fmt::Display`] output can be asserted without + /// A small `no_std` sink so [`fmt::Display`] output can be asserted without /// `alloc`, mirroring the helper in the module-specific tests. struct Sink { data: [u8; 16], diff --git a/spdr/tests/module.rs b/spdr/tests/module.rs index 4bd474c..100130a 100644 --- a/spdr/tests/module.rs +++ b/spdr/tests/module.rs @@ -4,7 +4,7 @@ //! This adds a new module-specific snapshot and leaves the Phase 1, 2, and 3 //! snapshots untouched. The snapshot locks the unbuffered decode against //! regression; it does not prove correctness, which is verified at review against -//! an independent decoder's physical-attribute readout (DDR5SPDEditor) and the +//! an independent decoder's physical-attribute readout (`DDR5SPDEditor`) and the //! part's mechanical datasheet. use spdr::{DecodeError, ModuleSpecific, ModuleType, decode_module_specific}; diff --git a/spdr/tests/robustness.rs b/spdr/tests/robustness.rs index bd60944..3316604 100644 --- a/spdr/tests/robustness.rs +++ b/spdr/tests/robustness.rs @@ -83,26 +83,26 @@ fn every_truncation_returns_ok_or_truncated() { let truncated = &FIXTURE[..len]; assert_ok_or_truncated( - spdr::decode_identity_and_base(truncated), + &spdr::decode_identity_and_base(truncated), len, "identity and base", ); - assert_ok_or_truncated(spdr::verify_base_crc(truncated), len, "base CRC"); + assert_ok_or_truncated(&spdr::verify_base_crc(truncated), len, "base CRC"); // `crc16` returns a plain `u16` and cannot error; exercise it for the // panic check only. let _ = spdr::crc16(truncated); - assert_ok_or_truncated(spdr::decode_timings(truncated), len, "timings"); + assert_ok_or_truncated(&spdr::decode_timings(truncated), len, "timings"); assert_ok_or_truncated( - spdr::decode_module_specific(truncated), + &spdr::decode_module_specific(truncated), len, "module-specific", ); - assert_ok_or_truncated(spdr::decode_manufacturing(truncated), len, "manufacturing"); + assert_ok_or_truncated(&spdr::decode_manufacturing(truncated), len, "manufacturing"); // The vendor regions read past the bytes the base block covers, so most // prefixes are `Truncated`; a present-magic region either reads fully // (`Ok`) or runs off the end (`Truncated`), never another variant. - assert_ok_or_truncated(spdr::decode_xmp(truncated), len, "XMP"); - assert_ok_or_truncated(spdr::decode_expo(truncated), len, "EXPO"); + assert_ok_or_truncated(&spdr::decode_xmp(truncated), len, "XMP"); + assert_ok_or_truncated(&spdr::decode_expo(truncated), len, "EXPO"); } } @@ -111,7 +111,7 @@ fn every_truncation_returns_ok_or_truncated() { /// (the remaining bytes are all valid), and a panic would already have aborted /// the test before this returned. fn assert_ok_or_truncated( - result: Result, + result: &Result, len: usize, decoder: &str, ) { From 663a30f2d241e98892d190ebede7d65ae57d5aa7 Mon Sep 17 00:00:00 2001 From: Dan Alec Date: Fri, 16 Oct 2026 17:43:52 -0300 Subject: [PATCH 2/5] chore: gate rustdoc, deny a curated pedantic set, and correct the fuzz blocker The gate gains a rustdoc step, because doc breakage was invisible to it: bit-range notation in field docs (`bits [7:5]`) parsed as intra-doc links, so every rendered field doc was a broken link, and one public doc pointed at a private item. Both are now fixed and cannot regress silently. A curated set of `clippy::pedantic` lints moves to `deny` at the workspace level, covering exactly the classes this pass found: silent narrowing, missing `# Errors`, unbackticked identifiers, `&Option` arguments, and needless pass-by-value. It stays curated rather than blanket so a future upstream lint cannot break CI on a toolchain bump. `ref_option` postdates the MSRV; plain `rustc` ignores `clippy::*` names entirely, so MSRV builds are unaffected. The fuzz harness documentation claimed the fuzz crate "cannot link" on Windows MSVC. That was wrong, and now says what is actually true: it compiles and links, and the resulting binary fails to load on its `clang_rt.asan_dynamic-x86_64.dll` import (exit `STATUS_DLL_NOT_FOUND`, then `STATUS_ENTRYPOINT_NOT_FOUND` with LLVM's runtime on `PATH`, and LNK1120 with `CC=clang CXX=clang++`). The attempt is recorded in the phase ledger rather than left as a silently blank row, and `spdr/fuzz/Cargo.lock` is committed so the harness resolves reproducibly. The README still says "property-tested, not fuzzed", which remains the honest state: the deep run is still owed on a Linux or WSL host. --- .github/workflows/ci.yml | 9 +- CHANGELOG.md | 39 ++++++++ Cargo.toml | 14 +++ .../2026-06-05-phase-6-robustness.md | 39 ++++++-- spdr/fuzz/Cargo.lock | 94 +++++++++++++++++++ spdr/fuzz/Cargo.toml | 18 ++-- 6 files changed, 196 insertions(+), 17 deletions(-) create mode 100644 spdr/fuzz/Cargo.lock diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7407e1c..ac91b1a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,7 @@ on: jobs: check: - name: fmt · clippy · test + name: fmt · clippy · doc · test runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -28,5 +28,12 @@ jobs: - name: Clippy run: cargo clippy --workspace --all-targets -- -D warnings + # Rustdoc warnings (broken intra-doc links, missing `# Errors` sections + # under the denied clippy lints) are build failures here too. `--lib` keeps + # the doc set to the two library APIs and dodges the known output-filename + # collision between the `spdr` lib and the `spdr` binary (cargo#6313). + - name: Docs + run: RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --lib + - name: Test run: cargo test --workspace diff --git a/CHANGELOG.md b/CHANGELOG.md index dc0d514..b2dcb6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,45 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +Quality and documentation pass over the shipped surface. No public API change +and no decoded-output change: every test and snapshot passes unchanged. + +### Added + +- Regression tests for the two saturation guards and the supported-CAS bit + domain, so the silent-narrowing fix above cannot come back unnoticed: each was + confirmed to fail against the previous `as` cast (it reported a wrapped `CL5` + instead of a saturated one). +- 29 pure decoders and accessors marked `const fn`, so a constant SPD byte can be + decoded at compile time — the point of an embeddable `no_std` crate. +- An explicit `# Errors` section on every public `Result`-returning function, + and a curated set of `clippy::pedantic` lints (silent-cast, doc, and argument + idioms) denied at the workspace level, so the classes of issue fixed here + cannot silently regress. CI now also builds rustdoc with `-D warnings`. + +### Fixed + +- The documented reason the fuzz harness "cannot link on Windows" was wrong: it + does compile and link under MSVC, then fails to load on the + `clang_rt.asan_dynamic-x86_64.dll` import. Corrected in + `spdr/fuzz/Cargo.toml` and the Phase 6 report, with the attempt recorded in + the deep-run ledger instead of left silently blank. +- Rustdoc parsed bit-range notation in doc comments (`bits [7:5]`) as + intra-doc links, so every rendered field doc was a broken link; the notation + is now escaped and renders exactly as written. Caught by the new doc gate. +- The two internal CAS-latency derivations (the linter's supported-set check and + the vendor-profile rated CL) narrowed `u32` quotients to `u16` with an + unchecked `as`. The quotient always fit for decoded SPD bytes, but the + narrowing is now explicit and saturating instead of wrapping for out-of-range + hand-built values. +- The supported-CAS mask arithmetic and the reference-raw-card `Display` used + unchecked narrowing casts on a constant bit count and on array-length + indexing; both now compute in one integer domain, with a compile-time check + tying the mask bit count to its byte count. +- A rustdoc warning: a public doc link to a private item in `spdr-cli`. + ## [0.1.1] - 2026-09-16 Metadata only. No code, no API change, no behaviour change from 0.1.0. diff --git a/Cargo.toml b/Cargo.toml index 7d2b6c1..3a5195b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,3 +18,17 @@ unsafe_code = "forbid" [workspace.lints.clippy] all = "deny" +# A curated set from `clippy::pedantic`: each of these caught a real issue in +# this codebase (silent `as` narrowing, undocumented `Result` errors, +# undocumented identifiers in docs, `&Option` arguments, needless +# pass-by-value). Kept curated rather than a blanket `pedantic` so a future +# upstream pedantic lint cannot break CI on a toolchain bump. `ref_option` +# postdates the 1.85 MSRV; plain `rustc` ignores `clippy::*` names entirely, so +# MSRV builds are unaffected (only clippy runs on pre-1.87 toolchains warn). +bool_to_int_with_if = "deny" +cast_possible_truncation = "deny" +doc_markdown = "deny" +missing_errors_doc = "deny" +needless_pass_by_value = "deny" +ref_option = "deny" +trivially_copy_pass_by_ref = "deny" diff --git a/docs/implementations/2026-06-05-phase-6-robustness.md b/docs/implementations/2026-06-05-phase-6-robustness.md index 9d34733..9bc8164 100644 --- a/docs/implementations/2026-06-05-phase-6-robustness.md +++ b/docs/implementations/2026-06-05-phase-6-robustness.md @@ -24,10 +24,15 @@ Two tools, split by where they can run: - **proptest** lives in the gate. It runs on Windows and in CI and is the always-on check. No CI workflow change is needed: the new properties are ordinary `#[test]`s and ride into the existing `cargo test` job. -- **cargo-fuzz** is committed as a harness but is **not built or run here**. - libFuzzer needs a clang/LLVM toolchain (Linux or WSL) that Windows MSVC does - not provide, so the fuzz crate cannot link on this machine. It is scaffolded, - rustfmt-clean, and ready for Mert to run on Linux. No fuzz result is claimed. +- **cargo-fuzz** is committed as a harness but is **not run here**, and cannot + run on this machine. Measured rather than assumed: `cargo fuzz build + decode_all` does compile and link under Windows MSVC, but the resulting + binary imports `clang_rt.asan_dynamic-x86_64.dll`, so it exits + `STATUS_DLL_NOT_FOUND` (0xC0000135) when that runtime is not on `PATH` and + `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) when LLVM's copy is; forcing + `CC=clang CXX=clang++` fails to link instead (LNK1120, unresolved external). + The harness is scaffolded, rustfmt-clean, and ready for Mert to run on Linux. + No fuzz result is claimed. ## What Changed @@ -122,10 +127,11 @@ capturing the shrunk input, never a weakening of the property. - **proptest in the gate, cargo-fuzz committed-but-not-run.** The split follows what each tool needs. proptest is pure Rust and runs anywhere `cargo test` - does, so it is the always-on regression guard. libFuzzer needs clang/LLVM and - does not link under Windows MSVC, so the fuzz harness is scaffolded and - rustfmt-clean but deliberately not built here. The report states the fuzz crate - was not run rather than implying a fuzz result. + does. proptest is pure Rust and runs anywhere `cargo test` + does, so it is the always-on regression guard. libFuzzer's Windows MSVC + support is incomplete in the ways measured above, so the fuzz harness is + scaffolded and rustfmt-clean but deliberately not run here. The report states + the fuzz crate was not run rather than implying a fuzz result. - **A stronger assertion only where the space is finite.** The two proptest properties assert no-panic only, because arbitrary and mutated bytes legitimately produce `UnknownEnum` and `NonAscii`, which are correct outcomes, not failures. @@ -166,8 +172,9 @@ Phase 1 through 5 unit, integration, and snapshot suites are untouched and green ### Fuzzing (Linux / WSL, run manually by Mert) -The fuzz crate is **not built or run on Windows**: libFuzzer cannot link under -MSVC. On a Linux or WSL host with a nightly toolchain and `cargo-fuzz` installed +The fuzz crate is **not run on Windows**: it builds, but its binary cannot load +here (see the measured details in Design Decisions). On a Linux or WSL host with +a nightly toolchain and `cargo-fuzz` installed (`cargo install cargo-fuzz`), from the `spdr/` crate directory: ``` @@ -191,6 +198,18 @@ fixture's decode left unchanged. | --- | --- | --- | --- | --- | --- | | _pending_ | _pending_ | `cargo +nightly fuzz run decode_all -- -max_total_time=` | _pending_ | _pending_ | _pending_ | +Attempted and recorded so the empty row above is not mistaken for an oversight: + +| Date | Host | Command | Result | +| --- | --- | --- | --- | +| 2026-10-16 | Windows 11, MSVC + Scoop LLVM 23 | `cargo +nightly fuzz run decode_all -- -max_total_time=45` | Build and link succeed; the binary then exits `STATUS_DLL_NOT_FOUND` (0xC0000135) on the missing `clang_rt.asan_dynamic-x86_64.dll`, `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) with LLVM's runtime on `PATH`, and `CC=clang CXX=clang++` fails to link (LNK1120). Zero executions, so it earns no fuzz result. | + +The same date's Windows substitute for a deep run is the proptest surface at +raised case counts, which passes on this host: from `spdr/`, +`PROPTEST_CASES=100000 cargo test --release --test robustness` (both properties +plus the exhaustive truncation test; 3 passed in 1.17 s on 2026-10-16). That is +still property-testing, not fuzzing, and the README wording stays accordingly. + Only after a recorded deep run with no crash does the README earn the word "fuzzed" as a completed claim. diff --git a/spdr/fuzz/Cargo.lock b/spdr/fuzz/Cargo.lock new file mode 100644 index 0000000..eb28fc7 --- /dev/null +++ b/spdr/fuzz/Cargo.lock @@ -0,0 +1,94 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "spdr" +version = "0.1.1" + +[[package]] +name = "spdr-fuzz" +version = "0.0.0" +dependencies = [ + "libfuzzer-sys", + "spdr", +] diff --git a/spdr/fuzz/Cargo.toml b/spdr/fuzz/Cargo.toml index e3670ad..610f5c7 100644 --- a/spdr/fuzz/Cargo.toml +++ b/spdr/fuzz/Cargo.toml @@ -1,11 +1,17 @@ # cargo-fuzz harness for the `spdr` decoders. # -# This is committed but is NOT built or run by the Windows gate: libFuzzer needs -# a clang/LLVM (Linux or WSL) toolchain that Windows MSVC does not provide, so it -# cannot link here. The empty `[workspace]` table makes `fuzz/` its own workspace -# root, so the parent's `cargo ... --workspace` never sees this package. Mert runs -# it manually on Linux; see -# `docs/implementations/2026-06-05-phase-6-robustness.md` for the invocation. +# This is committed but is NOT run by the Windows gate, and it cannot run on a +# stock Windows MSVC toolchain. Measured, not assumed: `cargo fuzz build +# decode_all` DOES compile and link here, but the resulting binary imports +# `clang_rt.asan_dynamic-x86_64.dll`, so it exits `STATUS_DLL_NOT_FOUND` +# (0xC0000135) when that runtime is not on PATH, and +# `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) when LLVM's copy is; rebuilding +# with `CC=clang CXX=clang++` fails to link instead (LNK1120, unresolved +# external). So the deep run belongs on Linux or WSL. The empty `[workspace]` +# table makes `fuzz/` its own workspace root, so the parent's `cargo ... +# --workspace` never sees this package. See +# `docs/implementations/2026-06-05-phase-6-robustness.md` for the invocation and +# the deep-run ledger. [package] name = "spdr-fuzz" version = "0.0.0" From fd92f40a78833ffcdf0565af6fe52c497f1f1e40 Mon Sep 17 00:00:00 2001 From: Dan Alec Date: Sun, 25 Oct 2026 15:03:29 -0300 Subject: [PATCH 3/5] fix(core): address the PR #1 review with explicit rounding and honest claims The review asked for prose corrections, three code changes, and a documentation trail. All of it is in this commit. Code: - `vendor::rated_cas_latency` computes the round-to-nearest in `u64`, so the rounding stays exact across the whole `u32` input range instead of saturating the add and rounding down. Only the final narrowing to `u16` saturates. New test: `rated_cas_latency_rounds_in_u64`. - `identity::decode_module_type` and `timing::data_rate_mt_s` go back to `pub(crate)`. The pass had widened them to `pub`, which left the boundary to a comment instead of the compiler. `const` is kept. - The CLI exit code is `if results.all_decoded() { 0 } else { 1 }` again. `bool_to_int_with_if` is dropped from the workspace deny list: it is a style lint that forbids the branch form and asks for `i32::from(!ok)`, so its only effect here was to force the less readable expression. Claims corrected, each against a measurement recorded in `docs/numerical-claims.md`: - 31 functions became `const fn` (27 in `spdr`, 4 in `spdr-cli`), and every one of them is crate-internal or an accessor: no public `decode_*` entry point is `const`. - Six public items gained `const`, so the change is additive rather than "no public API change". - The two saturation tests were confirmed to fail against the previous `as` cast; the bit-domain test is a characterization test, since the base arithmetic was already correct. - The rendered documentation was never broken: on the base `6b0d2d5` the bit-range text is plain text and no occurrence is wrapped in an `` element. The defect was the 22 rustdoc warnings, which the new `-D warnings` gate turns into a build failure. - `ref_option` is not newer than the MSRV: clippy 1.85.1 reports it as implied by `clippy::pedantic`. Trails: - `docs/numerical-claims.md` records every number above with its source. - `docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md` is the dated note for this change. - The Phase 6 report keeps its dated June rationale and gains a dated addendum for the measured Windows fuzz failure mode, instead of the rationale being rewritten in place. No decoded output changes. `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --lib`, `cargo build -p spdr` and `cargo test --workspace` are all clean. --- .github/workflows/ci.yml | 5 +- CHANGELOG.md | 29 ++-- Cargo.toml | 16 +- .../2026-06-05-phase-6-robustness.md | 55 ++++--- ...026-10-25-narrowing-const-and-doc-gates.md | 148 ++++++++++++++++++ docs/numerical-claims.md | 30 ++++ spdr-cli/src/lib.rs | 2 +- spdr/src/identity.rs | 66 ++++---- spdr/src/module.rs | 20 +-- spdr/src/timing.rs | 9 +- spdr/src/vendor.rs | 22 ++- 11 files changed, 312 insertions(+), 90 deletions(-) create mode 100644 docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ac91b1a..d4dd79a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,8 +28,9 @@ jobs: - name: Clippy run: cargo clippy --workspace --all-targets -- -D warnings - # Rustdoc warnings (broken intra-doc links, missing `# Errors` sections - # under the denied clippy lints) are build failures here too. `--lib` keeps + # Rustdoc warnings (broken intra-doc links) are build failures here too. + # Missing `# Errors` sections are caught by the Clippy step above, through + # the denied `missing_errors_doc` lint. `--lib` keeps # the doc set to the two library APIs and dodges the known output-filename # collision between the `spdr` lib and the `spdr` binary (cargo#6313). - name: Docs diff --git a/CHANGELOG.md b/CHANGELOG.md index b2dcb6b..d759656 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,17 +6,26 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] -Quality and documentation pass over the shipped surface. No public API change -and no decoded-output change: every test and snapshot passes unchanged. +Quality and documentation pass over the shipped surface. No decoded-output +change: every test and snapshot passes unchanged. The public API gains `const` +on six accessors, which is additive and therefore a semver commitment: +removing `const` later would be breaking. ### Added +- `const` on six public accessors: `Finding::severity`, `Finding::code`, + `SpdImage::is_empty`, `CasLatencies::contains` and `Timings::base_data_rate_mt_s` + in `spdr`, plus `DecodeResults::all_decoded` in `spdr-cli`. - Regression tests for the two saturation guards and the supported-CAS bit - domain, so the silent-narrowing fix above cannot come back unnoticed: each was - confirmed to fail against the previous `as` cast (it reported a wrapped `CL5` - instead of a saturated one). -- 29 pure decoders and accessors marked `const fn`, so a constant SPD byte can be - decoded at compile time — the point of an embeddable `no_std` crate. + domain, so the silent-narrowing fix below cannot come back unnoticed. The + two saturation tests were confirmed to fail against the previous `as` cast + (they reported a wrapped `CL5` instead of a saturated one). The bit-domain + test is a characterization test: the base arithmetic was already correct, so + it pins the behaviour rather than catching a regression. +- 31 pure decoders and accessors marked `const fn` (27 in `spdr`, 4 in + `spdr-cli`). All of them are crate-internal helpers or accessors; no public + `decode_*` entry point is `const`, so a downstream user still cannot decode + an SPD image at compile time. - An explicit `# Errors` section on every public `Result`-returning function, and a curated set of `clippy::pedantic` lints (silent-cast, doc, and argument idioms) denied at the workspace level, so the classes of issue fixed here @@ -30,8 +39,10 @@ and no decoded-output change: every test and snapshot passes unchanged. `spdr/fuzz/Cargo.toml` and the Phase 6 report, with the attempt recorded in the deep-run ledger instead of left silently blank. - Rustdoc parsed bit-range notation in doc comments (`bits [7:5]`) as - intra-doc links, so every rendered field doc was a broken link; the notation - is now escaped and renders exactly as written. Caught by the new doc gate. + intra-doc links, so `cargo doc` warned on every such field. The notation is + now written as a code span, which rustdoc does not link, and renders exactly + as written. The rendered documentation was correct before and after; the + defect was the warnings, which the new doc gate turns into a build failure. - The two internal CAS-latency derivations (the linter's supported-set check and the vendor-profile rated CL) narrowed `u32` quotients to `u16` with an unchecked `as`. The quotient always fit for decoded SPD bytes, but the diff --git a/Cargo.toml b/Cargo.toml index 3a5195b..d7724e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,14 +18,16 @@ unsafe_code = "forbid" [workspace.lints.clippy] all = "deny" -# A curated set from `clippy::pedantic`: each of these caught a real issue in -# this codebase (silent `as` narrowing, undocumented `Result` errors, +# A curated set from `clippy::pedantic`, each entry naming a class this pass +# found a real issue of: silent `as` narrowing, undocumented `Result` errors, # undocumented identifiers in docs, `&Option` arguments, needless -# pass-by-value). Kept curated rather than a blanket `pedantic` so a future -# upstream pedantic lint cannot break CI on a toolchain bump. `ref_option` -# postdates the 1.85 MSRV; plain `rustc` ignores `clippy::*` names entirely, so -# MSRV builds are unaffected (only clippy runs on pre-1.87 toolchains warn). -bool_to_int_with_if = "deny" +# pass-by-value. Kept curated rather than a blanket `pedantic` so a future +# upstream pedantic lint cannot break CI on a toolchain bump. `ref_option` is +# not newer than the MSRV: clippy 1.85.1 reports it as implied by `pedantic`, +# so the 1.85 toolchain resolves it. `bool_to_int_with_if` was dropped: it is a +# style lint that forbids `if ok { 0 } else { 1 }` and asks for +# `i32::from(!ok)` instead, so its only effect here was to force a less +# readable exit-code expression. cast_possible_truncation = "deny" doc_markdown = "deny" missing_errors_doc = "deny" diff --git a/docs/implementations/2026-06-05-phase-6-robustness.md b/docs/implementations/2026-06-05-phase-6-robustness.md index 9bc8164..456ed76 100644 --- a/docs/implementations/2026-06-05-phase-6-robustness.md +++ b/docs/implementations/2026-06-05-phase-6-robustness.md @@ -24,15 +24,11 @@ Two tools, split by where they can run: - **proptest** lives in the gate. It runs on Windows and in CI and is the always-on check. No CI workflow change is needed: the new properties are ordinary `#[test]`s and ride into the existing `cargo test` job. -- **cargo-fuzz** is committed as a harness but is **not run here**, and cannot - run on this machine. Measured rather than assumed: `cargo fuzz build - decode_all` does compile and link under Windows MSVC, but the resulting - binary imports `clang_rt.asan_dynamic-x86_64.dll`, so it exits - `STATUS_DLL_NOT_FOUND` (0xC0000135) when that runtime is not on `PATH` and - `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) when LLVM's copy is; forcing - `CC=clang CXX=clang++` fails to link instead (LNK1120, unresolved external). - The harness is scaffolded, rustfmt-clean, and ready for Mert to run on Linux. - No fuzz result is claimed. +- **cargo-fuzz** is committed as a harness but is **not built or run here**. + libFuzzer needs a clang/LLVM toolchain (Linux or WSL) that Windows MSVC does + not provide, so the fuzz crate cannot link on this machine (corrected + 2026-10-16: see the addendum below). It is scaffolded, rustfmt-clean, and + ready for Mert to run on Linux. No fuzz result is claimed. ## What Changed @@ -127,11 +123,11 @@ capturing the shrunk input, never a weakening of the property. - **proptest in the gate, cargo-fuzz committed-but-not-run.** The split follows what each tool needs. proptest is pure Rust and runs anywhere `cargo test` - does. proptest is pure Rust and runs anywhere `cargo test` - does, so it is the always-on regression guard. libFuzzer's Windows MSVC - support is incomplete in the ways measured above, so the fuzz harness is - scaffolded and rustfmt-clean but deliberately not run here. The report states - the fuzz crate was not run rather than implying a fuzz result. + does, so it is the always-on regression guard. libFuzzer needs clang/LLVM and + does not link under Windows MSVC (corrected 2026-10-16: see the addendum + below), so the fuzz harness is scaffolded and rustfmt-clean but deliberately + not built here. The report states the fuzz crate was not run rather than + implying a fuzz result. - **A stronger assertion only where the space is finite.** The two proptest properties assert no-panic only, because arbitrary and mutated bytes legitimately produce `UnknownEnum` and `NonAscii`, which are correct outcomes, not failures. @@ -172,9 +168,9 @@ Phase 1 through 5 unit, integration, and snapshot suites are untouched and green ### Fuzzing (Linux / WSL, run manually by Mert) -The fuzz crate is **not run on Windows**: it builds, but its binary cannot load -here (see the measured details in Design Decisions). On a Linux or WSL host with -a nightly toolchain and `cargo-fuzz` installed +The fuzz crate is **not built or run on Windows**: libFuzzer cannot link under +MSVC (corrected 2026-10-16: see the addendum below). On a Linux or WSL host +with a nightly toolchain and `cargo-fuzz` installed (`cargo install cargo-fuzz`), from the `spdr/` crate directory: ``` @@ -202,14 +198,35 @@ Attempted and recorded so the empty row above is not mistaken for an oversight: | Date | Host | Command | Result | | --- | --- | --- | --- | -| 2026-10-16 | Windows 11, MSVC + Scoop LLVM 23 | `cargo +nightly fuzz run decode_all -- -max_total_time=45` | Build and link succeed; the binary then exits `STATUS_DLL_NOT_FOUND` (0xC0000135) on the missing `clang_rt.asan_dynamic-x86_64.dll`, `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) with LLVM's runtime on `PATH`, and `CC=clang CXX=clang++` fails to link (LNK1120). Zero executions, so it earns no fuzz result. | +| 2026-10-16 | Windows 11 x86_64, MSVC + Scoop LLVM 23 (run by `danalec`, the PR #1 author) | `cargo +nightly fuzz run decode_all -- -max_total_time=45` | Build and link succeed; the binary then exits `STATUS_DLL_NOT_FOUND` (0xC0000135) on the missing `clang_rt.asan_dynamic-x86_64.dll`, `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) with LLVM's runtime on `PATH`, and `CC=clang CXX=clang++` fails to link (LNK1120). Zero executions, so it earns no fuzz result. | The same date's Windows substitute for a deep run is the proptest surface at -raised case counts, which passes on this host: from `spdr/`, +raised case counts, which passes on that host: from `spdr/`, `PROPTEST_CASES=100000 cargo test --release --test robustness` (both properties plus the exhaustive truncation test; 3 passed in 1.17 s on 2026-10-16). That is still property-testing, not fuzzing, and the README wording stays accordingly. +## Addendum · 2026-10-16 · the fuzz harness on Windows, measured + +The June rationale above says the fuzz crate "cannot link on this machine". +That was wrong. The correction is recorded here, dated, rather than rewritten +into the June text. + +Measured on Windows 11 x86_64 with MSVC and Scoop LLVM 23, by `danalec` (the +author of PR #1): `cargo +nightly fuzz build decode_all` **does compile and +link**. The failure comes one step later, at load time. + +| Variant | Outcome | +| --- | --- | +| Default (MSVC) | `STATUS_DLL_NOT_FOUND` (0xC0000135), on the missing `clang_rt.asan_dynamic-x86_64.dll` import | +| LLVM's runtime on `PATH` | `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) | +| `CC=clang CXX=clang++` | fails to link instead: LNK1120, unresolved external | + +Zero executions, so this earns no fuzz result. The harness is scaffolded, +rustfmt-clean, and ready for Mert to run on Linux, where the deep run is still +owed. The README keeps saying "property-tested, not fuzzed" until a recorded +deep run lands. + Only after a recorded deep run with no crash does the README earn the word "fuzzed" as a completed claim. diff --git a/docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md b/docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md new file mode 100644 index 0000000..905d232 --- /dev/null +++ b/docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md @@ -0,0 +1,148 @@ +# Quality pass · narrowing, `const`, and the doc gate + +A behaviour-preserving pass over the shipped surface, dated 2026-10-25 and +reviewed upstream in PR #1. No decoded output changed and every golden snapshot +passes byte for byte. Three things are worth recording here because each is +meaningful on its own: a CI gate that did not exist, a workspace lint policy, +and a numeric-behaviour change. + +Every number quoted here is traced in `docs/numerical-claims.md`. + +## Problem / Motivation + +The core crate is `#![forbid(unsafe_code)]` and never panics, so its +interesting failure mode is not a crash but a **wrong value**. Two failure +classes were open: + +1. **Silent narrowing.** A wider integer was narrowed to a narrower one with an + unchecked `as`. For decoded bytes every such quotient fits, so the casts + were safe in practice and fragile in principle: the invariant lived in a + comment instead of in the code, and a hand-built out-of-range value could + wrap to a plausible-looking number. +2. **Invisible doc breakage.** `cargo doc` was not run anywhere, so rustdoc + warnings could not fail a build. On the base `6b0d2d5` the doc build emits + 22 warnings: 21 unresolved bit-range links in `spdr` and one public doc link + to a private item in `spdr-cli`. + +## What Changed + +### The CI gate + +CI now builds the documentation with warnings as errors: + +```yaml +- name: Docs + run: RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --lib +``` + +`--lib` keeps the doc set to the two library APIs and dodges the known +output-filename collision between the `spdr` library and the `spdr` binary +(cargo#6313). + +### The workspace lint policy + +`[workspace.lints.clippy]` denies a curated set from `clippy::pedantic`: +`cast_possible_truncation`, `missing_errors_doc`, `doc_markdown`, +`ref_option`, `needless_pass_by_value`, `trivially_copy_pass_by_ref` and +`bool_to_int_with_if`. Curated rather than blanket, so that a future upstream +pedantic lint cannot break CI on a toolchain bump. + +Two facts about that set were measured rather than assumed, and both corrected +claims made earlier in the review: + +- `ref_option` is **not** newer than the MSRV. Clippy 1.85.1 reports it as + implied by `clippy::pedantic`, and an invented lint name on the same + toolchain gives `error[E0602]: unknown lint`, so the name is resolved rather + than ignored. +- `bool_to_int_with_if` fires on the *readable* branch form, + `if ok { 0 } else { 1 }`, and asks for `i32::from(!ok)` instead. It is a + style guard with no bearing on a wrong value, and its only effect here was + to force a less readable exit-code expression, so it was dropped from the + workspace deny list and the branch form kept. + +### The numeric-behaviour change + +Two CAS-latency derivations narrowed a `u32` quotient to `u16`. They now +narrow explicitly and saturate, so an out-of-range hand-built value cannot +wrap. The wrap case was a plausible latency: 65541 cycles came out as CL5, +which would have been reported as a real value. + +The rated-CL derivation computes its round-to-nearest in `u64` rather than in +`u32`, so the rounding stays exact across the whole `u32` input range instead +of saturating the add and rounding down. Only the final narrowing to `u16` +saturates. + +The supported-CAS mask arithmetic now computes its bit index in a single +integer domain, with a compile-time assertion tying the bit count to the byte +count it derives from. The reference-raw-card `Display` no longer casts the +alphabet length or the array indices. + +### `const` and the public API + +31 pure decoders and accessors are now `const fn` (27 in `spdr`, 4 in +`spdr-cli`). Every one of them is a crate-internal helper or an accessor: no +public `decode_*` entry point is `const`, so a downstream user still cannot +decode an SPD image at compile time. + +Six public items did gain `const`, which is additive and therefore a semver +commitment: `Finding::severity`, `Finding::code`, `SpdImage::is_empty`, +`CasLatencies::contains` and `Timings::base_data_rate_mt_s` in `spdr`, plus +`DecodeResults::all_decoded` in `spdr-cli`. Removing `const` later would be +breaking. + +Two crate-internal helpers had their visibility widened from `pub(crate)` to +`pub` during the pass. That was reverted: the compiler enforced the boundary, +a comment does not, and a future `pub use identity::*` would otherwise export +them silently. `const` was kept. + +### Documentation completeness + +Every public `Result`-returning function has an explicit `# Errors` section, +and identifiers in prose are backticked. Bit-range notation in doc comments +is written as a code span (`[7:5]`) rather than an escape, which rustdoc does +not turn into an intra-doc link and which reads cleanly in a crate whose source +is meant to be the open reference. + +## Design Decisions + +- **Curated lints, not blanket `pedantic`.** A blanket set means any new + upstream lint breaks CI on a toolchain bump, which is a maintenance tax the + project does not need. The curated set names the classes this pass actually + found. +- **Saturation, not wrapping.** A narrow cast that saturates is wrong on + out-of-range input; a narrow cast that wraps is wrong *and* plausible. When + the value cannot fit, reporting the maximum is the honest answer. +- **`u64` for the intermediate.** Widening the add and the divide costs + nothing on a `no_std` target and removes a rounding error that only shows up + near the top of the `u32` range. +- **The bit-domain test is a characterization test.** The base arithmetic was + already correct, so the test pins the behaviour rather than catching a + regression. The two saturation tests are genuine regression tests: both were + confirmed to fail against the previous `as` cast. +- **The README wording is unchanged.** It still says *property-tested, not + fuzzed*. The deep run is still owed on a Linux or WSL host; on Windows the + harness never reached a single execution. The on-box substitute is + `PROPTEST_CASES=100000 cargo test --release --test robustness`, which is + property-testing, not fuzzing. + +## Verification + +- `cargo fmt --check` · clean. +- `cargo clippy --workspace --all-targets -- -D warnings` · clean. +- `cargo clippy --workspace --all-targets -- -W clippy::pedantic` · zero + warnings. +- `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --lib` · clean. +- `cargo build -p spdr` · clean, the existing `no_std` guard. +- `cargo test --workspace` · the full suite passing. +- MSRV 1.85.1: `cargo build -p spdr`, the clippy gate, and the full test suite + all clean. + +The rendered documentation was correct before this pass and is correct after it. +What changed is that the warnings are gone and the build now fails on them. + +## Related Docs + +- `docs/numerical-claims.md` · every number quoted above, with its source. +- `docs/implementations/2026-06-05-phase-6-robustness.md` · the fuzz harness + and its measured Windows failure mode, with the 2026-10-16 addendum. +- `CHANGELOG.md` · the user-facing summary of the same change. diff --git a/docs/numerical-claims.md b/docs/numerical-claims.md index 727eb19..da963d5 100644 --- a/docs/numerical-claims.md +++ b/docs/numerical-claims.md @@ -198,3 +198,33 @@ Two reference-declared-reserved regions are deliberately excluded: `reserved_240 | monolithic package carries exactly one die; DDP/3DS carries more than one | Error | monolithic, 1 die | yes | Pinned to the JEDEC byte-4 package-type encoding Phase 1 decodes (and edlf's `sdram1Density` package bits). The current decode derives `package_type` and `die_count` from the same byte-4 bits, so the relationship holds by construction and the rule is a defense-in-depth invariant guard; it is exercised by a directly-constructed incoherent geometry in the unit tests. + +## Quality pass · narrowing, `const`, and the doc gate (2026-10-16) + +A behaviour-preserving pass over the shipped surface: no decoded output changed, and every golden snapshot passes byte for byte. + +### Counts measured from the diff + +| Claim | Value | Source | +| --- | --- | --- | +| Functions marked `const fn` | 31 (27 in `spdr`, 4 in `spdr-cli`) | Measured: `git diff 6b0d2d5 663a30f -U0 -- '*.rs'`, counting added lines matching `const fn`. Per file: `identity.rs` 14, `module.rs` 4, `manufacturing.rs` 3, `timing.rs` 3, `lint.rs` 2, `reader.rs` 1, `spdr-cli/src/lib.rs` 4. | +| Public items that gained `const` | 6 | Measured: `Finding::severity`, `Finding::code`, `SpdImage::is_empty`, `CasLatencies::contains`, `Timings::base_data_rate_mt_s` (in `spdr`), and `DecodeResults::all_decoded` (in `spdr-cli`). Additive, so removing `const` afterwards would be a breaking change. | +| Public `decode_*` entry points that are `const` | 0 | Measured: no `pub const fn decode_*` exists; every decoder marked `const` is crate-internal, so a downstream user still cannot decode an SPD image at compile time. | +| Rustdoc warnings on the base `6b0d2d5` | 22 | Measured: `cargo doc --workspace --no-deps --lib` in a worktree at `6b0d2d5` · 21 unresolved bit-range link warnings in `spdr`, plus one public-doc-link-to-private-item warning in `spdr-cli` (`lint_exit_code` links to the private `run_lint`). | +| Bit-range links in the base rendered HTML | 0 | Measured: the rendered `bits [7:5]` text appears in the generated pages, and no occurrence is wrapped in an `` element. The base output was therefore correct; the defect was the warnings, which the new `-D warnings` gate turns into a build failure. | + +### Toolchain measurements + +| Claim | Value | Source | +| --- | --- | --- | +| `ref_option` in the MSRV toolchain | known to clippy 1.85.1, and implied by `clippy::pedantic` | Measured: on a probe crate, `cargo +1.85.1 clippy -- -W clippy::pedantic` reports ``-W clippy::ref-option` implied by `-W clippy::pedantic`; an invented lint name on the same toolchain gives `error[E0602]: unknown lint`, so the name is resolved rather than ignored. | +| `bool_to_int_with_if` against the CLI's bool-to-int form | fires on the branch form, not on `i32::from(!flag)` | Measured: clippy 0.1.99 reports "boolean to int conversion using if" for `if results.all_decoded() { 0 } else { 1 }` and asks for `i32::from(!results.all_decoded())` instead; the `i32::from(!flag)` form raises no warning on clippy 1.85.1 or on clippy 0.1.99. It is a style guard with no bearing on a wrong value, so it was dropped from the workspace deny list and the readable branch form kept. | + +### Runs recorded in the deep-run ledger + +| Claim | Value | Source | +| --- | --- | --- | +| Proptest substitute run | `PROPTEST_CASES=100000 cargo test --release --test robustness` · 3 passed in 1.17 s | Measured on 2026-10-16, Windows 11 x86_64, by `danalec`; recorded in the Phase 6 deep-run ledger. This is property-testing, not fuzzing. | +| Fuzz attempt, zero executions | `cargo +nightly fuzz run decode_all -- -max_total_time=45` | Measured on 2026-10-16, Windows 11 x86_64, MSVC + Scoop LLVM 23, by `danalec`: it builds and links, then exits `STATUS_DLL_NOT_FOUND` (0xC0000135) on the missing `clang_rt.asan_dynamic-x86_64.dll`; `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) with LLVM's runtime on `PATH`; `CC=clang CXX=clang++` fails to link with LNK1120. Zero executions, so it earns no fuzz result. | +| CLI exit codes | `decode` 0 / 1 / 2 · `lint` 0 / 1 / 2 | Asserted by the `spdr-cli` integration tests (`decode_fixture_exits_zero`, `decode_truncated_file_exits_one_with_partial_output`, `decode_nonexistent_path_exits_two_with_stderr`, and the `lint` equivalents). Unchanged by this pass. | +| Round-to-nearest at the `u32` ceiling | `u32::MAX` ps over `2^31` ps rounds to 2 | Arithmetic in `u64`: `(4294967295 + 1073741824) / 2147483648` is 2, where the previous saturating `u32` add gave 1. Asserted by `rated_cas_latency_rounds_in_u64`. | diff --git a/spdr-cli/src/lib.rs b/spdr-cli/src/lib.rs index 4aa26b4..3eab450 100644 --- a/spdr-cli/src/lib.rs +++ b/spdr-cli/src/lib.rs @@ -159,7 +159,7 @@ fn run_decode(args: &DecodeArgs) -> i32 { }; println!("{rendered}"); - i32::from(!results.all_decoded()) + if results.all_decoded() { 0 } else { 1 } } // --- Lint surface ---------------------------------------------------------- diff --git a/spdr/src/identity.rs b/spdr/src/identity.rs index f6b619b..383e05b 100644 --- a/spdr/src/identity.rs +++ b/spdr/src/identity.rs @@ -154,7 +154,7 @@ impl DensityPerDie { } } -/// SDRAM I/O device width (DQ pins per device), from bits \[7:5\] of byte 6. +/// SDRAM I/O device width (DQ pins per device), from bits `[7:5]` of byte 6. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum IoWidth { @@ -177,7 +177,7 @@ impl IoWidth { } } -/// Number of bank groups per die, from bits \[7:5\] of byte 7. +/// Number of bank groups per die, from bits `[7:5]` of byte 7. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum BankGroups { @@ -200,7 +200,7 @@ impl BankGroups { } } -/// Number of banks within each bank group, from bits \[2:0\] of byte 7. +/// Number of banks within each bank group, from bits `[2:0]` of byte 7. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum BanksPerBankGroup { @@ -221,7 +221,7 @@ impl BanksPerBankGroup { } } -/// SDRAM package construction, from bits \[7:5\] of byte 4. +/// SDRAM package construction, from bits `[7:5]` of byte 4. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum PackageType { @@ -258,7 +258,7 @@ impl fmt::Display for PackageType { #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct IdentityAndBase { - /// Total addressable size of the SPD device in bytes (byte 0, bits \[6:4\]). + /// Total addressable size of the SPD device in bytes (byte 0, bits `[6:4]`). pub spd_bytes_total: u16, /// SPD revision (byte 1). pub spd_revision: SpdRevision, @@ -268,29 +268,29 @@ pub struct IdentityAndBase { pub module_type: ModuleType, /// Hybrid-module flag (byte 3, bit 7). pub hybrid: bool, - /// SDRAM density per die (byte 4, bits \[4:0\]). + /// SDRAM density per die (byte 4, bits `[4:0]`). pub density_per_die: DensityPerDie, - /// SDRAM package construction (byte 4, bits \[7:5\]). + /// SDRAM package construction (byte 4, bits `[7:5]`). pub package_type: PackageType, - /// Number of dies in the SDRAM package (byte 4, bits \[7:5\]). + /// Number of dies in the SDRAM package (byte 4, bits `[7:5]`). pub die_count: u8, - /// Number of row address bits (byte 5, bits \[4:0\], base 16). + /// Number of row address bits (byte 5, bits `[4:0]`, base 16). pub row_address_bits: u8, - /// Number of column address bits (byte 5, bits \[7:5\], base 10). + /// Number of column address bits (byte 5, bits `[7:5]`, base 10). pub column_address_bits: u8, - /// SDRAM I/O device width (byte 6, bits \[7:5\]). + /// SDRAM I/O device width (byte 6, bits `[7:5]`). pub io_width: IoWidth, - /// Bank groups per die (byte 7, bits \[7:5\]). + /// Bank groups per die (byte 7, bits `[7:5]`). pub bank_groups: BankGroups, - /// Banks per bank group (byte 7, bits \[2:0\]). + /// Banks per bank group (byte 7, bits `[2:0]`). pub banks_per_bank_group: BanksPerBankGroup, - /// Package ranks per channel (byte 234, bits \[5:3\], base 1). + /// Package ranks per channel (byte 234, bits `[5:3]`, base 1). pub package_ranks_per_channel: u8, /// Whether the rank organization is asymmetric (byte 234, bit 6). pub rank_mix_asymmetric: bool, - /// Number of channels (sub-channels) per DIMM (byte 235, bits \[7:5\]). + /// Number of channels (sub-channels) per DIMM (byte 235, bits `[7:5]`). pub channels_per_dimm: u8, - /// Primary bus width per channel in bits (byte 235, bits \[2:0\]). + /// Primary bus width per channel in bits (byte 235, bits `[2:0]`). pub primary_bus_width_bits: u16, } @@ -356,7 +356,7 @@ pub fn decode_identity_and_base(bytes: &[u8]) -> Result Result { match (byte0 >> 4) & 0x07 { 1 => Ok(256), @@ -370,7 +370,7 @@ const fn decode_spd_bytes_total(byte0: u8) -> Result { } } -/// Byte 1: SPD revision as two plain nibbles, major in \[7:4\], minor in \[3:0\]. +/// Byte 1: SPD revision as two plain nibbles, major in `[7:4]`, minor in `[3:0]`. const fn decode_spd_revision(byte1: u8) -> SpdRevision { SpdRevision { major: byte1 >> 4, @@ -392,12 +392,12 @@ const fn decode_device_type(byte2: u8) -> Result { } } -/// Byte 3: base module type in bits \[3:0\]; hybrid flag in bit 7. +/// Byte 3: base module type in bits `[3:0]`; hybrid flag in bit 7. /// -/// Crate-visible (this module is private, so `pub` stays crate-internal) so the -/// module-specific dispatch ([`crate::decode_module_specific`]) routes on the -/// same single decode of byte 3, rather than duplicating it. -pub const fn decode_module_type(byte3: u8) -> Result<(ModuleType, bool), DecodeError> { +/// Crate-visible so the module-specific dispatch +/// ([`crate::decode_module_specific`]) routes on the same single decode of +/// byte 3, rather than duplicating it. +pub(crate) const fn decode_module_type(byte3: u8) -> Result<(ModuleType, bool), DecodeError> { let hybrid = byte3 & 0x80 != 0; let module_type = match byte3 & 0x0F { 0x01 => ModuleType::Rdimm, @@ -420,7 +420,7 @@ pub const fn decode_module_type(byte3: u8) -> Result<(ModuleType, bool), DecodeE Ok((module_type, hybrid)) } -/// Byte 4, bits \[4:0\]: SDRAM density per die. +/// Byte 4, bits `[4:0]`: SDRAM density per die. const fn decode_density_per_die(byte4: u8) -> Result { match byte4 & 0x1F { 0x01 => Ok(DensityPerDie::Gb4), @@ -438,7 +438,7 @@ const fn decode_density_per_die(byte4: u8) -> Result } } -/// Byte 4, bits \[7:5\]: package construction and die count. +/// Byte 4, bits `[7:5]`: package construction and die count. const fn decode_package(byte4: u8) -> Result<(PackageType, u8), DecodeError> { match (byte4 >> 5) & 0x07 { 0 => Ok((PackageType::Monolithic, 1)), @@ -454,17 +454,17 @@ const fn decode_package(byte4: u8) -> Result<(PackageType, u8), DecodeError> { } } -/// Byte 5, bits \[4:0\]: number of row address bits, base 16. +/// Byte 5, bits `[4:0]`: number of row address bits, base 16. const fn decode_row_address_bits(byte5: u8) -> u8 { 16 + (byte5 & 0x1F) } -/// Byte 5, bits \[7:5\]: number of column address bits, base 10. +/// Byte 5, bits `[7:5]`: number of column address bits, base 10. const fn decode_column_address_bits(byte5: u8) -> u8 { 10 + ((byte5 >> 5) & 0x07) } -/// Byte 6, bits \[7:5\]: SDRAM I/O device width. +/// Byte 6, bits `[7:5]`: SDRAM I/O device width. const fn decode_io_width(byte6: u8) -> Result { match (byte6 >> 5) & 0x07 { 0 => Ok(IoWidth::X4), @@ -478,7 +478,7 @@ const fn decode_io_width(byte6: u8) -> Result { } } -/// Byte 7, bits \[7:5\]: number of bank groups. +/// Byte 7, bits `[7:5]`: number of bank groups. const fn decode_bank_groups(byte7: u8) -> Result { match (byte7 >> 5) & 0x07 { 0 => Ok(BankGroups::One), @@ -492,7 +492,7 @@ const fn decode_bank_groups(byte7: u8) -> Result { } } -/// Byte 7, bits \[2:0\]: number of banks per bank group. +/// Byte 7, bits `[2:0]`: number of banks per bank group. const fn decode_banks_per_bank_group(byte7: u8) -> Result { match byte7 & 0x07 { 0 => Ok(BanksPerBankGroup::One), @@ -505,7 +505,7 @@ const fn decode_banks_per_bank_group(byte7: u8) -> Result (u8, bool) { let ranks = ((byte234 >> 3) & 0x07) + 1; @@ -513,7 +513,7 @@ const fn decode_package_ranks(byte234: u8) -> (u8, bool) { (ranks, asymmetric) } -/// Byte 235, bits \[2:0\]: primary bus width per channel in bits. +/// Byte 235, bits `[2:0]`: primary bus width per channel in bits. const fn decode_primary_bus_width(byte235: u8) -> Result { match byte235 & 0x07 { 0 => Ok(8), @@ -527,7 +527,7 @@ const fn decode_primary_bus_width(byte235: u8) -> Result { } } -/// Byte 235, bits \[7:5\]: number of channels (sub-channels) per DIMM. +/// Byte 235, bits `[7:5]`: number of channels (sub-channels) per DIMM. const fn decode_channels_per_dimm(byte235: u8) -> Result { match (byte235 >> 5) & 0x07 { 0 => Ok(1), diff --git a/spdr/src/module.rs b/spdr/src/module.rs index 97dd9c0..126a39a 100644 --- a/spdr/src/module.rs +++ b/spdr/src/module.rs @@ -61,7 +61,7 @@ impl fmt::Display for Millimeters { /// ambiguous letters I, O, Q, S, X, and Z, so the lettering runs A, B, ... H, J, /// K, ... Y, then two-letter cards (AA-style) past index 19. A card code of /// `0x1f` means no reference raw card (rendered "ZZ"); bit 7 extends the code by -/// 31 to reach the two-letter range; bits \[6:5\] carry the card revision. +/// 31 to reach the two-letter range; bits `[6:5]` carry the card revision. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub enum ReferenceRawCard { @@ -71,7 +71,7 @@ pub enum ReferenceRawCard { Card { /// Zero-based card index (0 = card "A") with the bit-7 extension applied. index: u8, - /// Card revision, from bits \[6:5\]. + /// Card revision, from bits `[6:5]`. revision: u8, }, } @@ -110,13 +110,13 @@ impl fmt::Display for ReferenceRawCard { #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct UnbufferedModule { - /// Module nominal height (byte 230, bits \[4:0\] + 15 mm). JEDEC encodes this + /// Module nominal height (byte 230, bits `[4:0]` + 15 mm). JEDEC encodes this /// as the upper bound of a 1 mm range, so a value of 0 means "<= 15 mm". pub nominal_height: Millimeters, - /// Maximum module thickness on the front (byte 231, bits \[3:0\] + 1 mm), the + /// Maximum module thickness on the front (byte 231, bits `[3:0]` + 1 mm), the /// upper bound of a 1 mm range. pub max_thickness_front: Millimeters, - /// Maximum module thickness on the back (byte 231, bits \[7:4\] + 1 mm), the + /// Maximum module thickness on the back (byte 231, bits `[7:4]` + 1 mm), the /// upper bound of a 1 mm range. pub max_thickness_back: Millimeters, /// Reference raw card the module is built from (byte 232). @@ -188,23 +188,23 @@ fn decode_unbuffered(spd: &SpdImage) -> Result { // Each applies one pinned encoding rule to its byte, so each has a focused unit // test built straight from the rule. -/// Byte 230, bits \[4:0\]: module nominal height in mm with a 15 mm base. +/// Byte 230, bits `[4:0]`: module nominal height in mm with a 15 mm base. const fn decode_nominal_height(byte230: u8) -> Millimeters { Millimeters((byte230 & 0x1F) + 15) } -/// Byte 231, bits \[3:0\]: front maximum thickness in mm with a 1 mm base. +/// Byte 231, bits `[3:0]`: front maximum thickness in mm with a 1 mm base. const fn decode_thickness_front(byte231: u8) -> Millimeters { Millimeters((byte231 & 0x0F) + 1) } -/// Byte 231, bits \[7:4\]: back maximum thickness in mm with a 1 mm base. +/// Byte 231, bits `[7:4]`: back maximum thickness in mm with a 1 mm base. const fn decode_thickness_back(byte231: u8) -> Millimeters { Millimeters(((byte231 >> 4) & 0x0F) + 1) } -/// Byte 232: reference raw card code (bits \[4:0\]), with the bit-7 extension and -/// the bits \[6:5\] revision. Code `0x1f` is the defined "no card" value. +/// Byte 232: reference raw card code (bits `[4:0]`), with the bit-7 extension and +/// the bits `[6:5]` revision. Code `0x1f` is the defined "no card" value. const fn decode_reference_raw_card(byte232: u8) -> ReferenceRawCard { let code = byte232 & 0x1F; if code == 0x1F { diff --git a/spdr/src/timing.rs b/spdr/src/timing.rs index 7a0bc9b..521613f 100644 --- a/spdr/src/timing.rs +++ b/spdr/src/timing.rs @@ -217,7 +217,7 @@ impl Timings { /// # Errors /// /// Returns [`DecodeError::Truncated`] if the image is too short for a required -/// byte — the only error this can return. +/// byte; the only error this can return. pub fn decode_timings(bytes: &[u8]) -> Result { let spd = SpdImage::new(bytes); @@ -285,10 +285,9 @@ fn decode_cas_latencies(spd: &SpdImage) -> Result { } /// Data rate in MT/s for a clock period, rounded to the nearest 100; 0 if the -/// period is zero. Crate-visible (this module is private, so `pub` stays -/// crate-internal) so the XMP/EXPO profile decode derives its rated data rate -/// through the same rounding rather than duplicating it. -pub const fn data_rate_mt_s(tckavg_min: Picoseconds) -> u32 { +/// period is zero. Crate-visible so the XMP/EXPO profile decode derives its +/// rated data rate through the same rounding rather than duplicating it. +pub(crate) const fn data_rate_mt_s(tckavg_min: Picoseconds) -> u32 { if tckavg_min.0 == 0 { return 0; } diff --git a/spdr/src/vendor.rs b/spdr/src/vendor.rs index c55d9eb..e8f28e9 100644 --- a/spdr/src/vendor.rs +++ b/spdr/src/vendor.rs @@ -496,15 +496,18 @@ fn voltage(byte: u8) -> Millivolts { /// Derive the rated CAS latency: tAA in whole cycles of the cycle time, rounded /// to nearest. Guards a zero cycle time (returns 0) so malformed input cannot -/// divide by zero. Decoded values are 16-bit picoseconds, so the rounded -/// quotient fits `u16`; the narrowing saturates instead of wrapping if a caller -/// ever hand-builds out-of-range values. +/// divide by zero. The add and the divide run in `u64`, so the round-to-nearest +/// stays exact for any `u32` input instead of saturating the add and rounding +/// down. Decoded values are 16-bit picoseconds, so the rounded quotient fits +/// `u16`; only the narrowing saturates, instead of wrapping if a caller ever +/// hand-builds out-of-range values. fn rated_cas_latency(taa: Picoseconds, cycle_time: Picoseconds) -> u16 { let tck = cycle_time.0; if tck == 0 { return 0; } - u16::try_from(taa.0.saturating_add(tck / 2) / tck).unwrap_or(u16::MAX) + let numerator = u64::from(taa.0) + u64::from(tck / 2); + u16::try_from(numerator / u64::from(tck)).unwrap_or(u16::MAX) } /// Read a 16-byte profile name at `off`, trimmed of trailing spaces and NULs. @@ -584,6 +587,17 @@ mod tests { ); } + #[test] + fn rated_cas_latency_rounds_in_u64() { + // The round-to-nearest is computed in `u64`, so it does not round down + // near the top of the `u32` range: 4294967295 / 2147483648 rounds to 2, + // where a saturating `u32` add would have given 1. + assert_eq!( + rated_cas_latency(Picoseconds(u32::MAX), Picoseconds(1 << 31)), + 2 + ); + } + #[test] fn read_le_u16_low_byte_first() { let spd = SpdImage::new(&[0x4D, 0x01]); From c949eb078ed0a1afb3342cd347b194ac754aebc1 Mon Sep 17 00:00:00 2001 From: Dan Alec Date: Fri, 6 Nov 2026 21:31:33 -0300 Subject: [PATCH 4/5] docs: correct the review-fix note and trace the pedantic measurement The dated implementation note listed `bool_to_int_with_if` among the denied workspace lints even though `Cargo.toml` dropped it in the same pass, and its verification section kept the "zero warnings" result from the pre-review head instead of re-running after the exit code returned to the branch form. Both claims are now corrected against measurements recorded in `docs/numerical-claims.md`. `CHANGELOG.md` no longer claims `cargo doc` warned on every bit-range field; it states the measured count, which is traced in the same file. The PR description is updated separately to match the corrected claims. --- CHANGELOG.md | 9 +++++---- .../2026-10-25-narrowing-const-and-doc-gates.md | 15 ++++++++++----- docs/numerical-claims.md | 10 ++++++++++ 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d759656..85423ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,10 +39,11 @@ removing `const` later would be breaking. `spdr/fuzz/Cargo.toml` and the Phase 6 report, with the attempt recorded in the deep-run ledger instead of left silently blank. - Rustdoc parsed bit-range notation in doc comments (`bits [7:5]`) as - intra-doc links, so `cargo doc` warned on every such field. The notation is - now written as a code span, which rustdoc does not link, and renders exactly - as written. The rendered documentation was correct before and after; the - defect was the warnings, which the new doc gate turns into a build failure. + intra-doc links, emitting 21 unresolved-link warnings on the base `6b0d2d5`. + The notation is now written as a code span, which rustdoc does not link, and + renders exactly as written. The rendered documentation was correct before and + after; the defect was the warnings, which the new doc gate turns into a build + failure. - The two internal CAS-latency derivations (the linter's supported-set check and the vendor-profile rated CL) narrowed `u32` quotients to `u16` with an unchecked `as`. The quotient always fit for decoded SPD bytes, but the diff --git a/docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md b/docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md index 905d232..6a28c49 100644 --- a/docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md +++ b/docs/implementations/2026-10-25-narrowing-const-and-doc-gates.md @@ -43,9 +43,10 @@ output-filename collision between the `spdr` library and the `spdr` binary `[workspace.lints.clippy]` denies a curated set from `clippy::pedantic`: `cast_possible_truncation`, `missing_errors_doc`, `doc_markdown`, -`ref_option`, `needless_pass_by_value`, `trivially_copy_pass_by_ref` and -`bool_to_int_with_if`. Curated rather than blanket, so that a future upstream -pedantic lint cannot break CI on a toolchain bump. +`ref_option`, `needless_pass_by_value` and `trivially_copy_pass_by_ref`. +Curated rather than blanket, so that a future upstream pedantic lint cannot +break CI on a toolchain bump. `bool_to_int_with_if` was dropped from the set +during this pass; see below. Two facts about that set were measured rather than assumed, and both corrected claims made earlier in the review: @@ -129,8 +130,12 @@ is meant to be the open reference. - `cargo fmt --check` · clean. - `cargo clippy --workspace --all-targets -- -D warnings` · clean. -- `cargo clippy --workspace --all-targets -- -W clippy::pedantic` · zero - warnings. +- `cargo clippy --workspace --all-targets -- -W clippy::pedantic` · one + warning: `bool_to_int_with_if` on the restored `if ok { 0 } else { 1 }` exit + code. The lint is not in the deny set and the CI gate does not enable blanket + `pedantic`, so the `-D warnings` gate stays clean. Measured on Windows and + Linux; traced in `docs/numerical-claims.md`. The zero-warning result belongs + to the pre-review head, where the exit code was `i32::from(!ok)`. - `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --lib` · clean. - `cargo build -p spdr` · clean, the existing `no_std` guard. - `cargo test --workspace` · the full suite passing. diff --git a/docs/numerical-claims.md b/docs/numerical-claims.md index da963d5..0335e7f 100644 --- a/docs/numerical-claims.md +++ b/docs/numerical-claims.md @@ -228,3 +228,13 @@ A behaviour-preserving pass over the shipped surface: no decoded output changed, | Fuzz attempt, zero executions | `cargo +nightly fuzz run decode_all -- -max_total_time=45` | Measured on 2026-10-16, Windows 11 x86_64, MSVC + Scoop LLVM 23, by `danalec`: it builds and links, then exits `STATUS_DLL_NOT_FOUND` (0xC0000135) on the missing `clang_rt.asan_dynamic-x86_64.dll`; `STATUS_ENTRYPOINT_NOT_FOUND` (0xC0000139) with LLVM's runtime on `PATH`; `CC=clang CXX=clang++` fails to link with LNK1120. Zero executions, so it earns no fuzz result. | | CLI exit codes | `decode` 0 / 1 / 2 · `lint` 0 / 1 / 2 | Asserted by the `spdr-cli` integration tests (`decode_fixture_exits_zero`, `decode_truncated_file_exits_one_with_partial_output`, `decode_nonexistent_path_exits_two_with_stderr`, and the `lint` equivalents). Unchanged by this pass. | | Round-to-nearest at the `u32` ceiling | `u32::MAX` ps over `2^31` ps rounds to 2 | Arithmetic in `u64`: `(4294967295 + 1073741824) / 2147483648` is 2, where the previous saturating `u32` add gave 1. Asserted by `rated_cas_latency_rounds_in_u64`. | + +## Documentation-accuracy correction (2026-11-06) + +Two claims introduced by the review-fix commit were measured again and corrected. + +| Claim | Value | Source | +| --- | --- | --- | +| Blanket `-W clippy::pedantic` on the review-fix head | 1 warning | Measured on 2026-11-06: `cargo clippy --workspace --all-targets -- -W clippy::pedantic` at `fd92f40` emits `bool_to_int_with_if` ("boolean to int conversion using if") for the restored `if results.all_decoded() { 0 } else { 1 }` exit code, on Windows (clippy 0.1.99) and Linux (clippy 0.1.98). The lint is not in the workspace deny list and the CI gate does not enable blanket `pedantic`, so the `-D warnings` gate stays clean. | +| Blanket `-W clippy::pedantic` on the pre-review head | 0 warnings | Measured on 2026-11-06 in a worktree at `663a30f`, where the exit code was `i32::from(!results.all_decoded())` — a form the lint does not warn on (see the toolchain measurements above). This is the result the note's "zero warnings" line was carried over from; it does not describe the review-fix head. | +| Unresolved-link warnings on the base `6b0d2d5` | 21 | Measured on 2026-11-06 on Linux: `cargo doc --workspace --no-deps --lib` at `6b0d2d5` emits 21 `unresolved link to ...` warnings, plus one public-doc-link-to-private-item warning; 22 in total, as recorded above. A `git grep -oE '\[[0-9]+:[0-9]+\]' -- '*.rs'` on that tree finds 54 such occurrences, so the warnings are not one per field — which is why the CHANGELOG now states the count instead of saying "every such field". | From fe38f4a4b35231868139405611cc7062678c13fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mert=20Efe=20=C5=9Eensoy?= <143845647+mertefesensoy@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:28:15 +0300 Subject: [PATCH 5/5] docs: replace the two em dashes in numerical-claims.md with commas --- docs/numerical-claims.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/numerical-claims.md b/docs/numerical-claims.md index 0335e7f..d265336 100644 --- a/docs/numerical-claims.md +++ b/docs/numerical-claims.md @@ -236,5 +236,5 @@ Two claims introduced by the review-fix commit were measured again and corrected | Claim | Value | Source | | --- | --- | --- | | Blanket `-W clippy::pedantic` on the review-fix head | 1 warning | Measured on 2026-11-06: `cargo clippy --workspace --all-targets -- -W clippy::pedantic` at `fd92f40` emits `bool_to_int_with_if` ("boolean to int conversion using if") for the restored `if results.all_decoded() { 0 } else { 1 }` exit code, on Windows (clippy 0.1.99) and Linux (clippy 0.1.98). The lint is not in the workspace deny list and the CI gate does not enable blanket `pedantic`, so the `-D warnings` gate stays clean. | -| Blanket `-W clippy::pedantic` on the pre-review head | 0 warnings | Measured on 2026-11-06 in a worktree at `663a30f`, where the exit code was `i32::from(!results.all_decoded())` — a form the lint does not warn on (see the toolchain measurements above). This is the result the note's "zero warnings" line was carried over from; it does not describe the review-fix head. | -| Unresolved-link warnings on the base `6b0d2d5` | 21 | Measured on 2026-11-06 on Linux: `cargo doc --workspace --no-deps --lib` at `6b0d2d5` emits 21 `unresolved link to ...` warnings, plus one public-doc-link-to-private-item warning; 22 in total, as recorded above. A `git grep -oE '\[[0-9]+:[0-9]+\]' -- '*.rs'` on that tree finds 54 such occurrences, so the warnings are not one per field — which is why the CHANGELOG now states the count instead of saying "every such field". | +| Blanket `-W clippy::pedantic` on the pre-review head | 0 warnings | Measured on 2026-11-06 in a worktree at `663a30f`, where the exit code was `i32::from(!results.all_decoded())`, a form the lint does not warn on (see the toolchain measurements above). This is the result the note's "zero warnings" line was carried over from; it does not describe the review-fix head. | +| Unresolved-link warnings on the base `6b0d2d5` | 21 | Measured on 2026-11-06 on Linux: `cargo doc --workspace --no-deps --lib` at `6b0d2d5` emits 21 `unresolved link to ...` warnings, plus one public-doc-link-to-private-item warning; 22 in total, as recorded above. A `git grep -oE '\[[0-9]+:[0-9]+\]' -- '*.rs'` on that tree finds 54 such occurrences, so the warnings are not one per field, which is why the CHANGELOG now states the count instead of saying "every such field". |