a10 0.4.1

This library is meant as a low-level library safely exposing different OS's abilities to perform non-blocking I/O.
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! Type definitions for I/O functionality.
//!
//! # Working with Buffers
//!
//! For working with buffers A10 defines two plus two traits. For "regular",
//! i.e. single buffer I/O, we have the following two traits:
//!  * [`Buf`] is used in writing/sending.
//!  * [`BufMut`] is used in reading/receiving.
//!
//! The basic design of both traits is the same and is fairly simple. Usage
//! starts with a call to [`parts`]/[`parts_mut`], which returns a pointer to
//! the bytes in the bufer to read from or write into. For `BufMut` the caller
//! writes into the buffer and updates the length using [`set_init`], though
//! normally this is done by an I/O operation.
//!
//! For vectored I/O we have the same two traits as above, but suffixed with
//! `Slice`:
//!  * [`BufSlice`] is used in vectored writing/sending.
//!  * [`BufMutSlice`] is used in vectored reading/receiving.
//!
//! Neither of these traits can be implemented outside of the crate, but it's
//! already implemented for tuples and arrays.
//!
//! [`parts`]: Buf::parts
//! [`parts_mut`]: BufMut::parts_mut
//! [`set_init`]: BufMut::set_init
//!
//! ## Specialised Buffer Pool
//!
//! [`ReadBufPool`] is a specialised read buffer pool that can only be used in
//! read operations done by the kernel, i.e. no in-memory operations. In return
//! for this limited functionality we can do things such as [multishot reads],
//! which can greatly improve the performance by batching multiple reads into a
//! single system call.
//!
//! [multishot reads]: crate::fd::AsyncFd::multishot_read
//!
//! # Working with Standard I/O Streams
//!
//! The [`stdin`], [`stdout`] and [`stderr`] functions provide handles to
//! standard I/O streams of all Unix processes. All I/O performed using these
//! handles will non-blocking I/O.
//!
//! Note that these handles are **not** buffered, unlike the ones found in the
//! standard library (e.g. [`std::io::stdout`]). Furthermore these handle do not
//! flush the buffer used by the standard library, so it's not advised to use
//! both the handle from standard library and Heph simultaneously.

use std::mem::ManuallyDrop;
#[cfg(any(target_os = "android", target_os = "linux"))]
use std::os::fd::{AsRawFd, BorrowedFd};
use std::pin::Pin;
use std::task::{self, Poll};
use std::{io, ptr};

use crate::extract::{Extract, Extractor};
#[cfg(any(target_os = "android", target_os = "linux"))]
use crate::new_flag;
use crate::op::{OpState, fd_iter_operation, fd_operation, operation};
use crate::{AsyncFd, man_link, sys};

mod read_buf;
mod traits;

#[cfg(any(target_os = "android", target_os = "linux"))]
pub(crate) use traits::BufId;
pub(crate) use traits::BufMutParts;
// Re-export so we don't have to worry about import `std::io` and `crate::io`.
pub(crate) use std::io::*;

pub use read_buf::{ReadBuf, ReadBufPool};

#[doc(inline)]
pub use traits::{Buf, BufMut, BufMutSlice, BufSlice, IoMutSlice, IoSlice, StaticBuf};

/// Create a function and type to wraps standard {in,out,error}.
macro_rules! stdio {
    (
        $fn: ident () -> $name: ident, $fd: expr
    ) => {
        #[doc = concat!("Create a new [`", stringify!($name), "`].")]
        pub fn $fn(sq: $crate::SubmissionQueue) -> $name {
            unsafe { $name(::std::mem::ManuallyDrop::new($crate::fd::AsyncFd::from_raw($fd, $crate::fd::Kind::File, sq))) }
        }

        #[doc = concat!(
            "An [`AsyncFd`] for ", stringify!($fn), ".\n\n",
            "Created by calling [`", stringify!($fn), "`].\n\n",
            "# Notes\n\n",
            "This directly writes to the raw file descriptor, which means it's not buffered and will not flush anything buffered by the standard library.\n\n",
            "When this type is dropped it will not close ", stringify!($fn), ".",
        )]
        pub struct $name(::std::mem::ManuallyDrop<$crate::fd::AsyncFd>);

        impl ::std::ops::Deref for $name {
            type Target = $crate::fd::AsyncFd;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl ::std::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(::std::stringify!($name))
                    .field("fd", &*self.0)
                    .finish()
            }
        }

        impl ::std::ops::Drop for $name {
            fn drop(&mut self) {
                // We don't want to close the file descriptor, but we do need to
                // drop our reference to the submission queue.
                // SAFETY: with `ManuallyDrop` we don't drop the `AsyncFd` so
                // it's not dropped twice. Otherwise we get access to it using
                // safe methods.
                unsafe { ::std::ptr::drop_in_place(&mut self.0.sq) };
            }
        }
    };
}

stdio!(stdin() -> Stdin, libc::STDIN_FILENO);
stdio!(stdout() -> Stdout, libc::STDOUT_FILENO);
stdio!(stderr() -> Stderr, libc::STDERR_FILENO);

/// The io_uring_enter(2) manual says for IORING_OP_READ and IORING_OP_WRITE:
/// > If offs is set to -1, the offset will use (and advance) the file
/// > position, like the read(2) and write(2) system calls.
///
/// `-1` cast as `unsigned long long` in C is the same as as `u64::MAX`.
pub(crate) const NO_OFFSET: u64 = u64::MAX;

/// I/O system calls.
impl AsyncFd {
    /// Read from this fd into `buf`.
    #[doc = man_link!(read(2))]
    pub fn read<'fd, B: BufMut>(&'fd self, buf: B) -> Read<'fd, B> {
        Read::new(self, buf, NO_OFFSET)
    }

    /// Continuously read data from the fd.
    ///
    /// # Notes
    ///
    /// Is restricted to pollable files and will fall back to single shot if the
    /// file does not support `NOWAIT`.
    ///
    /// This will return `ENOBUFS` if no buffer is available in the `pool` to
    /// read into.
    pub fn multishot_read<'fd>(&'fd self, pool: ReadBufPool) -> MultishotRead<'fd> {
        MultishotRead::new(self, pool, ())
    }

    /// Read at least `n` bytes from this fd into `buf`.
    pub fn read_n<'fd, B: BufMut>(&'fd self, buf: B, n: usize) -> ReadN<'fd, B> {
        let buf = ReadNBuf { buf, last_read: 0 };
        ReadN {
            read: self.read(buf),
            offset: NO_OFFSET,
            left: n,
        }
    }

    /// Read from this fd into `bufs`.
    #[doc = man_link!(readv(2))]
    pub fn read_vectored<'fd, B: BufMutSlice<N>, const N: usize>(
        &'fd self,
        mut bufs: B,
    ) -> ReadVectored<'fd, B, N> {
        let iovecs = unsafe { bufs.as_iovecs_mut() };
        ReadVectored::new(self, (bufs, iovecs), NO_OFFSET)
    }

    /// Read at least `n` bytes from this fd into `bufs`.
    pub fn read_n_vectored<'fd, B: BufMutSlice<N>, const N: usize>(
        &'fd self,
        bufs: B,
        n: usize,
    ) -> ReadNVectored<'fd, B, N> {
        let bufs = ReadNBuf {
            buf: bufs,
            last_read: 0,
        };
        ReadNVectored {
            read: self.read_vectored(bufs),
            offset: NO_OFFSET,
            left: n,
        }
    }

    /// Write `buf` to this fd.
    #[doc = man_link!(write(2))]
    pub fn write<'fd, B: Buf>(&'fd self, buf: B) -> Write<'fd, B> {
        Write::new(self, buf, NO_OFFSET)
    }

    /// Write all of `buf` to this fd.
    pub fn write_all<'fd, B: Buf>(&'fd self, buf: B) -> WriteAll<'fd, B> {
        let buf = SkipBuf { buf, skip: 0 };
        WriteAll {
            write: Extractor {
                fut: self.write(buf),
            },
            offset: NO_OFFSET,
        }
    }

    /// Write `bufs` to this file.
    #[doc = man_link!(writev(2))]
    pub fn write_vectored<'fd, B: BufSlice<N>, const N: usize>(
        &'fd self,
        bufs: B,
    ) -> WriteVectored<'fd, B, N> {
        let iovecs = unsafe { bufs.as_iovecs() };
        WriteVectored::new(self, (bufs, iovecs), NO_OFFSET)
    }

    /// Write all `bufs` to this file.
    pub fn write_all_vectored<'fd, B: BufSlice<N>, const N: usize>(
        &'fd self,
        bufs: B,
    ) -> WriteAllVectored<'fd, B, N> {
        WriteAllVectored {
            write: self.write_vectored(bufs).extract(),
            offset: NO_OFFSET,
            skip: 0,
        }
    }

    /// Splice `length` bytes to `target` fd.
    ///
    /// See the `splice(2)` manual for correct usage.
    #[doc = man_link!(splice(2))]
    #[doc(alias = "splice")]
    #[cfg(any(target_os = "android", target_os = "linux"))]
    pub fn splice_to<'fd>(&'fd self, target: BorrowedFd<'fd>, length: u32) -> Splice<'fd> {
        self.splice(target, SpliceDirection::To, length)
    }

    /// Splice `length` bytes from `target` fd.
    ///
    /// See the `splice(2)` manual for correct usage.
    #[doc = man_link!(splice(2))]
    #[doc(alias = "splice")]
    #[cfg(any(target_os = "android", target_os = "linux"))]
    pub fn splice_from<'fd>(&'fd self, target: BorrowedFd<'fd>, length: u32) -> Splice<'fd> {
        self.splice(target, SpliceDirection::From, length)
    }

    #[cfg(any(target_os = "android", target_os = "linux"))]
    fn splice<'fd>(
        &'fd self,
        target: BorrowedFd<'fd>,
        direction: SpliceDirection,
        length: u32,
    ) -> Splice<'fd> {
        let target_fd = target.as_raw_fd();
        let flags = SpliceFlag(0);
        let args = (target_fd, direction, NO_OFFSET, NO_OFFSET, length, flags);
        Splice::new(self, (), args)
    }

    /// Explicitly close the file descriptor.
    ///
    /// # Notes
    ///
    /// This happens automatically on drop, this can be used to get a possible
    /// error.
    #[doc = man_link!(close(2))]
    pub fn close(self) -> Close {
        // We deconstruct `self` without dropping it to avoid closing the fd
        // twice.
        let this = ManuallyDrop::new(self);
        // SAFETY: this is safe because we're ensure the pointers are valid and
        // not touching `this` after reading the fields.
        let fd = this.fd();
        let kind = this.kind();
        let sq = unsafe { ptr::read(&raw const this.sq) };
        Close::new(sq, (), (fd, kind))
    }
}

#[derive(Copy, Clone, Debug)]
#[cfg(any(target_os = "android", target_os = "linux"))]
pub(crate) enum SpliceDirection {
    To,
    From,
}

#[cfg(any(target_os = "android", target_os = "linux"))]
new_flag!(
    /// Splice flags.
    ///
    /// Set using [`Splice::flags`].
    pub struct SpliceFlag(u32) impl BitOr {
        /// Attempt to move pages instead of copying.
        MOVE = libc::SPLICE_F_MOVE,
        /// More data will be coming in a subsequent splice.
        MORE = libc::SPLICE_F_MORE,
    }
);

fd_operation!(
    /// [`Future`] behind [`AsyncFd::read`].
    pub struct Read<B: BufMut>(sys::io::ReadOp<B>) -> io::Result<B>;

    /// [`Future`] behind [`AsyncFd::read_vectored`].
    pub struct ReadVectored<B: BufMutSlice<N>; const N: usize>(sys::io::ReadVectoredOp<B, N>) -> io::Result<B>;

    /// [`Future`] behind [`AsyncFd::write`].
    pub struct Write<B: Buf>(sys::io::WriteOp<B>) -> io::Result<usize>,
      impl Extract -> io::Result<(B, usize)>;

    /// [`Future`] behind [`AsyncFd::write_vectored`].
    pub struct WriteVectored<B: BufSlice<N>; const N: usize>(sys::io::WriteVectoredOp<B, N>) -> io::Result<usize>,
      impl Extract -> io::Result<(B, usize)>;
);

impl<'fd, B: BufMut> Read<'fd, B> {
    /// Change to a positional read starting at `offset`.
    ///
    /// The current file cursor is not affected by this function. This means
    /// that a call `read(buf).at(1024)` with a buffer of 1kb will **not**
    /// continue reading at 2kb in the next call to `read`.
    #[doc = man_link!(pread(2))]
    pub fn from(mut self, offset: u64) -> Self {
        if let Some(off) = self.state.args_mut() {
            *off = offset;
        }
        self
    }
}

impl<'fd, B: BufMutSlice<N>, const N: usize> ReadVectored<'fd, B, N> {
    /// Change to a positional read starting at `offset`.
    ///
    /// Also see [`Read::from`].
    #[doc = man_link!(preadv(2))]
    pub fn from(mut self, offset: u64) -> Self {
        if let Some(off) = self.state.args_mut() {
            *off = offset;
        }
        self
    }
}

impl<'fd, B: Buf> Write<'fd, B> {
    /// Change to a positional write starting at `offset`.
    ///
    /// The current file cursor is not affected by this function. This means
    /// that two calls to `write(buf).at(1024)` will overwrite each other's
    /// data.
    #[doc = man_link!(pwrite(2))]
    pub fn at(mut self, offset: u64) -> Self {
        if let Some(off) = self.state.args_mut() {
            *off = offset;
        }
        self
    }
}

impl<'fd, B: BufSlice<N>, const N: usize> WriteVectored<'fd, B, N> {
    /// Change to a positional read starting at `offset`.
    ///
    /// Also see [`Write::at`].
    #[doc = man_link!(pwritev(2))]
    pub fn at(mut self, offset: u64) -> Self {
        if let Some(off) = self.state.args_mut() {
            *off = offset;
        }
        self
    }
}

#[cfg(any(target_os = "android", target_os = "linux"))]
fd_operation!(
    /// [`Future`] behind [`AsyncFd::splice_to`] and [`AsyncFd::splice_from`].
    pub struct Splice(sys::io::SpliceOp) -> io::Result<usize>;
);

impl<'fd, B: BufMut> Read<'fd, B> {
    #[cfg(any(target_os = "android", target_os = "linux"))]
    pub(crate) fn fd(&self) -> &'fd AsyncFd {
        self.fd
    }
}

#[cfg(any(target_os = "android", target_os = "linux"))]
impl<'fd> Splice<'fd> {
    /// Start reading from input at `offset`.
    ///
    /// The operation will fail if the input is a pipe.
    pub fn from(mut self, offset: u64) -> Self {
        if let Some((_, _, off_in, _, _, _)) = self.state.args_mut() {
            *off_in = offset;
        }
        self
    }

    /// Start writing to output at `offset`.
    ///
    /// The operation will fail if the output is a pipe.
    pub fn at(mut self, offset: u64) -> Self {
        if let Some((_, _, _, off_out, _, _)) = self.state.args_mut() {
            *off_out = offset;
        }
        self
    }

    /// Set the `flags`.
    pub fn flags(mut self, flags: SpliceFlag) -> Self {
        if let Some((_, _, _, _, _, f)) = self.state.args_mut() {
            *f = flags;
        }
        self
    }
}

fd_iter_operation! {
    /// [`AsyncIterator`] behind [`AsyncFd::multishot_read`].
    pub struct MultishotRead(sys::io::MultishotReadOp) -> io::Result<ReadBuf>;
}

/// [`Future`] behind [`AsyncFd::read_n`].
#[derive(Debug)]
#[must_use = "`Future`s do nothing unless polled"]
pub struct ReadN<'fd, B: BufMut> {
    read: Read<'fd, ReadNBuf<B>>,
    offset: u64,
    /// Number of bytes we still need to read to hit our minimum.
    left: usize,
}

impl<'fd, B: BufMut> ReadN<'fd, B> {
    /// Change to a positional read starting at `offset`.
    ///
    /// Also see [`Read::from`].
    pub fn from(mut self, offset: u64) -> Self {
        if let Some(off) = self.read.state.args_mut() {
            *off = offset;
            self.offset = offset;
        }
        self
    }
}

impl<'fd, B: BufMut> Future for ReadN<'fd, B> {
    type Output = io::Result<B>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<Self::Output> {
        // SAFETY: not moving `self`.
        let this = unsafe { Pin::into_inner_unchecked(self) };
        let mut read = unsafe { Pin::new_unchecked(&mut this.read) };
        match read.as_mut().poll(ctx) {
            Poll::Ready(Ok(buf)) => {
                if buf.last_read == 0 {
                    return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()));
                }

                if buf.last_read >= this.left {
                    // Read the required amount of bytes.
                    return Poll::Ready(Ok(buf.buf));
                }

                this.left -= buf.last_read;
                if this.offset != NO_OFFSET {
                    this.offset += buf.last_read as u64;
                }

                this.read.state.reset(buf, this.offset);
                unsafe { Pin::new_unchecked(this) }.poll(ctx)
            }
            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
            Poll::Pending => Poll::Pending,
        }
    }
}

/// [`Future`] behind [`AsyncFd::read_n_vectored`].
#[derive(Debug)]
#[must_use = "`Future`s do nothing unless polled"]
pub struct ReadNVectored<'fd, B: BufMutSlice<N>, const N: usize> {
    read: ReadVectored<'fd, ReadNBuf<B>, N>,
    offset: u64,
    /// Number of bytes we still need to read to hit our minimum.
    left: usize,
}

impl<'fd, B: BufMutSlice<N>, const N: usize> ReadNVectored<'fd, B, N> {
    /// Change to a positional read starting at `offset`.
    ///
    /// Also see [`Read::from`].
    pub fn from(mut self, offset: u64) -> Self {
        if let Some(off) = self.read.state.args_mut() {
            *off = offset;
            self.offset = offset;
        }
        self
    }
}

impl<'fd, B: BufMutSlice<N>, const N: usize> Future for ReadNVectored<'fd, B, N> {
    type Output = io::Result<B>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<Self::Output> {
        // SAFETY: not moving `Future`.
        let this = unsafe { Pin::into_inner_unchecked(self) };
        let mut read = unsafe { Pin::new_unchecked(&mut this.read) };
        match read.as_mut().poll(ctx) {
            Poll::Ready(Ok(mut bufs)) => {
                if bufs.last_read == 0 {
                    return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()));
                }

                if bufs.last_read >= this.left {
                    // Read the required amount of bytes.
                    return Poll::Ready(Ok(bufs.buf));
                }

                this.left -= bufs.last_read;
                if this.offset != NO_OFFSET {
                    this.offset += bufs.last_read as u64;
                }

                let iovecs = unsafe { bufs.as_iovecs_mut() };
                let resources = (bufs, iovecs);
                this.read.state.reset(resources, this.offset);
                unsafe { Pin::new_unchecked(this) }.poll(ctx)
            }
            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
            Poll::Pending => Poll::Pending,
        }
    }
}

/// [`Future`] behind [`AsyncFd::write_all`].
#[derive(Debug)]
#[must_use = "`Future`s do nothing unless polled"]
pub struct WriteAll<'fd, B: Buf> {
    write: Extractor<Write<'fd, SkipBuf<B>>>,
    offset: u64,
}

impl<'fd, B: Buf> WriteAll<'fd, B> {
    /// Change to a positional write starting at `offset`.
    ///
    /// Also see [`Write::at`].
    pub fn at(mut self, offset: u64) -> Self {
        if let Some(off) = self.write.fut.state.args_mut() {
            *off = offset;
            self.offset = offset;
        }
        self
    }

    fn poll_inner(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<io::Result<B>> {
        // SAFETY: not moving `Future`.
        let this = unsafe { Pin::into_inner_unchecked(self) };
        let mut write = unsafe { Pin::new_unchecked(&mut this.write) };
        match write.as_mut().poll(ctx) {
            Poll::Ready(Ok((_, 0))) => Poll::Ready(Err(io::ErrorKind::WriteZero.into())),
            Poll::Ready(Ok((mut buf, n))) => {
                buf.skip += n as u32;
                if this.offset != NO_OFFSET {
                    this.offset += n as u64;
                }

                if let (_, 0) = unsafe { buf.parts() } {
                    // Written everything.
                    return Poll::Ready(Ok(buf.buf));
                }

                this.write.fut.state.reset(buf, this.offset);
                unsafe { Pin::new_unchecked(this) }.poll_inner(ctx)
            }
            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl<'fd, B: Buf> Future for WriteAll<'fd, B> {
    type Output = io::Result<()>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<Self::Output> {
        self.poll_inner(ctx).map_ok(|_| ())
    }
}

impl<'fd, B: Buf> Extract for WriteAll<'fd, B> {}

impl<'fd, B: Buf> Future for Extractor<WriteAll<'fd, B>> {
    type Output = io::Result<B>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<Self::Output> {
        // SAFETY: not moving `self.fut` (`s.fut`), directly called
        // `Future::poll` on it.
        unsafe { Pin::map_unchecked_mut(self, |s| &mut s.fut) }.poll_inner(ctx)
    }
}

/// [`Future`] behind [`AsyncFd::write_all_vectored`].
#[derive(Debug)]
#[must_use = "`Future`s do nothing unless polled"]
pub struct WriteAllVectored<'fd, B: BufSlice<N>, const N: usize> {
    write: Extractor<WriteVectored<'fd, B, N>>,
    offset: u64,
    skip: u64,
}

impl<'fd, B: BufSlice<N>, const N: usize> WriteAllVectored<'fd, B, N> {
    /// Change to a positional write starting at `offset`.
    ///
    /// Also see [`Write::at`].
    pub fn at(mut self, offset: u64) -> Self {
        if let Some(off) = self.write.fut.state.args_mut() {
            *off = offset;
            self.offset = offset;
        }
        self
    }

    /// Poll implementation used by the [`Future`] implement for the naked type
    /// and the type wrapper in an [`Extractor`].
    fn poll_inner(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<io::Result<B>> {
        // SAFETY: not moving `Future`.
        let this = unsafe { Pin::into_inner_unchecked(self) };
        let mut write = unsafe { Pin::new_unchecked(&mut this.write) };
        match write.as_mut().poll(ctx) {
            Poll::Ready(Ok((_, 0))) => Poll::Ready(Err(io::ErrorKind::WriteZero.into())),
            Poll::Ready(Ok((bufs, n))) => {
                this.skip += n as u64;
                if this.offset != NO_OFFSET {
                    this.offset += n as u64;
                }

                let mut iovecs = unsafe { bufs.as_iovecs() };
                let mut skip = this.skip;
                for iovec in &mut iovecs {
                    if iovec.len() as u64 <= skip {
                        // Skip entire buf.
                        skip -= iovec.len() as u64;
                        // SAFETY: setting it to zero is always valid.
                        unsafe { iovec.set_len(0) };
                    } else {
                        // SAFETY: checked above that the length > skip.
                        unsafe { iovec.skip(skip as usize) };
                        break;
                    }
                }

                if iovecs[N - 1].len() == 0 {
                    // Written everything.
                    return Poll::Ready(Ok(bufs));
                }

                this.write.fut.state.reset((bufs, iovecs), this.offset);
                unsafe { Pin::new_unchecked(this) }.poll_inner(ctx)
            }
            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl<'fd, B: BufSlice<N>, const N: usize> Future for WriteAllVectored<'fd, B, N> {
    type Output = io::Result<()>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<Self::Output> {
        self.poll_inner(ctx).map_ok(|_| ())
    }
}

impl<'fd, B: BufSlice<N>, const N: usize> Extract for WriteAllVectored<'fd, B, N> {}

impl<'fd, B: BufSlice<N>, const N: usize> Future for Extractor<WriteAllVectored<'fd, B, N>> {
    type Output = io::Result<B>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> Poll<Self::Output> {
        unsafe { Pin::map_unchecked_mut(self, |s| &mut s.fut) }.poll_inner(ctx)
    }
}

operation!(
    /// [`Future`] behind [`AsyncFd::close`].
    pub struct Close(sys::io::CloseOp) -> io::Result<()>;
);

/// Wrapper around a buffer `B` to keep track of the number of bytes written.
// Also used in the `net` module.
#[derive(Debug)]
pub(crate) struct ReadNBuf<B> {
    pub(crate) buf: B,
    pub(crate) last_read: usize,
}

unsafe impl<B: BufMut> BufMut for ReadNBuf<B> {
    unsafe fn parts_mut(&mut self) -> (*mut u8, u32) {
        unsafe { self.buf.parts_mut() }
    }

    unsafe fn set_init(&mut self, n: usize) {
        self.last_read = n;
        unsafe { self.buf.set_init(n) };
    }

    fn spare_capacity(&self) -> u32 {
        self.buf.spare_capacity()
    }

    fn has_spare_capacity(&self) -> bool {
        self.buf.has_spare_capacity()
    }

    #[cfg(any(target_os = "android", target_os = "linux"))]
    unsafe fn buffer_init(&mut self, id: BufId, n: u32) {
        self.last_read = n as usize;
        unsafe { self.buf.buffer_init(id, n) };
    }
}

unsafe impl<B: BufMutSlice<N>, const N: usize> BufMutSlice<N> for ReadNBuf<B> {
    unsafe fn as_iovecs_mut(&mut self) -> [IoMutSlice; N] {
        unsafe { self.buf.as_iovecs_mut() }
    }

    unsafe fn set_init(&mut self, n: usize) {
        self.last_read = n;
        unsafe { self.buf.set_init(n) };
    }
}

/// Wrapper around a buffer `B` to skip a number of bytes.
// Also used in the `net` module.
#[derive(Debug)]
pub(crate) struct SkipBuf<B> {
    pub(crate) buf: B,
    pub(crate) skip: u32,
}

unsafe impl<B: Buf> Buf for SkipBuf<B> {
    unsafe fn parts(&self) -> (*const u8, u32) {
        let (ptr, size) = unsafe { self.buf.parts() };
        if self.skip >= size {
            (ptr, 0)
        } else {
            (unsafe { ptr.add(self.skip as usize) }, size - self.skip)
        }
    }
}