Skip to main content

serialplugin_testing/
fake.rs

1//! An in-memory serial device.
2
3use crate::{Modem, WAIT};
4use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
5use std::collections::VecDeque;
6use std::io::{self, Read, Write};
7use std::sync::{Arc, Condvar, Mutex, MutexGuard};
8use std::time::{Duration, Instant};
9
10type Responder = Box<dyn FnMut(&FakeDevice, &[u8], usize) -> Vec<u8> + Send>;
11
12/// Modem status lines a [`FakeDevice`] reports.
13///
14/// ```
15/// use serialplugin_testing::Lines;
16///
17/// let lines = Lines::default().cts(false).ring(true);
18/// assert!(!lines.cts && lines.dsr && lines.ring && !lines.carrier);
19/// ```
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct Lines {
23    /// Clear to send.
24    pub cts: bool,
25    /// Data set ready.
26    pub dsr: bool,
27    /// Ring indicator.
28    pub ring: bool,
29    /// Carrier detect.
30    pub carrier: bool,
31}
32
33impl Default for Lines {
34    /// A ready device: CTS and DSR on.
35    fn default() -> Self {
36        Self {
37            cts: true,
38            dsr: true,
39            ring: false,
40            carrier: false,
41        }
42    }
43}
44
45impl Lines {
46    /// Set clear to send.
47    pub fn cts(mut self, on: bool) -> Self {
48        self.cts = on;
49        self
50    }
51
52    /// Set data set ready.
53    pub fn dsr(mut self, on: bool) -> Self {
54        self.dsr = on;
55        self
56    }
57
58    /// Set the ring indicator.
59    pub fn ring(mut self, on: bool) -> Self {
60        self.ring = on;
61        self
62    }
63
64    /// Set carrier detect.
65    pub fn carrier(mut self, on: bool) -> Self {
66        self.carrier = on;
67        self
68    }
69}
70
71/// A setting or control call the host made on the port, in order ([`FakeDevice::calls`]).
72#[derive(Debug, Clone, PartialEq, Eq)]
73#[non_exhaustive]
74pub enum Call {
75    /// `set_baud_rate`
76    BaudRate(u32),
77    /// `set_data_bits`
78    DataBits(DataBits),
79    /// `set_flow_control`
80    FlowControl(FlowControl),
81    /// `set_parity`
82    Parity(Parity),
83    /// `set_stop_bits`
84    StopBits(StopBits),
85    /// `write_request_to_send`
86    Rts(bool),
87    /// `write_data_terminal_ready`
88    Dtr(bool),
89    /// `set_break` / `clear_break`
90    Break(bool),
91    /// `clear` of the input (also as part of `All`)
92    ClearInput,
93    /// `clear` of the output (also as part of `All`)
94    ClearOutput,
95}
96
97#[derive(Clone)]
98struct Settings {
99    baud_rate: u32,
100    data_bits: DataBits,
101    flow_control: FlowControl,
102    parity: Parity,
103    stop_bits: StopBits,
104}
105
106struct State {
107    /// Bytes the host has not read yet.
108    rx: VecDeque<u8>,
109    /// Everything the host wrote.
110    written: Vec<u8>,
111    write_timeouts: Vec<Duration>,
112    calls: Vec<Call>,
113    settings: Settings,
114    lines: Lines,
115    read_error: Option<io::ErrorKind>,
116    /// Reads left that fail with the kind.
117    read_errors_left: (usize, io::ErrorKind),
118    write_error: Option<io::ErrorKind>,
119    /// Reads left that return `Ok(0)`.
120    eof_left: usize,
121    eof_reads: usize,
122    stall_writes: bool,
123    hold_writes: bool,
124    hold_reads: bool,
125    held: usize,
126    /// Buffer sizes of the read calls in progress.
127    reading: Vec<usize>,
128    driver_pending: Option<u32>,
129    out_pending: u32,
130    /// Handles of the host.
131    ports: usize,
132    /// Handles of the test.
133    handles: usize,
134    responder: Option<Responder>,
135    /// Writes the responder has not answered yet.
136    unanswered: VecDeque<Vec<u8>>,
137    /// A writer runs the responder (without the lock): it answers the writes of others too.
138    answering: bool,
139}
140
141#[derive(Clone)]
142struct Shared(Arc<(Mutex<State>, Condvar)>);
143
144impl Shared {
145    fn lock(&self) -> MutexGuard<'_, State> {
146        self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
147    }
148
149    fn change<T>(&self, f: impl FnOnce(&mut State) -> T) -> T {
150        let out = f(&mut self.lock());
151        self.0 .1.notify_all();
152        out
153    }
154
155    fn notify(&self) {
156        self.0 .1.notify_all();
157    }
158
159    /// Block while `gate` holds, counted as a held call.
160    fn pass<'a>(
161        &'a self,
162        mut state: MutexGuard<'a, State>,
163        gate: impl Fn(&State) -> bool,
164    ) -> MutexGuard<'a, State> {
165        if gate(&state) {
166            state.held += 1;
167            self.notify();
168            while gate(&state) {
169                state = self.0 .1.wait(state).unwrap_or_else(|e| e.into_inner());
170            }
171            state.held -= 1;
172            self.notify();
173        }
174        state
175    }
176
177    /// Wait until `done` holds; panics with `what` after [`WAIT`].
178    fn wait(&self, what: &str, done: impl Fn(&State) -> bool) {
179        let deadline = Instant::now() + WAIT;
180        let mut state = self.lock();
181        while !done(&state) {
182            let left = deadline.saturating_duration_since(Instant::now());
183            if left.is_zero() {
184                drop(state);
185                panic!("never: {what}");
186            }
187            let woken = self.0 .1.wait_timeout(state, left);
188            state = woken.unwrap_or_else(|e| e.into_inner()).0;
189        }
190    }
191
192    /// Answer the writes not answered yet, in order.
193    fn answer(&self) {
194        /// The responder while it is out; a panic in it puts it back.
195        struct Out<'a> {
196            shared: &'a Shared,
197            responder: Option<Responder>,
198            done: bool,
199        }
200        impl Drop for Out<'_> {
201            fn drop(&mut self) {
202                if self.done {
203                    return;
204                }
205                self.shared.change(|s| {
206                    if s.responder.is_none() {
207                        s.responder = self.responder.take();
208                    }
209                    s.answering = false;
210                });
211            }
212        }
213        {
214            let mut state = self.lock();
215            if state.answering || state.responder.is_none() {
216                return;
217            }
218            state.answering = true;
219        }
220        let device = FakeDevice::handle(self.clone());
221        let mut out = Out {
222            shared: self,
223            responder: None,
224            done: false,
225        };
226        while !out.done {
227            let mut state = self.lock();
228            // The first one, or one an answer has set meanwhile.
229            let mut replaced = None;
230            if let Some(new) = state.responder.take() {
231                replaced = out.responder.replace(new);
232            }
233            let next = state.unanswered.pop_front();
234            let unread = state.rx.len();
235            if next.is_none() {
236                state.responder = out.responder.take();
237                state.answering = false;
238                out.done = true;
239            }
240            // The responder may use its device, also when it is dropped.
241            drop(state);
242            drop(replaced);
243            if let (Some(bytes), Some(responder)) = (next, &mut out.responder) {
244                let reply = responder(&device, &bytes, unread);
245                self.change(|s| s.rx.extend(reply));
246            }
247        }
248    }
249}
250
251/// The device side of an in-memory serial port; clones are handles to the same device.
252///
253/// [`port`](Self::port) gives the host its side, a [`serialport::SerialPort`]. The device
254/// records what the host does and decides what it sees: bytes, errors, held calls.
255///
256/// ```
257/// use serialplugin_testing::FakeDevice;
258/// use std::io::{Read, Write};
259///
260/// let device = FakeDevice::new();
261/// let mut port = device.port();
262/// port.write_all(b"ping").unwrap();
263/// assert_eq!(device.written(), b"ping");
264///
265/// device.send(b"pong");
266/// let mut buf = [0; 4];
267/// port.read_exact(&mut buf).unwrap();
268/// assert_eq!(&buf, b"pong");
269/// ```
270///
271/// Dropping the last `FakeDevice` ends [`hold_reads`](Self::hold_reads) and
272/// [`hold_writes`](Self::hold_writes), so a test that fails while it holds the host does not
273/// hang on the way out.
274pub struct FakeDevice(Shared);
275
276impl Clone for FakeDevice {
277    fn clone(&self) -> Self {
278        Self::handle(self.0.clone())
279    }
280}
281
282impl Drop for FakeDevice {
283    fn drop(&mut self) {
284        self.0.change(|s| {
285            s.handles -= 1;
286            if s.handles == 0 {
287                s.hold_reads = false;
288                s.hold_writes = false;
289            }
290        });
291    }
292}
293
294impl Default for FakeDevice {
295    fn default() -> Self {
296        Self::new()
297    }
298}
299
300impl std::fmt::Debug for FakeDevice {
301    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302        f.debug_struct("FakeDevice").finish_non_exhaustive()
303    }
304}
305
306impl FakeDevice {
307    /// A silent device at 115200 8N1.
308    pub fn new() -> Self {
309        let state = State {
310            rx: VecDeque::new(),
311            written: Vec::new(),
312            write_timeouts: Vec::new(),
313            calls: Vec::new(),
314            settings: Settings {
315                baud_rate: 115_200,
316                data_bits: DataBits::Eight,
317                flow_control: FlowControl::None,
318                parity: Parity::None,
319                stop_bits: StopBits::One,
320            },
321            lines: Lines::default(),
322            read_error: None,
323            read_errors_left: (0, io::ErrorKind::Other),
324            write_error: None,
325            eof_left: 0,
326            eof_reads: 0,
327            stall_writes: false,
328            hold_writes: false,
329            hold_reads: false,
330            held: 0,
331            reading: Vec::new(),
332            driver_pending: None,
333            out_pending: 0,
334            ports: 0,
335            handles: 0,
336            responder: None,
337            unanswered: VecDeque::new(),
338            answering: false,
339        };
340        Self::handle(Shared(Arc::new((Mutex::new(state), Condvar::new()))))
341    }
342
343    fn handle(shared: Shared) -> Self {
344        shared.change(|s| s.handles += 1);
345        Self(shared)
346    }
347
348    /// A device where `modem` answers what the host writes.
349    pub fn with_modem(modem: Modem) -> Self {
350        let device = Self::new();
351        device.modem(modem);
352        device
353    }
354
355    /// The host's port (timeout 1 s). `try_clone` works, as on a real desktop port.
356    pub fn port(&self) -> FakePort {
357        self.open(true)
358    }
359
360    /// Like [`port`](Self::port), but `try_clone` fails: the host has one handle for reads
361    /// and writes.
362    pub fn unclonable_port(&self) -> FakePort {
363        self.open(false)
364    }
365
366    fn open(&self, clonable: bool) -> FakePort {
367        self.0.change(|s| s.ports += 1);
368        FakePort {
369            shared: self.0.clone(),
370            timeout: Duration::from_secs(1),
371            clonable,
372        }
373    }
374
375    /// Send bytes to the host.
376    pub fn send(&self, bytes: &[u8]) {
377        self.0.change(|s| s.rx.extend(bytes));
378    }
379
380    /// Bytes sent that the host has not read yet.
381    pub fn unread(&self) -> usize {
382        self.0.lock().rx.len()
383    }
384
385    /// Wait until the host read everything sent. It may still be handling it: see
386    /// [`wait_handled`](Self::wait_handled).
387    pub fn wait_read(&self) {
388        self.0.wait("the host read every byte", |s| s.rx.is_empty());
389    }
390
391    /// Wait until the host read everything sent and asks for more: a host that reads and
392    /// handles the bytes on one thread has handled them by then.
393    pub fn wait_handled(&self) {
394        self.0.wait("the host handled every byte", |s| {
395            s.rx.is_empty() && !s.reading.is_empty()
396        });
397    }
398
399    /// Wait until a read of the host asks for `size` bytes.
400    pub fn wait_asked(&self, size: usize) {
401        self.0
402            .wait(&format!("the host asks for {size} bytes"), |s| {
403                s.reading.contains(&size)
404            });
405    }
406
407    /// Everything the host wrote so far.
408    pub fn written(&self) -> Vec<u8> {
409        self.0.lock().written.clone()
410    }
411
412    /// Wait until what the host wrote satisfies `done`; returns it.
413    pub fn wait_written(&self, what: &str, done: impl Fn(&[u8]) -> bool) -> Vec<u8> {
414        self.0.wait(what, |s| done(&s.written));
415        self.written()
416    }
417
418    /// The port timeout at each write.
419    pub fn write_timeouts(&self) -> Vec<Duration> {
420        self.0.lock().write_timeouts.clone()
421    }
422
423    /// Setting and control calls so far.
424    pub fn calls(&self) -> Vec<Call> {
425        self.0.lock().calls.clone()
426    }
427
428    /// Answer every write: `reply` gets the device and the written bytes and returns what
429    /// the device sends. Writes are answered one at a time, in order; one made while `reply`
430    /// runs (by another handle, or by `reply` itself) is answered after it.
431    ///
432    /// Use the device it is given: a `FakeDevice` captured by `reply` is never dropped.
433    pub fn respond(&self, mut reply: impl FnMut(&FakeDevice, &[u8]) -> Vec<u8> + Send + 'static) {
434        self.set_responder(Box::new(move |device, bytes, _| reply(device, bytes)));
435    }
436
437    /// Let `modem` answer what the host writes.
438    pub fn modem(&self, mut modem: Modem) {
439        self.set_responder(Box::new(move |_, bytes, unread| {
440            modem.feed_with_unread(bytes, unread)
441        }));
442    }
443
444    fn set_responder(&self, responder: Responder) {
445        // The old one is dropped without the lock.
446        let _old = self.0.change(|s| s.responder.replace(responder));
447    }
448
449    /// Every read fails with `kind` from now on (an unplugged device).
450    pub fn fail_reads(&self, kind: io::ErrorKind) {
451        self.0.change(|s| s.read_error = Some(kind));
452    }
453
454    /// The next `n` reads fail with `kind`, then the device works again.
455    pub fn fail_reads_times(&self, n: usize, kind: io::ErrorKind) {
456        self.0.change(|s| s.read_errors_left = (n, kind));
457    }
458
459    /// Every write fails with `kind` from now on.
460    pub fn fail_writes(&self, kind: io::ErrorKind) {
461        self.0.change(|s| s.write_error = Some(kind));
462    }
463
464    /// Writes time out: the device takes no bytes.
465    pub fn stall_writes(&self, on: bool) {
466        self.0.change(|s| s.stall_writes = on);
467    }
468
469    /// Every read returns `Ok(0)` from now on (a tty after hang-up).
470    pub fn eof(&self) {
471        self.0.change(|s| s.eof_left = usize::MAX);
472    }
473
474    /// The device works again: undoes [`fail_reads`](Self::fail_reads),
475    /// [`fail_reads_times`](Self::fail_reads_times), [`fail_writes`](Self::fail_writes),
476    /// [`stall_writes`](Self::stall_writes), [`eof`](Self::eof) and
477    /// [`eof_times`](Self::eof_times).
478    pub fn recover(&self) {
479        self.0.change(|s| {
480            s.read_error = None;
481            s.read_errors_left.0 = 0;
482            s.write_error = None;
483            s.stall_writes = false;
484            s.eof_left = 0;
485        });
486    }
487
488    /// The next `n` reads return `Ok(0)`.
489    pub fn eof_times(&self, n: usize) {
490        self.0.change(|s| s.eof_left = n);
491    }
492
493    /// Reads that returned `Ok(0)` so far.
494    pub fn eof_reads(&self) -> usize {
495        self.0.lock().eof_reads
496    }
497
498    /// While on, writes block in the device. Ends when the last `FakeDevice` is dropped.
499    pub fn hold_writes(&self, on: bool) {
500        self.0.change(|s| s.hold_writes = on);
501    }
502
503    /// While on, reads block in the device, also one that waits for data already (its
504    /// timeout starts again when it is let go). Ends when the last `FakeDevice` is dropped.
505    pub fn hold_reads(&self, on: bool) {
506        self.0.change(|s| s.hold_reads = on);
507    }
508
509    /// Calls blocked in the device right now.
510    pub fn held(&self) -> usize {
511        self.0.lock().held
512    }
513
514    /// Wait until `n` calls are blocked in the device.
515    pub fn wait_held(&self, n: usize) {
516        self.0
517            .wait("the host is blocked in the device", |s| s.held == n);
518    }
519
520    /// Set the status lines.
521    pub fn set_lines(&self, lines: Lines) {
522        self.0.change(|s| s.lines = lines);
523    }
524
525    /// What `bytes_to_read` reports; `None` is the number of unread bytes.
526    pub fn set_driver_pending(&self, n: Option<u32>) {
527        self.0.change(|s| s.driver_pending = n);
528    }
529
530    /// What `bytes_to_write` reports.
531    pub fn set_out_pending(&self, n: u32) {
532        self.0.change(|s| s.out_pending = n);
533    }
534
535    /// Open handles of the host, clones included; 0 once it closed the port.
536    pub fn open_ports(&self) -> usize {
537        self.0.lock().ports
538    }
539
540    /// Wait until the host dropped every handle.
541    pub fn wait_closed(&self) {
542        self.0.wait("the host closed the port", |s| s.ports == 0);
543    }
544}
545
546/// The host side of a [`FakeDevice`].
547pub struct FakePort {
548    shared: Shared,
549    timeout: Duration,
550    clonable: bool,
551}
552
553impl std::fmt::Debug for FakePort {
554    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
555        f.debug_struct("FakePort")
556            .field("timeout", &self.timeout)
557            .finish_non_exhaustive()
558    }
559}
560
561impl FakePort {
562    fn set(&self, call: Call, f: impl FnOnce(&mut Settings)) -> serialport::Result<()> {
563        self.shared.change(|s| {
564            f(&mut s.settings);
565            s.calls.push(call);
566        });
567        Ok(())
568    }
569
570    fn settings(&self) -> Settings {
571        self.shared.lock().settings.clone()
572    }
573
574    fn read_locked<'a>(
575        &'a self,
576        mut state: MutexGuard<'a, State>,
577        buf: &mut [u8],
578    ) -> (MutexGuard<'a, State>, io::Result<usize>) {
579        let mut deadline = Instant::now() + self.timeout;
580        let fails = |kind| Err(io::Error::new(kind, "fake device: read error"));
581        loop {
582            if state.hold_reads {
583                state = self.shared.pass(state, |s| s.hold_reads);
584                deadline = Instant::now() + self.timeout;
585            }
586            if let Some(kind) = state.read_error {
587                return (state, fails(kind));
588            }
589            if let (left @ 1.., kind) = state.read_errors_left {
590                state.read_errors_left.0 = left - 1;
591                return (state, fails(kind));
592            }
593            if state.eof_left > 0 {
594                if state.eof_left != usize::MAX {
595                    state.eof_left -= 1;
596                }
597                state.eof_reads += 1;
598                return (state, Ok(0));
599            }
600            if !state.rx.is_empty() {
601                let n = buf.len().min(state.rx.len());
602                for (slot, byte) in buf.iter_mut().zip(state.rx.drain(..n)) {
603                    *slot = byte;
604                }
605                return (state, Ok(n));
606            }
607            let left = deadline.saturating_duration_since(Instant::now());
608            if left.is_zero() {
609                let e = io::Error::new(io::ErrorKind::TimedOut, "fake device: no data");
610                return (state, Err(e));
611            }
612            let woken = self.shared.0 .1.wait_timeout(state, left);
613            state = woken.unwrap_or_else(|e| e.into_inner()).0;
614        }
615    }
616}
617
618impl Drop for FakePort {
619    fn drop(&mut self) {
620        self.shared.change(|s| s.ports -= 1);
621    }
622}
623
624impl Read for FakePort {
625    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
626        if buf.is_empty() {
627            return Ok(0);
628        }
629        let mut state = self.shared.lock();
630        state.reading.push(buf.len());
631        self.shared.notify();
632        let (mut state, result) = self.read_locked(state, buf);
633        let asked = state.reading.iter().position(|n| *n == buf.len());
634        asked.map(|i| state.reading.swap_remove(i));
635        drop(state);
636        self.shared.notify();
637        result
638    }
639}
640
641impl Write for FakePort {
642    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
643        let mut state = self.shared.pass(self.shared.lock(), |s| s.hold_writes);
644        if let Some(kind) = state.write_error {
645            return Err(io::Error::new(kind, "fake device: write error"));
646        }
647        state.write_timeouts.push(self.timeout);
648        if state.stall_writes {
649            // The write would end at the port timeout, which is recorded: no need to wait.
650            return Err(io::Error::new(
651                io::ErrorKind::TimedOut,
652                "fake device: write stalled",
653            ));
654        }
655        state.written.extend(buf);
656        if state.responder.is_some() || state.answering {
657            state.unanswered.push_back(buf.to_vec());
658        }
659        drop(state);
660        self.shared.notify();
661        self.shared.answer();
662        Ok(buf.len())
663    }
664
665    fn flush(&mut self) -> io::Result<()> {
666        Ok(())
667    }
668}
669
670impl SerialPort for FakePort {
671    fn name(&self) -> Option<String> {
672        Some("fake".into())
673    }
674    fn baud_rate(&self) -> serialport::Result<u32> {
675        Ok(self.settings().baud_rate)
676    }
677    fn data_bits(&self) -> serialport::Result<DataBits> {
678        Ok(self.settings().data_bits)
679    }
680    fn flow_control(&self) -> serialport::Result<FlowControl> {
681        Ok(self.settings().flow_control)
682    }
683    fn parity(&self) -> serialport::Result<Parity> {
684        Ok(self.settings().parity)
685    }
686    fn stop_bits(&self) -> serialport::Result<StopBits> {
687        Ok(self.settings().stop_bits)
688    }
689    fn timeout(&self) -> Duration {
690        self.timeout
691    }
692    fn set_baud_rate(&mut self, v: u32) -> serialport::Result<()> {
693        self.set(Call::BaudRate(v), |s| s.baud_rate = v)
694    }
695    fn set_data_bits(&mut self, v: DataBits) -> serialport::Result<()> {
696        self.set(Call::DataBits(v), |s| s.data_bits = v)
697    }
698    fn set_flow_control(&mut self, v: FlowControl) -> serialport::Result<()> {
699        self.set(Call::FlowControl(v), |s| s.flow_control = v)
700    }
701    fn set_parity(&mut self, v: Parity) -> serialport::Result<()> {
702        self.set(Call::Parity(v), |s| s.parity = v)
703    }
704    fn set_stop_bits(&mut self, v: StopBits) -> serialport::Result<()> {
705        self.set(Call::StopBits(v), |s| s.stop_bits = v)
706    }
707    fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
708        self.timeout = timeout;
709        Ok(())
710    }
711    fn write_request_to_send(&mut self, v: bool) -> serialport::Result<()> {
712        self.set(Call::Rts(v), |_| {})
713    }
714    fn write_data_terminal_ready(&mut self, v: bool) -> serialport::Result<()> {
715        self.set(Call::Dtr(v), |_| {})
716    }
717    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
718        Ok(self.shared.lock().lines.cts)
719    }
720    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
721        Ok(self.shared.lock().lines.dsr)
722    }
723    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
724        Ok(self.shared.lock().lines.ring)
725    }
726    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
727        Ok(self.shared.lock().lines.carrier)
728    }
729    fn bytes_to_read(&self) -> serialport::Result<u32> {
730        let state = self.shared.lock();
731        Ok(state.driver_pending.unwrap_or(state.rx.len() as u32))
732    }
733    fn bytes_to_write(&self) -> serialport::Result<u32> {
734        Ok(self.shared.lock().out_pending)
735    }
736    fn clear(&self, which: ClearBuffer) -> serialport::Result<()> {
737        self.shared.change(|s| {
738            if matches!(which, ClearBuffer::Input | ClearBuffer::All) {
739                s.rx.clear();
740                s.calls.push(Call::ClearInput);
741            }
742            if matches!(which, ClearBuffer::Output | ClearBuffer::All) {
743                s.calls.push(Call::ClearOutput);
744            }
745        });
746        Ok(())
747    }
748    fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
749        if !self.clonable {
750            return Err(serialport::Error::new(
751                serialport::ErrorKind::Unknown,
752                "fake device: this port has no clones",
753            ));
754        }
755        self.shared.change(|s| s.ports += 1);
756        Ok(Box::new(FakePort {
757            shared: self.shared.clone(),
758            timeout: self.timeout,
759            clonable: true,
760        }))
761    }
762    fn set_break(&self) -> serialport::Result<()> {
763        self.set(Call::Break(true), |_| {})
764    }
765    fn clear_break(&self) -> serialport::Result<()> {
766        self.set(Call::Break(false), |_| {})
767    }
768}