partial_io/async_write.rs
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
// Copyright (c) The partial-io Contributors
// SPDX-License-Identifier: MIT
//! This module contains an `AsyncWrite` wrapper that breaks writes up
//! according to a provided iterator.
//!
//! This is separate from `PartialWrite` because on `WouldBlock` errors, it
//! causes `futures` to try writing or flushing again.
use crate::{futures_util::FuturesOps, PartialOp};
use futures::{io, prelude::*};
use pin_project::pin_project;
use std::{
fmt,
pin::Pin,
task::{Context, Poll},
};
/// A wrapper that breaks inner `AsyncWrite` instances up according to the
/// provided iterator.
///
/// Available with the `futures03` feature for `futures` traits, and with the `tokio1` feature for
/// `tokio` traits.
///
/// # Examples
///
/// This example uses `tokio`.
///
/// ```rust
/// # #[cfg(feature = "tokio1")]
/// use partial_io::{PartialAsyncWrite, PartialOp};
/// # #[cfg(feature = "tokio1")]
/// use std::io::{self, Cursor};
/// # #[cfg(feature = "tokio1")]
/// use tokio::io::AsyncWriteExt;
///
/// # #[cfg(feature = "tokio1")]
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let writer = Cursor::new(Vec::new());
/// // Sequential calls to `poll_write()` and the other `poll_` methods simulate the following behavior:
/// let iter = vec![
/// PartialOp::Err(io::ErrorKind::WouldBlock), // A not-ready state.
/// PartialOp::Limited(2), // Only allow 2 bytes to be written.
/// PartialOp::Err(io::ErrorKind::InvalidData), // Error from the underlying stream.
/// PartialOp::Unlimited, // Allow as many bytes to be written as possible.
/// ];
/// let mut partial_writer = PartialAsyncWrite::new(writer, iter);
/// let in_data = vec![1, 2, 3, 4];
///
/// // This causes poll_write to be called twice, yielding after the first call (WouldBlock).
/// assert_eq!(partial_writer.write(&in_data).await?, 2);
/// let cursor_ref = partial_writer.get_ref();
/// let out = cursor_ref.get_ref();
/// assert_eq!(&out[..], &[1, 2]);
///
/// // This next call returns an error.
/// assert_eq!(
/// partial_writer.write(&in_data[2..]).await.unwrap_err().kind(),
/// io::ErrorKind::InvalidData,
/// );
///
/// // And this one causes the last two bytes to be written.
/// assert_eq!(partial_writer.write(&in_data[2..]).await?, 2);
/// let cursor_ref = partial_writer.get_ref();
/// let out = cursor_ref.get_ref();
/// assert_eq!(&out[..], &[1, 2, 3, 4]);
///
/// Ok(())
/// }
///
/// # #[cfg(not(feature = "tokio1"))]
/// # fn main() {
/// # assert!(true, "dummy test");
/// # }
/// ```
#[pin_project]
pub struct PartialAsyncWrite<W> {
#[pin]
inner: W,
ops: FuturesOps,
}
impl<W> PartialAsyncWrite<W> {
/// Creates a new `PartialAsyncWrite` wrapper over the writer with the specified `PartialOp`s.
pub fn new<I>(inner: W, iter: I) -> Self
where
I: IntoIterator<Item = PartialOp> + 'static,
I::IntoIter: Send,
{
PartialAsyncWrite {
inner,
ops: FuturesOps::new(iter),
}
}
/// Sets the `PartialOp`s for this writer.
pub fn set_ops<I>(&mut self, iter: I) -> &mut Self
where
I: IntoIterator<Item = PartialOp> + 'static,
I::IntoIter: Send,
{
self.ops.replace(iter);
self
}
/// Sets the `PartialOp`s for this writer in a pinned context.
pub fn pin_set_ops<I>(self: Pin<&mut Self>, iter: I) -> Pin<&mut Self>
where
I: IntoIterator<Item = PartialOp> + 'static,
I::IntoIter: Send,
{
let mut this = self;
this.as_mut().project().ops.replace(iter);
this
}
/// Returns a shared reference to the underlying writer.
pub fn get_ref(&self) -> &W {
&self.inner
}
/// Returns a mutable reference to the underlying writer.
pub fn get_mut(&mut self) -> &mut W {
&mut self.inner
}
/// Returns a pinned mutable reference to the underlying writer.
pub fn pin_get_mut(self: Pin<&mut Self>) -> Pin<&mut W> {
self.project().inner
}
/// Consumes this wrapper, returning the underlying writer.
pub fn into_inner(self) -> W {
self.inner
}
}
// ---
// Futures impls
// ---
impl<W> AsyncWrite for PartialAsyncWrite<W>
where
W: AsyncWrite,
{
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
let this = self.project();
let inner = this.inner;
this.ops.poll_impl(
cx,
|cx, len| match len {
Some(len) => inner.poll_write(cx, &buf[..len]),
None => inner.poll_write(cx, buf),
},
buf.len(),
"error during poll_write, generated by partial-io",
)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
let this = self.project();
let inner = this.inner;
this.ops.poll_impl_no_limit(
cx,
|cx| inner.poll_flush(cx),
"error during poll_flush, generated by partial-io",
)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
let this = self.project();
let inner = this.inner;
this.ops.poll_impl_no_limit(
cx,
|cx| inner.poll_close(cx),
"error during poll_close, generated by partial-io",
)
}
}
/// This is a forwarding impl to support duplex structs.
impl<W> AsyncRead for PartialAsyncWrite<W>
where
W: AsyncRead,
{
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.project().inner.poll_read(cx, buf)
}
#[inline]
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context,
bufs: &mut [io::IoSliceMut],
) -> Poll<io::Result<usize>> {
self.project().inner.poll_read_vectored(cx, bufs)
}
}
/// This is a forwarding impl to support duplex structs.
impl<W> AsyncBufRead for PartialAsyncWrite<W>
where
W: AsyncBufRead,
{
#[inline]
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<&[u8]>> {
self.project().inner.poll_fill_buf(cx)
}
#[inline]
fn consume(self: Pin<&mut Self>, amt: usize) {
self.project().inner.consume(amt)
}
}
/// This is a forwarding impl to support duplex structs.
impl<W> AsyncSeek for PartialAsyncWrite<W>
where
W: AsyncSeek,
{
#[inline]
fn poll_seek(
self: Pin<&mut Self>,
cx: &mut Context,
pos: io::SeekFrom,
) -> Poll<io::Result<u64>> {
self.project().inner.poll_seek(cx, pos)
}
}
// ---
// Tokio impls
// ---
#[cfg(feature = "tokio1")]
mod tokio_impl {
use super::PartialAsyncWrite;
use std::{
io::{self, SeekFrom},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, ReadBuf};
impl<W> AsyncWrite for PartialAsyncWrite<W>
where
W: AsyncWrite,
{
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.project();
let inner = this.inner;
this.ops.poll_impl(
cx,
|cx, len| match len {
Some(len) => inner.poll_write(cx, &buf[..len]),
None => inner.poll_write(cx, buf),
},
buf.len(),
"error during poll_write, generated by partial-io",
)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
let this = self.project();
let inner = this.inner;
this.ops.poll_impl_no_limit(
cx,
|cx| inner.poll_flush(cx),
"error during poll_flush, generated by partial-io",
)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
let this = self.project();
let inner = this.inner;
this.ops.poll_impl_no_limit(
cx,
|cx| inner.poll_shutdown(cx),
"error during poll_shutdown, generated by partial-io",
)
}
}
/// This is a forwarding impl to support duplex structs.
impl<W> AsyncRead for PartialAsyncWrite<W>
where
W: AsyncRead,
{
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
self.project().inner.poll_read(cx, buf)
}
}
/// This is a forwarding impl to support duplex structs.
impl<W> AsyncBufRead for PartialAsyncWrite<W>
where
W: AsyncBufRead,
{
#[inline]
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<&[u8]>> {
self.project().inner.poll_fill_buf(cx)
}
#[inline]
fn consume(self: Pin<&mut Self>, amt: usize) {
self.project().inner.consume(amt)
}
}
/// This is a forwarding impl to support duplex structs.
impl<W> AsyncSeek for PartialAsyncWrite<W>
where
W: AsyncSeek,
{
#[inline]
fn start_seek(self: Pin<&mut Self>, position: SeekFrom) -> io::Result<()> {
self.project().inner.start_seek(position)
}
#[inline]
fn poll_complete(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
self.project().inner.poll_complete(cx)
}
}
}
impl<W> fmt::Debug for PartialAsyncWrite<W>
where
W: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PartialAsyncWrite")
.field("inner", &self.inner)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use crate::tests::assert_send;
#[test]
fn test_sendable() {
assert_send::<PartialAsyncWrite<File>>();
}
}