#![doc = include_str!("../README.md")]
#![cfg_attr(not(test), no_std)]
mod analysis;
mod deep;
mod discover;
#[cfg(feature = "verdict")]
#[doc(hidden)]
pub mod hook;
pub mod layout;
pub mod num;
mod ptr;
mod relative;
mod std_enums;
#[cfg(test)]
mod tests;
mod validate;
mod visit;
use core::{marker::PhantomData, mem::ManuallyDrop};
use analysis::{
Analysis, Exact, MUTABLE, Marks, POINTER_MUT, TAIL_UNSIZED_SOURCE, TAIL_UNSIZED_TARGET, analyze,
analyze_tail, mutable, mutable_part,
};
use layout::{Dfa, Endian, Field, Layout, Spec};
pub use layout::{crc32, sum16};
pub use puns_derive::Pun;
pub use relative::SelfRelative;
#[doc(hidden)]
pub use relative::sized_probe as __sized_probe;
use validate::{Checks, validate};
pub use visit::{Invalid, Pointee, Visit, validate_elems_in, validate_in};
pub unsafe trait Scalar {
const SPEC: Spec;
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a `Pun` type: `puns` does not know its layout and its valid values",
label = "not a `Pun` type",
note = "a struct, an enum or a union is one with `#[derive(Pun)]`, a self-relative pointer with \
`SelfRelative` and `self_relative!`"
)]
pub unsafe trait Pun {
#[doc(hidden)]
type Elem: Pun;
#[doc(hidden)]
type Fields: Fields;
#[doc(hidden)]
type Variants: Variants;
#[doc(hidden)]
type Rules: Rules;
#[doc(hidden)]
type Pointee: Pun;
#[doc(hidden)]
const PROBE: *const Self;
#[doc(hidden)]
const LAYOUT: Layout;
#[doc(hidden)]
const OPTION: Option<Layout> = None;
}
pub trait Tag<K: ?Sized>: Pun {
type Tag: Pun + Copy;
}
impl<K: Pun + Copy> Tag<K> for [u8] {
type Tag = K;
}
#[doc(hidden)]
pub unsafe trait Fields {
type Type: ?Sized + Pun;
type Next: Fields;
type Last: Fields;
type Path<P: Path>: Path;
const FIELD: Option<Field>;
}
#[doc(hidden)]
pub unsafe trait Variants {
type Fields: Fields;
type Next: Variants;
const TAG: Option<u128>;
const RANGES: Option<&'static [(u128, u128)]> = None;
}
unsafe impl Variants for () {
type Fields = ();
type Next = ();
const TAG: Option<u128> = None;
}
#[doc(hidden)]
pub trait Rules: sealed::Sealed {
const RULE: usize;
type Expr: Steps;
type Next: Rules;
}
impl Rules for () {
const RULE: usize = usize::MAX;
type Expr = ();
type Next = ();
}
#[doc(hidden)]
pub struct RuleAt<const R: usize, E, N>(PhantomData<(E, N)>);
impl<const R: usize, E: Steps, N: Rules> Rules for RuleAt<R, E, N> {
const RULE: usize = R;
type Expr = E;
type Next = N;
}
#[doc(hidden)]
pub trait Steps: sealed::Sealed {
const KIND: u8;
const AT: usize;
const FIRST: usize;
const END: usize;
type A: Steps;
type B: Steps;
type Cond: Steps;
type Then: Steps;
type InCond<X: steps::Ops>: steps::Ops;
type InThen<X: steps::Ops>: steps::Ops;
}
#[doc(hidden)]
pub mod steps {
use core::marker::PhantomData;
use super::{Pun, Rules, Steps, sealed::Sealed};
use crate::layout::Op;
pub const NONE: u8 = 0;
pub const ONE: u8 = 1;
pub const TWO: u8 = 2;
pub const WALK: u8 = 3;
pub struct One<const I: usize>;
pub struct Two<A, B>(PhantomData<(A, B)>);
pub struct Walk<const I: usize, C, N>(PhantomData<(C, N)>);
impl Sealed for () {}
impl<const I: usize> Sealed for One<I> {}
impl<A: Steps, B: Steps> Sealed for Two<A, B> {}
impl<const I: usize, C: Steps, N: Steps> Sealed for Walk<I, C, N> {}
impl<const R: usize, E: Steps, N: Rules> Sealed for super::RuleAt<R, E, N> {}
impl Steps for () {
const KIND: u8 = NONE;
const AT: usize = 0;
const FIRST: usize = 0;
const END: usize = 0;
type A = ();
type B = ();
type Cond = ();
type Then = ();
type InCond<X: Ops> = X;
type InThen<X: Ops> = X;
}
impl<const I: usize> Steps for One<I> {
const KIND: u8 = ONE;
const AT: usize = I;
const FIRST: usize = I;
const END: usize = I + 1;
type A = ();
type B = ();
type Cond = ();
type Then = ();
type InCond<X: Ops> = X;
type InThen<X: Ops> = X;
}
impl<A: Steps, B: Steps> Steps for Two<A, B> {
const KIND: u8 = TWO;
const AT: usize = 0;
const FIRST: usize =
if A::END == B::FIRST && A::KIND != NONE && B::KIND != NONE { A::FIRST } else { usize::MAX };
const END: usize = B::END;
type A = A;
type B = B;
type Cond = ();
type Then = ();
type InCond<X: Ops> = X;
type InThen<X: Ops> = X;
}
impl<const I: usize, C: Steps, N: Steps> Steps for Walk<I, C, N> {
const KIND: u8 = WALK;
const AT: usize = I;
const FIRST: usize = I;
const END: usize = I + 1;
type A = ();
type B = ();
type Cond = C;
type Then = N;
type InCond<X: Ops> = InWalk<X, Self, false>;
type InThen<X: Ops> = InWalk<X, Self, true>;
}
pub trait Ops: Sealed {
const OPS: &'static [Op];
}
pub struct InRule<T: ?Sized, R>(PhantomData<R>, PhantomData<T>);
pub struct InWalk<X, W, const NEXT: bool>(PhantomData<(X, W)>);
impl<T: ?Sized + Pun, R: Rules> Sealed for InRule<T, R> {}
impl<X: Ops, W: Steps, const NEXT: bool> Sealed for InWalk<X, W, NEXT> {}
impl<T: ?Sized + Pun, R: Rules> Ops for InRule<T, R> {
const OPS: &'static [Op] = T::LAYOUT.rule_ops(R::RULE);
}
impl<X: Ops, W: Steps, const NEXT: bool> Ops for InWalk<X, W, NEXT> {
const OPS: &'static [Op] = match crate::layout::op_at(X::OPS, W::AT) {
Some(Op::Walk { cond, next, .. }) => {
if NEXT {
next
} else {
cond
}
}
_ => &[],
};
}
}
mod sealed {
pub trait Sealed {}
}
impl sealed::Sealed for Root {}
impl<P: Path, F: ?Sized + Fields> sealed::Sealed for At<P, F> {}
#[doc(hidden)]
pub trait Path: sealed::Sealed {
const LEAF: usize;
}
#[doc(hidden)]
pub struct Root;
#[doc(hidden)]
pub struct At<P, F: ?Sized>(PhantomData<P>, PhantomData<F>);
impl Path for Root {
const LEAF: usize = 0;
}
impl<P: Path, F: ?Sized + Fields> Path for At<P, F> {
const LEAF: usize = P::LEAF
+ match F::FIELD {
Some(field) => field.leaf(),
None => 0,
};
}
unsafe impl Fields for () {
type Type = ();
type Next = ();
type Last = ();
type Path<P: Path> = P;
const FIELD: Option<Field> = None;
}
unsafe impl<T: Scalar> Pun for T {
type Elem = ();
type Fields = ();
type Variants = ();
type Rules = ();
type Pointee = ();
const PROBE: *const Self = core::ptr::null();
const LAYOUT: Layout = Layout::scalar::<T>(T::SPEC);
}
unsafe impl<T: Pun, const N: usize> Pun for [T; N] {
type Elem = T;
type Fields = ();
type Variants = ();
type Rules = ();
type Pointee = ();
const PROBE: *const Self = core::ptr::null();
const LAYOUT: Layout = Layout::array(&T::LAYOUT, N);
}
unsafe impl<T: Pun> Pun for [T] {
type Elem = T;
type Fields = ();
type Variants = ();
type Rules = ();
type Pointee = ();
const PROBE: *const Self = core::ptr::slice_from_raw_parts(core::ptr::null(), ptr::PROBE_LEN);
const LAYOUT: Layout = unsafe { Layout::slice::<T>(Self::PROBE, &T::LAYOUT) };
}
unsafe impl Pun for str {
type Elem = ();
type Fields = ();
type Variants = ();
type Rules = ();
type Pointee = ();
const PROBE: *const Self = <[u8] as Pun>::PROBE as *const str;
const LAYOUT: Layout = unsafe { Layout::pattern::<str>(Self::PROBE, Dfa::UTF8) };
}
unsafe impl<T: ?Sized + Pun> Pun for ManuallyDrop<T> {
type Elem = T::Elem;
type Fields = T::Fields;
type Variants = T::Variants;
type Rules = T::Rules;
type Pointee = T::Pointee;
const PROBE: *const Self = T::PROBE as *const Self;
const LAYOUT: Layout = T::LAYOUT;
}
unsafe impl<T> Pun for core::mem::MaybeUninit<T> {
type Elem = ();
type Fields = ();
type Variants = ();
type Rules = ();
type Pointee = ();
const PROBE: *const Self = core::ptr::null();
const LAYOUT: Layout = Layout::padding::<Self>();
}
unsafe impl Pun for core::convert::Infallible {
type Elem = ();
type Fields = ();
type Variants = ();
type Rules = ();
type Pointee = ();
const PROBE: *const Self = core::ptr::null();
const LAYOUT: Layout = Layout::uninhabited::<Self>();
}
#[doc(hidden)]
pub struct TupleField<T, const I: usize>(PhantomData<T>);
macro_rules! tuple_field {
([$($all:ident)+] $index:tt $ty:ident $next:ty) => {
unsafe impl<$($all: Pun),+> Fields for TupleField<($($all,)+), $index> {
type Type = $ty;
type Next = $next;
type Last = ();
type Path<P: Path> = At<P, Self>;
const FIELD: Option<Field> = Some(*<($($all,)+) as Pun>::LAYOUT.field($index));
}
};
}
macro_rules! tuple {
([$($all:ident)+] $($index:tt)+) => {
unsafe impl<$($all: Pun),+> Pun for ($($all,)+) {
type Elem = ();
type Fields = TupleField<Self, 0>;
type Variants = ();
type Rules = ();
type Pointee = ();
const PROBE: *const Self = core::ptr::null();
const LAYOUT: Layout = unsafe {
Layout::structure::<Self>(
Self::PROBE,
const {
&Layout::sort_fields([
$(Field::new(core::mem::offset_of!(Self, $index), &$all::LAYOUT)),+
])
},
&[],
)
};
}
};
}
tuple!([A] 0);
tuple_field!([A] 0 A ());
tuple!([A B] 0 1);
tuple_field!([A B] 0 A TupleField<(A, B), 1>);
tuple_field!([A B] 1 B ());
tuple!([A B C] 0 1 2);
tuple_field!([A B C] 0 A TupleField<(A, B, C), 1>);
tuple_field!([A B C] 1 B TupleField<(A, B, C), 2>);
tuple_field!([A B C] 2 C ());
tuple!([A B C D] 0 1 2 3);
tuple_field!([A B C D] 0 A TupleField<(A, B, C, D), 1>);
tuple_field!([A B C D] 1 B TupleField<(A, B, C, D), 2>);
tuple_field!([A B C D] 2 C TupleField<(A, B, C, D), 3>);
tuple_field!([A B C D] 3 D ());
macro_rules! impl_any {
($($ty:ty)+) => {$(
unsafe impl Scalar for $ty {
const SPEC: Spec = Spec::any::<$ty>();
}
)+};
}
impl_any!(() u8 u16 u32 u64 u128 usize);
macro_rules! impl_bits {
($($ty:ty)+) => {$(
unsafe impl Scalar for $ty {
const SPEC: Spec = Spec::any::<$ty>().not_a_number();
}
)+};
}
impl_bits!(i8 i16 i32 i64 i128 isize f32 f64);
unsafe impl<T: ?Sized> Scalar for PhantomData<T> {
const SPEC: Spec = Spec::any::<Self>();
}
unsafe impl Scalar for bool {
const SPEC: Spec = Spec::ranges::<bool>(Endian::NATIVE, &[(0, 1)]).not_a_number();
}
unsafe impl Scalar for char {
const SPEC: Spec =
Spec::ranges::<char>(Endian::NATIVE, &[(0, 0xD7FF), (0xE000, 0x10_FFFF)]).not_a_number();
}
macro_rules! impl_non_zero {
($($ty:ident)+) => {$(
unsafe impl Scalar for core::num::NonZero<$ty> {
const SPEC: Spec = Spec::ranges::<$ty>(Endian::NATIVE, &[(1, $ty::MAX as u128)]);
}
)+};
}
impl_non_zero!(u8 u16 u32 u64 u128 usize);
macro_rules! impl_signed_non_zero {
($($ty:ident)+) => {$(
unsafe impl Scalar for core::num::NonZero<$ty> {
const SPEC: Spec = Spec::ranges::<$ty>(
Endian::NATIVE,
&[(1, u128::MAX >> (128 - 8 * size_of::<$ty>()))],
)
.not_a_number();
}
)+};
}
impl_signed_non_zero!(i8 i16 i32 i64 i128 isize);
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Error {
Alignment,
Size,
Validity,
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(match self {
Error::Alignment => "value is not aligned for the target type",
Error::Size => "value has not the size of the target type",
Error::Validity => "value is not valid for the target type",
})
}
}
impl core::error::Error for Error {}
struct Plan<S: ?Sized, D: ?Sized>(PhantomData<S>, PhantomData<D>);
#[derive(Copy, Clone)]
#[expect(clippy::struct_excessive_bools, reason = "each is a question of its own, asked alone")]
struct Need {
part: bool,
fallible: bool,
reference: bool,
pointers: bool,
}
impl Need {
const VALUE: Need = Need { part: false, fallible: false, reference: false, pointers: false };
const REF: Need = Need { reference: true, ..Need::VALUE };
const PART: Need = Need { part: true, ..Need::VALUE };
const PART_REF: Need = Need { part: true, ..Need::REF };
const TRY: Need = Need { fallible: true, ..Need::VALUE };
const TRY_REF: Need = Need { fallible: true, ..Need::REF };
const VIEW: Need = Need { pointers: true, ..Need::REF };
const TRY_VIEW: Need = Need { pointers: true, ..Need::TRY_REF };
}
const POINTER_TARGET: &str = "the target holds a self-relative pointer, and what a pointer aims \
at is not a property of its bytes.\nUse `view_ref` to read a value \
that holds pointers as another type (it proves what they aim at)";
const fn check(analysis: &Analysis, need: Need) -> Option<Message> {
let Analysis { fit, relation, aligned, shift } = *analysis;
match fit.exact {
_ if need.part && fit.shrink => {}
_ if need.part => {
return Some(Message::new(
"the source can be smaller than the target (if it has a slice, it may be empty)",
));
}
Exact::Always => {}
Exact::Sometimes if need.fallible => {}
Exact::Sometimes => {
return Some(Message::new(
"the size of the source may not be a size of the target, depending on the length of \
its slice.\nUse `try_pun_ref` or `try_pun_mut` to check it at run time",
));
}
Exact::Never(why) if fit.shrink => {
return Some(Message::new(why).str(
".\nUse `head` or `tail` (or their `_ref` and `_mut` forms) to take a part of the source",
));
}
Exact::Never(why) => return Some(Message::new(why)),
}
if let Some(offset) = relation.pointer {
return Some(
Message::new(
"a pointer of the target is not, in the source, a pointer whose target it can read (the \
same scheme and offset, the same kind of target, not larger nor more aligned): only a \
pointer proves a pointer, and no check makes up for it",
)
.at(offset.saturating_sub(shift)),
);
}
if let Some(offset) = relation.uninit {
return Some(
Message::new("a byte that the target requires to be initialized is padding in the source")
.at(offset.saturating_sub(shift)),
);
}
if let Some(offset) = relation.disjoint {
return Some(
Message::new("no value of the source is valid for the target")
.at(offset.saturating_sub(shift)),
);
}
if let (Some(offset), false) = (relation.partial, need.fallible) {
return Some(
Message::new(if need.pointers {
"some values of the source are not valid for the target, or do not prove one of its \
rules.\nUse `try_view_ref` to check them at run time"
} else {
"some values of the source are not valid for the target, or do not prove one of its \
rules.\nUse a `try_*` function to check them at run time"
})
.at(offset.saturating_sub(shift)),
);
}
if need.reference && !aligned && !need.fallible {
return Some(Message::new(
"the target has a greater alignment than the source.\nUse `try_pun_ref` or \
`try_pun_mut` to check the address at run time",
));
}
None
}
impl<S: ?Sized + Pun, D: ?Sized + Pun> Plan<S, D> {
const ANALYSIS: Analysis = analyze(&S::LAYOUT, &D::LAYOUT);
const TAIL_ANALYSIS: Analysis = analyze_tail(&S::LAYOUT, &D::LAYOUT);
const MUTABLE: bool = mutable(&S::LAYOUT, &D::LAYOUT, &Self::ANALYSIS.fit);
const fn require(message: Option<Message>) {
if let Some(message) = message {
message.panic();
}
}
const fn check(need: Need) -> Option<Message> {
if let Some(message) = Self::gate(need) {
return Some(message);
}
check(&Self::ANALYSIS, need)
}
const fn gate(need: Need) -> Option<Message> {
if !need.pointers && D::LAYOUT.has_pointers() {
return Some(Message::new(POINTER_TARGET));
}
None
}
const NOT_MUTABLE: &'static str =
if S::LAYOUT.has_pointers() || D::LAYOUT.has_pointers() { POINTER_MUT } else { MUTABLE };
const fn check_tail(need: Need) -> Option<Message> {
if let Some(message) = Self::gate(need) {
return Some(message);
}
if S::LAYOUT.is_unsized() {
return Some(Message::new(TAIL_UNSIZED_SOURCE));
}
if D::LAYOUT.is_unsized() {
return Some(Message::new(TAIL_UNSIZED_TARGET));
}
match check(&Self::TAIL_ANALYSIS, Need { reference: false, ..need }) {
None if need.reference && !Self::TAIL_ANALYSIS.aligned => Some(Message::new(
"the target has a greater alignment than the source.\nUse `tail` to copy it, or \
`from_tail` to take it from bytes, whose address is checked at run time",
)),
verdict => verdict,
}
}
const BY_VALUE: () = Self::require(Self::check(Need::VALUE));
const BY_REF: () = Self::require(Self::check(Need::REF));
const BY_MUT: () = {
let () = Self::BY_REF;
if !Self::MUTABLE {
Message::new(Self::NOT_MUTABLE).panic();
}
};
const HEAD: () = Self::require(Self::check(Need::PART));
const HEAD_REF: () = Self::require(Self::check(Need::PART_REF));
const TAIL: () = Self::require(Self::check_tail(Need::PART));
const TAIL_REF: () = Self::require(Self::check_tail(Need::PART_REF));
const HEAD_MUT: () = Self::require(Self::check_head_mut());
const TAIL_MUT: () = Self::require(Self::check_tail_mut());
const TRY: () = Self::require(Self::check(Need::TRY));
const TRY_REF: () = Self::require(Self::check(Need::TRY_REF));
const FROM_TAIL: () = Self::require(Self::check_from_tail());
const FROM_TAIL_MUT: () = {
let () = Self::FROM_TAIL;
if !Self::MUTABLE {
Message::new(Self::NOT_MUTABLE).panic();
}
};
const fn check_from_tail() -> Option<Message> {
if D::LAYOUT.is_unsized() {
return Some(Message::new(
"the target is unsized: where it starts cannot be found from the end of the bytes.\nUse \
`from_head` or `from_bytes`",
));
}
Self::check(Need::TRY_REF)
}
const fn check_head_mut() -> Option<Message> {
if let Some(message) = Self::check(Need::PART_REF) {
return Some(message);
}
match mutable_part(&S::LAYOUT, &D::LAYOUT, &Self::ANALYSIS.fit, 0) {
Some(why) => Some(Message::new(why)),
None => None,
}
}
const fn check_tail_mut() -> Option<Message> {
if let Some(message) = Self::check_tail(Need::PART_REF) {
return Some(message);
}
let Analysis { fit, shift, .. } = Self::TAIL_ANALYSIS;
match mutable_part(&S::LAYOUT, &D::LAYOUT, &fit, shift) {
Some(why) => Some(Message::new(why)),
None => None,
}
}
const VIEW: () = Self::require(Self::check(Need::VIEW));
const TRY_VIEW: () = Self::require(Self::check(Need::TRY_VIEW));
const TRY_MUT: () = {
let () = Self::TRY_REF;
if !Self::MUTABLE {
Message::new(Self::NOT_MUTABLE).panic();
}
};
#[inline(always)]
const fn cast(source: *const S) -> *const D {
let (head, stride, exact) = const {
let (source, target) = (S::LAYOUT, D::LAYOUT);
match (target.stride(), Self::ANALYSIS.fit.exact) {
(0, _) => (0, 0, true),
(by, Exact::Always) => ((source.head() - target.head()) / by, source.stride() / by, true),
_ => (0, 0, false),
}
};
let len = if exact {
head + ptr::metadata(source) * stride
} else {
let (layout, target) = const { (S::LAYOUT, D::LAYOUT) };
let extent = layout.head() + ptr::metadata(source) * layout.stride();
(extent - target.head()) / target.stride()
};
ptr::from_raw_parts::<D>(source.cast(), len)
}
#[inline(always)]
const fn tail_cast(source: *const S) -> *const D {
let shift = const { Self::TAIL_ANALYSIS.shift };
ptr::from_raw_parts::<D>(unsafe { source.cast::<u8>().add(shift) }, 0)
}
#[inline(always)]
const fn try_cast(source: *const S) -> Result<*const D, Error> {
let (layout, target) = const { (S::LAYOUT, D::LAYOUT) };
let addr = source.cast::<u8>();
if const { !Self::ANALYSIS.aligned } && !ptr::is_aligned(addr, target.align()) {
return Err(Error::Alignment);
}
let extent = layout.head() + ptr::metadata(source) * layout.stride();
if extent < target.head() {
return Err(Error::Size);
}
let rest = extent - target.head();
let len = match target.stride() {
0 if rest == 0 => 0,
stride if stride != 0 && rest.is_multiple_of(stride) => rest / stride,
_ => return Err(Error::Size),
};
if const { D::LAYOUT.is_unsized() && D::LAYOUT.align() > S::LAYOUT.align() } {
match (target.size_of_val(len), layout.size_of_val(ptr::metadata(source))) {
(Some(needed), Some(available)) if needed <= available => {}
_ => return Err(Error::Size),
}
}
let target = ptr::from_raw_parts::<D>(addr, len);
if !unsafe { validate::<Self, Root, D>(target) } {
return Err(Error::Validity);
}
Ok(target)
}
}
impl<S: ?Sized + Pun, D: ?Sized + Pun> Checks for Plan<S, D> {
const MARKS: Marks = Self::ANALYSIS.relation.marks;
}
struct Message {
bytes: [u8; 512],
len: usize,
}
impl Message {
const fn new(what: &str) -> Self {
Self { bytes: [0; 512], len: 0 }.str("\ncannot pun: ").str(what)
}
const fn str(mut self, str: &str) -> Self {
let (bytes, mut i) = (str.as_bytes(), 0);
while i < bytes.len() && self.len < self.bytes.len() {
self.bytes[self.len] = bytes[i];
(self.len, i) = (self.len + 1, i + 1);
}
self
}
const fn at(self, offset: usize) -> Self {
let (mut digits, mut len, mut value) = ([0; 20], 0, offset);
loop {
len += 1;
digits[20 - len] = b'0' + (value % 10) as u8;
value /= 10;
if value == 0 {
break;
}
}
let digits = unsafe { core::str::from_utf8_unchecked(digits.split_at(20 - len).1) };
self.str(".\nThis is at byte ").str(digits).str(" of the target")
}
const fn panic(self) -> ! {
let this = self.str(".\n");
panic!("{}", unsafe { core::str::from_utf8_unchecked(this.bytes.split_at(this.len).0) })
}
}
#[inline(always)]
pub const fn pun<S: Pun + Copy, D: Pun + Copy>(value: S) -> D {
const { Plan::<S, D>::BY_VALUE };
unsafe { pun_unchecked(value) }
}
#[inline(always)]
pub const fn head<S: Pun + Copy, D: Pun + Copy>(value: S) -> D {
const { Plan::<S, D>::HEAD };
unsafe { pun_unchecked(value) }
}
#[inline(always)]
pub const fn tail<S: Pun + Copy, D: Pun + Copy>(value: S) -> D {
const { Plan::<S, D>::TAIL };
let shift = const { Plan::<S, D>::TAIL_ANALYSIS.shift };
unsafe { (&raw const value).cast::<u8>().add(shift).cast::<D>().read_unaligned() }
}
#[inline]
pub const fn try_pun<S: Pun + Copy, D: Pun + Copy>(value: S) -> Result<D, Error> {
const { Plan::<S, D>::TRY };
if !unsafe { validate::<Plan<S, D>, Root, D>((&raw const value).cast()) } {
return Err(Error::Validity);
}
Ok(unsafe { pun_unchecked(value) })
}
#[inline(always)]
const unsafe fn pun_unchecked<S: Copy, D: Copy>(value: S) -> D {
union Overlay<S: Copy, D: Copy> {
source: S,
target: D,
}
unsafe { Overlay { source: value }.target }
}
#[inline(always)]
pub const fn pun_ref<S: ?Sized + Pun, D: ?Sized + Pun>(value: &S) -> &D {
const { Plan::<S, D>::BY_REF };
unsafe { &*Plan::<S, D>::cast(value) }
}
#[inline(always)]
pub const fn pun_mut<S: ?Sized + Pun, D: ?Sized + Pun>(value: &mut S) -> &mut D {
const { Plan::<S, D>::BY_MUT };
let source: *mut S = value;
unsafe { &mut *Plan::<S, D>::cast(source).cast_mut() }
}
#[inline(always)]
pub fn view_ref<S: ?Sized + Pun, D: ?Sized + Pun>(value: &S) -> &D {
const { Plan::<S, D>::VIEW };
deep::proof::<S, D>();
unsafe { &*Plan::<S, D>::cast(value) }
}
#[inline]
pub fn try_view_ref<S: ?Sized + Pun, D: ?Sized + Pun>(value: &S) -> Result<&D, Error> {
const { Plan::<S, D>::TRY_VIEW };
deep::proof::<S, D>();
match Plan::<S, D>::try_cast(value) {
Ok(target) => Ok(unsafe { &*target }),
Err(error) => Err(error),
}
}
#[inline(always)]
pub const fn head_ref<S: ?Sized + Pun, D: ?Sized + Pun>(value: &S) -> &D {
const { Plan::<S, D>::HEAD_REF };
unsafe { &*Plan::<S, D>::cast(value) }
}
#[inline(always)]
pub const fn tail_ref<S: ?Sized + Pun, D: ?Sized + Pun>(value: &S) -> &D {
const { Plan::<S, D>::TAIL_REF };
unsafe { &*Plan::<S, D>::tail_cast(value) }
}
#[inline(always)]
pub const fn head_mut<S: ?Sized + Pun, D: ?Sized + Pun>(value: &mut S) -> &mut D {
const { Plan::<S, D>::HEAD_MUT };
let source: *mut S = value;
unsafe { &mut *Plan::<S, D>::cast(source).cast_mut() }
}
#[inline(always)]
pub const fn tail_mut<S: ?Sized + Pun, D: ?Sized + Pun>(value: &mut S) -> &mut D {
const { Plan::<S, D>::TAIL_MUT };
let source: *mut S = value;
unsafe { &mut *Plan::<S, D>::tail_cast(source).cast_mut() }
}
#[inline]
pub const fn try_pun_ref<S: ?Sized + Pun, D: ?Sized + Pun>(value: &S) -> Result<&D, Error> {
const { Plan::<S, D>::TRY_REF };
match Plan::<S, D>::try_cast(value) {
Ok(target) => Ok(unsafe { &*target }),
Err(error) => Err(error),
}
}
#[inline]
pub const fn try_pun_mut<S: ?Sized + Pun, D: ?Sized + Pun>(value: &mut S) -> Result<&mut D, Error> {
const { Plan::<S, D>::TRY_MUT };
let source: *mut S = value;
match Plan::<S, D>::try_cast(source) {
Ok(target) => Ok(unsafe { &mut *target.cast_mut() }),
Err(error) => Err(error),
}
}
#[inline(always)]
#[must_use]
pub const fn zeroed<T: Pun + Copy>() -> T {
const {
assert!(T::LAYOUT.zeroable(), "zero is not a valid value of this type");
assert!(!T::LAYOUT.has_pointers(), "this type holds a self-relative pointer");
};
unsafe { core::mem::zeroed() }
}
#[doc(hidden)]
#[inline(always)]
pub const fn int<T: Pun>(value: &T) -> u128 {
let spec = const {
match T::LAYOUT.as_integer() {
Some(spec) => spec,
None => panic!(
"a getter reads the unsigned integer fields of its struct as `u128`s, and this field is \
not one (a signed or floating-point number, a `bool`, a `char` or an enum is not)"
),
}
};
unsafe { spec.load(core::ptr::from_ref::<T>(value).cast()) }
}
#[inline(always)]
pub const fn as_bytes<S: ?Sized + Pun>(value: &S) -> &[u8] {
pun_ref(value)
}
#[inline]
pub const fn from_bytes<D: ?Sized + Pun>(bytes: &[u8]) -> Result<&D, Error> {
try_pun_ref::<[u8], D>(bytes)
}
#[inline]
pub const fn from_bytes_mut<D: ?Sized + Pun>(bytes: &mut [u8]) -> Result<&mut D, Error> {
try_pun_mut::<[u8], D>(bytes)
}
impl<D: ?Sized + Pun> Plan<[u8], D> {
#[inline(always)]
const unsafe fn front(addr: *const u8, n: usize) -> Result<(*const D, usize), Error> {
let (layout, rule) = const { (D::LAYOUT, D::LAYOUT.length_rule()) };
let (head, stride) = (layout.head(), layout.stride());
if n < head {
return Err(Error::Size);
}
if const { D::LAYOUT.align() > 1 } && !ptr::is_aligned(addr, layout.align()) {
return Err(Error::Alignment);
}
let len = match rule {
_ if stride == 0 => 0,
None => match n & !(layout.align() - 1) {
room if room >= head => (room - head) / stride,
_ => return Err(Error::Size),
},
Some(rule) => {
let Some(value) = (unsafe { validate::length::<D>(addr, n) }) else {
return Err(Error::Validity);
};
let before = head - rule.base;
if value > usize::MAX as u128 {
let whole = rule.elements || (value - before as u128).is_multiple_of(stride as u128);
return Err(if whole { Error::Size } else { Error::Validity });
}
let value = value as usize;
let len = match () {
() if rule.elements => value,
() if value >= before && (value - before).is_multiple_of(stride) => {
(value - before) / stride
}
() => return Err(Error::Validity),
};
if len > (n - head) / stride {
return Err(Error::Size);
}
len
}
};
let size = match layout.size_of_val(len) {
Some(size) if size <= n => size,
_ => return Err(Error::Size),
};
let target = ptr::from_raw_parts::<D>(addr, len);
if !unsafe { validate::<Self, Root, D>(target) } {
return Err(Error::Validity);
}
Ok((target, size))
}
#[inline(always)]
const unsafe fn back(addr: *const u8, n: usize) -> Result<(usize, *const D), Error> {
let layout = const { D::LAYOUT };
let Some(start) = n.checked_sub(layout.size()) else { return Err(Error::Size) };
let addr = unsafe { addr.add(start) };
if const { D::LAYOUT.align() > 1 } && !ptr::is_aligned(addr, layout.align()) {
return Err(Error::Alignment);
}
let target = ptr::from_raw_parts::<D>(addr, 0);
if !unsafe { validate::<Self, Root, D>(target) } {
return Err(Error::Validity);
}
Ok((start, target))
}
}
#[inline]
pub const fn from_head<D: ?Sized + Pun>(bytes: &[u8]) -> Result<(&D, &[u8]), Error> {
const { Plan::<[u8], D>::TRY_REF };
match unsafe { Plan::<[u8], D>::front(bytes.as_ptr(), bytes.len()) } {
Ok((target, size)) => Ok((unsafe { &*target }, bytes.split_at(size).1)),
Err(error) => Err(error),
}
}
#[doc(hidden)]
#[inline(always)]
#[must_use]
pub const fn rejects<D: ?Sized + Pun>(bytes: &[u8]) -> bool {
let Some((offset, spec)) = (const { D::LAYOUT.key() }) else { return false };
if bytes.len() < offset + spec.size {
return true;
}
!unsafe { spec.matches(bytes.as_ptr().add(offset)) }
}
#[inline]
pub const fn from_tail<D: ?Sized + Pun>(bytes: &[u8]) -> Result<(&[u8], &D), Error> {
const { Plan::<[u8], D>::FROM_TAIL };
match unsafe { Plan::<[u8], D>::back(bytes.as_ptr(), bytes.len()) } {
Ok((start, target)) => Ok((bytes.split_at(start).0, unsafe { &*target })),
Err(error) => Err(error),
}
}
#[inline]
pub const fn from_head_mut<D: ?Sized + Pun>(
bytes: &mut [u8],
) -> Result<(&mut D, &mut [u8]), Error> {
const { Plan::<[u8], D>::TRY_MUT };
match unsafe { Plan::<[u8], D>::front(bytes.as_mut_ptr().cast_const(), bytes.len()) } {
Ok((target, size)) => {
let len = ptr::metadata(target);
let (front, rest) = bytes.split_at_mut(size);
let target = ptr::from_raw_parts::<D>(front.as_mut_ptr().cast_const(), len).cast_mut();
Ok((unsafe { &mut *target }, rest))
}
Err(error) => Err(error),
}
}
#[inline]
pub const fn from_tail_mut<D: ?Sized + Pun>(
bytes: &mut [u8],
) -> Result<(&mut [u8], &mut D), Error> {
const { Plan::<[u8], D>::FROM_TAIL_MUT };
match unsafe { Plan::<[u8], D>::back(bytes.as_mut_ptr().cast_const(), bytes.len()) } {
Ok((start, _)) => {
let (rest, back) = bytes.split_at_mut(start);
let target = ptr::from_raw_parts::<D>(back.as_mut_ptr().cast_const(), 0).cast_mut();
Ok((rest, unsafe { &mut *target }))
}
Err(error) => Err(error),
}
}
#[doc(hidden)]
#[inline(always)]
pub const fn region<S: ?Sized + Pun>(value: &S, index: usize) -> &[u8] {
const { Plan::<S, [u8]>::BY_REF };
let head = const { S::LAYOUT.tail_shape().start };
let (_, tail, size) = validate::tail_of::<S>(value);
unsafe {
validate::region_at::<S, S::Rules>(
core::ptr::from_ref::<S>(value).cast::<u8>(),
size,
(head, tail),
index,
(0, 0),
)
}
}