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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//! Core traits implemented by every encodable value.
//!
//! [`Encode`] writes a value into a [`WriteBuf`]; [`Decode`] reads one out of a
//! [`ReadBuf`]. The traits are deliberately minimal so callers can compose them
//! with any framing strategy in the [`framing`][`crate::framing`] module.
use crate;
use crateResult;
/// A value that can be written to a [`WriteBuf`].
///
/// Implementors must guarantee that [`Encode::encoded_size`] returns the exact
/// number of bytes [`Encode::encode`] writes on success.
///
/// # Example
///
/// ```
/// use wire_codec::{Encode, Result, WriteBuf};
///
/// struct Tagged {
/// tag: u8,
/// value: u32,
/// }
///
/// impl Encode for Tagged {
/// fn encoded_size(&self) -> usize { 5 }
/// fn encode(&self, buf: &mut WriteBuf<'_>) -> Result<()> {
/// buf.write_u8(self.tag)?;
/// buf.write_u32_be(self.value)
/// }
/// }
///
/// let mut out = [0u8; 5];
/// let mut buf = WriteBuf::new(&mut out);
/// Tagged { tag: 0x01, value: 0xCAFEBABE }.encode(&mut buf).unwrap();
/// assert_eq!(&out, &[0x01, 0xCA, 0xFE, 0xBA, 0xBE]);
/// ```
/// A value that can be read from a [`ReadBuf`].
///
/// The lifetime parameter `'de` ties the decoded value to the borrowed input,
/// enabling zero-copy decoding of borrowed payloads (`&'de [u8]`, `&'de str`).
///
/// # Example
///
/// ```
/// use wire_codec::{Decode, ReadBuf, Result};
///
/// struct Tagged {
/// tag: u8,
/// value: u32,
/// }
///
/// impl<'de> Decode<'de> for Tagged {
/// fn decode(buf: &mut ReadBuf<'de>) -> Result<Self> {
/// let tag = buf.read_u8()?;
/// let value = buf.read_u32_be()?;
/// Ok(Self { tag, value })
/// }
/// }
///
/// let mut buf = ReadBuf::new(&[0x01, 0xCA, 0xFE, 0xBA, 0xBE]);
/// let tagged = Tagged::decode(&mut buf).unwrap();
/// assert_eq!(tagged.tag, 0x01);
/// assert_eq!(tagged.value, 0xCAFEBABE);
/// ```