-
Notifications
You must be signed in to change notification settings - Fork 0
/
pack.rs
120 lines (110 loc) · 3.57 KB
/
pack.rs
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use crate::pack::{ExtEnumError, PackTarget};
use impl_trait_for_tuples::impl_for_tuples;
#[derive(Debug, PartialEq, Eq)]
pub enum UnpackError {
NotEnoughData, // Only valid for unpacking, not enough data available.
InvalidEnumTag, // Invalid enum tag
}
#[derive(Debug, PartialEq, Eq)]
pub enum PackError<T> {
NotAllowed, // In case the packing is not allowed. e.g. attempting to pack a list of more than 255 items where the packing has a length prefix of 8 bits.
TargetError(T), // Wraps around PackTarget::Error
}
impl Into<UnpackError> for ExtEnumError {
fn into(self) -> UnpackError {
match self {
ExtEnumError::InvalidTag => UnpackError::InvalidEnumTag,
}
}
}
pub trait Pack: Sized {
fn unpack(data: &[u8]) -> Result<(Self, &[u8]), UnpackError>;
fn pack<T: PackTarget>(&self, target: T) -> Result<T, PackError<T::Error>>;
}
pub trait PackTagged: Sized {
type Tag;
fn get_tag(&self) -> Self::Tag;
fn unpack_data(tag: Self::Tag, data: &[u8]) -> Result<(Self, &[u8]), UnpackError>;
fn pack_data<T: PackTarget>(&self, target: T) -> Result<T, PackError<T::Error>>;
}
/* Default implementations */
macro_rules! default_impl {
($t:ty) => {
impl $crate::pack::Pack for $t {
fn unpack(data: &[u8]) -> Result<(Self, &[u8]), $crate::pack::UnpackError> {
let expected_size = core::mem::size_of::<$t>();
if data.len() < expected_size {
Err(UnpackError::NotEnoughData)
} else {
Ok((
<$t>::from_le_bytes(
core::convert::TryInto::try_into(&data[0..expected_size]).unwrap(),
),
&data[expected_size..],
))
}
}
fn pack<T: $crate::pack::PackTarget>(
&self,
target: T,
) -> Result<T, $crate::pack::PackError<T::Error>> {
target
.append(&(self.to_le_bytes()))
.map_err(PackError::TargetError)
}
}
};
}
default_impl!(u8);
default_impl!(u16);
default_impl!(u32);
default_impl!(u64);
default_impl!(u128);
default_impl!(i8);
default_impl!(i16);
default_impl!(i32);
default_impl!(i64);
default_impl!(i128);
impl Pack for bool {
fn unpack(data: &[u8]) -> Result<(Self, &[u8]), UnpackError> {
let (x, data) = u8::unpack(data)?;
Ok((x > 0, data))
}
fn pack<T: PackTarget>(&self, target: T) -> Result<T, PackError<T::Error>> {
(*self as u8).pack(target)
}
}
#[impl_for_tuples(10)]
impl Pack for Tuple {
fn unpack(data: &[u8]) -> Result<(Self, &[u8]), UnpackError> {
for_tuples!( #( let (Tuple, data) = Tuple::unpack(data)?; )* );
Ok(((for_tuples!( #( Tuple ),* )), data))
}
fn pack<T: PackTarget>(&self, target: T) -> Result<T, PackError<T::Error>> {
for_tuples!( #( let target = Tuple.pack(target)?; )* );
Ok(target)
}
}
impl<T> PackTagged for Option<T>
where
T: Pack,
{
type Tag = bool;
fn get_tag(&self) -> bool {
self.is_some()
}
fn unpack_data(tag: bool, data: &[u8]) -> Result<(Self, &[u8]), UnpackError> {
if tag {
let (inner, data) = T::unpack(data)?;
Ok((Some(inner), data))
} else {
Ok((None, data))
}
}
fn pack_data<TA: PackTarget>(&self, target: TA) -> Result<TA, PackError<TA::Error>> {
match self {
Some(inner) => inner.pack(target),
None => Ok(target),
}
}
}