nuclei 0.5.2

Proactive IO & runtime system
Documentation
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
//! Buffering around a reader or a writer: [`BufReader`], [`BufWriter`], and
//! both at once, [`BufStream`].

use core::pin::Pin;
use core::task::{Context, Poll, ready};
use std::io::{self, IoSlice, SeekFrom};

use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite};

/// The buffer the wrappers make when no capacity is given.
const DEFAULT_CAPACITY: usize = 8 * 1024;

/// A reader with a buffer in front: small reads take from the buffer, which
/// is filled by large reads of the reader. Writes, if the reader is also a
/// writer, go straight through.
#[derive(Debug)]
pub struct BufReader<R> {
    inner: R,
    buf: Box<[u8]>,
    pos: usize,
    cap: usize,
}

impl<R> BufReader<R> {
    /// A reader with a buffer of 8 KiB in front of `inner`.
    pub fn new(inner: R) -> Self {
        Self::with_capacity(DEFAULT_CAPACITY, inner)
    }

    /// A reader with a buffer of `capacity` bytes in front of `inner`.
    pub fn with_capacity(capacity: usize, inner: R) -> Self {
        Self {
            inner,
            buf: vec![0; capacity].into_boxed_slice(),
            pos: 0,
            cap: 0,
        }
    }

    /// The reader inside.
    pub fn get_ref(&self) -> &R {
        &self.inner
    }

    /// The reader inside, to change (reading it directly skips the bytes
    /// buffered).
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.inner
    }

    /// The reader inside, pinned.
    pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R>
    where
        R: Unpin,
    {
        Pin::new(&mut self.get_mut().inner)
    }

    /// The reader inside, taken back; the bytes buffered are lost.
    pub fn into_inner(self) -> R {
        self.inner
    }

    /// The bytes buffered and not read yet.
    pub fn buffer(&self) -> &[u8] {
        &self.buf[self.pos..self.cap]
    }

    fn discard_buffer(&mut self) {
        self.pos = 0;
        self.cap = 0;
    }
}

impl<R: AsyncRead + Unpin> AsyncRead for BufReader<R> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        out: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();
        // An empty buffer and a read at least its size: the buffer would only
        // add a copy.
        if this.pos == this.cap && out.len() >= this.buf.len() {
            let n = ready!(Pin::new(&mut this.inner).poll_read(cx, out))?;
            this.discard_buffer();
            return Poll::Ready(Ok(n));
        }
        let available = ready!(Pin::new(&mut *this).poll_fill_buf(cx))?;
        let n = available.len().min(out.len());
        out[..n].copy_from_slice(&available[..n]);
        Pin::new(this).consume(n);
        Poll::Ready(Ok(n))
    }
}

impl<R: AsyncRead + Unpin> AsyncBufRead for BufReader<R> {
    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
        let this = self.get_mut();
        if this.pos >= this.cap {
            let n = ready!(Pin::new(&mut this.inner).poll_read(cx, &mut this.buf))?;
            this.cap = n;
            this.pos = 0;
        }
        Poll::Ready(Ok(&this.buf[this.pos..this.cap]))
    }

    fn consume(self: Pin<&mut Self>, amount: usize) {
        let this = self.get_mut();
        this.pos = (this.pos + amount).min(this.cap);
    }
}

impl<R: AsyncRead + AsyncSeek + Unpin> AsyncSeek for BufReader<R> {
    /// Seeks the reader; a seek relative to the current position counts
    /// from the position of the next byte read through the buffer. The
    /// buffer is emptied.
    fn poll_seek(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        pos: SeekFrom,
    ) -> Poll<io::Result<u64>> {
        let this = self.get_mut();
        let pos = match pos {
            SeekFrom::Current(n) => {
                let buffered = (this.cap - this.pos) as i64;
                match n.checked_sub(buffered) {
                    Some(n) => SeekFrom::Current(n),
                    None => {
                        // Past `i64`'s range: two seeks, the buffered part first.
                        ready!(
                            Pin::new(&mut this.inner).poll_seek(cx, SeekFrom::Current(-buffered))
                        )?;
                        this.discard_buffer();
                        SeekFrom::Current(n)
                    }
                }
            }
            other => other,
        };
        let at = ready!(Pin::new(&mut this.inner).poll_seek(cx, pos))?;
        this.discard_buffer();
        Poll::Ready(Ok(at))
    }
}

impl<R: AsyncWrite + Unpin> AsyncWrite for BufReader<R> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
    }

    fn poll_write_vectored(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write_vectored(cx, bufs)
    }

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

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

/// A writer with a buffer in front: small writes gather in the buffer, which
/// goes to the writer when full, on a flush, or on a close. Reads, if the
/// writer is also a reader, go straight through. Dropping it loses what is
/// still buffered: flush or close it first.
#[derive(Debug)]
pub struct BufWriter<W> {
    inner: W,
    buf: Vec<u8>,
    written: usize,
}

impl<W> BufWriter<W> {
    /// A writer with a buffer of 8 KiB in front of `inner`.
    pub fn new(inner: W) -> Self {
        Self::with_capacity(DEFAULT_CAPACITY, inner)
    }

    /// A writer with a buffer of `capacity` bytes in front of `inner`.
    pub fn with_capacity(capacity: usize, inner: W) -> Self {
        Self {
            inner,
            buf: Vec::with_capacity(capacity),
            written: 0,
        }
    }

    /// The writer inside.
    pub fn get_ref(&self) -> &W {
        &self.inner
    }

    /// The writer inside, to change (writing it directly puts the bytes
    /// ahead of what is buffered).
    pub fn get_mut(&mut self) -> &mut W {
        &mut self.inner
    }

    /// The writer inside, pinned.
    pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W>
    where
        W: Unpin,
    {
        Pin::new(&mut self.get_mut().inner)
    }

    /// The writer inside, taken back; the bytes buffered are lost.
    pub fn into_inner(self) -> W {
        self.inner
    }

    /// The bytes buffered and not written to the writer yet.
    pub fn buffer(&self) -> &[u8] {
        &self.buf[self.written..]
    }
}

impl<W: AsyncWrite + Unpin> BufWriter<W> {
    /// Writes the buffer out to the writer, all of it.
    fn flush_buf(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        while self.written < self.buf.len() {
            let n = ready!(Pin::new(&mut self.inner).poll_write(cx, &self.buf[self.written..]))?;
            if n == 0 {
                return Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "the writer took no more of the buffered bytes",
                )));
            }
            self.written += n;
        }
        self.buf.clear();
        self.written = 0;
        Poll::Ready(Ok(()))
    }
}

impl<W: AsyncWrite + Unpin> AsyncWrite for BufWriter<W> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();
        if this.buf.len() + buf.len() > this.buf.capacity() {
            ready!(this.flush_buf(cx))?;
        }
        if buf.len() >= this.buf.capacity() {
            // As large as the buffer: straight to the writer.
            return Pin::new(&mut this.inner).poll_write(cx, buf);
        }
        this.buf.extend_from_slice(buf);
        Poll::Ready(Ok(buf.len()))
    }

    fn poll_write_vectored(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();
        let total: usize = bufs.iter().map(|b| b.len()).sum();
        if this.buf.len() + total > this.buf.capacity() {
            ready!(this.flush_buf(cx))?;
        }
        if total >= this.buf.capacity() {
            return Pin::new(&mut this.inner).poll_write_vectored(cx, bufs);
        }
        for b in bufs {
            this.buf.extend_from_slice(b);
        }
        Poll::Ready(Ok(total))
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = self.get_mut();
        ready!(this.flush_buf(cx))?;
        Pin::new(&mut this.inner).poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let this = self.get_mut();
        ready!(this.flush_buf(cx))?;
        Pin::new(&mut this.inner).poll_close(cx)
    }
}

impl<W: AsyncRead + Unpin> AsyncRead for BufWriter<W> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_read(cx, buf)
    }
}

impl<W: AsyncBufRead + Unpin> AsyncBufRead for BufWriter<W> {
    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
        Pin::new(&mut self.get_mut().inner).poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amount: usize) {
        Pin::new(&mut self.get_mut().inner).consume(amount);
    }
}

impl<W: AsyncWrite + AsyncSeek + Unpin> AsyncSeek for BufWriter<W> {
    /// Writes the buffer out, then seeks the writer.
    fn poll_seek(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        pos: SeekFrom,
    ) -> Poll<io::Result<u64>> {
        let this = self.get_mut();
        ready!(this.flush_buf(cx))?;
        Pin::new(&mut this.inner).poll_seek(cx, pos)
    }
}

/// A stream with a read buffer and a write buffer in front: a
/// [`BufReader`] around a [`BufWriter`].
#[derive(Debug)]
pub struct BufStream<S> {
    inner: BufReader<BufWriter<S>>,
}

impl<S> BufStream<S> {
    /// Buffers of 8 KiB each way in front of `stream`.
    pub fn new(stream: S) -> Self {
        Self {
            inner: BufReader::new(BufWriter::new(stream)),
        }
    }

    /// A read buffer of `read` bytes and a write buffer of `write` bytes in
    /// front of `stream`.
    pub fn with_capacity(read: usize, write: usize, stream: S) -> Self {
        Self {
            inner: BufReader::with_capacity(read, BufWriter::with_capacity(write, stream)),
        }
    }

    /// The stream inside.
    pub fn get_ref(&self) -> &S {
        self.inner.get_ref().get_ref()
    }

    /// The stream inside, to change.
    pub fn get_mut(&mut self) -> &mut S {
        self.inner.get_mut().get_mut()
    }

    /// The stream inside, taken back; the bytes buffered either way are lost.
    pub fn into_inner(self) -> S {
        self.inner.into_inner().into_inner()
    }
}

impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for BufStream<S> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_read(cx, buf)
    }
}

impl<S: AsyncRead + AsyncWrite + Unpin> AsyncBufRead for BufStream<S> {
    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
        Pin::new(&mut self.get_mut().inner).poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amount: usize) {
        Pin::new(&mut self.get_mut().inner).consume(amount);
    }
}

impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for BufStream<S> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
    }

    fn poll_write_vectored(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write_vectored(cx, bufs)
    }

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

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