use core::{
convert::Infallible,
fmt::{self, Debug, Write},
ops::Deref,
};
#[cfg(zerocopy_core_error)]
use core::error::Error;
#[cfg(all(not(zerocopy_core_error), any(feature = "std", test)))]
use std::error::Error;
use crate::{util::SendSyncPhantomData, KnownLayout, TryFromBytes, Unaligned};
#[cfg(doc)]
use crate::{FromBytes, Ref};
#[derive(PartialEq, Eq)]
pub enum ConvertError<A, S, V> {
Alignment(A),
Size(S),
Validity(V),
}
impl<Src, Dst: ?Sized + Unaligned, S, V> From<ConvertError<AlignmentError<Src, Dst>, S, V>>
for ConvertError<Infallible, S, V>
{
#[inline]
fn from(err: ConvertError<AlignmentError<Src, Dst>, S, V>) -> ConvertError<Infallible, S, V> {
match err {
ConvertError::Alignment(e) => ConvertError::Alignment(Infallible::from(e)),
ConvertError::Size(e) => ConvertError::Size(e),
ConvertError::Validity(e) => ConvertError::Validity(e),
}
}
}
impl<A: fmt::Debug, S: fmt::Debug, V: fmt::Debug> fmt::Debug for ConvertError<A, S, V> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Alignment(e) => f.debug_tuple("Alignment").field(e).finish(),
Self::Size(e) => f.debug_tuple("Size").field(e).finish(),
Self::Validity(e) => f.debug_tuple("Validity").field(e).finish(),
}
}
}
impl<A: fmt::Display, S: fmt::Display, V: fmt::Display> fmt::Display for ConvertError<A, S, V> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Alignment(e) => e.fmt(f),
Self::Size(e) => e.fmt(f),
Self::Validity(e) => e.fmt(f),
}
}
}
#[cfg(any(zerocopy_core_error, feature = "std", test))]
impl<A, S, V> Error for ConvertError<A, S, V>
where
A: fmt::Display + fmt::Debug,
S: fmt::Display + fmt::Debug,
V: fmt::Display + fmt::Debug,
{
}
#[derive(PartialEq, Eq)]
pub struct AlignmentError<Src, Dst: ?Sized> {
src: Src,
dst: SendSyncPhantomData<Dst>,
}
impl<Src, Dst: ?Sized> AlignmentError<Src, Dst> {
pub(crate) unsafe fn new_unchecked(src: Src) -> Self {
Self { src, dst: SendSyncPhantomData::default() }
}
#[inline]
pub fn into_src(self) -> Src {
self.src
}
pub(crate) fn with_src<NewSrc>(self, new_src: NewSrc) -> AlignmentError<NewSrc, Dst> {
AlignmentError { src: new_src, dst: SendSyncPhantomData::default() }
}
#[inline]
pub fn map_src<NewSrc>(self, f: impl Fn(Src) -> NewSrc) -> AlignmentError<NewSrc, Dst> {
AlignmentError { src: f(self.src), dst: SendSyncPhantomData::default() }
}
pub(crate) fn into<S, V>(self) -> ConvertError<Self, S, V> {
ConvertError::Alignment(self)
}
fn display_verbose_extras(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
where
Src: Deref,
Dst: KnownLayout,
{
#[allow(clippy::as_conversions)]
let addr = self.src.deref() as *const _ as *const ();
let addr_align = 2usize.pow((crate::util::AsAddress::addr(addr)).trailing_zeros());
f.write_str("\n\nSource type: ")?;
f.write_str(core::any::type_name::<Src>())?;
f.write_str("\nSource address: ")?;
addr.fmt(f)?;
f.write_str(" (a multiple of ")?;
addr_align.fmt(f)?;
f.write_str(")")?;
f.write_str("\nDestination type: ")?;
f.write_str(core::any::type_name::<Dst>())?;
f.write_str("\nDestination alignment: ")?;
<Dst as KnownLayout>::LAYOUT.align.get().fmt(f)?;
Ok(())
}
}
impl<Src, Dst: ?Sized + Unaligned> From<AlignmentError<Src, Dst>> for Infallible {
#[inline(always)]
fn from(_: AlignmentError<Src, Dst>) -> Infallible {
unsafe { core::hint::unreachable_unchecked() }
}
}
#[cfg(test)]
impl<Src, Dst> AlignmentError<Src, Dst> {
fn new_checked(src: Src) -> AlignmentError<Src, Dst> {
assert_ne!(core::mem::align_of::<Dst>(), 1);
unsafe { AlignmentError::new_unchecked(src) }
}
}
impl<Src, Dst: ?Sized> fmt::Debug for AlignmentError<Src, Dst> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AlignmentError").finish()
}
}
impl<Src, Dst: ?Sized> fmt::Display for AlignmentError<Src, Dst>
where
Src: Deref,
Dst: KnownLayout,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.")?;
if cfg!(debug_assertions) {
self.display_verbose_extras(f)
} else {
Ok(())
}
}
}
#[cfg(any(zerocopy_core_error, feature = "std", test))]
impl<Src, Dst: ?Sized> Error for AlignmentError<Src, Dst>
where
Src: Deref,
Dst: KnownLayout,
{
}
impl<Src, Dst: ?Sized, S, V> From<AlignmentError<Src, Dst>>
for ConvertError<AlignmentError<Src, Dst>, S, V>
{
#[inline(always)]
fn from(err: AlignmentError<Src, Dst>) -> Self {
Self::Alignment(err)
}
}
#[derive(PartialEq, Eq)]
pub struct SizeError<Src, Dst: ?Sized> {
src: Src,
dst: SendSyncPhantomData<Dst>,
}
impl<Src, Dst: ?Sized> SizeError<Src, Dst> {
pub(crate) fn new(src: Src) -> Self {
Self { src, dst: SendSyncPhantomData::default() }
}
#[inline]
pub fn into_src(self) -> Src {
self.src
}
pub(crate) fn with_src<NewSrc>(self, new_src: NewSrc) -> SizeError<NewSrc, Dst> {
SizeError { src: new_src, dst: SendSyncPhantomData::default() }
}
#[inline]
pub fn map_src<NewSrc>(self, f: impl Fn(Src) -> NewSrc) -> SizeError<NewSrc, Dst> {
SizeError { src: f(self.src), dst: SendSyncPhantomData::default() }
}
pub(crate) fn with_dst<NewDst: ?Sized>(self) -> SizeError<Src, NewDst> {
SizeError { src: self.src, dst: SendSyncPhantomData::default() }
}
pub(crate) fn into<A, V>(self) -> ConvertError<A, Self, V> {
ConvertError::Size(self)
}
fn display_verbose_extras(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
where
Src: Deref,
Dst: KnownLayout,
{
f.write_str("\nSource type: ")?;
f.write_str(core::any::type_name::<Src>())?;
let src_size = core::mem::size_of_val(&*self.src);
f.write_str("\nSource size: ")?;
src_size.fmt(f)?;
f.write_str(" byte")?;
if src_size != 1 {
f.write_char('s')?;
}
if let crate::SizeInfo::Sized { size } = Dst::LAYOUT.size_info {
f.write_str("\nDestination size: ")?;
size.fmt(f)?;
f.write_str(" byte")?;
if size != 1 {
f.write_char('s')?;
}
}
f.write_str("\nDestination type: ")?;
f.write_str(core::any::type_name::<Dst>())?;
Ok(())
}
}
impl<Src, Dst: ?Sized> fmt::Debug for SizeError<Src, Dst> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SizeError").finish()
}
}
impl<Src, Dst: ?Sized> fmt::Display for SizeError<Src, Dst>
where
Src: Deref,
Dst: KnownLayout,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("The conversion failed because the source was incorrectly sized to complete the conversion into the destination type.")?;
if cfg!(debug_assertions) {
f.write_str("\n")?;
self.display_verbose_extras(f)?;
}
Ok(())
}
}
#[cfg(any(zerocopy_core_error, feature = "std", test))]
impl<Src, Dst: ?Sized> Error for SizeError<Src, Dst>
where
Src: Deref,
Dst: KnownLayout,
{
}
impl<Src, Dst: ?Sized, A, V> From<SizeError<Src, Dst>> for ConvertError<A, SizeError<Src, Dst>, V> {
#[inline(always)]
fn from(err: SizeError<Src, Dst>) -> Self {
Self::Size(err)
}
}
#[derive(PartialEq, Eq)]
pub struct ValidityError<Src, Dst: ?Sized + TryFromBytes> {
pub(crate) src: Src,
dst: SendSyncPhantomData<Dst>,
}
impl<Src, Dst: ?Sized + TryFromBytes> ValidityError<Src, Dst> {
pub(crate) fn new(src: Src) -> Self {
Self { src, dst: SendSyncPhantomData::default() }
}
#[inline]
pub fn into_src(self) -> Src {
self.src
}
#[inline]
pub fn map_src<NewSrc>(self, f: impl Fn(Src) -> NewSrc) -> ValidityError<NewSrc, Dst> {
ValidityError { src: f(self.src), dst: SendSyncPhantomData::default() }
}
pub(crate) fn into<A, S>(self) -> ConvertError<A, S, Self> {
ConvertError::Validity(self)
}
fn display_verbose_extras(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
where
Src: Deref,
Dst: KnownLayout,
{
f.write_str("Destination type: ")?;
f.write_str(core::any::type_name::<Dst>())?;
Ok(())
}
}
impl<Src, Dst: ?Sized + TryFromBytes> fmt::Debug for ValidityError<Src, Dst> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ValidityError").finish()
}
}
impl<Src, Dst: ?Sized> fmt::Display for ValidityError<Src, Dst>
where
Src: Deref,
Dst: KnownLayout + TryFromBytes,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("The conversion failed because the source bytes are not a valid value of the destination type.")?;
if cfg!(debug_assertions) {
f.write_str("\n\n")?;
self.display_verbose_extras(f)?;
}
Ok(())
}
}
#[cfg(any(zerocopy_core_error, feature = "std", test))]
impl<Src, Dst: ?Sized> Error for ValidityError<Src, Dst>
where
Src: Deref,
Dst: KnownLayout + TryFromBytes,
{
}
impl<Src, Dst: ?Sized + TryFromBytes, A, S> From<ValidityError<Src, Dst>>
for ConvertError<A, S, ValidityError<Src, Dst>>
{
#[inline(always)]
fn from(err: ValidityError<Src, Dst>) -> Self {
Self::Validity(err)
}
}
#[allow(type_alias_bounds)]
pub type CastError<Src, Dst: ?Sized> =
ConvertError<AlignmentError<Src, Dst>, SizeError<Src, Dst>, Infallible>;
impl<Src, Dst: ?Sized> CastError<Src, Dst> {
#[inline]
pub fn into_src(self) -> Src {
match self {
Self::Alignment(e) => e.src,
Self::Size(e) => e.src,
Self::Validity(i) => match i {},
}
}
pub(crate) fn with_src<NewSrc>(self, new_src: NewSrc) -> CastError<NewSrc, Dst> {
match self {
Self::Alignment(e) => CastError::Alignment(e.with_src(new_src)),
Self::Size(e) => CastError::Size(e.with_src(new_src)),
Self::Validity(i) => match i {},
}
}
#[inline]
pub fn map_src<NewSrc>(self, f: impl Fn(Src) -> NewSrc) -> CastError<NewSrc, Dst> {
match self {
Self::Alignment(e) => CastError::Alignment(e.map_src(f)),
Self::Size(e) => CastError::Size(e.map_src(f)),
Self::Validity(i) => match i {},
}
}
pub(crate) fn into(self) -> TryCastError<Src, Dst>
where
Dst: TryFromBytes,
{
match self {
Self::Alignment(e) => TryCastError::Alignment(e),
Self::Size(e) => TryCastError::Size(e),
Self::Validity(i) => match i {},
}
}
}
impl<Src, Dst: ?Sized + Unaligned> From<CastError<Src, Dst>> for SizeError<Src, Dst> {
#[inline(always)]
fn from(err: CastError<Src, Dst>) -> SizeError<Src, Dst> {
match err {
#[allow(unreachable_code)]
CastError::Alignment(e) => match Infallible::from(e) {},
CastError::Size(e) => e,
CastError::Validity(i) => match i {},
}
}
}
#[allow(type_alias_bounds)]
pub type TryCastError<Src, Dst: ?Sized + TryFromBytes> =
ConvertError<AlignmentError<Src, Dst>, SizeError<Src, Dst>, ValidityError<Src, Dst>>;
impl<Src, Dst: ?Sized + TryFromBytes> TryCastError<Src, Dst> {
#[inline]
pub fn into_src(self) -> Src {
match self {
Self::Alignment(e) => e.src,
Self::Size(e) => e.src,
Self::Validity(e) => e.src,
}
}
#[inline]
pub fn map_src<NewSrc>(self, f: impl Fn(Src) -> NewSrc) -> TryCastError<NewSrc, Dst> {
match self {
Self::Alignment(e) => TryCastError::Alignment(e.map_src(f)),
Self::Size(e) => TryCastError::Size(e.map_src(f)),
Self::Validity(e) => TryCastError::Validity(e.map_src(f)),
}
}
}
impl<Src, Dst: ?Sized + TryFromBytes> From<CastError<Src, Dst>> for TryCastError<Src, Dst> {
#[inline]
fn from(value: CastError<Src, Dst>) -> Self {
match value {
CastError::Alignment(e) => Self::Alignment(e),
CastError::Size(e) => Self::Size(e),
CastError::Validity(i) => match i {},
}
}
}
#[allow(type_alias_bounds)]
pub type TryReadError<Src, Dst: ?Sized + TryFromBytes> =
ConvertError<Infallible, SizeError<Src, Dst>, ValidityError<Src, Dst>>;
impl<Src, Dst: ?Sized + TryFromBytes> TryReadError<Src, Dst> {
#[inline]
pub fn into_src(self) -> Src {
match self {
Self::Alignment(i) => match i {},
Self::Size(e) => e.src,
Self::Validity(e) => e.src,
}
}
#[inline]
pub fn map_src<NewSrc>(self, f: impl Fn(Src) -> NewSrc) -> TryReadError<NewSrc, Dst> {
match self {
Self::Alignment(i) => match i {},
Self::Size(e) => TryReadError::Size(e.map_src(f)),
Self::Validity(e) => TryReadError::Validity(e.map_src(f)),
}
}
}
#[allow(type_alias_bounds)]
pub type AlignedTryCastError<Src, Dst: ?Sized + TryFromBytes> =
ConvertError<Infallible, SizeError<Src, Dst>, ValidityError<Src, Dst>>;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct AllocError;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_send_sync() {
#[allow(dead_code)]
fn is_send_sync<T: Send + Sync>(_t: T) {}
#[allow(dead_code)]
fn alignment_err_is_send_sync<Src: Send + Sync, Dst>(err: AlignmentError<Src, Dst>) {
is_send_sync(err)
}
#[allow(dead_code)]
fn size_err_is_send_sync<Src: Send + Sync, Dst>(err: SizeError<Src, Dst>) {
is_send_sync(err)
}
#[allow(dead_code)]
fn validity_err_is_send_sync<Src: Send + Sync, Dst: TryFromBytes>(
err: ValidityError<Src, Dst>,
) {
is_send_sync(err)
}
#[allow(dead_code)]
fn convert_error_is_send_sync<Src: Send + Sync, Dst: TryFromBytes>(
err: ConvertError<
AlignmentError<Src, Dst>,
SizeError<Src, Dst>,
ValidityError<Src, Dst>,
>,
) {
is_send_sync(err)
}
}
#[test]
fn alignment_display() {
#[repr(C, align(128))]
struct Aligned {
bytes: [u8; 128],
}
impl_known_layout!(elain::Align::<8>);
let aligned = Aligned { bytes: [0; 128] };
let bytes = &aligned.bytes[1..];
let addr = crate::util::AsAddress::addr(bytes);
assert_eq!(
AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
\nSource type: &[u8]\
\nSource address: 0x{:x} (a multiple of 1)\
\nDestination type: elain::Align<8>\
\nDestination alignment: 8", addr)
);
let bytes = &aligned.bytes[2..];
let addr = crate::util::AsAddress::addr(bytes);
assert_eq!(
AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
\nSource type: &[u8]\
\nSource address: 0x{:x} (a multiple of 2)\
\nDestination type: elain::Align<8>\
\nDestination alignment: 8", addr)
);
let bytes = &aligned.bytes[3..];
let addr = crate::util::AsAddress::addr(bytes);
assert_eq!(
AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
\nSource type: &[u8]\
\nSource address: 0x{:x} (a multiple of 1)\
\nDestination type: elain::Align<8>\
\nDestination alignment: 8", addr)
);
let bytes = &aligned.bytes[4..];
let addr = crate::util::AsAddress::addr(bytes);
assert_eq!(
AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
\nSource type: &[u8]\
\nSource address: 0x{:x} (a multiple of 4)\
\nDestination type: elain::Align<8>\
\nDestination alignment: 8", addr)
);
}
#[test]
fn size_display() {
assert_eq!(
SizeError::<_, [u8]>::new(&[0u8; 2][..]).to_string(),
"The conversion failed because the source was incorrectly sized to complete the conversion into the destination type.\n\
\nSource type: &[u8]\
\nSource size: 2 bytes\
\nDestination type: [u8]"
);
assert_eq!(
SizeError::<_, [u8; 2]>::new(&[0u8; 1][..]).to_string(),
"The conversion failed because the source was incorrectly sized to complete the conversion into the destination type.\n\
\nSource type: &[u8]\
\nSource size: 1 byte\
\nDestination size: 2 bytes\
\nDestination type: [u8; 2]"
);
}
#[test]
fn validity_display() {
assert_eq!(
ValidityError::<_, bool>::new(&[2u8; 1][..]).to_string(),
"The conversion failed because the source bytes are not a valid value of the destination type.\n\
\n\
Destination type: bool"
);
}
}