> for $larger_byteorder {
#[inline(always)]
fn from(x: $name) -> $larger_byteorder {
$larger_byteorder::new(x.get().into())
}
}
)*
$(
impl TryFrom<$larger_byteorder_try> for $name {
type Error = TryFromIntError;
#[inline(always)]
fn try_from(x: $larger_byteorder_try) -> Result<$name, TryFromIntError> {
x.get().try_into().map($name::new)
}
}
)*
impl AsRef<[u8; $bytes]> for $name {
#[inline(always)]
fn as_ref(&self) -> &[u8; $bytes] {
&self.0
}
}
impl AsMut<[u8; $bytes]> for $name {
#[inline(always)]
fn as_mut(&mut self) -> &mut [u8; $bytes] {
&mut self.0
}
}
impl PartialEq<$name> for [u8; $bytes] {
#[inline(always)]
fn eq(&self, other: &$name) -> bool {
self.eq(&other.0)
}
}
impl PartialEq<[u8; $bytes]> for $name {
#[inline(always)]
fn eq(&self, other: &[u8; $bytes]) -> bool {
self.0.eq(other)
}
}
impl_fmt_traits!($name, $native, $number_kind);
impl_ops_traits!($name, $native, $number_kind);
impl Debug for $name {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// This results in a format like "U16(42)".
f.debug_tuple(stringify!($name)).field(&self.get()).finish()
}
}
};
}
define_type!(
A,
U16,
u16,
16,
2,
read_u16,
write_u16,
"unsigned integer",
[u32, u64, u128, usize],
[u32, u64, u128, usize],
[U32, U64, U128],
[U32, U64, U128]
);
define_type!(
A,
U32,
u32,
32,
4,
read_u32,
write_u32,
"unsigned integer",
[u64, u128],
[u64, u128],
[U64, U128],
[U64, U128]
);
define_type!(
A,
U64,
u64,
64,
8,
read_u64,
write_u64,
"unsigned integer",
[u128],
[u128],
[U128],
[U128]
);
define_type!(A, U128, u128, 128, 16, read_u128, write_u128, "unsigned integer", [], [], [], []);
define_type!(
An,
I16,
i16,
16,
2,
read_i16,
write_i16,
"signed integer",
[i32, i64, i128, isize],
[i32, i64, i128, isize],
[I32, I64, I128],
[I32, I64, I128]
);
define_type!(
An,
I32,
i32,
32,
4,
read_i32,
write_i32,
"signed integer",
[i64, i128],
[i64, i128],
[I64, I128],
[I64, I128]
);
define_type!(
An,
I64,
i64,
64,
8,
read_i64,
write_i64,
"signed integer",
[i128],
[i128],
[I128],
[I128]
);
define_type!(An, I128, i128, 128, 16, read_i128, write_i128, "signed integer", [], [], [], []);
define_type!(
An,
F32,
f32,
32,
4,
read_f32,
write_f32,
"floating point number",
[f64],
[],
[F64],
[]
);
define_type!(An, F64, f64, 64, 8, read_f64, write_f64, "floating point number", [], [], [], []);
macro_rules! module {
($name:ident, $trait:ident, $endianness_str:expr) => {
/// Numeric primitives stored in
#[doc = $endianness_str]
/// byte order.
pub mod $name {
use byteorder::$trait;
module!(@ty U16, $trait, "16-bit unsigned integer", $endianness_str);
module!(@ty U32, $trait, "32-bit unsigned integer", $endianness_str);
module!(@ty U64, $trait, "64-bit unsigned integer", $endianness_str);
module!(@ty U128, $trait, "128-bit unsigned integer", $endianness_str);
module!(@ty I16, $trait, "16-bit signed integer", $endianness_str);
module!(@ty I32, $trait, "32-bit signed integer", $endianness_str);
module!(@ty I64, $trait, "64-bit signed integer", $endianness_str);
module!(@ty I128, $trait, "128-bit signed integer", $endianness_str);
module!(@ty F32, $trait, "32-bit floating point number", $endianness_str);
module!(@ty F64, $trait, "64-bit floating point number", $endianness_str);
}
};
(@ty $ty:ident, $trait:ident, $desc_str:expr, $endianness_str:expr) => {
/// A
#[doc = $desc_str]
/// stored in
#[doc = $endianness_str]
/// byte order.
pub type $ty = crate::byteorder::$ty<$trait>;
};
}
module!(big_endian, BigEndian, "big-endian");
module!(little_endian, LittleEndian, "little-endian");
module!(network_endian, NetworkEndian, "network-endian");
module!(native_endian, NativeEndian, "native-endian");
#[cfg(any(test, kani))]
mod tests {
use ::byteorder::NativeEndian;
use {
super::*,
crate::{AsBytes, FromBytes, Unaligned},
};
#[cfg(not(kani))]
mod compatibility {
pub(super) use rand::{
distributions::{Distribution, Standard},
rngs::SmallRng,
Rng, SeedableRng,
};
pub(crate) trait Arbitrary {}
impl Arbitrary for T {}
}
#[cfg(kani)]
mod compatibility {
pub(crate) use kani::Arbitrary;
pub(crate) struct SmallRng;
impl SmallRng {
pub(crate) fn seed_from_u64(_state: u64) -> Self {
Self
}
}
pub(crate) trait Rng {
fn sample>(&mut self, _distr: D) -> T
where
T: Arbitrary,
{
kani::any()
}
}
impl Rng for SmallRng {}
pub(crate) trait Distribution {}
impl Distribution for U {}
pub(crate) struct Standard;
}
use compatibility::*;
// A native integer type (u16, i32, etc).
trait Native: Arbitrary + FromBytes + AsBytes + Copy + PartialEq + Debug {
const ZERO: Self;
const MAX_VALUE: Self;
type Distribution: Distribution;
const DIST: Self::Distribution;
fn rand(rng: &mut R) -> Self {
rng.sample(Self::DIST)
}
#[cfg(kani)]
fn any() -> Self {
kani::any()
}
fn checked_add(self, rhs: Self) -> Option;
fn checked_div(self, rhs: Self) -> Option;
fn checked_mul(self, rhs: Self) -> Option;
fn checked_rem(self, rhs: Self) -> Option;
fn checked_sub(self, rhs: Self) -> Option;
fn checked_shl(self, rhs: Self) -> Option;
fn checked_shr(self, rhs: Self) -> Option;
fn is_nan(self) -> bool;
/// For `f32` and `f64`, NaN values are not considered equal to
/// themselves. This method is like `assert_eq!`, but it treats NaN
/// values as equal.
fn assert_eq_or_nan(self, other: Self) {
let slf = (!self.is_nan()).then(|| self);
let other = (!other.is_nan()).then(|| other);
assert_eq!(slf, other);
}
}
trait ByteArray:
FromBytes + AsBytes + Copy + AsRef<[u8]> + AsMut<[u8]> + Debug + Default + Eq
{
/// Invert the order of the bytes in the array.
fn invert(self) -> Self;
}
trait ByteOrderType: FromBytes + AsBytes + Unaligned + Copy + Eq + Debug {
type Native: Native;
type ByteArray: ByteArray;
const ZERO: Self;
fn new(native: Self::Native) -> Self;
fn get(self) -> Self::Native;
fn set(&mut self, native: Self::Native);
fn from_bytes(bytes: Self::ByteArray) -> Self;
fn into_bytes(self) -> Self::ByteArray;
/// For `f32` and `f64`, NaN values are not considered equal to
/// themselves. This method is like `assert_eq!`, but it treats NaN
/// values as equal.
fn assert_eq_or_nan(self, other: Self) {
let slf = (!self.get().is_nan()).then(|| self);
let other = (!other.get().is_nan()).then(|| other);
assert_eq!(slf, other);
}
}
trait ByteOrderTypeUnsigned: ByteOrderType {
const MAX_VALUE: Self;
}
macro_rules! impl_byte_array {
($bytes:expr) => {
impl ByteArray for [u8; $bytes] {
fn invert(mut self) -> [u8; $bytes] {
self.reverse();
self
}
}
};
}
impl_byte_array!(2);
impl_byte_array!(4);
impl_byte_array!(8);
impl_byte_array!(16);
macro_rules! impl_byte_order_type_unsigned {
($name:ident, unsigned) => {
impl ByteOrderTypeUnsigned for $name {
const MAX_VALUE: $name = $name::MAX_VALUE;
}
};
($name:ident, signed) => {};
}
macro_rules! impl_traits {
($name:ident, $native:ident, $bytes:expr, $sign:ident $(, @$float:ident)?) => {
impl Native for $native {
// For some types, `0 as $native` is required (for example, when
// `$native` is a floating-point type; `0` is an integer), but
// for other types, it's a trivial cast. In all cases, Clippy
// thinks it's dangerous.
#[allow(trivial_numeric_casts, clippy::as_conversions)]
const ZERO: $native = 0 as $native;
const MAX_VALUE: $native = $native::MAX;
type Distribution = Standard;
const DIST: Standard = Standard;
impl_traits!(@float_dependent_methods $(@$float)?);
}
impl ByteOrderType for $name {
type Native = $native;
type ByteArray = [u8; $bytes];
const ZERO: $name = $name::ZERO;
fn new(native: $native) -> $name {
$name::new(native)
}
fn get(self) -> $native {
$name::get(self)
}
fn set(&mut self, native: $native) {
$name::set(self, native)
}
fn from_bytes(bytes: [u8; $bytes]) -> $name {
$name::from(bytes)
}
fn into_bytes(self) -> [u8; $bytes] {
<[u8; $bytes]>::from(self)
}
}
impl_byte_order_type_unsigned!($name, $sign);
};
(@float_dependent_methods) => {
fn checked_add(self, rhs: Self) -> Option { self.checked_add(rhs) }
fn checked_div(self, rhs: Self) -> Option { self.checked_div(rhs) }
fn checked_mul(self, rhs: Self) -> Option { self.checked_mul(rhs) }
fn checked_rem(self, rhs: Self) -> Option { self.checked_rem(rhs) }
fn checked_sub(self, rhs: Self) -> Option { self.checked_sub(rhs) }
fn checked_shl(self, rhs: Self) -> Option { self.checked_shl(rhs.try_into().unwrap_or(u32::MAX)) }
fn checked_shr(self, rhs: Self) -> Option { self.checked_shr(rhs.try_into().unwrap_or(u32::MAX)) }
fn is_nan(self) -> bool { false }
};
(@float_dependent_methods @float) => {
fn checked_add(self, rhs: Self) -> Option { Some(self + rhs) }
fn checked_div(self, rhs: Self) -> Option { Some(self / rhs) }
fn checked_mul(self, rhs: Self) -> Option { Some(self * rhs) }
fn checked_rem(self, rhs: Self) -> Option { Some(self % rhs) }
fn checked_sub(self, rhs: Self) -> Option { Some(self - rhs) }
fn checked_shl(self, _rhs: Self) -> Option { unimplemented!() }
fn checked_shr(self, _rhs: Self) -> Option { unimplemented!() }
fn is_nan(self) -> bool { self.is_nan() }
};
}
impl_traits!(U16, u16, 2, unsigned);
impl_traits!(U32, u32, 4, unsigned);
impl_traits!(U64, u64, 8, unsigned);
impl_traits!(U128, u128, 16, unsigned);
impl_traits!(I16, i16, 2, signed);
impl_traits!(I32, i32, 4, signed);
impl_traits!(I64, i64, 8, signed);
impl_traits!(I128, i128, 16, signed);
impl_traits!(F32, f32, 4, signed, @float);
impl_traits!(F64, f64, 8, signed, @float);
macro_rules! call_for_unsigned_types {
($fn:ident, $byteorder:ident) => {
$fn::>();
$fn::>();
$fn::>();
$fn::>();
};
}
macro_rules! call_for_signed_types {
($fn:ident, $byteorder:ident) => {
$fn::>();
$fn::>();
$fn::>();
$fn::>();
};
}
macro_rules! call_for_float_types {
($fn:ident, $byteorder:ident) => {
$fn::>();
$fn::>();
};
}
macro_rules! call_for_all_types {
($fn:ident, $byteorder:ident) => {
call_for_unsigned_types!($fn, $byteorder);
call_for_signed_types!($fn, $byteorder);
call_for_float_types!($fn, $byteorder);
};
}
#[cfg(target_endian = "big")]
type NonNativeEndian = LittleEndian;
#[cfg(target_endian = "little")]
type NonNativeEndian = BigEndian;
// We use a `u64` seed so that we can use `SeedableRng::seed_from_u64`.
// `SmallRng`'s `SeedableRng::Seed` differs by platform, so if we wanted to
// call `SeedableRng::from_seed`, which takes a `Seed`, we would need
// conditional compilation by `target_pointer_width`.
const RNG_SEED: u64 = 0x7A03CAE2F32B5B8F;
const RAND_ITERS: usize = if cfg!(any(miri, kani)) {
// The tests below which use this constant used to take a very long time
// on Miri, which slows down local development and CI jobs. We're not
// using Miri to check for the correctness of our code, but rather its
// soundness, and at least in the context of these particular tests, a
// single loop iteration is just as good for surfacing UB as multiple
// iterations are.
//
// As of the writing of this comment, here's one set of measurements:
//
// $ # RAND_ITERS == 1
// $ cargo miri test -- -Z unstable-options --report-time endian
// test byteorder::tests::test_native_endian ... ok <0.049s>
// test byteorder::tests::test_non_native_endian ... ok <0.061s>
//
// $ # RAND_ITERS == 1024
// $ cargo miri test -- -Z unstable-options --report-time endian
// test byteorder::tests::test_native_endian ... ok <25.716s>
// test byteorder::tests::test_non_native_endian ... ok <38.127s>
1
} else {
1024
};
#[cfg_attr(test, test)]
#[cfg_attr(kani, kani::proof)]
fn test_zero() {
fn test_zero() {
assert_eq!(T::ZERO.get(), T::Native::ZERO);
}
call_for_all_types!(test_zero, NativeEndian);
call_for_all_types!(test_zero, NonNativeEndian);
}
#[cfg_attr(test, test)]
#[cfg_attr(kani, kani::proof)]
fn test_max_value() {
fn test_max_value() {
assert_eq!(T::MAX_VALUE.get(), T::Native::MAX_VALUE);
}
call_for_unsigned_types!(test_max_value, NativeEndian);
call_for_unsigned_types!(test_max_value, NonNativeEndian);
}
#[cfg_attr(test, test)]
#[cfg_attr(kani, kani::proof)]
fn test_endian() {
fn test(invert: bool) {
let mut r = SmallRng::seed_from_u64(RNG_SEED);
for _ in 0..RAND_ITERS {
let native = T::Native::rand(&mut r);
let mut bytes = T::ByteArray::default();
bytes.as_bytes_mut().copy_from_slice(native.as_bytes());
if invert {
bytes = bytes.invert();
}
let mut from_native = T::new(native);
let from_bytes = T::from_bytes(bytes);
from_native.assert_eq_or_nan(from_bytes);
from_native.get().assert_eq_or_nan(native);
from_bytes.get().assert_eq_or_nan(native);
assert_eq!(from_native.into_bytes(), bytes);
assert_eq!(from_bytes.into_bytes(), bytes);
let updated = T::Native::rand(&mut r);
from_native.set(updated);
from_native.get().assert_eq_or_nan(updated);
}
}
fn test_native() {
test::(false);
}
fn test_non_native() {
test::(true);
}
call_for_all_types!(test_native, NativeEndian);
call_for_all_types!(test_non_native, NonNativeEndian);
}
#[test]
fn test_ops_impls() {
// Test implementations of traits in `core::ops`. Some of these are
// fairly banal, but some are optimized to perform the operation without
// swapping byte order (namely, bit-wise operations which are identical
// regardless of byte order). These are important to test, and while
// we're testing those anyway, it's trivial to test all of the impls.
fn test(op: F, op_native: G, op_native_checked: Option)
where
T: ByteOrderType,
F: Fn(T, T) -> T,
G: Fn(T::Native, T::Native) -> T::Native,
H: Fn(T::Native, T::Native) -> Option,
{
let mut r = SmallRng::seed_from_u64(RNG_SEED);
for _ in 0..RAND_ITERS {
let n0 = T::Native::rand(&mut r);
let n1 = T::Native::rand(&mut r);
let t0 = T::new(n0);
let t1 = T::new(n1);
// If this operation would overflow/underflow, skip it rather
// than attempt to catch and recover from panics.
if matches!(&op_native_checked, Some(checked) if checked(n0, n1).is_none()) {
continue;
}
let n_res = op_native(n0, n1);
let t_res = op(t0, t1);
// For `f32` and `f64`, NaN values are not considered equal to
// themselves. We store `Option`/`Option` and store
// NaN as `None` so they can still be compared.
let n_res = (!T::Native::is_nan(n_res)).then(|| n_res);
let t_res = (!T::Native::is_nan(t_res.get())).then(|| t_res.get());
assert_eq!(n_res, t_res);
}
}
macro_rules! test {
(@binary $trait:ident, $method:ident $([$checked_method:ident])?, $($call_for_macros:ident),*) => {{
test!(
@inner $trait,
core::ops::$trait::$method,
core::ops::$trait::$method,
{
#[allow(unused_mut, unused_assignments)]
let mut op_native_checked = None:: Option>;
$(
op_native_checked = Some(T::Native::$checked_method);
)?
op_native_checked
},
$($call_for_macros),*
);
}};
(@unary $trait:ident, $method:ident $([$checked_method:ident])?, $($call_for_macros:ident),*) => {{
test!(
@inner $trait,
|slf, _rhs| core::ops::$trait::$method(slf),
|slf, _rhs| core::ops::$trait::$method(slf),
{
#[allow(unused_mut, unused_assignments)]
let mut op_native_checked = None:: Option>;
$(
op_native_checked = Some(|slf, _rhs| T::Native::$checked_method(slf));
)?
op_native_checked
},
$($call_for_macros),*
);
}};
(@inner $trait:ident, $op:expr, $op_native:expr, $op_native_checked:expr, $($call_for_macros:ident),*) => {{
fn t>()
where
T::Native: core::ops::$trait