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
use crate::{Activity, Bufferable, Status};
use std::convert::TryInto;
use std::io::{self, IoSlice, Write};

/// An extension of [`std::io::Write`], but adds a `close` function to allow
/// the stream to be closed and any outstanding errors to be reported, without
/// requiring a `sync_all`.
pub trait WriteLayered: Write + Bufferable {
    /// Flush any buffers and declare the end of the stream. Subsequent writes
    /// will fail.
    fn close(&mut self) -> io::Result<()>;

    /// Like [`Write::flush`], but has a status parameter describing
    /// the future of the stream:
    ///  - `Status::Ok(Activity::Active)`: do nothing
    ///  - `Status::Ok(Activity::Push)`: flush any buffers and transmit all
    ///    data
    ///  - `Status::End`: flush any buffers and declare the end of the stream
    ///
    /// Passing `Status::Ok(Activity::Push)` makes this behave the same as
    /// `flush()`.
    fn flush_with_status(&mut self, status: Status) -> io::Result<()> {
        match status {
            Status::Open(Activity::Active) => Ok(()),
            Status::Open(Activity::Push) => self.flush(),
            Status::End => self.close(),
        }
    }
}

/// Default implementation of [`Write::write_vectored`], in terms of
/// [`Write::write`].
pub fn default_write_vectored<Inner: Write + ?Sized>(
    inner: &mut Inner,
    bufs: &[IoSlice<'_>],
) -> io::Result<usize> {
    let buf = bufs
        .iter()
        .find(|b| !b.is_empty())
        .map_or(&[][..], |b| &**b);
    inner.write(buf)
}

/// Default implementation of [`Write::is_write_vectored`] accompanying
/// [`default_write_vectored`].
#[cfg(can_vector)]
#[inline]
pub fn default_is_write_vectored<Inner: Write + ?Sized>(_inner: &Inner) -> bool {
    false
}

/// Default implementation of [`Write::write_all`], in terms of
/// [`Write::write`].
#[allow(clippy::indexing_slicing)]
pub fn default_write_all<Inner: Write + ?Sized>(
    inner: &mut Inner,
    mut buf: &[u8],
) -> io::Result<()> {
    while !buf.is_empty() {
        match inner.write(buf) {
            Ok(0) => {
                return Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "failed to write whole buffer",
                ));
            }
            Ok(n) => buf = &buf[n..],
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// Default implementation of [`Write::write_all_vectored`], in terms of
/// [`Write::write_vectored`].
#[cfg(write_all_vectored)]
pub fn default_write_all_vectored<Inner: Write + ?Sized>(
    inner: &mut Inner,
    mut bufs: &mut [IoSlice],
) -> io::Result<()> {
    // TODO: Use [rust-lang/rust#70436]once it stabilizes.
    // [rust-lang/rust#70436]: https://github.com/rust-lang/rust/issues/70436
    while !bufs.is_empty() {
        match inner.write_vectored(bufs) {
            Ok(nwritten) => bufs = advance(bufs, nwritten),
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (),
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// This will be obviated by [rust-lang/rust#62726].
///
/// [rust-lang/rust#62726]: https://github.com/rust-lang/rust/issues/62726.
///
/// Once this is removed, layered-io can become a `#![forbid(unsafe_code)]`
/// crate.
#[cfg(write_all_vectored)]
fn advance<'a, 'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
    use std::slice;

    // Number of buffers to remove.
    let mut remove = 0;
    // Total length of all the to be removed buffers.
    let mut accumulated_len = 0;
    for buf in bufs.iter() {
        if accumulated_len + buf.len() > n {
            break;
        }
        accumulated_len += buf.len();
        remove += 1;
    }

    #[allow(clippy::indexing_slicing)]
    let bufs = &mut bufs[remove..];
    if let Some(first) = bufs.first_mut() {
        let advance_by = n - accumulated_len;
        let mut ptr = first.as_ptr();
        let mut len = first.len();
        unsafe {
            ptr = ptr.add(advance_by);
            len -= advance_by;
            *first = IoSlice::<'a>::new(slice::from_raw_parts::<'a>(ptr, len));
        }
    }
    bufs
}

impl WriteLayered for std::io::Cursor<Vec<u8>> {
    #[inline]
    fn close(&mut self) -> io::Result<()> {
        self.set_position(self.get_ref().len().try_into().unwrap());
        Ok(())
    }
}

impl WriteLayered for std::io::Cursor<Box<[u8]>> {
    #[inline]
    fn close(&mut self) -> io::Result<()> {
        self.set_position(self.get_ref().len().try_into().unwrap());
        Ok(())
    }
}

impl WriteLayered for std::io::Cursor<&mut Vec<u8>> {
    #[inline]
    fn close(&mut self) -> io::Result<()> {
        self.set_position(self.get_ref().len().try_into().unwrap());
        Ok(())
    }
}

impl WriteLayered for std::io::Cursor<&mut [u8]> {
    #[inline]
    fn close(&mut self) -> io::Result<()> {
        self.set_position(self.get_ref().len().try_into().unwrap());
        Ok(())
    }
}

impl<W: WriteLayered> WriteLayered for Box<W> {
    #[inline]
    fn close(&mut self) -> io::Result<()> {
        self.as_mut().close()
    }
}

impl<W: WriteLayered> WriteLayered for &mut W {
    #[inline]
    fn close(&mut self) -> io::Result<()> {
        (**self).close()
    }
}