Thanks to visit codestin.com
Credit goes to lib.rs

#no-alloc #encoding

no-std codec

Codec trait to assist in making codecs

7 releases

Uses new Rust 2024

0.0.7 Oct 4, 2025
0.0.6 Jan 25, 2025
0.0.3 Dec 27, 2024

#17 in Multimedia

Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App Codestin Search App

329 downloads per month

MIT license

40KB
880 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

~665KB
~13K SLoC