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
use internal_prelude::v1::*;
pub trait PackedStruct<B> where Self: Sized {
fn pack(&self) -> B;
fn unpack(src: &B) -> Result<Self, PackingError>;
}
pub trait PackedStructInfo {
fn packed_bits() -> usize;
}
pub trait PackedStructSlice where Self: Sized {
fn pack_to_slice(&self, output: &mut [u8]) -> Result<(), PackingError>;
fn unpack_from_slice(src: &[u8]) -> Result<Self, PackingError>;
fn packed_bytes() -> usize;
#[cfg(any(feature="alloc", feature="std"))]
fn pack_to_vec(&self) -> Result<Vec<u8>, PackingError> {
let mut buf = vec![0; Self::packed_bytes()];
self.pack_to_slice(&mut buf)?;
Ok(buf)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Serialize)]
pub enum PackingError {
InvalidValue,
BitsError,
BufferTooSmall,
NotImplemented,
BufferSizeMismatch { expected: usize, actual: usize }
}
impl Display for PackingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
#[cfg(feature="std")]
impl ::std::error::Error for PackingError {
fn description(&self) -> &str {
match *self {
PackingError::InvalidValue => "Invalid value",
PackingError::BitsError => "Bits error",
PackingError::BufferTooSmall => "Buffer too small",
PackingError::BufferSizeMismatch { .. } => "Buffer size mismatched",
PackingError::NotImplemented => "Not implemented"
}
}
}
macro_rules! packing_slice {
($T: path; $num_bytes: expr) => (
impl PackedStructSlice for $T {
#[inline]
fn pack_to_slice(&self, output: &mut [u8]) -> Result<(), PackingError> {
if output.len() != $num_bytes {
return Err(PackingError::BufferTooSmall);
}
let packed = self.pack();
&mut output[..].copy_from_slice(&packed[..]);
Ok(())
}
#[inline]
fn unpack_from_slice(src: &[u8]) -> Result<Self, PackingError> {
if src.len() < $num_bytes {
return Err(PackingError::BufferTooSmall);
}
let mut s = [0; $num_bytes];
&mut s[..].copy_from_slice(&src[..$num_bytes]);
Self::unpack(&s)
}
#[inline]
fn packed_bytes() -> usize {
$num_bytes
}
}
)
}