minicbor_adapters/
embedded_io.rs

1/// Wrapper around an [`embedded_io::Write`] implementation that can be written to by [minicbor].
2///
3/// # Usage example
4///
5/// ```
6/// use minicbor_adapters::WriteToEmbeddedIo;
7///
8/// fn serialize(data: &[u8], into: impl embedded_io::Write) {
9///     minicbor::encode(data, WriteToEmbeddedIo(into)).unwrap();
10/// }
11/// ```
12#[derive(Debug)]
13pub struct WriteToEmbeddedIo<W: embedded_io::Write>(pub W);
14
15impl<W: embedded_io::Write> minicbor::encode::Write for WriteToEmbeddedIo<W> {
16    type Error = W::Error;
17
18    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
19        self.0.write_all(buf)
20    }
21}
22
23// This'd make a bad doctest, because most lines are really about using the only easily provided
24// impl of the trait.
25#[test]
26fn test_write() {
27    const BUF_LEN: usize = 10;
28    let mut buf = [0xff; BUF_LEN];
29    let mut remaining_buf = &mut buf[..];
30    minicbor::encode([1, 2, 3], WriteToEmbeddedIo(&mut remaining_buf)).unwrap();
31    let written = BUF_LEN - remaining_buf.len();
32    assert_eq!(&[0x83, 1, 2, 3], &buf[..written]);
33}