codec/lib.rs
1#![no_std]
2
3//! Example of creating a codec for a simple example protocol
4//!
5//! ```
6//! use codec::*;
7//! use heapless::String;
8//!
9//! enum TestProtocol {
10//! String(String<30>),
11//! Float(f64),
12//! Int(i64),
13//! }
14//!
15//! impl Codec<()> for TestProtocol {
16//! fn encode(self, buf: &mut impl EncodeBuffer, _ctx: ()) -> Result<(), EncodeError> {
17//! match self {
18//! TestProtocol::String(str) => {
19//! 1u8.encode(buf, ())?;
20//! str.encode(buf, StringContext::U8Len)
21//! }
22//! TestProtocol::Float(f64) => {
23//! 2u8.encode(buf, ())?;
24//! f64.encode(buf, Endian::Little)
25//! }
26//! TestProtocol::Int(i64) => {
27//! 3u8.encode(buf, ())?;
28//! i64.encode(buf, Endian::Little)
29//! }
30//! }
31//! }
32//! fn decode(buf: &mut impl DecodeBuffer, _ctx: ()) -> Result<Self, DecodeError> {
33//! let id = u8::decode(buf, ())?;
34//! match id {
35//! 1 => {
36//! let str = String::<30>::decode(buf, StringContext::U8Len)?;
37//! Ok(TestProtocol::String(str))
38//! },
39//! 2 => {
40//! let f64 = f64::decode(buf, Endian::Little)?;
41//! Ok(TestProtocol::Float(f64))
42//! },
43//! 3 => {
44//! let i64 = i64::decode(buf, Endian::Little)?;
45//! Ok(TestProtocol::Int(i64))
46//! },
47//! _ => Err(DecodeError::Invalid),
48//! }
49//! }
50//! }
51//!
52//! let mut slice = [0;12];
53//! let mut buf = StaticBuffer::new(&mut slice);
54//!
55//! let mut test_string = String::<30>::new();
56//! test_string.push_str("TestString");
57//!
58//! let test = TestProtocol::String(test_string);
59//! test.encode(&mut buf, ());
60//!
61//! // Buffer should now contain 1u8 for the id, 10u8 for the string length
62//! // and the string itself.
63//! assert_eq!(slice, *b"\x01\x0ATestString");
64//! ```
65//!
66//! As you can see, we are able to easily create a codec for this protocol
67//! with a minimal amount of code on our end.
68
69#[cfg(feature="std")]
70extern crate std;
71
72#[cfg(feature="std")]
73mod std_impls;
74
75mod codec;
76mod impls;
77mod buffers;
78
79pub use codec::*;
80pub use impls::*;
81pub use buffers::*;
82