derive_more/
convert.rs

1//! Definitions used in derived implementations of [`core::convert`] traits.
2
3#[cfg(feature = "try_from")]
4pub use self::try_from::TryFromReprError;
5#[cfg(feature = "try_into")]
6pub use self::try_into::TryIntoError;
7
8#[cfg(feature = "try_from")]
9mod try_from {
10    use core::fmt;
11
12    /// Error returned by the derived [`TryFrom`] implementation on enums to
13    /// convert from their repr.
14    ///
15    /// [`TryFrom`]: macro@crate::TryFrom
16    #[derive(Clone, Copy, Debug)]
17    pub struct TryFromReprError<T> {
18        /// Original input value which failed to convert via the derived
19        /// [`TryFrom`] implementation.
20        ///
21        /// [`TryFrom`]: macro@crate::TryFrom
22        pub input: T,
23    }
24
25    impl<T> TryFromReprError<T> {
26        #[doc(hidden)]
27        #[must_use]
28        #[inline]
29        pub const fn new(input: T) -> Self {
30            Self { input }
31        }
32    }
33
34    // `T`, as a discriminant, should only be an integer type, and therefore be `Debug`.
35    impl<T: fmt::Debug> fmt::Display for TryFromReprError<T> {
36        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37            write!(
38                f,
39                "`{:?}` does not correspond to a unit variant",
40                self.input
41            )
42        }
43    }
44
45    #[cfg(feature = "std")]
46    // `T` should only be an integer type and therefore be debug
47    impl<T: fmt::Debug> std::error::Error for TryFromReprError<T> {}
48}
49
50#[cfg(feature = "try_into")]
51mod try_into {
52    use core::fmt;
53
54    /// Error returned by the derived [`TryInto`] implementation.
55    ///
56    /// [`TryInto`]: macro@crate::TryInto
57    #[derive(Clone, Copy, Debug)]
58    pub struct TryIntoError<T> {
59        /// Original input value which failed to convert via the derived
60        /// [`TryInto`] implementation.
61        ///
62        /// [`TryInto`]: macro@crate::TryInto
63        pub input: T,
64        variant_names: &'static str,
65        output_type: &'static str,
66    }
67
68    impl<T> TryIntoError<T> {
69        #[doc(hidden)]
70        #[must_use]
71        #[inline]
72        pub const fn new(
73            input: T,
74            variant_names: &'static str,
75            output_type: &'static str,
76        ) -> Self {
77            Self {
78                input,
79                variant_names,
80                output_type,
81            }
82        }
83    }
84
85    impl<T> fmt::Display for TryIntoError<T> {
86        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87            write!(
88                f,
89                "Only {} can be converted to {}",
90                self.variant_names, self.output_type,
91            )
92        }
93    }
94
95    #[cfg(feature = "std")]
96    impl<T: fmt::Debug> std::error::Error for TryIntoError<T> {}
97}