1#![cfg_attr(not(test), deny(clippy::cast_possible_truncation))]
54#![cfg_attr(not(test), deny(clippy::cast_possible_wrap))]
55#![cfg_attr(feature = "rpc_try", feature(try_trait_v2))]
56#![cfg_attr(not(feature = "std"), no_std)]
57
58#[cfg(feature = "alloc")]
59#[macro_use]
60extern crate alloc;
61
62pub mod schema_capnp;
65
66pub mod any_pointer;
67pub mod any_pointer_list;
68pub mod capability;
69pub mod capability_list;
70pub mod constant;
71pub mod data;
72pub mod data_list;
73pub mod dynamic_list;
74pub mod dynamic_struct;
75pub mod dynamic_value;
76pub mod enum_list;
77pub mod introspect;
78pub mod io;
79pub mod list_list;
80pub mod message;
81pub mod primitive_list;
82pub mod private;
83pub mod raw;
84pub mod schema;
85pub mod serialize;
86pub mod serialize_packed;
87pub(crate) mod stringify;
88pub mod struct_list;
89pub mod text;
90pub mod text_list;
91pub mod traits;
92
93#[macro_export]
110macro_rules! generated_code {
111 ($vis:vis mod $mod_name:ident, $file_name:expr_2021) => {
112 $vis mod $mod_name {
113 #![allow(clippy::all)]
114 include!(concat!(env!("OUT_DIR"), "/", $file_name));
115 }
116 };
117
118 ($vis:vis mod $mod_name:ident) => {
119 $crate::generated_code!($vis mod $mod_name, concat!(stringify!($mod_name), ".rs"));
120 };
121}
122
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129#[repr(C, align(8))]
130pub struct Word {
131 raw_content: [u8; 8],
132}
133
134#[allow(clippy::too_many_arguments)]
138pub const fn word(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8) -> Word {
139 Word {
140 raw_content: [b0, b1, b2, b3, b4, b5, b6, b7],
141 }
142}
143
144impl Word {
145 #[cfg(feature = "alloc")]
147 pub fn allocate_zeroed_vec(length: usize) -> alloc::vec::Vec<Self> {
148 vec![word(0, 0, 0, 0, 0, 0, 0, 0); length]
149 }
150
151 pub fn words_to_bytes(words: &[Self]) -> &[u8] {
152 unsafe { core::slice::from_raw_parts(words.as_ptr() as *const u8, words.len() * 8) }
153 }
154
155 pub fn words_to_bytes_mut(words: &mut [Self]) -> &mut [u8] {
156 unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr() as *mut u8, words.len() * 8) }
157 }
158}
159
160#[cfg(any(feature = "quickcheck", test))]
161impl quickcheck::Arbitrary for Word {
162 fn arbitrary(g: &mut quickcheck::Gen) -> Self {
163 crate::word(
164 quickcheck::Arbitrary::arbitrary(g),
165 quickcheck::Arbitrary::arbitrary(g),
166 quickcheck::Arbitrary::arbitrary(g),
167 quickcheck::Arbitrary::arbitrary(g),
168 quickcheck::Arbitrary::arbitrary(g),
169 quickcheck::Arbitrary::arbitrary(g),
170 quickcheck::Arbitrary::arbitrary(g),
171 quickcheck::Arbitrary::arbitrary(g),
172 )
173 }
174}
175
176#[derive(Clone, Copy, Debug, PartialEq)]
178pub struct MessageSize {
179 pub word_count: u64,
180
181 pub cap_count: u32,
183}
184
185impl core::ops::AddAssign for MessageSize {
186 fn add_assign(&mut self, rhs: Self) {
187 self.word_count += rhs.word_count;
188 self.cap_count += rhs.cap_count;
189 }
190}
191
192#[derive(PartialEq, Eq, Clone, Copy, Debug)]
194pub struct NotInSchema(pub u16);
195
196impl ::core::fmt::Display for NotInSchema {
197 fn fmt(
198 &self,
199 fmt: &mut ::core::fmt::Formatter,
200 ) -> ::core::result::Result<(), ::core::fmt::Error> {
201 write!(
202 fmt,
203 "Enum value or union discriminant {} was not present in the schema.",
204 self.0
205 )
206 }
207}
208
209impl ::core::error::Error for NotInSchema {
210 fn description(&self) -> &str {
211 "Enum value or union discriminant was not present in schema."
212 }
213}
214
215pub type Result<T> = ::core::result::Result<T, Error>;
218
219#[cfg(feature = "alloc")]
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct ErrorDetail {
226 pub id: u64,
227 pub data: alloc::vec::Vec<u8>,
228}
229
230#[derive(Debug, Clone)]
232#[non_exhaustive]
233pub struct Error {
234 pub kind: ErrorKind,
237
238 #[cfg(feature = "alloc")]
239 extra: alloc::string::String,
240 #[cfg(feature = "alloc")]
242 #[allow(clippy::box_collection)]
243 details: Option<alloc::boxed::Box<alloc::vec::Vec<ErrorDetail>>>,
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249#[non_exhaustive]
250pub enum ErrorKind {
251 Failed,
253
254 Overloaded,
261
262 Disconnected,
265
266 Unimplemented,
269
270 BufferNotLargeEnough,
272
273 CannotCreateACanonicalMessageWithACapability,
275
276 CannotSetAnyPointerFieldToAPrimitiveValue,
278
279 CantHandleNonStructInlineComposite,
281
282 EmptyBuffer,
284
285 EmptySlice,
287
288 EnumValueOrUnionDiscriminantNotPresent(NotInSchema),
290
291 ExistingListPointerIsNotByteSized,
293
294 ExistingListValueIsIncompatibleWithExpectedType,
296
297 ExistingPointerIsNotAList,
299
300 ExpectedAListOrBlob,
302
303 ExpectedAPointerListButGotAListOfDataOnlyStructs,
305
306 ExpectedAPrimitiveListButGotAListOfPointerOnlyStructs,
308
309 FailedToFillTheWholeBuffer,
311
312 FieldAndDefaultMismatch,
314
315 FieldNotFound,
317
318 FoundBitListWhereStructListWasExpected,
320
321 FoundStructListWhereBitListWasExpected,
323
324 FourByteLengthTooBigForUSize,
326
327 FourByteSegmentLengthTooBigForUSize,
329
330 GroupFieldButTypeIsNotStruct,
332
333 InitIsOnlyValidForStructAndAnyPointerFields,
335
336 InitnIsOnlyValidForListTextOrDataFields,
338
339 InlineCompositeListWithNonStructElementsNotSupported,
341
342 InlineCompositeListsElementsOverrunItsWordCount,
344
345 InlineCompositeListsOfNonStructTypeAreNotSupported,
347
348 InvalidNumberOfSegments(usize),
350
351 InvalidSegmentId(u32),
353
354 ListAnyPointerNotSupported,
356
357 ListCapabilityNotSupported,
359
360 MalformedDoubleFarPointer,
362
363 MessageContainsInvalidCapabilityPointer,
365
366 MessageContainsListPointerOfNonBytesWhereDataWasExpected,
368
369 MessageContainsListPointerOfNonBytesWhereTextWasExpected,
371
372 MessageContainsListWithIncompatibleElementType,
374
375 MessageContainsNonCapabilityPointerWhereCapabilityPointerWasExpected,
377
378 MessageContainsNonStructPointerWhereStructPointerWasExpected,
380
381 MessageContainsNonListPointerWhereDataWasExpected,
383
384 MessageContainsNonListPointerWhereListPointerWasExpected,
386
387 MessageContainsNonListPointerWhereTextWasExpected,
389
390 MessageContainsNullCapabilityPointer,
392
393 MessageContainsOutOfBoundsPointer,
395
396 MessageContainsTextThatIsNotNULTerminated,
398
399 MessageEndsPrematurely(usize, usize),
401
402 MessageIsTooDeeplyNested,
404
405 MessageIsTooDeeplyNestedOrContainsCycles,
407
408 MessageNotAlignedBy8BytesBoundary,
410
411 MessageSizeOverflow,
413
414 MessageTooLarge(usize),
416
417 NestingLimitExceeded,
419
420 NotAStruct,
422
423 OnlyOneOfTheSectionPointersIsPointingToOurself,
425
426 PackedInputDidNotEndCleanlyOnASegmentBoundary,
428
429 PrematureEndOfFile,
431
432 PrematureEndOfPackedInput,
434
435 ReadLimitExceeded,
437
438 SettingDynamicCapabilitiesIsUnsupported,
440
441 StructReaderHadBitwidthOtherThan1,
443
444 TextBlobMissingNULTerminator,
446
447 TextContainsNonUtf8Data(core::str::Utf8Error),
449
450 TriedToReadFromNullArena,
452
453 TypeMismatch,
455
456 UnalignedSegment,
459
460 UnexpectedFarPointer,
462
463 UnknownPointerType,
465}
466
467impl Error {
468 #[cfg(feature = "alloc")]
469 pub fn new(kind: ErrorKind, extra: alloc::string::String) -> Self {
470 Self {
471 kind,
472 extra,
473 details: None,
474 }
475 }
476
477 pub fn from_kind(kind: ErrorKind) -> Self {
478 Self {
479 kind,
480 #[cfg(feature = "alloc")]
481 extra: alloc::string::String::new(),
482 #[cfg(feature = "alloc")]
483 details: None,
484 }
485 }
486
487 #[cfg(feature = "alloc")]
488 pub fn failed(description: alloc::string::String) -> Self {
489 Self::new(ErrorKind::Failed, description)
490 }
491
492 #[cfg(feature = "alloc")]
493 pub fn overloaded(description: alloc::string::String) -> Self {
494 Self::new(ErrorKind::Overloaded, description)
495 }
496
497 #[cfg(feature = "alloc")]
498 pub fn disconnected(description: alloc::string::String) -> Self {
499 Self::new(ErrorKind::Disconnected, description)
500 }
501
502 #[cfg(feature = "alloc")]
503 pub fn unimplemented(description: alloc::string::String) -> Self {
504 Self::new(ErrorKind::Unimplemented, description)
505 }
506
507 pub fn extra(&self) -> &str {
509 #[cfg(feature = "alloc")]
510 {
511 &self.extra
512 }
513 #[cfg(not(feature = "alloc"))]
514 {
515 ""
516 }
517 }
518
519 pub fn write_fmt(&mut self, fmt: core::fmt::Arguments<'_>) {
522 #[cfg(feature = "alloc")]
523 {
524 use core::fmt::Write;
525 let _ = self.extra.write_fmt(fmt);
526 }
527 #[cfg(not(feature = "alloc"))]
528 {
529 let _ = fmt;
530 }
531 }
532
533 #[cfg(feature = "alloc")]
539 pub fn get_detail(&self, detail_id: u64) -> Option<&[u8]> {
540 let details = self.details.as_ref()?;
541 details
542 .iter()
543 .find(|detail| detail.id == detail_id)
544 .map(|detail| detail.data.as_slice())
545 }
546
547 #[cfg(feature = "alloc")]
549 pub fn get_details(&self) -> &[ErrorDetail] {
550 match &self.details {
551 Some(details) => details.as_slice(),
552 None => &[],
553 }
554 }
555
556 #[cfg(feature = "alloc")]
568 pub fn set_detail(&mut self, detail_id: u64, data: alloc::vec::Vec<u8>) {
569 let details = self.details.get_or_insert_with(Default::default);
570 if let Some(existing) = details.iter_mut().find(|detail| detail.id == detail_id) {
571 existing.data = data;
572 } else {
573 details.push(ErrorDetail {
574 id: detail_id,
575 data,
576 });
577 }
578 }
579
580 #[cfg(feature = "alloc")]
582 pub fn release_detail(&mut self, detail_id: u64) -> Option<alloc::vec::Vec<u8>> {
583 let details = self.details.as_mut()?;
584 let idx = details.iter().position(|detail| detail.id == detail_id)?;
585 let detail = details.remove(idx);
586 if details.is_empty() {
587 self.details = None;
588 }
589 Some(detail.data)
590 }
591}
592
593#[cfg(feature = "std")]
594impl core::convert::From<::std::io::Error> for Error {
595 fn from(err: ::std::io::Error) -> Self {
596 use std::io;
597 let kind = match err.kind() {
598 io::ErrorKind::TimedOut => ErrorKind::Overloaded,
599 io::ErrorKind::BrokenPipe
600 | io::ErrorKind::ConnectionRefused
601 | io::ErrorKind::ConnectionReset
602 | io::ErrorKind::ConnectionAborted
603 | io::ErrorKind::NotConnected => ErrorKind::Disconnected,
604 io::ErrorKind::UnexpectedEof => ErrorKind::PrematureEndOfFile,
605 _ => ErrorKind::Failed,
606 };
607 #[cfg(feature = "alloc")]
608 return Self::new(kind, format!("{err}"));
609 #[cfg(not(feature = "alloc"))]
610 return Self::from_kind(kind);
611 }
612}
613
614#[cfg(feature = "embedded-io")]
615impl From<embedded_io::ErrorKind> for ErrorKind {
616 fn from(value: embedded_io::ErrorKind) -> Self {
617 match value {
618 embedded_io::ErrorKind::Other => Self::Failed,
619 embedded_io::ErrorKind::NotFound => Self::Failed,
620 embedded_io::ErrorKind::PermissionDenied => Self::Failed,
621 embedded_io::ErrorKind::ConnectionRefused => Self::Failed,
622 embedded_io::ErrorKind::ConnectionReset => Self::Failed,
623 embedded_io::ErrorKind::ConnectionAborted => Self::Failed,
624 embedded_io::ErrorKind::NotConnected => Self::Failed,
625 embedded_io::ErrorKind::AddrInUse => Self::Failed,
626 embedded_io::ErrorKind::AddrNotAvailable => Self::Failed,
627 embedded_io::ErrorKind::BrokenPipe => Self::Failed,
628 embedded_io::ErrorKind::AlreadyExists => Self::Failed,
629 embedded_io::ErrorKind::InvalidInput => Self::Failed,
630 embedded_io::ErrorKind::InvalidData => Self::Failed,
631 embedded_io::ErrorKind::TimedOut => Self::Failed,
632 embedded_io::ErrorKind::Interrupted => Self::Failed,
633 embedded_io::ErrorKind::Unsupported => Self::Failed,
634 embedded_io::ErrorKind::OutOfMemory => Self::Failed,
635 _ => Self::Failed,
636 }
637 }
638}
639
640#[cfg(feature = "alloc")]
641impl core::convert::From<alloc::string::FromUtf8Error> for Error {
642 fn from(err: alloc::string::FromUtf8Error) -> Self {
643 Self::failed(format!("{err}"))
644 }
645}
646
647impl core::convert::From<core::str::Utf8Error> for Error {
648 fn from(err: core::str::Utf8Error) -> Self {
649 Self::from_kind(ErrorKind::TextContainsNonUtf8Data(err))
650 }
651}
652
653impl core::convert::From<NotInSchema> for Error {
654 fn from(e: NotInSchema) -> Self {
655 Self::from_kind(ErrorKind::EnumValueOrUnionDiscriminantNotPresent(e))
656 }
657}
658
659impl core::fmt::Display for ErrorKind {
660 fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
661 match self {
662 Self::Failed => write!(fmt, "Failed"),
663 Self::Overloaded => write!(fmt, "Overloaded"),
664 Self::Disconnected => write!(fmt, "Disconnected"),
665 Self::Unimplemented => write!(fmt, "Unimplemented"),
666 Self::BufferNotLargeEnough => write!(fmt, "buffer is not large enough"),
667 Self::ExistingListPointerIsNotByteSized => write!(
668 fmt,
669 "Called get_writable_{{data|text}}_pointer() but existing list pointer is not byte-sized."
670 ),
671 Self::ExistingPointerIsNotAList => write!(
672 fmt,
673 "Called get_writable_{{data|text|list|struct_list}}_pointer() but existing pointer is not a list."
674 ),
675 Self::CannotCreateACanonicalMessageWithACapability => {
676 write!(fmt, "Cannot create a canonical message with a capability")
677 }
678 Self::FourByteLengthTooBigForUSize => write!(
679 fmt,
680 "Cannot represent 4 byte length as `usize`. This may indicate that you are running on 8 or 16 bit platform or message is too large."
681 ),
682 Self::FourByteSegmentLengthTooBigForUSize => write!(
683 fmt,
684 "Cannot represent 4 byte segment length as usize. This may indicate that you are running on 8 or 16 bit platform or segment is too large"
685 ),
686 Self::CannotSetAnyPointerFieldToAPrimitiveValue => {
687 write!(fmt, "cannot set AnyPointer field to a primitive value")
688 }
689 Self::CantHandleNonStructInlineComposite => {
690 write!(fmt, "Don't know how to handle non-STRUCT inline composite.")
691 }
692 Self::EmptyBuffer => write!(fmt, "empty buffer"),
693 Self::EmptySlice => write!(fmt, "empty slice"),
694 Self::EnumValueOrUnionDiscriminantNotPresent(val) => write!(
695 fmt,
696 "Enum value or union discriminant {val} was not present in schema"
697 ),
698 Self::ExistingListValueIsIncompatibleWithExpectedType => write!(
699 fmt,
700 "Existing list value is incompatible with expected type."
701 ),
702 Self::ExpectedAListOrBlob => write!(fmt, "Expected a list or blob."),
703 Self::ExpectedAPointerListButGotAListOfDataOnlyStructs => write!(
704 fmt,
705 "Expected a pointer list, but got a list of data-only structs"
706 ),
707 Self::ExpectedAPrimitiveListButGotAListOfPointerOnlyStructs => write!(
708 fmt,
709 "Expected a primitive list, but got a list of pointer-only structs"
710 ),
711 Self::FailedToFillTheWholeBuffer => write!(fmt, "failed to fill the whole buffer"),
712 Self::FieldAndDefaultMismatch => write!(fmt, "field and default mismatch"),
713 Self::FieldNotFound => write!(fmt, "field not found"),
714 Self::FoundBitListWhereStructListWasExpected => write!(
715 fmt,
716 "Found bit list where struct list was expected; upgrading boolean lists to struct lists is no longer supported."
717 ),
718 Self::FoundStructListWhereBitListWasExpected => {
719 write!(fmt, "Found struct list where bit list was expected.")
720 }
721 Self::GroupFieldButTypeIsNotStruct => write!(fmt, "group field but type is not Struct"),
722 Self::InitIsOnlyValidForStructAndAnyPointerFields => {
723 write!(fmt, "init() is only valid for struct and AnyPointer fields")
724 }
725 Self::InitnIsOnlyValidForListTextOrDataFields => {
726 write!(fmt, "initn() is only valid for list, text, or data fields")
727 }
728 Self::InlineCompositeListWithNonStructElementsNotSupported => write!(
729 fmt,
730 "InlineComposite list with non-STRUCT elements not supported."
731 ),
732 Self::InlineCompositeListsElementsOverrunItsWordCount => write!(
733 fmt,
734 "InlineComposite list's elements overrun its word count."
735 ),
736 Self::InlineCompositeListsOfNonStructTypeAreNotSupported => write!(
737 fmt,
738 "InlineComposite lists of non-STRUCT type are not supported."
739 ),
740 Self::InvalidNumberOfSegments(segment_count) => {
741 write!(fmt, "Too many or too few segments {segment_count}")
742 }
743 Self::InvalidSegmentId(id) => write!(fmt, "Invalid segment id {id}"),
744 Self::ListAnyPointerNotSupported => write!(fmt, "List(AnyPointer) not supported."),
745 Self::ListCapabilityNotSupported => write!(fmt, "List(Capability) not supported"),
746 Self::MalformedDoubleFarPointer => write!(fmt, "Malformed double-far pointer."),
747 Self::MessageContainsInvalidCapabilityPointer => {
748 write!(fmt, "Message contained invalid capability pointer.")
749 }
750 Self::MessageContainsListPointerOfNonBytesWhereDataWasExpected => write!(
751 fmt,
752 "Message contains list pointer of non-bytes where data was expected."
753 ),
754 Self::MessageContainsListPointerOfNonBytesWhereTextWasExpected => write!(
755 fmt,
756 "Message contains list pointer of non-bytes where text was expected."
757 ),
758 Self::MessageContainsListWithIncompatibleElementType => {
759 write!(fmt, "Message contains list with incompatible element type.")
760 }
761 Self::MessageContainsNonCapabilityPointerWhereCapabilityPointerWasExpected => write!(
762 fmt,
763 "Message contains non-capability pointer where capability pointer was expected."
764 ),
765 Self::MessageContainsNonListPointerWhereDataWasExpected => write!(
766 fmt,
767 "Message contains non-list pointer where data was expected."
768 ),
769 Self::MessageContainsNonListPointerWhereListPointerWasExpected => write!(
770 fmt,
771 "Message contains non-list pointer where list pointer was expected"
772 ),
773 Self::MessageContainsNonListPointerWhereTextWasExpected => write!(
774 fmt,
775 "Message contains non-list pointer where text was expected."
776 ),
777 Self::MessageContainsNonStructPointerWhereStructPointerWasExpected => write!(
778 fmt,
779 "Message contains non-struct pointer where struct pointer was expected."
780 ),
781 Self::MessageContainsNullCapabilityPointer => {
782 write!(fmt, "Message contains null capability pointer.")
783 }
784 Self::MessageContainsOutOfBoundsPointer => {
785 write!(fmt, "Message contains out-of-bounds pointer")
786 }
787 Self::MessageContainsTextThatIsNotNULTerminated => {
788 write!(fmt, "Message contains text that is not NUL-terminated")
789 }
790 Self::MessageEndsPrematurely(header, body) => write!(
791 fmt,
792 "Message ends prematurely. Header claimed {header} words, but message only has {body} words"
793 ),
794 Self::MessageIsTooDeeplyNested => write!(fmt, "Message is too deeply nested."),
795 Self::MessageIsTooDeeplyNestedOrContainsCycles => {
796 write!(fmt, "Message is too deeply-nested or contains cycles.")
797 }
798 Self::MessageSizeOverflow => {
799 write!(fmt, "Message's size cannot be represented in usize")
800 }
801 Self::MessageTooLarge(val) => write!(fmt, "Message is too large: {val}"),
802 Self::MessageNotAlignedBy8BytesBoundary => write!(
803 fmt,
804 "Message was not aligned by 8 bytes boundary. Either ensure that message is properly aligned or compile `capnp` crate with \"unaligned\" feature enabled."
805 ),
806 Self::NestingLimitExceeded => write!(fmt, "nesting limit exceeded"),
807 Self::NotAStruct => write!(fmt, "not a struct"),
808 Self::OnlyOneOfTheSectionPointersIsPointingToOurself => write!(
809 fmt,
810 "Only one of the section pointers is pointing to ourself"
811 ),
812 Self::PackedInputDidNotEndCleanlyOnASegmentBoundary => write!(
813 fmt,
814 "Packed input did not end cleanly on a segment boundary."
815 ),
816 Self::PrematureEndOfFile => write!(fmt, "Premature end of file"),
817 Self::PrematureEndOfPackedInput => write!(fmt, "Premature end of packed input."),
818 Self::ReadLimitExceeded => write!(fmt, "Read limit exceeded"),
819 Self::SettingDynamicCapabilitiesIsUnsupported => {
820 write!(fmt, "setting dynamic capabilities is unsupported")
821 }
822 Self::StructReaderHadBitwidthOtherThan1 => {
823 write!(fmt, "struct reader had bitwidth other than 1")
824 }
825 Self::TextBlobMissingNULTerminator => write!(fmt, "Text blob missing NUL terminator."),
826 Self::TextContainsNonUtf8Data(e) => write!(fmt, "Text contains non-utf8 data: {e}"),
827 Self::TriedToReadFromNullArena => write!(fmt, "Tried to read from null arena"),
828 Self::TypeMismatch => write!(fmt, "type mismatch"),
829 Self::UnalignedSegment => write!(
830 fmt,
831 "Detected unaligned segment. You must either ensure all of your segments are 8-byte aligned, or you must enable the \"unaligned\" feature in the capnp crate"
832 ),
833 Self::UnexpectedFarPointer => write!(fmt, "Unexpected far pointer"),
834 Self::UnknownPointerType => write!(fmt, "Unknown pointer type."),
835 }
836 }
837}
838
839impl core::fmt::Display for Error {
840 fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
841 let extra = self.extra();
842 if extra.is_empty() {
843 write!(fmt, "{}", self.kind)
844 } else {
845 write!(fmt, "{}: {extra}", self.kind)
846 }
847 }
848}
849
850impl core::error::Error for Error {
851 fn description(&self) -> &str {
852 self.extra()
853 }
854 fn cause(&self) -> Option<&dyn ::core::error::Error> {
855 None
856 }
857}
858
859pub enum OutputSegments<'a> {
862 SingleSegment([&'a [u8]; 1]),
863
864 #[cfg(feature = "alloc")]
865 MultiSegment(alloc::vec::Vec<&'a [u8]>),
866}
867
868impl<'a> core::ops::Deref for OutputSegments<'a> {
869 type Target = [&'a [u8]];
870 fn deref(&self) -> &[&'a [u8]] {
871 match self {
872 OutputSegments::SingleSegment(s) => s,
873
874 #[cfg(feature = "alloc")]
875 OutputSegments::MultiSegment(v) => v,
876 }
877 }
878}
879
880impl message::ReaderSegments for OutputSegments<'_> {
881 fn get_segment(&self, id: u32) -> Option<&[u8]> {
882 match self {
883 OutputSegments::SingleSegment(s) => s.get(id as usize).copied(),
884
885 #[cfg(feature = "alloc")]
886 OutputSegments::MultiSegment(v) => v.get(id as usize).copied(),
887 }
888 }
889}
890
891#[cfg(test)]
892mod tests {
893 use super::*;
894
895 #[test]
896 #[cfg(target_pointer_width = "64")]
897 fn error_size() {
898 assert_eq!(core::mem::size_of::<ErrorKind>(), 24);
899 #[cfg(feature = "alloc")]
900 assert_eq!(core::mem::size_of::<Error>(), 56);
901 #[cfg(not(feature = "alloc"))]
902 assert_eq!(core::mem::size_of::<Error>(), 24);
903 }
904
905 #[test]
906 fn error_from_kind_extra_is_empty() {
907 let e = Error::from_kind(ErrorKind::NotAStruct);
908 assert_eq!(e.extra(), "");
909 }
910
911 #[test]
912 #[cfg(feature = "alloc")]
913 fn error_details() {
914 let mut e = Error::failed("foo".into());
915 assert_eq!(e.extra(), "foo");
916 assert!(e.get_details().is_empty());
917 assert_eq!(e.get_detail(123), None);
918
919 e.set_detail(123, b"foo".to_vec());
920 e.set_detail(456, b"bar".to_vec());
921 assert_eq!(e.get_detail(123), Some(&b"foo"[..]));
922 assert_eq!(e.get_detail(456), Some(&b"bar"[..]));
923 assert_eq!(e.get_detail(789), None);
924 assert_eq!(e.get_details().len(), 2);
925
926 e.set_detail(123, b"baz".to_vec());
928 assert_eq!(e.get_detail(123), Some(&b"baz"[..]));
929 assert_eq!(
930 e.get_details(),
931 &[
932 ErrorDetail {
933 id: 123,
934 data: b"baz".to_vec(),
935 },
936 ErrorDetail {
937 id: 456,
938 data: b"bar".to_vec(),
939 },
940 ]
941 );
942
943 let mut e2 = e.clone();
944 assert_eq!(e2.extra(), "foo");
945 assert_eq!(e2.get_detail(123), Some(&b"baz"[..]));
946 assert_eq!(e2.get_detail(456), Some(&b"bar"[..]));
947
948 assert_eq!(e2.release_detail(123), Some(b"baz".to_vec()));
949 assert_eq!(e2.get_detail(123), None);
950 assert_eq!(e2.get_detail(456), Some(&b"bar"[..]));
951 assert_eq!(e2.release_detail(123), None);
952
953 assert_eq!(e2.release_detail(456), Some(b"bar".to_vec()));
955 assert!(e2.details.is_none());
956 assert_eq!(e2.extra(), "foo");
957
958 let mut e3 = Error::from_kind(ErrorKind::NotAStruct);
960 e3.set_detail(1, vec![]);
961 assert_eq!(e3.get_detail(1), Some(&b""[..]));
962 assert_eq!(e3.release_detail(1), Some(vec![]));
963 assert!(e3.details.is_none());
964 }
965}