minicbor-adapters 0.0.8

Adapters between `minicbor` and other crates such as `heapless` and `cboritem`
Documentation
//! Implementations of minicbor writing into heapless types

use heapless::{LenType, vec::VecInner, vec::VecStorage};

/// Wrapper around a [`heapless::Vec`] that can be written to by [minicbor].
///
/// The wrapper can generally be short-lived; it updates the vector's length as it goes. The vector
/// consequently contains incomplete data if encoding errs out prematurely.
///
/// # Usage example
///
/// ```
/// use minicbor_adapters::WriteToHeapless;
/// let mut buf = heapless::Vec::<u8, 32>::new();
/// minicbor::encode([1, 2, 3], WriteToHeapless(&mut buf)).unwrap();
/// assert_eq!(&[0x83, 1, 2, 3], &buf);
/// ```
#[derive(Debug)]
pub struct WriteToHeapless<'a, LenT: LenType, S: VecStorage<u8> + ?Sized>(
    pub &'a mut VecInner<u8, LenT, S>,
);

impl<LenT: LenType, S: VecStorage<u8> + ?Sized> minicbor::encode::Write
    for WriteToHeapless<'_, LenT, S>
{
    type Error = heapless::CapacityError;

    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        self.0.extend_from_slice(buf)
    }
}

#[cfg(test)]
#[test]
fn test_write_vecview() {
    let mut buf = heapless::Vec::<u8, 32>::new();
    let buf = buf.as_mut_view();
    minicbor::encode([1, 2, 3], WriteToHeapless(buf)).unwrap();
    assert_eq!(&[0x83, 1, 2, 3], buf.as_slice());
}

// The successful case is covered by the doctest
#[cfg(test)]
#[test]
fn test_write_error() {
    extern crate std;
    use std::format;

    let mut buf = heapless::Vec::<u8, 3>::new();
    let err = minicbor::encode([1, 2, 3], WriteToHeapless(&mut buf)).unwrap_err();
    // Precise message may change, but this checks that it makes sense.
    assert_eq!(format!("{err}"), "write error: insufficient capacity");
}