1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//! 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.
extern crate std;
pub use *;
pub use *;
pub use *;