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
use crate::{Packed, View};
use std::{any, borrow::Borrow, fmt, hash, marker};
pub struct Packet<T> {
boxed: Box<[u8]>,
marker: marker::PhantomData<T>,
}
impl<T> Packet<T>
where
T: Packed,
{
#[inline]
pub(crate) fn new(boxed: Box<[u8]>) -> Self {
Self {
boxed,
marker: marker::PhantomData,
}
}
#[inline]
pub fn view(&self) -> View<'_, T> {
View::new(self.boxed.as_ref())
}
pub fn pack<P>(packed: P) -> Self
where
P: AsRef<T>,
{
let mut boxed = vec![0; <T as Packed>::SIZE];
packed.as_ref().unchecked_write_to_slice(&mut boxed);
Self::new(boxed.into_boxed_slice())
}
#[inline]
#[must_use = "this will clone data from the slice, it is often expensive"]
pub fn unpack(&self) -> T {
self.view().unpack()
}
}
impl<T> Borrow<[u8]> for Packet<T> {
fn borrow(&self) -> &[u8] {
self.boxed.borrow()
}
}
impl<T> Clone for Packet<T> {
fn clone(&self) -> Self {
Self {
boxed: self.boxed.clone(),
marker: self.marker,
}
}
}
impl<T> AsRef<[u8]> for Packet<T> {
fn as_ref(&self) -> &[u8] {
self.boxed.as_ref()
}
}
impl<T, U> PartialEq<Packet<U>> for Packet<T> {
fn eq(&self, other: &Packet<U>) -> bool {
self.boxed.eq(&other.boxed)
}
}
impl<T> Eq for Packet<T> {}
impl<T, U> PartialOrd<Packet<U>> for Packet<T> {
fn partial_cmp(&self, other: &Packet<U>) -> Option<std::cmp::Ordering> {
self.boxed.partial_cmp(&other.boxed)
}
}
impl<T> Ord for Packet<T> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.boxed.cmp(&other.boxed)
}
}
impl<T> hash::Hash for Packet<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.boxed.hash(state);
self.marker.hash(state);
}
}
impl<T> fmt::Debug for Packet<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ty = any::type_name::<T>();
f.debug_struct(&format!("Packet<{}>", ty))
.field("slice", &self.boxed)
.field("marker", &self.marker)
.finish()
}
}