1 | //! Error formatting a struct |
2 | |
3 | use core::fmt; |
4 | use std::io; |
5 | |
6 | use crate::error; |
7 | |
8 | /// An error occurred when formatting. |
9 | #[non_exhaustive ] |
10 | #[allow (missing_copy_implementations)] |
11 | #[derive (Debug)] |
12 | pub enum Format { |
13 | /// The type being formatted does not contain sufficient information to format a component. |
14 | #[non_exhaustive ] |
15 | InsufficientTypeInformation, |
16 | /// The component named has a value that cannot be formatted into the requested format. |
17 | /// |
18 | /// This variant is only returned when using well-known formats. |
19 | InvalidComponent(&'static str), |
20 | /// A value of `std::io::Error` was returned internally. |
21 | StdIo(io::Error), |
22 | } |
23 | |
24 | impl fmt::Display for Format { |
25 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
26 | match self { |
27 | Self::InsufficientTypeInformation => f.write_str( |
28 | data:"The type being formatted does not contain sufficient information to format a \ |
29 | data: component." , |
30 | ), |
31 | Self::InvalidComponent(component: &&'static str) => write!( |
32 | f, |
33 | "The {component} component cannot be formatted into the requested format." |
34 | ), |
35 | Self::StdIo(err: &Error) => err.fmt(f), |
36 | } |
37 | } |
38 | } |
39 | |
40 | impl From<io::Error> for Format { |
41 | fn from(err: io::Error) -> Self { |
42 | Self::StdIo(err) |
43 | } |
44 | } |
45 | |
46 | impl TryFrom<Format> for io::Error { |
47 | type Error = error::DifferentVariant; |
48 | |
49 | fn try_from(err: Format) -> Result<Self, Self::Error> { |
50 | match err { |
51 | Format::StdIo(err: Error) => Ok(err), |
52 | _ => Err(error::DifferentVariant), |
53 | } |
54 | } |
55 | } |
56 | |
57 | #[cfg (feature = "std" )] |
58 | #[allow (clippy::std_instead_of_core)] |
59 | impl std::error::Error for Format { |
60 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
61 | match *self { |
62 | Self::InsufficientTypeInformation | Self::InvalidComponent(_) => None, |
63 | Self::StdIo(ref err: &Error) => Some(err), |
64 | } |
65 | } |
66 | } |
67 | |
68 | impl From<Format> for crate::Error { |
69 | fn from(original: Format) -> Self { |
70 | Self::Format(original) |
71 | } |
72 | } |
73 | |
74 | impl TryFrom<crate::Error> for Format { |
75 | type Error = error::DifferentVariant; |
76 | |
77 | fn try_from(err: crate::Error) -> Result<Self, Self::Error> { |
78 | match err { |
79 | crate::Error::Format(err: Format) => Ok(err), |
80 | _ => Err(error::DifferentVariant), |
81 | } |
82 | } |
83 | } |
84 | |
85 | #[cfg (feature = "serde" )] |
86 | impl Format { |
87 | /// Obtain an error type for the serializer. |
88 | #[doc (hidden)] // Exposed only for the `declare_format_string` macro |
89 | pub fn into_invalid_serde_value<S: serde::Serializer>(self) -> S::Error { |
90 | use serde::ser::Error; |
91 | S::Error::custom(self) |
92 | } |
93 | } |
94 | |