serialplugin_testing/
peer.rs1use crate::{Modem, WAIT};
4use std::io::{self, ErrorKind, Read, Write};
5use std::net::{TcpListener, TcpStream};
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::Arc;
8use std::thread::JoinHandle;
9use std::time::{Duration, Instant};
10
11const POLL: Duration = Duration::from_millis(20);
13
14pub trait Io: Read + Write + Send {
16 fn bound_reads(&mut self, timeout: Duration) -> io::Result<()>;
18
19 fn bound_writes(&mut self, timeout: Duration) -> io::Result<()>;
21
22 fn reopens(&self) -> bool {
24 false
25 }
26}
27
28impl Io for TcpStream {
29 fn bound_reads(&mut self, timeout: Duration) -> io::Result<()> {
30 self.set_read_timeout(Some(timeout))
31 }
32
33 fn bound_writes(&mut self, timeout: Duration) -> io::Result<()> {
34 self.set_write_timeout(Some(timeout))
35 }
36}
37
38#[cfg(unix)]
39impl Io for serialport::TTYPort {
40 fn bound_reads(&mut self, timeout: Duration) -> io::Result<()> {
41 Ok(serialport::SerialPort::set_timeout(self, timeout)?)
42 }
43
44 fn bound_writes(&mut self, timeout: Duration) -> io::Result<()> {
45 self.bound_reads(timeout)
46 }
47
48 fn reopens(&self) -> bool {
49 true
50 }
51}
52
53pub fn tcp_listener() -> (TcpListener, String) {
55 let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
56 let path = format!("tcp://{}", listener.local_addr().unwrap());
57 (listener, path)
58}
59
60pub fn accept(listener: &TcpListener) -> TcpStream {
63 listener.set_nonblocking(true).unwrap();
64 let deadline = Instant::now() + WAIT;
65 let accepted = loop {
66 match listener.accept() {
67 Err(e) if e.kind() == ErrorKind::WouldBlock && Instant::now() < deadline => {
68 std::thread::park_timeout(Duration::from_millis(1));
69 }
70 other => break other,
71 }
72 };
73 listener.set_nonblocking(false).unwrap();
74 let (mut stream, _) = accepted.unwrap_or_else(|e| panic!("the host did not connect: {e}"));
75 stream.set_nonblocking(false).unwrap();
76 stream.bound_reads(POLL).unwrap();
77 stream
78}
79
80pub fn recv_until(io: &mut dyn Io, done: impl Fn(&[u8]) -> bool) -> Vec<u8> {
83 let deadline = Instant::now() + WAIT;
84 let mut got = Vec::new();
85 io.bound_reads(POLL).expect("the device side is open");
86 while !done(&got) {
87 let closed = match read_some(io) {
88 Got::Data(bytes) => {
89 got.extend(bytes);
90 false
91 }
92 Got::Nothing => false,
93 Got::Closed => true,
94 };
95 let text = || String::from_utf8_lossy(&got).into_owned();
96 assert!(
97 !closed || io.reopens(),
98 "the host closed the connection, got {:?}",
99 text()
100 );
101 assert!(
102 Instant::now() < deadline,
103 "the host never sent it{}, got {:?}",
104 if closed { " (the port is closed)" } else { "" },
105 text()
106 );
107 if closed {
108 std::thread::park_timeout(POLL);
109 }
110 }
111 got
112}
113
114enum Got {
115 Data(Vec<u8>),
116 Nothing,
118 Closed,
120}
121
122fn read_some(io: &mut dyn Io) -> Got {
123 let mut buf = [0; 256];
124 match io.read(&mut buf) {
125 Ok(0) => Got::Closed,
126 Ok(n) => Got::Data(buf[..n].to_vec()),
127 Err(e) if is_transient(&e) => Got::Nothing,
128 Err(_) => Got::Closed,
130 }
131}
132
133fn is_transient(e: &io::Error) -> bool {
134 matches!(
135 e.kind(),
136 ErrorKind::TimedOut | ErrorKind::WouldBlock | ErrorKind::Interrupted
137 )
138}
139
140pub fn serve(mut io: Box<dyn Io>, mut modem: Modem) -> Server {
144 let stop = Arc::new(AtomicBool::new(false));
145 let stopped = stop.clone();
146 let thread = std::thread::spawn(move || {
147 if io.bound_reads(POLL).and(io.bound_writes(POLL)).is_err() {
148 return;
149 }
150 let mut reply = Vec::new();
151 while !stopped.load(Ordering::SeqCst) {
152 let closed = if reply.is_empty() {
153 match read_some(io.as_mut()) {
154 Got::Data(bytes) => {
155 reply = modem.feed(&bytes);
156 false
157 }
158 Got::Nothing => false,
159 Got::Closed => true,
160 }
161 } else {
162 match io.write(&reply) {
164 Ok(0) => true,
165 Ok(n) => {
166 reply.drain(..n);
167 false
168 }
169 Err(e) => !is_transient(&e),
170 }
171 };
172 if closed && !io.reopens() {
173 return;
174 }
175 if closed {
176 reply.clear();
178 std::thread::park_timeout(POLL);
179 }
180 }
181 });
182 Server {
183 stop,
184 thread: Some(thread),
185 }
186}
187
188#[must_use = "the device is served until the Server is dropped"]
190#[derive(Debug)]
191pub struct Server {
192 stop: Arc<AtomicBool>,
193 thread: Option<JoinHandle<()>>,
194}
195
196impl Drop for Server {
197 fn drop(&mut self) {
198 self.stop.store(true, Ordering::SeqCst);
199 if let Some(thread) = self.thread.take() {
200 thread.thread().unpark();
201 let _ = thread.join();
202 }
203 }
204}
205
206#[cfg(unix)]
208#[derive(Debug)]
209#[non_exhaustive]
210pub struct Pty {
211 pub device: serialport::TTYPort,
213 pub host: serialport::TTYPort,
215 pub path: String,
217}
218
219#[cfg(unix)]
221pub fn pty() -> Pty {
222 use serialport::SerialPort;
223 static PAIR: std::sync::Mutex<()> = std::sync::Mutex::new(());
225 let guard = PAIR.lock().unwrap_or_else(|e| e.into_inner());
226 let (mut device, host) = serialport::TTYPort::pair().expect("pty pair");
227 drop(guard);
228 let path = host.name().expect("slave name");
229 device.set_timeout(POLL).unwrap();
230 Pty { device, host, path }
231}