pipe_chain/pipe/
peek.rs

1use crate::{Pipe, Result};
2use std::marker::PhantomData;
3
4/// Applies a [Pipe] without consuming the input
5pub trait PeekExt<I, O, E, R> {
6    /// Makes a [Pipe] optional if it returns a non fatal error
7    ///
8    /// example:
9    ///  ```
10    /// # use fatal_error::FatalError;
11    /// # use pipe_chain::{Pipe, PeekExt, tag, str::TagStrError, Incomplete};
12    /// # use std::error::Error as StdError;
13    /// # #[derive(Debug, PartialEq, Eq)]
14    /// # enum Error {
15    /// #     Incomplete(Incomplete),
16    /// #     Tag(TagStrError),
17    /// # }
18    /// #
19    /// # impl std::fmt::Display for Error {
20    /// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21    /// #        write!(f, "{self:?}")
22    /// #     }
23    /// # }
24    /// # impl StdError for Error {}
25    /// #
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    /// assert_eq!(
34    ///     tag::<Error, _, _>("foo").peek().apply("foobar"),
35    ///     Ok(("foobar", ("foo",)))
36    /// );
37    ///
38    /// assert_eq!(
39    ///     tag::<Error, _, _>("boo").peek().apply("foobar"),
40    ///     Err(FatalError::Error(Error::Tag(TagStrError("boo".into(), "foo".into()))))
41    /// );
42    /// ```
43    fn peek(self) -> Peek<Self, R>
44    where
45        Self: Sized,
46        I: Clone,
47    {
48        Peek::new(self)
49    }
50}
51
52impl<I: Clone, O, E, R, P: Pipe<I, O, E, R>> PeekExt<I, O, E, R> for P {}
53
54/// [PeekExt::peek] implementation
55pub struct Peek<P, R>(P, PhantomData<R>);
56
57impl<P, R> Peek<P, R> {
58    fn new(p: P) -> Self { Peek(p, PhantomData) }
59}
60
61impl<I, O, E, R, P> Pipe<I, O, E> for Peek<P, R>
62where
63    I: Clone,
64    P: Pipe<I, O, E, R>,
65{
66    fn apply(&mut self, input: I) -> Result<I, O, E> {
67        self.0.apply(input.clone()).map(|(_, x)| (input, x))
68    }
69}