endian.rs100.00%
1
// Copyright 2024 Google LLC2
//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 at6
//7
// https://www.apache.org/licenses/LICENSE-2.08
//9
// Unless required by applicable law or agreed to in writing, software10
// 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 and13
// limitations under the License.14
15
macro_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 {12x27
#[cfg(target_endian = $endian)]28
{29
self.v6x30
}31
#[cfg(target_endian = $opposite)]32
{33
self.v.swap_bytes()6x34
}35
}12x36
}37
38
impl From<$ne_type> for $ed_type {39
fn from(value: $ne_type) -> Self {10x40
#[cfg(target_endian = $endian)]41
{42
Self { v: value }7x43
}44
#[cfg(target_endian = $opposite)]45
{46
Self {3x47
v: value.swap_bytes(),3x48
}3x49
}50
}10x51
}52
53
impl From<$ed_type> for $ne_type {54
fn from(value: $ed_type) -> Self {6x55
#[cfg(target_endian = $endian)]56
{57
value.v3x58
}59
#[cfg(target_endian = $opposite)]60
{61
value.v.swap_bytes()3x62
}63
}6x64
}65
66
impl ::core::fmt::Display for $ed_type {67
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {6x68
#[cfg(target_endian = $endian)]69
{70
::core::fmt::Display::fmt(&self.v, f)3x71
}72
#[cfg(target_endian = $opposite)]73
{74
::core::fmt::Display::fmt(&self.v.swap_bytes(), f)3x75
}76
}6x77
}78
79
impl ::core::fmt::Debug for $ed_type {80
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {6x81
f.write_str(stringify!($ed_type))?;6x82
::core::fmt::Write::write_char(f, '(')?;6x83
::core::fmt::Debug::fmt(&self.to_ne(), f)?;6x84
::core::fmt::Write::write_char(f, ')')6x85
}6x86
}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 {6x90
Self {6x91
v: $ne_type::from_ne_bytes(value),6x92
}6x93
}6x94
}95
};96
}97
98
macro_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
105
endian_type!(u16, Lu16, Bu16);106
endian_type!(u32, Lu32, Bu32);107
endian_type!(u64, Lu64, Bu64);108
109
#[cfg(test)]110
#[path = "endian_test.rs"]111
mod tests;112