1use 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
13type Subscriber = Box<dyn FnMut(&[u8]) -> bool + Send>;
15
16#[derive(Debug, Clone, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub struct Faults {
34 pub silent: bool,
36 pub burst: Option<(Vec<u8>, usize)>,
39 pub chunk: Option<usize>,
41 pub delay: Duration,
44}
45
46impl Faults {
47 pub fn silent(mut self, on: bool) -> Self {
49 self.silent = on;
50 self
51 }
52
53 pub fn burst(mut self, bytes: &[u8], times: usize) -> Self {
55 self.burst = Some((bytes.to_vec(), times));
56 self
57 }
58
59 pub fn chunk(mut self, max: usize) -> Self {
61 self.chunk = Some(max.max(1));
62 self
63 }
64
65 pub fn delay(mut self, delay: Duration) -> Self {
67 self.delay = delay;
68 self
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct Lines {
83 pub cts: bool,
85 pub dsr: bool,
87 pub ring: bool,
89 pub carrier: bool,
91}
92
93impl Default for Lines {
94 fn default() -> Self {
96 Self {
97 cts: true,
98 dsr: true,
99 ring: false,
100 carrier: false,
101 }
102 }
103}
104
105impl Lines {
106 pub fn cts(mut self, on: bool) -> Self {
108 self.cts = on;
109 self
110 }
111
112 pub fn dsr(mut self, on: bool) -> Self {
114 self.dsr = on;
115 self
116 }
117
118 pub fn ring(mut self, on: bool) -> Self {
120 self.ring = on;
121 self
122 }
123
124 pub fn carrier(mut self, on: bool) -> Self {
126 self.carrier = on;
127 self
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
133#[non_exhaustive]
134pub enum Call {
135 BaudRate(u32),
137 DataBits(DataBits),
139 FlowControl(FlowControl),
141 Parity(Parity),
143 StopBits(StopBits),
145 Rts(bool),
147 Dtr(bool),
149 Break(bool),
151 ClearInput,
153 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 rx: VecDeque<u8>,
169 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 read_errors_left: (usize, io::ErrorKind),
178 write_error: Option<io::ErrorKind>,
179 eof_left: usize,
181 eof_reads: usize,
182 stall_writes: bool,
183 hold_writes: bool,
184 hold_reads: bool,
185 held: usize,
186 reading: Vec<usize>,
188 driver_pending: Option<u32>,
189 out_pending: u32,
190 ports: usize,
192 handles: usize,
194 responder: Option<Responder>,
195 unanswered: VecDeque<Vec<u8>>,
197 answering: bool,
199 faults: Faults,
200 clock: Option<Arc<dyn Clock>>,
202 system_clock: Option<Arc<dyn Clock>>,
204 subscribers: Vec<Subscriber>,
205 late: VecDeque<Late>,
208 late_seq: u64,
209}
210
211struct Late {
213 id: u64,
214 bytes: Vec<u8>,
215 due: bool,
216}
217
218impl State {
219 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 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 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 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 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 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 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 fn answer(&self) {
356 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 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 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
413pub 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 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 pub fn with_modem(modem: Modem) -> Self {
518 let device = Self::new();
519 device.modem(modem);
520 device
521 }
522
523 pub fn port(&self) -> FakePort {
525 self.open(true)
526 }
527
528 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 pub fn send(&self, bytes: &[u8]) {
545 self.0.change(|s| s.rx.extend(bytes));
546 }
547
548 pub fn unread(&self) -> usize {
550 self.0.lock().rx.len()
551 }
552
553 pub fn wait_read(&self) {
556 self.0.wait("the host read every byte", |s| s.rx.is_empty());
557 }
558
559 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 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 pub fn written(&self) -> Vec<u8> {
577 self.0.lock().written.clone()
578 }
579
580 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 pub fn write_timeouts(&self) -> Vec<Duration> {
588 self.0.lock().write_timeouts.clone()
589 }
590
591 pub fn calls(&self) -> Vec<Call> {
593 self.0.lock().calls.clone()
594 }
595
596 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 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 let _old = self.0.change(|s| s.responder.replace(responder));
615 }
616
617 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 pub fn faults(&self, faults: Faults) {
637 self.0.change(|s| s.faults = faults);
638 }
639
640 pub fn send_after(&self, after: Duration, bytes: &[u8]) {
642 self.0.send_after(after, bytes.to_vec());
643 }
644
645 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 #[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 pub fn fail_reads(&self, kind: io::ErrorKind) {
670 self.0.change(|s| s.read_error = Some(kind));
671 }
672
673 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 pub fn fail_writes(&self, kind: io::ErrorKind) {
680 self.0.change(|s| s.write_error = Some(kind));
681 }
682
683 pub fn stall_writes(&self, on: bool) {
685 self.0.change(|s| s.stall_writes = on);
686 }
687
688 pub fn eof(&self) {
690 self.0.change(|s| s.eof_left = usize::MAX);
691 }
692
693 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 pub fn eof_times(&self, n: usize) {
709 self.0.change(|s| s.eof_left = n);
710 }
711
712 pub fn eof_reads(&self) -> usize {
714 self.0.lock().eof_reads
715 }
716
717 pub fn hold_writes(&self, on: bool) {
719 self.0.change(|s| s.hold_writes = on);
720 }
721
722 pub fn hold_reads(&self, on: bool) {
725 self.0.change(|s| s.hold_reads = on);
726 }
727
728 pub fn held(&self) -> usize {
730 self.0.lock().held
731 }
732
733 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 pub fn set_lines(&self, lines: Lines) {
741 self.0.change(|s| s.lines = lines);
742 }
743
744 pub fn set_driver_pending(&self, n: Option<u32>) {
746 self.0.change(|s| s.driver_pending = n);
747 }
748
749 pub fn set_out_pending(&self, n: u32) {
751 self.0.change(|s| s.out_pending = n);
752 }
753
754 pub fn open_ports(&self) -> usize {
756 self.0.lock().ports
757 }
758
759 pub fn wait_closed(&self) {
761 self.0.wait("the host closed the port", |s| s.ports == 0);
762 }
763}
764
765enum Deadline {
767 Real(Instant),
768 Clock {
770 clock: Arc<dyn Clock>,
771 at: Duration,
772 bound: Instant,
773 armed: bool,
775 },
776}
777
778impl Deadline {
779 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 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
814pub 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 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 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 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 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}