Skip to content

Commit

Permalink
io: add a into_std method for tokio's TcpStream
Browse files Browse the repository at this point in the history
Fixes: #3031

Signed-off-by: Fuyang Liu <liufuyang@users.noreply.github.com>
  • Loading branch information
liufuyang committed Nov 28, 2020
1 parent 5e406a7 commit cf99d4e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
10 changes: 10 additions & 0 deletions tokio/src/io/poll_evented.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ impl<E: Source> PollEvented<E> {
pub(crate) fn registration(&self) -> &Registration {
&self.registration
}

/// Deregister the inner io from the registration and returns a Result containing the inner io
pub(crate) fn into_inner(mut self) -> io::Result<E> {
let mut inner = self
.io
.take()
.ok_or(io::Error::from(io::ErrorKind::NotFound))?;
self.registration.deregister(&mut inner)?;
Ok(inner)
}
}

feature! {
Expand Down
23 changes: 21 additions & 2 deletions tokio/src/net/tcp/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ use std::fmt;
use std::io;
use std::net::{Shutdown, SocketAddr};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket};
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket};

#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
Expand Down Expand Up @@ -184,6 +184,25 @@ impl TcpStream {
Ok(TcpStream { io })
}

/// Turn a `TcpStream` into a `std::net::TcpStream`.
pub fn into_std(self) -> io::Result<std::net::TcpStream> {
#[cfg(unix)]
{
self.io
.into_inner()
.map(|io| io.into_raw_fd())
.map(|raw_fd| unsafe { std::net::TcpStream::from_raw_fd(raw_fd) })
}

#[cfg(windows)]
{
self.io
.into_inner()
.map(|io| io.into_raw_socket())
.map(|raw_socket| unsafe { std::net::TcpStream::from_raw_socket(raw_socket) })
}
}

/// Returns the local address that this stream is bound to.
///
/// # Examples
Expand Down

0 comments on commit cf99d4e

Please sign in to comment.