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 creates a `MultipartWrite` from a type that implements
11/// `std::iter::Extend<A> + Default` for some `A`.
12///
13/// `A` becomes the part type in the multipart writer.  This writer is always
14/// ready to receive a value.
15pub fn from_extend<A, T: Unpin + Default + Extend<A>>() -> FromExtend<A, T> {
16    FromExtend::new(Default::default())
17}
18
19/// `MultipartWrite` for [`from_extend`].
20pub struct FromExtend<A, T> {
21    inner: Option<T>,
22    _a: PhantomData<A>,
23}
24
25impl<A, T: Unpin + 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: Unpin + Default + Extend<A>> Unpin for FromExtend<A, T> {}
32
33impl<A, T> FusedMultipartWrite<A> for FromExtend<A, T>
34where
35    T: Unpin + Default + Extend<A>,
36{
37    fn is_terminated(&self) -> bool {
38        false
39    }
40}
41
42impl<A, T> MultipartWrite<A> for FromExtend<A, T>
43where
44    T: Unpin + Default + Extend<A>,
45{
46    type Error = IoError;
47    type Output = T;
48    type Recv = ();
49
50    fn poll_ready(
51        self: Pin<&mut Self>,
52        _cx: &mut Context<'_>,
53    ) -> Poll<Result<(), Self::Error>> {
54        Poll::Ready(Ok(()))
55    }
56
57    fn start_send(
58        mut self: Pin<&mut Self>,
59        part: A,
60    ) -> Result<Self::Recv, Self::Error> {
61        match self.inner.as_mut() {
62            Some(vs) => vs.extend([part]),
63            _ => {
64                let mut vs = T::default();
65                vs.extend([part]);
66                self.inner = Some(vs);
67            },
68        }
69        Ok(())
70    }
71
72    fn poll_flush(
73        self: Pin<&mut Self>,
74        _cx: &mut Context<'_>,
75    ) -> Poll<Result<(), Self::Error>> {
76        Poll::Ready(Ok(()))
77    }
78
79    fn poll_complete(
80        mut self: Pin<&mut Self>,
81        _cx: &mut Context<'_>,
82    ) -> Poll<Result<Self::Output, Self::Error>> {
83        Poll::Ready(Ok(self.inner.take().unwrap_or_default()))
84    }
85}
86
87impl<A, T> Debug for FromExtend<A, T>
88where
89    T: Debug,
90{
91    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
92        f.debug_struct("FromExtend").field("inner", &self.inner).finish()
93    }
94}