encode/combinators/
cond.rs1use core::borrow::Borrow;
2use core::ops::Deref;
3
4#[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 #[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 #[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}