Skip to main content

cal_model/
mock.rs

1//! An in-memory XCP transport: ECU calibration memory as a sparse map.
2//!
3//! [`MockTransport`] implements [`XcpTransport`](crate::XcpTransport) over
4//! per-page address → byte maps. A full calibration cycle — read, adjust,
5//! write, snapshot, diff — runs against it with no hardware, no timing, and
6//! no flaky I/O, which is what makes this crate's session tests meaningful
7//! rather than merely fast.
8//!
9//! It also records every access ([`requests`](MockTransport::requests)) and
10//! can be told to fail ([`fail_reads`](MockTransport::fail_reads) /
11//! [`fail_writes`](MockTransport::fail_writes)), which is how the
12//! error-propagation paths are exercised.
13//!
14//! ```
15//! use cal_model::mock::MockTransport;
16//! use cal_model::{CalError, XcpTransport};
17//!
18//! let mut bench = MockTransport::seeded(&[(0x720100, vec![0x10, 0x00])]);
19//! assert_eq!(bench.read(0x720100, 2)?, vec![0x10, 0x00]);
20//! bench.write(0x720100, &[0x20, 0x00])?;
21//! assert_eq!(bench.read(0x720100, 2)?, vec![0x20, 0x00]);
22//! # Ok::<(), CalError>(())
23//! ```
24
25use crate::error::CalError;
26use crate::session::XcpTransport;
27use std::collections::BTreeMap;
28
29/// One page of calibration memory: address → byte. Sparse: an address that
30/// was never written reads as zero, exactly like freshly erased flash.
31type Page = BTreeMap<u32, u8>;
32
33/// One access a session made, in order.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Request {
36    /// A read of `len` bytes at `addr`.
37    Read {
38        /// ECU address read.
39        addr: u32,
40        /// Byte count requested.
41        len: u8,
42    },
43    /// A write of `len` bytes at `addr`.
44    Write {
45        /// ECU address written.
46        addr: u32,
47        /// Byte count written.
48        len: u8,
49    },
50    /// A `SET_CAL_PAGE` switch to `page`.
51    SetPage(u32),
52}
53
54/// An in-memory ECU: pages of calibration memory behind the
55/// [`XcpTransport`] contract.
56#[derive(Debug, Clone)]
57pub struct MockTransport {
58    pages: BTreeMap<u32, Page>,
59    page: u32,
60    requests: Vec<Request>,
61    read_failure: Option<String>,
62    write_failure: Option<String>,
63}
64
65impl MockTransport {
66    /// An empty ECU on page 0.
67    #[must_use]
68    pub fn new() -> Self {
69        Self {
70            pages: BTreeMap::new(),
71            page: 0,
72            requests: Vec::new(),
73            read_failure: None,
74            write_failure: None,
75        }
76    }
77
78    /// An ECU seeded with `(address, bytes)` pairs — a factory calibration.
79    #[must_use]
80    pub fn seeded(seeds: &[(u32, Vec<u8>)]) -> Self {
81        let mut transport = Self::new();
82        for (addr, bytes) in seeds {
83            transport.seed(*addr, bytes);
84        }
85        transport
86    }
87
88    /// Make every read fail with `message` (a slave that is not answering).
89    #[must_use]
90    pub fn fail_reads(mut self, message: &str) -> Self {
91        self.read_failure = Some(message.to_string());
92        self
93    }
94
95    /// Make every write fail with `message` (a write-protected page).
96    #[must_use]
97    pub fn fail_writes(mut self, message: &str) -> Self {
98        self.write_failure = Some(message.to_string());
99        self
100    }
101
102    /// The active page.
103    #[must_use]
104    pub const fn page(&self) -> u32 {
105        self.page
106    }
107
108    /// Every access so far, in order.
109    #[must_use]
110    pub fn requests(&self) -> &[Request] {
111        &self.requests
112    }
113
114    /// Write `bytes` at `addr` on the active page, outside the transport
115    /// contract (test setup).
116    pub fn seed(&mut self, addr: u32, bytes: &[u8]) {
117        let page = self.pages.entry(self.page).or_default();
118        for (offset, &byte) in bytes.iter().enumerate() {
119            let Some(address) = addr.checked_add(u32::try_from(offset).unwrap_or(u32::MAX)) else {
120                continue;
121            };
122            page.insert(address, byte);
123        }
124    }
125
126    /// The bytes at `addr..addr + len` on the active page, bypassing the
127    /// transport contract (test assertions).
128    #[must_use]
129    pub fn peek(&self, addr: u32, len: u8) -> Vec<u8> {
130        let empty = Page::new();
131        let page = self.pages.get(&self.page).unwrap_or(&empty);
132        let len = usize::from(len);
133        let mut out = Vec::with_capacity(len);
134        for offset in 0..len {
135            let Some(address) = addr.checked_add(u32::try_from(offset).unwrap_or(u32::MAX)) else {
136                out.push(0);
137                continue;
138            };
139            out.push(page.get(&address).copied().unwrap_or(0));
140        }
141        out
142    }
143
144    /// The byte at `addr` on the active page.
145    #[must_use]
146    pub fn byte(&self, addr: u32) -> u8 {
147        self.peek(addr, 1).first().copied().unwrap_or(0)
148    }
149
150    /// The byte at `addr` on page `page`, ignoring the active page.
151    #[must_use]
152    pub fn byte_on(&self, page: u32, addr: u32) -> u8 {
153        self.pages
154            .get(&page)
155            .and_then(|p| p.get(&addr))
156            .copied()
157            .unwrap_or(0)
158    }
159
160    /// This mock, recovered from a `&dyn XcpTransport`.
161    ///
162    /// A [`CalibrationSession`](crate::CalibrationSession) owns its
163    /// transport as a trait object; `as_any` is the sanctioned way back to
164    /// the concrete type when a caller needs to inspect what the session did.
165    #[must_use]
166    pub fn from_transport(transport: &dyn XcpTransport) -> Option<&Self> {
167        transport.as_any()?.downcast_ref::<Self>()
168    }
169}
170
171impl Default for MockTransport {
172    fn default() -> Self {
173        Self::new()
174    }
175}
176
177impl XcpTransport for MockTransport {
178    fn read(&mut self, addr: u32, len: u8) -> Result<Vec<u8>, CalError> {
179        self.requests.push(Request::Read { addr, len });
180        if let Some(message) = &self.read_failure {
181            return Err(CalError::Transport(message.clone()));
182        }
183        Ok(self.peek(addr, len))
184    }
185
186    fn write(&mut self, addr: u32, data: &[u8]) -> Result<(), CalError> {
187        #[allow(clippy::cast_possible_truncation)]
188        self.requests.push(Request::Write {
189            addr,
190            len: data.len() as u8,
191        });
192        if let Some(message) = &self.write_failure {
193            return Err(CalError::Transport(message.clone()));
194        }
195        self.seed(addr, data);
196        Ok(())
197    }
198
199    fn set_page(&mut self, page: u32) -> Result<(), CalError> {
200        self.requests.push(Request::SetPage(page));
201        self.pages.entry(page).or_default();
202        self.page = page;
203        Ok(())
204    }
205
206    fn as_any(&self) -> Option<&dyn std::any::Any> {
207        Some(self)
208    }
209}