mirror of
https://github.com/Lokathor/bytemuck.git
synced 2024-11-24 07:42:24 +00:00
Add NoPadding
, AnyBitPattern
, and CheckedBitPattern
traits (#91)
* add MaybePod and NoPadding traits * MaybePod and NoPadding derive macros * fix doctest * fmt * fix bad doc link * move new casting functions into separate modules * fmt * fix doctest and derive test * remove relaxed module, add anybitpattern * rename MaybePod to CheckedCastFromPod * rename checked casting functions * rework CheckedCastFromPod into CheckedBitPattern * add anybitpattern derive, fix up other derives * fix doctest * fix derive trait of bits type * export AnyBitPattern derive * export anybitpattern from traits * actually export derive macro for AnyBitPattern * make bits struct pub because of type leaking rules * allow clippy lint in derive * add copy bound to CheckedBitPattern * - replace Pod bounds with NoPadding+AnyBitPattern - add try and panic versions of checked cast functions - slightly update docs * fix derive tests * - adapt the allocation module cast functions as well - as part of that, make AnyBitPattern a subtrait of Zeroable - AnyBitPattern derive also derives Zeroable * @JakobDegen and @zakarumych nits * superset -> subset on CheckedBitPattern and NoPadding docs * derive Debug on generated `Bits` structs, which can be useful for debugging failures * don't derive debug on spirv target arch * make it work on 1.34 * merge conflicts * fix erroneous behavior in doctest
This commit is contained in:
parent
4569a30c9f
commit
b472189ff8
@ -29,8 +29,8 @@ nightly_portable_simd = []
|
||||
|
||||
[dependencies]
|
||||
# use the upper line for testing against bytemuck_derive changes, if any
|
||||
#bytemuck_derive = { version = "1.0.1-alpha.0", path = "derive", optional = true }
|
||||
bytemuck_derive = { version = "1", optional = true }
|
||||
bytemuck_derive = { path = "./derive", optional = true }
|
||||
# bytemuck_derive = { version = "1", optional = true }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# Note(Lokathor): Don't use all-feautures or it would use `unsound_ptr_pod_impl` too.
|
||||
|
@ -20,4 +20,4 @@ quote = "1"
|
||||
proc-macro2 = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
bytemuck = "1.2"
|
||||
bytemuck = { path = "../", features = ["derive"] }
|
||||
|
@ -8,7 +8,9 @@ use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{parse_macro_input, DeriveInput};
|
||||
|
||||
use crate::traits::{Contiguous, Derivable, Pod, TransparentWrapper, Zeroable};
|
||||
use crate::traits::{
|
||||
AnyBitPattern, Contiguous, Derivable, CheckedBitPattern, NoPadding, Pod, TransparentWrapper, Zeroable,
|
||||
};
|
||||
|
||||
/// Derive the `Pod` trait for a struct
|
||||
///
|
||||
@ -42,6 +44,24 @@ pub fn derive_pod(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
proc_macro::TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
/// Derive the `AnyBitPattern` trait for a struct
|
||||
///
|
||||
/// The macro ensures that the struct follows all the the safety requirements
|
||||
/// for the `AnyBitPattern` trait.
|
||||
///
|
||||
/// The following constraints need to be satisfied for the macro to succeed
|
||||
///
|
||||
/// - All fields ind the struct must to implement `AnyBitPattern`
|
||||
#[proc_macro_derive(AnyBitPattern)]
|
||||
pub fn derive_anybitpattern(
|
||||
input: proc_macro::TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
let expanded =
|
||||
derive_marker_trait::<AnyBitPattern>(parse_macro_input!(input as DeriveInput));
|
||||
|
||||
proc_macro::TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
/// Derive the `Zeroable` trait for a struct
|
||||
///
|
||||
/// The macro ensures that the struct follows all the the safety requirements
|
||||
@ -73,6 +93,61 @@ pub fn derive_zeroable(
|
||||
proc_macro::TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
/// Derive the `NoPadding` trait for a struct or enum
|
||||
///
|
||||
/// The macro ensures that the type follows all the the safety requirements
|
||||
/// for the `NoPadding` trait.
|
||||
///
|
||||
/// The following constraints need to be satisfied for the macro to succeed
|
||||
/// (the rest of the constraints are guaranteed by the `NoPadding` subtrait bounds,
|
||||
/// i.e. the type must be `Sized + Copy + 'static`):
|
||||
///
|
||||
/// If applied to a struct:
|
||||
/// - All fields in the struct must implement `NoPadding`
|
||||
/// - The struct must be `#[repr(C)]` or `#[repr(transparent)]`
|
||||
/// - The struct must not contain any padding bytes
|
||||
/// - The struct must contain no generic parameters
|
||||
///
|
||||
/// If applied to an enum:
|
||||
/// - The enum must be explicit `#[repr(Int)]`
|
||||
/// - All variants must be fieldless
|
||||
/// - The enum must contain no generic parameters
|
||||
#[proc_macro_derive(NoPadding)]
|
||||
pub fn derive_no_padding(
|
||||
input: proc_macro::TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
let expanded =
|
||||
derive_marker_trait::<NoPadding>(parse_macro_input!(input as DeriveInput));
|
||||
|
||||
proc_macro::TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
/// Derive the `CheckedBitPattern` trait for a struct or enum.
|
||||
///
|
||||
/// The macro ensures that the type follows all the the safety requirements
|
||||
/// for the `CheckedBitPattern` trait and derives the required `Bits` type
|
||||
/// definition and `is_valid_bit_pattern` method for the type automatically.
|
||||
///
|
||||
/// The following constraints need to be satisfied for the macro to succeed
|
||||
/// (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`
|
||||
/// is a subtrait of):
|
||||
///
|
||||
/// If applied to a struct:
|
||||
/// - All fields must implement `CheckedBitPattern`
|
||||
///
|
||||
/// If applied to an enum:
|
||||
/// - All requirements already checked by `NoPadding`, just impls the trait
|
||||
#[proc_macro_derive(CheckedBitPattern)]
|
||||
pub fn derive_maybe_pod(
|
||||
input: proc_macro::TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
let expanded =
|
||||
derive_marker_trait::<CheckedBitPattern>(parse_macro_input!(input as DeriveInput));
|
||||
|
||||
proc_macro::TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
/// Derive the `TransparentWrapper` trait for a struct
|
||||
///
|
||||
/// The macro ensures that the struct follows all the the safety requirements
|
||||
@ -164,16 +239,26 @@ fn derive_marker_trait_inner<Trait: Derivable>(
|
||||
input.generics.split_for_impl();
|
||||
|
||||
let trait_ = Trait::ident();
|
||||
Trait::check_attributes(&input.attrs)?;
|
||||
let asserts = Trait::struct_asserts(&input)?;
|
||||
Trait::check_attributes(&input.data, &input.attrs)?;
|
||||
let asserts = Trait::asserts(&input)?;
|
||||
let trait_params = Trait::generic_params(&input)?;
|
||||
let trait_impl = Trait::trait_impl(&input)?;
|
||||
let (trait_impl_extras, trait_impl) = Trait::trait_impl(&input)?;
|
||||
|
||||
let implies_trait = if let Some(implies_trait) = Trait::implies_trait() {
|
||||
quote!(unsafe impl #implies_trait for #name {})
|
||||
} else {
|
||||
quote!()
|
||||
};
|
||||
|
||||
Ok(quote! {
|
||||
#asserts
|
||||
|
||||
#trait_impl_extras
|
||||
|
||||
unsafe impl #impl_generics #trait_ #trait_params for #name #ty_generics #where_clause {
|
||||
#trait_impl
|
||||
}
|
||||
|
||||
#implies_trait
|
||||
})
|
||||
}
|
||||
|
@ -8,17 +8,24 @@ use syn::{
|
||||
|
||||
pub trait Derivable {
|
||||
fn ident() -> TokenStream;
|
||||
fn implies_trait() -> Option<TokenStream> {
|
||||
None
|
||||
}
|
||||
fn generic_params(_input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
Ok(quote!())
|
||||
}
|
||||
fn struct_asserts(_input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
fn asserts(_input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
Ok(quote!())
|
||||
}
|
||||
fn check_attributes(_attributes: &[Attribute]) -> Result<(), &'static str> {
|
||||
fn check_attributes(
|
||||
_ty: &Data, _attributes: &[Attribute],
|
||||
) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
fn trait_impl(_input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
Ok(quote!())
|
||||
fn trait_impl(
|
||||
_input: &DeriveInput,
|
||||
) -> Result<(TokenStream, TokenStream), &'static str> {
|
||||
Ok((quote!(), quote!()))
|
||||
}
|
||||
}
|
||||
|
||||
@ -29,7 +36,7 @@ impl Derivable for Pod {
|
||||
quote!(::bytemuck::Pod)
|
||||
}
|
||||
|
||||
fn struct_asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
if !input.generics.params.is_empty() {
|
||||
return Err("Pod requires cannot be derived for structs containing generic parameters because the padding requirements can't be verified for generic structs");
|
||||
}
|
||||
@ -44,7 +51,9 @@ impl Derivable for Pod {
|
||||
))
|
||||
}
|
||||
|
||||
fn check_attributes(attributes: &[Attribute]) -> Result<(), &'static str> {
|
||||
fn check_attributes(
|
||||
_ty: &Data, attributes: &[Attribute],
|
||||
) -> Result<(), &'static str> {
|
||||
let repr = get_repr(attributes);
|
||||
match repr.as_ref().map(|repr| repr.as_str()) {
|
||||
Some("C") => Ok(()),
|
||||
@ -56,6 +65,22 @@ impl Derivable for Pod {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AnyBitPattern;
|
||||
|
||||
impl Derivable for AnyBitPattern {
|
||||
fn ident() -> TokenStream {
|
||||
quote!(::bytemuck::AnyBitPattern)
|
||||
}
|
||||
|
||||
fn implies_trait() -> Option<TokenStream> {
|
||||
Some(quote!(::bytemuck::Zeroable))
|
||||
}
|
||||
|
||||
fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
generate_fields_are_trait(input, Self::ident())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Zeroable;
|
||||
|
||||
impl Derivable for Zeroable {
|
||||
@ -63,11 +88,125 @@ impl Derivable for Zeroable {
|
||||
quote!(::bytemuck::Zeroable)
|
||||
}
|
||||
|
||||
fn struct_asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
generate_fields_are_trait(input, Self::ident())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoPadding;
|
||||
|
||||
impl Derivable for NoPadding {
|
||||
fn ident() -> TokenStream {
|
||||
quote!(::bytemuck::NoPadding)
|
||||
}
|
||||
|
||||
fn check_attributes(
|
||||
ty: &Data, attributes: &[Attribute],
|
||||
) -> Result<(), &'static str> {
|
||||
let repr = get_repr(attributes);
|
||||
match ty {
|
||||
Data::Struct(_) => match repr.as_deref() {
|
||||
Some("C" | "transparent") => Ok(()),
|
||||
_ => Err("NoPadding 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) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("NoPadding requires the enum to be an explicit #[repr(Int)]")
|
||||
},
|
||||
Data::Union(_) => Err("NoPadding can only be derived on enums and structs")
|
||||
}
|
||||
}
|
||||
|
||||
fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
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");
|
||||
}
|
||||
|
||||
match &input.data {
|
||||
Data::Struct(DataStruct { .. }) => {
|
||||
let assert_no_padding = generate_assert_no_padding(&input)?;
|
||||
let assert_fields_are_no_padding =
|
||||
generate_fields_are_trait(&input, Self::ident())?;
|
||||
|
||||
Ok(quote!(
|
||||
#assert_no_padding
|
||||
#assert_fields_are_no_padding
|
||||
))
|
||||
}
|
||||
Data::Enum(DataEnum { variants, .. }) => {
|
||||
if variants.iter().any(|variant| !variant.fields.is_empty()) {
|
||||
Err("Only fieldless enums are supported for NoPadding")
|
||||
} else {
|
||||
Ok(quote!())
|
||||
}
|
||||
}
|
||||
Data::Union(_) => Err("Internal error in NoPadding derive"), // shouldn't be possible since we already error in attribute check for this case
|
||||
}
|
||||
}
|
||||
|
||||
fn trait_impl(
|
||||
_input: &DeriveInput,
|
||||
) -> Result<(TokenStream, TokenStream), &'static str> {
|
||||
Ok((quote!(), quote!()))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CheckedBitPattern;
|
||||
|
||||
impl Derivable for CheckedBitPattern {
|
||||
fn ident() -> TokenStream {
|
||||
quote!(::bytemuck::CheckedBitPattern)
|
||||
}
|
||||
|
||||
fn check_attributes(
|
||||
ty: &Data, attributes: &[Attribute],
|
||||
) -> Result<(), &'static str> {
|
||||
let repr = get_repr(attributes);
|
||||
match ty {
|
||||
Data::Struct(_) => match repr.as_deref() {
|
||||
Some("C" | "transparent") => Ok(()),
|
||||
_ => Err("CheckedBitPattern derive 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) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("CheckedBitPattern requires the enum to be an explicit #[repr(Int)]")
|
||||
},
|
||||
Data::Union(_) => Err("CheckedBitPattern can only be derived on enums and structs")
|
||||
}
|
||||
}
|
||||
|
||||
fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
if !input.generics.params.is_empty() {
|
||||
return Err("CheckedBitPattern cannot be derived for structs containing generic parameters");
|
||||
}
|
||||
|
||||
match &input.data {
|
||||
Data::Struct(DataStruct { .. }) => {
|
||||
let assert_fields_are_maybe_pod =
|
||||
generate_fields_are_trait(&input, Self::ident())?;
|
||||
|
||||
Ok(assert_fields_are_maybe_pod)
|
||||
}
|
||||
Data::Enum(_) => Ok(quote!()), // nothing needed, already guaranteed OK by NoPadding
|
||||
Data::Union(_) => Err("Internal error in CheckedBitPattern derive"), // shouldn't be possible since we already error in attribute check for this case
|
||||
}
|
||||
}
|
||||
|
||||
fn trait_impl(
|
||||
input: &DeriveInput,
|
||||
) -> Result<(TokenStream, TokenStream), &'static str> {
|
||||
match &input.data {
|
||||
Data::Struct(DataStruct { fields, .. }) => {
|
||||
Ok(generate_checked_bit_pattern_struct(&input.ident, fields, &input.attrs))
|
||||
}
|
||||
Data::Enum(_) => generate_checked_bit_pattern_enum(input),
|
||||
Data::Union(_) => Err("Internal error in CheckedBitPattern derive"), // shouldn't be possible since we already error in attribute check for this case
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransparentWrapper;
|
||||
|
||||
impl TransparentWrapper {
|
||||
@ -100,7 +239,7 @@ impl Derivable for TransparentWrapper {
|
||||
.ok_or("when deriving TransparentWrapper for a struct with more than one field you need to specify the transparent field using #[transparent(T)]")
|
||||
}
|
||||
|
||||
fn struct_asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
fn asserts(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
let fields = get_struct_fields(input)?;
|
||||
let wrapped_type = match Self::get_wrapper_type(&input.attrs, fields) {
|
||||
Some(wrapped_type) => wrapped_type.to_string(),
|
||||
@ -119,7 +258,9 @@ impl Derivable for TransparentWrapper {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_attributes(attributes: &[Attribute]) -> Result<(), &'static str> {
|
||||
fn check_attributes(
|
||||
_ty: &Data, attributes: &[Attribute],
|
||||
) -> Result<(), &'static str> {
|
||||
let repr = get_repr(attributes);
|
||||
|
||||
match repr.as_ref().map(|repr| repr.as_str()) {
|
||||
@ -138,7 +279,9 @@ impl Derivable for Contiguous {
|
||||
quote!(::bytemuck::Contiguous)
|
||||
}
|
||||
|
||||
fn trait_impl(input: &DeriveInput) -> Result<TokenStream, &'static str> {
|
||||
fn trait_impl(
|
||||
input: &DeriveInput,
|
||||
) -> Result<(TokenStream, TokenStream), &'static str> {
|
||||
let repr = get_repr(&input.attrs)
|
||||
.ok_or("Contiguous requires the enum to be #[repr(Int)]")?;
|
||||
|
||||
@ -172,11 +315,14 @@ impl Derivable for Contiguous {
|
||||
let min_lit = LitInt::new(&format!("{}", min), input.span());
|
||||
let max_lit = LitInt::new(&format!("{}", max), input.span());
|
||||
|
||||
Ok(quote! {
|
||||
type Int = #repr_ident;
|
||||
const MIN_VALUE: #repr_ident = #min_lit;
|
||||
const MAX_VALUE: #repr_ident = #max_lit;
|
||||
})
|
||||
Ok((
|
||||
quote!(),
|
||||
quote! {
|
||||
type Int = #repr_ident;
|
||||
const MIN_VALUE: #repr_ident = #min_lit;
|
||||
const MAX_VALUE: #repr_ident = #max_lit;
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@ -204,6 +350,108 @@ fn get_field_types<'a>(
|
||||
fields.iter().map(|field| &field.ty)
|
||||
}
|
||||
|
||||
fn generate_checked_bit_pattern_struct(
|
||||
input_ident: &Ident, fields: &Fields, attrs: &[Attribute],
|
||||
) -> (TokenStream, TokenStream) {
|
||||
let bits_ty = Ident::new(&format!("{}Bits", input_ident), input_ident.span());
|
||||
|
||||
let repr = get_simple_attr(attrs, "repr").unwrap(); // should be checked in attr check already
|
||||
|
||||
let field_names = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
field.ident.clone().unwrap_or_else(|| {
|
||||
Ident::new(&format!("field{}", i), input_ident.span())
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let field_tys = fields.iter().map(|field| &field.ty).collect::<Vec<_>>();
|
||||
|
||||
let field_name = &field_names[..];
|
||||
let field_ty = &field_tys[..];
|
||||
|
||||
#[cfg(not(target_arch = "spirv"))]
|
||||
let derive_dbg = quote!(#[derive(Debug)]);
|
||||
#[cfg(target_arch = "spirv")]
|
||||
let derive_dbg = quote!();
|
||||
|
||||
(
|
||||
quote! {
|
||||
#[repr(#repr)]
|
||||
#[derive(Clone, Copy, ::bytemuck::AnyBitPattern)]
|
||||
#derive_dbg
|
||||
pub struct #bits_ty {
|
||||
#(#field_name: <#field_ty as ::bytemuck::CheckedBitPattern>::Bits,)*
|
||||
}
|
||||
},
|
||||
quote! {
|
||||
type Bits = #bits_ty;
|
||||
|
||||
#[inline]
|
||||
#[allow(clippy::double_comparisons)]
|
||||
fn is_valid_bit_pattern(bits: &#bits_ty) -> bool {
|
||||
#(<#field_ty as ::bytemuck::CheckedBitPattern>::is_valid_bit_pattern(&bits.#field_name) && )* true
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn generate_checked_bit_pattern_enum(
|
||||
input: &DeriveInput,
|
||||
) -> Result<(TokenStream, TokenStream), &'static str> {
|
||||
let span = input.span();
|
||||
let mut variants_with_discriminant =
|
||||
VariantDiscriminantIterator::new(get_enum_variants(input)?);
|
||||
|
||||
let (min, max, count) = variants_with_discriminant.try_fold(
|
||||
(i64::max_value(), i64::min_value(), 0),
|
||||
|(min, max, count), res| {
|
||||
let discriminant = res?;
|
||||
Ok((i64::min(min, discriminant), i64::max(max, discriminant), count + 1))
|
||||
},
|
||||
)?;
|
||||
|
||||
let check = if count == 0 {
|
||||
quote_spanned!(span => false)
|
||||
} else if max - min == count - 1 {
|
||||
// contiguous range
|
||||
let min_lit = LitInt::new(&format!("{}", min), span);
|
||||
let max_lit = LitInt::new(&format!("{}", max), span);
|
||||
|
||||
quote!(*bits >= #min_lit && *bits <= #max_lit)
|
||||
} else {
|
||||
// not contiguous range, check for each
|
||||
let variant_lits =
|
||||
VariantDiscriminantIterator::new(get_enum_variants(input)?)
|
||||
.map(|res| {
|
||||
let variant = res?;
|
||||
Ok(LitInt::new(&format!("{}", variant), span))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
// count is at least 1
|
||||
let first = &variant_lits[0];
|
||||
let rest = &variant_lits[1..];
|
||||
|
||||
quote!(matches!(*bits, #first #(| #rest )*))
|
||||
};
|
||||
|
||||
let repr = get_simple_attr(&input.attrs, "repr").unwrap(); // should be checked in attr check already
|
||||
Ok((
|
||||
quote!(),
|
||||
quote! {
|
||||
type Bits = #repr;
|
||||
|
||||
#[inline]
|
||||
#[allow(clippy::double_comparisons)]
|
||||
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
|
||||
#check
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// Check that a struct has no padding by asserting that the size of the struct
|
||||
/// is equal to the sum of the size of it's fields
|
||||
fn generate_assert_no_padding(
|
||||
|
@ -1,6 +1,8 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use bytemuck_derive::{Contiguous, Pod, TransparentWrapper, Zeroable};
|
||||
use bytemuck::{
|
||||
AnyBitPattern, Contiguous, CheckedBitPattern, NoPadding, Pod, TransparentWrapper, Zeroable,
|
||||
};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
#[derive(Copy, Clone, Pod, Zeroable)]
|
||||
@ -48,3 +50,99 @@ enum ContiguousWithImplicitValues {
|
||||
D,
|
||||
E,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, NoPadding)]
|
||||
#[repr(C)]
|
||||
struct NoPaddingTest {
|
||||
a: u16,
|
||||
b: u16,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, NoPadding, CheckedBitPattern, PartialEq, Eq)]
|
||||
enum CheckedBitPatternEnumWithValues {
|
||||
A = 0,
|
||||
B = 1,
|
||||
C = 2,
|
||||
D = 3,
|
||||
E = 4,
|
||||
}
|
||||
|
||||
#[repr(i8)]
|
||||
#[derive(Clone, Copy, NoPadding, CheckedBitPattern)]
|
||||
enum CheckedBitPatternEnumWithImplicitValues {
|
||||
A = -10,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, NoPadding, CheckedBitPattern, PartialEq, Eq)]
|
||||
enum CheckedBitPatternEnumNonContiguous {
|
||||
A = 1,
|
||||
B = 8,
|
||||
C = 2,
|
||||
D = 3,
|
||||
E = 56,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, NoPadding, CheckedBitPattern, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
struct CheckedBitPatternStruct {
|
||||
a: u8,
|
||||
b: CheckedBitPatternEnumNonContiguous,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, AnyBitPattern, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
struct AnyBitPatternTest {
|
||||
a: u16,
|
||||
b: u16
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fails_cast_contiguous() {
|
||||
let can_cast = CheckedBitPatternEnumWithValues::is_valid_bit_pattern(&5);
|
||||
assert!(!can_cast);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_cast_contiguous() {
|
||||
let res = bytemuck::checked::from_bytes::<CheckedBitPatternEnumWithValues>(&[2u8]);
|
||||
assert_eq!(*res, CheckedBitPatternEnumWithValues::C);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fails_cast_noncontiguous() {
|
||||
let can_cast = CheckedBitPatternEnumNonContiguous::is_valid_bit_pattern(&4);
|
||||
assert!(!can_cast);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_cast_noncontiguous() {
|
||||
let res =
|
||||
bytemuck::checked::from_bytes::<CheckedBitPatternEnumNonContiguous>(&[56u8]);
|
||||
assert_eq!(*res, CheckedBitPatternEnumNonContiguous::E);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fails_cast_struct() {
|
||||
let pod = [0u8, 24u8];
|
||||
let res = bytemuck::checked::try_from_bytes::<CheckedBitPatternStruct>(&pod);
|
||||
assert!(res.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_cast_struct() {
|
||||
let pod = [0u8, 8u8];
|
||||
let res = bytemuck::checked::from_bytes::<CheckedBitPatternStruct>(&pod);
|
||||
assert_eq!(*res, CheckedBitPatternStruct { a: 0, b: CheckedBitPatternEnumNonContiguous::B });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anybitpattern_implies_zeroable() {
|
||||
let test = AnyBitPatternTest::zeroed();
|
||||
assert_eq!(test, AnyBitPatternTest { a: 0, b: 0 });
|
||||
}
|
||||
|
@ -4,10 +4,9 @@
|
||||
//!
|
||||
//! * You must enable the `extern_crate_alloc` feature of `bytemuck` or you will
|
||||
//! not be able to use this module! This is generally done by adding the
|
||||
//! feature to the dependency in Cargo.toml like so:
|
||||
//! feature to the dependency in Cargo.toml like so:
|
||||
//! `bytemuck = { version = "VERSION_YOU_ARE_USING", features = ["extern_crate_alloc"]}`
|
||||
|
||||
|
||||
use super::*;
|
||||
use alloc::{
|
||||
alloc::{alloc_zeroed, Layout},
|
||||
@ -19,7 +18,7 @@ use core::convert::TryInto;
|
||||
|
||||
/// As [`try_cast_box`](try_cast_box), but unwraps for you.
|
||||
#[inline]
|
||||
pub fn cast_box<A: Pod, B: Pod>(input: Box<A>) -> Box<B> {
|
||||
pub fn cast_box<A: NoPadding, B: AnyBitPattern>(input: Box<A>) -> Box<B> {
|
||||
try_cast_box(input).map_err(|(e, _v)| e).unwrap()
|
||||
}
|
||||
|
||||
@ -33,7 +32,7 @@ pub fn cast_box<A: Pod, B: Pod>(input: Box<A>) -> Box<B> {
|
||||
/// alignment.
|
||||
/// * The start and end size of the `Box` must have the exact same size.
|
||||
#[inline]
|
||||
pub fn try_cast_box<A: Pod, B: Pod>(
|
||||
pub fn try_cast_box<A: NoPadding, B: AnyBitPattern>(
|
||||
input: Box<A>,
|
||||
) -> Result<Box<B>, (PodCastError, Box<A>)> {
|
||||
if align_of::<A>() != align_of::<B>() {
|
||||
@ -140,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.
|
||||
#[inline]
|
||||
pub fn cast_vec<A: Pod, B: Pod>(input: Vec<A>) -> Vec<B> {
|
||||
pub fn cast_vec<A: NoPadding, B: AnyBitPattern>(input: Vec<A>) -> Vec<B> {
|
||||
try_cast_vec(input).map_err(|(e, _v)| e).unwrap()
|
||||
}
|
||||
|
||||
@ -157,7 +156,7 @@ pub fn cast_vec<A: Pod, B: Pod>(input: Vec<A>) -> Vec<B> {
|
||||
/// capacity and length get adjusted during transmutation, but for now it's
|
||||
/// absolute.
|
||||
#[inline]
|
||||
pub fn try_cast_vec<A: Pod, B: Pod>(
|
||||
pub fn try_cast_vec<A: NoPadding, B: AnyBitPattern>(
|
||||
input: Vec<A>,
|
||||
) -> Result<Vec<B>, (PodCastError, Vec<A>)> {
|
||||
if align_of::<A>() != align_of::<B>() {
|
||||
@ -200,7 +199,7 @@ pub fn try_cast_vec<A: Pod, B: Pod>(
|
||||
/// assert_eq!(&vec_of_words[..], &[0x0005_0006, 0x0007_0008][..])
|
||||
/// }
|
||||
/// ```
|
||||
pub fn pod_collect_to_vec<A: Pod, B: Pod>(src: &[A]) -> Vec<B> {
|
||||
pub fn pod_collect_to_vec<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(src: &[A]) -> Vec<B> {
|
||||
let src_size = size_of_val(src);
|
||||
// Note(Lokathor): dst_count is rounded up so that the dest will always be at
|
||||
// least as many bytes as the src.
|
||||
|
43
src/anybitpattern.rs
Normal file
43
src/anybitpattern.rs
Normal file
@ -0,0 +1,43 @@
|
||||
use crate::{Pod, Zeroable};
|
||||
|
||||
/// Marker trait for "plain old data" types that are valid for any bit pattern.
|
||||
///
|
||||
/// The requirements for this is very similar to [`Pod`],
|
||||
/// except that it doesn't require that the type contains no padding bytes.
|
||||
/// 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
|
||||
/// *immutable* references and *owned* values into [`AnyBitPattern`] types, not
|
||||
/// *mutable* references.
|
||||
///
|
||||
/// [`Pod`] is a subset of [`AnyBitPattern`], meaning that any `T: Pod` is also
|
||||
/// [`AnyBitPattern`] but any `T: AnyBitPattern` is not necessarily [`Pod`].
|
||||
///
|
||||
/// [`AnyBitPattern`] is a subset of [`Zeroable`], meaning that any `T: AnyBitPattern`
|
||||
/// is also [`Zeroable`], but any `T: Zeroable` is not necessarily [`AnyBitPattern ]
|
||||
///
|
||||
/// # Derive
|
||||
///
|
||||
/// A `#[derive(AnyBitPattern)]` macro is provided under the `derive` feature flag which will
|
||||
/// automatically validate the requirements of this trait and implement the
|
||||
/// trait for you for both structs and enums. This is the recommended method for
|
||||
/// implementing the trait, however it's also possible to do manually. If you
|
||||
/// implement it manually, you *must* carefully follow the below safety rules.
|
||||
///
|
||||
/// * *NOTE: even `C-style`, fieldless enums are intentionally **excluded** from
|
||||
/// this trait, since it is **unsound** for an enum to have a discriminant value
|
||||
/// that is not one of its defined variants.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Similar to [`Pod`] except we disregard the rule about it must not contain padding.
|
||||
/// Still, this is a quite strong guarantee about a type, so *be careful* when
|
||||
/// implementing it manually.
|
||||
///
|
||||
/// * The type must be inhabited (eg: no
|
||||
/// [Infallible](core::convert::Infallible)).
|
||||
/// * The type must be valid for any bit pattern of its backing memory.
|
||||
/// * Structs need to have all fields also be `AnyBitPattern`.
|
||||
/// * There's probably more, don't mess it up (I mean it).
|
||||
pub unsafe trait AnyBitPattern: Zeroable + Sized + Copy + 'static {}
|
||||
|
||||
unsafe impl<T: Pod> AnyBitPattern for T {}
|
456
src/checked.rs
Normal file
456
src/checked.rs
Normal file
@ -0,0 +1,456 @@
|
||||
//! Checked versions of the casting functions exposed in crate root
|
||||
//! that support [`CheckedBitPattern`] types.
|
||||
|
||||
use crate::{internal::{self, something_went_wrong}, NoPadding, AnyBitPattern};
|
||||
|
||||
/// 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
|
||||
/// a runtime check on a perticular set of bits. This is particularly
|
||||
/// useful for types like fieldless ('C-style') enums, [`char`], bool, and structs containing them.
|
||||
///
|
||||
/// To do this, we define a `Bits` type which is a type with equivalent layout
|
||||
/// to `Self` other than the invalid bit patterns which disallow `Self` from
|
||||
/// being [`AnyBitPattern`]. This `Bits` type must itself implement [`AnyBitPattern`].
|
||||
/// Then, we implement a function that checks wheter a certain instance
|
||||
/// of the `Bits` is also a valid bit pattern of `Self`. If this check passes, then we
|
||||
/// can allow casting from the `Bits` to `Self` (and therefore, any type which
|
||||
/// is able to be cast to `Bits` is also able to be cast to `Self`).
|
||||
///
|
||||
/// [`AnyBitPattern`] is a subset of [`CheckedBitPattern`], meaning that any `T: AnyBitPattern` is also
|
||||
/// [`CheckedBitPattern`]. This means you can also use any [`AnyBitPattern`] type in the checked versions
|
||||
/// of casting functions in this module. If it's possible, prefer implementing [`AnyBitPattern`] for your
|
||||
/// type directly instead of [`CheckedBitPattern`] as it gives greater flexibility.
|
||||
///
|
||||
/// # Derive
|
||||
///
|
||||
/// A `#[derive(CheckedBitPattern)]` macro is provided under the `derive` feature flag which will
|
||||
/// automatically validate the requirements of this trait and implement the
|
||||
/// 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.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// If manually implementing the trait, we can do something like so:
|
||||
///
|
||||
/// ```rust
|
||||
/// use bytemuck::{CheckedBitPattern, NoPadding};
|
||||
///
|
||||
/// #[repr(u32)]
|
||||
/// #[derive(Copy, Clone)]
|
||||
/// enum MyEnum {
|
||||
/// Variant0 = 0,
|
||||
/// Variant1 = 1,
|
||||
/// Variant2 = 2,
|
||||
/// }
|
||||
///
|
||||
/// unsafe impl CheckedBitPattern for MyEnum {
|
||||
/// type Bits = u32;
|
||||
///
|
||||
/// fn is_valid_bit_pattern(bits: &u32) -> bool {
|
||||
/// match *bits {
|
||||
/// 0 | 1 | 2 => true,
|
||||
/// _ => false,
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // It is often useful to also implement `NoPadding` on our `CheckedBitPattern` types.
|
||||
/// // 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.
|
||||
/// unsafe impl NoPadding for MyEnum {}
|
||||
/// ```
|
||||
///
|
||||
/// We can now use relevant casting functions. For example,
|
||||
///
|
||||
/// ```rust
|
||||
/// # use bytemuck::{CheckedBitPattern, NoPadding};
|
||||
/// # #[repr(u32)]
|
||||
/// # #[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
/// # enum MyEnum {
|
||||
/// # Variant0 = 0,
|
||||
/// # Variant1 = 1,
|
||||
/// # Variant2 = 2,
|
||||
/// # }
|
||||
/// # unsafe impl NoPadding for MyEnum {}
|
||||
/// # unsafe impl CheckedBitPattern for MyEnum {
|
||||
/// # type Bits = u32;
|
||||
/// # fn is_valid_bit_pattern(bits: &u32) -> bool {
|
||||
/// # match *bits {
|
||||
/// # 0 | 1 | 2 => true,
|
||||
/// # _ => false,
|
||||
/// # }
|
||||
/// # }
|
||||
/// # }
|
||||
/// use bytemuck::{bytes_of, bytes_of_mut};
|
||||
/// use bytemuck::checked;
|
||||
///
|
||||
/// let bytes = bytes_of(&2u32);
|
||||
/// let result = checked::try_from_bytes::<MyEnum>(bytes);
|
||||
/// assert_eq!(result, Ok(&MyEnum::Variant2));
|
||||
///
|
||||
/// // Fails for invalid discriminant
|
||||
/// let bytes = bytes_of(&100u32);
|
||||
/// let result = checked::try_from_bytes::<MyEnum>(bytes);
|
||||
/// assert!(result.is_err());
|
||||
///
|
||||
/// // Since we implemented NoPadding, we can also cast mutably from an original type
|
||||
/// // that is `NoPadding + AnyBitPattern`:
|
||||
/// let mut my_u32 = 2u32;
|
||||
/// {
|
||||
/// let as_enum_mut = checked::cast_mut::<_, MyEnum>(&mut my_u32);
|
||||
/// assert_eq!(as_enum_mut, &mut MyEnum::Variant2);
|
||||
/// *as_enum_mut = MyEnum::Variant0;
|
||||
/// }
|
||||
/// assert_eq!(my_u32, 0u32);
|
||||
/// ```
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// * `Self` *must* have the same layout as the specified `Bits` except for
|
||||
/// the possible invalid bit patterns being checked during [`is_valid_bit_pattern`].
|
||||
/// * This almost certainly means your type must be `#[repr(C)]` or a similar
|
||||
/// specified repr, but if you think you know better, you probably don't. If you
|
||||
/// still think you know better, be careful and have fun. And don't mess it up
|
||||
/// (I mean it).
|
||||
/// * If [`is_valid_bit_pattern`] returns true, then the bit pattern contained in
|
||||
/// `bits` must also be valid for an instance of `Self`.
|
||||
/// * Probably more, don't mess it up (I mean it 2.0)
|
||||
///
|
||||
/// [`is_valid_bit_pattern`]: CheckedBitPattern::is_valid_bit_pattern
|
||||
/// [`Pod`]: crate::Pod
|
||||
pub unsafe trait CheckedBitPattern: Copy {
|
||||
/// `Self` *must* have the same layout as the specified `Bits` except for
|
||||
/// the possible invalid bit patterns being checked during [`is_valid_bit_pattern`].
|
||||
///
|
||||
/// [`is_valid_bit_pattern`]: CheckedBitPattern::is_valid_bit_pattern
|
||||
type Bits: AnyBitPattern;
|
||||
|
||||
/// If this function returns true, then it must be valid to reinterpret `bits` as `&Self`.
|
||||
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool;
|
||||
}
|
||||
|
||||
unsafe impl<T: AnyBitPattern> CheckedBitPattern for T {
|
||||
type Bits = T;
|
||||
|
||||
#[inline(always)]
|
||||
fn is_valid_bit_pattern(_bits: &T) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl CheckedBitPattern for char {
|
||||
type Bits = u32;
|
||||
|
||||
#[inline]
|
||||
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
|
||||
core::char::from_u32(*bits).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl CheckedBitPattern for bool {
|
||||
type Bits = u8;
|
||||
|
||||
#[inline]
|
||||
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
|
||||
match *bits {
|
||||
0 | 1 => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The things that can go wrong when casting between [`CheckedBitPattern`] data forms.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum CheckedCastError {
|
||||
/// An error occurred during a true-[`Pod`] cast
|
||||
PodCastError(crate::PodCastError),
|
||||
/// When casting to a [`CheckedBitPattern`] type, it is possible that the original
|
||||
/// data contains an invalid bit pattern. If so, the cast will fail and
|
||||
/// this error will be returned. Will never happen on casts between
|
||||
/// [`Pod`] types.
|
||||
InvalidBitPattern,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "spirv"))]
|
||||
impl core::fmt::Display for CheckedCastError {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "extern_crate_std")]
|
||||
impl std::error::Error for CheckedCastError {}
|
||||
|
||||
impl From<crate::PodCastError> for CheckedCastError {
|
||||
fn from(err: crate::PodCastError) -> CheckedCastError {
|
||||
CheckedCastError::PodCastError(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
/// * If the slice contains an invalid bit pattern for `T`
|
||||
#[inline]
|
||||
pub fn try_from_bytes<T: CheckedBitPattern>(
|
||||
s: &[u8],
|
||||
) -> Result<&T, CheckedCastError> {
|
||||
let pod = unsafe { internal::try_from_bytes(s) }?;
|
||||
|
||||
if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
|
||||
Ok(unsafe { &*(pod as *const <T as CheckedBitPattern>::Bits as *const T) })
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
/// * If the slice contains an invalid bit pattern for `T`
|
||||
#[inline]
|
||||
pub fn try_from_bytes_mut<T: CheckedBitPattern + NoPadding>(
|
||||
s: &mut [u8],
|
||||
) -> Result<&mut T, CheckedCastError> {
|
||||
let pod = unsafe { internal::try_from_bytes_mut(s) }?;
|
||||
|
||||
if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
|
||||
Ok(unsafe { &mut *(pod as *mut <T as CheckedBitPattern>::Bits as *mut T) })
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads from the bytes as if they were a `T`.
|
||||
///
|
||||
/// ## Failure
|
||||
/// * If the `bytes` length is not equal to `size_of::<T>()`.
|
||||
/// * If the slice contains an invalid bit pattern for `T`
|
||||
#[inline]
|
||||
pub fn try_pod_read_unaligned<T: CheckedBitPattern>(bytes: &[u8]) -> Result<T, CheckedCastError> {
|
||||
let pod = unsafe { internal::try_pod_read_unaligned(bytes) }?;
|
||||
|
||||
if <T as CheckedBitPattern>::is_valid_bit_pattern(pod) {
|
||||
Ok(unsafe { transmute!(pod) })
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to cast `T` into `U`.
|
||||
///
|
||||
/// Note that for this particular type of cast, alignment isn't a factor. The
|
||||
/// input value is semantically copied into the function and then returned to a
|
||||
/// new memory location which will have whatever the required alignment of the
|
||||
/// output type is.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the types don't have the same size this fails.
|
||||
/// * If `a` contains an invalid bit pattern for `B` this fails.
|
||||
#[inline]
|
||||
pub fn try_cast<A: NoPadding, B: CheckedBitPattern>(
|
||||
a: A,
|
||||
) -> Result<B, CheckedCastError> {
|
||||
let pod = unsafe { internal::try_cast(a) }?;
|
||||
|
||||
if <B as CheckedBitPattern>::is_valid_bit_pattern(&pod) {
|
||||
Ok(unsafe { transmute!(pod) })
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert a `&T` into `&U`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the reference isn't aligned in the new type
|
||||
/// * If the source type and target type aren't the same size.
|
||||
/// * If `a` contains an invalid bit pattern for `B` this fails.
|
||||
#[inline]
|
||||
pub fn try_cast_ref<A: NoPadding, B: CheckedBitPattern>(
|
||||
a: &A,
|
||||
) -> Result<&B, CheckedCastError> {
|
||||
let pod = unsafe { internal::try_cast_ref(a) }?;
|
||||
|
||||
if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
|
||||
Ok(unsafe { &*(pod as *const <B as CheckedBitPattern>::Bits as *const B) })
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert a `&mut T` into `&mut U`.
|
||||
///
|
||||
/// As [`checked_cast_ref`], but `mut`.
|
||||
#[inline]
|
||||
pub fn try_cast_mut<A: NoPadding + AnyBitPattern, B: CheckedBitPattern + NoPadding>(
|
||||
a: &mut A,
|
||||
) -> Result<&mut B, CheckedCastError> {
|
||||
let pod = unsafe { internal::try_cast_mut(a) }?;
|
||||
|
||||
if <B as CheckedBitPattern>::is_valid_bit_pattern(pod) {
|
||||
Ok(unsafe { &mut *(pod as *mut <B as CheckedBitPattern>::Bits as *mut B) })
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
|
||||
///
|
||||
/// * `input.as_ptr() as usize == output.as_ptr() as usize`
|
||||
/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the target type has a greater alignment requirement and the input slice
|
||||
/// isn't aligned.
|
||||
/// * If the target element type is a different size from the current element
|
||||
/// type, and the output slice wouldn't be a whole number of elements when
|
||||
/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
|
||||
/// that's a failure).
|
||||
/// * 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.
|
||||
/// * If any element of the converted slice would contain an invalid bit pattern for `B` this fails.
|
||||
#[inline]
|
||||
pub fn try_cast_slice<A: NoPadding, B: CheckedBitPattern>(
|
||||
a: &[A],
|
||||
) -> Result<&[B], CheckedCastError> {
|
||||
let pod = unsafe { internal::try_cast_slice(a) }?;
|
||||
|
||||
if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
|
||||
Ok(unsafe {
|
||||
core::slice::from_raw_parts(pod.as_ptr() as *const B, pod.len())
|
||||
})
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
|
||||
/// length).
|
||||
///
|
||||
/// As [`checked_cast_slice`], but `&mut`.
|
||||
#[inline]
|
||||
pub fn try_cast_slice_mut<A: NoPadding + AnyBitPattern, B: CheckedBitPattern + NoPadding>(
|
||||
a: &mut [A],
|
||||
) -> Result<&mut [B], CheckedCastError> {
|
||||
let pod = unsafe { internal::try_cast_slice_mut(a) }?;
|
||||
|
||||
if pod.iter().all(|pod| <B as CheckedBitPattern>::is_valid_bit_pattern(pod)) {
|
||||
Ok(unsafe {
|
||||
core::slice::from_raw_parts_mut(pod.as_ptr() as *mut B, pod.len())
|
||||
})
|
||||
} else {
|
||||
Err(CheckedCastError::InvalidBitPattern)
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn from_bytes<T: CheckedBitPattern>(s: &[u8]) -> &T {
|
||||
match try_from_bytes(s) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("from_bytes", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn from_bytes_mut<T: NoPadding + CheckedBitPattern>(s: &mut [u8]) -> &mut T {
|
||||
match try_from_bytes_mut(s) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("from_bytes_mut", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the slice into a `T` value.
|
||||
///
|
||||
/// ## Panics
|
||||
/// * This is like `try_pod_read_unaligned` but will panic on failure.
|
||||
#[inline]
|
||||
pub fn pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> T {
|
||||
match try_pod_read_unaligned(bytes) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("pod_read_unaligned", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `T` into `U`
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
|
||||
#[inline]
|
||||
pub fn cast<A: NoPadding, B: CheckedBitPattern>(a: A) -> B {
|
||||
match try_cast(a) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("cast", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&mut T` into `&mut U`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + CheckedBitPattern>(a: &mut A) -> &mut B {
|
||||
match try_cast_mut(a) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("cast_mut", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&T` into `&U`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_ref`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_ref<A: NoPadding, B: CheckedBitPattern>(a: &A) -> &B {
|
||||
match try_cast_ref(a) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("cast_ref", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&[A]` into `&[B]`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_slice`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_slice<A: NoPadding, B: CheckedBitPattern>(a: &[A]) -> &[B] {
|
||||
match try_cast_slice(a) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("cast_slice", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&mut [T]` into `&mut [U]`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_slice_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_slice_mut<A: NoPadding + AnyBitPattern, B: NoPadding + CheckedBitPattern>(a: &mut [A]) -> &mut [B] {
|
||||
match try_cast_slice_mut(a) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("cast_slice_mut", e),
|
||||
}
|
||||
}
|
372
src/internal.rs
Normal file
372
src/internal.rs
Normal file
@ -0,0 +1,372 @@
|
||||
//! Internal implementation of casting functions not bound by marker traits
|
||||
//! and therefore marked as unsafe. This is used so that we don't need to duplicate
|
||||
//! the business logic contained in these functions between the versions exported in
|
||||
//! the crate root, `checked`, and `relaxed` modules.
|
||||
#![allow(unused_unsafe)]
|
||||
|
||||
use crate::PodCastError;
|
||||
use core::{marker::*, mem::*};
|
||||
|
||||
/*
|
||||
|
||||
Note(Lokathor): We've switched all of the `unwrap` to `match` because there is
|
||||
apparently a bug: https://github.com/rust-lang/rust/issues/68667
|
||||
and it doesn't seem to show up in simple godbolt examples but has been reported
|
||||
as having an impact when there's a cast mixed in with other more complicated
|
||||
code around it. Rustc/LLVM ends up missing that the `Err` can't ever happen for
|
||||
particular type combinations, and then it doesn't fully eliminated the panic
|
||||
possibility code branch.
|
||||
|
||||
*/
|
||||
|
||||
/// Immediately panics.
|
||||
#[cold]
|
||||
#[inline(never)]
|
||||
pub(crate) fn something_went_wrong<D: core::fmt::Display>(_src: &str, _err: D) -> ! {
|
||||
// Note(Lokathor): Keeping the panic here makes the panic _formatting_ go
|
||||
// here too, which helps assembly readability and also helps keep down
|
||||
// the inline pressure.
|
||||
#[cfg(not(target_arch = "spirv"))]
|
||||
panic!("{src}>{err}", src = _src, err = _err);
|
||||
// Note: On the spirv targets from [rust-gpu](https://github.com/EmbarkStudios/rust-gpu)
|
||||
// panic formatting cannot be used. We we just give a generic error message
|
||||
// The chance that the panicking version of these functions will ever get
|
||||
// called on spir-v targets with invalid inputs is small, but giving a
|
||||
// simple error message is better than no error message at all.
|
||||
#[cfg(target_arch = "spirv")]
|
||||
panic!("Called a panicing helper from bytemuck which paniced");
|
||||
}
|
||||
|
||||
/// Re-interprets `&T` as `&[u8]`.
|
||||
///
|
||||
/// 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.
|
||||
#[inline(always)]
|
||||
pub(crate) unsafe fn bytes_of<T: Copy>(t: &T) -> &[u8] {
|
||||
if size_of::<T>() == 0 {
|
||||
&[]
|
||||
} else {
|
||||
match try_cast_slice::<T, u8>(core::slice::from_ref(t)) {
|
||||
Ok(s) => s,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut T` as `&mut [u8]`.
|
||||
///
|
||||
/// 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.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn bytes_of_mut<T: Copy>(t: &mut T) -> &mut [u8] {
|
||||
if size_of::<T>() == 0 {
|
||||
&mut []
|
||||
} else {
|
||||
match try_cast_slice_mut::<T, u8>(core::slice::from_mut(t)) {
|
||||
Ok(s) => s,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes`] but will panic on error.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn from_bytes<T: Copy>(s: &[u8]) -> &T {
|
||||
match try_from_bytes(s) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("from_bytes", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn from_bytes_mut<T: Copy>(s: &mut [u8]) -> &mut T {
|
||||
match try_from_bytes_mut(s) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("from_bytes_mut", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads from the bytes as if they were a `T`.
|
||||
///
|
||||
/// ## Failure
|
||||
/// * If the `bytes` length is not equal to `size_of::<T>()`.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_pod_read_unaligned<T: Copy>(bytes: &[u8]) -> Result<T, PodCastError> {
|
||||
if bytes.len() != size_of::<T>() {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else {
|
||||
Ok(unsafe { (bytes.as_ptr() as *const T).read_unaligned() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the slice into a `T` value.
|
||||
///
|
||||
/// ## Panics
|
||||
/// * This is like `try_pod_read_unaligned` but will panic on failure.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn pod_read_unaligned<T: Copy>(bytes: &[u8]) -> T {
|
||||
match try_pod_read_unaligned(bytes) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("pod_read_unaligned", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_from_bytes<T: Copy>(
|
||||
s: &[u8],
|
||||
) -> Result<&T, PodCastError> {
|
||||
if s.len() != size_of::<T>() {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else {
|
||||
Ok(unsafe { &*(s.as_ptr() as *const T) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_from_bytes_mut<T: Copy>(
|
||||
s: &mut [u8],
|
||||
) -> Result<&mut T, PodCastError> {
|
||||
if s.len() != size_of::<T>() {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else {
|
||||
Ok(unsafe { &mut *(s.as_mut_ptr() as *mut T) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `T` into `U`
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn cast<A: Copy, B: Copy>(a: A) -> B {
|
||||
if size_of::<A>() == size_of::<B>() {
|
||||
unsafe { transmute!(a) }
|
||||
} else {
|
||||
something_went_wrong("cast", PodCastError::SizeMismatch)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&mut T` into `&mut U`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn cast_mut<A: Copy, B: Copy>(a: &mut A) -> &mut B {
|
||||
if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
|
||||
// Plz mr compiler, just notice that we can't ever hit Err in this case.
|
||||
match try_cast_mut(a) {
|
||||
Ok(b) => b,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
match try_cast_mut(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_mut", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&T` into `&U`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_ref`] but will panic on error.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn cast_ref<A: Copy, B: Copy>(a: &A) -> &B {
|
||||
if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
|
||||
// Plz mr compiler, just notice that we can't ever hit Err in this case.
|
||||
match try_cast_ref(a) {
|
||||
Ok(b) => b,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
match try_cast_ref(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_ref", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&[A]` into `&[B]`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_slice`] but will panic on error.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn cast_slice<A: Copy, B: Copy>(a: &[A]) -> &[B] {
|
||||
match try_cast_slice(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_slice", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast `&mut [T]` into `&mut [U]`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_cast_slice_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn cast_slice_mut<A: Copy, B: Copy>(a: &mut [A]) -> &mut [B] {
|
||||
match try_cast_slice_mut(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_slice_mut", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to cast `T` into `U`.
|
||||
///
|
||||
/// Note that for this particular type of cast, alignment isn't a factor. The
|
||||
/// input value is semantically copied into the function and then returned to a
|
||||
/// new memory location which will have whatever the required alignment of the
|
||||
/// output type is.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the types don't have the same size this fails.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_cast<A: Copy, B: Copy>(
|
||||
a: A,
|
||||
) -> Result<B, PodCastError> {
|
||||
if size_of::<A>() == size_of::<B>() {
|
||||
Ok(unsafe { transmute!(a) })
|
||||
} else {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert a `&T` into `&U`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the reference isn't aligned in the new type
|
||||
/// * If the source type and target type aren't the same size.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_cast_ref<A: Copy, B: Copy>(
|
||||
a: &A,
|
||||
) -> Result<&B, PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a as *const A as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe { &*(a as *const A as *const B) })
|
||||
} else {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert a `&mut T` into `&mut U`.
|
||||
///
|
||||
/// As [`try_cast_ref`], but `mut`.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_cast_mut<A: Copy, B: Copy>(
|
||||
a: &mut A,
|
||||
) -> Result<&mut B, PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a as *mut A as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe { &mut *(a as *mut A as *mut B) })
|
||||
} else {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
|
||||
///
|
||||
/// * `input.as_ptr() as usize == output.as_ptr() as usize`
|
||||
/// * `input.len() * size_of::<A>() == output.len() * size_of::<B>()`
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the target type has a greater alignment requirement and the input slice
|
||||
/// isn't aligned.
|
||||
/// * If the target element type is a different size from the current element
|
||||
/// type, and the output slice wouldn't be a whole number of elements when
|
||||
/// accounting for the size change (eg: 3 `u16` values is 1.5 `u32` values, so
|
||||
/// that's a failure).
|
||||
/// * 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.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_cast_slice<A: Copy, B: Copy>(
|
||||
a: &[A],
|
||||
) -> Result<&[B], PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a.as_ptr() as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, a.len()) })
|
||||
} else if size_of::<A>() == 0 || size_of::<B>() == 0 {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
|
||||
let new_len = core::mem::size_of_val(a) / size_of::<B>();
|
||||
Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, new_len) })
|
||||
} else {
|
||||
Err(PodCastError::OutputSliceWouldHaveSlop)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
|
||||
/// length).
|
||||
///
|
||||
/// As [`try_cast_slice`], but `&mut`.
|
||||
#[inline]
|
||||
pub(crate) unsafe fn try_cast_slice_mut<A: Copy, B: Copy>(
|
||||
a: &mut [A],
|
||||
) -> Result<&mut [B], PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a.as_mut_ptr() as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe {
|
||||
core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, a.len())
|
||||
})
|
||||
} else if size_of::<A>() == 0 || size_of::<B>() == 0 {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
|
||||
let new_len = core::mem::size_of_val(a) / size_of::<B>();
|
||||
Ok(unsafe {
|
||||
core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, new_len)
|
||||
})
|
||||
} else {
|
||||
Err(PodCastError::OutputSliceWouldHaveSlop)
|
||||
}
|
||||
}
|
380
src/lib.rs
380
src/lib.rs
@ -66,7 +66,7 @@ macro_rules! impl_unsafe_marker_for_array {
|
||||
/// statically.
|
||||
macro_rules! transmute {
|
||||
($val:expr) => {
|
||||
transmute_copy(&ManuallyDrop::new($val))
|
||||
::core::mem::transmute_copy(&::core::mem::ManuallyDrop::new($val))
|
||||
};
|
||||
}
|
||||
|
||||
@ -80,12 +80,23 @@ pub mod allocation;
|
||||
#[cfg(feature = "extern_crate_alloc")]
|
||||
pub use allocation::*;
|
||||
|
||||
mod anybitpattern;
|
||||
pub use anybitpattern::*;
|
||||
|
||||
pub mod checked;
|
||||
pub use checked::CheckedBitPattern;
|
||||
|
||||
mod internal;
|
||||
|
||||
mod zeroable;
|
||||
pub use zeroable::*;
|
||||
|
||||
mod pod;
|
||||
pub use pod::*;
|
||||
|
||||
mod nopadding;
|
||||
pub use nopadding::*;
|
||||
|
||||
mod contiguous;
|
||||
pub use contiguous::*;
|
||||
|
||||
@ -96,156 +107,9 @@ mod transparent;
|
||||
pub use transparent::*;
|
||||
|
||||
#[cfg(feature = "derive")]
|
||||
pub use bytemuck_derive::{Contiguous, Pod, TransparentWrapper, Zeroable};
|
||||
|
||||
/*
|
||||
|
||||
Note(Lokathor): We've switched all of the `unwrap` to `match` because there is
|
||||
apparently a bug: https://github.com/rust-lang/rust/issues/68667
|
||||
and it doesn't seem to show up in simple godbolt examples but has been reported
|
||||
as having an impact when there's a cast mixed in with other more complicated
|
||||
code around it. Rustc/LLVM ends up missing that the `Err` can't ever happen for
|
||||
particular type combinations, and then it doesn't fully eliminated the panic
|
||||
possibility code branch.
|
||||
|
||||
*/
|
||||
|
||||
/// Immediately panics.
|
||||
#[cold]
|
||||
#[inline(never)]
|
||||
fn something_went_wrong(_src: &str, _err: PodCastError) -> ! {
|
||||
// Note(Lokathor): Keeping the panic here makes the panic _formatting_ go
|
||||
// here too, which helps assembly readability and also helps keep down
|
||||
// the inline pressure.
|
||||
#[cfg(not(target_arch = "spirv"))]
|
||||
panic!("{src}>{err:?}", src = _src, err = _err);
|
||||
// Note: On the spirv targets from [rust-gpu](https://github.com/EmbarkStudios/rust-gpu)
|
||||
// panic formatting cannot be used. We we just give a generic error message
|
||||
// The chance that the panicking version of these functions will ever get
|
||||
// called on spir-v targets with invalid inputs is small, but giving a
|
||||
// simple error message is better than no error message at all.
|
||||
#[cfg(target_arch = "spirv")]
|
||||
panic!("Called a panicing helper from bytemuck which paniced");
|
||||
}
|
||||
|
||||
/// Re-interprets `&T` as `&[u8]`.
|
||||
///
|
||||
/// 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.
|
||||
#[inline]
|
||||
pub fn bytes_of<T: Pod>(t: &T) -> &[u8] {
|
||||
if size_of::<T>() == 0 {
|
||||
&[]
|
||||
} else {
|
||||
match try_cast_slice::<T, u8>(core::slice::from_ref(t)) {
|
||||
Ok(s) => s,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut T` as `&mut [u8]`.
|
||||
///
|
||||
/// 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.
|
||||
#[inline]
|
||||
pub fn bytes_of_mut<T: Pod>(t: &mut T) -> &mut [u8] {
|
||||
if size_of::<T>() == 0 {
|
||||
&mut []
|
||||
} else {
|
||||
match try_cast_slice_mut::<T, u8>(core::slice::from_mut(t)) {
|
||||
Ok(s) => s,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn from_bytes<T: Pod>(s: &[u8]) -> &T {
|
||||
match try_from_bytes(s) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("from_bytes", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn from_bytes_mut<T: Pod>(s: &mut [u8]) -> &mut T {
|
||||
match try_from_bytes_mut(s) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("from_bytes_mut", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads from the bytes as if they were a `T`.
|
||||
///
|
||||
/// ## Failure
|
||||
/// * If the `bytes` length is not equal to `size_of::<T>()`.
|
||||
#[inline]
|
||||
pub fn try_pod_read_unaligned<T: Pod>(bytes: &[u8]) -> Result<T, PodCastError> {
|
||||
if bytes.len() != size_of::<T>() {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else {
|
||||
Ok(unsafe { (bytes.as_ptr() as *const T).read_unaligned() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the slice into a `T` value.
|
||||
///
|
||||
/// ## Panics
|
||||
/// * This is like `try_pod_read_unaligned` but will panic on failure.
|
||||
#[inline]
|
||||
pub fn pod_read_unaligned<T: Pod>(bytes: &[u8]) -> T {
|
||||
match try_pod_read_unaligned(bytes) {
|
||||
Ok(t) => t,
|
||||
Err(e) => something_went_wrong("pod_read_unaligned", e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
#[inline]
|
||||
pub fn try_from_bytes<T: Pod>(s: &[u8]) -> Result<&T, PodCastError> {
|
||||
if s.len() != size_of::<T>() {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else {
|
||||
Ok(unsafe { &*(s.as_ptr() as *const T) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
#[inline]
|
||||
pub fn try_from_bytes_mut<T: Pod>(
|
||||
s: &mut [u8],
|
||||
) -> Result<&mut T, PodCastError> {
|
||||
if s.len() != size_of::<T>() {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if (s.as_ptr() as usize) % align_of::<T>() != 0 {
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else {
|
||||
Ok(unsafe { &mut *(s.as_mut_ptr() as *mut T) })
|
||||
}
|
||||
}
|
||||
pub use bytemuck_derive::{
|
||||
AnyBitPattern, Contiguous, CheckedBitPattern, NoPadding, Pod, TransparentWrapper, Zeroable,
|
||||
};
|
||||
|
||||
/// The things that can go wrong when casting between [`Pod`] data forms.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
@ -278,18 +142,94 @@ impl core::fmt::Display for PodCastError {
|
||||
#[cfg(feature = "extern_crate_std")]
|
||||
impl std::error::Error for PodCastError {}
|
||||
|
||||
/// Re-interprets `&T` as `&[u8]`.
|
||||
///
|
||||
/// 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.
|
||||
#[inline]
|
||||
pub fn bytes_of<T: NoPadding>(t: &T) -> &[u8] {
|
||||
unsafe { internal::bytes_of(t) }
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut T` as `&mut [u8]`.
|
||||
///
|
||||
/// 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.
|
||||
#[inline]
|
||||
pub fn bytes_of_mut<T: NoPadding + AnyBitPattern>(t: &mut T) -> &mut [u8] {
|
||||
unsafe { internal::bytes_of_mut(t) }
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn from_bytes<T: AnyBitPattern>(s: &[u8]) -> &T {
|
||||
unsafe { internal::from_bytes(s) }
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// This is [`try_from_bytes_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn from_bytes_mut<T: NoPadding + AnyBitPattern>(s: &mut [u8]) -> &mut T {
|
||||
unsafe { internal::from_bytes_mut(s) }
|
||||
}
|
||||
|
||||
/// Reads from the bytes as if they were a `T`.
|
||||
///
|
||||
/// ## Failure
|
||||
/// * If the `bytes` length is not equal to `size_of::<T>()`.
|
||||
#[inline]
|
||||
pub fn try_pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> Result<T, PodCastError> {
|
||||
unsafe { internal::try_pod_read_unaligned(bytes) }
|
||||
}
|
||||
|
||||
/// Reads the slice into a `T` value.
|
||||
///
|
||||
/// ## Panics
|
||||
/// * This is like `try_pod_read_unaligned` but will panic on failure.
|
||||
#[inline]
|
||||
pub fn pod_read_unaligned<T: AnyBitPattern>(bytes: &[u8]) -> T {
|
||||
unsafe { internal::pod_read_unaligned(bytes) }
|
||||
}
|
||||
|
||||
/// Re-interprets `&[u8]` as `&T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
#[inline]
|
||||
pub fn try_from_bytes<T: AnyBitPattern>(s: &[u8]) -> Result<&T, PodCastError> {
|
||||
unsafe { internal::try_from_bytes(s) }
|
||||
}
|
||||
|
||||
/// Re-interprets `&mut [u8]` as `&mut T`.
|
||||
///
|
||||
/// ## Failure
|
||||
///
|
||||
/// * If the slice isn't aligned for the new type
|
||||
/// * If the slice's length isn’t exactly the size of the new type
|
||||
#[inline]
|
||||
pub fn try_from_bytes_mut<T: NoPadding + AnyBitPattern>(
|
||||
s: &mut [u8],
|
||||
) -> Result<&mut T, PodCastError> {
|
||||
unsafe { internal::try_from_bytes_mut(s) }
|
||||
}
|
||||
|
||||
/// Cast `T` into `U`
|
||||
///
|
||||
/// ## Panics
|
||||
///
|
||||
/// * This is like [`try_cast`](try_cast), but will panic on a size mismatch.
|
||||
#[inline]
|
||||
pub fn cast<A: Pod, B: Pod>(a: A) -> B {
|
||||
if size_of::<A>() == size_of::<B>() {
|
||||
unsafe { transmute!(a) }
|
||||
} else {
|
||||
something_went_wrong("cast", PodCastError::SizeMismatch)
|
||||
}
|
||||
pub fn cast<A: NoPadding, B: AnyBitPattern>(a: A) -> B {
|
||||
unsafe { internal::cast(a) }
|
||||
}
|
||||
|
||||
/// Cast `&mut T` into `&mut U`.
|
||||
@ -298,19 +238,8 @@ pub fn cast<A: Pod, B: Pod>(a: A) -> B {
|
||||
///
|
||||
/// This is [`try_cast_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_mut<A: Pod, B: Pod>(a: &mut A) -> &mut B {
|
||||
if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
|
||||
// Plz mr compiler, just notice that we can't ever hit Err in this case.
|
||||
match try_cast_mut(a) {
|
||||
Ok(b) => b,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
match try_cast_mut(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_mut", e),
|
||||
}
|
||||
}
|
||||
pub fn cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(a: &mut A) -> &mut B {
|
||||
unsafe { internal::cast_mut(a) }
|
||||
}
|
||||
|
||||
/// Cast `&T` into `&U`.
|
||||
@ -319,19 +248,8 @@ pub fn cast_mut<A: Pod, B: Pod>(a: &mut A) -> &mut B {
|
||||
///
|
||||
/// This is [`try_cast_ref`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_ref<A: Pod, B: Pod>(a: &A) -> &B {
|
||||
if size_of::<A>() == size_of::<B>() && align_of::<A>() >= align_of::<B>() {
|
||||
// Plz mr compiler, just notice that we can't ever hit Err in this case.
|
||||
match try_cast_ref(a) {
|
||||
Ok(b) => b,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
match try_cast_ref(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_ref", e),
|
||||
}
|
||||
}
|
||||
pub fn cast_ref<A: NoPadding, B: AnyBitPattern>(a: &A) -> &B {
|
||||
unsafe { internal::cast_ref(a) }
|
||||
}
|
||||
|
||||
/// Cast `&[A]` into `&[B]`.
|
||||
@ -340,11 +258,8 @@ pub fn cast_ref<A: Pod, B: Pod>(a: &A) -> &B {
|
||||
///
|
||||
/// This is [`try_cast_slice`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_slice<A: Pod, B: Pod>(a: &[A]) -> &[B] {
|
||||
match try_cast_slice(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_slice", e),
|
||||
}
|
||||
pub fn cast_slice<A: NoPadding, B: AnyBitPattern>(a: &[A]) -> &[B] {
|
||||
unsafe { internal::cast_slice(a) }
|
||||
}
|
||||
|
||||
/// Cast `&mut [T]` into `&mut [U]`.
|
||||
@ -353,22 +268,19 @@ pub fn cast_slice<A: Pod, B: Pod>(a: &[A]) -> &[B] {
|
||||
///
|
||||
/// This is [`try_cast_slice_mut`] but will panic on error.
|
||||
#[inline]
|
||||
pub fn cast_slice_mut<A: Pod, B: Pod>(a: &mut [A]) -> &mut [B] {
|
||||
match try_cast_slice_mut(a) {
|
||||
Ok(b) => b,
|
||||
Err(e) => something_went_wrong("cast_slice_mut", e),
|
||||
}
|
||||
pub fn cast_slice_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(a: &mut [A]) -> &mut [B] {
|
||||
unsafe { internal::cast_slice_mut(a) }
|
||||
}
|
||||
|
||||
/// As `align_to`, but safe because of the [`Pod`] bound.
|
||||
#[inline]
|
||||
pub fn pod_align_to<T: Pod, U: Pod>(vals: &[T]) -> (&[T], &[U], &[T]) {
|
||||
pub fn pod_align_to<T: NoPadding, U: AnyBitPattern>(vals: &[T]) -> (&[T], &[U], &[T]) {
|
||||
unsafe { vals.align_to::<U>() }
|
||||
}
|
||||
|
||||
/// As `align_to_mut`, but safe because of the [`Pod`] bound.
|
||||
#[inline]
|
||||
pub fn pod_align_to_mut<T: Pod, U: Pod>(
|
||||
pub fn pod_align_to_mut<T: NoPadding + AnyBitPattern, U: NoPadding + AnyBitPattern>(
|
||||
vals: &mut [T],
|
||||
) -> (&mut [T], &mut [U], &mut [T]) {
|
||||
unsafe { vals.align_to_mut::<U>() }
|
||||
@ -385,12 +297,8 @@ pub fn pod_align_to_mut<T: Pod, U: Pod>(
|
||||
///
|
||||
/// * If the types don't have the same size this fails.
|
||||
#[inline]
|
||||
pub fn try_cast<A: Pod, B: Pod>(a: A) -> Result<B, PodCastError> {
|
||||
if size_of::<A>() == size_of::<B>() {
|
||||
Ok(unsafe { transmute!(a) })
|
||||
} else {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
}
|
||||
pub fn try_cast<A: NoPadding, B: AnyBitPattern>(a: A) -> Result<B, PodCastError> {
|
||||
unsafe { internal::try_cast(a) }
|
||||
}
|
||||
|
||||
/// Try to convert a `&T` into `&U`.
|
||||
@ -400,36 +308,16 @@ pub fn try_cast<A: Pod, B: Pod>(a: A) -> Result<B, PodCastError> {
|
||||
/// * If the reference isn't aligned in the new type
|
||||
/// * If the source type and target type aren't the same size.
|
||||
#[inline]
|
||||
pub fn try_cast_ref<A: Pod, B: Pod>(a: &A) -> Result<&B, PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a as *const A as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe { &*(a as *const A as *const B) })
|
||||
} else {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
}
|
||||
pub fn try_cast_ref<A: NoPadding, B: AnyBitPattern>(a: &A) -> Result<&B, PodCastError> {
|
||||
unsafe { internal::try_cast_ref(a) }
|
||||
}
|
||||
|
||||
/// Try to convert a `&mut T` into `&mut U`.
|
||||
///
|
||||
/// As [`try_cast_ref`], but `mut`.
|
||||
#[inline]
|
||||
pub fn try_cast_mut<A: Pod, B: Pod>(a: &mut A) -> Result<&mut B, PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a as *mut A as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe { &mut *(a as *mut A as *mut B) })
|
||||
} else {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
}
|
||||
pub fn try_cast_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(a: &mut A) -> Result<&mut B, PodCastError> {
|
||||
unsafe { internal::try_cast_mut(a) }
|
||||
}
|
||||
|
||||
/// Try to convert `&[A]` into `&[B]` (possibly with a change in length).
|
||||
@ -448,23 +336,8 @@ pub fn try_cast_mut<A: Pod, B: Pod>(a: &mut A) -> Result<&mut B, PodCastError> {
|
||||
/// * 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.
|
||||
#[inline]
|
||||
pub fn try_cast_slice<A: Pod, B: Pod>(a: &[A]) -> Result<&[B], PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a.as_ptr() as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, a.len()) })
|
||||
} else if size_of::<A>() == 0 || size_of::<B>() == 0 {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
|
||||
let new_len = core::mem::size_of_val(a) / size_of::<B>();
|
||||
Ok(unsafe { core::slice::from_raw_parts(a.as_ptr() as *const B, new_len) })
|
||||
} else {
|
||||
Err(PodCastError::OutputSliceWouldHaveSlop)
|
||||
}
|
||||
pub fn try_cast_slice<A: NoPadding, B: AnyBitPattern>(a: &[A]) -> Result<&[B], PodCastError> {
|
||||
unsafe { internal::try_cast_slice(a) }
|
||||
}
|
||||
|
||||
/// Try to convert `&mut [A]` into `&mut [B]` (possibly with a change in
|
||||
@ -472,27 +345,8 @@ pub fn try_cast_slice<A: Pod, B: Pod>(a: &[A]) -> Result<&[B], PodCastError> {
|
||||
///
|
||||
/// As [`try_cast_slice`], but `&mut`.
|
||||
#[inline]
|
||||
pub fn try_cast_slice_mut<A: Pod, B: Pod>(
|
||||
pub fn try_cast_slice_mut<A: NoPadding + AnyBitPattern, B: NoPadding + AnyBitPattern>(
|
||||
a: &mut [A],
|
||||
) -> Result<&mut [B], PodCastError> {
|
||||
// Note(Lokathor): everything with `align_of` and `size_of` will optimize away
|
||||
// after monomorphization.
|
||||
if align_of::<B>() > align_of::<A>()
|
||||
&& (a.as_mut_ptr() as usize) % align_of::<B>() != 0
|
||||
{
|
||||
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned)
|
||||
} else if size_of::<B>() == size_of::<A>() {
|
||||
Ok(unsafe {
|
||||
core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, a.len())
|
||||
})
|
||||
} else if size_of::<A>() == 0 || size_of::<B>() == 0 {
|
||||
Err(PodCastError::SizeMismatch)
|
||||
} else if core::mem::size_of_val(a) % size_of::<B>() == 0 {
|
||||
let new_len = core::mem::size_of_val(a) / size_of::<B>();
|
||||
Ok(unsafe {
|
||||
core::slice::from_raw_parts_mut(a.as_mut_ptr() as *mut B, new_len)
|
||||
})
|
||||
} else {
|
||||
Err(PodCastError::OutputSliceWouldHaveSlop)
|
||||
}
|
||||
unsafe { internal::try_cast_slice_mut(a) }
|
||||
}
|
||||
|
52
src/nopadding.rs
Normal file
52
src/nopadding.rs
Normal file
@ -0,0 +1,52 @@
|
||||
use crate::Pod;
|
||||
|
||||
/// Marker trait for "plain old data" types with no padding.
|
||||
///
|
||||
/// 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.
|
||||
/// 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
|
||||
/// 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
|
||||
/// 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
|
||||
/// [`NoPadding`] but any `T: NoPadding` is not necessarily [`Pod`]. If possible,
|
||||
/// prefer implementing [`Pod`] directly. To get more [`Pod`]-like functionality for
|
||||
/// a type that is only [`NoPadding`], consider also implementing [`CheckedBitPattern`][crate::CheckedBitPattern].
|
||||
///
|
||||
/// # Derive
|
||||
///
|
||||
/// A `#[derive(NoPadding)]` macro is provided under the `derive` feature flag which will
|
||||
/// automatically validate the requirements of this trait and implement the
|
||||
/// 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
|
||||
/// implement it manually, you *must* carefully follow the below safety rules.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The same as [`Pod`] except we disregard the rule about it must
|
||||
/// allow any bit pattern (i.e. it does not need to be [`Zeroable`][crate::Zeroable]).
|
||||
/// Still, this is a quite strong guarantee about a type, so *be careful* whem
|
||||
/// implementing it manually.
|
||||
///
|
||||
/// * The type must be inhabited (eg: no
|
||||
/// [Infallible](core::convert::Infallible)).
|
||||
/// * The type must not contain any padding bytes, either in the middle or on
|
||||
/// 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
|
||||
/// the end).
|
||||
/// * Structs need to have all fields also be `NoPadding`.
|
||||
/// * 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
|
||||
/// all other rules end up being followed.
|
||||
/// * Enums need to have an explicit `#[repr(Int)]`
|
||||
/// * Enums must have only fieldless variants
|
||||
/// * There's probably more, don't mess it up (I mean it).
|
||||
pub unsafe trait NoPadding: Sized + Copy + 'static {}
|
||||
|
||||
unsafe impl<T: Pod> NoPadding for T {}
|
||||
|
||||
unsafe impl NoPadding for char {}
|
||||
|
||||
unsafe impl NoPadding for bool {}
|
Loading…
Reference in New Issue
Block a user