#traits #no-alloc #encode #encoding #assist #endian

no-std codec

Codec trait to assist in making codecs

6 releases

new 0.0.6 Jan 25, 2025
0.0.5 Jan 12, 2025
0.0.3 Dec 27, 2024

#64 in Multimedia

Download history 2/week @ 2024-10-02 10/week @ 2024-10-09 4/week @ 2024-10-16 15/week @ 2024-10-30 13/week @ 2024-11-06 6/week @ 2024-11-13 12/week @ 2024-11-20 6/week @ 2024-11-27 340/week @ 2024-12-25 19/week @ 2025-01-01 307/week @ 2025-01-08 23/week @ 2025-01-15

689 downloads per month

MIT license

30KB
620 lines

Codec

This crate contains the codec trait, and helper implementations which make it easier to create a codec.

Example of creating a codec for a simple example protocol:

use codec::*;
use heapless::String;
enum TestProtocol {
    String(String<30>),
    Float(f64),
    Int(i64),
}
impl Codec<()> for TestProtocol {
    fn encode(self, buf: &mut impl EncodeBuffer, _ctx: ()) -> Result<(), EncodeError> {
        match self {
            TestProtocol::String(str) => {
                1u8.encode(buf, ())?;
                str.encode(buf, StringContext::U8Len)
            }
            TestProtocol::Float(f64) => {
                2u8.encode(buf, ())?;
                f64.encode(buf, Endian::Little)
            }
            TestProtocol::Int(i64) => {
                3u8.encode(buf, ())?;
                i64.encode(buf, Endian::Little)
            }
        }
    }
    fn decode(buf: &mut impl DecodeBuffer, _ctx: ()) -> Result<Self, DecodeError> {
        let id = u8::decode(buf, ())?;
        match id {
            1 => {
                let str = String::<30>::decode(buf, StringContext::U8Len)?;
                Ok(TestProtocol::String(str))
            },
            2 => {
                let f64 = f64::decode(buf, Endian::Little)?;
                Ok(TestProtocol::Float(f64))
            },
            3 => {
                let i64 = i64::decode(buf, Endian::Little)?;
                Ok(TestProtocol::Int(i64))
            },
            _ => Err(DecodeError::Invalid),
        }
    }
}

let mut slice = [0;12];
let mut buf = StaticBuffer::new(&mut slice);

let mut test_string = String::<30>::new();
test_string.push_str("TestString");

let test = TestProtocol::String(test_string);
test.encode(&mut buf, ());

// Buffer should now contain 1u8 for the id, 10u8 for the string length
// and the string itself.
assert_eq!(slice, *b"\x01\x0ATestString");

As you can see, we are able to easily create a codec for this protocol with a minimal amount of code on our end.

Dependencies

~475KB