Alioth Code Coverage

endian.rs100.00%

1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15macro_rules! endian_impl {
16 ($ne_type:ident, $ed_type:ident, $endian:expr, $opposite:expr) => {
17 #[repr(transparent)]
18 #[derive(
19 ::zerocopy::Immutable, ::zerocopy::IntoBytes, ::zerocopy::FromBytes, Copy, Clone,
20 )]
21 pub struct $ed_type {
22 v: $ne_type,
23 }
24
25 impl $ed_type {
26 pub fn to_ne(self) -> $ne_type {12x
27 #[cfg(target_endian = $endian)]
28 {
29 self.v6x
30 }
31 #[cfg(target_endian = $opposite)]
32 {
33 self.v.swap_bytes()6x
34 }
35 }12x
36 }
37
38 impl From<$ne_type> for $ed_type {
39 fn from(value: $ne_type) -> Self {18x
40 #[cfg(target_endian = $endian)]
41 {
42 Self { v: value }15x
43 }
44 #[cfg(target_endian = $opposite)]
45 {
46 Self {3x
47 v: value.swap_bytes(),3x
48 }3x
49 }
50 }18x
51 }
52
53 impl From<$ed_type> for $ne_type {
54 fn from(value: $ed_type) -> Self {6x
55 #[cfg(target_endian = $endian)]
56 {
57 value.v3x
58 }
59 #[cfg(target_endian = $opposite)]
60 {
61 value.v.swap_bytes()3x
62 }
63 }6x
64 }
65
66 impl ::core::fmt::Display for $ed_type {
67 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {6x
68 #[cfg(target_endian = $endian)]
69 {
70 ::core::fmt::Display::fmt(&self.v, f)3x
71 }
72 #[cfg(target_endian = $opposite)]
73 {
74 ::core::fmt::Display::fmt(&self.v.swap_bytes(), f)3x
75 }
76 }6x
77 }
78
79 impl ::core::fmt::Debug for $ed_type {
80 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {6x
81 f.write_str(stringify!($ed_type))?;6x
82 ::core::fmt::Write::write_char(f, '(')?;6x
83 ::core::fmt::Debug::fmt(&self.to_ne(), f)?;6x
84 ::core::fmt::Write::write_char(f, ')')6x
85 }6x
86 }
87
88 impl From<[u8; ::core::mem::size_of::<$ne_type>()]> for $ed_type {
89 fn from(value: [u8; ::core::mem::size_of::<$ne_type>()]) -> Self {6x
90 Self {6x
91 v: $ne_type::from_ne_bytes(value),6x
92 }6x
93 }6x
94 }
95 };
96}
97
98macro_rules! endian_type {
99 ($ne_type:ident, $le_type:ident, $be_type:ident) => {
100 endian_impl!($ne_type, $le_type, "little", "big");
101 endian_impl!($ne_type, $be_type, "big", "little");
102 };
103}
104
105endian_type!(u16, Lu16, Bu16);
106endian_type!(u32, Lu32, Bu32);
107endian_type!(u64, Lu64, Bu64);
108
109#[cfg(test)]
110#[path = "endian_test.rs"]
111mod tests;
112