1#[cfg(not(no_zerocopy_core_error_1_81_0))]
119use core::error::Error;
120use core::{
121 convert::Infallible,
122 fmt::{self, Debug, Write},
123 ops::Deref,
124};
125#[cfg(all(no_zerocopy_core_error_1_81_0, any(feature = "std", test)))]
126use std::error::Error;
127
128use crate::{util::SendSyncPhantomData, KnownLayout, TryFromBytes, Unaligned};
129#[cfg(doc)]
130use crate::{FromBytes, Ref};
131
132#[derive(PartialEq, Eq, Clone)]
153pub enum ConvertError<A, S, V> {
154 Alignment(A),
156 Size(S),
158 Validity(V),
160}
161
162impl<Src, Dst: ?Sized + Unaligned, S, V> From<ConvertError<AlignmentError<Src, Dst>, S, V>>
163 for ConvertError<Infallible, S, V>
164{
165 #[inline]
198 fn from(err: ConvertError<AlignmentError<Src, Dst>, S, V>) -> ConvertError<Infallible, S, V> {
199 match err {
200 ConvertError::Alignment(e) => {
201 #[allow(unreachable_code)]
202 return ConvertError::Alignment(Infallible::from(e));
203 }
204 ConvertError::Size(e) => ConvertError::Size(e),
205 ConvertError::Validity(e) => ConvertError::Validity(e),
206 }
207 }
208}
209
210impl<A: fmt::Debug, S: fmt::Debug, V: fmt::Debug> fmt::Debug for ConvertError<A, S, V> {
211 #[inline]
212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 match self {
214 Self::Alignment(e) => f.debug_tuple("Alignment").field(e).finish(),
215 Self::Size(e) => f.debug_tuple("Size").field(e).finish(),
216 Self::Validity(e) => f.debug_tuple("Validity").field(e).finish(),
217 }
218 }
219}
220
221impl<A: fmt::Display, S: fmt::Display, V: fmt::Display> fmt::Display for ConvertError<A, S, V> {
227 #[inline]
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 match self {
230 Self::Alignment(e) => e.fmt(f),
231 Self::Size(e) => e.fmt(f),
232 Self::Validity(e) => e.fmt(f),
233 }
234 }
235}
236
237#[cfg(any(not(no_zerocopy_core_error_1_81_0), feature = "std", test))]
238#[cfg_attr(doc_cfg, doc(cfg(all(rust = "1.81.0", feature = "std"))))]
239impl<A, S, V> Error for ConvertError<A, S, V>
240where
241 A: fmt::Display + fmt::Debug,
242 S: fmt::Display + fmt::Debug,
243 V: fmt::Display + fmt::Debug,
244{
245}
246
247pub struct AlignmentError<Src, Dst: ?Sized> {
249 src: Src,
251 _dst: SendSyncPhantomData<Dst>,
256}
257
258impl<Src, Dst: ?Sized> AlignmentError<Src, Dst> {
259 pub(crate) unsafe fn new_unchecked(src: Src) -> Self {
264 Self { src, _dst: SendSyncPhantomData::default() }
267 }
268
269 #[inline]
271 pub fn into_src(self) -> Src {
272 self.src
273 }
274
275 pub(crate) fn with_src<NewSrc>(self, new_src: NewSrc) -> AlignmentError<NewSrc, Dst> {
276 AlignmentError { src: new_src, _dst: SendSyncPhantomData::default() }
280 }
281
282 #[inline]
303 pub fn map_src<NewSrc>(self, f: impl FnOnce(Src) -> NewSrc) -> AlignmentError<NewSrc, Dst> {
304 AlignmentError { src: f(self.src), _dst: SendSyncPhantomData::default() }
305 }
306
307 pub(crate) fn into<S, V>(self) -> ConvertError<Self, S, V> {
308 ConvertError::Alignment(self)
309 }
310
311 fn display_verbose_extras(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
315 where
316 Src: Deref,
317 Dst: KnownLayout,
318 {
319 #[allow(clippy::as_conversions)]
320 let addr = self.src.deref() as *const _ as *const ();
321 let addr_align = 2usize.pow((crate::util::AsAddress::addr(addr)).trailing_zeros());
322
323 f.write_str("\n\nSource type: ")?;
324 f.write_str(core::any::type_name::<Src>())?;
325
326 f.write_str("\nSource address: ")?;
327 addr.fmt(f)?;
328 f.write_str(" (a multiple of ")?;
329 addr_align.fmt(f)?;
330 f.write_str(")")?;
331
332 f.write_str("\nDestination type: ")?;
333 f.write_str(core::any::type_name::<Dst>())?;
334
335 f.write_str("\nDestination alignment: ")?;
336 <Dst as KnownLayout>::LAYOUT.align.get().fmt(f)?;
337
338 Ok(())
339 }
340}
341
342impl<Src: Clone, Dst: ?Sized> Clone for AlignmentError<Src, Dst> {
343 #[inline]
344 fn clone(&self) -> Self {
345 Self { src: self.src.clone(), _dst: SendSyncPhantomData::default() }
346 }
347}
348
349impl<Src: PartialEq, Dst: ?Sized> PartialEq for AlignmentError<Src, Dst> {
350 #[inline]
351 fn eq(&self, other: &Self) -> bool {
352 self.src == other.src
353 }
354}
355
356impl<Src: Eq, Dst: ?Sized> Eq for AlignmentError<Src, Dst> {}
357
358impl<Src, Dst: ?Sized + Unaligned> From<AlignmentError<Src, Dst>> for Infallible {
359 #[inline(always)]
360 fn from(_: AlignmentError<Src, Dst>) -> Infallible {
361 unsafe { core::hint::unreachable_unchecked() }
366 }
367}
368
369#[cfg(test)]
370impl<Src, Dst> AlignmentError<Src, Dst> {
371 fn new_checked(src: Src) -> AlignmentError<Src, Dst> {
374 assert_ne!(core::mem::align_of::<Dst>(), 1);
375 unsafe { AlignmentError::new_unchecked(src) }
378 }
379}
380
381impl<Src, Dst: ?Sized> fmt::Debug for AlignmentError<Src, Dst> {
382 #[inline]
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 f.debug_struct("AlignmentError").finish()
385 }
386}
387
388impl<Src, Dst: ?Sized> fmt::Display for AlignmentError<Src, Dst>
394where
395 Src: Deref,
396 Dst: KnownLayout,
397{
398 #[inline]
399 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400 f.write_str("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.")?;
401
402 if cfg!(debug_assertions) {
403 self.display_verbose_extras(f)
404 } else {
405 Ok(())
406 }
407 }
408}
409
410#[cfg(any(not(no_zerocopy_core_error_1_81_0), feature = "std", test))]
411#[cfg_attr(doc_cfg, doc(cfg(all(rust = "1.81.0", feature = "std"))))]
412impl<Src, Dst: ?Sized> Error for AlignmentError<Src, Dst>
413where
414 Src: Deref,
415 Dst: KnownLayout,
416{
417}
418
419impl<Src, Dst: ?Sized, S, V> From<AlignmentError<Src, Dst>>
420 for ConvertError<AlignmentError<Src, Dst>, S, V>
421{
422 #[inline(always)]
423 fn from(err: AlignmentError<Src, Dst>) -> Self {
424 Self::Alignment(err)
425 }
426}
427
428pub struct SizeError<Src, Dst: ?Sized> {
430 src: Src,
432 _dst: SendSyncPhantomData<Dst>,
434}
435
436impl<Src, Dst: ?Sized> SizeError<Src, Dst> {
437 pub(crate) fn new(src: Src) -> Self {
438 Self { src, _dst: SendSyncPhantomData::default() }
439 }
440
441 #[inline]
443 pub fn into_src(self) -> Src {
444 self.src
445 }
446
447 pub(crate) fn with_src<NewSrc>(self, new_src: NewSrc) -> SizeError<NewSrc, Dst> {
449 SizeError { src: new_src, _dst: SendSyncPhantomData::default() }
450 }
451
452 #[inline]
474 pub fn map_src<NewSrc>(self, f: impl FnOnce(Src) -> NewSrc) -> SizeError<NewSrc, Dst> {
475 SizeError { src: f(self.src), _dst: SendSyncPhantomData::default() }
476 }
477
478 pub(crate) fn with_dst<NewDst: ?Sized>(self) -> SizeError<Src, NewDst> {
480 SizeError { src: self.src, _dst: SendSyncPhantomData::default() }
481 }
482
483 pub(crate) fn into<A, V>(self) -> ConvertError<A, Self, V> {
485 ConvertError::Size(self)
486 }
487
488 fn display_verbose_extras(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
492 where
493 Src: Deref,
494 Dst: KnownLayout,
495 {
496 f.write_str("\nSource type: ")?;
498 f.write_str(core::any::type_name::<Src>())?;
499
500 let src_size = core::mem::size_of_val(&*self.src);
502 f.write_str("\nSource size: ")?;
503 src_size.fmt(f)?;
504 f.write_str(" byte")?;
505 if src_size != 1 {
506 f.write_char('s')?;
507 }
508
509 if let crate::SizeInfo::Sized { size } = Dst::LAYOUT.size_info {
511 f.write_str("\nDestination size: ")?;
512 size.fmt(f)?;
513 f.write_str(" byte")?;
514 if size != 1 {
515 f.write_char('s')?;
516 }
517 }
518
519 f.write_str("\nDestination type: ")?;
521 f.write_str(core::any::type_name::<Dst>())?;
522
523 Ok(())
524 }
525}
526
527impl<Src: Clone, Dst: ?Sized> Clone for SizeError<Src, Dst> {
528 #[inline]
529 fn clone(&self) -> Self {
530 Self { src: self.src.clone(), _dst: SendSyncPhantomData::default() }
531 }
532}
533
534impl<Src: PartialEq, Dst: ?Sized> PartialEq for SizeError<Src, Dst> {
535 #[inline]
536 fn eq(&self, other: &Self) -> bool {
537 self.src == other.src
538 }
539}
540
541impl<Src: Eq, Dst: ?Sized> Eq for SizeError<Src, Dst> {}
542
543impl<Src, Dst: ?Sized> fmt::Debug for SizeError<Src, Dst> {
544 #[inline]
545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546 f.debug_struct("SizeError").finish()
547 }
548}
549
550impl<Src, Dst: ?Sized> fmt::Display for SizeError<Src, Dst>
556where
557 Src: Deref,
558 Dst: KnownLayout,
559{
560 #[inline]
561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562 f.write_str("The conversion failed because the source was incorrectly sized to complete the conversion into the destination type.")?;
563 if cfg!(debug_assertions) {
564 f.write_str("\n")?;
565 self.display_verbose_extras(f)?;
566 }
567 Ok(())
568 }
569}
570
571#[cfg(any(not(no_zerocopy_core_error_1_81_0), feature = "std", test))]
572#[cfg_attr(doc_cfg, doc(cfg(all(rust = "1.81.0", feature = "std"))))]
573impl<Src, Dst: ?Sized> Error for SizeError<Src, Dst>
574where
575 Src: Deref,
576 Dst: KnownLayout,
577{
578}
579
580impl<Src, Dst: ?Sized, A, V> From<SizeError<Src, Dst>> for ConvertError<A, SizeError<Src, Dst>, V> {
581 #[inline(always)]
582 fn from(err: SizeError<Src, Dst>) -> Self {
583 Self::Size(err)
584 }
585}
586
587pub struct ValidityError<Src, Dst: ?Sized + TryFromBytes> {
589 pub(crate) src: Src,
591 _dst: SendSyncPhantomData<Dst>,
593}
594
595impl<Src, Dst: ?Sized + TryFromBytes> ValidityError<Src, Dst> {
596 pub(crate) fn new(src: Src) -> Self {
597 Self { src, _dst: SendSyncPhantomData::default() }
598 }
599
600 #[inline]
602 pub fn into_src(self) -> Src {
603 self.src
604 }
605
606 #[inline]
627 pub fn map_src<NewSrc>(self, f: impl FnOnce(Src) -> NewSrc) -> ValidityError<NewSrc, Dst> {
628 ValidityError { src: f(self.src), _dst: SendSyncPhantomData::default() }
629 }
630
631 pub(crate) fn into<A, S>(self) -> ConvertError<A, S, Self> {
633 ConvertError::Validity(self)
634 }
635
636 fn display_verbose_extras(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
640 where
641 Dst: KnownLayout,
642 {
643 f.write_str("Destination type: ")?;
644 f.write_str(core::any::type_name::<Dst>())?;
645 Ok(())
646 }
647}
648
649impl<Src: Clone, Dst: ?Sized + TryFromBytes> Clone for ValidityError<Src, Dst> {
650 #[inline]
651 fn clone(&self) -> Self {
652 Self { src: self.src.clone(), _dst: SendSyncPhantomData::default() }
653 }
654}
655
656impl<Src: PartialEq, Dst: ?Sized + TryFromBytes> PartialEq for ValidityError<Src, Dst> {
657 #[inline]
658 fn eq(&self, other: &Self) -> bool {
659 self.src == other.src
660 }
661}
662
663impl<Src: Eq, Dst: ?Sized + TryFromBytes> Eq for ValidityError<Src, Dst> {}
664
665impl<Src, Dst: ?Sized + TryFromBytes> fmt::Debug for ValidityError<Src, Dst> {
666 #[inline]
667 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
668 f.debug_struct("ValidityError").finish()
669 }
670}
671
672impl<Src, Dst: ?Sized> fmt::Display for ValidityError<Src, Dst>
678where
679 Dst: KnownLayout + TryFromBytes,
680{
681 #[inline]
682 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683 f.write_str("The conversion failed because the source bytes are not a valid value of the destination type.")?;
684 if cfg!(debug_assertions) {
685 f.write_str("\n\n")?;
686 self.display_verbose_extras(f)?;
687 }
688 Ok(())
689 }
690}
691
692#[cfg(any(not(no_zerocopy_core_error_1_81_0), feature = "std", test))]
693#[cfg_attr(doc_cfg, doc(cfg(all(rust = "1.81.0", feature = "std"))))]
694impl<Src, Dst: ?Sized> Error for ValidityError<Src, Dst> where Dst: KnownLayout + TryFromBytes {}
695
696impl<Src, Dst: ?Sized + TryFromBytes, A, S> From<ValidityError<Src, Dst>>
697 for ConvertError<A, S, ValidityError<Src, Dst>>
698{
699 #[inline(always)]
700 fn from(err: ValidityError<Src, Dst>) -> Self {
701 Self::Validity(err)
702 }
703}
704
705#[allow(type_alias_bounds)]
712pub type CastError<Src, Dst: ?Sized> =
713 ConvertError<AlignmentError<Src, Dst>, SizeError<Src, Dst>, Infallible>;
714
715impl<Src, Dst: ?Sized> CastError<Src, Dst> {
716 #[inline]
718 pub fn into_src(self) -> Src {
719 match self {
720 Self::Alignment(e) => e.src,
721 Self::Size(e) => e.src,
722 Self::Validity(i) => match i {},
723 }
724 }
725
726 pub(crate) fn with_src<NewSrc>(self, new_src: NewSrc) -> CastError<NewSrc, Dst> {
728 match self {
729 Self::Alignment(e) => CastError::Alignment(e.with_src(new_src)),
730 Self::Size(e) => CastError::Size(e.with_src(new_src)),
731 Self::Validity(i) => match i {},
732 }
733 }
734
735 #[inline]
757 pub fn map_src<NewSrc>(self, f: impl FnOnce(Src) -> NewSrc) -> CastError<NewSrc, Dst> {
758 match self {
759 Self::Alignment(e) => CastError::Alignment(e.map_src(f)),
760 Self::Size(e) => CastError::Size(e.map_src(f)),
761 Self::Validity(i) => match i {},
762 }
763 }
764
765 pub(crate) fn into(self) -> TryCastError<Src, Dst>
767 where
768 Dst: TryFromBytes,
769 {
770 match self {
771 Self::Alignment(e) => TryCastError::Alignment(e),
772 Self::Size(e) => TryCastError::Size(e),
773 Self::Validity(i) => match i {},
774 }
775 }
776}
777
778impl<Src, Dst: ?Sized + Unaligned> From<CastError<Src, Dst>> for SizeError<Src, Dst> {
779 #[inline(always)]
819 fn from(err: CastError<Src, Dst>) -> SizeError<Src, Dst> {
820 match err {
821 #[allow(unreachable_code)]
822 CastError::Alignment(e) => match Infallible::from(e) {},
823 CastError::Size(e) => e,
824 CastError::Validity(i) => match i {},
825 }
826 }
827}
828
829#[allow(type_alias_bounds)]
837pub type TryCastError<Src, Dst: ?Sized + TryFromBytes> =
838 ConvertError<AlignmentError<Src, Dst>, SizeError<Src, Dst>, ValidityError<Src, Dst>>;
839
840impl<Src, Dst: ?Sized + TryFromBytes> TryCastError<Src, Dst> {
844 #[inline]
846 pub fn into_src(self) -> Src {
847 match self {
848 Self::Alignment(e) => e.src,
849 Self::Size(e) => e.src,
850 Self::Validity(e) => e.src,
851 }
852 }
853
854 #[inline]
878 pub fn map_src<NewSrc>(self, f: impl FnOnce(Src) -> NewSrc) -> TryCastError<NewSrc, Dst> {
879 match self {
880 Self::Alignment(e) => TryCastError::Alignment(e.map_src(f)),
881 Self::Size(e) => TryCastError::Size(e.map_src(f)),
882 Self::Validity(e) => TryCastError::Validity(e.map_src(f)),
883 }
884 }
885}
886
887impl<Src, Dst: ?Sized + TryFromBytes> From<CastError<Src, Dst>> for TryCastError<Src, Dst> {
888 #[inline]
889 fn from(value: CastError<Src, Dst>) -> Self {
890 match value {
891 CastError::Alignment(e) => Self::Alignment(e),
892 CastError::Size(e) => Self::Size(e),
893 CastError::Validity(i) => match i {},
894 }
895 }
896}
897
898#[allow(type_alias_bounds)]
906pub type TryReadError<Src, Dst: ?Sized + TryFromBytes> =
907 ConvertError<Infallible, SizeError<Src, Dst>, ValidityError<Src, Dst>>;
908
909impl<Src, Dst: ?Sized + TryFromBytes> TryReadError<Src, Dst> {
910 #[inline]
912 pub fn into_src(self) -> Src {
913 match self {
914 Self::Alignment(i) => match i {},
915 Self::Size(e) => e.src,
916 Self::Validity(e) => e.src,
917 }
918 }
919
920 #[inline]
944 pub fn map_src<NewSrc>(self, f: impl FnOnce(Src) -> NewSrc) -> TryReadError<NewSrc, Dst> {
945 match self {
946 Self::Alignment(i) => match i {},
947 Self::Size(e) => TryReadError::Size(e.map_src(f)),
948 Self::Validity(e) => TryReadError::Validity(e.map_src(f)),
949 }
950 }
951}
952
953#[allow(type_alias_bounds)]
987pub type AlignedTryCastError<Src, Dst: ?Sized + TryFromBytes> =
988 ConvertError<Infallible, SizeError<Src, Dst>, ValidityError<Src, Dst>>;
989
990#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1002pub struct AllocError;
1003
1004#[cfg(test)]
1005mod tests {
1006 use core::convert::Infallible;
1007
1008 use super::*;
1009
1010 #[test]
1011 fn test_send_sync() {
1012 #[allow(dead_code)]
1016 fn is_send_sync<T: Send + Sync>(_t: T) {}
1017
1018 #[allow(dead_code)]
1019 fn alignment_err_is_send_sync<Src: Send + Sync, Dst>(err: AlignmentError<Src, Dst>) {
1020 is_send_sync(err)
1021 }
1022
1023 #[allow(dead_code)]
1024 fn size_err_is_send_sync<Src: Send + Sync, Dst>(err: SizeError<Src, Dst>) {
1025 is_send_sync(err)
1026 }
1027
1028 #[allow(dead_code)]
1029 fn validity_err_is_send_sync<Src: Send + Sync, Dst: TryFromBytes>(
1030 err: ValidityError<Src, Dst>,
1031 ) {
1032 is_send_sync(err)
1033 }
1034
1035 #[allow(dead_code)]
1036 fn convert_error_is_send_sync<Src: Send + Sync, Dst: TryFromBytes>(
1037 err: ConvertError<
1038 AlignmentError<Src, Dst>,
1039 SizeError<Src, Dst>,
1040 ValidityError<Src, Dst>,
1041 >,
1042 ) {
1043 is_send_sync(err)
1044 }
1045 }
1046
1047 #[test]
1048 fn test_eq_partial_eq_clone() {
1049 #[allow(dead_code)]
1054 fn is_eq_partial_eq_clone<T: Eq + PartialEq + Clone>(_t: T) {}
1055
1056 #[allow(dead_code)]
1057 fn alignment_err_is_eq_partial_eq_clone<Src: Eq + PartialEq + Clone, Dst>(
1058 err: AlignmentError<Src, Dst>,
1059 ) {
1060 is_eq_partial_eq_clone(err)
1061 }
1062
1063 #[allow(dead_code)]
1064 fn size_err_is_eq_partial_eq_clone<Src: Eq + PartialEq + Clone, Dst>(
1065 err: SizeError<Src, Dst>,
1066 ) {
1067 is_eq_partial_eq_clone(err)
1068 }
1069
1070 #[allow(dead_code)]
1071 fn validity_err_is_eq_partial_eq_clone<Src: Eq + PartialEq + Clone, Dst: TryFromBytes>(
1072 err: ValidityError<Src, Dst>,
1073 ) {
1074 is_eq_partial_eq_clone(err)
1075 }
1076
1077 #[allow(dead_code)]
1078 fn convert_error_is_eq_partial_eq_clone<Src: Eq + PartialEq + Clone, Dst: TryFromBytes>(
1079 err: ConvertError<
1080 AlignmentError<Src, Dst>,
1081 SizeError<Src, Dst>,
1082 ValidityError<Src, Dst>,
1083 >,
1084 ) {
1085 is_eq_partial_eq_clone(err)
1086 }
1087 }
1088
1089 #[test]
1090 fn alignment_display() {
1091 #[repr(C, align(128))]
1092 struct Aligned {
1093 bytes: [u8; 128],
1094 }
1095
1096 impl_known_layout!(elain::Align::<8>);
1097
1098 let aligned = Aligned { bytes: [0; 128] };
1099
1100 let bytes = &aligned.bytes[1..];
1101 let addr = crate::util::AsAddress::addr(bytes);
1102 assert_eq!(
1103 AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
1104 format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
1105 \nSource type: &[u8]\
1106 \nSource address: 0x{:x} (a multiple of 1)\
1107 \nDestination type: elain::Align<8>\
1108 \nDestination alignment: 8", addr)
1109 );
1110
1111 let bytes = &aligned.bytes[2..];
1112 let addr = crate::util::AsAddress::addr(bytes);
1113 assert_eq!(
1114 AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
1115 format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
1116 \nSource type: &[u8]\
1117 \nSource address: 0x{:x} (a multiple of 2)\
1118 \nDestination type: elain::Align<8>\
1119 \nDestination alignment: 8", addr)
1120 );
1121
1122 let bytes = &aligned.bytes[3..];
1123 let addr = crate::util::AsAddress::addr(bytes);
1124 assert_eq!(
1125 AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
1126 format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
1127 \nSource type: &[u8]\
1128 \nSource address: 0x{:x} (a multiple of 1)\
1129 \nDestination type: elain::Align<8>\
1130 \nDestination alignment: 8", addr)
1131 );
1132
1133 let bytes = &aligned.bytes[4..];
1134 let addr = crate::util::AsAddress::addr(bytes);
1135 assert_eq!(
1136 AlignmentError::<_, elain::Align::<8>>::new_checked(bytes).to_string(),
1137 format!("The conversion failed because the address of the source is not a multiple of the alignment of the destination type.\n\
1138 \nSource type: &[u8]\
1139 \nSource address: 0x{:x} (a multiple of 4)\
1140 \nDestination type: elain::Align<8>\
1141 \nDestination alignment: 8", addr)
1142 );
1143 }
1144
1145 #[test]
1146 fn size_display() {
1147 assert_eq!(
1148 SizeError::<_, [u8]>::new(&[0u8; 2][..]).to_string(),
1149 "The conversion failed because the source was incorrectly sized to complete the conversion into the destination type.\n\
1150 \nSource type: &[u8]\
1151 \nSource size: 2 bytes\
1152 \nDestination type: [u8]"
1153 );
1154
1155 assert_eq!(
1156 SizeError::<_, [u8; 2]>::new(&[0u8; 1][..]).to_string(),
1157 "The conversion failed because the source was incorrectly sized to complete the conversion into the destination type.\n\
1158 \nSource type: &[u8]\
1159 \nSource size: 1 byte\
1160 \nDestination size: 2 bytes\
1161 \nDestination type: [u8; 2]"
1162 );
1163 }
1164
1165 #[test]
1166 fn validity_display() {
1167 assert_eq!(
1168 ValidityError::<_, bool>::new(&[2u8; 1][..]).to_string(),
1169 "The conversion failed because the source bytes are not a valid value of the destination type.\n\
1170 \n\
1171 Destination type: bool"
1172 );
1173 }
1174
1175 #[test]
1176 fn test_convert_error_debug() {
1177 let err: ConvertError<
1178 AlignmentError<&[u8], u16>,
1179 SizeError<&[u8], u16>,
1180 ValidityError<&[u8], bool>,
1181 > = ConvertError::Alignment(AlignmentError::new_checked(&[0u8]));
1182 assert_eq!(format!("{:?}", err), "Alignment(AlignmentError)");
1183
1184 let err: ConvertError<
1185 AlignmentError<&[u8], u16>,
1186 SizeError<&[u8], u16>,
1187 ValidityError<&[u8], bool>,
1188 > = ConvertError::Size(SizeError::new(&[0u8]));
1189 assert_eq!(format!("{:?}", err), "Size(SizeError)");
1190
1191 let err: ConvertError<
1192 AlignmentError<&[u8], u16>,
1193 SizeError<&[u8], u16>,
1194 ValidityError<&[u8], bool>,
1195 > = ConvertError::Validity(ValidityError::new(&[0u8]));
1196 assert_eq!(format!("{:?}", err), "Validity(ValidityError)");
1197 }
1198
1199 #[test]
1200 fn test_convert_error_from_unaligned() {
1201 let err: ConvertError<
1203 AlignmentError<&[u8], u8>,
1204 SizeError<&[u8], u8>,
1205 ValidityError<&[u8], bool>,
1206 > = ConvertError::Size(SizeError::new(&[0u8]));
1207 let converted: ConvertError<Infallible, SizeError<&[u8], u8>, ValidityError<&[u8], bool>> =
1208 ConvertError::from(err);
1209 match converted {
1210 ConvertError::Size(_) => {}
1211 _ => panic!("Expected Size error"),
1212 }
1213 }
1214
1215 #[test]
1216 fn test_alignment_error_display_debug() {
1217 let err: AlignmentError<&[u8], u16> = AlignmentError::new_checked(&[0u8]);
1218 assert!(format!("{:?}", err).contains("AlignmentError"));
1219 assert!(format!("{}", err).contains("address of the source is not a multiple"));
1220 }
1221
1222 #[test]
1223 fn test_size_error_display_debug() {
1224 let err: SizeError<&[u8], u16> = SizeError::new(&[0u8]);
1225 assert!(format!("{:?}", err).contains("SizeError"));
1226 assert!(format!("{}", err).contains("source was incorrectly sized"));
1227 }
1228
1229 #[test]
1230 fn test_validity_error_display_debug() {
1231 let err: ValidityError<&[u8], bool> = ValidityError::new(&[0u8]);
1232 assert!(format!("{:?}", err).contains("ValidityError"));
1233 assert!(format!("{}", err).contains("source bytes are not a valid value"));
1234 }
1235
1236 #[test]
1237 fn test_convert_error_display_debug_more() {
1238 let err: ConvertError<
1239 AlignmentError<&[u8], u16>,
1240 SizeError<&[u8], u16>,
1241 ValidityError<&[u8], bool>,
1242 > = ConvertError::Alignment(AlignmentError::new_checked(&[0u8]));
1243 assert!(format!("{}", err).contains("address of the source is not a multiple"));
1244
1245 let err: ConvertError<
1246 AlignmentError<&[u8], u16>,
1247 SizeError<&[u8], u16>,
1248 ValidityError<&[u8], bool>,
1249 > = ConvertError::Size(SizeError::new(&[0u8]));
1250 assert!(format!("{}", err).contains("source was incorrectly sized"));
1251
1252 let err: ConvertError<
1253 AlignmentError<&[u8], u16>,
1254 SizeError<&[u8], u16>,
1255 ValidityError<&[u8], bool>,
1256 > = ConvertError::Validity(ValidityError::new(&[0u8]));
1257 assert!(format!("{}", err).contains("source bytes are not a valid value"));
1258 }
1259
1260 #[test]
1261 fn test_alignment_error_methods() {
1262 let err: AlignmentError<&[u8], u16> = AlignmentError::new_checked(&[0u8]);
1263
1264 let src = err.clone().into_src();
1266 assert_eq!(src, &[0u8]);
1267
1268 let converted: ConvertError<
1270 AlignmentError<&[u8], u16>,
1271 SizeError<&[u8], u16>,
1272 ValidityError<&[u8], bool>,
1273 > = err.clone().into();
1274 match converted {
1275 ConvertError::Alignment(_) => {}
1276 _ => panic!("Expected Alignment error"),
1277 }
1278
1279 let cloned = err.clone();
1281 assert_eq!(err, cloned);
1282
1283 assert_eq!(err, cloned);
1285 let err2: AlignmentError<&[u8], u16> = AlignmentError::new_checked(&[1u8]);
1286 assert_ne!(err, err2);
1287 }
1288
1289 #[test]
1290 fn test_convert_error_from_unaligned_variants() {
1291 let err: ConvertError<
1293 AlignmentError<&[u8], u8>,
1294 SizeError<&[u8], u8>,
1295 ValidityError<&[u8], bool>,
1296 > = ConvertError::Validity(ValidityError::new(&[0u8]));
1297 let converted: ConvertError<Infallible, SizeError<&[u8], u8>, ValidityError<&[u8], bool>> =
1298 ConvertError::from(err);
1299 match converted {
1300 ConvertError::Validity(_) => {}
1301 _ => panic!("Expected Validity error"),
1302 }
1303
1304 let err: ConvertError<
1305 AlignmentError<&[u8], u8>,
1306 SizeError<&[u8], u8>,
1307 ValidityError<&[u8], bool>,
1308 > = ConvertError::Size(SizeError::new(&[0u8]));
1309 let converted: ConvertError<Infallible, SizeError<&[u8], u8>, ValidityError<&[u8], bool>> =
1310 ConvertError::from(err);
1311 match converted {
1312 ConvertError::Size(_) => {}
1313 _ => panic!("Expected Size error"),
1314 }
1315 }
1316}