rename NoPadding to NoUninit and clarify docs (#95)

This commit is contained in:
Gray Olson 2022-03-29 20:25:51 -07:00 committed by GitHub
parent 1652a2dcd2
commit 1fb245c926
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 87 additions and 87 deletions

View File

@ -9,7 +9,7 @@ use quote::{quote, quote_spanned};
use syn::{parse_macro_input, DeriveInput, spanned::Spanned}; use syn::{parse_macro_input, DeriveInput, spanned::Spanned};
use crate::traits::{ use crate::traits::{
AnyBitPattern, Contiguous, Derivable, CheckedBitPattern, NoPadding, Pod, TransparentWrapper, Zeroable, AnyBitPattern, Contiguous, Derivable, CheckedBitPattern, NoUninit, Pod, TransparentWrapper, Zeroable,
}; };
/// Derive the `Pod` trait for a struct /// Derive the `Pod` trait for a struct
@ -93,17 +93,17 @@ pub fn derive_zeroable(
proc_macro::TokenStream::from(expanded) proc_macro::TokenStream::from(expanded)
} }
/// Derive the `NoPadding` trait for a struct or enum /// Derive the `NoUninit` trait for a struct or enum
/// ///
/// The macro ensures that the type follows all the the safety requirements /// The macro ensures that the type follows all the the safety requirements
/// for the `NoPadding` trait. /// for the `NoUninit` trait.
/// ///
/// The following constraints need to be satisfied for the macro to succeed /// The following constraints need to be satisfied for the macro to succeed
/// (the rest of the constraints are guaranteed by the `NoPadding` subtrait bounds, /// (the rest of the constraints are guaranteed by the `NoUninit` subtrait bounds,
/// i.e. the type must be `Sized + Copy + 'static`): /// i.e. the type must be `Sized + Copy + 'static`):
/// ///
/// If applied to a struct: /// If applied to a struct:
/// - All fields in the struct must implement `NoPadding` /// - All fields in the struct must implement `NoUninit`
/// - The struct must be `#[repr(C)]` or `#[repr(transparent)]` /// - The struct must be `#[repr(C)]` or `#[repr(transparent)]`
/// - The struct must not contain any padding bytes /// - The struct must not contain any padding bytes
/// - The struct must contain no generic parameters /// - The struct must contain no generic parameters
@ -112,12 +112,12 @@ pub fn derive_zeroable(
/// - The enum must be explicit `#[repr(Int)]` /// - The enum must be explicit `#[repr(Int)]`
/// - All variants must be fieldless /// - All variants must be fieldless
/// - The enum must contain no generic parameters /// - The enum must contain no generic parameters
#[proc_macro_derive(NoPadding)] #[proc_macro_derive(NoUninit)]
pub fn derive_no_padding( pub fn derive_no_uninit(
input: proc_macro::TokenStream, input: proc_macro::TokenStream,
) -> proc_macro::TokenStream { ) -> proc_macro::TokenStream {
let expanded = let expanded =
derive_marker_trait::<NoPadding>(parse_macro_input!(input as DeriveInput)); derive_marker_trait::<NoUninit>(parse_macro_input!(input as DeriveInput));
proc_macro::TokenStream::from(expanded) proc_macro::TokenStream::from(expanded)
} }
@ -130,14 +130,14 @@ pub fn derive_no_padding(
/// ///
/// The following constraints need to be satisfied for the macro to succeed /// The following constraints need to be satisfied for the macro to succeed
/// (the rest of the constraints are guaranteed by the `CheckedBitPattern` subtrait bounds, /// (the rest of the constraints are guaranteed by the `CheckedBitPattern` subtrait bounds,
/// i.e. are guaranteed by the requirements of the `NoPadding` trait which `CheckedBitPattern` /// i.e. are guaranteed by the requirements of the `NoUninit` trait which `CheckedBitPattern`
/// is a subtrait of): /// is a subtrait of):
/// ///
/// If applied to a struct: /// If applied to a struct:
/// - All fields must implement `CheckedBitPattern` /// - All fields must implement `CheckedBitPattern`
/// ///
/// If applied to an enum: /// If applied to an enum:
/// - All requirements already checked by `NoPadding`, just impls the trait /// - All requirements already checked by `NoUninit`, just impls the trait
#[proc_macro_derive(CheckedBitPattern)] #[proc_macro_derive(CheckedBitPattern)]
pub fn derive_maybe_pod( pub fn derive_maybe_pod(
input: proc_macro::TokenStream, input: proc_macro::TokenStream,

View File

@ -107,11 +107,11 @@ impl Derivable for Zeroable {
} }
} }
pub struct NoPadding; pub struct NoUninit;
impl Derivable for NoPadding { impl Derivable for NoUninit {
fn ident() -> TokenStream { fn ident() -> TokenStream {
quote!(::bytemuck::NoPadding) quote!(::bytemuck::NoUninit)
} }
fn check_attributes( fn check_attributes(
@ -121,20 +121,20 @@ impl Derivable for NoPadding {
match ty { match ty {
Data::Struct(_) => match repr.as_deref() { Data::Struct(_) => match repr.as_deref() {
Some("C" | "transparent") => Ok(()), Some("C" | "transparent") => Ok(()),
_ => Err("NoPadding derive requires the type to be #[repr(C)] or #[repr(transparent)]"), _ => Err("NoUninit requires the struct to be #[repr(C)] or #[repr(transparent)]"),
}, },
Data::Enum(_) => if repr.map(|repr| repr.starts_with('u') || repr.starts_with('i')) == Some(true) { Data::Enum(_) => if repr.map(|repr| repr.starts_with('u') || repr.starts_with('i')) == Some(true) {
Ok(()) Ok(())
} else { } else {
Err("NoPadding requires the enum to be an explicit #[repr(Int)]") Err("NoUninit requires the enum to be an explicit #[repr(Int)]")
}, },
Data::Union(_) => Err("NoPadding cannot be derived for unions") Data::Union(_) => Err("NoUninit can only be derived on enums and structs")
} }
} }
fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> { fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
if !input.generics.params.is_empty() { if !input.generics.params.is_empty() {
return Err("NoPadding cannot be derived for structs containing generic parameters because the padding requirements can't be verified for generic structs"); return Err("NoUninit cannot be derived for structs containing generic parameters because the padding requirements can't be verified for generic structs");
} }
match &input.data { match &input.data {
@ -150,12 +150,12 @@ impl Derivable for NoPadding {
} }
Data::Enum(DataEnum { variants, .. }) => { Data::Enum(DataEnum { variants, .. }) => {
if variants.iter().any(|variant| !variant.fields.is_empty()) { if variants.iter().any(|variant| !variant.fields.is_empty()) {
Err("Only fieldless enums are supported for NoPadding") Err("Only fieldless enums are supported for NoUninit")
} else { } else {
Ok(quote!()) Ok(quote!())
} }
} }
Data::Union(_) => Err("NoPadding cannot be derived for unions") Data::Union(_) => Err("NoUninit cannot be derived for unions"), // shouldn't be possible since we already error in attribute check for this case
} }
} }
@ -203,7 +203,7 @@ impl Derivable for CheckedBitPattern {
Ok(assert_fields_are_maybe_pod) Ok(assert_fields_are_maybe_pod)
} }
Data::Enum(_) => Ok(quote!()), // nothing needed, already guaranteed OK by NoPadding Data::Enum(_) => Ok(quote!()), // nothing needed, already guaranteed OK by NoUninit
Data::Union(_) => Err("Internal error in CheckedBitPattern derive"), // shouldn't be possible since we already error in attribute check for this case Data::Union(_) => Err("Internal error in CheckedBitPattern derive"), // shouldn't be possible since we already error in attribute check for this case
} }
} }

View File

@ -1,7 +1,7 @@
#![allow(dead_code)] #![allow(dead_code)]
use bytemuck::{ use bytemuck::{
Contiguous, CheckedBitPattern, NoPadding, Pod, TransparentWrapper, Zeroable, AnyBitPattern, AnyBitPattern, Contiguous, CheckedBitPattern, NoUninit, Pod, TransparentWrapper, Zeroable,
}; };
use std::marker::PhantomData; use std::marker::PhantomData;
@ -51,9 +51,9 @@ enum ContiguousWithImplicitValues {
E, E,
} }
#[derive(Copy, Clone, NoPadding)] #[derive(Copy, Clone, NoUninit)]
#[repr(C)] #[repr(C)]
struct NoPaddingTest { struct NoUninitTest {
a: u16, a: u16,
b: u16, b: u16,
} }
@ -66,7 +66,7 @@ union UnionTestAnyBitPattern {
} }
#[repr(u8)] #[repr(u8)]
#[derive(Debug, Clone, Copy, NoPadding, CheckedBitPattern, PartialEq, Eq)] #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)]
enum CheckedBitPatternEnumWithValues { enum CheckedBitPatternEnumWithValues {
A = 0, A = 0,
B = 1, B = 1,
@ -76,7 +76,7 @@ enum CheckedBitPatternEnumWithValues {
} }
#[repr(i8)] #[repr(i8)]
#[derive(Clone, Copy, NoPadding, CheckedBitPattern)] #[derive(Clone, Copy, NoUninit, CheckedBitPattern)]
enum CheckedBitPatternEnumWithImplicitValues { enum CheckedBitPatternEnumWithImplicitValues {
A = -10, A = -10,
B, B,
@ -86,7 +86,7 @@ enum CheckedBitPatternEnumWithImplicitValues {
} }
#[repr(u8)] #[repr(u8)]
#[derive(Debug, Clone, Copy, NoPadding, CheckedBitPattern, PartialEq, Eq)] #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)]
enum CheckedBitPatternEnumNonContiguous { enum CheckedBitPatternEnumNonContiguous {
A = 1, A = 1,
B = 8, B = 8,
@ -95,7 +95,7 @@ enum CheckedBitPatternEnumNonContiguous {
E = 56, E = 56,
} }
#[derive(Debug, Copy, Clone, NoPadding, CheckedBitPattern, PartialEq, Eq)] #[derive(Debug, Copy, Clone, NoUninit, CheckedBitPattern, PartialEq, Eq)]
#[repr(C)] #[repr(C)]
struct CheckedBitPatternStruct { struct CheckedBitPatternStruct {
a: u8, a: u8,

View File

@ -18,7 +18,7 @@ use core::convert::TryInto;
/// As [`try_cast_box`](try_cast_box), but unwraps for you. /// As [`try_cast_box`](try_cast_box), but unwraps for you.
#[inline] #[inline]
pub fn cast_box<A: NoPadding, B: AnyBitPattern>(input: Box<A>) -> Box<B> { pub fn cast_box<A: NoUninit, B: AnyBitPattern>(input: Box<A>) -> Box<B> {
try_cast_box(input).map_err(|(e, _v)| e).unwrap() try_cast_box(input).map_err(|(e, _v)| e).unwrap()
} }
@ -32,7 +32,7 @@ pub fn cast_box<A: NoPadding, B: AnyBitPattern>(input: Box<A>) -> Box<B> {
/// alignment. /// alignment.
/// * The start and end size of the `Box` must have the exact same size. /// * The start and end size of the `Box` must have the exact same size.
#[inline] #[inline]
pub fn try_cast_box<A: NoPadding, B: AnyBitPattern>( pub fn try_cast_box<A: NoUninit, B: AnyBitPattern>(
input: Box<A>, input: Box<A>,
) -> Result<Box<B>, (PodCastError, Box<A>)> { ) -> Result<Box<B>, (PodCastError, Box<A>)> {
if align_of::<A>() != align_of::<B>() { if align_of::<A>() != align_of::<B>() {
@ -139,7 +139,7 @@ pub fn zeroed_slice_box<T: Zeroable>(length: usize) -> Box<[T]> {
/// As [`try_cast_vec`](try_cast_vec), but unwraps for you. /// As [`try_cast_vec`](try_cast_vec), but unwraps for you.
#[inline] #[inline]
pub fn cast_vec<A: NoPadding, B: AnyBitPattern>(input: Vec<A>) -> Vec<B> { pub fn cast_vec<A: NoUninit, B: AnyBitPattern>(input: Vec<A>) -> Vec<B> {
try_cast_vec(input).map_err(|(e, _v)| e).unwrap() try_cast_vec(input).map_err(|(e, _v)| e).unwrap()
} }
@ -156,7 +156,7 @@ pub fn cast_vec<A: NoPadding, B: AnyBitPattern>(input: Vec<A>) -> Vec<B> {
/// capacity and length get adjusted during transmutation, but for now it's /// capacity and length get adjusted during transmutation, but for now it's
/// absolute. /// absolute.
#[inline] #[inline]
pub fn try_cast_vec<A: NoPadding, B: AnyBitPattern>( pub fn try_cast_vec<A: NoUninit, B: AnyBitPattern>(
input: Vec<A>, input: Vec<A>,
) -> Result<Vec<B>, (PodCastError, Vec<A>)> { ) -> Result<Vec<B>, (PodCastError, Vec<A>)> {
if align_of::<A>() != align_of::<B>() { if align_of::<A>() != align_of::<B>() {
@ -199,7 +199,7 @@ pub fn try_cast_vec<A: NoPadding, B: AnyBitPattern>(
/// assert_eq!(&vec_of_words[..], &[0x0005_0006, 0x0007_0008][..]) /// assert_eq!(&vec_of_words[..], &[0x0005_0006, 0x0007_0008][..])
/// } /// }
/// ``` /// ```
pub fn pod_collect_to_vec<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(src: &[A]) -> Vec<B> { pub fn pod_collect_to_vec<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(src: &[A]) -> Vec<B> {
let src_size = size_of_val(src); let src_size = size_of_val(src);
// Note(Lokathor): dst_count is rounded up so that the dest will always be at // Note(Lokathor): dst_count is rounded up so that the dest will always be at
// least as many bytes as the src. // least as many bytes as the src.

View File

@ -3,9 +3,9 @@ use crate::{Pod, Zeroable};
/// Marker trait for "plain old data" types that are valid for any bit pattern. /// Marker trait for "plain old data" types that are valid for any bit pattern.
/// ///
/// The requirements for this is very similar to [`Pod`], /// The requirements for this is very similar to [`Pod`],
/// except that it doesn't require that the type contains no padding bytes. /// except that it doesn't require that the type contains no uninit (or padding) bytes.
/// This limits what you can do with a type of this kind, but also broadens the /// This limits what you can do with a type of this kind, but also broadens the
/// included types to `repr(C)` structs that contain padding. Notably, you can only cast /// included types to `repr(C)` `struct`s that contain padding as well as `union`s. Notably, you can only cast
/// *immutable* references and *owned* values into [`AnyBitPattern`] types, not /// *immutable* references and *owned* values into [`AnyBitPattern`] types, not
/// *mutable* references. /// *mutable* references.
/// ///
@ -29,7 +29,7 @@ use crate::{Pod, Zeroable};
/// ///
/// # Safety /// # Safety
/// ///
/// Similar to [`Pod`] except we disregard the rule about it must not contain padding. /// Similar to [`Pod`] except we disregard the rule about it must not contain uninit bytes.
/// Still, this is a quite strong guarantee about a type, so *be careful* when /// Still, this is a quite strong guarantee about a type, so *be careful* when
/// implementing it manually. /// implementing it manually.
/// ///

View File

@ -1,7 +1,7 @@
//! Checked versions of the casting functions exposed in crate root //! Checked versions of the casting functions exposed in crate root
//! that support [`CheckedBitPattern`] types. //! that support [`CheckedBitPattern`] types.
use crate::{internal::{self, something_went_wrong}, NoPadding, AnyBitPattern}; use crate::{internal::{self, something_went_wrong}, NoUninit, AnyBitPattern};
/// A marker trait that allows types that have some invalid bit patterns to be used /// A marker trait that allows types that have some invalid bit patterns to be used
/// in places that otherwise require [`AnyBitPattern`] or [`Pod`] types by performing /// in places that otherwise require [`AnyBitPattern`] or [`Pod`] types by performing
@ -33,7 +33,7 @@ use crate::{internal::{self, something_went_wrong}, NoPadding, AnyBitPattern};
/// If manually implementing the trait, we can do something like so: /// If manually implementing the trait, we can do something like so:
/// ///
/// ```rust /// ```rust
/// use bytemuck::{CheckedBitPattern, NoPadding}; /// use bytemuck::{CheckedBitPattern, NoUninit};
/// ///
/// #[repr(u32)] /// #[repr(u32)]
/// #[derive(Copy, Clone)] /// #[derive(Copy, Clone)]
@ -54,16 +54,16 @@ use crate::{internal::{self, something_went_wrong}, NoPadding, AnyBitPattern};
/// } /// }
/// } /// }
/// ///
/// // It is often useful to also implement `NoPadding` on our `CheckedBitPattern` types. /// // It is often useful to also implement `NoUninit` on our `CheckedBitPattern` types.
/// // This will allow us to do casting of mutable references (and mutable slices). /// // This will allow us to do casting of mutable references (and mutable slices).
/// // It is not always possible to do so, but in this case we have no padding so it is. /// // It is not always possible to do so, but in this case we have no padding so it is.
/// unsafe impl NoPadding for MyEnum {} /// unsafe impl NoUninit for MyEnum {}
/// ``` /// ```
/// ///
/// We can now use relevant casting functions. For example, /// We can now use relevant casting functions. For example,
/// ///
/// ```rust /// ```rust
/// # use bytemuck::{CheckedBitPattern, NoPadding}; /// # use bytemuck::{CheckedBitPattern, NoUninit};
/// # #[repr(u32)] /// # #[repr(u32)]
/// # #[derive(Copy, Clone, PartialEq, Eq, Debug)] /// # #[derive(Copy, Clone, PartialEq, Eq, Debug)]
/// # enum MyEnum { /// # enum MyEnum {
@ -71,7 +71,7 @@ use crate::{internal::{self, something_went_wrong}, NoPadding, AnyBitPattern};
/// # Variant1 = 1, /// # Variant1 = 1,
/// # Variant2 = 2, /// # Variant2 = 2,
/// # } /// # }
/// # unsafe impl NoPadding for MyEnum {} /// # unsafe impl NoUninit for MyEnum {}
/// # unsafe impl CheckedBitPattern for MyEnum { /// # unsafe impl CheckedBitPattern for MyEnum {
/// # type Bits = u32; /// # type Bits = u32;
/// # fn is_valid_bit_pattern(bits: &u32) -> bool { /// # fn is_valid_bit_pattern(bits: &u32) -> bool {
@ -93,8 +93,8 @@ use crate::{internal::{self, something_went_wrong}, NoPadding, AnyBitPattern};
/// let result = checked::try_from_bytes::<MyEnum>(bytes); /// let result = checked::try_from_bytes::<MyEnum>(bytes);
/// assert!(result.is_err()); /// assert!(result.is_err());
/// ///
/// // Since we implemented NoPadding, we can also cast mutably from an original type /// // Since we implemented NoUninit, we can also cast mutably from an original type
/// // that is `NoPadding + AnyBitPattern`: /// // that is `NoUninit + AnyBitPattern`:
/// let mut my_u32 = 2u32; /// let mut my_u32 = 2u32;
/// { /// {
/// let as_enum_mut = checked::cast_mut::<_, MyEnum>(&mut my_u32); /// let as_enum_mut = checked::cast_mut::<_, MyEnum>(&mut my_u32);
@ -214,7 +214,7 @@ pub fn try_from_bytes<T: CheckedBitPattern>(
/// * If the slice's length isnt exactly the size of the new type /// * If the slice's length isnt exactly the size of the new type
/// * If the slice contains an invalid bit pattern for `T` /// * If the slice contains an invalid bit pattern for `T`
#[inline] #[inline]
pub fn try_from_bytes_mut<T: CheckedBitPattern + NoPadding>( pub fn try_from_bytes_mut<T: CheckedBitPattern + NoUninit>(
s: &mut [u8], s: &mut [u8],
) -> Result<&mut T, CheckedCastError> { ) -> Result<&mut T, CheckedCastError> {
let pod = unsafe { internal::try_from_bytes_mut(s) }?; let pod = unsafe { internal::try_from_bytes_mut(s) }?;
@ -254,7 +254,7 @@ pub fn try_pod_read_unaligned<T: CheckedBitPattern>(bytes: &[u8]) -> Result<T, C
/// * If the types don't have the same size this fails. /// * If the types don't have the same size this fails.
/// * If `a` contains an invalid bit pattern for `B` this fails. /// * If `a` contains an invalid bit pattern for `B` this fails.
#[inline] #[inline]
pub fn try_cast<A: NoPadding, B: CheckedBitPattern>( pub fn try_cast<A: NoUninit, B: CheckedBitPattern>(
a: A, a: A,
) -> Result<B, CheckedCastError> { ) -> Result<B, CheckedCastError> {
let pod = unsafe { internal::try_cast(a) }?; let pod = unsafe { internal::try_cast(a) }?;
@ -274,7 +274,7 @@ pub fn try_cast<A: NoPadding, B: CheckedBitPattern>(
/// * If the source type and target type aren't the same size. /// * If the source type and target type aren't the same size.
/// * If `a` contains an invalid bit pattern for `B` this fails. /// * If `a` contains an invalid bit pattern for `B` this fails.
#[inline] #[inline]
pub fn try_cast_ref<A: NoPadding, B: CheckedBitPattern>( pub fn try_cast_ref<A: NoUninit, B: CheckedBitPattern>(
a: &A, a: &A,
) -> Result<&B, CheckedCastError> { ) -> Result<&B, CheckedCastError> {
let pod = unsafe { internal::try_cast_ref(a) }?; let pod = unsafe { internal::try_cast_ref(a) }?;
@ -290,7 +290,7 @@ pub fn try_cast_ref<A: NoPadding, B: CheckedBitPattern>(
/// ///
/// As [`checked_cast_ref`], but `mut`. /// As [`checked_cast_ref`], but `mut`.
#[inline] #[inline]
pub fn try_cast_mut<A: NoPadding + AnyBitPattern, B: CheckedBitPattern + NoPadding>( pub fn try_cast_mut<A: NoUninit + AnyBitPattern, B: CheckedBitPattern + NoUninit>(
a: &mut A, a: &mut A,
) -> Result<&mut B, CheckedCastError> { ) -> Result<&mut B, CheckedCastError> {
let pod = unsafe { internal::try_cast_mut(a) }?; let pod = unsafe { internal::try_cast_mut(a) }?;
@ -319,7 +319,7 @@ pub fn try_cast_mut<A: NoPadding + AnyBitPattern, B: CheckedBitPattern + NoPaddi
/// and a non-ZST. /// and a non-ZST.
/// * If any element of the converted slice would contain an invalid bit pattern for `B` this fails. /// * If any element of the converted slice would contain an invalid bit pattern for `B` this fails.
#[inline] #[inline]
pub fn try_cast_slice<A: NoPadding, B: CheckedBitPattern>( pub fn try_cast_slice<A: NoUninit, B: CheckedBitPattern>(
a: &[A], a: &[A],
) -> Result<&[B], CheckedCastError> { ) -> Result<&[B], CheckedCastError> {
let pod = unsafe { internal::try_cast_slice(a) }?; let pod = unsafe { internal::try_cast_slice(a) }?;
@ -338,7 +338,7 @@ pub fn try_cast_slice<A: NoPadding, B: CheckedBitPattern>(
/// ///
/// As [`checked_cast_slice`], but `&mut`. /// As [`checked_cast_slice`], but `&mut`.
#[inline] #[inline]
pub fn try_cast_slice_mut<A: NoPadding + AnyBitPattern, B: CheckedBitPattern + NoPadding>( pub fn try_cast_slice_mut<A: NoUninit + AnyBitPattern, B: CheckedBitPattern + NoUninit>(
a: &mut [A], a: &mut [A],
) -> Result<&mut [B], CheckedCastError> { ) -> Result<&mut [B], CheckedCastError> {
let pod = unsafe { internal::try_cast_slice_mut(a) }?; let pod = unsafe { internal::try_cast_slice_mut(a) }?;
@ -371,7 +371,7 @@ pub fn from_bytes<T: CheckedBitPattern>(s: &[u8]) -> &T {
/// ///
/// This is [`try_from_bytes_mut`] but will panic on error. /// This is [`try_from_bytes_mut`] but will panic on error.
#[inline] #[inline]
pub fn from_bytes_mut<T: NoPadding + CheckedBitPattern>(s: &mut [u8]) -> &mut T { pub fn from_bytes_mut<T: NoUninit + CheckedBitPattern>(s: &mut [u8]) -> &mut T {
match try_from_bytes_mut(s) { match try_from_bytes_mut(s) {
Ok(t) => t, Ok(t) => t,
Err(e) => something_went_wrong("from_bytes_mut", e), Err(e) => something_went_wrong("from_bytes_mut", e),
@ -396,7 +396,7 @@ pub fn pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> T {
/// ///
/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch. /// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
#[inline] #[inline]
pub fn cast<A: NoPadding, B: CheckedBitPattern>(a: A) -> B { pub fn cast<A: NoUninit, B: CheckedBitPattern>(a: A) -> B {
match try_cast(a) { match try_cast(a) {
Ok(t) => t, Ok(t) => t,
Err(e) => something_went_wrong("cast", e), Err(e) => something_went_wrong("cast", e),
@ -409,7 +409,7 @@ pub fn cast<A: NoPadding, B: CheckedBitPattern>(a: A) -> B {
/// ///
/// This is [`try_cast_mut`] but will panic on error. /// This is [`try_cast_mut`] but will panic on error.
#[inline] #[inline]
pub fn cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + CheckedBitPattern>(a: &mut A) -> &mut B { pub fn cast_mut<A: NoUninit + AnyBitPattern, B: NoUninit + CheckedBitPattern>(a: &mut A) -> &mut B {
match try_cast_mut(a) { match try_cast_mut(a) {
Ok(t) => t, Ok(t) => t,
Err(e) => something_went_wrong("cast_mut", e), Err(e) => something_went_wrong("cast_mut", e),
@ -422,7 +422,7 @@ pub fn cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + CheckedBitPattern>(
/// ///
/// This is [`try_cast_ref`] but will panic on error. /// This is [`try_cast_ref`] but will panic on error.
#[inline] #[inline]
pub fn cast_ref<A: NoPadding, B: CheckedBitPattern>(a: &A) -> &B { pub fn cast_ref<A: NoUninit, B: CheckedBitPattern>(a: &A) -> &B {
match try_cast_ref(a) { match try_cast_ref(a) {
Ok(t) => t, Ok(t) => t,
Err(e) => something_went_wrong("cast_ref", e), Err(e) => something_went_wrong("cast_ref", e),
@ -435,7 +435,7 @@ pub fn cast_ref<A: NoPadding, B: CheckedBitPattern>(a: &A) -> &B {
/// ///
/// This is [`try_cast_slice`] but will panic on error. /// This is [`try_cast_slice`] but will panic on error.
#[inline] #[inline]
pub fn cast_slice<A: NoPadding, B: CheckedBitPattern>(a: &[A]) -> &[B] { pub fn cast_slice<A: NoUninit, B: CheckedBitPattern>(a: &[A]) -> &[B] {
match try_cast_slice(a) { match try_cast_slice(a) {
Ok(t) => t, Ok(t) => t,
Err(e) => something_went_wrong("cast_slice", e), Err(e) => something_went_wrong("cast_slice", e),
@ -448,7 +448,7 @@ pub fn cast_slice<A: NoPadding, B: CheckedBitPattern>(a: &[A]) -> &[B] {
/// ///
/// This is [`try_cast_slice_mut`] but will panic on error. /// This is [`try_cast_slice_mut`] but will panic on error.
#[inline] #[inline]
pub fn cast_slice_mut<A: NoPadding + AnyBitPattern, B: NoPadding + CheckedBitPattern>(a: &mut [A]) -> &mut [B] { pub fn cast_slice_mut<A: NoUninit + AnyBitPattern, B: NoUninit + CheckedBitPattern>(a: &mut [A]) -> &mut [B] {
match try_cast_slice_mut(a) { match try_cast_slice_mut(a) {
Ok(t) => t, Ok(t) => t,
Err(e) => something_went_wrong("cast_slice_mut", e), Err(e) => something_went_wrong("cast_slice_mut", e),

View File

@ -94,8 +94,8 @@ pub use zeroable::*;
mod pod; mod pod;
pub use pod::*; pub use pod::*;
mod nopadding; mod no_uninit;
pub use nopadding::*; pub use no_uninit::*;
mod contiguous; mod contiguous;
pub use contiguous::*; pub use contiguous::*;
@ -108,7 +108,7 @@ pub use transparent::*;
#[cfg(feature = "derive")] #[cfg(feature = "derive")]
pub use bytemuck_derive::{ pub use bytemuck_derive::{
AnyBitPattern, Contiguous, CheckedBitPattern, NoPadding, Pod, TransparentWrapper, Zeroable, AnyBitPattern, Contiguous, CheckedBitPattern, NoUninit, Pod, TransparentWrapper, Zeroable,
}; };
/// The things that can go wrong when casting between [`Pod`] data forms. /// The things that can go wrong when casting between [`Pod`] data forms.
@ -147,7 +147,7 @@ impl std::error::Error for PodCastError {}
/// Any ZST becomes an empty slice, and in that case the pointer value of that /// Any ZST becomes an empty slice, and in that case the pointer value of that
/// empty slice might not match the pointer value of the input reference. /// empty slice might not match the pointer value of the input reference.
#[inline] #[inline]
pub fn bytes_of<T: NoPadding>(t: &T) -> &[u8] { pub fn bytes_of<T: NoUninit>(t: &T) -> &[u8] {
unsafe { internal::bytes_of(t) } unsafe { internal::bytes_of(t) }
} }
@ -156,7 +156,7 @@ pub fn bytes_of<T: NoPadding>(t: &T) -> &[u8] {
/// Any ZST becomes an empty slice, and in that case the pointer value of that /// Any ZST becomes an empty slice, and in that case the pointer value of that
/// empty slice might not match the pointer value of the input reference. /// empty slice might not match the pointer value of the input reference.
#[inline] #[inline]
pub fn bytes_of_mut<T: NoPadding + AnyBitPattern>(t: &mut T) -> &mut [u8] { pub fn bytes_of_mut<T: NoUninit + AnyBitPattern>(t: &mut T) -> &mut [u8] {
unsafe { internal::bytes_of_mut(t) } unsafe { internal::bytes_of_mut(t) }
} }
@ -176,7 +176,7 @@ pub fn from_bytes<T: AnyBitPattern>(s: &[u8]) -> &T {
/// ///
/// This is [`try_from_bytes_mut`] but will panic on error. /// This is [`try_from_bytes_mut`] but will panic on error.
#[inline] #[inline]
pub fn from_bytes_mut<T: NoPadding + AnyBitPattern>(s: &mut [u8]) -> &mut T { pub fn from_bytes_mut<T: NoUninit + AnyBitPattern>(s: &mut [u8]) -> &mut T {
unsafe { internal::from_bytes_mut(s) } unsafe { internal::from_bytes_mut(s) }
} }
@ -216,7 +216,7 @@ pub fn try_from_bytes<T: AnyBitPattern>(s: &[u8]) -> Result<&T, PodCastError> {
/// * If the slice isn't aligned for the new type /// * If the slice isn't aligned for the new type
/// * If the slice's length isnt exactly the size of the new type /// * If the slice's length isnt exactly the size of the new type
#[inline] #[inline]
pub fn try_from_bytes_mut<T: NoPadding + AnyBitPattern>( pub fn try_from_bytes_mut<T: NoUninit + AnyBitPattern>(
s: &mut [u8], s: &mut [u8],
) -> Result<&mut T, PodCastError> { ) -> Result<&mut T, PodCastError> {
unsafe { internal::try_from_bytes_mut(s) } unsafe { internal::try_from_bytes_mut(s) }
@ -228,7 +228,7 @@ pub fn try_from_bytes_mut<T: NoPadding + AnyBitPattern>(
/// ///
/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch. /// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
#[inline] #[inline]
pub fn cast<A: NoPadding, B: AnyBitPattern>(a: A) -> B { pub fn cast<A: NoUninit, B: AnyBitPattern>(a: A) -> B {
unsafe { internal::cast(a) } unsafe { internal::cast(a) }
} }
@ -238,7 +238,7 @@ pub fn cast<A: NoPadding, B: AnyBitPattern>(a: A) -> B {
/// ///
/// This is [`try_cast_mut`] but will panic on error. /// This is [`try_cast_mut`] but will panic on error.
#[inline] #[inline]
pub fn cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(a: &mut A) -> &mut B { pub fn cast_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(a: &mut A) -> &mut B {
unsafe { internal::cast_mut(a) } unsafe { internal::cast_mut(a) }
} }
@ -248,7 +248,7 @@ pub fn cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(a: &
/// ///
/// This is [`try_cast_ref`] but will panic on error. /// This is [`try_cast_ref`] but will panic on error.
#[inline] #[inline]
pub fn cast_ref<A: NoPadding, B: AnyBitPattern>(a: &A) -> &B { pub fn cast_ref<A: NoUninit, B: AnyBitPattern>(a: &A) -> &B {
unsafe { internal::cast_ref(a) } unsafe { internal::cast_ref(a) }
} }
@ -258,7 +258,7 @@ pub fn cast_ref<A: NoPadding, B: AnyBitPattern>(a: &A) -> &B {
/// ///
/// This is [`try_cast_slice`] but will panic on error. /// This is [`try_cast_slice`] but will panic on error.
#[inline] #[inline]
pub fn cast_slice<A: NoPadding, B: AnyBitPattern>(a: &[A]) -> &[B] { pub fn cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B] {
unsafe { internal::cast_slice(a) } unsafe { internal::cast_slice(a) }
} }
@ -268,19 +268,19 @@ pub fn cast_slice<A: NoPadding, B: AnyBitPattern>(a: &[A]) -> &[B] {
/// ///
/// This is [`try_cast_slice_mut`] but will panic on error. /// This is [`try_cast_slice_mut`] but will panic on error.
#[inline] #[inline]
pub fn cast_slice_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(a: &mut [A]) -> &mut [B] { pub fn cast_slice_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(a: &mut [A]) -> &mut [B] {
unsafe { internal::cast_slice_mut(a) } unsafe { internal::cast_slice_mut(a) }
} }
/// As `align_to`, but safe because of the [`Pod`] bound. /// As `align_to`, but safe because of the [`Pod`] bound.
#[inline] #[inline]
pub fn pod_align_to<T: NoPadding, U: AnyBitPattern>(vals: &[T]) -> (&[T], &[U], &[T]) { pub fn pod_align_to<T: NoUninit, U: AnyBitPattern>(vals: &[T]) -> (&[T], &[U], &[T]) {
unsafe { vals.align_to::<U>() } unsafe { vals.align_to::<U>() }
} }
/// As `align_to_mut`, but safe because of the [`Pod`] bound. /// As `align_to_mut`, but safe because of the [`Pod`] bound.
#[inline] #[inline]
pub fn pod_align_to_mut<T: NoPadding + AnyBitPattern, U: NoPadding + AnyBitPattern>( pub fn pod_align_to_mut<T: NoUninit + AnyBitPattern, U: NoUninit + AnyBitPattern>(
vals: &mut [T], vals: &mut [T],
) -> (&mut [T], &mut [U], &mut [T]) { ) -> (&mut [T], &mut [U], &mut [T]) {
unsafe { vals.align_to_mut::<U>() } unsafe { vals.align_to_mut::<U>() }
@ -297,7 +297,7 @@ pub fn pod_align_to_mut<T: NoPadding + AnyBitPattern, U: NoPadding + AnyBitPatte
/// ///
/// * If the types don't have the same size this fails. /// * If the types don't have the same size this fails.
#[inline] #[inline]
pub fn try_cast<A: NoPadding, B: AnyBitPattern>(a: A) -> Result<B, PodCastError> { pub fn try_cast<A: NoUninit, B: AnyBitPattern>(a: A) -> Result<B, PodCastError> {
unsafe { internal::try_cast(a) } unsafe { internal::try_cast(a) }
} }
@ -308,7 +308,7 @@ pub fn try_cast<A: NoPadding, B: AnyBitPattern>(a: A) -> Result<B, PodCastError>
/// * If the reference isn't aligned in the new type /// * If the reference isn't aligned in the new type
/// * If the source type and target type aren't the same size. /// * If the source type and target type aren't the same size.
#[inline] #[inline]
pub fn try_cast_ref<A: NoPadding, B: AnyBitPattern>(a: &A) -> Result<&B, PodCastError> { pub fn try_cast_ref<A: NoUninit, B: AnyBitPattern>(a: &A) -> Result<&B, PodCastError> {
unsafe { internal::try_cast_ref(a) } unsafe { internal::try_cast_ref(a) }
} }
@ -316,7 +316,7 @@ pub fn try_cast_ref<A: NoPadding, B: AnyBitPattern>(a: &A) -> Result<&B, PodCast
/// ///
/// As [`try_cast_ref`], but `mut`. /// As [`try_cast_ref`], but `mut`.
#[inline] #[inline]
pub fn try_cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(a: &mut A) -> Result<&mut B, PodCastError> { pub fn try_cast_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(a: &mut A) -> Result<&mut B, PodCastError> {
unsafe { internal::try_cast_mut(a) } unsafe { internal::try_cast_mut(a) }
} }
@ -336,7 +336,7 @@ pub fn try_cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(
/// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts) /// * Similarly, you can't convert between a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
/// and a non-ZST. /// and a non-ZST.
#[inline] #[inline]
pub fn try_cast_slice<A: NoPadding, B: AnyBitPattern>(a: &[A]) -> Result<&[B], PodCastError> { pub fn try_cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> Result<&[B], PodCastError> {
unsafe { internal::try_cast_slice(a) } unsafe { internal::try_cast_slice(a) }
} }
@ -345,7 +345,7 @@ pub fn try_cast_slice<A: NoPadding, B: AnyBitPattern>(a: &[A]) -> Result<&[B], P
/// ///
/// As [`try_cast_slice`], but `&mut`. /// As [`try_cast_slice`], but `&mut`.
#[inline] #[inline]
pub fn try_cast_slice_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>( pub fn try_cast_slice_mut<A: NoUninit + AnyBitPattern, B: NoUninit + AnyBitPattern>(
a: &mut [A], a: &mut [A],
) -> Result<&mut [B], PodCastError> { ) -> Result<&mut [B], PodCastError> {
unsafe { internal::try_cast_slice_mut(a) } unsafe { internal::try_cast_slice_mut(a) }

View File

@ -1,23 +1,23 @@
use crate::Pod; use crate::Pod;
/// Marker trait for "plain old data" types with no padding. /// Marker trait for "plain old data" types with no uninit (or padding) bytes.
/// ///
/// The requirements for this is very similar to [`Pod`], /// The requirements for this is very similar to [`Pod`],
/// except that it doesn't require that all bit patterns of the type are valid, i.e. /// except that it doesn't require that all bit patterns of the type are valid, i.e.
/// it does not require the type to be [`Zeroable`][crate::Zeroable]. /// it does not require the type to be [`Zeroable`][crate::Zeroable].
/// This limits what you can do with a type of this kind, but also broadens the /// This limits what you can do with a type of this kind, but also broadens the
/// included types to things like C-style enums. Notably, you can only cast from /// included types to things like C-style enums. Notably, you can only cast from
/// *immutable* references to a [`NoPadding`] type into *immutable* references of any other /// *immutable* references to a [`NoUninit`] type into *immutable* references of any other
/// type, no casting of mutable references or mutable references to slices etc. /// type, no casting of mutable references or mutable references to slices etc.
/// ///
/// [`Pod`] is a subset of [`NoPadding`], meaning that any `T: Pod` is also /// [`Pod`] is a subset of [`NoUninit`], meaning that any `T: Pod` is also
/// [`NoPadding`] but any `T: NoPadding` is not necessarily [`Pod`]. If possible, /// [`NoUninit`] but any `T: NoUninit` is not necessarily [`Pod`]. If possible,
/// prefer implementing [`Pod`] directly. To get more [`Pod`]-like functionality for /// prefer implementing [`Pod`] directly. To get more [`Pod`]-like functionality for
/// a type that is only [`NoPadding`], consider also implementing [`CheckedBitPattern`][crate::CheckedBitPattern]. /// a type that is only [`NoUninit`], consider also implementing [`CheckedBitPattern`][crate::CheckedBitPattern].
/// ///
/// # Derive /// # Derive
/// ///
/// A `#[derive(NoPadding)]` macro is provided under the `derive` feature flag which will /// A `#[derive(NoUninit)]` macro is provided under the `derive` feature flag which will
/// automatically validate the requirements of this trait and implement the /// automatically validate the requirements of this trait and implement the
/// trait for you for both enums and structs. This is the recommended method for /// trait for you for both enums and structs. This is the recommended method for
/// implementing the trait, however it's also possible to do manually. If you /// implementing the trait, however it's also possible to do manually. If you
@ -32,21 +32,21 @@ use crate::Pod;
/// ///
/// * The type must be inhabited (eg: no /// * The type must be inhabited (eg: no
/// [Infallible](core::convert::Infallible)). /// [Infallible](core::convert::Infallible)).
/// * The type must not contain any padding bytes, either in the middle or on /// * The type must not contain any uninit (or padding) bytes, either in the middle or on
/// the end (eg: no `#[repr(C)] struct Foo(u8, u16)`, which has padding in the /// the end (eg: no `#[repr(C)] struct Foo(u8, u16)`, which has padding in the
/// middle, and also no `#[repr(C)] struct Foo(u16, u8)`, which has padding on /// middle, and also no `#[repr(C)] struct Foo(u16, u8)`, which has padding on
/// the end). /// the end).
/// * Structs need to have all fields also be `NoPadding`. /// * Structs need to have all fields also be `NoUninit`.
/// * Structs need to be `repr(C)` or `repr(transparent)`. In the case of /// * Structs need to be `repr(C)` or `repr(transparent)`. In the case of
/// `repr(C)`, the `packed` and `align` repr modifiers can be used as long as /// `repr(C)`, the `packed` and `align` repr modifiers can be used as long as
/// all other rules end up being followed. /// all other rules end up being followed.
/// * Enums need to have an explicit `#[repr(Int)]` /// * Enums need to have an explicit `#[repr(Int)]`
/// * Enums must have only fieldless variants /// * Enums must have only fieldless variants
/// * There's probably more, don't mess it up (I mean it). /// * There's probably more, don't mess it up (I mean it).
pub unsafe trait NoPadding: Sized + Copy + 'static {} pub unsafe trait NoUninit: Sized + Copy + 'static {}
unsafe impl<T: Pod> NoPadding for T {} unsafe impl<T: Pod> NoUninit for T {}
unsafe impl NoPadding for char {} unsafe impl NoUninit for char {}
unsafe impl NoPadding for bool {} unsafe impl NoUninit for bool {}

View File

@ -18,7 +18,7 @@ use super::*;
/// [Infallible](core::convert::Infallible)). /// [Infallible](core::convert::Infallible)).
/// * The type must allow any bit pattern (eg: no `bool` or `char`, which have /// * The type must allow any bit pattern (eg: no `bool` or `char`, which have
/// illegal bit patterns). /// illegal bit patterns).
/// * The type must not contain any padding bytes, either in the middle or on /// * The type must not contain any uninit (or padding) bytes, either in the middle or on
/// the end (eg: no `#[repr(C)] struct Foo(u8, u16)`, which has padding in the /// the end (eg: no `#[repr(C)] struct Foo(u8, u16)`, which has padding in the
/// middle, and also no `#[repr(C)] struct Foo(u16, u8)`, which has padding on /// middle, and also no `#[repr(C)] struct Foo(u16, u8)`, which has padding on
/// the end). /// the end).