Skip to main content

serialplugin_testing/
fake.rs

1//! An in-memory serial device.
2
3use crate::clock::{Clock, SystemClock};
4use crate::{Modem, WAIT};
5use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
6use std::collections::VecDeque;
7use std::io::{self, Read, Write};
8use std::sync::{mpsc, Arc, Condvar, Mutex, MutexGuard, Weak};
9use std::time::{Duration, Instant};
10
11type Responder = Box<dyn FnMut(&FakeDevice, &[u8], usize) -> Vec<u8> + Send>;
12
13/// Gets the bytes of each write; `false` once nobody listens any more.
14type Subscriber = Box<dyn FnMut(&[u8]) -> bool + Send>;
15
16/// Faults of a port, for what the device answers ([`FakeDevice::respond`],
17/// [`FakeDevice::modem`]) and how the host reads it. Set with [`FakeDevice::faults`]; the
18/// default has none.
19///
20/// ```
21/// use serialplugin_testing::Faults;
22/// use std::time::Duration;
23///
24/// let faults = Faults::default()
25///     .burst(b"\r\n+CSQ: 20,99\r\n", 3)
26///     .chunk(5)
27///     .delay(Duration::from_millis(200));
28/// assert_eq!(faults.chunk, Some(5));
29/// assert!(!faults.silent);
30/// ```
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub struct Faults {
34    /// Answers are dropped: the host's commands hang (the modem still sees them).
35    pub silent: bool,
36    /// These bytes, that many times, after every answer that is not empty (a burst of
37    /// unsolicited lines).
38    pub burst: Option<(Vec<u8>, usize)>,
39    /// Every read returns at most this many bytes: lines split across reads.
40    pub chunk: Option<usize>,
41    /// Answers arrive this late, on the device's [clock](FakeDevice::clock), and in order: an
42    /// answer never comes before one given earlier, also when the delay was cut meanwhile.
43    pub delay: Duration,
44}
45
46impl Faults {
47    /// Set [`silent`](field@Self::silent).
48    pub fn silent(mut self, on: bool) -> Self {
49        self.silent = on;
50        self
51    }
52
53    /// Set [`burst`](field@Self::burst).
54    pub fn burst(mut self, bytes: &[u8], times: usize) -> Self {
55        self.burst = Some((bytes.to_vec(), times));
56        self
57    }
58
59    /// Set [`chunk`](field@Self::chunk); 0 is taken as 1.
60    pub fn chunk(mut self, max: usize) -> Self {
61        self.chunk = Some(max.max(1));
62        self
63    }
64
65    /// Set [`delay`](field@Self::delay).
66    pub fn delay(mut self, delay: Duration) -> Self {
67        self.delay = delay;
68        self
69    }
70}
71
72/// Modem status lines a [`FakeDevice`] reports.
73///
74/// ```
75/// use serialplugin_testing::Lines;
76///
77/// let lines = Lines::default().cts(false).ring(true);
78/// assert!(!lines.cts && lines.dsr && lines.ring && !lines.carrier);
79/// ```
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct Lines {
83    /// Clear to send.
84    pub cts: bool,
85    /// Data set ready.
86    pub dsr: bool,
87    /// Ring indicator.
88    pub ring: bool,
89    /// Carrier detect.
90    pub carrier: bool,
91}
92
93impl Default for Lines {
94    /// A ready device: CTS and DSR on.
95    fn default() -> Self {
96        Self {
97            cts: true,
98            dsr: true,
99            ring: false,
100            carrier: false,
101        }
102    }
103}
104
105impl Lines {
106    /// Set clear to send.
107    pub fn cts(mut self, on: bool) -> Self {
108        self.cts = on;
109        self
110    }
111
112    /// Set data set ready.
113    pub fn dsr(mut self, on: bool) -> Self {
114        self.dsr = on;
115        self
116    }
117
118    /// Set the ring indicator.
119    pub fn ring(mut self, on: bool) -> Self {
120        self.ring = on;
121        self
122    }
123
124    /// Set carrier detect.
125    pub fn carrier(mut self, on: bool) -> Self {
126        self.carrier = on;
127        self
128    }
129}
130
131/// A setting or control call the host made on the port, in order ([`FakeDevice::calls`]).
132#[derive(Debug, Clone, PartialEq, Eq)]
133#[non_exhaustive]
134pub enum Call {
135    /// `set_baud_rate`
136    BaudRate(u32),
137    /// `set_data_bits`
138    DataBits(DataBits),
139    /// `set_flow_control`
140    FlowControl(FlowControl),
141    /// `set_parity`
142    Parity(Parity),
143    /// `set_stop_bits`
144    StopBits(StopBits),
145    /// `write_request_to_send`
146    Rts(bool),
147    /// `write_data_terminal_ready`
148    Dtr(bool),
149    /// `set_break` / `clear_break`
150    Break(bool),
151    /// `clear` of the input (also as part of `All`)
152    ClearInput,
153    /// `clear` of the output (also as part of `All`)
154    ClearOutput,
155}
156
157#[derive(Clone)]
158struct Settings {
159    baud_rate: u32,
160    data_bits: DataBits,
161    flow_control: FlowControl,
162    parity: Parity,
163    stop_bits: StopBits,
164}
165
166struct State {
167    /// Bytes the host has not read yet.
168    rx: VecDeque<u8>,
169    /// Everything the host wrote.
170    written: Vec<u8>,
171    write_timeouts: Vec<Duration>,
172    calls: Vec<Call>,
173    settings: Settings,
174    lines: Lines,
175    read_error: Option<io::ErrorKind>,
176    /// Reads left that fail with the kind.
177    read_errors_left: (usize, io::ErrorKind),
178    write_error: Option<io::ErrorKind>,
179    /// Reads left that return `Ok(0)`.
180    eof_left: usize,
181    eof_reads: usize,
182    stall_writes: bool,
183    hold_writes: bool,
184    hold_reads: bool,
185    held: usize,
186    /// Buffer sizes of the read calls in progress.
187    reading: Vec<usize>,
188    driver_pending: Option<u32>,
189    out_pending: u32,
190    /// Handles of the host.
191    ports: usize,
192    /// Handles of the test.
193    handles: usize,
194    responder: Option<Responder>,
195    /// Writes the responder has not answered yet.
196    unanswered: VecDeque<Vec<u8>>,
197    /// A writer runs the responder (without the lock): it answers the writes of others too.
198    answering: bool,
199    faults: Faults,
200    /// Set by the test: port timeouts run on it too.
201    clock: Option<Arc<dyn Clock>>,
202    /// For delays when the test set no clock; made on first use.
203    system_clock: Option<Arc<dyn Clock>>,
204    subscribers: Vec<Subscriber>,
205    /// Answers in the order they were given, from the first that still waits for its delay:
206    /// one is handed to the host once it and all before it are due.
207    late: VecDeque<Late>,
208    late_seq: u64,
209}
210
211/// An answer behind its delay.
212struct Late {
213    id: u64,
214    bytes: Vec<u8>,
215    due: bool,
216}
217
218impl State {
219    /// Hand the host the due answers at the front of the queue.
220    fn flush_late(&mut self) {
221        while self.late.front().is_some_and(|l| l.due) {
222            let late = self.late.pop_front().expect("front");
223            self.rx.extend(late.bytes);
224        }
225    }
226
227    /// The clock delays run on.
228    fn delay_clock(&mut self) -> Arc<dyn Clock> {
229        if let Some(clock) = &self.clock {
230            return clock.clone();
231        }
232        self.system_clock
233            .get_or_insert_with(|| Arc::new(SystemClock::new()))
234            .clone()
235    }
236}
237
238#[derive(Clone)]
239struct Shared(Arc<(Mutex<State>, Condvar)>);
240
241impl Shared {
242    fn lock(&self) -> MutexGuard<'_, State> {
243        self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
244    }
245
246    fn change<T>(&self, f: impl FnOnce(&mut State) -> T) -> T {
247        let out = f(&mut self.lock());
248        self.0 .1.notify_all();
249        out
250    }
251
252    fn notify(&self) {
253        self.0 .1.notify_all();
254    }
255
256    /// Bytes for the host after `after` on the delay clock (at once when zero).
257    fn send_after(&self, after: Duration, bytes: Vec<u8>) {
258        if after.is_zero() {
259            self.change(|s| s.rx.extend(bytes));
260            return;
261        }
262        let clock = self.lock().delay_clock();
263        // Held weakly: a dropped device gets nothing.
264        let shared: Weak<(Mutex<State>, Condvar)> = Arc::downgrade(&self.0);
265        clock.at(
266            clock.now() + after,
267            Box::new(move || {
268                if let Some(shared) = shared.upgrade() {
269                    Shared(shared).change(|s| s.rx.extend(bytes));
270                }
271            }),
272        );
273    }
274
275    /// An answer of the responder, through the faults, after the answers before it.
276    fn deliver(&self, mut reply: Vec<u8>) {
277        let mut state = self.lock();
278        if state.faults.silent || reply.is_empty() {
279            return;
280        }
281        if let Some((bytes, times)) = &state.faults.burst {
282            for _ in 0..*times {
283                reply.extend(bytes);
284            }
285        }
286        let delay = state.faults.delay;
287        if delay.is_zero() && state.late.is_empty() {
288            state.rx.extend(reply);
289            drop(state);
290            self.notify();
291            return;
292        }
293        state.late_seq += 1;
294        let id = state.late_seq;
295        state.late.push_back(Late {
296            id,
297            bytes: reply,
298            due: delay.is_zero(),
299        });
300        if delay.is_zero() {
301            return;
302        }
303        let clock = state.delay_clock();
304        drop(state);
305        let shared: Weak<(Mutex<State>, Condvar)> = Arc::downgrade(&self.0);
306        clock.at(
307            clock.now() + delay,
308            Box::new(move || {
309                if let Some(shared) = shared.upgrade() {
310                    Shared(shared).change(|s| {
311                        if let Some(late) = s.late.iter_mut().find(|l| l.id == id) {
312                            late.due = true;
313                        }
314                        s.flush_late();
315                    });
316                }
317            }),
318        );
319    }
320
321    /// Block while `gate` holds, counted as a held call.
322    fn pass<'a>(
323        &'a self,
324        mut state: MutexGuard<'a, State>,
325        gate: impl Fn(&State) -> bool,
326    ) -> MutexGuard<'a, State> {
327        if gate(&state) {
328            state.held += 1;
329            self.notify();
330            while gate(&state) {
331                state = self.0 .1.wait(state).unwrap_or_else(|e| e.into_inner());
332            }
333            state.held -= 1;
334            self.notify();
335        }
336        state
337    }
338
339    /// Wait until `done` holds; panics with `what` after [`WAIT`].
340    fn wait(&self, what: &str, done: impl Fn(&State) -> bool) {
341        let deadline = Instant::now() + WAIT;
342        let mut state = self.lock();
343        while !done(&state) {
344            let left = deadline.saturating_duration_since(Instant::now());
345            if left.is_zero() {
346                drop(state);
347                panic!("never: {what}");
348            }
349            let woken = self.0 .1.wait_timeout(state, left);
350            state = woken.unwrap_or_else(|e| e.into_inner()).0;
351        }
352    }
353
354    /// Answer the writes not answered yet, in order.
355    fn answer(&self) {
356        /// The responder while it is out; a panic in it puts it back.
357        struct Out<'a> {
358            shared: &'a Shared,
359            responder: Option<Responder>,
360            done: bool,
361        }
362        impl Drop for Out<'_> {
363            fn drop(&mut self) {
364                if self.done {
365                    return;
366                }
367                self.shared.change(|s| {
368                    if s.responder.is_none() {
369                        s.responder = self.responder.take();
370                    }
371                    s.answering = false;
372                });
373            }
374        }
375        {
376            let mut state = self.lock();
377            if state.answering || state.responder.is_none() {
378                return;
379            }
380            state.answering = true;
381        }
382        let device = FakeDevice::handle(self.clone());
383        let mut out = Out {
384            shared: self,
385            responder: None,
386            done: false,
387        };
388        while !out.done {
389            let mut state = self.lock();
390            // The first one, or one an answer has set meanwhile.
391            let mut replaced = None;
392            if let Some(new) = state.responder.take() {
393                replaced = out.responder.replace(new);
394            }
395            let next = state.unanswered.pop_front();
396            let unread = state.rx.len();
397            if next.is_none() {
398                state.responder = out.responder.take();
399                state.answering = false;
400                out.done = true;
401            }
402            // The responder may use its device, also when it is dropped.
403            drop(state);
404            drop(replaced);
405            if let (Some(bytes), Some(responder)) = (next, &mut out.responder) {
406                let reply = responder(&device, &bytes, unread);
407                self.deliver(reply);
408            }
409        }
410    }
411}
412
413/// The device side of an in-memory serial port; clones are handles to the same device.
414///
415/// [`port`](Self::port) gives the host its side, a [`serialport::SerialPort`]. The device
416/// records what the host does and decides what it sees: bytes, errors, held calls.
417///
418/// ```
419/// use serialplugin_testing::FakeDevice;
420/// use std::io::{Read, Write};
421///
422/// let device = FakeDevice::new();
423/// let mut port = device.port();
424/// port.write_all(b"ping").unwrap();
425/// assert_eq!(device.written(), b"ping");
426///
427/// device.send(b"pong");
428/// let mut buf = [0; 4];
429/// port.read_exact(&mut buf).unwrap();
430/// assert_eq!(&buf, b"pong");
431/// ```
432///
433/// Dropping the last `FakeDevice` ends [`hold_reads`](Self::hold_reads) and
434/// [`hold_writes`](Self::hold_writes), so a test that fails while it holds the host does not
435/// hang on the way out.
436pub struct FakeDevice(Shared);
437
438impl Clone for FakeDevice {
439    fn clone(&self) -> Self {
440        Self::handle(self.0.clone())
441    }
442}
443
444impl Drop for FakeDevice {
445    fn drop(&mut self) {
446        self.0.change(|s| {
447            s.handles -= 1;
448            if s.handles == 0 {
449                s.hold_reads = false;
450                s.hold_writes = false;
451            }
452        });
453    }
454}
455
456impl Default for FakeDevice {
457    fn default() -> Self {
458        Self::new()
459    }
460}
461
462impl std::fmt::Debug for FakeDevice {
463    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464        f.debug_struct("FakeDevice").finish_non_exhaustive()
465    }
466}
467
468impl FakeDevice {
469    /// A silent device at 115200 8N1.
470    pub fn new() -> Self {
471        let state = State {
472            rx: VecDeque::new(),
473            written: Vec::new(),
474            write_timeouts: Vec::new(),
475            calls: Vec::new(),
476            settings: Settings {
477                baud_rate: 115_200,
478                data_bits: DataBits::Eight,
479                flow_control: FlowControl::None,
480                parity: Parity::None,
481                stop_bits: StopBits::One,
482            },
483            lines: Lines::default(),
484            read_error: None,
485            read_errors_left: (0, io::ErrorKind::Other),
486            write_error: None,
487            eof_left: 0,
488            eof_reads: 0,
489            stall_writes: false,
490            hold_writes: false,
491            hold_reads: false,
492            held: 0,
493            reading: Vec::new(),
494            driver_pending: None,
495            out_pending: 0,
496            ports: 0,
497            handles: 0,
498            responder: None,
499            unanswered: VecDeque::new(),
500            answering: false,
501            faults: Faults::default(),
502            clock: None,
503            system_clock: None,
504            subscribers: Vec::new(),
505            late: VecDeque::new(),
506            late_seq: 0,
507        };
508        Self::handle(Shared(Arc::new((Mutex::new(state), Condvar::new()))))
509    }
510
511    fn handle(shared: Shared) -> Self {
512        shared.change(|s| s.handles += 1);
513        Self(shared)
514    }
515
516    /// A device where `modem` answers what the host writes.
517    pub fn with_modem(modem: Modem) -> Self {
518        let device = Self::new();
519        device.modem(modem);
520        device
521    }
522
523    /// The host's port (timeout 1 s). `try_clone` works, as on a real desktop port.
524    pub fn port(&self) -> FakePort {
525        self.open(true)
526    }
527
528    /// Like [`port`](Self::port), but `try_clone` fails: the host has one handle for reads
529    /// and writes.
530    pub fn unclonable_port(&self) -> FakePort {
531        self.open(false)
532    }
533
534    fn open(&self, clonable: bool) -> FakePort {
535        self.0.change(|s| s.ports += 1);
536        FakePort {
537            shared: self.0.clone(),
538            timeout: Duration::from_secs(1),
539            clonable,
540        }
541    }
542
543    /// Send bytes to the host.
544    pub fn send(&self, bytes: &[u8]) {
545        self.0.change(|s| s.rx.extend(bytes));
546    }
547
548    /// Bytes sent that the host has not read yet.
549    pub fn unread(&self) -> usize {
550        self.0.lock().rx.len()
551    }
552
553    /// Wait until the host read everything sent. It may still be handling it: see
554    /// [`wait_handled`](Self::wait_handled).
555    pub fn wait_read(&self) {
556        self.0.wait("the host read every byte", |s| s.rx.is_empty());
557    }
558
559    /// Wait until the host read everything sent and asks for more: a host that reads and
560    /// handles the bytes on one thread has handled them by then.
561    pub fn wait_handled(&self) {
562        self.0.wait("the host handled every byte", |s| {
563            s.rx.is_empty() && !s.reading.is_empty()
564        });
565    }
566
567    /// Wait until a read of the host asks for `size` bytes.
568    pub fn wait_asked(&self, size: usize) {
569        self.0
570            .wait(&format!("the host asks for {size} bytes"), |s| {
571                s.reading.contains(&size)
572            });
573    }
574
575    /// Everything the host wrote so far.
576    pub fn written(&self) -> Vec<u8> {
577        self.0.lock().written.clone()
578    }
579
580    /// Wait until what the host wrote satisfies `done`; returns it.
581    pub fn wait_written(&self, what: &str, done: impl Fn(&[u8]) -> bool) -> Vec<u8> {
582        self.0.wait(what, |s| done(&s.written));
583        self.written()
584    }
585
586    /// The port timeout at each write.
587    pub fn write_timeouts(&self) -> Vec<Duration> {
588        self.0.lock().write_timeouts.clone()
589    }
590
591    /// Setting and control calls so far.
592    pub fn calls(&self) -> Vec<Call> {
593        self.0.lock().calls.clone()
594    }
595
596    /// Answer every write: `reply` gets the device and the written bytes and returns what
597    /// the device sends. Writes are answered one at a time, in order; one made while `reply`
598    /// runs (by another handle, or by `reply` itself) is answered after it.
599    ///
600    /// Use the device it is given: a `FakeDevice` captured by `reply` is never dropped.
601    pub fn respond(&self, mut reply: impl FnMut(&FakeDevice, &[u8]) -> Vec<u8> + Send + 'static) {
602        self.set_responder(Box::new(move |device, bytes, _| reply(device, bytes)));
603    }
604
605    /// Let `modem` answer what the host writes.
606    pub fn modem(&self, mut modem: Modem) {
607        self.set_responder(Box::new(move |_, bytes, unread| {
608            modem.feed_with_unread(bytes, unread)
609        }));
610    }
611
612    fn set_responder(&self, responder: Responder) {
613        // The old one is dropped without the lock.
614        let _old = self.0.change(|s| s.responder.replace(responder));
615    }
616
617    /// The clock of the device: [`Faults::delay`], [`send_after`](Self::send_after) and the
618    /// port timeout of every read that starts afterwards run on it. A read that waits for data ends when this clock
619    /// reaches its timeout (a [`ManualClock`](crate::ManualClock) that is advanced, a paused
620    /// tokio clock that skips ahead). A clock that does not get there within [`WAIT`] of real
621    /// time fails the read with `ErrorKind::Other`: that bounds a failing test. A paused tokio
622    /// clock does not skip ahead while a `spawn_blocking` task runs: read on a thread of your
623    /// own. Without a clock: real time, as a port has.
624    ///
625    /// Answers still waiting for their delay on the clock before are handed to the host now:
626    /// their clock is gone, and the answers after them would wait for them for ever.
627    pub fn clock(&self, clock: Arc<dyn Clock>) {
628        self.0.change(|s| {
629            s.clock = Some(clock);
630            s.late.iter_mut().for_each(|l| l.due = true);
631            s.flush_late();
632        });
633    }
634
635    /// Faults from now on; [`Faults::default`] ends them.
636    pub fn faults(&self, faults: Faults) {
637        self.0.change(|s| s.faults = faults);
638    }
639
640    /// Send bytes to the host once `after` has passed on the device's [clock](Self::clock).
641    pub fn send_after(&self, after: Duration, bytes: &[u8]) {
642        self.0.send_after(after, bytes.to_vec());
643    }
644
645    /// The bytes of every write of the host that the device takes from now on, in order, one
646    /// message per write call (a failed or stalled write sends none; a held one, when it is
647    /// let go). No polling: `recv` wakes on the write.
648    pub fn subscribe_writes(&self) -> mpsc::Receiver<Vec<u8>> {
649        let (tx, rx) = mpsc::channel();
650        self.0.change(|s| {
651            s.subscribers
652                .push(Box::new(move |bytes| tx.send(bytes.to_vec()).is_ok()))
653        });
654        rx
655    }
656
657    /// [`subscribe_writes`](Self::subscribe_writes) for async tests (feature `tokio`).
658    #[cfg(feature = "tokio")]
659    pub fn subscribe_writes_async(&self) -> tokio::sync::mpsc::UnboundedReceiver<Vec<u8>> {
660        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
661        self.0.change(|s| {
662            s.subscribers
663                .push(Box::new(move |bytes| tx.send(bytes.to_vec()).is_ok()))
664        });
665        rx
666    }
667
668    /// Every read fails with `kind` from now on (an unplugged device).
669    pub fn fail_reads(&self, kind: io::ErrorKind) {
670        self.0.change(|s| s.read_error = Some(kind));
671    }
672
673    /// The next `n` reads fail with `kind`, then the device works again.
674    pub fn fail_reads_times(&self, n: usize, kind: io::ErrorKind) {
675        self.0.change(|s| s.read_errors_left = (n, kind));
676    }
677
678    /// Every write fails with `kind` from now on.
679    pub fn fail_writes(&self, kind: io::ErrorKind) {
680        self.0.change(|s| s.write_error = Some(kind));
681    }
682
683    /// Writes time out: the device takes no bytes.
684    pub fn stall_writes(&self, on: bool) {
685        self.0.change(|s| s.stall_writes = on);
686    }
687
688    /// Every read returns `Ok(0)` from now on (a tty after hang-up).
689    pub fn eof(&self) {
690        self.0.change(|s| s.eof_left = usize::MAX);
691    }
692
693    /// The device works again: undoes [`fail_reads`](Self::fail_reads),
694    /// [`fail_reads_times`](Self::fail_reads_times), [`fail_writes`](Self::fail_writes),
695    /// [`stall_writes`](Self::stall_writes), [`eof`](Self::eof) and
696    /// [`eof_times`](Self::eof_times).
697    pub fn recover(&self) {
698        self.0.change(|s| {
699            s.read_error = None;
700            s.read_errors_left.0 = 0;
701            s.write_error = None;
702            s.stall_writes = false;
703            s.eof_left = 0;
704        });
705    }
706
707    /// The next `n` reads return `Ok(0)`.
708    pub fn eof_times(&self, n: usize) {
709        self.0.change(|s| s.eof_left = n);
710    }
711
712    /// Reads that returned `Ok(0)` so far.
713    pub fn eof_reads(&self) -> usize {
714        self.0.lock().eof_reads
715    }
716
717    /// While on, writes block in the device. Ends when the last `FakeDevice` is dropped.
718    pub fn hold_writes(&self, on: bool) {
719        self.0.change(|s| s.hold_writes = on);
720    }
721
722    /// While on, reads block in the device, also one that waits for data already (its
723    /// timeout starts again when it is let go). Ends when the last `FakeDevice` is dropped.
724    pub fn hold_reads(&self, on: bool) {
725        self.0.change(|s| s.hold_reads = on);
726    }
727
728    /// Calls blocked in the device right now.
729    pub fn held(&self) -> usize {
730        self.0.lock().held
731    }
732
733    /// Wait until `n` calls are blocked in the device.
734    pub fn wait_held(&self, n: usize) {
735        self.0
736            .wait("the host is blocked in the device", |s| s.held == n);
737    }
738
739    /// Set the status lines.
740    pub fn set_lines(&self, lines: Lines) {
741        self.0.change(|s| s.lines = lines);
742    }
743
744    /// What `bytes_to_read` reports; `None` is the number of unread bytes.
745    pub fn set_driver_pending(&self, n: Option<u32>) {
746        self.0.change(|s| s.driver_pending = n);
747    }
748
749    /// What `bytes_to_write` reports.
750    pub fn set_out_pending(&self, n: u32) {
751        self.0.change(|s| s.out_pending = n);
752    }
753
754    /// Open handles of the host, clones included; 0 once it closed the port.
755    pub fn open_ports(&self) -> usize {
756        self.0.lock().ports
757    }
758
759    /// Wait until the host dropped every handle.
760    pub fn wait_closed(&self) {
761        self.0.wait("the host closed the port", |s| s.ports == 0);
762    }
763}
764
765/// The end of a read's wait.
766enum Deadline {
767    Real(Instant),
768    /// On the device clock; `bound` (real time) only ends a test whose clock never gets there.
769    Clock {
770        clock: Arc<dyn Clock>,
771        at: Duration,
772        bound: Instant,
773        /// Its wake job is scheduled.
774        armed: bool,
775    },
776}
777
778impl Deadline {
779    /// The wake job to schedule before the first wait, once.
780    fn arm(&mut self) -> Option<(Arc<dyn Clock>, Duration)> {
781        match self {
782            Self::Clock {
783                clock, at, armed, ..
784            } if !*armed => {
785                *armed = true;
786                Some((clock.clone(), *at))
787            }
788            _ => None,
789        }
790    }
791
792    /// Real time to wait at most before looking again; zero once it passed. A clock that
793    /// never got there within [`WAIT`] is an error of the test, not a timeout of the port.
794    fn left(&self) -> io::Result<Duration> {
795        match self {
796            Self::Real(end) => Ok(end.saturating_duration_since(Instant::now())),
797            Self::Clock {
798                clock, at, bound, ..
799            } => {
800                if clock.now() >= *at {
801                    return Ok(Duration::ZERO);
802                }
803                match bound.saturating_duration_since(Instant::now()) {
804                    left if left.is_zero() => Err(io::Error::other(
805                        "fake device: the clock never reached the port timeout",
806                    )),
807                    left => Ok(left),
808                }
809            }
810        }
811    }
812}
813
814/// The host side of a [`FakeDevice`].
815pub struct FakePort {
816    shared: Shared,
817    timeout: Duration,
818    clonable: bool,
819}
820
821impl std::fmt::Debug for FakePort {
822    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
823        f.debug_struct("FakePort")
824            .field("timeout", &self.timeout)
825            .finish_non_exhaustive()
826    }
827}
828
829impl FakePort {
830    fn set(&self, call: Call, f: impl FnOnce(&mut Settings)) -> serialport::Result<()> {
831        self.shared.change(|s| {
832            f(&mut s.settings);
833            s.calls.push(call);
834        });
835        Ok(())
836    }
837
838    fn settings(&self) -> Settings {
839        self.shared.lock().settings.clone()
840    }
841
842    fn read_locked<'a>(
843        &'a self,
844        mut state: MutexGuard<'a, State>,
845        buf: &mut [u8],
846    ) -> (MutexGuard<'a, State>, io::Result<usize>) {
847        let mut deadline = self.deadline(&state);
848        let fails = |kind| Err(io::Error::new(kind, "fake device: read error"));
849        loop {
850            if state.hold_reads {
851                state = self.shared.pass(state, |s| s.hold_reads);
852                deadline = self.deadline(&state);
853            }
854            if let Some(kind) = state.read_error {
855                return (state, fails(kind));
856            }
857            if let (left @ 1.., kind) = state.read_errors_left {
858                state.read_errors_left.0 = left - 1;
859                return (state, fails(kind));
860            }
861            if state.eof_left > 0 {
862                if state.eof_left != usize::MAX {
863                    state.eof_left -= 1;
864                }
865                state.eof_reads += 1;
866                return (state, Ok(0));
867            }
868            if !state.rx.is_empty() {
869                let max = state.faults.chunk.unwrap_or(usize::MAX).max(1);
870                let n = buf.len().min(state.rx.len()).min(max);
871                for (slot, byte) in buf.iter_mut().zip(state.rx.drain(..n)) {
872                    *slot = byte;
873                }
874                return (state, Ok(n));
875            }
876            let left = match deadline.left() {
877                Ok(left) => left,
878                Err(e) => return (state, Err(e)),
879            };
880            if left.is_zero() {
881                let e = io::Error::new(io::ErrorKind::TimedOut, "fake device: no data");
882                return (state, Err(e));
883            }
884            if let Some((clock, at)) = deadline.arm() {
885                // Scheduled without the device lock: a clock may run a due job at once. The
886                // loop looks at the clock again before it waits, so a job that ran meanwhile
887                // is not missed.
888                drop(state);
889                let shared = Arc::downgrade(&self.shared.0);
890                clock.at(
891                    at,
892                    Box::new(move || {
893                        if let Some(shared) = shared.upgrade() {
894                            // Taking the lock orders the wakeup after the read began to wait.
895                            drop(shared.0.lock());
896                            shared.1.notify_all();
897                        }
898                    }),
899                );
900                state = self.shared.lock();
901                continue;
902            }
903            let woken = self.shared.0 .1.wait_timeout(state, left);
904            state = woken.unwrap_or_else(|e| e.into_inner()).0;
905        }
906    }
907
908    /// When a read that starts now times out. On the device clock, a job wakes the read then;
909    /// it is scheduled only once the read has to wait ([`Deadline::arm`]).
910    fn deadline(&self, state: &State) -> Deadline {
911        let Some(clock) = state.clock.clone() else {
912            return Deadline::Real(Instant::now() + self.timeout);
913        };
914        let at = clock.now() + self.timeout;
915        Deadline::Clock {
916            clock,
917            at,
918            bound: Instant::now() + WAIT,
919            armed: false,
920        }
921    }
922}
923
924impl Drop for FakePort {
925    fn drop(&mut self) {
926        self.shared.change(|s| s.ports -= 1);
927    }
928}
929
930impl Read for FakePort {
931    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
932        if buf.is_empty() {
933            return Ok(0);
934        }
935        let mut state = self.shared.lock();
936        state.reading.push(buf.len());
937        self.shared.notify();
938        let (mut state, result) = self.read_locked(state, buf);
939        let asked = state.reading.iter().position(|n| *n == buf.len());
940        asked.map(|i| state.reading.swap_remove(i));
941        drop(state);
942        self.shared.notify();
943        result
944    }
945}
946
947impl Write for FakePort {
948    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
949        let mut state = self.shared.pass(self.shared.lock(), |s| s.hold_writes);
950        if let Some(kind) = state.write_error {
951            return Err(io::Error::new(kind, "fake device: write error"));
952        }
953        state.write_timeouts.push(self.timeout);
954        if state.stall_writes {
955            // The write would end at the port timeout, which is recorded: no need to wait.
956            return Err(io::Error::new(
957                io::ErrorKind::TimedOut,
958                "fake device: write stalled",
959            ));
960        }
961        state.written.extend(buf);
962        state.subscribers.retain_mut(|send| send(buf));
963        if state.responder.is_some() || state.answering {
964            state.unanswered.push_back(buf.to_vec());
965        }
966        drop(state);
967        self.shared.notify();
968        self.shared.answer();
969        Ok(buf.len())
970    }
971
972    fn flush(&mut self) -> io::Result<()> {
973        Ok(())
974    }
975}
976
977impl SerialPort for FakePort {
978    fn name(&self) -> Option<String> {
979        Some("fake".into())
980    }
981    fn baud_rate(&self) -> serialport::Result<u32> {
982        Ok(self.settings().baud_rate)
983    }
984    fn data_bits(&self) -> serialport::Result<DataBits> {
985        Ok(self.settings().data_bits)
986    }
987    fn flow_control(&self) -> serialport::Result<FlowControl> {
988        Ok(self.settings().flow_control)
989    }
990    fn parity(&self) -> serialport::Result<Parity> {
991        Ok(self.settings().parity)
992    }
993    fn stop_bits(&self) -> serialport::Result<StopBits> {
994        Ok(self.settings().stop_bits)
995    }
996    fn timeout(&self) -> Duration {
997        self.timeout
998    }
999    fn set_baud_rate(&mut self, v: u32) -> serialport::Result<()> {
1000        self.set(Call::BaudRate(v), |s| s.baud_rate = v)
1001    }
1002    fn set_data_bits(&mut self, v: DataBits) -> serialport::Result<()> {
1003        self.set(Call::DataBits(v), |s| s.data_bits = v)
1004    }
1005    fn set_flow_control(&mut self, v: FlowControl) -> serialport::Result<()> {
1006        self.set(Call::FlowControl(v), |s| s.flow_control = v)
1007    }
1008    fn set_parity(&mut self, v: Parity) -> serialport::Result<()> {
1009        self.set(Call::Parity(v), |s| s.parity = v)
1010    }
1011    fn set_stop_bits(&mut self, v: StopBits) -> serialport::Result<()> {
1012        self.set(Call::StopBits(v), |s| s.stop_bits = v)
1013    }
1014    fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
1015        self.timeout = timeout;
1016        Ok(())
1017    }
1018    fn write_request_to_send(&mut self, v: bool) -> serialport::Result<()> {
1019        self.set(Call::Rts(v), |_| {})
1020    }
1021    fn write_data_terminal_ready(&mut self, v: bool) -> serialport::Result<()> {
1022        self.set(Call::Dtr(v), |_| {})
1023    }
1024    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
1025        Ok(self.shared.lock().lines.cts)
1026    }
1027    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
1028        Ok(self.shared.lock().lines.dsr)
1029    }
1030    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
1031        Ok(self.shared.lock().lines.ring)
1032    }
1033    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
1034        Ok(self.shared.lock().lines.carrier)
1035    }
1036    fn bytes_to_read(&self) -> serialport::Result<u32> {
1037        let state = self.shared.lock();
1038        Ok(state.driver_pending.unwrap_or(state.rx.len() as u32))
1039    }
1040    fn bytes_to_write(&self) -> serialport::Result<u32> {
1041        Ok(self.shared.lock().out_pending)
1042    }
1043    fn clear(&self, which: ClearBuffer) -> serialport::Result<()> {
1044        self.shared.change(|s| {
1045            if matches!(which, ClearBuffer::Input | ClearBuffer::All) {
1046                s.rx.clear();
1047                s.calls.push(Call::ClearInput);
1048            }
1049            if matches!(which, ClearBuffer::Output | ClearBuffer::All) {
1050                s.calls.push(Call::ClearOutput);
1051            }
1052        });
1053        Ok(())
1054    }
1055    fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
1056        if !self.clonable {
1057            return Err(serialport::Error::new(
1058                serialport::ErrorKind::Unknown,
1059                "fake device: this port has no clones",
1060            ));
1061        }
1062        self.shared.change(|s| s.ports += 1);
1063        Ok(Box::new(FakePort {
1064            shared: self.shared.clone(),
1065            timeout: self.timeout,
1066            clonable: true,
1067        }))
1068    }
1069    fn set_break(&self) -> serialport::Result<()> {
1070        self.set(Call::Break(true), |_| {})
1071    }
1072    fn clear_break(&self) -> serialport::Result<()> {
1073        self.set(Call::Break(false), |_| {})
1074    }
1075}