// Copyright 2019 The Fuchsia Authors // // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. // This file may not be copied, modified, or distributed except according to // those terms.
//! Byte order-aware numeric primitives. //! //! This module contains equivalents of the native multi-byte integer types with //! no alignment requirement and supporting byte order conversions. //! //! For each native multi-byte integer type - `u16`, `i16`, `u32`, etc - and //! floating point type - `f32` and `f64` - an equivalent type is defined by //! this module - [`U16`], [`I16`], [`U32`], [`F64`], etc. Unlike their native //! counterparts, these types have alignment 1, and take a type parameter //! specifying the byte order in which the bytes are stored in memory. Each type //! implements the [`FromBytes`], [`AsBytes`], and [`Unaligned`] traits. //! //! These two properties, taken together, make these types useful for defining //! data structures whose memory layout matches a wire format such as that of a //! network protocol or a file format. Such formats often have multi-byte values //! at offsets that do not respect the alignment requirements of the equivalent //! native types, and stored in a byte order not necessarily the same as that of //! the target platform. //! //! Type aliases are provided for common byte orders in the [`big_endian`], //! [`little_endian`], [`network_endian`], and [`native_endian`] submodules. //! //! # Example //! //! One use of these types is for representing network packet formats, such as //! UDP: //! //! ```rust,edition2021 //! # #[cfg(feature = "derive")] { // This example uses derives, and won't compile without them //! use zerocopy::{AsBytes, ByteSlice, FromBytes, FromZeroes, Ref, Unaligned}; //! use zerocopy::byteorder::network_endian::U16; //! //! #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] //! #[repr(C)] //! struct UdpHeader { //! src_port: U16, //! dst_port: U16, //! length: U16, //! checksum: U16, //! } //! //! struct UdpPacket<B: ByteSlice> { //! header: Ref<B, UdpHeader>, //! body: B, //! } //! //! impl<B: ByteSlice> UdpPacket<B> { //! fn parse(bytes: B) -> Option<UdpPacket<B>> { //! let (header, body) = Ref::new_from_prefix(bytes)?; //! Some(UdpPacket { header, body }) //! } //! //! fn src_port(&self) -> u16 { //! self.header.src_port.get() //! } //! //! // more getters... //! } //! # } //! ```
// We don't reexport `WriteBytesExt` or `ReadBytesExt` because those are only // available with the `std` feature enabled, and zerocopy is `no_std` by // default. pubuse ::byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian, NetworkEndian, BE, LE};
#[inline(always)] fn $method(self, rhs: $name<O>) -> $name<O> { let self_native: $native = self.get(); let rhs_native: $native = rhs.get(); let result_native = core::ops::$trait::$method(self_native, rhs_native);
$name::<O>::new(result_native)
}
}
impl<O: ByteOrder> core::ops::$trait_assign for $name<O> { #[inline(always)] fn $method_assign(&mutself, rhs: $name<O>) {
*self = core::ops::$trait::$method(*self, rhs);
}
}
}; // Implement traits in terms of the same trait on the native type, but // without performing a byte order swap. This only works for bitwise // operations like `&`, `|`, etc.
(@without_byteorder_swap $name:ident, $native:ident, $trait:ident, $method:ident, $trait_assign:ident, $method_assign:ident) => { impl<O: ByteOrder> core::ops::$traitfor $name<O> { type Output = $name<O>;
#[inline(always)] fn $method(self, rhs: $name<O>) -> $name<O> { let self_native = $native::from_ne_bytes(self.0); let rhs_native = $native::from_ne_bytes(rhs.0); let result_native = core::ops::$trait::$method(self_native, rhs_native);
$name(result_native.to_ne_bytes(), PhantomData)
}
}
macro_rules! define_max_value_constant {
($name:ident, $bytes:expr, "unsigned integer") => { /// The maximum value. /// /// This constant should be preferred to constructing a new value using /// `new`, as `new` may perform an endianness swap depending on the /// endianness `O` and the endianness of the platform. pubconst MAX_VALUE: $name<O> = $name([0xFFu8; $bytes], PhantomData);
}; // We don't provide maximum and minimum value constants for signed values // and floats because there's no way to do it generically - it would require // a different value depending on the value of the `ByteOrder` type // parameter. Currently, one workaround would be to provide implementations // for concrete implementations of that trait. In the long term, if we are // ever able to make the `new` constructor a const fn, we could use that // instead.
($name:ident, $bytes:expr, "signed integer") => {};
($name:ident, $bytes:expr, "floating point number") => {};
}
`", stringify!($name), "` is like the native `", stringify!($native), "` type with
two major differences: First, it has no alignment requirement (its alignment is 1).
Second, the endianness of its memory layout is given by the type parameter `O`,
which can be any type which implements [`ByteOrder`]. In particular, this refers
to [`BigEndian`], [`LittleEndian`], [`NativeEndian`], and [`NetworkEndian`].
", stringify!($article), " `", stringify!($name), "` can be constructed using
the [`new`] method, and its contained value can be obtained as a native
`",stringify!($native), "` using the [`get`] method, or updated in place with
the [`set`] method. In all cases, if the endianness `O` is not the same as the
endianness of the current platform, an endianness swap will be performed in
order to uphold the invariants that a) the layout of `", stringify!($name), "`
has endianness `O` and that, b) the layout of `", stringify!($native), "` has
the platform's native endianness.
`", stringify!($name), "` implements [`FromBytes`], [`AsBytes`], and [`Unaligned`],
making it useful for parsing and serialization. See the module documentation for an
example of how it can be used for parsing UDP packets.
safety_comment! { /// SAFETY: /// `$name<O>` is `repr(transparent)`, and so it has the same layout /// as its only non-zero field, which is a `u8` array. `u8` arrays /// are `FromZeroes`, `FromBytes`, `AsBytes`, and `Unaligned`.
impl_or_verify!(O => FromZeroes for $name<O>);
impl_or_verify!(O => FromBytes for $name<O>);
impl_or_verify!(O => AsBytes for $name<O>);
impl_or_verify!(O => Unaligned for $name<O>);
}
impl<O> $name<O> { /// The value zero. /// /// This constant should be preferred to constructing a new value /// using `new`, as `new` may perform an endianness swap depending /// on the endianness and platform. pubconst ZERO: $name<O> = $name([0u8; $bytes], PhantomData);
/// Constructs a new value from bytes which are already in the /// endianness `O`. #[inline(always)] pubconstfn from_bytes(bytes: [u8; $bytes]) -> $name<O> {
$name(bytes, PhantomData)
}
}
impl<O: ByteOrder> $name<O> { // TODO(joshlf): Make these const fns if the `ByteOrder` methods // ever become const fns.
/// Constructs a new value, possibly performing an endianness swap /// to guarantee that the returned value has endianness `O`. #[inline(always)] pubfn new(n: $native) -> $name<O> { letmut out = $name::default();
O::$write_method(&mut out.0[..], n);
out
}
/// Returns the value as a primitive type, possibly performing an /// endianness swap to guarantee that the return value has the /// endianness of the native platform. #[inline(always)] pubfn get(self) -> $native {
O::$read_method(&self.0[..])
}
/// Updates the value in place as a primitive type, possibly /// performing an endianness swap to guarantee that the stored value /// has the endianness `O`. #[inline(always)] pubfn set(&mutself, n: $native) {
O::$write_method(&mutself.0[..], n);
}
}
// The reasoning behind which traits to implement here is to only // implement traits which won't cause inference issues. Notably, // comparison traits like PartialEq and PartialOrd tend to cause // inference issues.
impl<O: ByteOrder> Debug for $name<O> { #[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()
}
}
};
}
/// 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;
/// 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);
}
}
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 = 0as $native; const MAX_VALUE: $native = $native::MAX;
type Distribution = Standard; const DIST: Standard = Standard;
#[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
};
#[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<T, F, G, H>(op: F, op_native: G, op_native_checked: Option<H>) where
T: ByteOrderType,
F: Fn(T, T) -> T,
G: Fn(T::Native, T::Native) -> T::Native,
H: Fn(T::Native, T::Native) -> Option<T::Native>,
{ letmut r = SmallRng::seed_from_u64(RNG_SEED); for _ in0..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<f32>`/`Option<f64>` 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);
}
}
#[test] fn test_debug_impl() { // Ensure that Debug applies format options to the inner value. let val = U16::<LE>::new(10);
assert_eq!(format!("{:?}", val), "U16(10)");
assert_eq!(format!("{:03?}", val), "U16(010)");
assert_eq!(format!("{:x?}", val), "U16(a)");
}
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.18 Sekunden
(vorverarbeitet am 2026-06-20)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.