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
//! Utility functions for the [`AsyncSkip`] trait.

use std::future::Future;
use std::io;
use std::ops::DerefMut;
use std::pin::Pin;
use std::task::{ready, Context, Poll};

use futures_util::io::{BufReader, Cursor};
use futures_util::{AsyncBufRead, AsyncRead, AsyncSeek};

use crate::{AsyncSkip, SeekSkipAdapter};

//
// public types
//

/// An extension trait which adds utility methods to [`AsyncSkip`] types.
pub trait AsyncSkipExt: AsyncSkip {
    /// Skip an amount of bytes in a stream.
    ///
    /// A skip beyond the end of a stream is allowed, but behavior is defined by the implementation.
    fn skip(&mut self, amount: u64) -> Skip<'_, Self> {
        Skip { amount, inner: self }
    }

    /// Returns the current position of the cursor from the start of the stream.
    fn stream_position(&mut self) -> StreamPosition<'_, Self> {
        StreamPosition { inner: self }
    }

    /// Returns the length of this stream, in bytes.
    fn stream_len(&mut self) -> StreamLen<'_, Self> {
        StreamLen { inner: self }
    }
}

/// Future for the [`skip`](AsyncSkipExt::skip) method.
pub struct Skip<'a, T: ?Sized> {
    amount: u64,
    inner: &'a mut T,
}

/// Future for the [`stream_position`](AsyncSkipExt::stream_position) method.
pub struct StreamPosition<'a, T: ?Sized> {
    inner: &'a mut T,
}

/// Future for the [`stream_len`](AsyncSkipExt::stream_len) method.
pub struct StreamLen<'a, T: ?Sized> {
    inner: &'a mut T,
}

//
// AsyncSkipExt impls
//

impl<T: AsyncSkip + ?Sized> AsyncSkipExt for T {}

//
// Skip impls
//

impl<T: AsyncSkip + Unpin + ?Sized> Future for Skip<'_, T> {
    type Output = io::Result<()>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let amount = self.amount;
        Pin::new(&mut *self.inner).poll_skip(cx, amount)
    }
}

//
// StreamPosition impls
//

impl<T: AsyncSkip + Unpin + ?Sized> Future for StreamPosition<'_, T> {
    type Output = io::Result<u64>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut *self.inner).poll_stream_position(cx)
    }
}

//
// StreamLen impls
//

impl<T: AsyncSkip + Unpin + ?Sized> Future for StreamLen<'_, T> {
    type Output = io::Result<u64>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut *self.inner).poll_stream_len(cx)
    }
}

//
// SeekSkipAdapter impls
//

impl<T: AsyncRead + Unpin + ?Sized> AsyncRead for SeekSkipAdapter<T> {
    fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.0).poll_read(cx, buf)
    }
}

impl<R: AsyncSeek + Unpin + ?Sized> AsyncSkip for SeekSkipAdapter<R> {
    fn poll_skip(mut self: Pin<&mut Self>, cx: &mut Context<'_>, amount: u64) -> Poll<io::Result<()>> {
        match amount.try_into() {
            Ok(0) => (),
            Ok(amount) => {
                let reader = Pin::new(&mut self.get_mut().0);
                ready!(reader.poll_seek(cx, io::SeekFrom::Current(amount)))?;
            }
            Err(_) => {
                let stream_pos = ready!(self.as_mut().poll_stream_position(cx))?;
                let seek_pos = stream_pos
                    .checked_add(amount)
                    .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "seek past u64::MAX"))?;
                let reader = Pin::new(&mut self.get_mut().0);
                ready!(reader.poll_seek(cx, io::SeekFrom::Start(seek_pos)))?;
            }
        }
        Ok(()).into()
    }

    fn poll_stream_position(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
        let reader = Pin::new(&mut self.get_mut().0);
        reader.poll_seek(cx, io::SeekFrom::Current(0))
    }

    fn poll_stream_len(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
        // This is the unstable Seek::stream_len
        let stream_pos = ready!(self.as_mut().poll_stream_position(cx))?;
        let mut reader = Pin::new(&mut self.get_mut().0);
        let len = ready!(reader.as_mut().poll_seek(cx, io::SeekFrom::End(0)))?;

        if stream_pos != len {
            ready!(reader.poll_seek(cx, io::SeekFrom::Start(stream_pos)))?;
        }

        Ok(len).into()
    }
}

//
// AsyncSkip impls
//

macro_rules! deref_async_skip {
    () => {
        fn poll_skip(mut self: Pin<&mut Self>, cx: &mut Context<'_>, amount: u64) -> Poll<io::Result<()>> {
            Pin::new(&mut **self).poll_skip(cx, amount)
        }

        fn poll_stream_position(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
            Pin::new(&mut **self).poll_stream_position(cx)
        }

        fn poll_stream_len(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
            Pin::new(&mut **self).poll_stream_len(cx)
        }
    };
}

impl<R: AsyncSkip + Unpin + ?Sized> AsyncSkip for &mut R {
    deref_async_skip!();
}

impl<R: AsyncSkip + Unpin + ?Sized> AsyncSkip for Box<R> {
    deref_async_skip!();
}

impl<P: DerefMut + Unpin> AsyncSkip for Pin<P>
where
    P::Target: AsyncSkip,
{
    fn poll_skip(self: Pin<&mut Self>, cx: &mut Context<'_>, amount: u64) -> Poll<io::Result<()>> {
        self.get_mut().as_mut().poll_skip(cx, amount)
    }

    fn poll_stream_position(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
        self.get_mut().as_mut().poll_stream_position(cx)
    }

    fn poll_stream_len(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
        self.get_mut().as_mut().poll_stream_len(cx)
    }
}

macro_rules! async_skip_via_adapter {
    () => {
        fn poll_skip(self: Pin<&mut Self>, cx: &mut Context<'_>, amount: u64) -> Poll<io::Result<()>> {
            Pin::new(&mut SeekSkipAdapter(self.get_mut())).poll_skip(cx, amount)
        }

        fn poll_stream_position(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
            Pin::new(&mut SeekSkipAdapter(self.get_mut())).poll_stream_position(cx)
        }

        fn poll_stream_len(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
            Pin::new(&mut SeekSkipAdapter(self.get_mut())).poll_stream_len(cx)
        }
    };
}

impl<T: AsRef<[u8]> + Unpin> AsyncSkip for Cursor<T> {
    async_skip_via_adapter!();
}

impl<R: AsyncRead + AsyncSkip> AsyncSkip for BufReader<R> {
    /// Poll skipping `amount` bytes in a [`BufReader`] implementing [`AsyncRead`] + [`AsyncSkip`].
    fn poll_skip(mut self: Pin<&mut Self>, cx: &mut Context<'_>, amount: u64) -> Poll<io::Result<()>> {
        let buf_len = self.buffer().len();
        if let Some(skip_amount) = amount.checked_sub(buf_len as u64) {
            if skip_amount != 0 {
                ready!(self.as_mut().get_pin_mut().poll_skip(cx, skip_amount))?
            }
        }
        self.consume(buf_len.min(amount as usize));
        Poll::Ready(Ok(()))
    }

    /// Poll the stream position for a [`BufReader`] implementing [`AsyncRead`] + [`AsyncSkip`].
    fn poll_stream_position(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
        let stream_pos = ready!(self.as_mut().get_pin_mut().poll_stream_position(cx))?;
        Poll::Ready(Ok(stream_pos.saturating_sub(self.buffer().len() as u64)))
    }

    /// Poll the stream length for a [`BufReader`] implementing [`AsyncRead`] + [`AsyncSkip`].
    fn poll_stream_len(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
        self.as_mut().get_pin_mut().poll_stream_len(cx)
    }
}