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
use crate::internal_prelude::v1::*;
use crate::types_bits::ByteArray;
pub trait PackedStruct where Self: Sized {
type ByteArray : ByteArray;
fn pack(&self) -> PackingResult<Self::ByteArray>;
fn unpack(src: &Self::ByteArray) -> PackingResult<Self>;
}
pub trait PackedStructInfo {
fn packed_bits() -> usize;
}
pub trait PackedStructSlice where Self: Sized {
fn pack_to_slice(&self, output: &mut [u8]) -> PackingResult<()>;
fn unpack_from_slice(src: &[u8]) -> PackingResult<Self>;
fn packed_bytes_size(opt_self: Option<&Self>) -> PackingResult<usize>;
#[cfg(any(feature="alloc", feature="std"))]
fn pack_to_vec(&self) -> PackingResult<Vec<u8>> {
let size = Self::packed_bytes_size(Some(self))?;
let mut buf = vec![0; size];
self.pack_to_slice(&mut buf)?;
Ok(buf)
}
}
#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum PackingError {
InvalidValue,
BitsError,
BufferTooSmall,
NotImplemented,
InstanceRequiredForSize,
MoreThanOneDynamicType,
BufferSizeMismatch { expected: usize, actual: usize },
BufferModMismatch { actual_size: usize, modulo_required: usize },
SliceIndexingError { slice_len: usize },
InternalError
}
impl crate::Display for PackingError {
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::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",
PackingError::InstanceRequiredForSize => "This structure's packing size can't be determined statically, an instance is required.",
PackingError::BufferModMismatch { .. } => "The structure's size is not a multiple of the item's size",
PackingError::SliceIndexingError { .. } => "Failed to index into a slice",
PackingError::MoreThanOneDynamicType => "Only one dynamically sized type is supported in the tuple",
PackingError::InternalError => "Internal error"
}
}
}
impl From<PackingError> for crate::fmt::Error {
fn from(_: PackingError) -> Self {
Self
}
}
pub type PackingResult<T> = Result<T, PackingError>;