Skip to main content

multipart_write/write/
extend.rs

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