encode/combinators/
cond.rs

1use core::borrow::Borrow;
2use core::ops::Deref;
3
4///  Encodes a value only if a condition is met
5///
6/// # Examples
7///
8/// ```rust
9/// # #[cfg(feature = "alloc")] {
10/// use encode::Encodable;
11/// use encode::combinators::Cond;
12/// use std::ffi::CStr;
13///
14/// let non_empty = |s:&&CStr| !s.is_empty();
15///
16/// let mut buf = Vec::new();
17/// Cond::new(c"hello", non_empty).encode(&mut buf).unwrap();
18/// assert_eq!(&buf, b"hello\0", "A non-empty CStr includes the null terminator");
19///
20/// buf.clear();
21///
22/// Cond::new(c"", non_empty).encode(&mut buf).unwrap();
23/// assert_eq!(&buf, b"", "An empty CStr does not produce any output");
24/// # }
25/// ```
26#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
27pub struct Cond<E, F> {
28    encodable: E,
29    condition: F,
30}
31
32impl<E, F> Cond<E, F> {
33    /// Creates a new [`Cond`] combinator.
34    #[inline]
35    #[must_use]
36    pub const fn new(encodable: E, condition: F) -> Self
37    where
38        F: Fn(&E) -> bool,
39    {
40        Self {
41            encodable,
42            condition,
43        }
44    }
45    /// Consumes the [`Cond`] combinator and returns the inner value.
46    #[inline]
47    #[must_use]
48    pub fn into_inner(self) -> (E, F) {
49        (self.encodable, self.condition)
50    }
51}
52
53impl<E, F> AsRef<E> for Cond<E, F> {
54    #[inline]
55    fn as_ref(&self) -> &E {
56        &self.encodable
57    }
58}
59impl<E, F> Borrow<E> for Cond<E, F> {
60    #[inline]
61    fn borrow(&self) -> &E {
62        &self.encodable
63    }
64}
65impl<E, F> Deref for Cond<E, F> {
66    type Target = E;
67    #[inline]
68    fn deref(&self) -> &Self::Target {
69        self.as_ref()
70    }
71}
72
73impl<Encodable, Encoder, F> crate::Encodable<Encoder> for Cond<Encodable, F>
74where
75    Encodable: crate::Encodable<Encoder>,
76    Encoder: crate::BaseEncoder,
77    F: Fn(&Encodable) -> bool,
78{
79    type Error = Encodable::Error;
80
81    #[inline]
82    fn encode(&self, encoder: &mut Encoder) -> Result<(), Self::Error> {
83        if (self.condition)(&self.encodable) {
84            self.encodable.encode(encoder)
85        } else {
86            Ok(())
87        }
88    }
89}