Crate codec

Source
Expand description

Example of creating a codec for a simple example protocol

use codec::codec::*;
use codec::impls::*;
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.

Structs§

Enums§

Traits§