1pub trait AsBytes {
2 fn as_byte(&self) -> &[u8];
3}
4
5macro_rules! number_default_for_as_bytes {
6 ($($b:tt,$n:tt);*) => {
7 $(
8 impl AsBytes for $b
9 {
10 fn as_byte(&self) -> &[u8] {
11 unsafe {
12 &*(self as *const $b as *const [u8;$n])
13 }
14 }
15 }
16 )*
17
18 };
19}
20
21number_default_for_as_bytes!(u8,1;u16,2;u32,4;u64,8;u128,16;i8,1;i16,2;i32,4;i64,8;i128,16);
22
23#[cfg(target_pointer_width = "64")]
24impl AsBytes for usize {
25 fn as_byte(&self) -> &[u8] {
26 unsafe { &*(self as *const usize as *const [u8; 8]) }
27 }
28}
29#[cfg(target_pointer_width = "32")]
30impl AsBytes for usize {
31 fn as_byte(&self) -> &[u8] {
32 unsafe { &*(self as *const usize as *const [u8; 4]) }
33 }
34}
35#[cfg(target_pointer_width = "64")]
36impl AsBytes for isize {
37 fn as_byte(&self) -> &[u8] {
38 unsafe { &*(self as *const isize as *const [u8; 8]) }
39 }
40}
41#[cfg(target_pointer_width = "32")]
42impl AsBytes for isize {
43 fn as_byte(&self) -> &[u8] {
44 unsafe { &*(self as *const isize as *const [u8; 4]) }
45 }
46}
47
48impl AsBytes for Vec<u8> {
49 fn as_byte(&self) -> &[u8] {
50 self.as_slice()
51 }
52}
53
54impl AsBytes for [u8] {
55 fn as_byte(&self) -> &[u8] {
56 self
57 }
58}
59impl AsBytes for &str {
60 fn as_byte(&self) -> &[u8] {
61 self.as_bytes()
62 }
63}
64impl AsBytes for &[char] {
65 fn as_byte(&self) -> &[u8] {
66 unsafe { std::mem::transmute(*self) }
67 }
68}
69impl AsBytes for Vec<char> {
70 fn as_byte(&self) -> &[u8] {
71 let cs = self.as_slice();
72 unsafe { std::mem::transmute(cs) }
73 }
74}
75
76impl<T> AsBytes for &T
77where
78 T: AsBytes,
79{
80 fn as_byte(&self) -> &[u8] {
81 (*self).as_byte()
82 }
83}