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
//! # Adapter for using async read/write streams in `std::io` contexts //! //! Sometimes, you'll come across an interface that only takes `std::io` `Read + Write` //! types, but also needs to be adapted for an async/await application. The //! [AsStdIo] adapter allows an [AsyncRead] + [AsyncWrite] stream to be used //! as its counterpart from `std::io`. Assuming that whatever is consuming the //! wrapped stream will bubble up [io::ErrorKind::WouldBlock] errors and allows //! operations to be resumed, this provides a way to both use an async stream //! with the `std::io`-only interface, and to write an async wrapper around it. //! //! ## Example //! //! ```rust //! # use std::collections::VecDeque; //! # use std::io::{self, Read}; //! # use std::pin::Pin; //! # //! # use futures::prelude::*; //! # use futures::ready; //! # use futures::task::{Context, Poll}; //! # //! use async_stdio::*; //! //! struct ChunkReader<R> { //! // ... //! # reader: R, //! # chunk_size: usize, //! # buffer: VecDeque<u8>, //! } //! //! impl<R: Read> ChunkReader<R> { //! fn new(reader: R, chunk_size: usize) -> Self { //! // ... //! # ChunkReader { //! # reader, //! # chunk_size, //! # buffer: Default::default(), //! # } //! } //! //! /// Reads a chunk from the stream //! /// //! /// If the stream ends before a full chunk is read, may return a smaller //! /// chunk. Returns an empty chunk if there is no more to be read. //! fn read_chunk(&mut self) -> io::Result<Vec<u8>> { //! // ... //! # let mut tmp = vec![0u8; self.chunk_size]; //! # let mut bytes = self.chunk_size; //! # loop { //! # if self.buffer.len() >= self.chunk_size || bytes == 0 { //! # let end = self.buffer.len().min(self.chunk_size); //! # tmp.truncate(0); //! # return Ok(self.buffer.drain(..end).fold(tmp, |mut out, b| { //! # out.push(b); //! # out //! # })); //! # } //! # bytes = self.reader.read(&mut tmp)?; //! # self.buffer.extend(&tmp[..bytes]); //! # } //! } //! } //! //! /// Wrapper around the std-only `ChunkReader` to turn it //! /// into an async `Stream` //! struct AsyncChunked<S> { //! inner: ChunkReader<AsStdIo<S>>, //! waker_ctrl: WakerCtrlHandle, //! } //! //! impl<S: AsyncRead + Unpin> AsyncChunked<S> { //! fn new(stream: S, chunk_size: usize) -> AsyncChunked<S> { //! let (stream, waker_ctrl) = AsStdIo::new(stream, None); //! let inner = ChunkReader::new(stream, chunk_size); //! AsyncChunked { inner, waker_ctrl } //! } //! } //! //! impl<S: AsyncRead + Unpin> Stream for AsyncChunked<S> { //! type Item = io::Result<Vec<u8>>; //! //! fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { //! let this = self.get_mut(); //! // Make sure the waker is set before the calls to `std::io::Read::read` //! this.waker_ctrl.register(cx.waker()); //! // `into_poll` (from `ResultExt`) converts `WouldBlock` into `Pending` //! let chunk_res = ready!(this.inner.read_chunk().into_poll()); //! //! Poll::Ready( //! chunk_res //! .map(|chunk| if chunk.is_empty() { None } else { Some(chunk) }) //! .transpose(), //! ) //! } //! } //! //! // Pretend this doesn't already implement `io::Read` //! let stream = io::Cursor::new(vec![0, 1, 2, 3, 4, 5]); //! let mut async_chunked = AsyncChunked::new(stream, 2); //! //! # use futures::executor::block_on; //! let chunks: Vec<Vec<u8>> = block_on(async_chunked.map(|chunk| chunk.unwrap()).collect()); //! //! let expected: Vec<Vec<u8>> = vec![vec![0, 1], vec![2, 3], vec![4, 5]]; //! //! assert_eq!(chunks, expected,); //! ``` #![warn(missing_docs)] use std::io; use std::marker::Unpin; use std::ops::{Deref, DerefMut}; use std::pin::Pin; use std::sync::Arc; use futures::io::{AsyncRead, AsyncWrite}; use futures::task::{ArcWake, AtomicWaker, Context, Poll, Waker}; /// Adapter to use an async byte stream as a `std::io::{Read, Write}` type /// /// For correct operation, `set_waker` must be called before any calls to `read` /// or `write`. If the async stream would return `Poll::Pending`, it will be /// converted to an `io::ErrorKind::WouldBlock` error. #[derive(Debug)] pub struct AsStdIo<S> { inner: S, waker: Waker, } /// Waker control for the [AsStdIo] wrapper /// /// Internally, it's an [AtomicWaker], so the waker it points to can be updated /// with `waker_ctrl.register(cx.waker())`. pub struct WakerCtrl(AtomicWaker); /// Convenience type for a ref-counted pointer to a [WakerCtrl]. pub type WakerCtrlHandle = Arc<WakerCtrl>; impl Deref for WakerCtrl { type Target = AtomicWaker; fn deref(&self) -> &AtomicWaker { &self.0 } } impl DerefMut for WakerCtrl { fn deref_mut(&mut self) -> &mut AtomicWaker { &mut self.0 } } impl ArcWake for WakerCtrl { fn wake_by_ref(arc_self: &Arc<Self>) { AtomicWaker::wake(&*arc_self) } } /// Extension traits for `Poll` and `io::Result` pub mod ext { use super::*; /// Extension trait for converting an `io::Result<T>` to a `Poll<io::Result<T>>` pub trait ResultExt<T> { /// Perform the conversion /// /// An IO error with the kind [io::ErrorKind::WouldBlock] will get converted /// to [Poll::Pending]. All other results will become [Poll::Ready] fn into_poll(self) -> Poll<io::Result<T>>; } impl<T> ResultExt<T> for io::Result<T> { fn into_poll(self) -> Poll<io::Result<T>> { if let Err(ref e) = self { if e.kind() == io::ErrorKind::WouldBlock { return Poll::Pending; } } Poll::Ready(self) } } /// Extension trait for converting a `Poll<io::Result<T>>` into an `io::Result<T>` pub trait PollExt<T> { /// Perform the conversion /// /// A `Poll::Pending` will be turned into an IO error with the kind /// [io::ErrorKind::WouldBlock]. [Poll::Ready] will simply be unwrapped. fn into_io_result(self) -> io::Result<T>; } impl<T> PollExt<T> for Poll<io::Result<T>> { fn into_io_result(self) -> io::Result<T> { match self { Poll::Ready(res) => res, Poll::Pending => Err(io::ErrorKind::WouldBlock.into()), } } } } pub use ext::{PollExt as _, ResultExt as _}; impl<S> Deref for AsStdIo<S> { type Target = S; fn deref(&self) -> &Self::Target { &self.inner } } impl<S> DerefMut for AsStdIo<S> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl<S> AsStdIo<S> { /// Wrap the async stream and initialize the wrapper with the provided waker. /// /// If no waker is provided, it will be initialized with a no-op waker. /// /// Also returns a handle that can be used to control the waker. pub fn new(stream: S, waker: Option<&Waker>) -> (Self, WakerCtrlHandle) { let atomic_waker = AtomicWaker::new(); if let Some(waker) = waker { atomic_waker.register(waker); } let waker_ctrl = Arc::new(WakerCtrl(atomic_waker)); ( AsStdIo { inner: stream, waker: waker_ctrl.clone().into_waker(), }, waker_ctrl, ) } /// Get a pinned reference to the internal stream and a context with which to /// poll it. /// /// Sometimes useful if you need to perform some operation such as /// [AsyncWrite::close] on it which doesn't have an `std` counterpart. pub fn get_stream_with_context(&mut self) -> (Pin<&mut S>, Context) where S: Unpin, { (Pin::new(&mut self.inner), Context::from_waker(&self.waker)) } } impl<S> io::Read for AsStdIo<S> where S: AsyncRead + Unpin, { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let (stream, mut cx) = self.get_stream_with_context(); stream.poll_read(&mut cx, buf).into_io_result() } } impl<S> io::Write for AsStdIo<S> where S: AsyncWrite + Unpin, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let (stream, mut cx) = self.get_stream_with_context(); stream.poll_write(&mut cx, buf).into_io_result() } fn flush(&mut self) -> io::Result<()> { let (stream, mut cx) = self.get_stream_with_context(); stream.poll_flush(&mut cx).into_io_result() } }