cat-dev-serial 0.0.14

A library for interacting with the serial port of a CAT-DEV hardware unit distributed by Nintendo (i.e. a type of Wii-U DevKits).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
use crate::underlying::sys::DEFAULT_TIMEOUT_MS;
use libc::{O_NOCTTY, O_NONBLOCK};
use std::{
	fs::{File, OpenOptions},
	io::{Error as IoError, ErrorKind as IoErrorKind, IoSlice, IoSliceMut, Result as IoResult},
	os::{
		raw::{c_int, c_short},
		unix::{fs::OpenOptionsExt, io::AsRawFd},
	},
	path::{Path, PathBuf},
	time::Duration,
};
use valuable::{Fields, NamedField, NamedValues, StructDef, Structable, Valuable, Value, Visit};

#[cfg(all(
	any(target_os = "android", target_os = "linux"),
	not(any(target_arch = "powerpc", target_arch = "powerpc64"))
))]
pub type RawTermios = libc::termios2;
#[cfg(not(all(
	any(target_os = "android", target_os = "linux"),
	not(any(target_arch = "powerpc", target_arch = "powerpc64"))
)))]
pub type RawTermios = libc::termios;

#[derive(Debug)]
pub struct RawSyncSerialPort {
	pub fd: File,
	pub read_timeout_ms: u32,
	pub write_timeout_ms: u32,
}

impl RawSyncSerialPort {
	/// Attempt to connect to a new raw serial port.
	///
	/// ## Errors
	///
	/// If we cannot open the file to the serial port device, or if we cannot
	/// configure it appropriately for talking with a cat-dev device.
	pub fn new(path: impl AsRef<Path>) -> IoResult<Self> {
		let this = Self {
			fd: OpenOptions::new()
				.read(true)
				.write(true)
				.create(false)
				.custom_flags(O_NONBLOCK | O_NOCTTY)
				.open(path)?,
			read_timeout_ms: DEFAULT_TIMEOUT_MS,
			write_timeout_ms: DEFAULT_TIMEOUT_MS,
		};

		let mut termios = Self::get_termios_from_fd(&this.fd)?;
		Self::set_baud_rate(&mut termios)?;
		termios.c_cflag = (termios.c_cflag & !libc::CSIZE) | libc::CS8;
		termios.c_cflag = termios.c_cflag & !libc::PARODD & !libc::PARENB;
		termios.c_cflag &= !libc::CSTOPB;
		Self::set_termios_on_fd(&this.fd, &termios)?;

		Ok(this)
	}

	/// Attempt to clone this particular object.
	///
	/// ## Errors
	///
	/// If we cannot end up cloning the file descriptor.
	pub fn try_clone(&self) -> IoResult<Self> {
		Ok(Self {
			fd: self.fd.try_clone()?,
			read_timeout_ms: self.read_timeout_ms,
			write_timeout_ms: self.write_timeout_ms,
		})
	}

	/// Get the read timeout for this serial port.
	///
	/// ## Errors
	///
	/// Never, used for API compatability with windows which can fail.
	#[allow(
		// Windows needs a result type here, and we want to match signatures.
		clippy::unnecessary_wraps,
	)]
	pub fn get_read_timeout(&self) -> IoResult<Duration> {
		Ok(Duration::from_millis(self.read_timeout_ms.into()))
	}

	/// Get the write timeout for this serial port.
	///
	/// ## Errors
	///
	/// Never, used for API compatability with windows which can fail.
	#[allow(
		// Windows needs a result type here, and we want to match signatures.
		clippy::unnecessary_wraps,
	)]
	pub fn get_write_timeout(&self) -> IoResult<Duration> {
		Ok(Duration::from_millis(self.write_timeout_ms.into()))
	}

	/// Set the read timeout for this serial port.
	///
	/// ## Errors
	///
	/// If the timeout is not between 1, or 4294967294 millisecds (aka 1ms,
	/// and ~50 days).
	pub fn set_read_timeout(&mut self, new_timeout: Duration) -> IoResult<()> {
		let timeout_ms = new_timeout.as_millis();
		if timeout_ms < 1 || timeout_ms > (u32::MAX - 1).into() {
			return Err(IoError::other(
				"read timeout must be between 1, and 4294967294",
			));
		}
		self.read_timeout_ms = timeout_ms.try_into().unwrap_or(u32::MAX);
		Ok(())
	}

	/// Set the write timeout for this serial port.
	///
	/// ## Errors
	///
	/// If the timeout is not between 1, or 4294967294 millisecds (aka 1ms,
	/// and ~50 days).
	pub fn set_write_timeout(&mut self, new_timeout: Duration) -> IoResult<()> {
		let timeout_ms = new_timeout.as_millis();
		if timeout_ms < 1 || timeout_ms > (u32::MAX - 1).into() {
			return Err(IoError::other(
				"write timeout must be between 1, and 4294967294",
			));
		}
		self.write_timeout_ms = timeout_ms.try_into().unwrap_or(u32::MAX);
		Ok(())
	}

	/// Attempt to read data into a buffer from the serial port.
	///
	/// ## Errors
	///
	/// If we get an error from the OS attempting to read bytes from the OS.
	#[allow(
		// We manually check that sign loss isn't an issue.
		clippy::cast_sign_loss,
	)]
	pub fn read(&self, buff: &mut [u8]) -> IoResult<usize> {
		if !Self::poll(&self.fd, libc::POLLIN, self.read_timeout_ms)? {
			return Err(IoErrorKind::TimedOut.into());
		}

		loop {
			match unsafe {
				Self::check_isize(libc::read(
					self.fd.as_raw_fd(),
					buff.as_mut_ptr().cast(),
					buff.len() as _,
				))
			} {
				Ok(size) => return Ok(size as usize),
				Err(cause) => {
					if cause.raw_os_error() == Some(libc::EINTR) {
						continue;
					}

					return Err(cause);
				}
			}
		}
	}

	/// If this implementation supports vectored reads.
	#[must_use]
	pub const fn can_read_vectored() -> bool {
		true
	}

	/// Attempt to read from multiple ranges at once, aka perform a "vectored"
	/// read.
	///
	/// ## Errors
	///
	/// If we timeout waiting for the device to become ready, or if we cannot
	/// execute the `readv` system call.
	#[allow(
		// Truncation is okay in this api.
		clippy::cast_possible_truncation,
		// Wrapping is okay in this API.
		clippy::cast_possible_wrap,
		// We manually check to ensure sign loss isn't a big deal.
		clippy::cast_sign_loss,
	)]
	pub fn read_vectored(&self, buff: &mut [IoSliceMut<'_>]) -> IoResult<usize> {
		if !Self::poll(&self.fd, libc::POLLIN, self.read_timeout_ms)? {
			return Err(IoErrorKind::TimedOut.into());
		}

		loop {
			match unsafe {
				Self::check_isize(libc::readv(
					self.fd.as_raw_fd(),
					buff.as_mut_ptr().cast(),
					buff.len() as _,
				))
			} {
				Ok(read) => return Ok(read as usize),
				Err(cause) => {
					if cause.raw_os_error() == Some(libc::EINTR) {
						continue;
					}

					return Err(cause);
				}
			}
		}
	}

	/// Attempt to write data from a buffer to the serial port.
	///
	/// ## Errors
	///
	/// If we get an error from the OS attempting to write bytes from the OS.
	#[allow(
		// Truncation is okay for this API.
		clippy::cast_possible_truncation,
		// Wrapping is okay for this API.
		clippy::cast_possible_wrap,
		// We validate manually the sign loss isn't an issue.
		clippy::cast_sign_loss,
	)]
	pub fn write(&self, buff: &[u8]) -> IoResult<usize> {
		if !Self::poll(&self.fd, libc::POLLOUT, self.write_timeout_ms)? {
			return Err(IoErrorKind::TimedOut.into());
		}

		loop {
			match unsafe {
				Self::check_isize(libc::write(
					self.fd.as_raw_fd(),
					buff.as_ptr().cast(),
					buff.len() as _,
				))
			} {
				Ok(size) => return Ok(size as usize),
				Err(cause) => {
					if cause.raw_os_error() == Some(libc::EINTR) {
						continue;
					}

					return Err(cause);
				}
			}
		}
	}

	/// If this implementation supports vectored writes.
	#[must_use]
	pub const fn can_write_vectored() -> bool {
		true
	}

	/// Attempt to write to multiple ranges at once, aka perform a "vectored"
	/// write.
	///
	/// ## Errors
	///
	/// If we timeout waiting for the device to become ready, or if we cannot
	/// execute the `writev` system call.
	#[allow(
		// Wrapping is okay for this API.
		clippy::cast_possible_wrap,
		// Truncation is okay in this API.
		clippy::cast_possible_truncation,
		// We validate sign loss isn't an issue manually.
		clippy::cast_sign_loss,
	)]
	pub fn write_vectored(&self, buff: &[IoSlice<'_>]) -> IoResult<usize> {
		if !Self::poll(&self.fd, libc::POLLOUT, self.write_timeout_ms)? {
			return Err(IoErrorKind::TimedOut.into());
		}

		loop {
			match unsafe {
				Self::check_isize(libc::writev(
					self.fd.as_raw_fd(),
					buff.as_ptr().cast(),
					buff.len() as _,
				))
			} {
				Ok(read) => return Ok(read as usize),
				Err(cause) => {
					if cause.raw_os_error() == Some(libc::EINTR) {
						continue;
					}

					return Err(cause);
				}
			}
		}
	}

	/// Flush all output to the serial port.
	///
	/// ## Errors
	///
	/// If we cannot call `tcdrain`, or it returns an error.
	pub fn flush_output(&self) -> IoResult<()> {
		unsafe {
			Self::check(libc::tcdrain(self.fd.as_raw_fd()))?;
		}

		Ok(())
	}

	/// Attempt to discard any existing buffers.
	///
	/// ## Errors
	///
	/// If `tcflush` returns an error from the OS.
	pub fn discard_buffers(&self, discard_input: bool, discard_output: bool) -> IoResult<()> {
		let mut flags = 0;
		if discard_input && discard_output {
			flags |= libc::TCIOFLUSH;
		} else if discard_input {
			flags |= libc::TCIFLUSH;
		} else if discard_output {
			flags |= libc::TCOFLUSH;
		}

		unsafe {
			Self::check(libc::tcflush(self.fd.as_raw_fd(), flags))?;
		}

		Ok(())
	}

	/// Set the (request-to-send) signal to on or off.
	///
	/// ## Errors
	///
	/// If we get an error calling `EscapeCommFunction`.
	pub fn set_rts(&self, state: bool) -> IoResult<()> {
		Self::set_pin(&self.fd, libc::TIOCM_RTS, state)
	}

	/// Check the clear-to-send signal of a serial device.
	///
	/// ## Errors
	///
	/// If we cannot call the underlying OS APIs.
	pub fn read_cts(&self) -> IoResult<bool> {
		Self::read_pin(&self.fd, libc::TIOCM_CTS)
	}

	/// Set the (data-terminal-ready) signal.
	///
	/// ## Errors
	///
	/// If we cannot call the underlying OS APIs.
	pub fn set_dtr(&self, state: bool) -> IoResult<()> {
		Self::set_pin(&self.fd, libc::TIOCM_DTR, state)
	}

	/// Check the data-set-ready signal of a serial device.
	///
	/// ## Errors
	///
	/// If we cannot call the underlying OS APIs.
	pub fn read_dsr(&self) -> IoResult<bool> {
		Self::read_pin(&self.fd, libc::TIOCM_DSR)
	}

	/// Check the ring indicator signal of a serial device.
	///
	/// ## Errors
	///
	/// If we cannot call the underlying OS APIs.
	pub fn read_ri(&self) -> IoResult<bool> {
		Self::read_pin(&self.fd, libc::TIOCM_RI)
	}

	/// Check the carrier detect signal of a serial device.
	///
	/// ## Errors
	///
	/// If we cannot call the underlying OS APIs.
	pub fn read_cd(&self) -> IoResult<bool> {
		Self::read_pin(&self.fd, libc::TIOCM_CD)
	}

	/// Enumerate all possible serial devices.
	///
	/// ## Errors
	///
	/// If we cannot look at the OS for the possible OS devices.
	#[cfg(any(
		target_os = "dragonfly",
		target_os = "freebsd",
		target_os = "ios",
		target_os = "macos",
		target_os = "netbsd",
		target_os = "openbsd",
	))]
	pub fn enumerate() -> IoResult<Vec<PathBuf>> {
		use std::os::unix::{ffi::OsStrExt, fs::FileTypeExt};

		Ok(std::fs::read_dir("/dev")?
			.filter_map(|resulting_entry| {
				let entry = resulting_entry.ok()?;
				let kind = entry.metadata().ok()?.file_type();
				if kind.is_char_device() && Self::is_tty_name(entry.file_name().as_bytes()) {
					Some(entry.path())
				} else {
					None
				}
			})
			.collect())
	}

	#[cfg(any(target_os = "linux", target_os = "android"))]
	pub fn enumerate() -> IoResult<Vec<PathBuf>> {
		use std::os::unix::{ffi::OsStrExt, fs::FileTypeExt};

		Ok(std::fs::read_dir("/sys/class/tty")?
			.filter_map(|resulting_entry| {
				let entry = resulting_entry.ok()?;
				let base_name = entry.file_name();

				let dev_path = Path::new("/dev").join(&base_name);
				let metadata = dev_path.metadata().ok()?;
				if !metadata.file_type().is_char_device() {
					return None;
				}

				match base_name.as_bytes().strip_prefix(b"tty") {
					// Skip entries just called "tty", or things not starting with "tty",
					// probably not a serial port
					Some(b"") | None => return None,
					// Skip "tty1", "tty2", etc (these these are virtual terminals,
					// not serial ports).
					Some(&[c, ..]) if c.is_ascii_digit() => return None,
					// Accept the rest.
					Some(_) => (),
				}

				// There's a bunch of ttyS* ports that are not really serial ports.
				//
				// They have a file called `device/driver_override` set to "(null)".
				if let Ok(driver_override) =
					std::fs::read(entry.path().join("device/driver_override"))
					&& driver_override == b"(null)\n"
				{
					return None;
				}

				Some(dev_path)
			})
			.collect())
	}

	#[cfg(any(target_os = "illumos", target_os = "solaris"))]
	pub fn enumerate() -> IoResult<Vec<PathBuf>> {
		use std::os::unix::fs::FileTypeExt;

		// https://illumos.org/man/1M/ports
		// Let's hope Solaris is doing the same.
		// If only Oracle actually had navigatable documentation.
		let cua = std::fs::read_dir("/dev/cua")?;
		let term = std::fs::read_dir("/dev/cua")?;

		Ok(cua
			.chain(term)
			.filter_map(|entry| {
				let entry = entry.ok()?;
				let kind = entry.metadata().ok()?.file_type();
				if kind.is_char_device() {
					Some(entry.path())
				} else {
					None
				}
			})
			.collect())
	}

	#[cfg(not(any(
		target_os = "dragonfly",
		target_os = "freebsd",
		target_os = "ios",
		target_os = "macos",
		target_os = "netbsd",
		target_os = "openbsd",
		target_os = "illumos",
		target_os = "solaris",
		target_os = "linux",
		target_os = "android",
	)))]
	pub fn enumerate() -> IoResult<Vec<PathBuf>> {
		Err(IoError::new(
			IoErrorKind::Other,
			"port enumeration is not implemented for this platform",
		))
	}

	#[cfg(any(target_os = "ios", target_os = "macos"))]
	fn is_tty_name(name: &[u8]) -> bool {
		// Sigh, closed source doesn't have to mean undocumented.
		// Anyway:
		// https://stackoverflow.com/questions/14074413/serial-port-names-on-mac-os-x
		// https://learn.adafruit.com/ftdi-friend/com-slash-serial-port-name
		name.starts_with(b"tty.") || name.starts_with(b"cu.")
	}

	#[cfg(any(
		target_os = "dragonfly",
		target_os = "freebsd",
		target_os = "netbsd",
		target_os = "openbsd",
	))]
	fn is_tty_name(name: &[u8]) -> bool {
		// For BSD variants, we simply report all entries in /dev that look like a TTY.
		// This may contain a lot of false positives for pseudo-terminals or other fake terminals.
		// If anyone can improve this for a specific BSD they love, by all means send a PR.

		// https://man.dragonflybsd.org/?command=sio&section=4
		// https://leaf.dragonflybsd.org/cgi/web-man?command=ucom&section=ANY
		#[cfg(target_os = "dragonfly")]
		const PREFIXES: [&[u8]; 4] = [b"ttyd", b"cuaa", b"ttyU", b"cuaU"];

		// https://www.freebsd.org/cgi/man.cgi?query=uart&sektion=4&apropos=0&manpath=FreeBSD+13.0-RELEASE+and+Ports
		// https://www.freebsd.org/cgi/man.cgi?query=ucom&sektion=4&apropos=0&manpath=FreeBSD+13.0-RELEASE+and+Ports
		#[cfg(target_os = "freebsd")]
		const PREFIXES: [&[u8]; 5] = [b"ttyu", b"cuau", b"cuad", b"ttyU", b"cuaU"];

		// https://man.netbsd.org/com.4
		// https://man.netbsd.org/ucom.4
		#[cfg(target_os = "netbsd")]
		const PREFIXES: [&[u8]; 4] = [b"tty", b"dty", b"ttyU", b"dtyU"];

		// https://man.openbsd.org/com
		// https://man.openbsd.org/ucom
		#[cfg(target_os = "openbsd")]
		const PREFIXES: [&[u8]; 4] = [b"tty", b"cua", b"ttyU", b"cuaU"];

		for prefix in PREFIXES {
			if let Some(suffix) = name.strip_prefix(prefix) {
				if !suffix.is_empty() && suffix.iter().all(|c| c.is_ascii_digit()) {
					return true;
				}
			}
		}

		false
	}

	/// Poll a file descriptor for an event being ready.
	///
	/// ## Errors
	///
	/// If we cannot poll the file descriptor.
	#[allow(
		// Wrapping is okay here.
		clippy::cast_possible_wrap,
	)]
	fn poll(fd: &File, events: c_short, timeout_ms: u32) -> IoResult<bool> {
		let mut poll_fd = libc::pollfd {
			fd: fd.as_raw_fd(),
			events,
			revents: 0,
		};
		unsafe {
			Self::check(libc::poll(&raw mut poll_fd, 1, timeout_ms as i32))?;
		}
		Ok(poll_fd.revents != 0)
	}

	/// Read the pin of a particular serial device.
	///
	/// ## Errors
	///
	/// If we cannot call `ioctl` on the file descriptor.
	fn read_pin(fd: &File, pin: c_int) -> IoResult<bool> {
		let mut bits: c_int = 0;
		unsafe {
			Self::check(libc::ioctl(fd.as_raw_fd(), libc::TIOCMGET as _, &mut bits))?;
		}
		Ok(bits & pin != 0)
	}

	/// Set the pin of a particular serial device.
	///
	/// ## Errors
	///
	/// If we cannot call `ioctl` on the file descriptor.
	fn set_pin(fd: &File, pin: c_int, state: bool) -> IoResult<()> {
		unsafe {
			Self::check(libc::ioctl(
				fd.as_raw_fd(),
				if state {
					libc::TIOCMBIS
				} else {
					libc::TIOCMBIC
				} as _,
				&pin,
			))?;
		}

		Ok(())
	}

	/// Small wrapper function to perform setting the baud rate flags
	/// appropriately.
	///
	/// ## Errors
	///
	/// If we get an error back from the OS attempting to set some speeds.
	#[allow(
		// Certain paths need the return type to be a result, others do not.
		clippy::unnecessary_wraps,
	)]
	fn set_baud_rate(termios: &mut RawTermios) -> IoResult<()> {
		#[cfg(any(
			target_os = "dragonfly",
			target_os = "freebsd",
			target_os = "ios",
			target_os = "macos",
			target_os = "netbsd",
			target_os = "openbsd",
		))]
		unsafe {
			Self::check(libc::cfsetospeed(termios, 57600 as _))?;
			Self::check(libc::cfsetispeed(termios, 57600 as _))?;
			Ok(())
		}

		#[cfg(all(
			not(any(
				target_os = "dragonfly",
				target_os = "freebsd",
				target_os = "ios",
				target_os = "macos",
				target_os = "netbsd",
				target_os = "openbsd",
			)),
			any(target_os = "android", target_os = "linux"),
			not(any(target_arch = "powerpc", target_arch = "powerpc64"))
		))]
		{
			termios.c_cflag &= !(libc::CBAUD | libc::CIBAUD);
			termios.c_cflag |= libc::BOTHER;
			termios.c_cflag |= libc::BOTHER << libc::IBSHIFT;
			termios.c_ospeed = 57600;
			termios.c_ispeed = 57600;
			Ok(())
		}

		#[cfg(all(
			not(any(
				target_os = "dragonfly",
				target_os = "freebsd",
				target_os = "ios",
				target_os = "macos",
				target_os = "netbsd",
				target_os = "openbsd",
			)),
			not(all(
				any(target_os = "android", target_os = "linux"),
				not(any(target_arch = "powerpc", target_arch = "powerpc64"))
			)),
		))]
		unsafe {
			Self::check(libc::cfsetospeed(termios, libc::B57600))?;
			Self::check(libc::cfsetispeed(termios, libc::B57600))?;
			Ok(())
		}
	}

	/// Get the terminal interface flags for a particular file descriptor.
	///
	/// ## Errors
	///
	/// If we cannot call the appropriate api, or get an error back from the OS.
	fn get_termios_from_fd(fd: &File) -> IoResult<RawTermios> {
		#[cfg(all(
			any(target_os = "android", target_os = "linux"),
			not(any(target_arch = "powerpc", target_arch = "powerpc64"))
		))]
		unsafe {
			let mut termios = std::mem::zeroed();
			Self::check(libc::ioctl(
				fd.as_raw_fd(),
				libc::TCGETS2 as _,
				&mut termios,
			))?;
			Ok(termios)
		}

		#[cfg(not(all(
			any(target_os = "android", target_os = "linux"),
			not(any(target_arch = "powerpc", target_arch = "powerpc64"))
		)))]
		unsafe {
			let mut termios = std::mem::zeroed();
			Self::check(libc::tcgetattr(fd.as_raw_fd(), &mut termios))?;
			Ok(termios)
		}
	}

	/// Set the terminal interface flags on a file descriptor.
	///
	/// ## Errors
	///
	/// If we cannot call the appropriate api either `ioctl`, or `tcsetattr`
	/// on the underlying file descriptor, or we get an error back from the OS.
	fn set_termios_on_fd(fd: &File, termios: &RawTermios) -> IoResult<()> {
		#[cfg(all(
			any(target_os = "android", target_os = "linux"),
			not(any(target_arch = "powerpc", target_arch = "powerpc64"))
		))]
		unsafe {
			Self::check(libc::ioctl(fd.as_raw_fd(), libc::TCSETSW2 as _, termios))?;
			Ok(())
		}

		#[cfg(not(all(
			any(target_os = "android", target_os = "linux"),
			not(any(target_arch = "powerpc", target_arch = "powerpc64"))
		)))]
		unsafe {
			Self::check(libc::tcsetattr(fd.as_raw_fd(), libc::TCSADRAIN, termios))?;
			Ok(())
		}
	}

	/// Check a return code and turn it into an OS Error.
	///
	/// ## Errors
	///
	/// If the OS returns an error code that is -1.
	fn check(ret: i32) -> IoResult<i32> {
		if ret == -1 {
			Err(IoError::last_os_error())
		} else {
			Ok(ret)
		}
	}

	/// Check a return size and turn it into an OS Error.
	///
	/// ## Errors
	///
	/// If the OS returns an error code that is -1.
	fn check_isize(ret: isize) -> IoResult<isize> {
		if ret == -1 {
			Err(IoError::last_os_error())
		} else {
			Ok(ret)
		}
	}
}

const RAW_SYNC_SERIAL_PORT_FIELDS: &[NamedField<'static>] = &[
	NamedField::new("fd"),
	NamedField::new("read_timeout_ms"),
	NamedField::new("write_timeout_ms"),
];

impl Structable for RawSyncSerialPort {
	fn definition(&self) -> StructDef<'_> {
		StructDef::new_static(
			"RawSyncSerialPortFields",
			Fields::Named(RAW_SYNC_SERIAL_PORT_FIELDS),
		)
	}
}

impl Valuable for RawSyncSerialPort {
	fn as_value(&self) -> Value<'_> {
		Value::Structable(self)
	}

	fn visit(&self, visitor: &mut dyn Visit) {
		visitor.visit_named_fields(&NamedValues::new(
			RAW_SYNC_SERIAL_PORT_FIELDS,
			&[
				Valuable::as_value(&format!("{:?}", self.fd)),
				Valuable::as_value(&self.read_timeout_ms),
				Valuable::as_value(&self.write_timeout_ms),
			],
		));
	}
}