Skip to main content

multipart_write/write/
from_extend.rs

1use std::fmt::{self, Debug, Formatter};
2use std::io::Error as IoError;
3use std::iter::Extend;
4use std::marker::PhantomData;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7
8use crate::{FusedMultipartWrite, MultipartWrite};
9
10/// Function that constructs a `MultipartWrite` from any value that has a
11/// default and implements [`std::iter::Extend`].
12pub fn from_extend<A, T: Default + Extend<A>>() -> FromExtend<A, T> {
13    FromExtend::new(Default::default())
14}
15
16pin_project_lite::pin_project! {
17    /// `MultipartWrite` for the [`from_extend`] function.
18    #[must_use = "futures do nothing unless polled"]
19    pub struct FromExtend<A, T> {
20        inner: Option<T>,
21        _a: PhantomData<A>,
22    }
23}
24
25impl<A, T: Default + Extend<A>> FromExtend<A, T> {
26    fn new(inner: T) -> Self {
27        FromExtend { inner: Some(inner), _a: PhantomData }
28    }
29}
30
31impl<A, T> FusedMultipartWrite<A> for FromExtend<A, T>
32where
33    T: Default + Extend<A>,
34{
35    fn is_terminated(&self) -> bool {
36        false
37    }
38}
39
40impl<A, T> MultipartWrite<A> for FromExtend<A, T>
41where
42    T: Default + Extend<A>,
43{
44    type Error = IoError;
45    type Output = T;
46    type Recv = ();
47
48    fn poll_ready(
49        self: Pin<&mut Self>,
50        _cx: &mut Context<'_>,
51    ) -> Poll<Result<(), Self::Error>> {
52        Poll::Ready(Ok(()))
53    }
54
55    fn start_send(
56        mut self: Pin<&mut Self>,
57        part: A,
58    ) -> Result<Self::Recv, Self::Error> {
59        match self.inner.as_mut() {
60            Some(vs) => vs.extend([part]),
61            _ => {
62                let mut vs = T::default();
63                vs.extend([part]);
64                self.inner = Some(vs);
65            },
66        }
67        Ok(())
68    }
69
70    fn poll_flush(
71        self: Pin<&mut Self>,
72        _cx: &mut Context<'_>,
73    ) -> Poll<Result<(), Self::Error>> {
74        Poll::Ready(Ok(()))
75    }
76
77    fn poll_complete(
78        mut self: Pin<&mut Self>,
79        _cx: &mut Context<'_>,
80    ) -> Poll<Result<Self::Output, Self::Error>> {
81        Poll::Ready(Ok(self.inner.take().unwrap_or_default()))
82    }
83}
84
85impl<A, T> Debug for FromExtend<A, T>
86where
87    T: Debug,
88{
89    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
90        f.debug_struct("FromExtend").field("inner", &self.inner).finish()
91    }
92}