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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! # mio-serial - Serial port I/O for mio
//!
//! This crate provides a serial port implementation compatable with mio.
//!
//! **Windows support is present but largely untested by the author**
//!
//! ## Links
//!   - repo:  <https://github.com/berkowski/mio-serial>
//!   - docs:  <https://docs.rs/mio-serial>
#![deny(missing_docs)]
#![warn(rust_2018_idioms)]

// Enums, Structs, and Traits from the serialport crate
pub use serialport::{
    // Enums
    ClearBuffer,
    DataBits,
    // Structs
    Error,
    ErrorKind,
    FlowControl,
    Parity,
    // Types
    Result,
    // Traits
    SerialPort,
    SerialPortBuilder,
    SerialPortInfo,
    SerialPortType,
    StopBits,
    UsbPortInfo,
};

// Re-export port-enumerating utility function.
pub use serialport::available_ports;

// Re-export creation of SerialPortBuilder objects
pub use serialport::new;

use mio::{event::Source, Interest, Registry, Token};
use std::convert::TryFrom;
use std::io::{Error as StdIoError, ErrorKind as StdIoErrorKind, Result as StdIoResult};
use std::time::Duration;

#[cfg(unix)]
mod os_prelude {
    pub use mio::unix::SourceFd;
    pub use nix::{self, libc};
    pub use serialport::TTYPort as NativeBlockingSerialPort;
    pub use std::os::unix::prelude::*;
}

#[cfg(windows)]
mod os_prelude {
    pub use mio::windows::NamedPipe;
    pub use serialport::COMPort as NativeBlockingSerialPort;
    pub use std::ffi::OsStr;
    pub use std::io::{self, Read, Write};
    pub use std::mem;
    pub use std::os::windows::ffi::OsStrExt;
    pub use std::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle};
    pub use std::path::Path;
    pub use std::ptr;
    pub use std::time::Duration;
    pub use winapi::shared::minwindef::TRUE;
    pub use winapi::um::commapi::SetCommTimeouts;
    pub use winapi::um::fileapi::*;
    pub use winapi::um::handleapi::{DuplicateHandle, INVALID_HANDLE_VALUE};
    pub use winapi::um::processthreadsapi::GetCurrentProcess;
    pub use winapi::um::winbase::{COMMTIMEOUTS, FILE_FLAG_OVERLAPPED};
    pub use winapi::um::winnt::{
        DUPLICATE_SAME_ACCESS, FILE_ATTRIBUTE_NORMAL, GENERIC_READ, GENERIC_WRITE, HANDLE,
    };
}
use os_prelude::*;

/// SerialStream
#[derive(Debug)]
pub struct SerialStream {
    #[cfg(unix)]
    inner: serialport::TTYPort,
    #[cfg(windows)]
    inner: mem::ManuallyDrop<serialport::COMPort>,
    #[cfg(windows)]
    pipe: NamedPipe,
}

#[cfg(unix)]
fn map_nix_error(e: nix::Error) -> crate::Error {
    crate::Error {
        kind: crate::ErrorKind::Io(StdIoErrorKind::Other),
        description: e.to_string(),
    }
}

impl SerialStream {
    /// Open a nonblocking serial port from the provided builder
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use mio_serial::{SerialPortBuilder, SerialStream};
    /// use std::path::Path;
    ///
    /// let args = mio_serial::new("/dev/ttyUSB0", 9600);
    /// let serial = SerialStream::open(&args).unwrap();
    /// ```
    pub fn open(builder: &crate::SerialPortBuilder) -> crate::Result<Self> {
        log::debug!("opening serial port in synchronous blocking mode");
        let port = NativeBlockingSerialPort::open(builder)?;
        Self::try_from(port)
    }

    /// Create a pair of pseudo serial terminals
    ///
    /// ## Returns
    /// Two connected `Serial` objects: `(master, slave)`
    ///
    /// ## Errors
    /// Attempting any IO or parameter settings on the slave tty after the master
    /// tty is closed will return errors.
    ///
    /// ## Examples
    ///
    /// ```
    /// use mio_serial::SerialStream;
    ///
    /// let (master, slave) = SerialStream::pair().unwrap();
    /// ```
    #[cfg(unix)]
    pub fn pair() -> crate::Result<(Self, Self)> {
        let (master, slave) = NativeBlockingSerialPort::pair()?;

        let master = Self::try_from(master)?;
        let slave = Self::try_from(slave)?;

        Ok((master, slave))
    }

    /// Sets the exclusivity of the port
    ///
    /// If a port is exclusive, then trying to open the same device path again
    /// will fail.
    ///
    /// See the man pages for the tiocexcl and tiocnxcl ioctl's for more details.
    ///
    /// ## Errors
    ///
    /// * `Io` for any error while setting exclusivity for the port.
    #[cfg(unix)]
    pub fn set_exclusive(&mut self, exclusive: bool) -> crate::Result<()> {
        self.inner.set_exclusive(exclusive)
    }

    /// Returns the exclusivity of the port
    ///
    /// If a port is exclusive, then trying to open the same device path again
    /// will fail.
    #[cfg(unix)]
    pub fn exclusive(&self) -> bool {
        self.inner.exclusive()
    }

    /// Attempts to clone the `SerialPort`. This allow you to write and read simultaneously from the
    /// same serial connection.
    ///
    /// Also, you must be very careful when changing the settings of a cloned `SerialPort` : since
    /// the settings are cached on a per object basis, trying to modify them from two different
    /// objects can cause some nasty behavior.
    ///
    /// This is the same as `SerialPort::try_clone()` but returns the concrete type instead.
    ///
    /// # Errors
    ///
    /// This function returns an error if the serial port couldn't be cloned.
    ///
    /// # DON'T USE THIS AS-IS
    ///
    /// This logic has never really completely worked.  Cloned file descriptors in asynchronous
    /// code is a semantic minefield.  Are you cloning the file descriptor?  Are you cloning the
    /// event flags on the file descriptor?  Both?  It's a bit of a mess even within one OS,
    /// let alone across multiple OS's
    ///
    /// Maybe it can be done with more work, but until a clear use-case is required (or mio/tokio
    /// gets an equivalent of the unix `AsyncFd` for async file handles, see
    /// https://github.com/tokio-rs/tokio/issues/3781 and
    /// https://github.com/tokio-rs/tokio/pull/3760#issuecomment-839854617) I would rather not
    /// have any enabled code over a kind-of-works-maybe impl.  So I'll leave this code here
    /// for now but hard-code it disabled.
    #[cfg(never)]
    pub fn try_clone_native(&self) -> Result<SerialStream> {
        // This works so long as the underlying serialport-rs method doesn't do anything but
        // duplicate the low-level file descriptor.  This is the case as of serialport-rs:4.0.1
        let cloned_native = self.inner.try_clone_native()?;
        #[cfg(unix)]
        {
            Ok(Self {
                inner: cloned_native,
            })
        }
        #[cfg(windows)]
        {
            // Same procedure as used in serialport-rs for duplicating raw handles
            // https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-duplicatehandle
            // states that it can be used as well for pipes created with CreateNamedPipe as well
            let pipe_handle = self.pipe.as_raw_handle();

            let process_handle: HANDLE = unsafe { GetCurrentProcess() };
            let mut cloned_pipe_handle: HANDLE = INVALID_HANDLE_VALUE;
            unsafe {
                DuplicateHandle(
                    process_handle,
                    pipe_handle,
                    process_handle,
                    &mut cloned_pipe_handle,
                    0,
                    TRUE,
                    DUPLICATE_SAME_ACCESS,
                );
                if cloned_pipe_handle != INVALID_HANDLE_VALUE {
                    let cloned_pipe = unsafe { NamedPipe::from_raw_handle(cloned_pipe_handle) };
                    Ok(Self {
                        inner: mem::ManuallyDrop::new(cloned_native),
                        pipe: cloned_pipe,
                    })
                } else {
                    Err(StdIoError::last_os_error().into())
                }
            }
        }
    }
}

impl crate::SerialPort for SerialStream {
    /// Return the name associated with the serial port, if known.
    #[inline(always)]
    fn name(&self) -> Option<String> {
        self.inner.name()
    }

    /// Returns the current baud rate.
    ///
    /// This function returns `None` if the baud rate could not be determined. This may occur if
    /// the hardware is in an uninitialized state. Setting a baud rate with `set_baud_rate()`
    /// should initialize the baud rate to a supported value.
    #[inline(always)]
    fn baud_rate(&self) -> crate::Result<u32> {
        self.inner.baud_rate()
    }

    /// Returns the character size.
    ///
    /// This function returns `None` if the character size could not be determined. This may occur
    /// if the hardware is in an uninitialized state or is using a non-standard character size.
    /// Setting a baud rate with `set_char_size()` should initialize the character size to a
    /// supported value.
    #[inline(always)]
    fn data_bits(&self) -> crate::Result<crate::DataBits> {
        self.inner.data_bits()
    }

    /// Returns the flow control mode.
    ///
    /// This function returns `None` if the flow control mode could not be determined. This may
    /// occur if the hardware is in an uninitialized state or is using an unsupported flow control
    /// mode. Setting a flow control mode with `set_flow_control()` should initialize the flow
    /// control mode to a supported value.
    #[inline(always)]
    fn flow_control(&self) -> crate::Result<crate::FlowControl> {
        self.inner.flow_control()
    }

    /// Returns the parity-checking mode.
    ///
    /// This function returns `None` if the parity mode could not be determined. This may occur if
    /// the hardware is in an uninitialized state or is using a non-standard parity mode. Setting
    /// a parity mode with `set_parity()` should initialize the parity mode to a supported value.
    #[inline(always)]
    fn parity(&self) -> crate::Result<crate::Parity> {
        self.inner.parity()
    }

    /// Returns the number of stop bits.
    ///
    /// This function returns `None` if the number of stop bits could not be determined. This may
    /// occur if the hardware is in an uninitialized state or is using an unsupported stop bit
    /// configuration. Setting the number of stop bits with `set_stop-bits()` should initialize the
    /// stop bits to a supported value.
    #[inline(always)]
    fn stop_bits(&self) -> crate::Result<crate::StopBits> {
        self.inner.stop_bits()
    }

    /// Returns the current timeout. This parameter is const and equal to zero and implemented due
    /// to required for trait completeness.
    #[inline(always)]
    fn timeout(&self) -> Duration {
        Duration::from_secs(0)
    }

    /// Sets the baud rate.
    ///
    /// ## Errors
    ///
    /// If the implementation does not support the requested baud rate, this function may return an
    /// `InvalidInput` error. Even if the baud rate is accepted by `set_baud_rate()`, it may not be
    /// supported by the underlying hardware.
    #[inline(always)]
    fn set_baud_rate(&mut self, baud_rate: u32) -> crate::Result<()> {
        self.inner.set_baud_rate(baud_rate)
    }

    /// Sets the character size.
    #[inline(always)]
    fn set_data_bits(&mut self, data_bits: crate::DataBits) -> crate::Result<()> {
        self.inner.set_data_bits(data_bits)
    }

    // Port settings setters

    /// Sets the flow control mode.
    #[inline(always)]
    fn set_flow_control(&mut self, flow_control: crate::FlowControl) -> crate::Result<()> {
        self.inner.set_flow_control(flow_control)
    }

    /// Sets the parity-checking mode.
    #[inline(always)]
    fn set_parity(&mut self, parity: crate::Parity) -> crate::Result<()> {
        self.inner.set_parity(parity)
    }

    /// Sets the number of stop bits.
    #[inline(always)]
    fn set_stop_bits(&mut self, stop_bits: crate::StopBits) -> crate::Result<()> {
        self.inner.set_stop_bits(stop_bits)
    }

    /// Sets the timeout for future I/O operations. This parameter is ignored but
    /// required for trait completeness.
    #[inline(always)]
    fn set_timeout(&mut self, _: Duration) -> crate::Result<()> {
        Ok(())
    }

    /// Sets the state of the RTS (Request To Send) control signal.
    ///
    /// Setting a value of `true` asserts the RTS control signal. `false` clears the signal.
    ///
    /// ## Errors
    ///
    /// This function returns an error if the RTS control signal could not be set to the desired
    /// state on the underlying hardware:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn write_request_to_send(&mut self, level: bool) -> crate::Result<()> {
        self.inner.write_request_to_send(level)
    }

    /// Writes to the Data Terminal Ready pin
    ///
    /// Setting a value of `true` asserts the DTR control signal. `false` clears the signal.
    ///
    /// ## Errors
    ///
    /// This function returns an error if the DTR control signal could not be set to the desired
    /// state on the underlying hardware:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn write_data_terminal_ready(&mut self, level: bool) -> crate::Result<()> {
        self.inner.write_data_terminal_ready(level)
    }

    // Functions for setting non-data control signal pins

    /// Reads the state of the CTS (Clear To Send) control signal.
    ///
    /// This function returns a boolean that indicates whether the CTS control signal is asserted.
    ///
    /// ## Errors
    ///
    /// This function returns an error if the state of the CTS control signal could not be read
    /// from the underlying hardware:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn read_clear_to_send(&mut self) -> crate::Result<bool> {
        self.inner.read_clear_to_send()
    }

    /// Reads the state of the Data Set Ready control signal.
    ///
    /// This function returns a boolean that indicates whether the DSR control signal is asserted.
    ///
    /// ## Errors
    ///
    /// This function returns an error if the state of the DSR control signal could not be read
    /// from the underlying hardware:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn read_data_set_ready(&mut self) -> crate::Result<bool> {
        self.inner.read_data_set_ready()
    }

    // Functions for reading additional pins

    /// Reads the state of the Ring Indicator control signal.
    ///
    /// This function returns a boolean that indicates whether the RI control signal is asserted.
    ///
    /// ## Errors
    ///
    /// This function returns an error if the state of the RI control signal could not be read from
    /// the underlying hardware:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn read_ring_indicator(&mut self) -> crate::Result<bool> {
        self.inner.read_ring_indicator()
    }

    /// Reads the state of the Carrier Detect control signal.
    ///
    /// This function returns a boolean that indicates whether the CD control signal is asserted.
    ///
    /// ## Errors
    ///
    /// This function returns an error if the state of the CD control signal could not be read from
    /// the underlying hardware:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn read_carrier_detect(&mut self) -> crate::Result<bool> {
        self.inner.read_carrier_detect()
    }

    /// Gets the number of bytes available to be read from the input buffer.
    ///
    /// # Errors
    ///
    /// This function may return the following errors:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn bytes_to_read(&self) -> crate::Result<u32> {
        self.inner.bytes_to_read()
    }

    /// Get the number of bytes written to the output buffer, awaiting transmission.
    ///
    /// # Errors
    ///
    /// This function may return the following errors:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn bytes_to_write(&self) -> crate::Result<u32> {
        self.inner.bytes_to_write()
    }

    /// Discards all bytes from the serial driver's input buffer and/or output buffer.
    ///
    /// # Errors
    ///
    /// This function may return the following errors:
    ///
    /// * `NoDevice` if the device was disconnected.
    /// * `Io` for any other type of I/O error.
    #[inline(always)]
    fn clear(&self, buffer_to_clear: crate::ClearBuffer) -> crate::Result<()> {
        self.inner.clear(buffer_to_clear)
    }

    /// Attempts to clone the `SerialPort`. This allow you to write and read simultaneously from the
    /// same serial connection. Please note that if you want a real asynchronous serial port you
    /// should look at [mio-serial](https://crates.io/crates/mio-serial) or
    /// [tokio-serial](https://crates.io/crates/tokio-serial).
    ///
    /// Also, you must be very carefull when changing the settings of a cloned `SerialPort` : since
    /// the settings are cached on a per object basis, trying to modify them from two different
    /// objects can cause some nasty behavior.
    ///
    /// # Errors
    ///
    /// This function returns an error if the serial port couldn't be cloned.
    #[inline(always)]
    #[cfg(never)]
    fn try_clone(&self) -> crate::Result<Box<dyn crate::SerialPort>> {
        Ok(Box::new(self.try_clone_native()?))
    }

    /// Cloning is not supported for SerialStream objects
    ///
    /// This logic has never really completely worked.  Cloned file descriptors in asynchronous
    /// code is a semantic minefield.  Are you cloning the file descriptor?  Are you cloning the
    /// event flags on the file descriptor?  Both?  It's a bit of a mess even within one OS,
    /// let alone across multiple OS's
    ///
    /// Maybe it can be done with more work, but until a clear use-case is required (or mio/tokio
    /// gets an equivalent of the unix `AsyncFd` for async file handles, see
    /// https://github.com/tokio-rs/tokio/issues/3781 and
    /// https://github.com/tokio-rs/tokio/pull/3760#issuecomment-839854617) I would rather not
    /// have any code available over a kind-of-works-maybe impl.  So I'll leave this code here
    /// for now but hard-code it disabled.
    fn try_clone(&self) -> crate::Result<Box<dyn crate::SerialPort>> {
        Err(crate::Error::new(
            crate::ErrorKind::Io(StdIoErrorKind::Other),
            "cloning SerialStream is not supported",
        ))
    }

    /// Start transmitting a break
    #[inline(always)]
    fn set_break(&self) -> crate::Result<()> {
        self.inner.set_break()
    }

    /// Stop transmitting a break
    #[inline(always)]
    fn clear_break(&self) -> crate::Result<()> {
        self.inner.clear_break()
    }
}

impl TryFrom<NativeBlockingSerialPort> for SerialStream {
    type Error = crate::Error;
    #[cfg(unix)]
    fn try_from(port: NativeBlockingSerialPort) -> std::result::Result<Self, Self::Error> {
        log::debug!(
            "switching {} to asynchronous mode",
            port.name().unwrap_or_else(|| String::from("<UNKNOWN>"))
        );
        log::debug!("setting VMIN = 1");
        use nix::sys::termios::{self, SetArg, SpecialCharacterIndices};
        let mut t = termios::tcgetattr(port.as_raw_fd()).map_err(map_nix_error)?;

        // Set VMIN = 1 to block until at least one character is received.
        t.control_chars[SpecialCharacterIndices::VMIN as usize] = 1;
        termios::tcsetattr(port.as_raw_fd(), SetArg::TCSANOW, &t).map_err(map_nix_error)?;

        // Set the O_NONBLOCK flag.
        log::debug!("setting O_NONBLOCK flag");
        let flags = unsafe { libc::fcntl(port.as_raw_fd(), libc::F_GETFL) };
        if flags < 0 {
            return Err(StdIoError::last_os_error().into());
        }

        match unsafe { libc::fcntl(port.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } {
            0 => Ok(SerialStream { inner: port }),
            _ => Err(StdIoError::last_os_error().into()),
        }
    }
    #[cfg(windows)]
    fn try_from(port: NativeBlockingSerialPort) -> std::result::Result<Self, Self::Error> {
        log::debug!(
            "switching {} to asynchronous mode",
            port.name().unwrap_or_else(|| String::from("<UNKNOWN>"))
        );
        log::debug!("reading serial port settings");
        let name = port
            .name()
            .ok_or_else(|| crate::Error::new(crate::ErrorKind::NoDevice, "Empty device name"))?;
        let baud = port.baud_rate()?;
        let parity = port.parity()?;
        let data_bits = port.data_bits()?;
        let stop_bits = port.stop_bits()?;
        let flow_control = port.flow_control()?;

        let mut path = Vec::<u16>::new();
        path.extend(OsStr::new("\\\\.\\").encode_wide());
        path.extend(Path::new(&name).as_os_str().encode_wide());
        path.push(0);

        // Drop the port object, we'll reopen the file path as a raw handle
        log::debug!("closing synchronous port to re-open in FILE_FLAG_OVERLAPPED mode");
        mem::drop(port);

        let handle = unsafe {
            CreateFileW(
                path.as_ptr(),
                GENERIC_READ | GENERIC_WRITE,
                0,
                ptr::null_mut(),
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                0 as HANDLE,
            )
        };

        if handle == INVALID_HANDLE_VALUE {
            log::error!("unable to open new async file handle");
            return Err(crate::Error::from(StdIoError::last_os_error()));
        }

        // Construct NamedPipe and COMPort from Handle
        //
        // We need both the NamedPipe for Read/Write and COMPort for serialport related
        // actions.  Both are created using FromRawHandle which takes ownership of the
        // handle which may case a double-free as both objects attempt to close the handle.
        //
        // Looking through the source for both NamedPipe and COMPort, NamedPipe does some
        // cleanup in Drop while COMPort just closes the handle.
        //
        // We'll use a ManuallyDrop<T> for COMPort and defer cleanup to the NamedPipe
        let pipe = unsafe { NamedPipe::from_raw_handle(handle) };
        let mut com_port =
            mem::ManuallyDrop::new(unsafe { serialport::COMPort::from_raw_handle(handle) });

        log::debug!("re-setting serial port parameters to original values from synchronous port");
        com_port.set_baud_rate(baud)?;
        com_port.set_parity(parity)?;
        com_port.set_data_bits(data_bits)?;
        com_port.set_stop_bits(stop_bits)?;
        com_port.set_flow_control(flow_control)?;
        sys::override_comm_timeouts(handle)?;

        Ok(Self {
            inner: com_port,
            pipe,
        })
    }
}

#[cfg(unix)]
mod io {
    use super::{SerialStream, StdIoError, StdIoResult};
    use nix::libc;
    use nix::sys::termios;
    use std::io::ErrorKind as StdIoErrorKind;
    use std::io::{Read, Write};
    use std::os::unix::prelude::*;

    macro_rules! uninterruptibly {
        ($e:expr) => {{
            loop {
                match $e {
                    Err(ref error) if error.kind() == StdIoErrorKind::Interrupted => {}
                    res => break res,
                }
            }
        }};
    }

    impl Read for SerialStream {
        fn read(&mut self, bytes: &mut [u8]) -> StdIoResult<usize> {
            uninterruptibly!(match unsafe {
                libc::read(
                    self.as_raw_fd(),
                    bytes.as_ptr() as *mut libc::c_void,
                    bytes.len() as libc::size_t,
                )
            } {
                x if x >= 0 => Ok(x as usize),
                _ => Err(StdIoError::last_os_error()),
            })
        }
    }

    impl Write for SerialStream {
        fn write(&mut self, bytes: &[u8]) -> StdIoResult<usize> {
            uninterruptibly!(match unsafe {
                libc::write(
                    self.as_raw_fd(),
                    bytes.as_ptr() as *const libc::c_void,
                    bytes.len() as libc::size_t,
                )
            } {
                x if x >= 0 => Ok(x as usize),
                _ => Err(StdIoError::last_os_error()),
            })
        }

        fn flush(&mut self) -> StdIoResult<()> {
            uninterruptibly!(termios::tcdrain(self.inner.as_raw_fd()).map_err(StdIoError::from))
        }
    }

    impl<'a> Read for &'a SerialStream {
        fn read(&mut self, bytes: &mut [u8]) -> StdIoResult<usize> {
            uninterruptibly!(match unsafe {
                libc::read(
                    self.as_raw_fd(),
                    bytes.as_ptr() as *mut libc::c_void,
                    bytes.len() as libc::size_t,
                )
            } {
                x if x >= 0 => Ok(x as usize),
                _ => Err(StdIoError::last_os_error()),
            })
        }
    }

    impl<'a> Write for &'a SerialStream {
        fn write(&mut self, bytes: &[u8]) -> StdIoResult<usize> {
            uninterruptibly!(match unsafe {
                libc::write(
                    self.as_raw_fd(),
                    bytes.as_ptr() as *const libc::c_void,
                    bytes.len() as libc::size_t,
                )
            } {
                x if x >= 0 => Ok(x as usize),
                _ => Err(StdIoError::last_os_error()),
            })
        }

        fn flush(&mut self) -> StdIoResult<()> {
            uninterruptibly!(termios::tcdrain(self.inner.as_raw_fd()).map_err(StdIoError::from))
        }
    }
}

#[cfg(windows)]
mod io {
    use super::{NativeBlockingSerialPort, SerialStream, StdIoResult};
    use crate::sys;
    use mio::windows::NamedPipe;
    use std::io::{Read, Write};
    use std::mem;
    use std::os::windows::prelude::*;

    impl Read for SerialStream {
        fn read(&mut self, bytes: &mut [u8]) -> StdIoResult<usize> {
            self.pipe.read(bytes)
        }
    }

    impl Write for SerialStream {
        fn write(&mut self, bytes: &[u8]) -> StdIoResult<usize> {
            self.pipe.write(bytes)
        }

        fn flush(&mut self) -> StdIoResult<()> {
            self.pipe.flush()
        }
    }

    impl AsRawHandle for SerialStream {
        fn as_raw_handle(&self) -> RawHandle {
            self.pipe.as_raw_handle()
        }
    }

    impl IntoRawHandle for SerialStream {
        fn into_raw_handle(self) -> RawHandle {
            // Since NamedPipe doesn't impl IntoRawHandle we'll use AsRawHandle and bypass
            // NamedPipe's destructor to keep the handle in the current state
            let manual = mem::ManuallyDrop::new(self.pipe);
            manual.as_raw_handle()
        }
    }

    impl FromRawHandle for SerialStream {
        /// This method can potentially fail to override the communication timeout
        /// value set in `sys::override_comm_timeouts` without any indication to the user.
        unsafe fn from_raw_handle(handle: RawHandle) -> Self {
            let inner = mem::ManuallyDrop::new(NativeBlockingSerialPort::from_raw_handle(handle));
            let pipe = NamedPipe::from_raw_handle(handle);
            sys::override_comm_timeouts(handle).ok();

            Self { inner, pipe }
        }
    }
}

#[cfg(unix)]
mod sys {
    use super::{NativeBlockingSerialPort, SerialStream};
    use std::os::unix::prelude::*;

    impl AsRawFd for SerialStream {
        fn as_raw_fd(&self) -> RawFd {
            self.inner.as_raw_fd()
        }
    }

    impl IntoRawFd for SerialStream {
        fn into_raw_fd(self) -> RawFd {
            self.inner.into_raw_fd()
        }
    }

    impl FromRawFd for SerialStream {
        unsafe fn from_raw_fd(fd: RawFd) -> Self {
            let port = NativeBlockingSerialPort::from_raw_fd(fd);
            Self { inner: port }
        }
    }
}

#[cfg(windows)]
mod sys {

    use super::os_prelude::*;
    use super::StdIoResult;
    /// Overrides timeout value set by serialport-rs so that the read end will
    /// never wake up with 0-byte payload.
    pub(crate) fn override_comm_timeouts(handle: RawHandle) -> StdIoResult<()> {
        let mut timeouts = COMMTIMEOUTS {
            // wait at most 1ms between two bytes (0 means no timeout)
            ReadIntervalTimeout: 1,
            // disable "total" timeout to wait at least 1 byte forever
            ReadTotalTimeoutMultiplier: 0,
            ReadTotalTimeoutConstant: 0,
            // write timeouts are just copied from serialport-rs
            WriteTotalTimeoutMultiplier: 0,
            WriteTotalTimeoutConstant: 0,
        };

        let r = unsafe { SetCommTimeouts(handle, &mut timeouts) };
        if r == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }
}

#[cfg(unix)]
impl Source for SerialStream {
    #[inline(always)]
    fn register(
        &mut self,
        registry: &Registry,
        token: Token,
        interests: Interest,
    ) -> StdIoResult<()> {
        SourceFd(&self.as_raw_fd()).register(registry, token, interests)
    }

    #[inline(always)]
    fn reregister(
        &mut self,
        registry: &Registry,
        token: Token,
        interests: Interest,
    ) -> StdIoResult<()> {
        SourceFd(&self.as_raw_fd()).reregister(registry, token, interests)
    }

    #[inline(always)]
    fn deregister(&mut self, registry: &Registry) -> StdIoResult<()> {
        SourceFd(&self.as_raw_fd()).deregister(registry)
    }
}

#[cfg(windows)]
impl Source for SerialStream {
    fn register(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> StdIoResult<()> {
        self.pipe.register(registry, token, interest)
    }

    fn reregister(
        &mut self,
        registry: &Registry,
        token: Token,
        interest: Interest,
    ) -> StdIoResult<()> {
        self.pipe.reregister(registry, token, interest)
    }

    fn deregister(&mut self, registry: &Registry) -> StdIoResult<()> {
        self.pipe.deregister(registry)
    }
}

/// An extension trait for SerialPortBuilder
///
/// This trait adds an additional method to SerialPortBuilder:
///
/// - open_native_async
///
/// These methods mirror the `open_native` methods of SerialPortBuilder
pub trait SerialPortBuilderExt {
    /// Open a platform-specific interface to the port with the specified settings
    fn open_native_async(self) -> Result<SerialStream>;
}

impl SerialPortBuilderExt for SerialPortBuilder {
    /// Open a platform-specific interface to the port with the specified settings
    fn open_native_async(self) -> Result<SerialStream> {
        SerialStream::open(&self)
    }
}