tokio-async-await-0.1.5/Cargo.toml.orig010064400007650000024000000013751341457741600162100ustar0000000000000000[package] name = "tokio-async-await" # When releasing to crates.io: # - Update html_root_url. version = "0.1.5" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" homepage = "https://tokio.rs" documentation = "https://docs.rs/tokio-async-await/0.1.3" description = """ Experimental async/await support for Tokio """ categories = ["asynchronous"] [features] # This feature comes with no promise of stability. Things will # break with each patch release. Use at your own risk. async-await-preview = ["futures/nightly"] [dependencies] futures = "0.1.23" tokio-io = { version = "0.1.7", path = "../tokio-io" } [dev-dependencies] bytes = "0.4.9" tokio = { version = "0.1.8", path = ".." } hyper = "0.12.8" tokio-async-await-0.1.5/Cargo.toml0000644000000021640000000000000124420ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "tokio-async-await" version = "0.1.5" authors = ["Carl Lerche "] description = "Experimental async/await support for Tokio\n" homepage = "https://tokio.rs" documentation = "https://docs.rs/tokio-async-await/0.1.3" categories = ["asynchronous"] license = "MIT" repository = "https://github.com/tokio-rs/tokio" [dependencies.futures] version = "0.1.23" [dependencies.tokio-io] version = "0.1.7" [dev-dependencies.bytes] version = "0.4.9" [dev-dependencies.hyper] version = "0.12.8" [dev-dependencies.tokio] version = "0.1.8" [features] async-await-preview = ["futures/nightly"] tokio-async-await-0.1.5/LICENSE010064400007650000024000000041161341457741600143220ustar0000000000000000Copyright (c) 2019 Tokio Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Copyright (c) 2016 futures-rs authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tokio-async-await-0.1.5/README.md010064400007650000024000000025671341352070500145700ustar0000000000000000# Tokio async/await preview This crate provides a preview of Tokio with async / await support. It is a shim layer on top of `tokio`. **This crate requires Rust nightly and does not provide API stability guarantees. You are living on the edge here.** ## Usage To use this crate, you need to start with a Rust 2018 edition crate, with rustc 1.33.0-nightly or later. Add this to your `Cargo.toml`: ```toml # In the `[packages]` section edition = "2018" # In the `[dependencies]` section tokio = {version = "0.1.0", features = ["async-await-preview"]} ``` Then, get started. In your application, add: ```rust // The nightly features that are commonly needed with async / await #![feature(await_macro, async_await, futures_api)] // This pulls in the `tokio-async-await` crate. While Rust 2018 doesn't require // `extern crate`, we need to pull in the macros. #[macro_use] extern crate tokio; fn main() { // And we are async... tokio::run_async(async { println!("Hello"); }); } ``` Because nightly is required, run the app with `cargo +nightly run` Check the [examples](examples) directory for more. ## License This project is licensed under the [MIT license](LICENSE). ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Tokio by you, shall be licensed as MIT, without any additional terms or conditions. tokio-async-await-0.1.5/src/await.rs010064400007650000024000000007201337762053300155510ustar0000000000000000/// Wait for a future to complete. #[macro_export] macro_rules! await { ($e:expr) => {{ use $crate::std_await; #[allow(unused_imports)] use $crate::compat::forward::IntoAwaitable as IntoAwaitableForward; #[allow(unused_imports)] use $crate::compat::backward::IntoAwaitable as IntoAwaitableBackward; #[allow(unused_mut)] let mut e = $e; let e = e.into_awaitable(); std_await!(e) }} } tokio-async-await-0.1.5/src/compat/backward.rs010064400007650000024000000035571341352070500175070ustar0000000000000000use futures::{Future, Poll}; use std::pin::Pin; use std::future::{ Future as StdFuture, }; use std::ptr::NonNull; use std::task::{ LocalWaker, Poll as StdPoll, UnsafeWake, Waker, }; /// Convert an 0.3 `Future` to an 0.1 `Future`. #[derive(Debug)] pub struct Compat(Pin>); impl Compat { /// Create a new `Compat` backed by `future`. pub fn new(future: T) -> Compat { Compat(Box::pin(future)) } } /// Convert a value into one that can be used with `await!`. pub trait IntoAwaitable { type Awaitable; fn into_awaitable(self) -> Self::Awaitable; } impl IntoAwaitable for T where T: StdFuture, { type Awaitable = Self; fn into_awaitable(self) -> Self { self } } impl Future for Compat where T: StdFuture>, { type Item = Item; type Error = Error; fn poll(&mut self) -> Poll { use futures::Async::*; let local_waker = noop_local_waker(); let res = self.0.as_mut().poll(&local_waker); match res { StdPoll::Ready(Ok(val)) => Ok(Ready(val)), StdPoll::Ready(Err(err)) => Err(err), StdPoll::Pending => Ok(NotReady), } } } // ===== NoopWaker ===== struct NoopWaker; fn noop_local_waker() -> LocalWaker { let w: NonNull = NonNull::dangling(); unsafe { LocalWaker::new(w) } } fn noop_waker() -> Waker { let w: NonNull = NonNull::dangling(); unsafe { Waker::new(w) } } unsafe impl UnsafeWake for NoopWaker { unsafe fn clone_raw(&self) -> Waker { noop_waker() } unsafe fn drop_raw(&self) { } unsafe fn wake(&self) { unimplemented!("async-await-preview currently only supports futures 0.1. Use the compatibility layer of futures 0.3 instead, if you want to use futures 0.3."); } } tokio-async-await-0.1.5/src/compat/forward.rs010064400007650000024000000033711337762053300174000ustar0000000000000000 use futures::{Future, Async}; use std::marker::Unpin; use std::future::Future as StdFuture; use std::pin::Pin; use std::task::{LocalWaker, Poll as StdPoll}; /// Converts an 0.1 `Future` into an 0.3 `Future`. #[derive(Debug)] pub struct Compat(T); pub(crate) fn convert_poll(poll: Result, E>) -> StdPoll> { use futures::Async::{Ready, NotReady}; match poll { Ok(Ready(val)) => StdPoll::Ready(Ok(val)), Ok(NotReady) => StdPoll::Pending, Err(err) => StdPoll::Ready(Err(err)), } } pub(crate) fn convert_poll_stream( poll: Result>, E>) -> StdPoll>> { use futures::Async::{Ready, NotReady}; match poll { Ok(Ready(Some(val))) => StdPoll::Ready(Some(Ok(val))), Ok(Ready(None)) => StdPoll::Ready(None), Ok(NotReady) => StdPoll::Pending, Err(err) => StdPoll::Ready(Some(Err(err))), } } /// Convert a value into one that can be used with `await!`. pub trait IntoAwaitable { type Awaitable; /// Convert `self` into a value that can be used with `await!`. fn into_awaitable(self) -> Self::Awaitable; } impl IntoAwaitable for T { type Awaitable = Compat; fn into_awaitable(self) -> Self::Awaitable { Compat(self) } } impl StdFuture for Compat where T: Future + Unpin { type Output = Result; fn poll(mut self: Pin<&mut Self>, _lw: &LocalWaker) -> StdPoll { use futures::Async::{Ready, NotReady}; // TODO: wire in cx match self.0.poll() { Ok(Ready(val)) => StdPoll::Ready(Ok(val)), Ok(NotReady) => StdPoll::Pending, Err(e) => StdPoll::Ready(Err(e)), } } } tokio-async-await-0.1.5/src/compat/mod.rs010064400007650000024000000000641337762053300165070ustar0000000000000000#![doc(hidden)] pub mod forward; pub mod backward; tokio-async-await-0.1.5/src/io/flush.rs010064400007650000024000000014121337762053300161730ustar0000000000000000use tokio_io::AsyncWrite; use std::io; use std::future::Future; use std::marker::Unpin; use std::pin::Pin; use std::task::{LocalWaker, Poll}; /// A future used to fully flush an I/O object. #[derive(Debug)] pub struct Flush<'a, T: ?Sized + 'a> { writer: &'a mut T, } // Pin is never projected to fields impl<'a, T: ?Sized> Unpin for Flush<'a, T> {} impl<'a, T: AsyncWrite + ?Sized> Flush<'a, T> { pub(super) fn new(writer: &'a mut T) -> Flush<'a, T> { Flush { writer } } } impl<'a, T: AsyncWrite + ?Sized> Future for Flush<'a, T> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, _wx: &LocalWaker) -> Poll { use crate::compat::forward::convert_poll; convert_poll(self.writer.poll_flush()) } } tokio-async-await-0.1.5/src/io/mod.rs010064400007650000024000000140301337762053300156310ustar0000000000000000//! Use I/O with `async` / `await`. mod flush; mod read; mod read_exact; mod write; mod write_all; pub use self::flush::Flush; pub use self::read::Read; pub use self::read_exact::ReadExact; pub use self::write::Write; pub use self::write_all::WriteAll; use tokio_io::{AsyncRead, AsyncWrite}; /// An extension trait which adds utility methods to `AsyncRead` types. pub trait AsyncReadExt: AsyncRead { /// Tries to read some bytes directly into the given `buf` in an /// asynchronous manner, returning a future. /// /// The returned future will resolve to the number of bytes read once the read /// operation is completed. /// /// # Examples /// /// ``` /// #![feature(async_await, await_macro, futures_api)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. /// use tokio::prelude::AsyncReadExt; /// use std::io::Cursor; /// /// let mut reader = Cursor::new([1, 2, 3, 4]); /// let mut output = [0u8; 5]; /// /// let bytes = await!(reader.read_async(&mut output[..])).unwrap(); /// /// // This is only guaranteed to be 4 because `&[u8]` is a synchronous /// // reader. In a real system you could get anywhere from 1 to /// // `output.len()` bytes in a single read. /// assert_eq!(bytes, 4); /// assert_eq!(output, [1, 2, 3, 4, 0]); /// }); /// ``` fn read_async<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self> { Read::new(self, buf) } /// Creates a future which will read exactly enough bytes to fill `buf`, /// returning an error if end of file (EOF) is hit sooner. /// /// The returned future will resolve once the read operation is completed. /// /// In the case of an error the buffer and the object will be discarded, with /// the error yielded. /// /// # Examples /// /// ``` /// #![feature(async_await, await_macro, futures_api)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. /// use tokio::prelude::AsyncReadExt; /// use std::io::Cursor; /// /// let mut reader = Cursor::new([1, 2, 3, 4]); /// let mut output = [0u8; 4]; /// /// await!(reader.read_exact_async(&mut output)).unwrap(); /// /// assert_eq!(output, [1, 2, 3, 4]); /// }); /// ``` /// /// ## EOF is hit before `buf` is filled /// /// ``` /// #![feature(async_await, await_macro, futures_api)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. /// use tokio::prelude::AsyncReadExt; /// use std::io::{self, Cursor}; /// /// let mut reader = Cursor::new([1, 2, 3, 4]); /// let mut output = [0u8; 5]; /// /// let result = await!(reader.read_exact_async(&mut output)); /// /// assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof); /// }); /// ``` fn read_exact_async<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self> { ReadExact::new(self, buf) } } /// An extension trait which adds utility methods to `AsyncWrite` types. pub trait AsyncWriteExt: AsyncWrite { /// Write data into this object. /// /// Creates a future that will write the entire contents of the buffer `buf` into /// this `AsyncWrite`. /// /// The returned future will not complete until all the data has been written. /// /// # Examples /// /// ``` /// #![feature(async_await, await_macro, futures_api)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. /// use tokio::prelude::AsyncWriteExt; /// use std::io::Cursor; /// /// let mut buf = [0u8; 5]; /// let mut writer = Cursor::new(&mut buf[..]); /// /// let n = await!(writer.write_async(&[1, 2, 3, 4])).unwrap(); /// /// assert_eq!(writer.into_inner()[..n], [1, 2, 3, 4, 0][..n]); /// }); /// ``` fn write_async<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self> { Write::new(self, buf) } /// Write an entire buffer into this object. /// /// Creates a future that will write the entire contents of the buffer `buf` into /// this `AsyncWrite`. /// /// The returned future will not complete until all the data has been written. /// /// # Examples /// /// ``` /// #![feature(async_await, await_macro, futures_api)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. /// use tokio::prelude::AsyncWriteExt; /// use std::io::Cursor; /// /// let mut buf = [0u8; 5]; /// let mut writer = Cursor::new(&mut buf[..]); /// /// await!(writer.write_all_async(&[1, 2, 3, 4])).unwrap(); /// /// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]); /// }); /// ``` fn write_all_async<'a>(&'a mut self, buf: &'a [u8]) -> WriteAll<'a, Self> { WriteAll::new(self, buf) } /// Creates a future which will entirely flush this `AsyncWrite`. /// /// # Examples /// /// ``` /// #![feature(async_await, await_macro, futures_api)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. /// use tokio::prelude::AsyncWriteExt; /// use std::io::{BufWriter, Cursor}; /// /// let mut output = [0u8; 5]; /// /// { /// let mut writer = Cursor::new(&mut output[..]); /// let mut buffered = BufWriter::new(writer); /// await!(buffered.write_all_async(&[1, 2])).unwrap(); /// await!(buffered.write_all_async(&[3, 4])).unwrap(); /// await!(buffered.flush_async()).unwrap(); /// } /// /// assert_eq!(output, [1, 2, 3, 4, 0]); /// }); /// ``` fn flush_async<'a>(&mut self) -> Flush { Flush::new(self) } } impl AsyncReadExt for T {} impl AsyncWriteExt for T {} tokio-async-await-0.1.5/src/io/read.rs010064400007650000024000000015751337762053300157770ustar0000000000000000use tokio_io::AsyncRead; use std::future::Future; use std::task::{self, Poll}; use std::io; use std::marker::Unpin; use std::pin::Pin; /// A future which can be used to read bytes. #[derive(Debug)] pub struct Read<'a, T: ?Sized + 'a> { reader: &'a mut T, buf: &'a mut [u8], } // Pinning is never projected to fields impl<'a, T: ?Sized> Unpin for Read<'a, T> {} impl<'a, T: AsyncRead + ?Sized> Read<'a, T> { pub(super) fn new(reader: &'a mut T, buf: &'a mut [u8]) -> Read<'a, T> { Read { reader, buf, } } } impl<'a, T: AsyncRead + ?Sized> Future for Read<'a, T> { type Output = io::Result; fn poll(mut self: Pin<&mut Self>, _lw: &task::LocalWaker) -> Poll { use crate::compat::forward::convert_poll; let this = &mut *self; convert_poll(this.reader.poll_read(this.buf)) } } tokio-async-await-0.1.5/src/io/read_exact.rs010064400007650000024000000025561337762053300171630ustar0000000000000000use tokio_io::AsyncRead; use std::future::Future; use std::task::{self, Poll}; use std::io; use std::marker::Unpin; use std::mem; use std::pin::Pin; /// A future which can be used to read exactly enough bytes to fill a buffer. #[derive(Debug)] pub struct ReadExact<'a, T: ?Sized + 'a> { reader: &'a mut T, buf: &'a mut [u8], } // Pinning is never projected to fields impl<'a, T: ?Sized> Unpin for ReadExact<'a, T> {} impl<'a, T: AsyncRead + ?Sized> ReadExact<'a, T> { pub(super) fn new(reader: &'a mut T, buf: &'a mut [u8]) -> ReadExact<'a, T> { ReadExact { reader, buf, } } } fn eof() -> io::Error { io::Error::new(io::ErrorKind::UnexpectedEof, "early eof") } impl<'a, T: AsyncRead + ?Sized> Future for ReadExact<'a, T> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, _lw: &task::LocalWaker) -> Poll { use crate::compat::forward::convert_poll; let this = &mut *self; while !this.buf.is_empty() { let n = try_ready!(convert_poll(this.reader.poll_read(this.buf))); { let (_, rest) = mem::replace(&mut this.buf, &mut []).split_at_mut(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(eof())) } } Poll::Ready(Ok(())) } } tokio-async-await-0.1.5/src/io/write.rs010064400007650000024000000015671337762053300162170ustar0000000000000000use tokio_io::AsyncWrite; use std::future::Future; use std::task::{self, Poll}; use std::io; use std::marker::Unpin; use std::pin::Pin; /// A future used to write data. #[derive(Debug)] pub struct Write<'a, T: 'a + ?Sized> { writer: &'a mut T, buf: &'a [u8], } // Pinning is never projected to fields impl<'a, T: ?Sized> Unpin for Write<'a, T> {} impl<'a, T: AsyncWrite + ?Sized> Write<'a, T> { pub(super) fn new(writer: &'a mut T, buf: &'a [u8]) -> Write<'a, T> { Write { writer, buf, } } } impl<'a, T: AsyncWrite + ?Sized> Future for Write<'a, T> { type Output = io::Result; fn poll(mut self: Pin<&mut Self>, _lw: &task::LocalWaker) -> Poll> { use crate::compat::forward::convert_poll; let this = &mut *self; convert_poll(this.writer.poll_write(this.buf)) } } tokio-async-await-0.1.5/src/io/write_all.rs010064400007650000024000000025371337762053300170450ustar0000000000000000use tokio_io::AsyncWrite; use std::future::Future; use std::task::{self, Poll}; use std::io; use std::marker::Unpin; use std::mem; use std::pin::Pin; /// A future used to write the entire contents of a buffer. #[derive(Debug)] pub struct WriteAll<'a, T: ?Sized + 'a> { writer: &'a mut T, buf: &'a [u8], } // Pinning is never projected to fields impl<'a, T: ?Sized> Unpin for WriteAll<'a, T> {} impl<'a, T: AsyncWrite + ?Sized> WriteAll<'a, T> { pub(super) fn new(writer: &'a mut T, buf: &'a [u8]) -> WriteAll<'a, T> { WriteAll { writer, buf, } } } fn zero_write() -> io::Error { io::Error::new(io::ErrorKind::WriteZero, "zero-length write") } impl<'a, T: AsyncWrite + ?Sized> Future for WriteAll<'a, T> { type Output = io::Result<()>; fn poll(mut self: Pin<&mut Self>, _lw: &task::LocalWaker) -> Poll> { use crate::compat::forward::convert_poll; let this = &mut *self; while !this.buf.is_empty() { let n = try_ready!(convert_poll(this.writer.poll_write(this.buf))); { let (_, rest) = mem::replace(&mut this.buf, &[]).split_at(n); this.buf = rest; } if n == 0 { return Poll::Ready(Err(zero_write())) } } Poll::Ready(Ok(())) } } tokio-async-await-0.1.5/src/lib.rs010064400007650000024000000051271341457741600152230ustar0000000000000000#![cfg(feature = "async-await-preview")] #![feature( rust_2018_preview, arbitrary_self_types, async_await, await_macro, futures_api, )] #![doc(html_root_url = "https://docs.rs/tokio-async-await/0.1.5")] #![deny(missing_docs, missing_debug_implementations)] #![cfg_attr(test, deny(warnings))] //! A preview of Tokio w/ `async` / `await` support. extern crate futures; extern crate tokio_io; /// Extracts the successful type of a `Poll>`. /// /// This macro bakes in propagation of `Pending` and `Err` signals by returning early. macro_rules! try_ready { ($x:expr) => { match $x { std::task::Poll::Ready(Ok(x)) => x, std::task::Poll::Ready(Err(e)) => return std::task::Poll::Ready(Err(e.into())), std::task::Poll::Pending => return std::task::Poll::Pending, } } } #[macro_use] mod await; pub mod compat; pub mod io; pub mod sink; pub mod stream; /* pub mod prelude { //! A "prelude" for users of the `tokio` crate. //! //! This prelude is similar to the standard library's prelude in that you'll //! almost always want to import its entire contents, but unlike the standard //! library's prelude you'll have to do so manually: //! //! ``` //! use tokio::prelude::*; //! ``` //! //! The prelude may grow over time as additional items see ubiquitous use. pub use tokio_main::prelude::*; #[doc(inline)] pub use crate::async_await::{ io::{ AsyncReadExt, AsyncWriteExt, }, sink::{ SinkExt, }, stream::{ StreamExt, }, }; } */ // Rename the `await` macro in `std`. This is used by the redefined // `await` macro in this crate. #[doc(hidden)] pub use std::await as std_await; /* use std::future::{Future as StdFuture}; fn run>(t: T) { drop(t); } async fn map_ok(future: T) -> Result<(), ()> { let _ = await!(future); Ok(()) } /// Like `tokio::run`, but takes an `async` block pub fn run_async(future: F) where F: StdFuture + Send + 'static, { use async_await::compat::backward; let future = backward::Compat::new(map_ok(future)); run(future); unimplemented!(); } */ /* /// Like `tokio::spawn`, but takes an `async` block pub fn spawn_async(future: F) where F: StdFuture + Send + 'static, { use crate::async_await::compat::backward; spawn(backward::Compat::new(async || { let _ = await!(future); Ok(()) })); } */ tokio-async-await-0.1.5/src/sink/mod.rs010064400007650000024000000011601337762053300161660ustar0000000000000000//! Use sinks with `async` / `await`. mod send; pub use self::send::Send; use futures::Sink; use std::marker::Unpin; /// An extension trait which adds utility methods to `Sink` types. pub trait SinkExt: Sink { /// Send an item into the sink. /// /// Note that, **because of the flushing requirement, it is usually better /// to batch together items to send via `send_all`, rather than flushing /// between each item.** fn send_async(&mut self, item: Self::SinkItem) -> Send where Self: Sized + Unpin, { Send::new(self, item) } } impl SinkExt for T {} tokio-async-await-0.1.5/src/sink/send.rs010064400007650000024000000027301337762053300163440ustar0000000000000000use futures::Sink; use std::future::Future; use std::task::{self, Poll}; use std::marker::Unpin; use std::pin::Pin; /// Future for the `SinkExt::send_async` combinator, which sends a value to a /// sink and then waits until the sink has fully flushed. #[derive(Debug)] pub struct Send<'a, T: Sink + 'a + ?Sized> { sink: &'a mut T, item: Option, } impl Unpin for Send<'_, T> {} impl<'a, T: Sink + Unpin + ?Sized> Send<'a, T> { pub(super) fn new(sink: &'a mut T, item: T::SinkItem) -> Self { Send { sink, item: Some(item), } } } impl Future for Send<'_, T> { type Output = Result<(), T::SinkError>; fn poll(mut self: Pin<&mut Self>, _lw: &task::LocalWaker) -> Poll { use crate::compat::forward::convert_poll; use futures::AsyncSink::{Ready, NotReady}; if let Some(item) = self.item.take() { match self.sink.start_send(item) { Ok(Ready) => {} Ok(NotReady(val)) => { self.item = Some(val); return Poll::Pending; } Err(err) => { return Poll::Ready(Err(err)); } } } // we're done sending the item, but want to block on flushing the // sink try_ready!(convert_poll(self.sink.poll_complete())); Poll::Ready(Ok(())) } } tokio-async-await-0.1.5/src/stream/mod.rs010064400007650000024000000020041337762053300165130ustar0000000000000000//! Use streams with `async` / `await`. mod next; pub use self::next::Next; use futures::Stream; use std::marker::Unpin; /// An extension trait which adds utility methods to `Stream` types. pub trait StreamExt: Stream { /// Creates a future that resolves to the next item in the stream. /// /// # Examples /// /// ``` /// #![feature(await_macro, async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. /// use tokio::prelude::{stream, StreamExt}; /// /// let mut stream = stream::iter_ok::<_, ()>(1..3); /// /// assert_eq!(await!(stream.next()), Some(Ok(1))); /// assert_eq!(await!(stream.next()), Some(Ok(2))); /// assert_eq!(await!(stream.next()), Some(Ok(3))); /// assert_eq!(await!(stream.next()), None); /// }); /// ``` fn next(&mut self) -> Next where Self: Sized + Unpin, { Next::new(self) } } impl StreamExt for T {} tokio-async-await-0.1.5/src/stream/next.rs010064400007650000024000000013341337762053300167170ustar0000000000000000use futures::Stream; use std::future::Future; use std::marker::Unpin; use std::pin::Pin; use std::task::{LocalWaker, Poll}; /// A future of the next element of a stream. #[derive(Debug)] pub struct Next<'a, T: 'a> { stream: &'a mut T, } impl<'a, T: Stream + Unpin> Unpin for Next<'a, T> {} impl<'a, T: Stream + Unpin> Next<'a, T> { pub(super) fn new(stream: &'a mut T) -> Next<'a, T> { Next { stream } } } impl<'a, T: Stream + Unpin> Future for Next<'a, T> { type Output = Option>; fn poll(mut self: Pin<&mut Self>, _lw: &LocalWaker) -> Poll { use crate::compat::forward::convert_poll_stream; convert_poll_stream(self.stream.poll()) } } tokio-async-await-0.1.5/.cargo_vcs_info.json0000644000000001120000000000000144330ustar00{ "git": { "sha1": "961aae41c4074ee3ccab09648e870cfa8592724c" } }