pipe_chain/pipe/boxed.rs
1use crate::{Pipe, Result};
2
3/// Wrap a [Pipe] into a [Box]
4pub trait BoxedExt<I, O, E, R = I> {
5 /// Wraps the current [`Pipe`] into a [`Box`]
6 ///
7 /// example:
8 /// ```
9 /// # use pipe_chain::{Pipe, BoxedPipe, BoxedExt, AndExt, tag, str::TagStrError, Incomplete};
10 /// # use fatal_error::FatalError;
11 /// # use std::error::Error as StdError;
12 /// # #[derive(Debug, PartialEq, Eq)]
13 /// # enum Error {
14 /// # Incomplete(Incomplete),
15 /// # Tag(TagStrError),
16 /// # }
17 /// #
18 /// # impl std::fmt::Display for Error {
19 /// # fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 /// # write!(f, "{self:?}")
21 /// # }
22 /// # }
23 /// # impl StdError for Error {}
24 /// #
25 /// # impl From<Incomplete> for Error {
26 /// # fn from(value: Incomplete) -> Error { Error::Incomplete(value) }
27 /// # }
28 /// #
29 /// # impl From<TagStrError> for Error {
30 /// # fn from(value: TagStrError) -> Error { Error::Tag(value) }
31 /// # }
32 /// fn mk_pipe<'a>() -> BoxedPipe<'a, &'a str, (&'a str, &'a str), Error> {
33 /// tag::<Error, _, _>("1").and(tag("2")).boxed()
34 /// }
35 ///
36 /// fn mk_pipe2<'a>() -> BoxedPipe<'a, &'a str, (&'a str, &'a str), Error> {
37 /// tag::<Error, _, _>("1").and(tag("2")).and_self(tag("3")).boxed()
38 /// }
39 ///
40 /// let mut v = vec![mk_pipe(), mk_pipe2()];
41 ///
42 /// assert_eq!(v[0].apply("123"), Ok(("3", ("1", "2"))));
43 /// assert_eq!(v[1].apply("123"), Ok(("", ("1", "2"))));
44 /// ```
45 fn boxed<'a>(self) -> BoxedPipe<'a, I, O, E, R>
46 where
47 Self: Pipe<I, O, E, R> + Sized + 'a,
48 {
49 BoxedPipe::new(self)
50 }
51}
52
53impl<I, O, E, R, P> BoxedExt<I, O, E, R> for P where P: Pipe<I, O, E, R> {}
54
55/// [BoxedExt::boxed] implementation
56pub struct BoxedPipe<'a, I, O, E, R = I>(Box<dyn Pipe<I, O, E, R> + 'a>);
57
58impl<'a, I, O, E, R> BoxedPipe<'a, I, O, E, R> {
59 fn new<P>(p: P) -> Self
60 where
61 P: Pipe<I, O, E, R> + Sized + 'a,
62 {
63 Self(Box::new(p))
64 }
65}
66
67impl<'a, I, O, E, R> Pipe<I, O, E, R> for BoxedPipe<'a, I, O, E, R> {
68 fn apply(&mut self, input: I) -> Result<R, O, E> { self.0.apply(input) }
69}