compio-io 0.10.0-rc.2

IO traits for completion based async IO
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
#[cfg(feature = "allocator_api")]
use std::alloc::Allocator;
use std::{future, io::Cursor};

use compio_buf::{BufResult, IntoInner, IoBuf, IoVectoredBuf, buf_try, t_alloc};

use crate::IoResult;

mod buf;
#[macro_use]
mod ext;

pub use buf::*;
pub use ext::*;

/// # AsyncWrite
///
/// Async write with a ownership of a buffer
pub trait AsyncWrite {
    /// Write some bytes from the buffer into this source and return a
    /// [`BufResult`], consisting of the buffer and a [`usize`] indicating how
    /// many bytes were written.
    async fn write<T: IoBuf>(&mut self, buf: T) -> BufResult<usize, T>;

    /// Like `write`, except that it write bytes from a buffer implements
    /// [`IoVectoredBuf`] into the source.
    ///
    /// The default implementation will write from the first buffers with
    /// non-zero [`buf_len`], meaning it's possible and likely that not all
    /// contents are written. If guaranteed full write is desired, it is
    /// recommended to use [`AsyncWriteExt::write_vectored_all`] instead.
    ///
    /// [`buf_len`]: IoBuf::buf_len
    async fn write_vectored<T: IoVectoredBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        loop_write_vectored!(buf, iter, self.write(iter))
    }

    /// Attempts to flush the object, ensuring that any buffered data reach
    /// their destination.
    async fn flush(&mut self) -> IoResult<()>;

    /// Initiates or attempts to shut down this writer, returning success when
    /// the I/O connection has completely shut down.
    async fn shutdown(&mut self) -> IoResult<()>;
}

impl<A: AsyncWrite + ?Sized> AsyncWrite for &mut A {
    async fn write<T: IoBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        (**self).write(buf).await
    }

    async fn write_vectored<T: IoVectoredBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        (**self).write_vectored(buf).await
    }

    async fn flush(&mut self) -> IoResult<()> {
        (**self).flush().await
    }

    async fn shutdown(&mut self) -> IoResult<()> {
        (**self).shutdown().await
    }
}

impl<W: AsyncWrite + ?Sized, #[cfg(feature = "allocator_api")] A: Allocator> AsyncWrite
    for t_alloc!(Box, W, A)
{
    async fn write<T: IoBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        (**self).write(buf).await
    }

    async fn write_vectored<T: IoVectoredBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        (**self).write_vectored(buf).await
    }

    async fn flush(&mut self) -> IoResult<()> {
        (**self).flush().await
    }

    async fn shutdown(&mut self) -> IoResult<()> {
        (**self).shutdown().await
    }
}

/// Write is implemented for `Vec<u8>` by appending to the vector. The vector
/// will grow as needed.
impl<#[cfg(feature = "allocator_api")] A: Allocator> AsyncWrite for t_alloc!(Vec, u8, A) {
    async fn write<T: IoBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        self.extend_from_slice(buf.as_init());
        BufResult(Ok(buf.buf_len()), buf)
    }

    async fn write_vectored<T: IoVectoredBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        let len = buf.iter_slice().map(|b| b.buf_len()).sum();
        self.reserve(len - self.len());
        for buf in buf.iter_slice() {
            self.extend_from_slice(buf);
        }
        BufResult(Ok(len), buf)
    }

    async fn flush(&mut self) -> IoResult<()> {
        Ok(())
    }

    async fn shutdown(&mut self) -> IoResult<()> {
        Ok(())
    }
}

/// # AsyncWriteAt
///
/// Async write with a ownership of a buffer and a position
pub trait AsyncWriteAt {
    /// Like [`AsyncWrite::write`], except that it writes at a specified
    /// position.
    async fn write_at<T: IoBuf>(&mut self, buf: T, pos: u64) -> BufResult<usize, T>;

    /// Like [`AsyncWrite::write_vectored`], except that it writes at a
    /// specified position.
    async fn write_vectored_at<T: IoVectoredBuf>(
        &mut self,
        buf: T,
        pos: u64,
    ) -> BufResult<usize, T> {
        loop_write_vectored!(buf, iter, self.write_at(iter, pos))
    }
}

impl<A: AsyncWriteAt + ?Sized> AsyncWriteAt for &mut A {
    async fn write_at<T: IoBuf>(&mut self, buf: T, pos: u64) -> BufResult<usize, T> {
        (**self).write_at(buf, pos).await
    }

    async fn write_vectored_at<T: IoVectoredBuf>(
        &mut self,
        buf: T,
        pos: u64,
    ) -> BufResult<usize, T> {
        (**self).write_vectored_at(buf, pos).await
    }
}

impl<W: AsyncWriteAt + ?Sized, #[cfg(feature = "allocator_api")] A: Allocator> AsyncWriteAt
    for t_alloc!(Box, W, A)
{
    async fn write_at<T: IoBuf>(&mut self, buf: T, pos: u64) -> BufResult<usize, T> {
        (**self).write_at(buf, pos).await
    }

    async fn write_vectored_at<T: IoVectoredBuf>(
        &mut self,
        buf: T,
        pos: u64,
    ) -> BufResult<usize, T> {
        (**self).write_vectored_at(buf, pos).await
    }
}

impl AsyncWrite for &mut [u8] {
    async fn write<T: IoBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        let slice = buf.as_init();
        BufResult(std::io::Write::write(self, slice), buf)
    }

    async fn write_vectored<T: IoVectoredBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        let mut iter = match buf.owned_iter() {
            Ok(buf) => buf,
            Err(buf) => return BufResult(Ok(0), buf),
        };
        let mut total = 0;
        loop {
            let n = match std::io::Write::write(self, iter.as_init()) {
                Ok(n) => n,
                // TODO: unlikely
                Err(e) => return BufResult(Err(e), iter.into_inner()),
            };
            total += n;
            if (**self).is_empty() {
                return BufResult(Ok(total), iter.into_inner());
            }
            match iter.next() {
                Ok(next) => iter = next,
                Err(buf) => return BufResult(Ok(total), buf),
            }
        }
    }

    async fn flush(&mut self) -> IoResult<()> {
        Ok(())
    }

    async fn shutdown(&mut self) -> IoResult<()> {
        Ok(())
    }
}

macro_rules! impl_write_at {
    ($($(const $len:ident =>)? $ty:ty),*) => {
        $(
            impl<$(const $len: usize)?> AsyncWriteAt for $ty {
                async fn write_at<T: IoBuf>(&mut self, buf: T, pos: u64) -> BufResult<usize, T> {
                    let pos = (pos as usize).min(self.len());
                    let slice = buf.as_init();
                    let n = slice.len().min(self.len() - pos);
                    self[pos..pos + n].copy_from_slice(&slice[..n]);
                    BufResult(Ok(n), buf)
                }

                async fn write_vectored_at<T: IoVectoredBuf>(&mut self, buf: T, pos: u64) -> BufResult<usize, T> {
                    let mut iter = match buf.owned_iter() {
                        Ok(buf) => buf,
                        Err(buf) => return BufResult(Ok(0), buf),
                    };
                    let mut total = 0;
                    loop {
                        let n;
                        (n, iter) = match self.write_at(iter, pos + total as u64).await {
                            BufResult(Ok(n), iter) => (n, iter),
                            // TODO: unlikely
                            BufResult(Err(e), iter) => return BufResult(Err(e), iter.into_inner()),
                        };
                        total += n;
                        if (*self).is_empty() {
                            return BufResult(Ok(total), iter.into_inner());
                        }
                        match iter.next() {
                            Ok(next) => iter = next,
                            Err(buf) => return BufResult(Ok(total), buf),
                        }
                    }
                }
            }
        )*
    }
}

impl_write_at!([u8], const LEN => [u8; LEN]);

/// This implementation aligns the behavior of files. If `pos` is larger than
/// the vector length, the vectored will be extended, and the extended area will
/// be filled with 0.
impl<#[cfg(feature = "allocator_api")] A: Allocator> AsyncWriteAt for t_alloc!(Vec, u8, A) {
    async fn write_at<T: IoBuf>(&mut self, buf: T, pos: u64) -> BufResult<usize, T> {
        let pos = pos as usize;
        let slice = buf.as_init();
        if pos <= self.len() {
            let n = slice.len().min(self.len() - pos);
            if n < slice.len() {
                self.reserve(slice.len() - n);
                self[pos..pos + n].copy_from_slice(&slice[..n]);
                self.extend_from_slice(&slice[n..]);
            } else {
                self[pos..pos + n].copy_from_slice(slice);
            }
        } else {
            self.reserve(pos - self.len() + slice.len());
            self.resize(pos, 0);
            self.extend_from_slice(slice);
        }
        BufResult(Ok(slice.len()), buf)
    }

    async fn write_vectored_at<T: IoVectoredBuf>(
        &mut self,
        buf: T,
        pos: u64,
    ) -> BufResult<usize, T> {
        let mut pos = pos as usize;
        let len = buf.iter_slice().map(|b| b.buf_len()).sum();
        if pos <= self.len() {
            self.reserve(len - (self.len() - pos));
        } else {
            self.reserve(pos - self.len() + len);
            self.resize(pos, 0);
        }
        for slice in buf.iter_slice() {
            if pos <= self.len() {
                let n = slice.len().min(self.len() - pos);
                if n < slice.len() {
                    self[pos..pos + n].copy_from_slice(&slice[..n]);
                    self.extend_from_slice(&slice[n..]);
                } else {
                    self[pos..pos + n].copy_from_slice(slice);
                }
            } else {
                self.extend_from_slice(slice);
            }
            pos += slice.len();
        }
        BufResult(Ok(len), buf)
    }
}

impl<A: AsyncWriteAt> AsyncWrite for Cursor<A> {
    async fn write<T: IoBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        let pos = self.position();
        let (n, buf) = buf_try!(self.get_mut().write_at(buf, pos).await);
        self.set_position(pos + n as u64);
        BufResult(Ok(n), buf)
    }

    async fn write_vectored<T: IoVectoredBuf>(&mut self, buf: T) -> BufResult<usize, T> {
        let pos = self.position();
        let (n, buf) = buf_try!(self.get_mut().write_vectored_at(buf, pos).await);
        self.set_position(pos + n as u64);
        BufResult(Ok(n), buf)
    }

    async fn flush(&mut self) -> IoResult<()> {
        Ok(())
    }

    async fn shutdown(&mut self) -> IoResult<()> {
        Ok(())
    }
}

/// # AsyncZeroCopyWrite
///
/// Async zerocopy write with ownership of a buffer.
pub trait AsyncWriteZerocopy {
    /// The future that will be resolved when the buffer is safe to be reused.
    type BufferReadyFuture<T: IoBuf>: Future<Output = T>;
    /// The future that will be resolved when the vectored buffer is safe to be
    /// reused.
    type VectoredBufferReadyFuture<T: IoVectoredBuf>: Future<Output = T>;

    /// Write some bytes from buffer into this source using the underlying
    /// zero-copy mechanism. It returns a result of the underlying write
    /// operation and a future that will be resolved when the buffer is safe
    /// to be reused.
    fn write_zerocopy<T: IoBuf>(
        &mut self,
        buf: T,
    ) -> impl Future<Output = BufResult<usize, Self::BufferReadyFuture<T>>>;

    /// Like `write_zerocopy`, except that it writes from a buffer implements
    /// [`IoVectoredBuf`] into the source.
    fn write_zerocopy_vectored<T: IoVectoredBuf>(
        &mut self,
        buf: T,
    ) -> impl Future<Output = BufResult<usize, Self::VectoredBufferReadyFuture<T>>>;
}

impl<A: AsyncWriteZerocopy + ?Sized> AsyncWriteZerocopy for &mut A {
    type BufferReadyFuture<T: IoBuf> = A::BufferReadyFuture<T>;
    type VectoredBufferReadyFuture<T: IoVectoredBuf> = A::VectoredBufferReadyFuture<T>;

    fn write_zerocopy<T: IoBuf>(
        &mut self,
        buf: T,
    ) -> impl Future<Output = BufResult<usize, Self::BufferReadyFuture<T>>> {
        (**self).write_zerocopy(buf)
    }

    fn write_zerocopy_vectored<T: IoVectoredBuf>(
        &mut self,
        buf: T,
    ) -> impl Future<Output = BufResult<usize, Self::VectoredBufferReadyFuture<T>>> {
        (**self).write_zerocopy_vectored(buf)
    }
}

impl<W: AsyncWriteZerocopy + ?Sized, #[cfg(feature = "allocator_api")] A: Allocator>
    AsyncWriteZerocopy for t_alloc!(Box, W, A)
{
    type BufferReadyFuture<T: IoBuf> = W::BufferReadyFuture<T>;
    type VectoredBufferReadyFuture<T: IoVectoredBuf> = W::VectoredBufferReadyFuture<T>;

    fn write_zerocopy<T: IoBuf>(
        &mut self,
        buf: T,
    ) -> impl Future<Output = BufResult<usize, Self::BufferReadyFuture<T>>> {
        (**self).write_zerocopy(buf)
    }

    fn write_zerocopy_vectored<T: IoVectoredBuf>(
        &mut self,
        buf: T,
    ) -> impl Future<Output = BufResult<usize, Self::VectoredBufferReadyFuture<T>>> {
        (**self).write_zerocopy_vectored(buf)
    }
}

impl<#[cfg(feature = "allocator_api")] A: Allocator> AsyncWriteZerocopy for t_alloc!(Vec, u8, A) {
    type BufferReadyFuture<T: IoBuf> = future::Ready<T>;
    type VectoredBufferReadyFuture<T: IoVectoredBuf> = future::Ready<T>;

    async fn write_zerocopy<T: IoBuf>(
        &mut self,
        buf: T,
    ) -> BufResult<usize, Self::BufferReadyFuture<T>> {
        let slice = buf.as_init();
        self.extend_from_slice(slice);
        BufResult(Ok(slice.len()), future::ready(buf))
    }

    async fn write_zerocopy_vectored<T: IoVectoredBuf>(
        &mut self,
        buf: T,
    ) -> BufResult<usize, Self::VectoredBufferReadyFuture<T>> {
        let len = buf.iter_slice().map(|b| b.buf_len()).sum();
        self.reserve(len - self.len());
        for slice in buf.iter_slice() {
            self.extend_from_slice(slice);
        }
        BufResult(Ok(len), future::ready(buf))
    }
}