rust / expert
Snippet
Constructing an Async Stream Iterator via Direct Poll Methods
This snippet creates a custom asynchronous stream-like trait called AsyncProducer that yields items or errors. It demonstrates how to wrap a producer inside an error-recovery decorator that catches failures during polling and fallbacks to a default recovery message before terminating.
snippet.rs
rust
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
use std::pin::Pin;use std::task::{Context, Poll};pub trait AsyncProducer {type Item;type Error;fn poll_next(self: Pin<&mut Self>,cx: &mut Context<'_>,) -> Poll<Option<Result<Self::Item, Self::Error>>>;}pub struct FallbackProducer<P> {primary: P,fallback_active: bool,}impl<P> FallbackProducer<P> {pub fn new(primary: P) -> Self {Self {primary,fallback_active: false,}}}impl<P> AsyncProducer for FallbackProducer<P>whereP: AsyncProducer<Item = String> + Unpin,{type Item = String;type Error = P::Error;fn poll_next(mut self: Pin<&mut Self>,cx: &mut Context<'_>,) -> Poll<Option<Result<Self::Item, Self::Error>>>{if self.fallback_active {return Poll::Ready(None);}match Pin::new(&mut self.primary).poll_next(cx) {Poll::Ready(Some(Err(_))) => {self.fallback_active = true;Poll::Ready(Some(Ok(String::from("Recovered"))))}other => other,}}}
Breakdown
1
pub trait AsyncProducer
Declares a custom async trait utilizing pin-projected self references for safe asynchronous polling.
2
type Item; type Error;
Defines associated types for the emitted successful values and error types.
3
match Pin::new(&mut self.primary).poll_next(cx)
Polls the underlying primary producer using a pinned mutable reference.
4
Poll::Ready(Some(Ok(String::from("Recovered"))))
Intercepts errors to return a fallback value, transitioning the state machine to inactive.