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
/**************************************************************************************************
 *                                                                                                *
 * This Source Code Form is subject to the terms of the Mozilla Public                            *
 * License, v. 2.0. If a copy of the MPL was not distributed with this                            *
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.                                       *
 *                                                                                                *
 **************************************************************************************************/

// ======================================== Documentation ======================================= \\

//! This crate provides [`AsyncPeek`], a trait to read data asynchronously without removing it
//! from the queue (like when using the blocking methods [`std::net::TcpStream::peek()`] and
//! [`std::net::UdpSocket::peek()`]).

// =========================================== Imports ========================================== \\

use cfg_if::cfg_if;
use core::cmp;
use core::future::Future;
use core::ops::{Deref, DerefMut};
use core::pin::Pin;
use core::task::{Context, Poll};
use std::io::Error;

#[cfg(feature = "async-io")]
use std::net::{TcpStream, UdpSocket};

// ========================================= Interfaces ========================================= \\

/// Read data asynchronously without removing it from the queue.
pub trait AsyncPeek {
    /// Attempts to read data into `buf` without removing it from the queue.
    ///
    /// Returns the number of bytes read on success, or [`io::Error`] if an error is encountered.
    ///
    /// If no data is available, the current task is registered to be notified when data becomes
    /// available or the stream is closed, and `Poll::Pending` is returned.
    ///
    /// [`io::Error`]: std::io::Error
    fn poll_peek(
        self: Pin<&mut Self>,
        ctx: &mut Context,
        buf: &mut [u8],
    ) -> Poll<Result<usize, Error>>;
}

/// An extension trait which adds utility methods to [`AsyncPeek`] types.
pub trait AsyncPeekExt: AsyncPeek {
    /// Tries to read data into `buf` without removing it from the queue.
    ///
    /// Returns the number of bytes read, or [`io::Error`] if an error is encountered.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// # smol::block_on(async {
    /// #
    /// use async_peek::{AsyncPeek, AsyncPeekExt};
    /// use smol::Async;
    /// use std::net::{TcpStream, ToSocketAddrs};
    ///
    /// let addr = "127.0.0.1:0".to_socket_addrs()?.next().unwrap();
    /// let mut stream = Async::<TcpStream>::connect(addr).await?;
    /// let mut buf = [0; 64];
    ///
    /// let n = stream.peek(&mut buf).await?;
    /// println!("Peeked {} bytes", n);
    /// #
    /// # std::io::Result::Ok(()) });
    /// ```
    ///
    /// [`io::Error`]: std::io::Error
    fn peek<'peek>(&'peek mut self, buf: &'peek mut [u8]) -> Peek<'peek, Self>
    where
        Self: Unpin,
    {
        Peek { peek: self, buf }
    }
}

// ============================================ Types =========================================== \\

/// Future for the [`peek()`] function.
///
/// [`peek()`]: AsyncPeekExt::peek()
pub struct Peek<'peek, P: ?Sized> {
    peek: &'peek mut P,
    buf: &'peek mut [u8],
}

// ======================================== macro_rules! ======================================== \\

#[allow(unused)]
macro_rules! impl_for_net {
    ($net:ty) => {
        impl AsyncPeek for $net {
            fn poll_peek(
                self: Pin<&mut Self>,
                ctx: &mut Context,
                buf: &mut [u8],
            ) -> Poll<Result<usize, Error>> {
                let fut = (&*self).peek(buf);
                ufut::pin!(fut);

                fut.poll(ctx)
            }
        }
    };
}

// ======================================= impl AsyncPeek ======================================= \\

impl AsyncPeek for &[u8] {
    fn poll_peek(
        self: Pin<&mut Self>,
        _: &mut Context,
        buf: &mut [u8],
    ) -> Poll<Result<usize, Error>> {
        let len = cmp::min(buf.len(), self.len());
        buf[0..len].copy_from_slice(&self[0..len]);

        Poll::Ready(Ok(len))
    }
}

impl<T> AsyncPeek for &mut T
where
    T: AsyncPeek + Unpin + ?Sized,
{
    fn poll_peek(
        mut self: Pin<&mut Self>,
        ctx: &mut Context,
        buf: &mut [u8],
    ) -> Poll<Result<usize, Error>> {
        Pin::new(&mut **self).poll_peek(ctx, buf)
    }
}

impl<T> AsyncPeek for Box<T>
where
    T: AsyncPeek + Unpin + ?Sized,
{
    fn poll_peek(
        mut self: Pin<&mut Self>,
        ctx: &mut Context,
        buf: &mut [u8],
    ) -> Poll<Result<usize, Error>> {
        Pin::new(&mut **self).poll_peek(ctx, buf)
    }
}

impl<T> AsyncPeek for Pin<T>
where
    T: DerefMut + Unpin,
    <T as Deref>::Target: AsyncPeek,
{
    fn poll_peek(
        self: Pin<&mut Self>,
        ctx: &mut Context,
        buf: &mut [u8],
    ) -> Poll<Result<usize, Error>> {
        self.get_mut().as_mut().poll_peek(ctx, buf)
    }
}



cfg_if! {
    if #[cfg(feature = "async-io")] {
        impl_for_net!(async_io::Async<TcpStream>);
        impl_for_net!(async_io::Async<UdpSocket>);
        impl_for_net!(&async_io::Async<TcpStream>);
        impl_for_net!(&async_io::Async<UdpSocket>);
    }
}

cfg_if! {
    if #[cfg(feature = "async-net")] {
        impl_for_net!(async_net::TcpStream);
        impl_for_net!(async_net::UdpSocket);
        impl_for_net!(&async_net::TcpStream);
        impl_for_net!(&async_net::UdpSocket);
    }
}

// ====================================== impl AsyncPeekExt ===================================== \\

impl<P: AsyncPeek + ?Sized> AsyncPeekExt for P {}

// ========================================= impl Future ======================================== \\

impl<P: AsyncPeek + Unpin> Future for Peek<'_, P> {
    type Output = Result<usize, Error>;

    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
        let this = &mut *self;
        Pin::new(&mut this.peek).poll_peek(ctx, this.buf)
    }
}