minicbor_adapters/heapless/
writers.rs

1//! Implementations of minicbor writing into heapless types
2
3use heapless::{LenType, vec::VecInner, vec::VecStorage};
4
5/// Wrapper around a [`heapless::Vec`] that can be written to by [minicbor].
6///
7/// The wrapper can generally be short-lived; it updates the vector's length as it goes. The vector
8/// consequently contains incomplete data if encoding errs out prematurely.
9///
10/// # Usage example
11///
12/// ```
13/// use minicbor_adapters::WriteToHeapless;
14/// let mut buf = heapless::Vec::<u8, 32>::new();
15/// minicbor::encode([1, 2, 3], WriteToHeapless(&mut buf)).unwrap();
16/// assert_eq!(&[0x83, 1, 2, 3], &buf);
17/// ```
18#[derive(Debug)]
19pub struct WriteToHeapless<'a, LenT: LenType, S: VecStorage<u8> + ?Sized>(
20    pub &'a mut VecInner<u8, LenT, S>,
21);
22
23impl<LenT: LenType, S: VecStorage<u8> + ?Sized> minicbor::encode::Write
24    for WriteToHeapless<'_, LenT, S>
25{
26    type Error = heapless::CapacityError;
27
28    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
29        self.0.extend_from_slice(buf)
30    }
31}
32
33#[cfg(test)]
34#[test]
35fn test_write_vecview() {
36    let mut buf = heapless::Vec::<u8, 32>::new();
37    let buf = buf.as_mut_view();
38    minicbor::encode([1, 2, 3], WriteToHeapless(buf)).unwrap();
39    assert_eq!(&[0x83, 1, 2, 3], buf.as_slice());
40}
41
42// The successful case is covered by the doctest
43#[cfg(test)]
44#[test]
45fn test_write_error() {
46    extern crate std;
47    use std::format;
48
49    let mut buf = heapless::Vec::<u8, 3>::new();
50    let err = minicbor::encode([1, 2, 3], WriteToHeapless(&mut buf)).unwrap_err();
51    // Precise message may change, but this checks that it makes sense.
52    assert_eq!(format!("{err}"), "write error: insufficient capacity");
53}