pipe_chain/pipe/
unpack.rs

1use crate::{Pipe, Result};
2use std::marker::PhantomData;
3use tuplify::Unpack;
4
5/// Combinator that calls [tuplify::Unpack::unpack] on it's output
6pub trait UnpackExt<I, O, E, R> {
7    /// Unpacks the output of a pipe
8    ///
9    /// Example:
10    /// ```rust
11    /// # use fatal_error::FatalError;
12    /// # use pipe_chain::{Pipe, AndExt, UnpackExt, tag, Incomplete, str::TagStrError};
13    /// # use std::error::Error as StdError;
14    /// # #[derive(Debug, PartialEq, Eq)]
15    /// # enum Error {
16    /// #     Incomplete(Incomplete),
17    /// #     Tag(TagStrError),
18    /// # }
19    /// #
20    /// # impl std::fmt::Display for Error {
21    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22    /// #        write!(f, "{self:?}")
23    /// #     }
24    /// # }
25    /// # impl StdError for Error {}
26    /// # impl From<Incomplete> for Error {
27    /// #     fn from(value: Incomplete) -> Error { Error::Incomplete(value) }
28    /// # }
29    /// #
30    /// # impl From<TagStrError> for Error {
31    /// #     fn from(value: TagStrError) -> Error { Error::Tag(value) }
32    /// # }
33    /// // unpacking many elements does nothing
34    /// assert_eq!(
35    ///     tag::<Error, _, _>("foo").and(tag("bar")).unpack().apply("foobar"),
36    ///     Ok(("", ("foo", "bar")))
37    /// );
38    ///
39    /// // single element without unpacking
40    /// assert_eq!(tag::<Error, _, _>("foo").apply("foo"), Ok(("", ("foo",))));
41    ///
42    /// // single element with unpacking
43    /// assert_eq!(tag::<Error, _, _>("foo").unpack().apply("foo"), Ok(("", "foo")));
44    /// ```
45    fn unpack(self) -> UnpackPipe<Self, O>
46    where
47        O: Unpack,
48        Self: Sized,
49    {
50        UnpackPipe::new(self)
51    }
52}
53
54impl<I, O, E, R, P> UnpackExt<I, O, E, R> for P where P: Pipe<I, O, E, R> {}
55
56/// [UnpackExt::unpack] implementation
57pub struct UnpackPipe<P, O> {
58    p: P,
59    o: PhantomData<O>,
60}
61
62impl<P, O> UnpackPipe<P, O> {
63    fn new(p: P) -> Self { Self { p, o: PhantomData } }
64}
65
66impl<I, O, E, R, P> Pipe<I, O::Output, E, R> for UnpackPipe<P, O>
67where
68    O: Unpack,
69    P: Pipe<I, O, E, R>,
70{
71    fn apply(&mut self, input: I) -> Result<R, O::Output, E> {
72        self.p.apply(input).map(|(i, o)| (i, o.unpack()))
73    }
74}