Skip to content

Commit

Permalink
Don't project if you require Unpin.
Browse files Browse the repository at this point in the history
This doesn't make sense. For Unpin types, Pin does nothing, so Pin::new() is sufficient.

However Pin::new is only implemented for `Pin<P> where <P as Deref>::Target: Unpin`, so if it weren't Unpin,
you would have to use unsafe { Pin::new_unchecked(s) }, as `Pin::new()` wouldn't compile.

Thus project and Pin::new together is always a code smell.
  • Loading branch information
najamelan committed Mar 4, 2020
1 parent 1a2a99a commit 18cc347
Showing 1 changed file with 6 additions and 16 deletions.
22 changes: 6 additions & 16 deletions src/stream.rs
Expand Up @@ -3,66 +3,56 @@
//! There is no dependency on actual TLS implementations. Everything like
//! `native_tls` or `openssl` will work as long as there is a TLS stream supporting standard
//! `Read + Write` traits.
use pin_project::{pin_project, project};
use std::pin::Pin;
use std::task::{Context, Poll};

use tokio::io::{AsyncRead, AsyncWrite};

/// Stream, either plain TCP or TLS.
#[pin_project]
pub enum Stream<S, T> {
/// Unencrypted socket stream.
Plain(#[pin] S),
Plain(S),
/// Encrypted socket stream.
Tls(#[pin] T),
Tls(T),
}

impl<S: AsyncRead + Unpin, T: AsyncRead + Unpin> AsyncRead for Stream<S, T> {
#[project]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
#[project]
match self.project() {
match self.get_mut() {
Stream::Plain(ref mut s) => Pin::new(s).poll_read(cx, buf),
Stream::Tls(ref mut s) => Pin::new(s).poll_read(cx, buf),
}
}
}

impl<S: AsyncWrite + Unpin, T: AsyncWrite + Unpin> AsyncWrite for Stream<S, T> {
#[project]
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, std::io::Error>> {
#[project]
match self.project() {
match self.get_mut() {
Stream::Plain(ref mut s) => Pin::new(s).poll_write(cx, buf),
Stream::Tls(ref mut s) => Pin::new(s).poll_write(cx, buf),
}
}

#[project]
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
#[project]
match self.project() {
match self.get_mut() {
Stream::Plain(ref mut s) => Pin::new(s).poll_flush(cx),
Stream::Tls(ref mut s) => Pin::new(s).poll_flush(cx),
}
}

#[project]
fn poll_shutdown(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), std::io::Error>> {
#[project]
match self.project() {
match self.get_mut() {
Stream::Plain(ref mut s) => Pin::new(s).poll_shutdown(cx),
Stream::Tls(ref mut s) => Pin::new(s).poll_shutdown(cx),
}
Expand Down

0 comments on commit 18cc347

Please sign in to comment.