encode 2.0.0

A simple framework for encoding binary data.
Documentation
use core::borrow::Borrow;

///  Encodes a value only if a condition is met
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "alloc")] {
/// use encode::Encodable;
/// use encode::combinators::Cond;
/// use std::ffi::CStr;
///
/// let non_empty = |s:&&CStr| !s.is_empty();
///
/// let mut buf = Vec::new();
/// Cond::new(c"hello", non_empty).encode(&mut buf).unwrap();
/// assert_eq!(&buf, b"hello\0", "A non-empty CStr includes the null terminator");
///
/// buf.clear();
///
/// Cond::new(c"", non_empty).encode(&mut buf).unwrap();
/// assert_eq!(&buf, b"", "An empty CStr does not produce any output");
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Cond<E, F> {
    encodable: E,
    condition: F,
}

impl<E, F> Cond<E, F> {
    /// Creates a new [`Cond`] combinator.
    #[inline]
    #[must_use]
    pub const fn new(encodable: E, condition: F) -> Self
    where
        F: Fn(&E) -> bool,
    {
        Self {
            encodable,
            condition,
        }
    }
    /// Consumes the [`Cond`] combinator and returns the inner value.
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> (E, F) {
        (self.encodable, self.condition)
    }
}

impl<E, F> AsRef<E> for Cond<E, F> {
    #[inline]
    fn as_ref(&self) -> &E {
        &self.encodable
    }
}
impl<E, F> Borrow<E> for Cond<E, F> {
    #[inline]
    fn borrow(&self) -> &E {
        &self.encodable
    }
}

impl<Encodable, Encoder, F> crate::Encodable<Encoder> for Cond<Encodable, F>
where
    Encodable: crate::Encodable<Encoder>,
    Encoder: crate::BaseEncoder,
    F: Fn(&Encodable) -> bool,
{
    type Error = Encodable::Error;

    #[inline]
    fn encode(&self, encoder: &mut Encoder) -> Result<(), Self::Error> {
        if (self.condition)(&self.encodable) {
            self.encodable.encode(encoder)
        } else {
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use core::borrow::Borrow;

    use rstest::rstest;

    use super::*;
    use crate::Encodable;

    const BUF_SIZE: usize = 32;

    #[rstest]
    #[case::condition_met(true, &[1u8])]
    #[case::condition_not_met(false, &[])]
    fn assert_that_cond_encoding_respects_condition(
        #[case] condition: bool,
        #[case] expected: &[u8],
    ) {
        let cond = Cond::new(1u8, move |_: &u8| condition);
        let mut buf = [0u8; BUF_SIZE];
        let mut encoder = &mut buf as &mut [u8];
        cond.encode(&mut encoder).unwrap();
        let written = BUF_SIZE - encoder.len();
        assert_eq!(&buf[..written], expected);
    }

    #[test]
    fn assert_that_cond_into_inner_returns_value_and_condition() {
        let cond = Cond::new(42u8, |_: &u8| true);
        let (val, _) = cond.into_inner();
        assert_eq!(val, 42u8);
    }

    #[test]
    fn assert_that_cond_as_ref_works() {
        let cond = Cond::new(42u8, |_: &u8| true);
        assert_eq!(cond.as_ref(), &42u8);
    }

    #[test]
    fn assert_that_cond_borrow_works() {
        let cond = Cond::new(42u8, |_: &u8| true);
        let borrowed: &u8 = cond.borrow();
        assert_eq!(*borrowed, 42u8);
    }
}