#![allow(unknown_lints)]
#![deny(renamed_and_removed_lints)]
#![deny(
anonymous_parameters,
deprecated_in_future,
late_bound_lifetime_arguments,
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
path_statements,
patterns_in_fns_without_body,
rust_2018_idioms,
trivial_numeric_casts,
unreachable_pub,
unsafe_op_in_unsafe_fn,
unused_extern_crates,
unused_qualifications,
variant_size_differences
)]
#![cfg_attr(
__INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS,
deny(fuzzy_provenance_casts, lossy_provenance_casts)
)]
#![deny(
clippy::all,
clippy::alloc_instead_of_core,
clippy::arithmetic_side_effects,
clippy::as_underscore,
clippy::assertions_on_result_states,
clippy::as_conversions,
clippy::correctness,
clippy::dbg_macro,
clippy::decimal_literal_representation,
clippy::double_must_use,
clippy::get_unwrap,
clippy::indexing_slicing,
clippy::missing_inline_in_public_items,
clippy::missing_safety_doc,
clippy::must_use_candidate,
clippy::must_use_unit,
clippy::obfuscated_if_else,
clippy::perf,
clippy::print_stdout,
clippy::return_self_not_must_use,
clippy::std_instead_of_core,
clippy::style,
clippy::suspicious,
clippy::todo,
clippy::undocumented_unsafe_blocks,
clippy::unimplemented,
clippy::unnested_or_patterns,
clippy::unwrap_used,
clippy::use_debug
)]
#![allow(clippy::type_complexity)]
#![deny(
rustdoc::bare_urls,
rustdoc::broken_intra_doc_links,
rustdoc::invalid_codeblock_attributes,
rustdoc::invalid_html_tags,
rustdoc::invalid_rust_codeblocks,
rustdoc::missing_crate_level_docs,
rustdoc::private_intra_doc_links
)]
#![cfg_attr(any(test, kani), allow(
// In tests, you get line numbers and have access to source code, so panic
// messages are less important. You also often unwrap a lot, which would
// make expect'ing instead very verbose.
clippy::unwrap_used,
// In tests, there's no harm to "panic risks" - the worst that can happen is
// that your test will fail, and you'll fix it. By contrast, panic risks in
// production code introduce the possibly of code panicking unexpectedly "in
// the field".
clippy::arithmetic_side_effects,
clippy::indexing_slicing,
))]
#![cfg_attr(not(test), no_std)]
#![cfg_attr(
all(feature = "simd-nightly", any(target_arch = "x86", target_arch = "x86_64")),
feature(stdarch_x86_avx512)
)]
#![cfg_attr(
all(feature = "simd-nightly", target_arch = "arm"),
feature(stdarch_arm_dsp, stdarch_arm_neon_intrinsics)
)]
#![cfg_attr(
all(feature = "simd-nightly", any(target_arch = "powerpc", target_arch = "powerpc64")),
feature(stdarch_powerpc)
)]
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![cfg_attr(
__INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS,
feature(layout_for_ptr, strict_provenance)
)]
#[cfg(any(feature = "derive", test))]
extern crate self as zerocopy;
#[macro_use]
mod macros;
pub mod byteorder;
mod deprecated;
pub mod error;
#[doc(hidden)]
pub mod layout;
#[doc(hidden)]
pub mod macro_util;
#[doc(hidden)]
pub mod pointer;
mod r#ref;
mod util;
mod wrappers;
pub use crate::byteorder::*;
pub use crate::error::*;
pub use crate::r#ref::*;
pub use crate::wrappers::*;
use core::{
cell::{self, RefMut, UnsafeCell},
cmp::Ordering,
fmt::{self, Debug, Display, Formatter},
hash::Hasher,
marker::PhantomData,
mem::{self, ManuallyDrop, MaybeUninit},
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Wrapping,
},
ops::{Deref, DerefMut},
ptr::{self, NonNull},
slice,
sync::atomic::{
AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16, AtomicU32,
AtomicU8, AtomicUsize,
},
};
use crate::pointer::{invariant, BecauseExclusive, BecauseImmutable};
#[cfg(any(feature = "alloc", test))]
extern crate alloc;
#[cfg(any(feature = "alloc", test))]
use alloc::{boxed::Box, vec::Vec};
#[cfg(any(feature = "alloc", test, kani))]
use core::alloc::Layout;
#[doc(hidden)]
pub use crate::pointer::{Maybe, MaybeAligned, Ptr};
#[doc(hidden)]
pub use crate::layout::*;
#[allow(unused_imports)]
use crate::util::polyfills::{self, NonNullExt as _, NumExt as _};
#[rustversion::nightly]
#[cfg(all(test, not(__INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)))]
const _: () = {
#[deprecated = "some tests may be skipped due to missing RUSTFLAGS=\"--cfg __INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS\""]
const _WARNING: () = ();
#[warn(deprecated)]
_WARNING
};
#[allow(unused)]
use {FromZeros as FromZeroes, IntoBytes as AsBytes, Ref as LayoutVerified};
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::KnownLayout;
#[cfg_attr(feature = "derive", doc = "[derive]: zerocopy_derive::KnownLayout")]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.KnownLayout.html"),
)]
pub unsafe trait KnownLayout {
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
type PointerMetadata: PointerMetadata;
#[doc(hidden)]
const LAYOUT: DstLayout;
#[doc(hidden)]
fn raw_from_ptr_len(bytes: NonNull<u8>, meta: Self::PointerMetadata) -> NonNull<Self>;
#[doc(hidden)]
fn pointer_to_metadata(ptr: NonNull<Self>) -> Self::PointerMetadata;
#[doc(hidden)]
#[must_use]
#[inline(always)]
fn size_of_val_raw(ptr: NonNull<Self>) -> Option<usize> {
let meta = Self::pointer_to_metadata(ptr);
meta.size_for_metadata(Self::LAYOUT)
}
}
#[doc(hidden)]
pub trait PointerMetadata {
fn from_elem_count(elems: usize) -> Self;
fn size_for_metadata(&self, layout: DstLayout) -> Option<usize>;
}
impl PointerMetadata for () {
#[inline]
#[allow(clippy::unused_unit)]
fn from_elem_count(_elems: usize) -> () {}
#[inline]
fn size_for_metadata(&self, layout: DstLayout) -> Option<usize> {
match layout.size_info {
SizeInfo::Sized { size } => Some(size),
SizeInfo::SliceDst(_) => None,
}
}
}
impl PointerMetadata for usize {
#[inline]
fn from_elem_count(elems: usize) -> usize {
elems
}
#[inline]
fn size_for_metadata(&self, layout: DstLayout) -> Option<usize> {
match layout.size_info {
SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }) => {
let slice_len = elem_size.checked_mul(*self)?;
let without_padding = offset.checked_add(slice_len)?;
without_padding.checked_add(util::padding_needed_for(without_padding, layout.align))
}
SizeInfo::Sized { .. } => unreachable!(),
}
}
}
unsafe impl<T> KnownLayout for [T] {
#[allow(clippy::missing_inline_in_public_items)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized,
{
}
type PointerMetadata = usize;
const LAYOUT: DstLayout = DstLayout::for_slice::<T>();
#[inline(always)]
fn raw_from_ptr_len(data: NonNull<u8>, elems: usize) -> NonNull<Self> {
#[allow(unstable_name_collisions)]
NonNull::slice_from_raw_parts(data.cast::<T>(), elems)
}
#[inline(always)]
fn pointer_to_metadata(ptr: NonNull<[T]>) -> usize {
#[allow(clippy::as_conversions)]
let slc = ptr.as_ptr() as *const [()];
let slc = unsafe { &*slc };
slc.len()
}
}
#[rustfmt::skip]
impl_known_layout!(
(),
u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, f32, f64,
bool, char,
NonZeroU8, NonZeroI8, NonZeroU16, NonZeroI16, NonZeroU32, NonZeroI32,
NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128, NonZeroUsize, NonZeroIsize,
AtomicBool, AtomicI16, AtomicI32, AtomicI8, AtomicIsize, AtomicU16, AtomicU32,
AtomicU8, AtomicUsize
);
#[rustfmt::skip]
impl_known_layout!(
T => Option<T>,
T: ?Sized => PhantomData<T>,
T => Wrapping<T>,
T => MaybeUninit<T>,
T: ?Sized => *const T,
T: ?Sized => *mut T,
T => AtomicPtr<T>
);
impl_known_layout!(const N: usize, T => [T; N]);
safety_comment! {
unsafe_impl_known_layout!(#[repr([u8])] str);
unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] ManuallyDrop<T>);
unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] UnsafeCell<T>);
}
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::FromZeros;
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::Immutable;
#[cfg_attr(
feature = "derive",
doc = "[derive]: zerocopy_derive::Immutable",
doc = "[derive-analysis]: zerocopy_derive::Immutable#analysis"
)]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Immutable.html"),
doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Immutable.html#analysis"),
)]
pub unsafe trait Immutable {
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
}
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::TryFromBytes;
#[cfg_attr(feature = "derive", doc = "[derive]: zerocopy_derive::TryFromBytes")]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.TryFromBytes.html"),
)]
pub unsafe trait TryFromBytes {
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
#[doc(hidden)]
fn is_bit_valid<A: invariant::Aliasing + invariant::AtLeast<invariant::Shared>>(
candidate: Maybe<'_, Self, A>,
) -> bool;
#[must_use = "has no side effects"]
#[inline]
fn try_ref_from(candidate: &[u8]) -> Result<&Self, TryCastError<&[u8], Self>>
where
Self: KnownLayout + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
match Ptr::from_ref(candidate).try_cast_into_no_leftover::<Self, BecauseImmutable>() {
Ok(candidate) => {
match candidate.try_into_valid() {
Ok(valid) => Ok(valid.as_ref()),
Err(e) => {
Err(e.map_src(|src| src.as_bytes::<BecauseImmutable>().as_ref()).into())
}
}
}
Err(e) => Err(e.map_src(Ptr::as_ref).into()),
}
}
#[must_use = "has no side effects"]
#[inline]
fn try_ref_from_prefix(candidate: &[u8]) -> Result<(&Self, &[u8]), TryCastError<&[u8], Self>>
where
Self: KnownLayout + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
try_ref_from_prefix_suffix(candidate, CastType::Prefix)
}
#[must_use = "has no side effects"]
#[inline]
fn try_ref_from_suffix(candidate: &[u8]) -> Result<(&[u8], &Self), TryCastError<&[u8], Self>>
where
Self: KnownLayout + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
try_ref_from_prefix_suffix(candidate, CastType::Suffix).map(swap)
}
#[must_use = "has no side effects"]
#[inline]
fn try_mut_from(bytes: &mut [u8]) -> Result<&mut Self, TryCastError<&mut [u8], Self>>
where
Self: KnownLayout,
{
util::assert_dst_is_not_zst::<Self>();
match Ptr::from_mut(bytes).try_cast_into_no_leftover::<Self, BecauseExclusive>() {
Ok(candidate) => {
match candidate.try_into_valid() {
Ok(candidate) => Ok(candidate.as_mut()),
Err(e) => {
Err(e.map_src(|src| src.as_bytes::<BecauseExclusive>().as_mut()).into())
}
}
}
Err(e) => Err(e.map_src(Ptr::as_mut).into()),
}
}
#[must_use = "has no side effects"]
#[inline]
fn try_mut_from_prefix(
candidate: &mut [u8],
) -> Result<(&mut Self, &mut [u8]), TryCastError<&mut [u8], Self>>
where
Self: KnownLayout,
{
util::assert_dst_is_not_zst::<Self>();
try_mut_from_prefix_suffix(candidate, CastType::Prefix)
}
#[must_use = "has no side effects"]
#[inline]
fn try_mut_from_suffix(
candidate: &mut [u8],
) -> Result<(&mut [u8], &mut Self), TryCastError<&mut [u8], Self>>
where
Self: KnownLayout,
{
util::assert_dst_is_not_zst::<Self>();
try_mut_from_prefix_suffix(candidate, CastType::Suffix).map(swap)
}
#[must_use = "has no side effects"]
#[inline]
fn try_read_from(bytes: &[u8]) -> Result<Self, TryReadError<&[u8], Self>>
where
Self: Sized,
{
let mut candidate = match MaybeUninit::<Self>::read_from(bytes) {
Ok(candidate) => candidate,
Err(e) => {
return Err(TryReadError::Size(e.with_dst()));
}
};
let c_ptr = Ptr::from_mut(&mut candidate);
let c_ptr = c_ptr.transparent_wrapper_into_inner();
let c_ptr = unsafe { c_ptr.assume_validity::<invariant::Initialized>() };
if !Self::is_bit_valid(c_ptr.forget_aligned()) {
return Err(ValidityError::new(bytes).into());
}
Ok(unsafe { candidate.assume_init() })
}
}
#[inline(always)]
fn try_ref_from_prefix_suffix<T: TryFromBytes + KnownLayout + Immutable + ?Sized>(
candidate: &[u8],
cast_type: CastType,
) -> Result<(&T, &[u8]), TryCastError<&[u8], T>> {
match Ptr::from_ref(candidate).try_cast_into::<T, BecauseImmutable>(cast_type) {
Ok((candidate, prefix_suffix)) => {
match candidate.try_into_valid() {
Ok(valid) => Ok((valid.as_ref(), prefix_suffix.as_ref())),
Err(e) => Err(e.map_src(|src| src.as_bytes::<BecauseImmutable>().as_ref()).into()),
}
}
Err(e) => Err(e.map_src(Ptr::as_ref).into()),
}
}
#[inline(always)]
fn try_mut_from_prefix_suffix<T: TryFromBytes + KnownLayout + ?Sized>(
candidate: &mut [u8],
cast_type: CastType,
) -> Result<(&mut T, &mut [u8]), TryCastError<&mut [u8], T>> {
match Ptr::from_mut(candidate).try_cast_into::<T, BecauseExclusive>(cast_type) {
Ok((candidate, prefix_suffix)) => {
match candidate.try_into_valid() {
Ok(valid) => Ok((valid.as_mut(), prefix_suffix.as_mut())),
Err(e) => Err(e.map_src(|src| src.as_bytes::<BecauseExclusive>().as_mut()).into()),
}
}
Err(e) => Err(e.map_src(Ptr::as_mut).into()),
}
}
#[inline(always)]
fn swap<T, U>((t, u): (T, U)) -> (U, T) {
(u, t)
}
#[cfg_attr(
feature = "derive",
doc = "[derive]: zerocopy_derive::FromZeros",
doc = "[derive-analysis]: zerocopy_derive::FromZeros#analysis"
)]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeros.html"),
doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeros.html#analysis"),
)]
pub unsafe trait FromZeros: TryFromBytes {
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
#[inline(always)]
fn zero(&mut self) {
let slf: *mut Self = self;
let len = mem::size_of_val(self);
unsafe { ptr::write_bytes(slf.cast::<u8>(), 0, len) };
}
#[must_use = "has no side effects"]
#[inline(always)]
fn new_zeroed() -> Self
where
Self: Sized,
{
unsafe { mem::zeroed() }
}
#[must_use = "has no side effects (other than allocation)"]
#[cfg(any(feature = "alloc", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
fn new_box_zeroed() -> Box<Self>
where
Self: Sized,
{
let layout = Layout::new::<Self>();
if layout.size() == 0 {
return Box::new(Self::new_zeroed());
}
#[allow(clippy::undocumented_unsafe_blocks)]
let ptr = unsafe { alloc::alloc::alloc_zeroed(layout).cast::<Self>() };
if ptr.is_null() {
alloc::alloc::handle_alloc_error(layout);
}
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe {
Box::from_raw(ptr)
}
}
#[must_use = "has no side effects (other than allocation)"]
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline]
fn new_box_slice_zeroed(len: usize) -> Box<[Self]>
where
Self: Sized,
{
let size = mem::size_of::<Self>()
.checked_mul(len)
.expect("mem::size_of::<Self>() * len overflows `usize`");
let align = mem::align_of::<Self>();
#[allow(clippy::as_conversions)]
let max_alloc = (isize::MAX as usize).saturating_sub(align);
assert!(size <= max_alloc);
let layout =
Layout::from_size_align(size, align).expect("total allocation size overflows `isize`");
let ptr = if layout.size() != 0 {
#[allow(clippy::undocumented_unsafe_blocks)]
let ptr = unsafe { alloc::alloc::alloc_zeroed(layout).cast::<Self>() };
if ptr.is_null() {
alloc::alloc::handle_alloc_error(layout);
}
ptr
} else {
NonNull::<Self>::dangling().as_ptr()
};
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe {
Box::from_raw(slice::from_raw_parts_mut(ptr, len))
}
}
#[must_use = "has no side effects (other than allocation)"]
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[inline(always)]
fn new_vec_zeroed(len: usize) -> Vec<Self>
where
Self: Sized,
{
Self::new_box_slice_zeroed(len).into()
}
}
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::FromBytes;
#[cfg_attr(
feature = "derive",
doc = "[derive]: zerocopy_derive::FromBytes",
doc = "[derive-analysis]: zerocopy_derive::FromBytes#analysis"
)]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromBytes.html"),
doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromBytes.html#analysis"),
)]
pub unsafe trait FromBytes: FromZeros {
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
#[must_use = "has no side effects"]
#[inline]
fn ref_from(bytes: &[u8]) -> Result<&Self, CastError<&[u8], Self>>
where
Self: KnownLayout + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
match Ptr::from_ref(bytes).try_cast_into_no_leftover::<_, BecauseImmutable>() {
Ok(ptr) => Ok(ptr.bikeshed_recall_valid().as_ref()),
Err(err) => Err(err.map_src(|src| src.as_ref())),
}
}
#[must_use = "has no side effects"]
#[inline]
fn ref_from_prefix(bytes: &[u8]) -> Result<(&Self, &[u8]), CastError<&[u8], Self>>
where
Self: KnownLayout + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
ref_from_prefix_suffix(bytes, CastType::Prefix)
}
#[must_use = "has no side effects"]
#[inline]
fn ref_from_suffix(bytes: &[u8]) -> Result<(&[u8], &Self), CastError<&[u8], Self>>
where
Self: Immutable + KnownLayout,
{
util::assert_dst_is_not_zst::<Self>();
ref_from_prefix_suffix(bytes, CastType::Suffix).map(swap)
}
#[must_use = "has no side effects"]
#[inline]
fn mut_from(bytes: &mut [u8]) -> Result<&mut Self, CastError<&mut [u8], Self>>
where
Self: IntoBytes + KnownLayout,
{
util::assert_dst_is_not_zst::<Self>();
match Ptr::from_mut(bytes).try_cast_into_no_leftover::<_, BecauseExclusive>() {
Ok(ptr) => Ok(ptr.bikeshed_recall_valid().as_mut()),
Err(err) => Err(err.map_src(|src| src.as_mut())),
}
}
#[must_use = "has no side effects"]
#[inline]
fn mut_from_prefix(
bytes: &mut [u8],
) -> Result<(&mut Self, &mut [u8]), CastError<&mut [u8], Self>>
where
Self: IntoBytes + KnownLayout,
{
util::assert_dst_is_not_zst::<Self>();
mut_from_prefix_suffix(bytes, CastType::Prefix)
}
#[must_use = "has no side effects"]
#[inline]
fn mut_from_suffix(
bytes: &mut [u8],
) -> Result<(&mut [u8], &mut Self), CastError<&mut [u8], Self>>
where
Self: IntoBytes + KnownLayout,
{
util::assert_dst_is_not_zst::<Self>();
mut_from_prefix_suffix(bytes, CastType::Suffix).map(swap)
}
#[must_use = "has no side effects"]
#[inline]
fn ref_from_prefix_with_trailing_elements(
bytes: &[u8],
count: usize,
) -> Result<(&Self, &[u8]), CastError<&[u8], Self>>
where
Self: KnownLayout<PointerMetadata = usize> + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
Ref::<_, Self>::with_trailing_elements_from_prefix(bytes, count)
.map(|(r, b)| (r.into_ref(), b))
}
#[deprecated(
since = "0.8.0",
note = "renamed to `FromBytes::from_prefix_with_trailing_elements`"
)]
#[doc(hidden)]
#[must_use = "has no side effects"]
#[inline]
fn slice_from_prefix(bytes: &[u8], count: usize) -> Option<(&[Self], &[u8])>
where
Self: Sized + Immutable,
{
<[Self]>::ref_from_prefix_with_trailing_elements(bytes, count).ok()
}
#[must_use = "has no side effects"]
#[inline]
fn ref_from_suffix_with_trailing_elements(
bytes: &[u8],
count: usize,
) -> Result<(&[u8], &Self), CastError<&[u8], Self>>
where
Self: KnownLayout<PointerMetadata = usize> + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
Ref::<_, Self>::with_trailing_elements_from_suffix(bytes, count)
.map(|(b, r)| (b, r.into_ref()))
}
#[deprecated(
since = "0.8.0",
note = "renamed to `FromBytes::from_prefix_with_trailing_elements`"
)]
#[doc(hidden)]
#[must_use = "has no side effects"]
#[inline]
fn slice_from_suffix(bytes: &[u8], count: usize) -> Option<(&[u8], &[Self])>
where
Self: Sized + Immutable,
{
<[Self]>::ref_from_suffix_with_trailing_elements(bytes, count).ok()
}
#[deprecated(since = "0.8.0", note = "`FromBytes::mut_from` now supports slices")]
#[must_use = "has no side effects"]
#[doc(hidden)]
#[inline]
fn mut_slice_from(bytes: &mut [u8]) -> Option<&mut [Self]>
where
Self: Sized + IntoBytes + Immutable,
{
<[Self]>::mut_from(bytes).ok()
}
#[must_use = "has no side effects"]
#[inline]
fn mut_from_prefix_with_trailing_elements(
bytes: &mut [u8],
count: usize,
) -> Result<(&mut Self, &mut [u8]), CastError<&mut [u8], Self>>
where
Self: IntoBytes + KnownLayout<PointerMetadata = usize> + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
Ref::<_, Self>::with_trailing_elements_from_prefix(bytes, count)
.map(|(r, b)| (r.into_mut(), b))
}
#[deprecated(
since = "0.8.0",
note = "renamed to `FromBytes::mut_from_prefix_with_trailing_elements`"
)]
#[doc(hidden)]
#[must_use = "has no side effects"]
#[inline]
fn mut_slice_from_prefix(bytes: &mut [u8], count: usize) -> Option<(&mut [Self], &mut [u8])>
where
Self: Sized + IntoBytes + Immutable,
{
<[Self]>::mut_from_prefix_with_trailing_elements(bytes, count).ok()
}
#[must_use = "has no side effects"]
#[inline]
fn mut_from_suffix_with_trailing_elements(
bytes: &mut [u8],
count: usize,
) -> Result<(&mut [u8], &mut Self), CastError<&mut [u8], Self>>
where
Self: IntoBytes + KnownLayout<PointerMetadata = usize> + Immutable,
{
util::assert_dst_is_not_zst::<Self>();
Ref::<_, Self>::with_trailing_elements_from_suffix(bytes, count)
.map(|(b, r)| (b, r.into_mut()))
}
#[deprecated(
since = "0.8.0",
note = "renamed to `FromBytes::mut_from_suffix_with_trailing_elements`"
)]
#[doc(hidden)]
#[inline]
fn mut_slice_from_suffix(bytes: &mut [u8], count: usize) -> Option<(&mut [u8], &mut [Self])>
where
Self: Sized + IntoBytes + Immutable,
{
<[Self]>::mut_from_suffix_with_trailing_elements(bytes, count).ok()
}
#[must_use = "has no side effects"]
#[inline]
fn read_from(bytes: &[u8]) -> Result<Self, SizeError<&[u8], Self>>
where
Self: Sized,
{
match Ref::<_, Unalign<Self>>::new_sized(bytes) {
Ok(r) => Ok(r.read().into_inner()),
Err(CastError::Size(e)) => Err(e.with_dst()),
Err(CastError::Alignment(_)) => unreachable!(),
Err(CastError::Validity(i)) => match i {},
}
}
#[must_use = "has no side effects"]
#[inline]
fn read_from_prefix(bytes: &[u8]) -> Result<Self, SizeError<&[u8], Self>>
where
Self: Sized,
{
match Ref::<_, Unalign<Self>>::new_sized_from_prefix(bytes) {
Ok((r, _)) => Ok(r.read().into_inner()),
Err(CastError::Size(e)) => Err(e.with_dst()),
Err(CastError::Alignment(_)) => unreachable!(),
Err(CastError::Validity(i)) => match i {},
}
}
#[must_use = "has no side effects"]
#[inline]
fn read_from_suffix(bytes: &[u8]) -> Result<Self, CastError<&[u8], Self>>
where
Self: Sized,
{
match Ref::<_, Unalign<Self>>::new_sized_from_suffix(bytes) {
Ok((_, r)) => Ok(r.read().into_inner()),
Err(CastError::Size(e)) => Err(CastError::Size(e.with_dst())),
Err(CastError::Alignment(_)) => unreachable!(),
Err(CastError::Validity(i)) => match i {},
}
}
#[deprecated(since = "0.8.0", note = "`FromBytes::ref_from` now supports slices")]
#[allow(clippy::must_use_candidate)]
#[doc(hidden)]
#[inline]
fn slice_from(bytes: &[u8]) -> Option<&[Self]>
where
Self: Sized + Immutable,
{
<[Self]>::ref_from(bytes).ok()
}
}
#[inline(always)]
fn ref_from_prefix_suffix<T>(
bytes: &[u8],
cast_type: CastType,
) -> Result<(&T, &[u8]), CastError<&[u8], T>>
where
T: ?Sized + FromBytes + KnownLayout + Immutable,
{
let (slf, suffix) = Ptr::from_ref(bytes)
.try_cast_into::<_, BecauseImmutable>(cast_type)
.map_err(|err| err.map_src(|s| s.as_ref()))?;
Ok((slf.bikeshed_recall_valid().as_ref(), suffix.as_ref()))
}
#[inline(always)]
fn mut_from_prefix_suffix<T>(
bytes: &mut [u8],
cast_type: CastType,
) -> Result<(&mut T, &mut [u8]), CastError<&mut [u8], T>>
where
T: ?Sized + FromBytes + KnownLayout,
{
let (slf, suffix) = Ptr::from_mut(bytes)
.try_cast_into::<_, BecauseExclusive>(cast_type)
.map_err(|err| err.map_src(|s| s.as_mut()))?;
Ok((slf.bikeshed_recall_valid().as_mut(), suffix.as_mut()))
}
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::IntoBytes;
#[cfg_attr(
feature = "derive",
doc = "[derive]: zerocopy_derive::IntoBytes",
doc = "[derive-analysis]: zerocopy_derive::IntoBytes#analysis"
)]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.IntoBytes.html"),
doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.IntoBytes.html#analysis"),
)]
pub unsafe trait IntoBytes {
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
#[must_use = "has no side effects"]
#[inline(always)]
fn as_bytes(&self) -> &[u8]
where
Self: Immutable,
{
let len = mem::size_of_val(self);
let slf: *const Self = self;
unsafe { slice::from_raw_parts(slf.cast::<u8>(), len) }
}
#[must_use = "has no side effects"]
#[inline(always)]
fn as_mut_bytes(&mut self) -> &mut [u8]
where
Self: FromBytes,
{
let len = mem::size_of_val(self);
let slf: *mut Self = self;
unsafe { slice::from_raw_parts_mut(slf.cast::<u8>(), len) }
}
#[must_use = "callers should check the return value to see if the operation succeeded"]
#[inline]
fn write_to(&self, bytes: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
where
Self: Immutable,
{
if bytes.len() != mem::size_of_val(self) {
return Err(SizeError::new(self));
}
bytes.copy_from_slice(self.as_bytes());
Ok(())
}
#[must_use = "callers should check the return value to see if the operation succeeded"]
#[inline]
fn write_to_prefix(&self, bytes: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
where
Self: Immutable,
{
let size = mem::size_of_val(self);
match bytes.get_mut(..size) {
Some(bytes) => {
bytes.copy_from_slice(self.as_bytes());
Ok(())
}
None => Err(SizeError::new(self)),
}
}
#[must_use = "callers should check the return value to see if the operation succeeded"]
#[inline]
fn write_to_suffix(&self, bytes: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
where
Self: Immutable,
{
let start = if let Some(start) = bytes.len().checked_sub(mem::size_of_val(self)) {
start
} else {
return Err(SizeError::new(self));
};
let bytes = if let Some(bytes) = bytes.get_mut(start..) {
bytes
} else {
return Err(SizeError::new(self));
};
bytes.copy_from_slice(self.as_bytes());
Ok(())
}
#[deprecated(since = "0.8.0", note = "`IntoBytes::as_bytes_mut` was renamed to `as_mut_bytes`")]
#[doc(hidden)]
#[inline]
fn as_bytes_mut(&mut self) -> &mut [u8]
where
Self: FromBytes,
{
self.as_mut_bytes()
}
}
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::Unaligned;
#[cfg_attr(
feature = "derive",
doc = "[derive]: zerocopy_derive::Unaligned",
doc = "[derive-analysis]: zerocopy_derive::Unaligned#analysis"
)]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Unaligned.html"),
doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.Unaligned.html#analysis"),
)]
pub unsafe trait Unaligned {
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
}
safety_comment! {
unsafe_impl!((): Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_unaligned!(());
}
safety_comment! {
unsafe_impl!(u8: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
unsafe_impl!(i8: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_unaligned!(u8, i8);
unsafe_impl!(u16: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(i16: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(u32: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(i32: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(u64: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(i64: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(u128: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(i128: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(usize: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(isize: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(f32: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(f64: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes);
}
safety_comment! {
unsafe_impl!(bool: Immutable, FromZeros, IntoBytes, Unaligned);
assert_unaligned!(bool);
unsafe_impl!(bool: TryFromBytes; |byte: MaybeAligned<u8>| *byte.unaligned_as_ref() < 2);
}
safety_comment! {
unsafe_impl!(char: Immutable, FromZeros, IntoBytes);
unsafe_impl!(char: TryFromBytes; |candidate: MaybeAligned<u32>| {
let candidate = candidate.read_unaligned();
char::from_u32(candidate).is_some()
});
}
safety_comment! {
unsafe_impl!(str: Immutable, FromZeros, IntoBytes, Unaligned);
unsafe_impl!(str: TryFromBytes; |candidate: MaybeAligned<[u8]>| {
let candidate = candidate.unaligned_as_ref();
core::str::from_utf8(candidate).is_ok()
});
}
safety_comment! {
unsafe_impl!(NonZeroU8: Immutable, IntoBytes, Unaligned);
unsafe_impl!(NonZeroI8: Immutable, IntoBytes, Unaligned);
assert_unaligned!(NonZeroU8, NonZeroI8);
unsafe_impl!(NonZeroU16: Immutable, IntoBytes);
unsafe_impl!(NonZeroI16: Immutable, IntoBytes);
unsafe_impl!(NonZeroU32: Immutable, IntoBytes);
unsafe_impl!(NonZeroI32: Immutable, IntoBytes);
unsafe_impl!(NonZeroU64: Immutable, IntoBytes);
unsafe_impl!(NonZeroI64: Immutable, IntoBytes);
unsafe_impl!(NonZeroU128: Immutable, IntoBytes);
unsafe_impl!(NonZeroI128: Immutable, IntoBytes);
unsafe_impl!(NonZeroUsize: Immutable, IntoBytes);
unsafe_impl!(NonZeroIsize: Immutable, IntoBytes);
unsafe_impl!(NonZeroU8: TryFromBytes; |n: MaybeAligned<u8>| NonZeroU8::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroI8: TryFromBytes; |n: MaybeAligned<i8>| NonZeroI8::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroU16: TryFromBytes; |n: MaybeAligned<u16>| NonZeroU16::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroI16: TryFromBytes; |n: MaybeAligned<i16>| NonZeroI16::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroU32: TryFromBytes; |n: MaybeAligned<u32>| NonZeroU32::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroI32: TryFromBytes; |n: MaybeAligned<i32>| NonZeroI32::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroU64: TryFromBytes; |n: MaybeAligned<u64>| NonZeroU64::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroI64: TryFromBytes; |n: MaybeAligned<i64>| NonZeroI64::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroU128: TryFromBytes; |n: MaybeAligned<u128>| NonZeroU128::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroI128: TryFromBytes; |n: MaybeAligned<i128>| NonZeroI128::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroUsize: TryFromBytes; |n: MaybeAligned<usize>| NonZeroUsize::new(n.read_unaligned()).is_some());
unsafe_impl!(NonZeroIsize: TryFromBytes; |n: MaybeAligned<isize>| NonZeroIsize::new(n.read_unaligned()).is_some());
}
safety_comment! {
unsafe_impl!(Option<NonZeroU8>: TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
unsafe_impl!(Option<NonZeroI8>: TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_unaligned!(Option<NonZeroU8>, Option<NonZeroI8>);
unsafe_impl!(Option<NonZeroU16>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroI16>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroU32>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroI32>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroU64>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroI64>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroU128>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroI128>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroUsize>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
unsafe_impl!(Option<NonZeroIsize>: TryFromBytes, FromZeros, FromBytes, IntoBytes);
}
safety_comment! {
#[cfg(feature = "alloc")]
unsafe_impl!(
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
T: Sized => Immutable for Box<T>
);
}
safety_comment! {
#[cfg(feature = "alloc")]
unsafe_impl!(
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
T => TryFromBytes for Option<Box<T>>;
|c: Maybe<Option<Box<T>>>| pointer::is_zeroed(c)
);
#[cfg(feature = "alloc")]
unsafe_impl!(
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
T => FromZeros for Option<Box<T>>
);
unsafe_impl!(
T => TryFromBytes for Option<&'_ T>;
|c: Maybe<Option<&'_ T>>| pointer::is_zeroed(c)
);
unsafe_impl!(T => FromZeros for Option<&'_ T>);
unsafe_impl!(
T => TryFromBytes for Option<&'_ mut T>;
|c: Maybe<Option<&'_ mut T>>| pointer::is_zeroed(c)
);
unsafe_impl!(T => FromZeros for Option<&'_ mut T>);
unsafe_impl!(
T => TryFromBytes for Option<NonNull<T>>;
|c: Maybe<Option<NonNull<T>>>| pointer::is_zeroed(c)
);
unsafe_impl!(T => FromZeros for Option<NonNull<T>>);
unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeros for opt_fn!(...));
unsafe_impl_for_power_set!(
A, B, C, D, E, F, G, H, I, J, K, L -> M => TryFromBytes for opt_fn!(...);
|c: Maybe<Self>| pointer::is_zeroed(c)
);
unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeros for opt_extern_c_fn!(...));
unsafe_impl_for_power_set!(
A, B, C, D, E, F, G, H, I, J, K, L -> M => TryFromBytes for opt_extern_c_fn!(...);
|c: Maybe<Self>| pointer::is_zeroed(c)
);
}
safety_comment! {
unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => Immutable for opt_fn!(...));
unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => Immutable for opt_extern_c_fn!(...));
}
macro_rules! impl_traits_for_atomics {
($($atomics:ident [$inners:ident]),* $(,)?) => {
$(
impl_for_transparent_wrapper!(TryFromBytes for $atomics [UnsafeCell<$inners>]);
impl_for_transparent_wrapper!(FromZeros for $atomics [UnsafeCell<$inners>]);
impl_for_transparent_wrapper!(FromBytes for $atomics [UnsafeCell<$inners>]);
impl_for_transparent_wrapper!(IntoBytes for $atomics [UnsafeCell<$inners>]);
)*
};
}
#[rustfmt::skip]
impl_traits_for_atomics!(
AtomicBool [bool],
AtomicI16 [i16], AtomicI32 [i32], AtomicI8 [i8], AtomicIsize [isize],
AtomicU16 [u16], AtomicU32 [u32], AtomicU8 [u8], AtomicUsize [usize],
);
safety_comment! {
unsafe_impl!(AtomicBool: Unaligned);
unsafe_impl!(AtomicU8: Unaligned);
unsafe_impl!(AtomicI8: Unaligned);
assert_unaligned!(AtomicBool, AtomicU8, AtomicI8);
}
safety_comment! {
unsafe_impl!(T: ?Sized => Immutable for PhantomData<T>);
unsafe_impl!(T: ?Sized => TryFromBytes for PhantomData<T>);
unsafe_impl!(T: ?Sized => FromZeros for PhantomData<T>);
unsafe_impl!(T: ?Sized => FromBytes for PhantomData<T>);
unsafe_impl!(T: ?Sized => IntoBytes for PhantomData<T>);
unsafe_impl!(T: ?Sized => Unaligned for PhantomData<T>);
assert_unaligned!(PhantomData<()>, PhantomData<u8>, PhantomData<u64>);
}
impl_for_transparent_wrapper!(T: Immutable => Immutable for Wrapping<T>);
impl_for_transparent_wrapper!(T: TryFromBytes => TryFromBytes for Wrapping<T>);
impl_for_transparent_wrapper!(T: FromZeros => FromZeros for Wrapping<T>);
impl_for_transparent_wrapper!(T: FromBytes => FromBytes for Wrapping<T>);
impl_for_transparent_wrapper!(T: IntoBytes => IntoBytes for Wrapping<T>);
impl_for_transparent_wrapper!(T: Unaligned => Unaligned for Wrapping<T>);
assert_unaligned!(Wrapping<()>, Wrapping<u8>);
safety_comment! {
unsafe_impl!(T => TryFromBytes for MaybeUninit<T>);
unsafe_impl!(T => FromZeros for MaybeUninit<T>);
unsafe_impl!(T => FromBytes for MaybeUninit<T>);
}
impl_for_transparent_wrapper!(T: Immutable => Immutable for MaybeUninit<T>);
impl_for_transparent_wrapper!(T: Unaligned => Unaligned for MaybeUninit<T>);
assert_unaligned!(MaybeUninit<()>, MaybeUninit<u8>);
impl_for_transparent_wrapper!(T: ?Sized + Immutable => Immutable for ManuallyDrop<T>);
impl_for_transparent_wrapper!(T: ?Sized + TryFromBytes => TryFromBytes for ManuallyDrop<T>);
impl_for_transparent_wrapper!(T: ?Sized + FromZeros => FromZeros for ManuallyDrop<T>);
impl_for_transparent_wrapper!(T: ?Sized + FromBytes => FromBytes for ManuallyDrop<T>);
impl_for_transparent_wrapper!(T: ?Sized + IntoBytes => IntoBytes for ManuallyDrop<T>);
impl_for_transparent_wrapper!(T: ?Sized + Unaligned => Unaligned for ManuallyDrop<T>);
assert_unaligned!(ManuallyDrop<()>, ManuallyDrop<u8>);
impl_for_transparent_wrapper!(T: FromZeros => FromZeros for UnsafeCell<T>);
impl_for_transparent_wrapper!(T: FromBytes => FromBytes for UnsafeCell<T>);
impl_for_transparent_wrapper!(T: ?Sized + IntoBytes => IntoBytes for UnsafeCell<T>);
impl_for_transparent_wrapper!(T: ?Sized + Unaligned => Unaligned for UnsafeCell<T>);
assert_unaligned!(UnsafeCell<()>, UnsafeCell<u8>);
unsafe impl<T: TryFromBytes> TryFromBytes for UnsafeCell<T> {
#[allow(clippy::missing_inline_in_public_items)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized,
{
}
#[inline]
fn is_bit_valid<A: invariant::Aliasing + invariant::AtLeast<invariant::Shared>>(
candidate: Maybe<'_, Self, A>,
) -> bool {
let c = candidate.into_exclusive_or_post_monomorphization_error();
let c = unsafe {
c.cast_unsized(|c: *mut UnsafeCell<T>| c.cast::<UnsafeCell<Unalign<MaybeUninit<T>>>>())
};
let c = unsafe { c.assume_valid() };
let c = c.bikeshed_recall_aligned();
let c: &mut Unalign<MaybeUninit<T>> = c.as_mut().get_mut();
let c: Ptr<'_, MaybeUninit<T>, _> = Ptr::from_mut(c).transparent_wrapper_into_inner();
let c: Ptr<'_, T, _> = c.transparent_wrapper_into_inner();
let c = unsafe { c.assume_initialized() };
let _: Ptr<'_, UnsafeCell<T>, (_, _, invariant::Initialized)> = candidate;
T::is_bit_valid(c.forget_exclusive())
}
}
safety_comment! {
unsafe_impl!(const N: usize, T: Immutable => Immutable for [T; N]);
unsafe_impl!(const N: usize, T: TryFromBytes => TryFromBytes for [T; N]; |c: Maybe<[T; N]>| {
<[T] as TryFromBytes>::is_bit_valid(c.as_slice())
});
unsafe_impl!(const N: usize, T: FromZeros => FromZeros for [T; N]);
unsafe_impl!(const N: usize, T: FromBytes => FromBytes for [T; N]);
unsafe_impl!(const N: usize, T: IntoBytes => IntoBytes for [T; N]);
unsafe_impl!(const N: usize, T: Unaligned => Unaligned for [T; N]);
assert_unaligned!([(); 0], [(); 1], [u8; 0], [u8; 1]);
unsafe_impl!(T: Immutable => Immutable for [T]);
unsafe_impl!(T: TryFromBytes => TryFromBytes for [T]; |c: Maybe<[T]>| {
c.iter().all(<T as TryFromBytes>::is_bit_valid)
});
unsafe_impl!(T: FromZeros => FromZeros for [T]);
unsafe_impl!(T: FromBytes => FromBytes for [T]);
unsafe_impl!(T: IntoBytes => IntoBytes for [T]);
unsafe_impl!(T: Unaligned => Unaligned for [T]);
}
safety_comment! {
unsafe_impl!(T: ?Sized => Immutable for *const T);
unsafe_impl!(T: ?Sized => Immutable for *mut T);
unsafe_impl!(T => TryFromBytes for *const T; |c: Maybe<*const T>| {
pointer::is_zeroed(c)
});
unsafe_impl!(T => FromZeros for *const T);
unsafe_impl!(T => TryFromBytes for *mut T; |c: Maybe<*const T>| {
pointer::is_zeroed(c)
});
unsafe_impl!(T => FromZeros for *mut T);
}
safety_comment! {
unsafe_impl!(T: ?Sized => Immutable for NonNull<T>);
}
safety_comment! {
unsafe_impl!(T: ?Sized => Immutable for &'_ T);
unsafe_impl!(T: ?Sized => Immutable for &'_ mut T);
}
safety_comment! {
unsafe_impl!(T: Immutable => Immutable for Option<T>);
}
#[cfg(feature = "simd")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "simd")))]
mod simd {
#[allow(unused_macros)] macro_rules! simd_arch_mod {
(#[cfg $cfg:tt] $arch:ident, $mod:ident, $($typ:ident),*) => {
#[cfg $cfg]
#[cfg_attr(doc_cfg, doc(cfg $cfg))]
mod $mod {
use core::arch::$arch::{$($typ),*};
use crate::*;
impl_known_layout!($($typ),*);
safety_comment! {
$( unsafe_impl!($typ: Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes); )*
}
}
};
}
#[rustfmt::skip]
const _: () = {
simd_arch_mod!(
#[cfg(target_arch = "x86")]
x86, x86, __m128, __m128d, __m128i, __m256, __m256d, __m256i
);
simd_arch_mod!(
#[cfg(all(feature = "simd-nightly", target_arch = "x86"))]
x86, x86_nightly, __m512bh, __m512, __m512d, __m512i
);
simd_arch_mod!(
#[cfg(target_arch = "x86_64")]
x86_64, x86_64, __m128, __m128d, __m128i, __m256, __m256d, __m256i
);
simd_arch_mod!(
#[cfg(all(feature = "simd-nightly", target_arch = "x86_64"))]
x86_64, x86_64_nightly, __m512bh, __m512, __m512d, __m512i
);
simd_arch_mod!(
#[cfg(target_arch = "wasm32")]
wasm32, wasm32, v128
);
simd_arch_mod!(
#[cfg(all(feature = "simd-nightly", target_arch = "powerpc"))]
powerpc, powerpc, vector_bool_long, vector_double, vector_signed_long, vector_unsigned_long
);
simd_arch_mod!(
#[cfg(all(feature = "simd-nightly", target_arch = "powerpc64"))]
powerpc64, powerpc64, vector_bool_long, vector_double, vector_signed_long, vector_unsigned_long
);
#[cfg(zerocopy_aarch64_simd)]
simd_arch_mod!(
#[cfg(target_arch = "aarch64")]
aarch64, aarch64, float32x2_t, float32x4_t, float64x1_t, float64x2_t, int8x8_t, int8x8x2_t,
int8x8x3_t, int8x8x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int16x4_t,
int16x8_t, int32x2_t, int32x4_t, int64x1_t, int64x2_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t,
poly8x8x4_t, poly8x16_t, poly8x16x2_t, poly8x16x3_t, poly8x16x4_t, poly16x4_t, poly16x8_t,
poly64x1_t, poly64x2_t, uint8x8_t, uint8x8x2_t, uint8x8x3_t, uint8x8x4_t, uint8x16_t,
uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint16x4_t, uint16x8_t, uint32x2_t, uint32x4_t,
uint64x1_t, uint64x2_t
);
simd_arch_mod!(
#[cfg(all(feature = "simd-nightly", target_arch = "arm"))]
arm, arm, int8x4_t, uint8x4_t
);
};
}
#[macro_export]
macro_rules! transmute {
($e:expr) => {{
let e = $e;
if false {
struct AssertIsIntoBytes<T: $crate::IntoBytes>(T);
let _ = AssertIsIntoBytes(e);
struct AssertIsFromBytes<U: $crate::FromBytes>(U);
#[allow(unused, unreachable_code)]
let u = AssertIsFromBytes(loop {});
u.0
} else {
let u = unsafe {
#[allow(clippy::useless_transmute, clippy::missing_transmute_annotations)]
$crate::macro_util::core_reexport::mem::transmute(e)
};
$crate::macro_util::must_use(u)
}
}}
}
#[macro_export]
macro_rules! transmute_ref {
($e:expr) => {{
let e: &_ = $e;
#[allow(unused, clippy::diverging_sub_expression)]
if false {
struct AssertSrcIsSized<'a, T: ::core::marker::Sized>(&'a T);
struct AssertSrcIsIntoBytes<'a, T: ?::core::marker::Sized + $crate::IntoBytes>(&'a T);
struct AssertSrcIsImmutable<'a, T: ?::core::marker::Sized + $crate::Immutable>(&'a T);
struct AssertDstIsSized<'a, T: ::core::marker::Sized>(&'a T);
struct AssertDstIsFromBytes<'a, U: ?::core::marker::Sized + $crate::FromBytes>(&'a U);
struct AssertDstIsImmutable<'a, T: ?::core::marker::Sized + $crate::Immutable>(&'a T);
let _ = AssertSrcIsSized(e);
let _ = AssertSrcIsIntoBytes(e);
let _ = AssertSrcIsImmutable(e);
if true {
#[allow(unused, unreachable_code)]
let u = AssertDstIsSized(loop {});
u.0
} else if true {
#[allow(unused, unreachable_code)]
let u = AssertDstIsFromBytes(loop {});
u.0
} else {
#[allow(unused, unreachable_code)]
let u = AssertDstIsImmutable(loop {});
u.0
}
} else if false {
let mut t = loop {};
e = &t;
let u;
$crate::assert_size_eq!(t, u);
$crate::assert_align_gt_eq!(t, u);
&u
} else {
let u = unsafe { $crate::macro_util::transmute_ref(e) };
$crate::macro_util::must_use(u)
}
}}
}
#[macro_export]
macro_rules! transmute_mut {
($e:expr) => {{
let e: &mut _ = $e;
#[allow(unused, clippy::diverging_sub_expression)]
if false {
struct AssertSrcIsSized<'a, T: ::core::marker::Sized>(&'a T);
struct AssertSrcIsFromBytes<'a, T: ?::core::marker::Sized + $crate::FromBytes>(&'a T);
struct AssertSrcIsIntoBytes<'a, T: ?::core::marker::Sized + $crate::IntoBytes>(&'a T);
struct AssertDstIsSized<'a, T: ::core::marker::Sized>(&'a T);
struct AssertDstIsFromBytes<'a, T: ?::core::marker::Sized + $crate::FromBytes>(&'a T);
struct AssertDstIsIntoBytes<'a, T: ?::core::marker::Sized + $crate::IntoBytes>(&'a T);
if true {
let _ = AssertSrcIsSized(&*e);
} else if true {
let _ = AssertSrcIsFromBytes(&*e);
} else {
let _ = AssertSrcIsIntoBytes(&*e);
}
if true {
#[allow(unused, unreachable_code)]
let u = AssertDstIsSized(loop {});
&mut *u.0
} else if true {
#[allow(unused, unreachable_code)]
let u = AssertDstIsFromBytes(loop {});
&mut *u.0
} else {
#[allow(unused, unreachable_code)]
let u = AssertDstIsIntoBytes(loop {});
&mut *u.0
}
} else if false {
let mut t = loop {};
e = &mut t;
let u;
$crate::assert_size_eq!(t, u);
$crate::assert_align_gt_eq!(t, u);
&mut u
} else {
let u = unsafe { $crate::macro_util::transmute_mut(e) };
$crate::macro_util::must_use(u)
}
}}
}
#[doc(alias("include_bytes", "include_data", "include_type"))]
#[macro_export]
macro_rules! include_value {
($file:expr $(,)?) => {
$crate::transmute!(*::core::include_bytes!($file))
};
}
pub unsafe trait ByteSlice: Deref<Target = [u8]> + Sized {}
pub trait ByteSliceMut: ByteSlice + DerefMut {}
impl<B: ByteSlice + DerefMut> ByteSliceMut for B {}
pub unsafe trait CopyableByteSlice: ByteSlice + Copy + CloneableByteSlice {}
pub unsafe trait CloneableByteSlice: ByteSlice + Clone {}
pub unsafe trait SplitByteSlice: ByteSlice {
#[must_use]
#[inline]
fn split_at(self, mid: usize) -> (Self, Self) {
if let Ok(splits) = try_split_at(self, mid) {
splits
} else {
panic!("mid > len")
}
}
#[must_use]
unsafe fn split_at_unchecked(self, mid: usize) -> (Self, Self);
}
#[inline]
fn try_split_at<S>(slice: S, mid: usize) -> Result<(S, S), S>
where
S: SplitByteSlice,
{
if mid <= slice.deref().len() {
unsafe { Ok(slice.split_at_unchecked(mid)) }
} else {
Err(slice)
}
}
pub trait SplitByteSliceMut: SplitByteSlice + ByteSliceMut {}
impl<B: SplitByteSlice + ByteSliceMut> SplitByteSliceMut for B {}
pub trait IntoByteSlice<'a>: ByteSlice + Into<&'a [u8]> {}
pub trait IntoByteSliceMut<'a>: ByteSliceMut + Into<&'a mut [u8]> {}
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe impl<'a> ByteSlice for &'a [u8] {}
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe impl<'a> CopyableByteSlice for &'a [u8] {}
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe impl<'a> CloneableByteSlice for &'a [u8] {}
unsafe impl<'a> SplitByteSlice for &'a [u8] {
#[inline]
unsafe fn split_at_unchecked(self, mid: usize) -> (Self, Self) {
unsafe { (<[u8]>::get_unchecked(self, ..mid), <[u8]>::get_unchecked(self, mid..)) }
}
}
impl<'a> IntoByteSlice<'a> for &'a [u8] {}
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe impl<'a> ByteSlice for &'a mut [u8] {}
unsafe impl<'a> SplitByteSlice for &'a mut [u8] {
#[inline]
unsafe fn split_at_unchecked(self, mid: usize) -> (Self, Self) {
use core::slice::from_raw_parts_mut;
let l_ptr = self.as_mut_ptr();
let r_ptr = unsafe { l_ptr.add(mid) };
let l_len = mid;
#[allow(unstable_name_collisions, clippy::incompatible_msrv)]
let r_len = unsafe { self.len().unchecked_sub(mid) };
unsafe { (from_raw_parts_mut(l_ptr, l_len), from_raw_parts_mut(r_ptr, r_len)) }
}
}
impl<'a> IntoByteSliceMut<'a> for &'a mut [u8] {}
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe impl<'a> ByteSlice for cell::Ref<'a, [u8]> {}
unsafe impl<'a> SplitByteSlice for cell::Ref<'a, [u8]> {
#[inline]
unsafe fn split_at_unchecked(self, mid: usize) -> (Self, Self) {
cell::Ref::map_split(self, |slice|
unsafe {
SplitByteSlice::split_at_unchecked(slice, mid)
})
}
}
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe impl<'a> ByteSlice for RefMut<'a, [u8]> {}
unsafe impl<'a> SplitByteSlice for RefMut<'a, [u8]> {
#[inline]
unsafe fn split_at_unchecked(self, mid: usize) -> (Self, Self) {
RefMut::map_split(self, |slice|
unsafe {
SplitByteSlice::split_at_unchecked(slice, mid)
})
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
mod alloc_support {
use super::*;
#[inline(always)]
pub fn extend_vec_zeroed<T: FromZeros>(v: &mut Vec<T>, additional: usize) {
insert_vec_zeroed(v, v.len(), additional);
}
#[inline]
pub fn insert_vec_zeroed<T: FromZeros>(v: &mut Vec<T>, position: usize, additional: usize) {
assert!(position <= v.len());
v.reserve(additional);
unsafe {
let ptr = v.as_mut_ptr();
#[allow(clippy::arithmetic_side_effects)]
ptr.add(position).copy_to(ptr.add(position + additional), v.len() - position);
ptr.add(position).write_bytes(0, additional);
#[allow(clippy::arithmetic_side_effects)]
v.set_len(v.len() + additional);
}
}
#[cfg(test)]
mod tests {
use core::convert::TryFrom as _;
use super::*;
#[test]
fn test_extend_vec_zeroed() {
let mut v = vec![100u64, 200, 300];
extend_vec_zeroed(&mut v, 3);
assert_eq!(v.len(), 6);
assert_eq!(&*v, &[100, 200, 300, 0, 0, 0]);
drop(v);
let mut v: Vec<u64> = Vec::new();
extend_vec_zeroed(&mut v, 3);
assert_eq!(v.len(), 3);
assert_eq!(&*v, &[0, 0, 0]);
drop(v);
}
#[test]
fn test_extend_vec_zeroed_zst() {
let mut v = vec![(), (), ()];
extend_vec_zeroed(&mut v, 3);
assert_eq!(v.len(), 6);
assert_eq!(&*v, &[(), (), (), (), (), ()]);
drop(v);
let mut v: Vec<()> = Vec::new();
extend_vec_zeroed(&mut v, 3);
assert_eq!(&*v, &[(), (), ()]);
drop(v);
}
#[test]
fn test_insert_vec_zeroed() {
let mut v: Vec<u64> = Vec::new();
insert_vec_zeroed(&mut v, 0, 2);
assert_eq!(v.len(), 2);
assert_eq!(&*v, &[0, 0]);
drop(v);
let mut v = vec![100u64, 200, 300];
insert_vec_zeroed(&mut v, 0, 2);
assert_eq!(v.len(), 5);
assert_eq!(&*v, &[0, 0, 100, 200, 300]);
drop(v);
let mut v = vec![100u64, 200, 300];
insert_vec_zeroed(&mut v, 1, 1);
assert_eq!(v.len(), 4);
assert_eq!(&*v, &[100, 0, 200, 300]);
drop(v);
let mut v = vec![100u64, 200, 300];
insert_vec_zeroed(&mut v, 3, 1);
assert_eq!(v.len(), 4);
assert_eq!(&*v, &[100, 200, 300, 0]);
drop(v);
}
#[test]
fn test_insert_vec_zeroed_zst() {
let mut v: Vec<()> = Vec::new();
insert_vec_zeroed(&mut v, 0, 2);
assert_eq!(v.len(), 2);
assert_eq!(&*v, &[(), ()]);
drop(v);
let mut v = vec![(), (), ()];
insert_vec_zeroed(&mut v, 0, 2);
assert_eq!(v.len(), 5);
assert_eq!(&*v, &[(), (), (), (), ()]);
drop(v);
let mut v = vec![(), (), ()];
insert_vec_zeroed(&mut v, 1, 1);
assert_eq!(v.len(), 4);
assert_eq!(&*v, &[(), (), (), ()]);
drop(v);
let mut v = vec![(), (), ()];
insert_vec_zeroed(&mut v, 3, 1);
assert_eq!(v.len(), 4);
assert_eq!(&*v, &[(), (), (), ()]);
drop(v);
}
#[test]
fn test_new_box_zeroed() {
assert_eq!(*u64::new_box_zeroed(), 0);
}
#[test]
fn test_new_box_zeroed_array() {
drop(<[u32; 0x1000]>::new_box_zeroed());
}
#[test]
fn test_new_box_zeroed_zst() {
#[allow(clippy::unit_cmp)]
{
assert_eq!(*<()>::new_box_zeroed(), ());
}
}
#[test]
fn test_new_box_slice_zeroed() {
let mut s: Box<[u64]> = u64::new_box_slice_zeroed(3);
assert_eq!(s.len(), 3);
assert_eq!(&*s, &[0, 0, 0]);
s[1] = 3;
assert_eq!(&*s, &[0, 3, 0]);
}
#[test]
fn test_new_box_slice_zeroed_empty() {
let s: Box<[u64]> = u64::new_box_slice_zeroed(0);
assert_eq!(s.len(), 0);
}
#[test]
fn test_new_box_slice_zeroed_zst() {
let mut s: Box<[()]> = <()>::new_box_slice_zeroed(3);
assert_eq!(s.len(), 3);
assert!(s.get(10).is_none());
#[allow(clippy::unit_cmp)]
{
assert_eq!(s[1], ());
}
s[2] = ();
}
#[test]
fn test_new_box_slice_zeroed_zst_empty() {
let s: Box<[()]> = <()>::new_box_slice_zeroed(0);
assert_eq!(s.len(), 0);
}
#[test]
#[should_panic(expected = "mem::size_of::<Self>() * len overflows `usize`")]
fn test_new_box_slice_zeroed_panics_mul_overflow() {
let _ = u16::new_box_slice_zeroed(usize::MAX);
}
#[test]
#[should_panic(expected = "assertion failed: size <= max_alloc")]
fn test_new_box_slice_zeroed_panics_isize_overflow() {
let max = usize::try_from(isize::MAX).unwrap();
let _ = u16::new_box_slice_zeroed((max / mem::size_of::<u16>()) + 1);
}
}
}
#[cfg(feature = "alloc")]
#[doc(inline)]
pub use alloc_support::*;
#[cfg(test)]
#[allow(clippy::assertions_on_result_states, clippy::unreadable_literal)]
mod tests {
use core::convert::TryInto as _;
use static_assertions::assert_impl_all;
use super::*;
use crate::util::testutil::*;
#[derive(Debug, Eq, PartialEq, FromBytes, IntoBytes, Unaligned, Immutable)]
#[repr(transparent)]
struct Unsized([u8]);
impl Unsized {
fn from_mut_slice(slc: &mut [u8]) -> &mut Unsized {
unsafe { mem::transmute(slc) }
}
}
#[allow(clippy::decimal_literal_representation)]
#[test]
fn test_dst_layout_extend_sized_with_sized() {
macro_rules! test_align_is_size {
($n:expr) => {
let base = DstLayout::for_type::<u8>();
let trailing_field = DstLayout::for_type::<elain::Align<$n>>();
let packs =
core::iter::once(None).chain((0..29).map(|p| NonZeroUsize::new(2usize.pow(p))));
for pack in packs {
let composite = base.extend(trailing_field, pack);
let max_align = pack.unwrap_or(DstLayout::CURRENT_MAX_ALIGN);
let align = $n.min(max_align.get());
assert_eq!(
composite,
DstLayout {
align: NonZeroUsize::new(align).unwrap(),
size_info: SizeInfo::Sized { size: align }
}
)
}
};
}
test_align_is_size!(1);
test_align_is_size!(2);
test_align_is_size!(4);
test_align_is_size!(8);
test_align_is_size!(16);
test_align_is_size!(32);
test_align_is_size!(64);
test_align_is_size!(128);
test_align_is_size!(256);
test_align_is_size!(512);
test_align_is_size!(1024);
test_align_is_size!(2048);
test_align_is_size!(4096);
test_align_is_size!(8192);
test_align_is_size!(16384);
test_align_is_size!(32768);
test_align_is_size!(65536);
test_align_is_size!(131072);
test_align_is_size!(262144);
test_align_is_size!(524288);
test_align_is_size!(1048576);
test_align_is_size!(2097152);
test_align_is_size!(4194304);
test_align_is_size!(8388608);
test_align_is_size!(16777216);
test_align_is_size!(33554432);
test_align_is_size!(67108864);
test_align_is_size!(33554432);
test_align_is_size!(134217728);
test_align_is_size!(268435456);
}
#[test]
fn test_dst_layout_extend_sized_with_dst() {
let aligns = (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap());
let packs = core::iter::once(None).chain(aligns.clone().map(Some));
for align in aligns {
for pack in packs.clone() {
let base = DstLayout::for_type::<u8>();
let elem_size = 42;
let trailing_field_offset = 11;
let trailing_field = DstLayout {
align,
size_info: SizeInfo::SliceDst(TrailingSliceLayout { elem_size, offset: 11 }),
};
let composite = base.extend(trailing_field, pack);
let max_align = pack.unwrap_or(DstLayout::CURRENT_MAX_ALIGN).get();
let align = align.get().min(max_align);
assert_eq!(
composite,
DstLayout {
align: NonZeroUsize::new(align).unwrap(),
size_info: SizeInfo::SliceDst(TrailingSliceLayout {
elem_size,
offset: align + trailing_field_offset,
}),
}
)
}
}
}
#[test]
fn test_dst_layout_pad_to_align_with_sized() {
for align in (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap()) {
let layout = DstLayout { align, size_info: SizeInfo::Sized { size: 1 } };
assert_eq!(
layout.pad_to_align(),
DstLayout { align, size_info: SizeInfo::Sized { size: align.get() } }
);
}
macro_rules! test {
(unpadded { size: $unpadded_size:expr, align: $unpadded_align:expr }
=> padded { size: $padded_size:expr, align: $padded_align:expr }) => {
let unpadded = DstLayout {
align: NonZeroUsize::new($unpadded_align).unwrap(),
size_info: SizeInfo::Sized { size: $unpadded_size },
};
let padded = unpadded.pad_to_align();
assert_eq!(
padded,
DstLayout {
align: NonZeroUsize::new($padded_align).unwrap(),
size_info: SizeInfo::Sized { size: $padded_size },
}
);
};
}
test!(unpadded { size: 0, align: 4 } => padded { size: 0, align: 4 });
test!(unpadded { size: 1, align: 4 } => padded { size: 4, align: 4 });
test!(unpadded { size: 2, align: 4 } => padded { size: 4, align: 4 });
test!(unpadded { size: 3, align: 4 } => padded { size: 4, align: 4 });
test!(unpadded { size: 4, align: 4 } => padded { size: 4, align: 4 });
test!(unpadded { size: 5, align: 4 } => padded { size: 8, align: 4 });
test!(unpadded { size: 6, align: 4 } => padded { size: 8, align: 4 });
test!(unpadded { size: 7, align: 4 } => padded { size: 8, align: 4 });
test!(unpadded { size: 8, align: 4 } => padded { size: 8, align: 4 });
let current_max_align = DstLayout::CURRENT_MAX_ALIGN.get();
test!(unpadded { size: 1, align: current_max_align }
=> padded { size: current_max_align, align: current_max_align });
test!(unpadded { size: current_max_align + 1, align: current_max_align }
=> padded { size: current_max_align * 2, align: current_max_align });
}
#[test]
fn test_dst_layout_pad_to_align_with_dst() {
for align in (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap()) {
for offset in 0..10 {
for elem_size in 0..10 {
let layout = DstLayout {
align,
size_info: SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }),
};
assert_eq!(layout.pad_to_align(), layout);
}
}
}
}
#[test]
#[cfg_attr(miri, ignore)]
fn test_validate_cast_and_convert_metadata() {
#[allow(non_local_definitions)]
impl From<usize> for SizeInfo {
fn from(size: usize) -> SizeInfo {
SizeInfo::Sized { size }
}
}
#[allow(non_local_definitions)]
impl From<(usize, usize)> for SizeInfo {
fn from((offset, elem_size): (usize, usize)) -> SizeInfo {
SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size })
}
}
fn layout<S: Into<SizeInfo>>(s: S, align: usize) -> DstLayout {
DstLayout { size_info: s.into(), align: NonZeroUsize::new(align).unwrap() }
}
macro_rules! test {
($(:$sizes:expr =>)?
layout($size:tt, $align:tt)
.validate($addr:tt, $bytes_len:tt, $cast_type:tt), $expect:pat $(,)?
) => {
itertools::iproduct!(
test!(@generate_size $size),
test!(@generate_align $align),
test!(@generate_usize $addr),
test!(@generate_usize $bytes_len),
test!(@generate_cast_type $cast_type)
).for_each(|(size_info, align, addr, bytes_len, cast_type)| {
let previous_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let actual = std::panic::catch_unwind(|| {
layout(size_info, align).validate_cast_and_convert_metadata(addr, bytes_len, cast_type)
}).map_err(|d| {
let msg = d.downcast::<&'static str>().ok().map(|s| *s.as_ref());
assert!(msg.is_some() || cfg!(not(zerocopy_panic_in_const)), "non-string panic messages are not permitted when `--cfg zerocopy_panic_in_const` is set");
msg
});
std::panic::set_hook(previous_hook);
assert_matches::assert_matches!(
actual, $expect,
"layout({:?}, {}).validate_cast_and_convert_metadata({}, {}, {:?})" ,size_info, align, addr, bytes_len, cast_type
);
});
};
(@generate_usize _) => { 0..8 };
(@generate_size _) => {
test!(@generate_size (_)).chain(test!(@generate_size (_, _)))
};
(@generate_size ($sized_sizes:tt | $unsized_sizes:tt)) => {
test!(@generate_size ($sized_sizes)).chain(test!(@generate_size $unsized_sizes))
};
(@generate_size (_)) => { test!(@generate_size (0..8)) };
(@generate_size ($sizes:expr)) => { $sizes.into_iter().map(Into::<SizeInfo>::into) };
(@generate_size ($min_sizes:tt, $elem_sizes:tt)) => {
itertools::iproduct!(
test!(@generate_min_size $min_sizes),
test!(@generate_elem_size $elem_sizes)
).map(Into::<SizeInfo>::into)
};
(@generate_fixed_size _) => { (0..8).into_iter().map(Into::<SizeInfo>::into) };
(@generate_min_size _) => { 0..8 };
(@generate_elem_size _) => { 1..8 };
(@generate_align _) => { [1, 2, 4, 8, 16] };
(@generate_opt_usize _) => { [None].into_iter().chain((0..8).map(Some).into_iter()) };
(@generate_cast_type _) => { [CastType::Prefix, CastType::Suffix] };
(@generate_cast_type $variant:ident) => { [CastType::$variant] };
(@$_:ident ($vals:expr)) => { $vals };
(@$_:ident $vals:expr) => { $vals };
}
const EVENS: [usize; 8] = [0, 2, 4, 6, 8, 10, 12, 14];
const ODDS: [usize; 8] = [1, 3, 5, 7, 9, 11, 13, 15];
test!(
layout(((1..8) | ((1..8), (1..8))), _).validate([0], [0], _),
Ok(Err(MetadataCastError::Size))
);
test!(
layout(((2..8) | ((2..8), (2..8))), _).validate([0], [1], Prefix),
Ok(Err(MetadataCastError::Size))
);
test!(
layout(((2..8) | ((2..8), (2..8))), _).validate([0x1000_0000 - 1], [1], Suffix),
Ok(Err(MetadataCastError::Size))
);
test!(layout(_, [2]).validate(ODDS, _, Prefix), Ok(Err(MetadataCastError::Alignment)));
test!(layout(_, [2]).validate(ODDS, _, Prefix), Ok(Err(MetadataCastError::Alignment)));
test!(layout(_, [2]).validate(EVENS, ODDS, Suffix), Ok(Err(MetadataCastError::Alignment)));
test!(layout(_, [2]).validate(EVENS, ODDS, Suffix), Ok(Err(MetadataCastError::Alignment)));
mod msgs {
pub(super) const TRAILING: &str =
"attempted to cast to slice type with zero-sized element";
pub(super) const OVERFLOW: &str = "`addr` + `bytes_len` > usize::MAX";
}
test!(layout((_, [0]), _).validate(_, _, _), Err(Some(msgs::TRAILING) | None),);
test!(layout(_, _).validate([usize::MAX], (1..100), _), Err(Some(msgs::OVERFLOW) | None));
test!(layout(_, _).validate((1..100), [usize::MAX], _), Err(Some(msgs::OVERFLOW) | None));
test!(
layout(_, _).validate(
[usize::MAX / 2 + 1, usize::MAX],
[usize::MAX / 2 + 1, usize::MAX],
_
),
Err(Some(msgs::OVERFLOW) | None)
);
fn validate_behavior(
(layout, addr, bytes_len, cast_type): (DstLayout, usize, usize, CastType),
) {
if let Ok((elems, split_at)) =
layout.validate_cast_and_convert_metadata(addr, bytes_len, cast_type)
{
let (size_info, align) = (layout.size_info, layout.align);
let debug_str = format!(
"layout({:?}, {}).validate_cast_and_convert_metadata({}, {}, {:?}) => ({}, {})",
size_info, align, addr, bytes_len, cast_type, elems, split_at
);
let sized = matches!(layout.size_info, SizeInfo::Sized { .. });
assert!(!(sized && elems != 0), "{}", debug_str);
let resulting_size = match layout.size_info {
SizeInfo::Sized { size } => size,
SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }) => {
let padded_size = |elems| {
let without_padding = offset + elems * elem_size;
without_padding + util::padding_needed_for(without_padding, align)
};
let resulting_size = padded_size(elems);
assert!(padded_size(elems + 1) > bytes_len, "{}", debug_str);
resulting_size
}
};
assert!(resulting_size <= bytes_len, "{}", debug_str);
match cast_type {
CastType::Prefix => {
assert_eq!(addr % align, 0, "{}", debug_str);
assert_eq!(resulting_size, split_at, "{}", debug_str);
}
CastType::Suffix => {
assert_eq!(split_at, bytes_len - resulting_size, "{}", debug_str);
assert_eq!((addr + split_at) % align, 0, "{}", debug_str);
}
}
} else {
let min_size = match layout.size_info {
SizeInfo::Sized { size } => size,
SizeInfo::SliceDst(TrailingSliceLayout { offset, .. }) => {
offset + util::padding_needed_for(offset, layout.align)
}
};
let insufficient_bytes = bytes_len < min_size;
let base = match cast_type {
CastType::Prefix => 0,
CastType::Suffix => bytes_len,
};
let misaligned = (base + addr) % layout.align != 0;
assert!(insufficient_bytes || misaligned);
}
}
let sizes = 0..8;
let elem_sizes = 1..8;
let size_infos = sizes
.clone()
.map(Into::<SizeInfo>::into)
.chain(itertools::iproduct!(sizes, elem_sizes).map(Into::<SizeInfo>::into));
let layouts = itertools::iproduct!(size_infos, [1, 2, 4, 8, 16, 32])
.filter(|(size_info, align)| !matches!(size_info, SizeInfo::Sized { size } if size % align != 0))
.map(|(size_info, align)| layout(size_info, align));
itertools::iproduct!(layouts, 0..8, 0..8, [CastType::Prefix, CastType::Suffix])
.for_each(validate_behavior);
}
#[test]
#[cfg(__INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)]
fn test_validate_rust_layout() {
use core::ptr::NonNull;
#[derive(Debug)]
struct MacroArgs {
offset: usize,
align: NonZeroUsize,
elem_size: Option<usize>,
}
fn test<T: ?Sized, W: Fn(usize) -> NonNull<T>>(
args: MacroArgs,
with_elems: W,
addr_of_slice_field: Option<fn(NonNull<T>) -> NonNull<u8>>,
) {
let dst = args.elem_size.is_some();
let layout = {
let size_info = match args.elem_size {
Some(elem_size) => {
SizeInfo::SliceDst(TrailingSliceLayout { offset: args.offset, elem_size })
}
None => SizeInfo::Sized {
size: args.offset + util::padding_needed_for(args.offset, args.align),
},
};
DstLayout { size_info, align: args.align }
};
for elems in 0..128 {
let ptr = with_elems(elems);
if let Some(addr_of_slice_field) = addr_of_slice_field {
let slc_field_ptr = addr_of_slice_field(ptr).as_ptr();
#[allow(clippy::incompatible_msrv)]
let offset: usize =
unsafe { slc_field_ptr.byte_offset_from(ptr.as_ptr()).try_into().unwrap() };
assert_eq!(offset, args.offset);
}
let (size, align) = unsafe {
(mem::size_of_val_raw(ptr.as_ptr()), mem::align_of_val_raw(ptr.as_ptr()))
};
let assert_msg = if !cfg!(miri) {
format!("\n{:?}\nsize:{}, align:{}", args, size, align)
} else {
String::new()
};
let without_padding =
args.offset + args.elem_size.map(|elem_size| elems * elem_size).unwrap_or(0);
assert!(size >= without_padding, "{}", assert_msg);
assert_eq!(align, args.align.get(), "{}", assert_msg);
let expected_size =
without_padding + util::padding_needed_for(without_padding, args.align);
assert_eq!(expected_size, size, "{}", assert_msg);
if args.elem_size.map(|elem_size| elem_size > 0).unwrap_or(true) {
let addr = ptr.addr().get();
let (got_elems, got_split_at) = layout
.validate_cast_and_convert_metadata(addr, size, CastType::Prefix)
.unwrap();
let assert_msg = if !cfg!(miri) {
format!(
"{}\nvalidate_cast_and_convert_metadata({}, {})",
assert_msg, addr, size,
)
} else {
String::new()
};
assert_eq!(got_split_at, size, "{}", assert_msg);
if dst {
assert!(got_elems >= elems, "{}", assert_msg);
if got_elems != elems {
let got_ptr = with_elems(got_elems);
let size_of_got_ptr = unsafe { mem::size_of_val_raw(got_ptr.as_ptr()) };
assert_eq!(size_of_got_ptr, size, "{}", assert_msg);
}
} else {
assert_eq!(got_elems, 0, "{}", assert_msg)
}
}
}
}
macro_rules! validate_against_rust {
($offset:literal, $align:literal $(, $elem_size:literal)?) => {{
#[repr(C, align($align))]
struct Foo([u8; $offset]$(, [[u8; $elem_size]])?);
let args = MacroArgs {
offset: $offset,
align: $align.try_into().unwrap(),
elem_size: {
#[allow(unused)]
let ret = None::<usize>;
$(let ret = Some($elem_size);)?
ret
}
};
#[repr(C, align($align))]
struct FooAlign;
let aligned_buf = Align::<_, FooAlign>::new([0u8; 1024]);
let with_elems = |elems| {
let slc = NonNull::slice_from_raw_parts(NonNull::from(&aligned_buf.t), elems);
#[allow(clippy::as_conversions)]
NonNull::new(slc.as_ptr() as *mut Foo).unwrap()
};
let addr_of_slice_field = {
#[allow(unused)]
let f = None::<fn(NonNull<Foo>) -> NonNull<u8>>;
$(
let f: Option<fn(NonNull<Foo>) -> NonNull<u8>> = Some(|ptr: NonNull<Foo>| unsafe {
NonNull::new(ptr::addr_of_mut!((*ptr.as_ptr()).1)).unwrap().cast::<u8>()
});
let _ = $elem_size;
)?
f
};
test::<Foo, _>(args, with_elems, addr_of_slice_field);
}};
}
validate_against_rust!(0, 1);
validate_against_rust!(0, 1, 0);
validate_against_rust!(0, 1, 1);
validate_against_rust!(0, 1, 2);
validate_against_rust!(0, 1, 3);
validate_against_rust!(0, 1, 4);
validate_against_rust!(0, 2);
validate_against_rust!(0, 2, 0);
validate_against_rust!(0, 2, 1);
validate_against_rust!(0, 2, 2);
validate_against_rust!(0, 2, 3);
validate_against_rust!(0, 2, 4);
validate_against_rust!(0, 4);
validate_against_rust!(0, 4, 0);
validate_against_rust!(0, 4, 1);
validate_against_rust!(0, 4, 2);
validate_against_rust!(0, 4, 3);
validate_against_rust!(0, 4, 4);
validate_against_rust!(0, 8);
validate_against_rust!(0, 8, 0);
validate_against_rust!(0, 8, 1);
validate_against_rust!(0, 8, 2);
validate_against_rust!(0, 8, 3);
validate_against_rust!(0, 8, 4);
validate_against_rust!(0, 16);
validate_against_rust!(0, 16, 0);
validate_against_rust!(0, 16, 1);
validate_against_rust!(0, 16, 2);
validate_against_rust!(0, 16, 3);
validate_against_rust!(0, 16, 4);
validate_against_rust!(1, 1);
validate_against_rust!(1, 1, 0);
validate_against_rust!(1, 1, 1);
validate_against_rust!(1, 1, 2);
validate_against_rust!(1, 1, 3);
validate_against_rust!(1, 1, 4);
validate_against_rust!(1, 2);
validate_against_rust!(1, 2, 0);
validate_against_rust!(1, 2, 1);
validate_against_rust!(1, 2, 2);
validate_against_rust!(1, 2, 3);
validate_against_rust!(1, 2, 4);
validate_against_rust!(1, 4);
validate_against_rust!(1, 4, 0);
validate_against_rust!(1, 4, 1);
validate_against_rust!(1, 4, 2);
validate_against_rust!(1, 4, 3);
validate_against_rust!(1, 4, 4);
validate_against_rust!(1, 8);
validate_against_rust!(1, 8, 0);
validate_against_rust!(1, 8, 1);
validate_against_rust!(1, 8, 2);
validate_against_rust!(1, 8, 3);
validate_against_rust!(1, 8, 4);
validate_against_rust!(1, 16);
validate_against_rust!(1, 16, 0);
validate_against_rust!(1, 16, 1);
validate_against_rust!(1, 16, 2);
validate_against_rust!(1, 16, 3);
validate_against_rust!(1, 16, 4);
validate_against_rust!(2, 1);
validate_against_rust!(2, 1, 0);
validate_against_rust!(2, 1, 1);
validate_against_rust!(2, 1, 2);
validate_against_rust!(2, 1, 3);
validate_against_rust!(2, 1, 4);
validate_against_rust!(2, 2);
validate_against_rust!(2, 2, 0);
validate_against_rust!(2, 2, 1);
validate_against_rust!(2, 2, 2);
validate_against_rust!(2, 2, 3);
validate_against_rust!(2, 2, 4);
validate_against_rust!(2, 4);
validate_against_rust!(2, 4, 0);
validate_against_rust!(2, 4, 1);
validate_against_rust!(2, 4, 2);
validate_against_rust!(2, 4, 3);
validate_against_rust!(2, 4, 4);
validate_against_rust!(2, 8);
validate_against_rust!(2, 8, 0);
validate_against_rust!(2, 8, 1);
validate_against_rust!(2, 8, 2);
validate_against_rust!(2, 8, 3);
validate_against_rust!(2, 8, 4);
validate_against_rust!(2, 16);
validate_against_rust!(2, 16, 0);
validate_against_rust!(2, 16, 1);
validate_against_rust!(2, 16, 2);
validate_against_rust!(2, 16, 3);
validate_against_rust!(2, 16, 4);
validate_against_rust!(3, 1);
validate_against_rust!(3, 1, 0);
validate_against_rust!(3, 1, 1);
validate_against_rust!(3, 1, 2);
validate_against_rust!(3, 1, 3);
validate_against_rust!(3, 1, 4);
validate_against_rust!(3, 2);
validate_against_rust!(3, 2, 0);
validate_against_rust!(3, 2, 1);
validate_against_rust!(3, 2, 2);
validate_against_rust!(3, 2, 3);
validate_against_rust!(3, 2, 4);
validate_against_rust!(3, 4);
validate_against_rust!(3, 4, 0);
validate_against_rust!(3, 4, 1);
validate_against_rust!(3, 4, 2);
validate_against_rust!(3, 4, 3);
validate_against_rust!(3, 4, 4);
validate_against_rust!(3, 8);
validate_against_rust!(3, 8, 0);
validate_against_rust!(3, 8, 1);
validate_against_rust!(3, 8, 2);
validate_against_rust!(3, 8, 3);
validate_against_rust!(3, 8, 4);
validate_against_rust!(3, 16);
validate_against_rust!(3, 16, 0);
validate_against_rust!(3, 16, 1);
validate_against_rust!(3, 16, 2);
validate_against_rust!(3, 16, 3);
validate_against_rust!(3, 16, 4);
validate_against_rust!(4, 1);
validate_against_rust!(4, 1, 0);
validate_against_rust!(4, 1, 1);
validate_against_rust!(4, 1, 2);
validate_against_rust!(4, 1, 3);
validate_against_rust!(4, 1, 4);
validate_against_rust!(4, 2);
validate_against_rust!(4, 2, 0);
validate_against_rust!(4, 2, 1);
validate_against_rust!(4, 2, 2);
validate_against_rust!(4, 2, 3);
validate_against_rust!(4, 2, 4);
validate_against_rust!(4, 4);
validate_against_rust!(4, 4, 0);
validate_against_rust!(4, 4, 1);
validate_against_rust!(4, 4, 2);
validate_against_rust!(4, 4, 3);
validate_against_rust!(4, 4, 4);
validate_against_rust!(4, 8);
validate_against_rust!(4, 8, 0);
validate_against_rust!(4, 8, 1);
validate_against_rust!(4, 8, 2);
validate_against_rust!(4, 8, 3);
validate_against_rust!(4, 8, 4);
validate_against_rust!(4, 16);
validate_against_rust!(4, 16, 0);
validate_against_rust!(4, 16, 1);
validate_against_rust!(4, 16, 2);
validate_against_rust!(4, 16, 3);
validate_against_rust!(4, 16, 4);
}
#[test]
fn test_known_layout() {
macro_rules! test {
($ty:ty, $expect:expr) => {
let expect = $expect;
assert_eq!(<$ty as KnownLayout>::LAYOUT, expect);
assert_eq!(<ManuallyDrop<$ty> as KnownLayout>::LAYOUT, expect);
assert_eq!(<PhantomData<$ty> as KnownLayout>::LAYOUT, <() as KnownLayout>::LAYOUT);
};
}
let layout = |offset, align, _trailing_slice_elem_size| DstLayout {
align: NonZeroUsize::new(align).unwrap(),
size_info: match _trailing_slice_elem_size {
None => SizeInfo::Sized { size: offset },
Some(elem_size) => SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }),
},
};
test!((), layout(0, 1, None));
test!(u8, layout(1, 1, None));
test!(u64, layout(8, mem::align_of::<u64>(), None));
test!(AU64, layout(8, 8, None));
test!(Option<&'static ()>, usize::LAYOUT);
test!([()], layout(0, 1, Some(0)));
test!([u8], layout(0, 1, Some(1)));
test!(str, layout(0, 1, Some(1)));
}
#[cfg(feature = "derive")]
#[test]
fn test_known_layout_derive() {
struct NotKnownLayout<T = ()> {
_t: T,
}
#[derive(KnownLayout)]
#[repr(C)]
struct AlignSize<const ALIGN: usize, const SIZE: usize>
where
elain::Align<ALIGN>: elain::Alignment,
{
_align: elain::Align<ALIGN>,
size: [u8; SIZE],
}
type AU16 = AlignSize<2, 2>;
type AU32 = AlignSize<4, 4>;
fn _assert_kl<T: ?Sized + KnownLayout>(_: &T) {}
let sized_layout = |align, size| DstLayout {
align: NonZeroUsize::new(align).unwrap(),
size_info: SizeInfo::Sized { size },
};
let unsized_layout = |align, elem_size, offset| DstLayout {
align: NonZeroUsize::new(align).unwrap(),
size_info: SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size }),
};
#[allow(dead_code)]
#[derive(KnownLayout)]
struct KL01(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
let expected = DstLayout::for_type::<KL01>();
assert_eq!(<KL01 as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL01 as KnownLayout>::LAYOUT, sized_layout(4, 8));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(align(64))]
struct KL01Align(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
let expected = DstLayout::for_type::<KL01Align>();
assert_eq!(<KL01Align as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL01Align as KnownLayout>::LAYOUT, sized_layout(64, 64));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(packed)]
struct KL01Packed(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
let expected = DstLayout::for_type::<KL01Packed>();
assert_eq!(<KL01Packed as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL01Packed as KnownLayout>::LAYOUT, sized_layout(1, 6));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(packed(2))]
struct KL01PackedN(NotKnownLayout<AU32>, NotKnownLayout<AU16>);
assert_impl_all!(KL01PackedN: KnownLayout);
let expected = DstLayout::for_type::<KL01PackedN>();
assert_eq!(<KL01PackedN as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL01PackedN as KnownLayout>::LAYOUT, sized_layout(2, 6));
#[allow(dead_code)]
#[derive(KnownLayout)]
struct KL03(NotKnownLayout, u8);
let expected = DstLayout::for_type::<KL03>();
assert_eq!(<KL03 as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL03 as KnownLayout>::LAYOUT, sized_layout(1, 1));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(align(64))]
struct KL03Align(NotKnownLayout<AU32>, u8);
let expected = DstLayout::for_type::<KL03Align>();
assert_eq!(<KL03Align as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL03Align as KnownLayout>::LAYOUT, sized_layout(64, 64));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(packed)]
struct KL03Packed(NotKnownLayout<AU32>, u8);
let expected = DstLayout::for_type::<KL03Packed>();
assert_eq!(<KL03Packed as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL03Packed as KnownLayout>::LAYOUT, sized_layout(1, 5));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(packed(2))]
struct KL03PackedN(NotKnownLayout<AU32>, u8);
assert_impl_all!(KL03PackedN: KnownLayout);
let expected = DstLayout::for_type::<KL03PackedN>();
assert_eq!(<KL03PackedN as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL03PackedN as KnownLayout>::LAYOUT, sized_layout(2, 6));
#[allow(dead_code)]
#[derive(KnownLayout)]
struct KL05<T>(u8, T);
fn _test_kl05<T>(t: T) -> impl KnownLayout {
KL05(0u8, t)
}
#[allow(dead_code)]
#[derive(KnownLayout)]
struct KL07<T: KnownLayout>(u8, T);
fn _test_kl07<T: KnownLayout>(t: T) -> impl KnownLayout {
let _ = KL07(0u8, t);
}
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C)]
struct KL10(NotKnownLayout<AU32>, [u8]);
let expected = DstLayout::new_zst(None)
.extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), None)
.extend(<[u8] as KnownLayout>::LAYOUT, None)
.pad_to_align();
assert_eq!(<KL10 as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL10 as KnownLayout>::LAYOUT, unsized_layout(4, 1, 4));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C, align(64))]
struct KL10Align(NotKnownLayout<AU32>, [u8]);
let repr_align = NonZeroUsize::new(64);
let expected = DstLayout::new_zst(repr_align)
.extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), None)
.extend(<[u8] as KnownLayout>::LAYOUT, None)
.pad_to_align();
assert_eq!(<KL10Align as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL10Align as KnownLayout>::LAYOUT, unsized_layout(64, 1, 4));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C, packed)]
struct KL10Packed(NotKnownLayout<AU32>, [u8]);
let repr_packed = NonZeroUsize::new(1);
let expected = DstLayout::new_zst(None)
.extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), repr_packed)
.extend(<[u8] as KnownLayout>::LAYOUT, repr_packed)
.pad_to_align();
assert_eq!(<KL10Packed as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL10Packed as KnownLayout>::LAYOUT, unsized_layout(1, 1, 4));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C, packed(2))]
struct KL10PackedN(NotKnownLayout<AU32>, [u8]);
let repr_packed = NonZeroUsize::new(2);
let expected = DstLayout::new_zst(None)
.extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), repr_packed)
.extend(<[u8] as KnownLayout>::LAYOUT, repr_packed)
.pad_to_align();
assert_eq!(<KL10PackedN as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL10PackedN as KnownLayout>::LAYOUT, unsized_layout(2, 1, 4));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C)]
struct KL11(NotKnownLayout<AU64>, u8);
let expected = DstLayout::new_zst(None)
.extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), None)
.extend(<u8 as KnownLayout>::LAYOUT, None)
.pad_to_align();
assert_eq!(<KL11 as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL11 as KnownLayout>::LAYOUT, sized_layout(8, 16));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C, align(64))]
struct KL11Align(NotKnownLayout<AU64>, u8);
let repr_align = NonZeroUsize::new(64);
let expected = DstLayout::new_zst(repr_align)
.extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), None)
.extend(<u8 as KnownLayout>::LAYOUT, None)
.pad_to_align();
assert_eq!(<KL11Align as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL11Align as KnownLayout>::LAYOUT, sized_layout(64, 64));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C, packed)]
struct KL11Packed(NotKnownLayout<AU64>, u8);
let repr_packed = NonZeroUsize::new(1);
let expected = DstLayout::new_zst(None)
.extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), repr_packed)
.extend(<u8 as KnownLayout>::LAYOUT, repr_packed)
.pad_to_align();
assert_eq!(<KL11Packed as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL11Packed as KnownLayout>::LAYOUT, sized_layout(1, 9));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C, packed(2))]
struct KL11PackedN(NotKnownLayout<AU64>, u8);
let repr_packed = NonZeroUsize::new(2);
let expected = DstLayout::new_zst(None)
.extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), repr_packed)
.extend(<u8 as KnownLayout>::LAYOUT, repr_packed)
.pad_to_align();
assert_eq!(<KL11PackedN as KnownLayout>::LAYOUT, expected);
assert_eq!(<KL11PackedN as KnownLayout>::LAYOUT, sized_layout(2, 10));
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C)]
struct KL14<T: ?Sized + KnownLayout>(u8, T);
fn _test_kl14<T: ?Sized + KnownLayout>(kl: &KL14<T>) {
_assert_kl(kl)
}
#[allow(dead_code)]
#[derive(KnownLayout)]
#[repr(C)]
struct KL15<T: KnownLayout>(u8, T);
fn _test_kl15<T: KnownLayout>(t: T) -> impl KnownLayout {
let _ = KL15(0u8, t);
}
#[allow(clippy::upper_case_acronyms, dead_code)]
#[derive(KnownLayout)]
#[repr(C)]
struct KLTU<T, U: ?Sized>(T, U);
assert_eq!(<KLTU<(), ()> as KnownLayout>::LAYOUT, sized_layout(1, 0));
assert_eq!(<KLTU<(), u8> as KnownLayout>::LAYOUT, sized_layout(1, 1));
assert_eq!(<KLTU<(), AU16> as KnownLayout>::LAYOUT, sized_layout(2, 2));
assert_eq!(<KLTU<(), [()]> as KnownLayout>::LAYOUT, unsized_layout(1, 0, 0));
assert_eq!(<KLTU<(), [u8]> as KnownLayout>::LAYOUT, unsized_layout(1, 1, 0));
assert_eq!(<KLTU<(), [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 0));
assert_eq!(<KLTU<u8, ()> as KnownLayout>::LAYOUT, sized_layout(1, 1));
assert_eq!(<KLTU<u8, u8> as KnownLayout>::LAYOUT, sized_layout(1, 2));
assert_eq!(<KLTU<u8, AU16> as KnownLayout>::LAYOUT, sized_layout(2, 4));
assert_eq!(<KLTU<u8, [()]> as KnownLayout>::LAYOUT, unsized_layout(1, 0, 1));
assert_eq!(<KLTU<u8, [u8]> as KnownLayout>::LAYOUT, unsized_layout(1, 1, 1));
assert_eq!(<KLTU<u8, [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 2));
assert_eq!(<KLTU<AU16, ()> as KnownLayout>::LAYOUT, sized_layout(2, 2));
assert_eq!(<KLTU<AU16, u8> as KnownLayout>::LAYOUT, sized_layout(2, 4));
assert_eq!(<KLTU<AU16, AU16> as KnownLayout>::LAYOUT, sized_layout(2, 4));
assert_eq!(<KLTU<AU16, [()]> as KnownLayout>::LAYOUT, unsized_layout(2, 0, 2));
assert_eq!(<KLTU<AU16, [u8]> as KnownLayout>::LAYOUT, unsized_layout(2, 1, 2));
assert_eq!(<KLTU<AU16, [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 2));
#[derive(KnownLayout)]
#[repr(C)]
struct KLF0;
assert_eq!(<KLF0 as KnownLayout>::LAYOUT, sized_layout(1, 0));
#[derive(KnownLayout)]
#[repr(C)]
struct KLF1([u8]);
assert_eq!(<KLF1 as KnownLayout>::LAYOUT, unsized_layout(1, 1, 0));
#[derive(KnownLayout)]
#[repr(C)]
struct KLF2(NotKnownLayout<u8>, [u8]);
assert_eq!(<KLF2 as KnownLayout>::LAYOUT, unsized_layout(1, 1, 1));
#[derive(KnownLayout)]
#[repr(C)]
struct KLF3(NotKnownLayout<u8>, NotKnownLayout<AU16>, [u8]);
assert_eq!(<KLF3 as KnownLayout>::LAYOUT, unsized_layout(2, 1, 4));
#[derive(KnownLayout)]
#[repr(C)]
struct KLF4(NotKnownLayout<u8>, NotKnownLayout<AU16>, NotKnownLayout<AU32>, [u8]);
assert_eq!(<KLF4 as KnownLayout>::LAYOUT, unsized_layout(4, 1, 8));
}
#[test]
fn test_object_safety() {
fn _takes_no_cell(_: &dyn Immutable) {}
fn _takes_unaligned(_: &dyn Unaligned) {}
}
#[test]
fn test_from_zeros_only() {
assert!(!bool::new_zeroed());
assert_eq!(char::new_zeroed(), '\0');
#[cfg(feature = "alloc")]
{
assert_eq!(bool::new_box_zeroed(), Box::new(false));
assert_eq!(char::new_box_zeroed(), Box::new('\0'));
assert_eq!(bool::new_box_slice_zeroed(3).as_ref(), [false, false, false]);
assert_eq!(char::new_box_slice_zeroed(3).as_ref(), ['\0', '\0', '\0']);
assert_eq!(bool::new_vec_zeroed(3).as_ref(), [false, false, false]);
assert_eq!(char::new_vec_zeroed(3).as_ref(), ['\0', '\0', '\0']);
}
let mut string = "hello".to_string();
let s: &mut str = string.as_mut();
assert_eq!(s, "hello");
s.zero();
assert_eq!(s, "\0\0\0\0\0");
}
#[test]
fn test_read_write() {
const VAL: u64 = 0x12345678;
#[cfg(target_endian = "big")]
const VAL_BYTES: [u8; 8] = VAL.to_be_bytes();
#[cfg(target_endian = "little")]
const VAL_BYTES: [u8; 8] = VAL.to_le_bytes();
assert_eq!(u64::read_from(&VAL_BYTES[..]), Ok(VAL));
let bytes_with_prefix: [u8; 16] = transmute!([VAL_BYTES, [0; 8]]);
assert_eq!(u64::read_from_prefix(&bytes_with_prefix[..]), Ok(VAL));
assert_eq!(u64::read_from_suffix(&bytes_with_prefix[..]), Ok(0));
let bytes_with_suffix: [u8; 16] = transmute!([[0; 8], VAL_BYTES]);
assert_eq!(u64::read_from_prefix(&bytes_with_suffix[..]), Ok(0));
assert_eq!(u64::read_from_suffix(&bytes_with_suffix[..]), Ok(VAL));
let mut bytes = [0u8; 8];
assert_eq!(VAL.write_to(&mut bytes[..]), Ok(()));
assert_eq!(bytes, VAL_BYTES);
let mut bytes = [0u8; 16];
assert_eq!(VAL.write_to_prefix(&mut bytes[..]), Ok(()));
let want: [u8; 16] = transmute!([VAL_BYTES, [0; 8]]);
assert_eq!(bytes, want);
let mut bytes = [0u8; 16];
assert_eq!(VAL.write_to_suffix(&mut bytes[..]), Ok(()));
let want: [u8; 16] = transmute!([[0; 8], VAL_BYTES]);
assert_eq!(bytes, want);
}
#[test]
fn test_try_from_bytes_try_read_from() {
assert_eq!(<bool as TryFromBytes>::try_read_from(&[0]), Ok(false));
assert_eq!(<bool as TryFromBytes>::try_read_from(&[1]), Ok(true));
assert!(matches!(<u8 as TryFromBytes>::try_read_from(&[]), Err(TryReadError::Size(_))));
assert!(matches!(<u8 as TryFromBytes>::try_read_from(&[0, 0]), Err(TryReadError::Size(_))));
assert!(matches!(
<bool as TryFromBytes>::try_read_from(&[2]),
Err(TryReadError::Validity(_))
));
let bytes: [u8; 9] = [0, 0, 0, 0, 0, 0, 0, 0, 0];
assert_eq!(<AU64 as TryFromBytes>::try_read_from(&bytes[..8]), Ok(AU64(0)));
assert_eq!(<AU64 as TryFromBytes>::try_read_from(&bytes[1..9]), Ok(AU64(0)));
}
#[test]
fn test_transmute() {
let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
let x: [[u8; 2]; 4] = transmute!(array_of_u8s);
assert_eq!(x, array_of_arrays);
let x: [u8; 8] = transmute!(array_of_arrays);
assert_eq!(x, array_of_u8s);
#[derive(IntoBytes)]
#[repr(transparent)]
struct PanicOnDrop(());
impl Drop for PanicOnDrop {
fn drop(&mut self) {
panic!("PanicOnDrop::drop");
}
}
#[allow(clippy::let_unit_value)]
let _: () = transmute!(PanicOnDrop(()));
const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7];
const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]];
const X: [[u8; 2]; 4] = transmute!(ARRAY_OF_U8S);
assert_eq!(X, ARRAY_OF_ARRAYS);
let x: usize = transmute!(UnsafeCell::new(1usize));
assert_eq!(x, 1);
let x: UnsafeCell<usize> = transmute!(1usize);
assert_eq!(x.into_inner(), 1);
let x: UnsafeCell<isize> = transmute!(UnsafeCell::new(1usize));
assert_eq!(x.into_inner(), 1);
}
#[test]
fn test_transmute_ref() {
let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
let x: &[[u8; 2]; 4] = transmute_ref!(&array_of_u8s);
assert_eq!(*x, array_of_arrays);
let x: &[u8; 8] = transmute_ref!(&array_of_arrays);
assert_eq!(*x, array_of_u8s);
const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7];
const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]];
#[allow(clippy::redundant_static_lifetimes)]
const X: &'static [[u8; 2]; 4] = transmute_ref!(&ARRAY_OF_U8S);
assert_eq!(*X, ARRAY_OF_ARRAYS);
let x: &[u8; 8] = transmute_ref!(X);
assert_eq!(*x, ARRAY_OF_U8S);
let u = AU64(0);
let array = [0, 0, 0, 0, 0, 0, 0, 0];
let x: &[u8; 8] = transmute_ref!(&u);
assert_eq!(*x, array);
let mut x = 0u8;
#[allow(clippy::useless_transmute)]
let y: &u8 = transmute_ref!(&mut x);
assert_eq!(*y, 0);
}
#[test]
fn test_transmute_mut() {
let mut array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
let mut array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
let x: &mut [[u8; 2]; 4] = transmute_mut!(&mut array_of_u8s);
assert_eq!(*x, array_of_arrays);
let x: &mut [u8; 8] = transmute_mut!(&mut array_of_arrays);
assert_eq!(*x, array_of_u8s);
{
let x: &mut [u8; 8] = transmute_mut!(&mut array_of_arrays);
assert_eq!(*x, array_of_u8s);
}
let mut u = AU64(0);
let array = [0, 0, 0, 0, 0, 0, 0, 0];
let x: &[u8; 8] = transmute_mut!(&mut u);
assert_eq!(*x, array);
let mut x = 0u8;
#[allow(clippy::useless_transmute)]
let y: &u8 = transmute_mut!(&mut x);
assert_eq!(*y, 0);
}
#[test]
fn test_macros_evaluate_args_once() {
let mut ctr = 0;
let _: usize = transmute!({
ctr += 1;
0usize
});
assert_eq!(ctr, 1);
let mut ctr = 0;
let _: &usize = transmute_ref!({
ctr += 1;
&0usize
});
assert_eq!(ctr, 1);
}
#[test]
fn test_include_value() {
const AS_U32: u32 = include_value!("../testdata/include_value/data");
assert_eq!(AS_U32, u32::from_ne_bytes([b'a', b'b', b'c', b'd']));
const AS_I32: i32 = include_value!("../testdata/include_value/data");
assert_eq!(AS_I32, i32::from_ne_bytes([b'a', b'b', b'c', b'd']));
}
#[test]
fn test_address() {
let buf = [0];
let r = Ref::<_, u8>::new(&buf[..]).unwrap();
let buf_ptr = buf.as_ptr();
let deref_ptr: *const u8 = r.deref();
assert_eq!(buf_ptr, deref_ptr);
let buf = [0];
let r = Ref::<_, [u8]>::new(&buf[..]).unwrap();
let buf_ptr = buf.as_ptr();
let deref_ptr = r.deref().as_ptr();
assert_eq!(buf_ptr, deref_ptr);
}
fn test_new_helper(mut r: Ref<&mut [u8], AU64>) {
assert_eq!(*r, AU64(0));
assert_eq!(r.read(), AU64(0));
const VAL1: AU64 = AU64(0xFF00FF00FF00FF00);
*r = VAL1;
assert_eq!(r.bytes(), &VAL1.to_bytes());
*r = AU64(0);
r.write(VAL1);
assert_eq!(r.bytes(), &VAL1.to_bytes());
const VAL2: AU64 = AU64(!VAL1.0); r.bytes_mut().copy_from_slice(&VAL2.to_bytes()[..]);
assert_eq!(*r, VAL2);
assert_eq!(r.read(), VAL2);
}
fn test_new_helper_slice(mut r: Ref<&mut [u8], [AU64]>, typed_len: usize) {
assert_eq!(&*r, vec![AU64(0); typed_len].as_slice());
let untyped_len = typed_len * 8;
assert_eq!(r.bytes().len(), untyped_len);
assert_eq!(r.bytes().as_ptr(), r.as_ptr().cast::<u8>());
const VAL1: AU64 = AU64(0xFF00FF00FF00FF00);
for typed in &mut *r {
*typed = VAL1;
}
assert_eq!(r.bytes(), VAL1.0.to_ne_bytes().repeat(typed_len).as_slice());
const VAL2: AU64 = AU64(!VAL1.0); r.bytes_mut().copy_from_slice(&VAL2.0.to_ne_bytes().repeat(typed_len));
assert!(r.iter().copied().all(|x| x == VAL2));
}
fn test_new_helper_unaligned(mut r: Ref<&mut [u8], [u8; 8]>) {
assert_eq!(*r, [0; 8]);
assert_eq!(r.read(), [0; 8]);
const VAL1: [u8; 8] = [0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00];
*r = VAL1;
assert_eq!(r.bytes(), &VAL1);
*r = [0; 8];
r.write(VAL1);
assert_eq!(r.bytes(), &VAL1);
const VAL2: [u8; 8] = [0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF]; r.bytes_mut().copy_from_slice(&VAL2[..]);
assert_eq!(*r, VAL2);
assert_eq!(r.read(), VAL2);
}
fn test_new_helper_slice_unaligned(mut r: Ref<&mut [u8], [u8]>, len: usize) {
assert_eq!(&*r, vec![0u8; len].as_slice());
assert_eq!(r.bytes().len(), len);
assert_eq!(r.bytes().as_ptr(), r.as_ptr());
let mut expected_bytes = [0xFF, 0x00].iter().copied().cycle().take(len).collect::<Vec<_>>();
r.copy_from_slice(&expected_bytes);
assert_eq!(r.bytes(), expected_bytes.as_slice());
for byte in &mut expected_bytes {
*byte = !*byte; }
r.bytes_mut().copy_from_slice(&expected_bytes);
assert_eq!(&*r, expected_bytes.as_slice());
}
#[test]
fn test_new_aligned_sized() {
let mut buf = Align::<[u8; 8], AU64>::default();
test_new_helper(Ref::<_, AU64>::new(&mut buf.t[..]).unwrap());
{
buf.set_default();
let (r, suffix) = Ref::<_, AU64>::new_from_prefix(&mut buf.t[..]).unwrap();
assert!(suffix.is_empty());
test_new_helper(r);
}
{
buf.set_default();
let (prefix, r) = Ref::<_, AU64>::new_from_suffix(&mut buf.t[..]).unwrap();
assert!(prefix.is_empty());
test_new_helper(r);
}
let mut buf = Align::<[u8; 24], AU64>::default();
test_new_helper_slice(Ref::<_, [AU64]>::new(&mut buf.t[..]).unwrap(), 3);
let ascending: [u8; 24] = (0..24).collect::<Vec<_>>().try_into().unwrap();
let mut ascending_prefix = ascending;
ascending_prefix[16..].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
let mut ascending_suffix = ascending;
ascending_suffix[..8].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
{
buf.t = ascending_suffix;
let (r, suffix) =
Ref::<_, [AU64]>::with_trailing_elements_from_prefix(&mut buf.t[..], 1).unwrap();
assert_eq!(suffix, &ascending[8..]);
test_new_helper_slice(r, 1);
}
{
buf.t = ascending_prefix;
let (prefix, r) =
Ref::<_, [AU64]>::with_trailing_elements_from_suffix(&mut buf.t[..], 1).unwrap();
assert_eq!(prefix, &ascending[..16]);
test_new_helper_slice(r, 1);
}
}
#[test]
fn test_new_unaligned_sized() {
let mut buf = [0u8; 8];
test_new_helper_unaligned(Ref::<_, [u8; 8]>::new_unaligned(&mut buf[..]).unwrap());
{
buf = [0u8; 8];
let (r, suffix) = Ref::<_, [u8; 8]>::new_unaligned_from_prefix(&mut buf[..]).unwrap();
assert!(suffix.is_empty());
test_new_helper_unaligned(r);
}
{
buf = [0u8; 8];
let (prefix, r) = Ref::<_, [u8; 8]>::new_unaligned_from_suffix(&mut buf[..]).unwrap();
assert!(prefix.is_empty());
test_new_helper_unaligned(r);
}
let mut buf = [0u8; 16];
test_new_helper_slice_unaligned(Ref::<_, [u8]>::new_unaligned(&mut buf[..]).unwrap(), 16);
{
buf = [0u8; 16];
let (r, suffix) =
Ref::<_, [u8]>::with_trailing_elements_unaligned_from_prefix(&mut buf[..], 8)
.unwrap();
assert_eq!(suffix, [0; 8]);
test_new_helper_slice_unaligned(r, 8);
}
{
buf = [0u8; 16];
let (prefix, r) =
Ref::<_, [u8]>::with_trailing_elements_unaligned_from_suffix(&mut buf[..], 8)
.unwrap();
assert_eq!(prefix, [0; 8]);
test_new_helper_slice_unaligned(r, 8);
}
}
#[test]
fn test_new_oversized() {
let mut buf = Align::<[u8; 16], AU64>::default();
{
let (r, suffix) = Ref::<_, AU64>::new_from_prefix(&mut buf.t[..]).unwrap();
assert_eq!(suffix.len(), 8);
test_new_helper(r);
}
{
buf.set_default();
let (prefix, r) = Ref::<_, AU64>::new_from_suffix(&mut buf.t[..]).unwrap();
assert_eq!(prefix.len(), 8);
test_new_helper(r);
}
}
#[test]
fn test_new_unaligned_oversized() {
let mut buf = [0u8; 16];
{
let (r, suffix) = Ref::<_, [u8; 8]>::new_unaligned_from_prefix(&mut buf[..]).unwrap();
assert_eq!(suffix.len(), 8);
test_new_helper_unaligned(r);
}
{
buf = [0u8; 16];
let (prefix, r) = Ref::<_, [u8; 8]>::new_unaligned_from_suffix(&mut buf[..]).unwrap();
assert_eq!(prefix.len(), 8);
test_new_helper_unaligned(r);
}
}
#[test]
fn test_ref_from_mut_from() {
let mut buf =
Align::<[u8; 16], AU64>::new([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
assert_eq!(
AU64::ref_from(&buf.t[8..]).unwrap().0.to_ne_bytes(),
[8, 9, 10, 11, 12, 13, 14, 15]
);
let suffix = AU64::mut_from(&mut buf.t[8..]).unwrap();
suffix.0 = 0x0101010101010101;
assert_eq!(
<[u8; 9]>::ref_from_suffix(&buf.t[..]).unwrap(),
(&[0, 1, 2, 3, 4, 5, 6][..], &[7u8, 1, 1, 1, 1, 1, 1, 1, 1])
);
let (prefix, suffix) = AU64::mut_from_suffix(&mut buf.t[1..]).unwrap();
assert_eq!(prefix, &mut [1u8, 2, 3, 4, 5, 6, 7][..]);
suffix.0 = 0x0202020202020202;
let (prefix, suffix) = <[u8; 10]>::mut_from_suffix(&mut buf.t[..]).unwrap();
assert_eq!(prefix, &mut [0u8, 1, 2, 3, 4, 5][..]);
suffix[0] = 42;
assert_eq!(
<[u8; 9]>::ref_from_prefix(&buf.t[..]).unwrap(),
(&[0u8, 1, 2, 3, 4, 5, 42, 7, 2], &[2u8, 2, 2, 2, 2, 2, 2][..])
);
<[u8; 2]>::mut_from_prefix(&mut buf.t[..]).unwrap().0[1] = 30;
assert_eq!(buf.t, [0, 30, 2, 3, 4, 5, 42, 7, 2, 2, 2, 2, 2, 2, 2, 2]);
}
#[test]
fn test_ref_from_mut_from_error() {
let mut buf = Align::<[u8; 16], AU64>::default();
assert!(AU64::ref_from(&buf.t[..]).is_err());
assert!(AU64::mut_from(&mut buf.t[..]).is_err());
assert!(<[u8; 8]>::ref_from(&buf.t[..]).is_err());
assert!(<[u8; 8]>::mut_from(&mut buf.t[..]).is_err());
let mut buf = Align::<[u8; 4], AU64>::default();
assert!(AU64::ref_from(&buf.t[..]).is_err());
assert!(AU64::mut_from(&mut buf.t[..]).is_err());
assert!(<[u8; 8]>::ref_from(&buf.t[..]).is_err());
assert!(<[u8; 8]>::mut_from(&mut buf.t[..]).is_err());
assert!(AU64::ref_from_prefix(&buf.t[..]).is_err());
assert!(AU64::mut_from_prefix(&mut buf.t[..]).is_err());
assert!(AU64::ref_from_suffix(&buf.t[..]).is_err());
assert!(AU64::mut_from_suffix(&mut buf.t[..]).is_err());
assert!(<[u8; 8]>::ref_from_prefix(&buf.t[..]).is_err());
assert!(<[u8; 8]>::mut_from_prefix(&mut buf.t[..]).is_err());
assert!(<[u8; 8]>::ref_from_suffix(&buf.t[..]).is_err());
assert!(<[u8; 8]>::mut_from_suffix(&mut buf.t[..]).is_err());
let mut buf = Align::<[u8; 13], AU64>::default();
assert!(AU64::ref_from(&buf.t[1..]).is_err());
assert!(AU64::mut_from(&mut buf.t[1..]).is_err());
assert!(AU64::ref_from(&buf.t[1..]).is_err());
assert!(AU64::mut_from(&mut buf.t[1..]).is_err());
assert!(AU64::ref_from_prefix(&buf.t[1..]).is_err());
assert!(AU64::mut_from_prefix(&mut buf.t[1..]).is_err());
assert!(AU64::ref_from_suffix(&buf.t[..]).is_err());
assert!(AU64::mut_from_suffix(&mut buf.t[..]).is_err());
}
#[test]
#[allow(clippy::cognitive_complexity)]
fn test_new_error() {
let buf = Align::<[u8; 16], AU64>::default();
assert!(Ref::<_, AU64>::new(&buf.t[..]).is_err());
assert!(Ref::<_, [u8; 8]>::new_unaligned(&buf.t[..]).is_err());
let buf = Align::<[u8; 4], AU64>::default();
assert!(Ref::<_, AU64>::new(&buf.t[..]).is_err());
assert!(Ref::<_, [u8; 8]>::new_unaligned(&buf.t[..]).is_err());
assert!(Ref::<_, AU64>::new_from_prefix(&buf.t[..]).is_err());
assert!(Ref::<_, AU64>::new_from_suffix(&buf.t[..]).is_err());
assert!(Ref::<_, [u8; 8]>::new_unaligned_from_prefix(&buf.t[..]).is_err());
assert!(Ref::<_, [u8; 8]>::new_unaligned_from_suffix(&buf.t[..]).is_err());
let buf = Align::<[u8; 12], AU64>::default();
assert!(Ref::<_, [AU64]>::new(&buf.t[..]).is_err());
assert!(Ref::<_, [[u8; 8]]>::new_unaligned(&buf.t[..]).is_err());
let buf = Align::<[u8; 12], AU64>::default();
assert!(Ref::<_, [AU64]>::with_trailing_elements_from_prefix(&buf.t[..], 2).is_err());
assert!(Ref::<_, [AU64]>::with_trailing_elements_from_suffix(&buf.t[..], 2).is_err());
assert!(Ref::<_, [[u8; 8]]>::with_trailing_elements_unaligned_from_prefix(&buf.t[..], 2)
.is_err());
assert!(Ref::<_, [[u8; 8]]>::with_trailing_elements_unaligned_from_suffix(&buf.t[..], 2)
.is_err());
let buf = Align::<[u8; 13], AU64>::default();
assert!(Ref::<_, AU64>::new(&buf.t[1..]).is_err());
assert!(Ref::<_, AU64>::new_from_prefix(&buf.t[1..]).is_err());
assert!(Ref::<_, [AU64]>::new(&buf.t[1..]).is_err());
assert!(Ref::<_, [AU64]>::with_trailing_elements_from_prefix(&buf.t[1..], 1).is_err());
assert!(Ref::<_, [AU64]>::with_trailing_elements_from_suffix(&buf.t[1..], 1).is_err());
assert!(Ref::<_, AU64>::new_from_suffix(&buf.t[..]).is_err());
let buf = Align::<[u8; 16], AU64>::default();
let unreasonable_len = usize::MAX / mem::size_of::<AU64>() + 1;
assert!(Ref::<_, [AU64]>::with_trailing_elements_from_prefix(&buf.t[..], unreasonable_len)
.is_err());
assert!(Ref::<_, [AU64]>::with_trailing_elements_from_suffix(&buf.t[..], unreasonable_len)
.is_err());
assert!(Ref::<_, [[u8; 8]]>::with_trailing_elements_unaligned_from_prefix(
&buf.t[..],
unreasonable_len
)
.is_err());
assert!(Ref::<_, [[u8; 8]]>::with_trailing_elements_unaligned_from_suffix(
&buf.t[..],
unreasonable_len
)
.is_err());
}
#[test]
fn test_to_methods() {
fn test<T: FromBytes + IntoBytes + Immutable + Debug + Eq + ?Sized, const N: usize>(
t: &mut T,
bytes: &[u8],
post_mutation: &T,
) {
assert_eq!(t.as_bytes(), bytes);
t.as_mut_bytes()[0] ^= 0xFF;
assert_eq!(t, post_mutation);
t.as_mut_bytes()[0] ^= 0xFF;
assert!(t.write_to(&mut vec![0; N - 1][..]).is_err());
assert!(t.write_to(&mut vec![0; N + 1][..]).is_err());
let mut bytes = [0; N];
assert_eq!(t.write_to(&mut bytes[..]), Ok(()));
assert_eq!(bytes, t.as_bytes());
assert!(t.write_to_prefix(&mut vec![0; N - 1][..]).is_err());
let mut bytes = [0; N];
assert_eq!(t.write_to_prefix(&mut bytes[..]), Ok(()));
assert_eq!(bytes, t.as_bytes());
let mut too_many_bytes = vec![0; N + 1];
too_many_bytes[N] = 123;
assert_eq!(t.write_to_prefix(&mut too_many_bytes[..]), Ok(()));
assert_eq!(&too_many_bytes[..N], t.as_bytes());
assert_eq!(too_many_bytes[N], 123);
assert!(t.write_to_suffix(&mut vec![0; N - 1][..]).is_err());
let mut bytes = [0; N];
assert_eq!(t.write_to_suffix(&mut bytes[..]), Ok(()));
assert_eq!(bytes, t.as_bytes());
let mut too_many_bytes = vec![0; N + 1];
too_many_bytes[0] = 123;
assert_eq!(t.write_to_suffix(&mut too_many_bytes[..]), Ok(()));
assert_eq!(&too_many_bytes[1..], t.as_bytes());
assert_eq!(too_many_bytes[0], 123);
}
#[derive(Debug, Eq, PartialEq, FromBytes, IntoBytes, Immutable)]
#[repr(C)]
struct Foo {
a: u32,
b: Wrapping<u32>,
c: Option<NonZeroU32>,
}
let expected_bytes: Vec<u8> = if cfg!(target_endian = "little") {
vec![1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]
} else {
vec![0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0]
};
let post_mutation_expected_a =
if cfg!(target_endian = "little") { 0x00_00_00_FE } else { 0xFF_00_00_01 };
test::<_, 12>(
&mut Foo { a: 1, b: Wrapping(2), c: None },
expected_bytes.as_bytes(),
&Foo { a: post_mutation_expected_a, b: Wrapping(2), c: None },
);
test::<_, 3>(
Unsized::from_mut_slice(&mut [1, 2, 3]),
&[1, 2, 3],
Unsized::from_mut_slice(&mut [0xFE, 2, 3]),
);
}
#[test]
fn test_array() {
#[derive(FromBytes, IntoBytes, Immutable)]
#[repr(C)]
struct Foo {
a: [u16; 33],
}
let foo = Foo { a: [0xFFFF; 33] };
let expected = [0xFFu8; 66];
assert_eq!(foo.as_bytes(), &expected[..]);
}
#[test]
fn test_display_debug() {
let buf = Align::<[u8; 8], u64>::default();
let r = Ref::<_, u64>::new(&buf.t[..]).unwrap();
assert_eq!(format!("{}", r), "0");
assert_eq!(format!("{:?}", r), "Ref(0)");
let buf = Align::<[u8; 8], u64>::default();
let r = Ref::<_, [u64]>::new(&buf.t[..]).unwrap();
assert_eq!(format!("{:?}", r), "Ref([0])");
}
#[test]
fn test_eq() {
let buf1 = 0_u64;
let r1 = Ref::<_, u64>::new(buf1.as_bytes()).unwrap();
let buf2 = 0_u64;
let r2 = Ref::<_, u64>::new(buf2.as_bytes()).unwrap();
assert_eq!(r1, r2);
}
#[test]
fn test_ne() {
let buf1 = 0_u64;
let r1 = Ref::<_, u64>::new(buf1.as_bytes()).unwrap();
let buf2 = 1_u64;
let r2 = Ref::<_, u64>::new(buf2.as_bytes()).unwrap();
assert_ne!(r1, r2);
}
#[test]
fn test_ord() {
let buf1 = 0_u64;
let r1 = Ref::<_, u64>::new(buf1.as_bytes()).unwrap();
let buf2 = 1_u64;
let r2 = Ref::<_, u64>::new(buf2.as_bytes()).unwrap();
assert!(r1 < r2);
}
#[test]
fn test_new_zeroed() {
assert!(!bool::new_zeroed());
assert_eq!(u64::new_zeroed(), 0);
#[allow(clippy::unit_cmp)]
{
assert_eq!(<()>::new_zeroed(), ());
}
}
#[test]
fn test_transparent_packed_generic_struct() {
#[derive(IntoBytes, FromBytes, Unaligned)]
#[repr(transparent)]
struct Foo<T> {
_t: T,
_phantom: PhantomData<()>,
}
assert_impl_all!(Foo<u32>: FromZeros, FromBytes, IntoBytes);
assert_impl_all!(Foo<u8>: Unaligned);
#[derive(IntoBytes, FromBytes, Unaligned)]
#[repr(packed)]
struct Bar<T, U> {
_t: T,
_u: U,
}
assert_impl_all!(Bar<u8, AU64>: FromZeros, FromBytes, IntoBytes, Unaligned);
}
#[test]
fn test_impls() {
trait TryFromBytesTestable {
fn with_passing_test_cases<F: Fn(Box<Self>)>(f: F);
fn with_failing_test_cases<F: Fn(&mut [u8])>(f: F);
}
impl<T: FromBytes> TryFromBytesTestable for T {
fn with_passing_test_cases<F: Fn(Box<Self>)>(f: F) {
f(Self::new_box_zeroed());
let ffs = {
let mut t = Self::new_zeroed();
let ptr: *mut T = &mut t;
unsafe { ptr::write_bytes(ptr.cast::<u8>(), 0xFF, mem::size_of::<T>()) };
t
};
f(Box::new(ffs));
}
fn with_failing_test_cases<F: Fn(&mut [u8])>(_f: F) {}
}
macro_rules! impl_try_from_bytes_testable_for_null_pointer_optimization {
($($tys:ty),*) => {
$(
impl TryFromBytesTestable for Option<$tys> {
fn with_passing_test_cases<F: Fn(Box<Self>)>(f: F) {
f(Box::new(None));
}
fn with_failing_test_cases<F: Fn(&mut [u8])>(f: F) {
for pos in 0..mem::size_of::<Self>() {
let mut bytes = [0u8; mem::size_of::<Self>()];
bytes[pos] = 0x01;
f(&mut bytes[..]);
}
}
}
)*
};
}
macro_rules! impl_try_from_bytes_testable {
(=> @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => {};
($ty:ty $(,$tys:ty)* => @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => {
impl TryFromBytesTestable for $ty {
impl_try_from_bytes_testable!(
@methods @success $($success_case),*
$(, @failure $($failure_case),*)?
);
}
impl_try_from_bytes_testable!($($tys),* => @success $($success_case),* $(, @failure $($failure_case),*)?);
};
($($($ty:ty),* => @success $($success_case:expr), * $(, @failure $($failure_case:expr),*)?;)*) => {
$(
impl_try_from_bytes_testable!($($ty),* => @success $($success_case),* $(, @failure $($failure_case),*)*);
)*
};
(@methods @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => {
fn with_passing_test_cases<F: Fn(Box<Self>)>(_f: F) {
$(
_f(Box::<Self>::from($success_case)); )*
}
fn with_failing_test_cases<F: Fn(&mut [u8])>(_f: F) {
$($(
#[allow(unused_qualifications)]
let mut case = $failure_case; _f(case.as_mut_bytes());
)*)?
}
};
}
impl_try_from_bytes_testable_for_null_pointer_optimization!(
Box<UnsafeCell<NotZerocopy>>,
&'static UnsafeCell<NotZerocopy>,
&'static mut UnsafeCell<NotZerocopy>,
NonNull<UnsafeCell<NotZerocopy>>,
fn(),
FnManyArgs,
extern "C" fn(),
ECFnManyArgs
);
macro_rules! bx {
($e:expr) => {
Box::new($e)
};
}
impl_try_from_bytes_testable!(
bool => @success true, false,
@failure 2u8, 3u8, 0xFFu8;
char => @success '\u{0}', '\u{D7FF}', '\u{E000}', '\u{10FFFF}',
@failure 0xD800u32, 0xDFFFu32, 0x110000u32;
str => @success "", "hello", "❤️🧡💛💚💙💜",
@failure [0, 159, 146, 150];
[u8] => @success vec![].into_boxed_slice(), vec![0, 1, 2].into_boxed_slice();
NonZeroU8, NonZeroI8, NonZeroU16, NonZeroI16, NonZeroU32,
NonZeroI32, NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128,
NonZeroUsize, NonZeroIsize
=> @success Self::new(1).unwrap(),
@failure Option::<Self>::None;
[bool; 0] => @success [];
[bool; 1]
=> @success [true], [false],
@failure [2u8], [3u8], [0xFFu8];
[bool]
=> @success vec![true, false].into_boxed_slice(), vec![false, true].into_boxed_slice(),
@failure [2u8], [3u8], [0xFFu8], [0u8, 1u8, 2u8];
Unalign<bool>
=> @success Unalign::new(false), Unalign::new(true),
@failure 2u8, 0xFFu8;
ManuallyDrop<bool>
=> @success ManuallyDrop::new(false), ManuallyDrop::new(true),
@failure 2u8, 0xFFu8;
ManuallyDrop<[u8]>
=> @success bx!(ManuallyDrop::new([])), bx!(ManuallyDrop::new([0u8])), bx!(ManuallyDrop::new([0u8, 1u8]));
ManuallyDrop<[bool]>
=> @success bx!(ManuallyDrop::new([])), bx!(ManuallyDrop::new([false])), bx!(ManuallyDrop::new([false, true])),
@failure [2u8], [3u8], [0xFFu8], [0u8, 1u8, 2u8];
ManuallyDrop<[UnsafeCell<u8>]>
=> @success bx!(ManuallyDrop::new([UnsafeCell::new(0)])), bx!(ManuallyDrop::new([UnsafeCell::new(0), UnsafeCell::new(1)]));
ManuallyDrop<[UnsafeCell<bool>]>
=> @success bx!(ManuallyDrop::new([UnsafeCell::new(false)])), bx!(ManuallyDrop::new([UnsafeCell::new(false), UnsafeCell::new(true)])),
@failure [2u8], [3u8], [0xFFu8], [0u8, 1u8, 2u8];
Wrapping<bool>
=> @success Wrapping(false), Wrapping(true),
@failure 2u8, 0xFFu8;
*const NotZerocopy
=> @success ptr::null::<NotZerocopy>(),
@failure [0x01; mem::size_of::<*const NotZerocopy>()];
*mut NotZerocopy
=> @success ptr::null_mut::<NotZerocopy>(),
@failure [0x01; mem::size_of::<*mut NotZerocopy>()];
);
mod autoref_trick {
use super::*;
pub(super) struct AutorefWrapper<T: ?Sized>(pub(super) PhantomData<T>);
pub(super) trait TestIsBitValidShared<T: ?Sized> {
#[allow(clippy::needless_lifetimes)]
fn test_is_bit_valid_shared<
'ptr,
A: invariant::Aliasing + invariant::AtLeast<invariant::Shared>,
>(
&self,
candidate: Maybe<'ptr, T, A>,
) -> Option<bool>;
}
impl<T: TryFromBytes + Immutable + ?Sized> TestIsBitValidShared<T> for AutorefWrapper<T> {
#[allow(clippy::needless_lifetimes)]
fn test_is_bit_valid_shared<
'ptr,
A: invariant::Aliasing + invariant::AtLeast<invariant::Shared>,
>(
&self,
candidate: Maybe<'ptr, T, A>,
) -> Option<bool> {
Some(T::is_bit_valid(candidate))
}
}
pub(super) trait TestTryFromRef<T: ?Sized> {
#[allow(clippy::needless_lifetimes)]
fn test_try_from_ref<'bytes>(
&self,
bytes: &'bytes [u8],
) -> Option<Option<&'bytes T>>;
#[allow(clippy::needless_lifetimes)]
fn test_try_from_mut<'bytes>(
&self,
bytes: &'bytes mut [u8],
) -> Option<Option<&'bytes mut T>>;
}
impl<T: TryFromBytes + Immutable + KnownLayout + ?Sized> TestTryFromRef<T> for AutorefWrapper<T> {
#[allow(clippy::needless_lifetimes)]
fn test_try_from_ref<'bytes>(
&self,
bytes: &'bytes [u8],
) -> Option<Option<&'bytes T>> {
Some(T::try_ref_from(bytes).ok())
}
#[allow(clippy::needless_lifetimes)]
fn test_try_from_mut<'bytes>(
&self,
bytes: &'bytes mut [u8],
) -> Option<Option<&'bytes mut T>> {
Some(T::try_mut_from(bytes).ok())
}
}
pub(super) trait TestTryReadFrom<T> {
fn test_try_read_from(&self, bytes: &[u8]) -> Option<Option<T>>;
}
impl<T: TryFromBytes> TestTryReadFrom<T> for AutorefWrapper<T> {
fn test_try_read_from(&self, bytes: &[u8]) -> Option<Option<T>> {
Some(T::try_read_from(bytes).ok())
}
}
pub(super) trait TestAsBytes<T: ?Sized> {
#[allow(clippy::needless_lifetimes)]
fn test_as_bytes<'slf, 't>(&'slf self, t: &'t T) -> Option<&'t [u8]>;
}
impl<T: IntoBytes + Immutable + ?Sized> TestAsBytes<T> for AutorefWrapper<T> {
#[allow(clippy::needless_lifetimes)]
fn test_as_bytes<'slf, 't>(&'slf self, t: &'t T) -> Option<&'t [u8]> {
Some(t.as_bytes())
}
}
}
use autoref_trick::*;
macro_rules! assert_on_allowlist {
($fn_name:ident($ty:ty) $(: $($tys:ty),*)?) => {{
use core::any::TypeId;
let allowlist: &[TypeId] = &[ $($(TypeId::of::<$tys>()),*)? ];
let allowlist_names: &[&str] = &[ $($(stringify!($tys)),*)? ];
let id = TypeId::of::<$ty>();
assert!(allowlist.contains(&id), "{} is not on allowlist for {}: {:?}", stringify!($ty), stringify!($fn_name), allowlist_names);
}};
}
// Asserts that `$ty` implements any `$trait` and doesn't implement any
// `!$trait`. Note that all `$trait`s must come before any `!$trait`s.
//
// For `T: TryFromBytes`, uses `TryFromBytesTestable` to test success
// and failure cases.
macro_rules! assert_impls {
($ty:ty: TryFromBytes) => {
// "Default" implementations that match the "real"
// implementations defined in the `autoref_trick` module above.
#[allow(unused, non_local_definitions)]
impl AutorefWrapper<$ty> {
#[allow(clippy::needless_lifetimes)]
fn test_is_bit_valid_shared<'ptr, A: invariant::Aliasing + invariant::AtLeast<invariant::Shared>>(
&mut self,
candidate: Maybe<'ptr, $ty, A>,
) -> Option<bool> {
assert_on_allowlist!(
test_is_bit_valid_shared($ty):
ManuallyDrop<UnsafeCell<()>>,
ManuallyDrop<[UnsafeCell<u8>]>,
ManuallyDrop<[UnsafeCell<bool>]>,
MaybeUninit<NotZerocopy>,
MaybeUninit<UnsafeCell<()>>,
Wrapping<UnsafeCell<()>>
);
None
}
#[allow(clippy::needless_lifetimes)]
fn test_try_from_ref<'bytes>(&mut self, _bytes: &'bytes [u8]) -> Option<Option<&'bytes $ty>> {
assert_on_allowlist!(
test_try_from_ref($ty):
ManuallyDrop<[UnsafeCell<bool>]>
);
None
}
#[allow(clippy::needless_lifetimes)]
fn test_try_from_mut<'bytes>(&mut self, _bytes: &'bytes mut [u8]) -> Option<Option<&'bytes mut $ty>> {
assert_on_allowlist!(
test_try_from_mut($ty):
ManuallyDrop<[UnsafeCell<bool>]>
);
None
}
fn test_try_read_from(&mut self, _bytes: &[u8]) -> Option<Option<&$ty>> {
assert_on_allowlist!(
test_try_read_from($ty):
str,
ManuallyDrop<[u8]>,
ManuallyDrop<[bool]>,
ManuallyDrop<[UnsafeCell<bool>]>,
[u8],
[bool]
);
None
}
fn test_as_bytes(&mut self, _t: &$ty) -> Option<&[u8]> {
assert_on_allowlist!(
test_as_bytes($ty):
Option<&'static UnsafeCell<NotZerocopy>>,
Option<&'static mut UnsafeCell<NotZerocopy>>,
Option<NonNull<UnsafeCell<NotZerocopy>>>,
Option<Box<UnsafeCell<NotZerocopy>>>,
Option<fn()>,
Option<FnManyArgs>,
Option<extern "C" fn()>,
Option<ECFnManyArgs>,
MaybeUninit<u8>,
MaybeUninit<NotZerocopy>,
MaybeUninit<UnsafeCell<()>>,
ManuallyDrop<UnsafeCell<()>>,
ManuallyDrop<[UnsafeCell<u8>]>,
ManuallyDrop<[UnsafeCell<bool>]>,
Wrapping<UnsafeCell<()>>,
*const NotZerocopy,
*mut NotZerocopy
);
None
}
}
<$ty as TryFromBytesTestable>::with_passing_test_cases(|mut val| {
// TODO(#494): These tests only get exercised for types
// which are `IntoBytes`. Once we implement #494, we should
// be able to support non-`IntoBytes` types by zeroing
// padding.
// We define `w` and `ww` since, in the case of the inherent
// methods, Rust thinks they're both borrowed mutably at the
// same time (given how we use them below). If we just
// defined a single `w` and used it for multiple operations,
// this would conflict.
//
// We `#[allow(unused_mut]` for the cases where the "real"
// impls are used, which take `&self`.
#[allow(unused_mut)]
let (mut w, mut ww) = (AutorefWrapper::<$ty>(PhantomData), AutorefWrapper::<$ty>(PhantomData));
let c = Ptr::from_ref(&*val);
let c = c.forget_aligned();
// SAFETY: TODO(#899): This is unsound. `$ty` is not
// necessarily `IntoBytes`, but that's the corner we've
// backed ourselves into by using `Ptr::from_ref`.
let c = unsafe { c.assume_initialized() };
let res = w.test_is_bit_valid_shared(c);
if let Some(res) = res {
assert!(res, "{}::is_bit_valid({:?}) (shared `Ptr`): got false, expected true", stringify!($ty), val);
}
let c = Ptr::from_mut(&mut *val);
let c = c.forget_aligned();
// SAFETY: TODO(#899): This is unsound. `$ty` is not
// necessarily `IntoBytes`, but that's the corner we've
// backed ourselves into by using `Ptr::from_ref`.
let c = unsafe { c.assume_initialized() };
let res = <$ty as TryFromBytes>::is_bit_valid(c);
assert!(res, "{}::is_bit_valid({:?}) (exclusive `Ptr`): got false, expected true", stringify!($ty), val);
// `bytes` is `Some(val.as_bytes())` if `$ty: IntoBytes +
// Immutable` and `None` otherwise.
let bytes = w.test_as_bytes(&*val);
// The inner closure returns
// `Some($ty::try_ref_from(bytes))` if `$ty: Immutable` and
// `None` otherwise.
let res = bytes.and_then(|bytes| ww.test_try_from_ref(bytes));
if let Some(res) = res {
assert!(res.is_some(), "{}::try_ref_from({:?}): got `None`, expected `Some`", stringify!($ty), val);
}
if let Some(bytes) = bytes {
// We need to get a mutable byte slice, and so we clone
// into a `Vec`. However, we also need these bytes to
// satisfy `$ty`'s alignment requirement, which isn't
// guaranteed for `Vec<u8>`. In order to get around
// this, we create a `Vec` which is twice as long as we
// need. There is guaranteed to be an aligned byte range
// of size `size_of_val(val)` within that range.
let val = &*val;
let size = mem::size_of_val(val);
let align = mem::align_of_val(val);
let mut vec = bytes.to_vec();
vec.extend(bytes);
let slc = vec.as_slice();
let offset = slc.as_ptr().align_offset(align);
let bytes_mut = &mut vec.as_mut_slice()[offset..offset+size];
bytes_mut.copy_from_slice(bytes);
let res = ww.test_try_from_mut(bytes_mut);
if let Some(res) = res {
assert!(res.is_some(), "{}::try_mut_from({:?}): got `None`, expected `Some`", stringify!($ty), val);
}
}
let res = bytes.and_then(|bytes| ww.test_try_read_from(bytes));
if let Some(res) = res {
assert!(res.is_some(), "{}::try_read_from({:?}): got `None`, expected `Some`", stringify!($ty), val);
}
});
#[allow(clippy::as_conversions)]
<$ty as TryFromBytesTestable>::with_failing_test_cases(|c| {
#[allow(unused_mut)] // For cases where the "real" impls are used, which take `&self`.
let mut w = AutorefWrapper::<$ty>(PhantomData);
// This is `Some($ty::try_ref_from(c))` if `$ty: Immutable` and
// `None` otherwise.
let res = w.test_try_from_ref(c);
if let Some(res) = res {
assert!(res.is_none(), "{}::try_ref_from({:?}): got Some, expected None", stringify!($ty), c);
}
let res = w.test_try_from_mut(c);
if let Some(res) = res {
assert!(res.is_none(), "{}::try_mut_from({:?}): got Some, expected None", stringify!($ty), c);
}
let res = w.test_try_read_from(c);
if let Some(res) = res {
assert!(res.is_none(), "{}::try_read_from({:?}): got Some, expected None", stringify!($ty), c);
}
});
#[allow(dead_code)]
const _: () = { static_assertions::assert_impl_all!($ty: TryFromBytes); };
};
($ty:ty: $trait:ident) => {
#[allow(dead_code)]
const _: () = { static_assertions::assert_impl_all!($ty: $trait); };
};
($ty:ty: !$trait:ident) => {
#[allow(dead_code)]
const _: () = { static_assertions::assert_not_impl_any!($ty: $trait); };
};
($ty:ty: $($trait:ident),* $(,)? $(!$negative_trait:ident),*) => {
$(
assert_impls!($ty: $trait);
)*
$(
assert_impls!($ty: !$negative_trait);
)*
};
}
// NOTE: The negative impl assertions here are not necessarily
// prescriptive. They merely serve as change detectors to make sure
// we're aware of what trait impls are getting added with a given
// change. Of course, some impls would be invalid (e.g., `bool:
// FromBytes`), and so this change detection is very important.
assert_impls!(
(): KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
Unaligned
);
assert_impls!(
u8: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
Unaligned
);
assert_impls!(
i8: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
Unaligned
);
assert_impls!(
u16: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
i16: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
u32: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
i32: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
u64: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
i64: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
u128: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
i128: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
usize: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
isize: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
f32: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
f64: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
!Unaligned
);
assert_impls!(
bool: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
IntoBytes,
Unaligned,
!FromBytes
);
assert_impls!(
char: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
str: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
IntoBytes,
Unaligned,
!FromBytes
);
assert_impls!(
NonZeroU8: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
Unaligned,
!FromZeros,
!FromBytes
);
assert_impls!(
NonZeroI8: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
Unaligned,
!FromZeros,
!FromBytes
);
assert_impls!(
NonZeroU16: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroI16: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroU32: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroI32: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroU64: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroI64: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroU128: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroI128: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroUsize: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(
NonZeroIsize: KnownLayout,
Immutable,
TryFromBytes,
IntoBytes,
!FromBytes,
!Unaligned
);
assert_impls!(Option<NonZeroU8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_impls!(Option<NonZeroI8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_impls!(Option<NonZeroU16>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroI16>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroU32>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroI32>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroU64>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroI64>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroU128>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroI128>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroUsize>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
assert_impls!(Option<NonZeroIsize>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned);
// Implements none of the ZC traits.
struct NotZerocopy;
#[rustfmt::skip]
type FnManyArgs = fn(
NotZerocopy, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8,
) -> (NotZerocopy, NotZerocopy);
// Allowed, because we're not actually using this type for FFI.
#[allow(improper_ctypes_definitions)]
#[rustfmt::skip]
type ECFnManyArgs = extern "C" fn(
NotZerocopy, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8,
) -> (NotZerocopy, NotZerocopy);
#[cfg(feature = "alloc")]
assert_impls!(Option<Box<UnsafeCell<NotZerocopy>>>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<Box<[UnsafeCell<NotZerocopy>]>>: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<&'static UnsafeCell<NotZerocopy>>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<&'static [UnsafeCell<NotZerocopy>]>: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<&'static mut UnsafeCell<NotZerocopy>>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<&'static mut [UnsafeCell<NotZerocopy>]>: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<NonNull<UnsafeCell<NotZerocopy>>>: KnownLayout, TryFromBytes, FromZeros, Immutable, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<NonNull<[UnsafeCell<NotZerocopy>]>>: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<fn()>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<FnManyArgs>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<extern "C" fn()>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Option<ECFnManyArgs>: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(PhantomData<NotZerocopy>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_impls!(PhantomData<UnsafeCell<()>>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_impls!(PhantomData<[u8]>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
assert_impls!(ManuallyDrop<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
// This test is important because it allows us to test our hand-rolled
// implementation of `<ManuallyDrop<T> as TryFromBytes>::is_bit_valid`.
assert_impls!(ManuallyDrop<bool>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
assert_impls!(ManuallyDrop<[u8]>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
// This test is important because it allows us to test our hand-rolled
// implementation of `<ManuallyDrop<T> as TryFromBytes>::is_bit_valid`.
assert_impls!(ManuallyDrop<[bool]>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
assert_impls!(ManuallyDrop<NotZerocopy>: !Immutable, !TryFromBytes, !KnownLayout, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(ManuallyDrop<[NotZerocopy]>: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(ManuallyDrop<UnsafeCell<()>>: KnownLayout, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned, !Immutable);
assert_impls!(ManuallyDrop<[UnsafeCell<u8>]>: KnownLayout, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned, !Immutable);
assert_impls!(ManuallyDrop<[UnsafeCell<bool>]>: KnownLayout, TryFromBytes, FromZeros, IntoBytes, Unaligned, !Immutable, !FromBytes);
assert_impls!(MaybeUninit<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, Unaligned, !IntoBytes);
assert_impls!(MaybeUninit<NotZerocopy>: KnownLayout, TryFromBytes, FromZeros, FromBytes, !Immutable, !IntoBytes, !Unaligned);
assert_impls!(MaybeUninit<UnsafeCell<()>>: KnownLayout, TryFromBytes, FromZeros, FromBytes, Unaligned, !Immutable, !IntoBytes);
assert_impls!(Wrapping<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
// This test is important because it allows us to test our hand-rolled
// implementation of `<Wrapping<T> as TryFromBytes>::is_bit_valid`.
assert_impls!(Wrapping<bool>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
assert_impls!(Wrapping<NotZerocopy>: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(Wrapping<UnsafeCell<()>>: KnownLayout, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned, !Immutable);
assert_impls!(Unalign<u8>: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, Unaligned);
// This test is important because it allows us to test our hand-rolled
// implementation of `<Unalign<T> as TryFromBytes>::is_bit_valid`.
assert_impls!(Unalign<bool>: KnownLayout, Immutable, TryFromBytes, FromZeros, IntoBytes, Unaligned, !FromBytes);
assert_impls!(Unalign<NotZerocopy>: Unaligned, !Immutable, !KnownLayout, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes);
assert_impls!(
[u8]: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
Unaligned
);
assert_impls!(
[bool]: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
IntoBytes,
Unaligned,
!FromBytes
);
assert_impls!([NotZerocopy]: KnownLayout, !Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(
[u8; 0]: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
Unaligned,
);
assert_impls!(
[NotZerocopy; 0]: KnownLayout,
!Immutable,
!TryFromBytes,
!FromZeros,
!FromBytes,
!IntoBytes,
!Unaligned
);
assert_impls!(
[u8; 1]: KnownLayout,
Immutable,
TryFromBytes,
FromZeros,
FromBytes,
IntoBytes,
Unaligned,
);
assert_impls!(
[NotZerocopy; 1]: KnownLayout,
!Immutable,
!TryFromBytes,
!FromZeros,
!FromBytes,
!IntoBytes,
!Unaligned
);
assert_impls!(*const NotZerocopy: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(*mut NotZerocopy: KnownLayout, Immutable, TryFromBytes, FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(*const [NotZerocopy]: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(*mut [NotZerocopy]: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(*const dyn Debug: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
assert_impls!(*mut dyn Debug: KnownLayout, Immutable, !TryFromBytes, !FromZeros, !FromBytes, !IntoBytes, !Unaligned);
#[cfg(feature = "simd")]
{
#[allow(unused_macros)]
macro_rules! test_simd_arch_mod {
($arch:ident, $($typ:ident),*) => {
{
use core::arch::$arch::{$($typ),*};
use crate::*;
$( assert_impls!($typ: KnownLayout, Immutable, TryFromBytes, FromZeros, FromBytes, IntoBytes, !Unaligned); )*
}
};
}
#[cfg(target_arch = "x86")]
test_simd_arch_mod!(x86, __m128, __m128d, __m128i, __m256, __m256d, __m256i);
#[cfg(all(feature = "simd-nightly", target_arch = "x86"))]
test_simd_arch_mod!(x86, __m512bh, __m512, __m512d, __m512i);
#[cfg(target_arch = "x86_64")]
test_simd_arch_mod!(x86_64, __m128, __m128d, __m128i, __m256, __m256d, __m256i);
#[cfg(all(feature = "simd-nightly", target_arch = "x86_64"))]
test_simd_arch_mod!(x86_64, __m512bh, __m512, __m512d, __m512i);
#[cfg(target_arch = "wasm32")]
test_simd_arch_mod!(wasm32, v128);
#[cfg(all(feature = "simd-nightly", target_arch = "powerpc"))]
test_simd_arch_mod!(
powerpc,
vector_bool_long,
vector_double,
vector_signed_long,
vector_unsigned_long
);
#[cfg(all(feature = "simd-nightly", target_arch = "powerpc64"))]
test_simd_arch_mod!(
powerpc64,
vector_bool_long,
vector_double,
vector_signed_long,
vector_unsigned_long
);
#[cfg(all(target_arch = "aarch64", zerocopy_aarch64_simd))]
#[rustfmt::skip]
test_simd_arch_mod!(
aarch64, float32x2_t, float32x4_t, float64x1_t, float64x2_t, int8x8_t, int8x8x2_t,
int8x8x3_t, int8x8x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int16x4_t,
int16x8_t, int32x2_t, int32x4_t, int64x1_t, int64x2_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t,
poly8x8x4_t, poly8x16_t, poly8x16x2_t, poly8x16x3_t, poly8x16x4_t, poly16x4_t, poly16x8_t,
poly64x1_t, poly64x2_t, uint8x8_t, uint8x8x2_t, uint8x8x3_t, uint8x8x4_t, uint8x16_t,
uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint16x4_t, uint16x8_t, uint32x2_t, uint32x4_t,
uint64x1_t, uint64x2_t
);
#[cfg(all(feature = "simd-nightly", target_arch = "arm"))]
#[rustfmt::skip]
test_simd_arch_mod!(arm, int8x4_t, uint8x4_t);
}
}
}
#[cfg(kani)]
mod proofs {
use super::*;
impl kani::Arbitrary for DstLayout {
fn any() -> Self {
let align: NonZeroUsize = kani::any();
let size_info: SizeInfo = kani::any();
kani::assume(align.is_power_of_two());
kani::assume(align < DstLayout::THEORETICAL_MAX_ALIGN);
// For testing purposes, we most care about instantiations of
// `DstLayout` that can correspond to actual Rust types. We use
// `Layout` to verify that our `DstLayout` satisfies the validity
// conditions of Rust layouts.
kani::assume(
match size_info {
SizeInfo::Sized { size } => Layout::from_size_align(size, align.get()),
SizeInfo::SliceDst(TrailingSliceLayout { offset, elem_size: _ }) => {
// `SliceDst`` cannot encode an exact size, but we know
// it is at least `offset` bytes.
Layout::from_size_align(offset, align.get())
}
}
.is_ok(),
);
Self { align: align, size_info: size_info }
}
}
impl kani::Arbitrary for SizeInfo {
fn any() -> Self {
let is_sized: bool = kani::any();
match is_sized {
true => {
let size: usize = kani::any();
kani::assume(size <= isize::MAX as _);
SizeInfo::Sized { size }
}
false => SizeInfo::SliceDst(kani::any()),
}
}
}
impl kani::Arbitrary for TrailingSliceLayout {
fn any() -> Self {
let elem_size: usize = kani::any();
let offset: usize = kani::any();
kani::assume(elem_size < isize::MAX as _);
kani::assume(offset < isize::MAX as _);
TrailingSliceLayout { elem_size, offset }
}
}
#[kani::proof]
fn prove_dst_layout_extend() {
use crate::util::{max, min, padding_needed_for};
let base: DstLayout = kani::any();
let field: DstLayout = kani::any();
let packed: Option<NonZeroUsize> = kani::any();
if let Some(max_align) = packed {
kani::assume(max_align.is_power_of_two());
kani::assume(base.align <= max_align);
}
// The base can only be extended if it's sized.
kani::assume(matches!(base.size_info, SizeInfo::Sized { .. }));
let base_size = if let SizeInfo::Sized { size } = base.size_info {
size
} else {
unreachable!();
};
// Under the above conditions, `DstLayout::extend` will not panic.
let composite = base.extend(field, packed);
// The field's alignment is clamped by `max_align` (i.e., the
// `packed` attribute, if any) [1].
//
// [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers:
//
// The alignments of each field, for the purpose of positioning
// fields, is the smaller of the specified alignment and the
// alignment of the field's type.
let field_align = min(field.align, packed.unwrap_or(DstLayout::THEORETICAL_MAX_ALIGN));
// The struct's alignment is the maximum of its previous alignment and
// `field_align`.
assert_eq!(composite.align, max(base.align, field_align));
// Compute the minimum amount of inter-field padding needed to
// satisfy the field's alignment, and offset of the trailing field.
// [1]
//
// [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers:
//
// Inter-field padding is guaranteed to be the minimum required in
// order to satisfy each field's (possibly altered) alignment.
let padding = padding_needed_for(base_size, field_align);
let offset = base_size + padding;
// For testing purposes, we'll also construct `alloc::Layout`
// stand-ins for `DstLayout`, and show that `extend` behaves
// comparably on both types.
let base_analog = Layout::from_size_align(base_size, base.align.get()).unwrap();
match field.size_info {
SizeInfo::Sized { size: field_size } => {
if let SizeInfo::Sized { size: composite_size } = composite.size_info {
// If the trailing field is sized, the resulting layout
// will be sized. Its size will be the sum of the
// preceeding layout, the size of the new field, and the
// size of inter-field padding between the two.
assert_eq!(composite_size, offset + field_size);
let field_analog =
Layout::from_size_align(field_size, field_align.get()).unwrap();
if let Ok((actual_composite, actual_offset)) = base_analog.extend(field_analog)
{
assert_eq!(actual_offset, offset);
assert_eq!(actual_composite.size(), composite_size);
assert_eq!(actual_composite.align(), composite.align.get());
} else {
// An error here reflects that composite of `base`
// and `field` cannot correspond to a real Rust type
// fragment, because such a fragment would violate
// the basic invariants of a valid Rust layout. At
// the time of writing, `DstLayout` is a little more
// permissive than `Layout`, so we don't assert
// anything in this branch (e.g., unreachability).
}
} else {
panic!("The composite of two sized layouts must be sized.")
}
}
SizeInfo::SliceDst(TrailingSliceLayout {
offset: field_offset,
elem_size: field_elem_size,
}) => {
if let SizeInfo::SliceDst(TrailingSliceLayout {
offset: composite_offset,
elem_size: composite_elem_size,
}) = composite.size_info
{
// The offset of the trailing slice component is the sum
// of the offset of the trailing field and the trailing
// slice offset within that field.
assert_eq!(composite_offset, offset + field_offset);
// The elem size is unchanged.
assert_eq!(composite_elem_size, field_elem_size);
let field_analog =
Layout::from_size_align(field_offset, field_align.get()).unwrap();
if let Ok((actual_composite, actual_offset)) = base_analog.extend(field_analog)
{
assert_eq!(actual_offset, offset);
assert_eq!(actual_composite.size(), composite_offset);
assert_eq!(actual_composite.align(), composite.align.get());
} else {
// An error here reflects that composite of `base`
// and `field` cannot correspond to a real Rust type
// fragment, because such a fragment would violate
// the basic invariants of a valid Rust layout. At
// the time of writing, `DstLayout` is a little more
// permissive than `Layout`, so we don't assert
// anything in this branch (e.g., unreachability).
}
} else {
panic!("The extension of a layout with a DST must result in a DST.")
}
}
}
}
#[kani::proof]
#[kani::should_panic]
fn prove_dst_layout_extend_dst_panics() {
let base: DstLayout = kani::any();
let field: DstLayout = kani::any();
let packed: Option<NonZeroUsize> = kani::any();
if let Some(max_align) = packed {
kani::assume(max_align.is_power_of_two());
kani::assume(base.align <= max_align);
}
kani::assume(matches!(base.size_info, SizeInfo::SliceDst(..)));
let _ = base.extend(field, packed);
}
#[kani::proof]
fn prove_dst_layout_pad_to_align() {
use crate::util::padding_needed_for;
let layout: DstLayout = kani::any();
let padded: DstLayout = layout.pad_to_align();
// Calling `pad_to_align` does not alter the `DstLayout`'s alignment.
assert_eq!(padded.align, layout.align);
if let SizeInfo::Sized { size: unpadded_size } = layout.size_info {
if let SizeInfo::Sized { size: padded_size } = padded.size_info {
// If the layout is sized, it will remain sized after padding is
// added. Its sum will be its unpadded size and the size of the
// trailing padding needed to satisfy its alignment
// requirements.
let padding = padding_needed_for(unpadded_size, layout.align);
assert_eq!(padded_size, unpadded_size + padding);
// Prove that calling `DstLayout::pad_to_align` behaves
// identically to `Layout::pad_to_align`.
let layout_analog =
Layout::from_size_align(unpadded_size, layout.align.get()).unwrap();
let padded_analog = layout_analog.pad_to_align();
assert_eq!(padded_analog.align(), layout.align.get());
assert_eq!(padded_analog.size(), padded_size);
} else {
panic!("The padding of a sized layout must result in a sized layout.")
}
} else {
// If the layout is a DST, padding cannot be statically added.
assert_eq!(padded.size_info, layout.size_info);
}
}
}