codec

Crates.iocodec
lib.rscodec
version0.0.7
created_at2024-12-26 21:34:37.864911+00
updated_at2025-10-04 03:18:12.870566+00
descriptionCodec trait to assist in making codecs
homepage
repositoryhttps://gitlab.com/donuts799/rust-utils/-/tree/main/codec?ref_type=heads
max_upload_size
id1495990
size40,748
Brendan Smith (smithb21)

documentation

README

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.

Commit count: 13

cargo fmt