|
| 1 | +use futures::Stream; |
| 2 | +use pin_project::{pin_project, pinned_drop}; |
| 3 | +use std::fmt::Display; |
| 4 | +use std::pin::Pin; |
| 5 | +use std::task::{Context, Poll}; |
| 6 | + |
| 7 | +/// The reason why the stream ended: |
| 8 | +/// - [CallbackStreamEndReason::Finished] if it finished gracefully |
| 9 | +/// - [CallbackStreamEndReason::Aborted] if it was abandoned. |
| 10 | +#[derive(Debug)] |
| 11 | +pub enum CallbackStreamEndReason { |
| 12 | + /// The stream finished gracefully. |
| 13 | + Finished, |
| 14 | + /// The stream was abandoned. |
| 15 | + Aborted, |
| 16 | +} |
| 17 | + |
| 18 | +impl Display for CallbackStreamEndReason { |
| 19 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 20 | + write!(f, "{:?}", self) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +/// Stream that executes a callback when it is fully consumed or gets cancelled. |
| 25 | +#[pin_project(PinnedDrop)] |
| 26 | +pub struct CallbackStream<S, F> |
| 27 | +where |
| 28 | + S: Stream, |
| 29 | + F: FnOnce(CallbackStreamEndReason), |
| 30 | +{ |
| 31 | + #[pin] |
| 32 | + stream: S, |
| 33 | + callback: Option<F>, |
| 34 | +} |
| 35 | + |
| 36 | +impl<S, F> Stream for CallbackStream<S, F> |
| 37 | +where |
| 38 | + S: Stream, |
| 39 | + F: FnOnce(CallbackStreamEndReason), |
| 40 | +{ |
| 41 | + type Item = S::Item; |
| 42 | + |
| 43 | + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 44 | + let this = self.project(); |
| 45 | + |
| 46 | + match this.stream.poll_next(cx) { |
| 47 | + Poll::Ready(None) => { |
| 48 | + // Stream is fully consumed, execute the callback |
| 49 | + if let Some(callback) = this.callback.take() { |
| 50 | + callback(CallbackStreamEndReason::Finished); |
| 51 | + } |
| 52 | + Poll::Ready(None) |
| 53 | + } |
| 54 | + other => other, |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +#[pinned_drop] |
| 60 | +impl<S, F> PinnedDrop for CallbackStream<S, F> |
| 61 | +where |
| 62 | + S: Stream, |
| 63 | + F: FnOnce(CallbackStreamEndReason), |
| 64 | +{ |
| 65 | + fn drop(self: Pin<&mut Self>) { |
| 66 | + let this = self.project(); |
| 67 | + if let Some(callback) = this.callback.take() { |
| 68 | + callback(CallbackStreamEndReason::Aborted); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +/// Wrap a stream with a callback that will be executed when the stream is fully |
| 74 | +/// consumed or gets canceled. |
| 75 | +pub fn with_callback<S, F>(stream: S, callback: F) -> CallbackStream<S, F> |
| 76 | +where |
| 77 | + S: Stream, |
| 78 | + F: FnOnce(CallbackStreamEndReason) + Send + 'static, |
| 79 | +{ |
| 80 | + CallbackStream { |
| 81 | + stream, |
| 82 | + callback: Some(callback), |
| 83 | + } |
| 84 | +} |
0 commit comments