1#[cfg(not(feature = "defmt"))]
26pub trait MatterError: Copy + core::fmt::Debug {}
27
28#[cfg(not(feature = "defmt"))]
29impl<T> MatterError for T where T: Copy + core::fmt::Debug {}
30
31#[cfg(feature = "defmt")]
37pub trait MatterError: Copy + core::fmt::Debug + defmt::Format {}
38
39#[cfg(feature = "defmt")]
40impl<T> MatterError for T where T: Copy + core::fmt::Debug + defmt::Format {}
41
42pub struct Error2<T> {
44 code: T,
45 #[cfg(all(feature = "std", feature = "backtrace"))]
46 backtrace: std::backtrace::Backtrace,
47 #[cfg(all(feature = "alloc", feature = "backtrace"))]
48 inner: Option<Box<dyn core::error::Error + Send + Sync>>,
49}
50
51impl<T: MatterError> Error2<T> {
52 pub fn new(code: T) -> Self {
53 Self {
54 code,
55 #[cfg(all(feature = "std", feature = "backtrace"))]
56 backtrace: std::backtrace::Backtrace::capture(),
57 #[cfg(all(feature = "alloc", feature = "backtrace"))]
58 inner: None,
59 }
60 }
61
62 #[cfg(all(feature = "alloc", feature = "backtrace"))]
63 pub fn new_with_details(
64 code: T,
65 detailed_err: Box<dyn core::error::Error + Send + Sync>,
66 ) -> Self {
67 Self {
68 code,
69 #[cfg(feature = "std")]
70 backtrace: std::backtrace::Backtrace::capture(),
71 inner: Some(detailed_err),
72 }
73 }
74
75 pub const fn code(&self) -> T {
76 self.code
77 }
78
79 #[cfg(all(feature = "std", feature = "backtrace"))]
80 pub const fn backtrace(&self) -> &std::backtrace::Backtrace {
81 &self.backtrace
82 }
83
84 #[cfg(all(feature = "alloc", feature = "backtrace"))]
85 pub fn details(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
86 self.inner.as_ref().map(|err| err.as_ref())
87 }
88
89 #[cfg(all(feature = "alloc", feature = "backtrace"))]
94 fn keep_as_source(&self) -> bool {
95 #[cfg(feature = "std")]
96 {
97 self.inner.is_some()
98 || self.backtrace.status() == std::backtrace::BacktraceStatus::Captured
99 }
100
101 #[cfg(not(feature = "std"))]
102 {
103 true
104 }
105 }
106}
107
108impl<T: MatterError> From<T> for Error2<T> {
109 fn from(value: T) -> Self {
110 Error2::new(value)
111 }
112}
113
114impl<T: MatterError> core::fmt::Debug for Error2<T> {
115 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
116 write!(f, "Error::{:?}", self.code)?;
118
119 #[cfg(all(feature = "std", feature = "backtrace"))]
120 {
121 if self.backtrace.status() == std::backtrace::BacktraceStatus::Captured {
122 write!(f, "\n{}", self.backtrace)?;
123 }
124 }
125
126 #[cfg(all(feature = "alloc", feature = "backtrace"))]
127 {
128 if let Some(inner) = &self.inner {
129 write!(f, "\nCaused by: {:?}", inner)?;
130 }
131 }
132
133 Ok(())
134 }
135}
136
137impl<T: MatterError> core::fmt::Display for Error2<T> {
138 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139 #[cfg(all(feature = "alloc", feature = "backtrace"))]
140 {
141 let err_msg = self
142 .inner
143 .as_ref()
144 .map_or(Default::default(), |err| err.to_string());
145
146 if err_msg.is_empty() {
147 write!(f, "{:?}", self.code())
148 } else {
149 write!(f, "{:?}: {}", self.code(), err_msg)
150 }
151 }
152 #[cfg(not(all(feature = "alloc", feature = "backtrace")))]
153 {
154 write!(f, "{:?}", self.code())
155 }
156 }
157}
158
159#[cfg(feature = "defmt")]
160impl<T: MatterError> defmt::Format for Error2<T> {
161 fn format(&self, f: defmt::Formatter<'_>) {
162 defmt::write!(f, "{:?}", self.code())
163 }
164}
165
166impl<T: MatterError> core::error::Error for Error2<T> {
167 #[cfg(all(feature = "alloc", feature = "backtrace"))]
168 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
169 self.inner
170 .as_ref()
171 .map(|e| e.as_ref() as &(dyn core::error::Error + 'static))
172 }
173}
174
175pub type BufferError = Error2<BufferErrorCode>;
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
180#[cfg_attr(feature = "defmt", derive(defmt::Format))]
181pub enum BufferErrorCode {
182 BufferTooSmall,
184 UnexpectedEof,
186}
187
188pub type Base38Error = Error2<Base38ErrorCode>;
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
192#[cfg_attr(feature = "defmt", derive(defmt::Format))]
193pub enum Base38ErrorCode {
194 InvalidCharacter,
196 InvalidLength,
198 OutputTooSmall,
200}
201
202impl From<BufferErrorCode> for ErrorCode {
209 fn from(value: BufferErrorCode) -> Self {
210 match value {
211 BufferErrorCode::BufferTooSmall => ErrorCode::BufferTooSmall,
212 BufferErrorCode::UnexpectedEof => ErrorCode::TruncatedPacket,
213 }
214 }
215}
216
217impl From<BufferErrorCode> for Error {
218 fn from(value: BufferErrorCode) -> Self {
219 ErrorCode::from(value).into()
220 }
221}
222
223impl<T> From<Error2<T>> for Error
233where
234 T: MatterError + Into<ErrorCode> + Send + Sync + 'static,
235{
236 fn from(value: Error2<T>) -> Self {
237 #[cfg(all(feature = "alloc", feature = "backtrace"))]
238 {
239 if value.keep_as_source() {
240 return Self::new_with_details(value.code().into(), Box::new(value));
241 }
242 }
243
244 Self::new(value.code().into())
245 }
246}
247
248use core::{array::TryFromSliceError, str::Utf8Error};
253
254#[cfg(all(feature = "alloc", feature = "backtrace"))]
255use alloc::{boxed::Box, string::ToString};
256
257use crate::io;
258
259#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
268#[cfg_attr(feature = "defmt", derive(defmt::Format))]
269pub enum ErrorCode {
270 InvalidData,
273 TLVTypeMismatch,
274 NotFound,
275 Invalid,
276 ConstraintError,
277 TLVUnexpectedNull,
279 NoSpace,
288 AlreadyExists,
289 AttributeNotFound,
290 AttributeIsCustom,
291 BufferTooSmall,
292 ClusterNotFound,
293 CommandNotFound,
294 Duplicate,
295 NodeNotFound,
296 EndpointNotFound,
297 EventNotFound,
298 InvalidAction,
299 InvalidCommand,
300 FailSafeRequired,
301 NeedsTimedInteraction,
302 DynamicConstraintError,
303 InvalidDataType,
304 UnsupportedAccess,
305 ResourceExhausted,
306 Busy,
307 DataVersionMismatch,
308 BtpError,
309 MdnsError,
310 NoCommand,
311 NoEndpoint,
312 NoExchange,
313 NoFabricId,
314 NoHandler,
315 NoNetworkInterface,
316 DBusError,
317 NoNodeId,
318 NoMemory,
319 NoSession,
320 NoSharedTrustRoots,
323 NoSpaceExchanges,
324 NoSpaceSessions,
325 TxTimeout,
326 RxTimeout,
327 NoTagFound,
328 PacketPoolExhaust,
329 StdIoError,
330 SysTimeFail,
331 InvalidAAD,
332 InvalidTransportType,
336 InvalidKeyLength,
337 InvalidOpcode,
338 InvalidProto,
339 InvalidPeerAddr,
340 InvalidAuthKey,
342 InvalidSignature,
343 InvalidState,
344 InvalidInState,
349 InvalidTime,
350 InvalidArgument,
351 RwLock,
352 TLVNotFound,
353 TruncatedPacket,
354 Utf8Fail,
355 GennCommInvalidAuthentication,
356 NocInvalidNoc,
357 NocInvalidPublicKey,
358 NocMissingCsr,
359 NocFabricTableFull,
360 NocFabricConflict,
361 NocLabelConflict,
362 NocInvalidFabricIndex,
363 NocInvalidAdminSubject,
364 Cancelled,
366 Failure,
367 CdInvalidFormat,
369 CdInvalidSignature,
370 CdSigningKeyNotFound,
371 CdInvalidVendorId,
372 CdInvalidProductId,
373 CdInvalidPaa,
374}
375
376impl From<ErrorCode> for Error {
377 fn from(code: ErrorCode) -> Self {
378 Self::new(code)
379 }
380}
381
382pub struct Error {
383 code: ErrorCode,
384 #[cfg(all(feature = "std", feature = "backtrace"))]
385 backtrace: std::backtrace::Backtrace,
386 #[cfg(all(feature = "alloc", feature = "backtrace"))]
387 inner: Option<Box<dyn core::error::Error + Send + Sync>>,
388}
389
390impl Error {
391 pub fn new(code: ErrorCode) -> Self {
392 Self {
393 code,
394 #[cfg(all(feature = "std", feature = "backtrace"))]
395 backtrace: std::backtrace::Backtrace::capture(),
396 #[cfg(all(feature = "alloc", feature = "backtrace"))]
397 inner: None,
398 }
399 }
400
401 #[cfg(all(feature = "alloc", feature = "backtrace"))]
402 pub fn new_with_details(
403 code: ErrorCode,
404 detailed_err: Box<dyn core::error::Error + Send + Sync>,
405 ) -> Self {
406 Self {
407 code,
408 #[cfg(feature = "std")]
409 backtrace: std::backtrace::Backtrace::capture(),
410 inner: Some(detailed_err),
411 }
412 }
413
414 pub const fn code(&self) -> ErrorCode {
415 self.code
416 }
417
418 pub const fn is_peer_unresponsive(&self) -> bool {
420 matches!(self.code, ErrorCode::TxTimeout | ErrorCode::RxTimeout)
421 }
422
423 #[cfg(all(feature = "std", feature = "backtrace"))]
424 pub const fn backtrace(&self) -> &std::backtrace::Backtrace {
425 &self.backtrace
426 }
427
428 #[cfg(all(feature = "alloc", feature = "backtrace"))]
429 pub fn details(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
430 self.inner.as_ref().map(|err| err.as_ref())
431 }
432}
433
434#[cfg(all(feature = "std", feature = "backtrace"))]
435impl From<std::io::Error> for Error {
436 fn from(e: std::io::Error) -> Self {
437 Self::new_with_details(ErrorCode::StdIoError, Box::new(e))
438 }
439}
440
441#[cfg(all(feature = "std", not(feature = "backtrace")))]
442impl From<std::io::Error> for Error {
443 fn from(_e: std::io::Error) -> Self {
444 Self::new(ErrorCode::StdIoError)
445 }
446}
447
448#[cfg(feature = "std")]
449impl<T> From<std::sync::PoisonError<T>> for Error {
450 fn from(_e: std::sync::PoisonError<T>) -> Self {
451 Self::new(ErrorCode::RwLock)
452 }
453}
454
455#[cfg(all(target_os = "linux", feature = "bluer", not(feature = "backtrace")))]
456impl From<bluer::Error> for Error {
457 fn from(e: bluer::Error) -> Self {
458 error!("Error in BTP: {}", display2format!(e));
461 Self::new(ErrorCode::BtpError)
462 }
463}
464
465#[cfg(all(target_os = "linux", feature = "bluer", feature = "backtrace"))]
466impl From<bluer::Error> for Error {
467 fn from(e: bluer::Error) -> Self {
468 Self::new_with_details(ErrorCode::BtpError, Box::new(e))
469 }
470}
471
472#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
473impl From<zbus::Error> for Error {
474 fn from(e: zbus::Error) -> Self {
475 error!("Error in D-Bus: {}", display2format!(e));
478 Self::new(ErrorCode::DBusError)
479 }
480}
481
482#[cfg(all(feature = "zbus", feature = "backtrace"))]
483impl From<zbus::Error> for Error {
484 fn from(e: zbus::Error) -> Self {
485 Self::new_with_details(ErrorCode::DBusError, Box::new(e))
486 }
487}
488
489#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
490impl From<zbus::zvariant::Error> for Error {
491 fn from(e: zbus::zvariant::Error) -> Self {
492 error!("Error in D-Bus: {}", display2format!(e));
495 Self::new(ErrorCode::DBusError)
496 }
497}
498
499#[cfg(all(feature = "zbus", feature = "backtrace"))]
500impl From<zbus::zvariant::Error> for Error {
501 fn from(e: zbus::zvariant::Error) -> Self {
502 Self::new_with_details(ErrorCode::DBusError, Box::new(e))
503 }
504}
505
506#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
507impl From<zbus::fdo::Error> for Error {
508 fn from(e: zbus::fdo::Error) -> Self {
509 error!("Error in D-Bus: {}", display2format!(e));
512 Self::new(ErrorCode::DBusError)
513 }
514}
515
516#[cfg(all(feature = "zbus", feature = "backtrace"))]
517impl From<zbus::fdo::Error> for Error {
518 fn from(e: zbus::fdo::Error) -> Self {
519 Self::new_with_details(ErrorCode::DBusError, Box::new(e))
520 }
521}
522
523#[cfg(feature = "std")]
524impl From<std::time::SystemTimeError> for Error {
525 fn from(_e: std::time::SystemTimeError) -> Self {
526 Error::new(ErrorCode::SysTimeFail)
527 }
528}
529
530impl From<TryFromSliceError> for Error {
531 fn from(_e: TryFromSliceError) -> Self {
532 Self::new(ErrorCode::Invalid)
533 }
534}
535
536impl From<Utf8Error> for Error {
537 fn from(_e: Utf8Error) -> Self {
538 Self::new(ErrorCode::Utf8Fail)
539 }
540}
541
542impl<T: num_enum::TryFromPrimitive> From<num_enum::TryFromPrimitiveError<T>> for Error {
543 fn from(_e: num_enum::TryFromPrimitiveError<T>) -> Self {
544 Self::new(ErrorCode::Invalid)
545 }
546}
547
548impl core::fmt::Debug for Error {
549 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
550 write!(f, "Error::{:?}", self.code)?;
551
552 #[cfg(all(feature = "std", feature = "backtrace"))]
553 {
554 if self.backtrace.status() == std::backtrace::BacktraceStatus::Captured {
555 write!(f, "\n{}", self.backtrace)?;
556 }
557 }
558
559 #[cfg(all(feature = "alloc", feature = "backtrace"))]
560 {
561 if let Some(inner) = &self.inner {
562 write!(f, "\nCaused by: {:?}", inner)?;
563 }
564 }
565
566 Ok(())
567 }
568}
569
570impl core::fmt::Display for Error {
571 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
572 #[cfg(all(feature = "alloc", feature = "backtrace"))]
573 {
574 let err_msg = self
575 .inner
576 .as_ref()
577 .map_or(Default::default(), |err| err.to_string());
578
579 if err_msg.is_empty() {
580 write!(f, "{:?}", self.code())
581 } else {
582 write!(f, "{:?}: {}", self.code(), err_msg)
583 }
584 }
585 #[cfg(not(all(feature = "alloc", feature = "backtrace")))]
586 {
587 write!(f, "{:?}", self.code())
588 }
589 }
590}
591
592#[cfg(feature = "defmt")]
593impl defmt::Format for Error {
594 fn format(&self, f: defmt::Formatter<'_>) {
595 defmt::write!(f, "{:?}", self.code())
596 }
597}
598
599impl core::error::Error for Error {
600 #[cfg(all(feature = "alloc", feature = "backtrace"))]
601 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
602 self.inner
603 .as_ref()
604 .map(|e| e.as_ref() as &(dyn core::error::Error + 'static))
605 }
606}
607
608impl io::Error for Error {
609 fn kind(&self) -> io::ErrorKind {
610 io::ErrorKind::Other
611 }
612}
613
614#[cfg(test)]
615#[cfg_attr(coverage_nightly, coverage(off))]
616mod tests {
617 use core::str::from_utf8;
618
619 use super::{Error, ErrorCode};
620
621 const CODES: &[ErrorCode] = &[
624 ErrorCode::AlreadyExists,
625 ErrorCode::AttributeNotFound,
626 ErrorCode::BufferTooSmall,
627 ErrorCode::ConstraintError,
628 ErrorCode::Invalid,
629 ErrorCode::InvalidData,
630 ErrorCode::InvalidTransportType,
631 ErrorCode::NoSpace,
632 ErrorCode::TxTimeout,
633 ErrorCode::RxTimeout,
634 ErrorCode::StdIoError,
635 ErrorCode::SysTimeFail,
636 ErrorCode::RwLock,
637 ErrorCode::Utf8Fail,
638 ErrorCode::Failure,
639 ErrorCode::CdInvalidPaa,
640 ];
641
642 #[test]
643 fn code_roundtrips_through_error() {
644 for code in CODES {
645 let err = Error::new(*code);
646 assert_eq!(err.code(), *code);
647
648 let err: Error = (*code).into();
649 assert_eq!(err.code(), *code);
650
651 let res: Result<(), Error> = (|| {
653 Err(*code)?;
654 Ok(())
655 })();
656 assert_eq!(res.unwrap_err().code(), *code);
657 }
658 }
659
660 #[test]
661 fn error_code_equality_and_hash() {
662 use std::collections::HashSet;
663
664 assert_eq!(ErrorCode::NoSpace, ErrorCode::NoSpace);
665 assert_ne!(ErrorCode::NoSpace, ErrorCode::NoSpaceExchanges);
666
667 let set: HashSet<ErrorCode> = CODES.iter().copied().collect();
668 assert_eq!(set.len(), CODES.len());
669
670 let a = ErrorCode::Busy;
672 let b = a;
673 assert_eq!(a, b);
674 }
675
676 #[test]
677 fn display_and_debug_do_not_panic() {
678 for code in CODES {
679 let err = Error::new(*code);
680
681 let display = format!("{err}");
682 let debug = format!("{err:?}");
683 let code_debug = format!("{code:?}");
684
685 assert!(
687 display.starts_with(&code_debug),
688 "{display} vs {code_debug}"
689 );
690 assert!(
691 debug.starts_with(&format!("Error::{code_debug}")),
692 "{debug}"
693 );
694 }
695 }
696
697 #[test]
698 fn is_peer_unresponsive_only_for_timeouts() {
699 assert!(Error::new(ErrorCode::TxTimeout).is_peer_unresponsive());
700 assert!(Error::new(ErrorCode::RxTimeout).is_peer_unresponsive());
701
702 for code in CODES {
703 if !matches!(code, ErrorCode::TxTimeout | ErrorCode::RxTimeout) {
704 assert!(!Error::new(*code).is_peer_unresponsive(), "{code:?}");
705 }
706 }
707 }
708
709 #[test]
710 fn core_conversions() {
711 let slice_err = <[u8; 4]>::try_from(&[1u8, 2, 3][..]).unwrap_err();
712 assert_eq!(Error::from(slice_err).code(), ErrorCode::Invalid);
713
714 let invalid: Vec<u8> = (0..2).map(|i| 0xff - i as u8).collect();
716 let utf8_err = from_utf8(&invalid).unwrap_err();
717 assert_eq!(Error::from(utf8_err).code(), ErrorCode::Utf8Fail);
718
719 #[derive(Debug, Copy, Clone, num_enum::TryFromPrimitive)]
720 #[repr(u8)]
721 enum Small {
722 _One = 1,
723 }
724 let prim_err = Small::try_from(9u8).unwrap_err();
725 assert_eq!(Error::from(prim_err).code(), ErrorCode::Invalid);
726 }
727
728 #[test]
729 fn error_is_a_core_error() {
730 let err = Error::new(ErrorCode::Busy);
731 let dyn_err: &dyn core::error::Error = &err;
732
733 assert!(dyn_err.source().is_none());
735
736 let boxed: Box<dyn core::error::Error + Send + Sync> = Box::new(err);
738 assert!(boxed.to_string().contains("Busy"));
739 }
740
741 #[test]
742 fn embedded_io_error_kind_is_other() {
743 use embedded_io_async::{Error as _, ErrorKind};
744
745 assert_eq!(Error::new(ErrorCode::NoSpace).kind(), ErrorKind::Other);
746 }
747
748 #[cfg(feature = "std")]
749 #[test]
750 fn std_conversions() {
751 let io = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
752 let err = Error::from(io);
753 assert_eq!(err.code(), ErrorCode::StdIoError);
754
755 let lock = std::sync::Mutex::new(());
756 let poisoned = std::sync::PoisonError::new(lock.lock().unwrap());
757 assert_eq!(Error::from(poisoned).code(), ErrorCode::RwLock);
758
759 let time_err = std::time::UNIX_EPOCH
760 .duration_since(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1))
761 .unwrap_err();
762 assert_eq!(Error::from(time_err).code(), ErrorCode::SysTimeFail);
763 }
764
765 #[cfg(all(feature = "alloc", feature = "backtrace"))]
766 #[test]
767 fn details_are_kept_and_displayed() {
768 let err = Error::new(ErrorCode::Busy);
769 assert!(err.details().is_none());
770 assert_eq!(format!("{err}"), "Busy");
771
772 let inner = std::io::Error::other("disk on fire");
773 let err = Error::new_with_details(ErrorCode::StdIoError, Box::new(inner));
774 assert_eq!(err.code(), ErrorCode::StdIoError);
775 assert!(err.details().unwrap().to_string().contains("disk on fire"));
776 assert_eq!(format!("{err}"), "StdIoError: disk on fire");
777
778 let dyn_err: &dyn core::error::Error = &err;
780 assert!(dyn_err
781 .source()
782 .unwrap()
783 .to_string()
784 .contains("disk on fire"));
785
786 #[cfg(feature = "std")]
788 {
789 let io = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
790 let err = Error::from(io);
791 assert!(err.details().unwrap().to_string().contains("gone"));
792 }
793 }
794
795 #[cfg(all(feature = "std", feature = "backtrace"))]
796 #[test]
797 fn backtrace_capture_does_not_panic() {
798 let err = Error::new(ErrorCode::Failure);
799
800 let _ = err.backtrace().status();
802 let _ = format!("{}", err.backtrace());
803
804 let debug = format!("{err:?}");
806 assert!(debug.starts_with("Error::Failure"));
807 if err.backtrace().status() != std::backtrace::BacktraceStatus::Captured {
808 assert_eq!(debug, "Error::Failure");
809 }
810 }
811
812 #[cfg(all(feature = "alloc", feature = "backtrace"))]
813 #[test]
814 fn converted_error_is_kept_as_source() {
815 use super::{BufferError, BufferErrorCode};
816
817 let err = Error::from(BufferError::new_with_details(
819 BufferErrorCode::UnexpectedEof,
820 Box::new(std::io::Error::other("short read")),
821 ));
822 assert_eq!(err.code(), ErrorCode::TruncatedPacket);
823
824 let source = core::error::Error::source(&err).unwrap();
825 let source = source.downcast_ref::<BufferError>().unwrap();
826 assert_eq!(source.code(), BufferErrorCode::UnexpectedEof);
827
828 assert_eq!(
829 format!("{err}"),
830 "TruncatedPacket: UnexpectedEof: short read"
831 );
832
833 let debug = format!("{err:?}");
834 assert!(debug.starts_with("Error::TruncatedPacket"));
835 assert!(debug.contains("\nCaused by: Error::UnexpectedEof"));
836 assert!(debug.contains("short read"));
837
838 #[cfg(feature = "std")]
840 {
841 let source = BufferError::new(BufferErrorCode::UnexpectedEof);
842 let captured = source.backtrace().status() == std::backtrace::BacktraceStatus::Captured;
843
844 assert_eq!(Error::from(source).details().is_some(), captured);
845 }
846 }
847
848 #[cfg(all(feature = "alloc", feature = "backtrace"))]
849 #[test]
850 fn details_can_be_downcast() {
851 use super::{BufferError, BufferErrorCode};
852
853 let err = Error::from(BufferError::new_with_details(
854 BufferErrorCode::UnexpectedEof,
855 Box::new(std::io::Error::other("short read")),
856 ));
857
858 let source = err.details().unwrap().downcast_ref::<BufferError>();
860 let source = source.unwrap();
861 assert_eq!(source.code(), BufferErrorCode::UnexpectedEof);
862
863 let io = source.details().unwrap().downcast_ref::<std::io::Error>();
864 assert_eq!(io.unwrap().to_string(), "short read");
865 }
866}