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
// Copyright (c) 2019-2020 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! Create a [`Sink`] implementation from an initial value and a closure
//! returning a [`Future`].
//!
//! This is very similar to how `futures::stream::unfold` creates a `Stream`
//! implementation from a seed value and a future-returning closure.
//!
//! # Examples
//!
//! ```no_run
//! use async_std::io;
//! use futures::prelude::*;
//! use quicksink::Action;
//!
//! quicksink::make_sink(io::stdout(), |mut stdout, action| async move {
//! match action {
//! Action::Send(x) => stdout.write_all(x).await?,
//! Action::Flush => stdout.flush().await?,
//! Action::Close => stdout.close().await?
//! }
//! Ok::<_, io::Error>(stdout)
//! });
//! ```
//!
//! # Panics
//!
//! - If any of the [`Sink`] methods produce an error, the sink transitions
//! to a failure state and none of its methods must be called afterwards or
//! else a panic will occur.
//! - If [`Sink::poll_close`] has been called, no other sink method must be
//! called afterwards or else a panic will be caused.
//!
use futures_core::ready;
use futures_sink::Sink;
use pin_project_lite::pin_project;
use std::{future::Future, pin::Pin, task::{Context, Poll}};
/// Returns a `Sink` impl based on the initial value and the given closure.
///
/// The closure will be applied to the initial value and an [`Action`] that
/// informs it about the action it should perform. The returned [`Future`]
/// will resolve to another value and the process starts over using this
/// output.
pub fn make_sink<S, F, T, A, E>(init: S, f: F) -> SinkImpl<S, F, T, A, E>
where
F: FnMut(S, Action<A>) -> T,
T: Future<Output = Result<S, E>>,
{
SinkImpl {
lambda: f,
future: None,
param: Some(init),
state: State::Empty,
_mark: std::marker::PhantomData
}
}
/// The command given to the closure so that it can perform appropriate action.
///
/// Presumably the closure encapsulates a resource to perform I/O. The commands
/// correspond to methods of the [`Sink`] trait and provide the closure with
/// sufficient information to know what kind of action to perform with it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Action<A> {
/// Send the given value.
/// Corresponds to [`Sink::start_send`].
Send(A),
/// Flush the resource.
/// Corresponds to [`Sink::poll_flush`].
Flush,
/// Close the resource.
/// Corresponds to [`Sink::poll_close`].
Close
}
/// The various states the `Sink` may be in.
#[derive(Debug, PartialEq, Eq)]
enum State {
/// The `Sink` is idle.
Empty,
/// The `Sink` is sending a value.
Sending,
/// The `Sink` is flushing its resource.
Flushing,
/// The `Sink` is closing its resource.
Closing,
/// The `Sink` is closed (terminal state).
Closed,
/// The `Sink` experienced an error (terminal state).
Failed
}
pin_project!
{
/// `SinkImpl` implements the `Sink` trait.
#[derive(Debug)]
pub struct SinkImpl<S, F, T, A, E> {
lambda: F,
#[pin] future: Option<T>,
param: Option<S>,
state: State,
_mark: std::marker::PhantomData<(A, E)>
}
}
impl<S, F, T, A, E> Sink<A> for SinkImpl<S, F, T, A, E>
where
F: FnMut(S, Action<A>) -> T,
T: Future<Output = Result<S, E>>
{
type Error = E;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
let mut this = self.project();
match this.state {
State::Sending | State::Flushing => {
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(p) => {
this.future.set(None);
*this.param = Some(p);
*this.state = State::Empty;
Poll::Ready(Ok(()))
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
Poll::Ready(Err(e))
}
}
}
State::Closing => {
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(_) => {
this.future.set(None);
*this.state = State::Closed;
panic!("SinkImpl::poll_ready called on a closing sink.")
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
Poll::Ready(Err(e))
}
}
}
State::Empty => {
assert!(this.param.is_some());
Poll::Ready(Ok(()))
}
State::Closed => panic!("SinkImpl::poll_ready called on a closed sink."),
State::Failed => panic!("SinkImpl::poll_ready called after error.")
}
}
fn start_send(self: Pin<&mut Self>, item: A) -> Result<(), Self::Error> {
assert_eq!(State::Empty, self.state);
let mut this = self.project();
let param = this.param.take().unwrap();
let future = (this.lambda)(param, Action::Send(item));
this.future.set(Some(future));
*this.state = State::Sending;
Ok(())
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
loop {
let mut this = self.as_mut().project();
match this.state {
State::Empty =>
if let Some(p) = this.param.take() {
let future = (this.lambda)(p, Action::Flush);
this.future.set(Some(future));
*this.state = State::Flushing
} else {
return Poll::Ready(Ok(()))
}
State::Sending =>
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(p) => {
this.future.set(None);
*this.param = Some(p);
*this.state = State::Empty
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
return Poll::Ready(Err(e))
}
}
State::Flushing =>
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(p) => {
this.future.set(None);
*this.param = Some(p);
*this.state = State::Empty;
return Poll::Ready(Ok(()))
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
return Poll::Ready(Err(e))
}
}
State::Closing =>
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(_) => {
this.future.set(None);
*this.state = State::Closed;
return Poll::Ready(Ok(()))
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
return Poll::Ready(Err(e))
}
}
State::Closed => return Poll::Ready(Ok(())),
State::Failed => panic!("SinkImpl::poll_flush called after error.")
}
}
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
loop {
let mut this = self.as_mut().project();
match this.state {
State::Empty =>
if let Some(p) = this.param.take() {
let future = (this.lambda)(p, Action::Close);
this.future.set(Some(future));
*this.state = State::Closing;
} else {
return Poll::Ready(Ok(()))
}
State::Sending =>
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(p) => {
this.future.set(None);
*this.param = Some(p);
*this.state = State::Empty
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
return Poll::Ready(Err(e))
}
}
State::Flushing =>
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(p) => {
this.future.set(None);
*this.param = Some(p);
*this.state = State::Empty
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
return Poll::Ready(Err(e))
}
}
State::Closing =>
match ready!(this.future.as_mut().as_pin_mut().unwrap().poll(cx)) {
Ok(_) => {
this.future.set(None);
*this.state = State::Closed;
return Poll::Ready(Ok(()))
}
Err(e) => {
this.future.set(None);
*this.state = State::Failed;
return Poll::Ready(Err(e))
}
}
State::Closed => return Poll::Ready(Ok(())),
State::Failed => panic!("SinkImpl::poll_closed called after error.")
}
}
}
}
#[cfg(test)]
mod tests {
use async_std::{io, task};
use futures::{channel::mpsc, prelude::*, stream};
use crate::{Action, make_sink};
#[test]
fn smoke_test() {
task::block_on(async {
let sink = make_sink(io::stdout(), |mut stdout, action| async move {
match action {
Action::Send(x) => stdout.write_all(x).await?,
Action::Flush => stdout.flush().await?,
Action::Close => stdout.close().await?
}
Ok::<_, io::Error>(stdout)
});
let values = vec![Ok(&b"hello\n"[..]), Ok(&b"world\n"[..])];
assert!(stream::iter(values).forward(sink).await.is_ok())
})
}
#[test]
fn replay() {
task::block_on(async {
let (tx, rx) = mpsc::unbounded();
let sink = make_sink(tx, |mut tx, action| async move {
tx.send(action.clone()).await?;
if action == Action::Close {
tx.close().await?
}
Ok::<_, mpsc::SendError>(tx)
});
futures::pin_mut!(sink);
let expected = [
Action::Send("hello\n"),
Action::Flush,
Action::Send("world\n"),
Action::Flush,
Action::Close
];
for &item in &["hello\n", "world\n"] {
sink.send(item).await.unwrap()
}
sink.close().await.unwrap();
let actual = rx.collect::<Vec<_>>().await;
assert_eq!(&expected[..], &actual[..])
});
}
}