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: &&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 | impl std::error::Error for Format { |
59 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
60 | match *self { |
61 | Self::InsufficientTypeInformation | Self::InvalidComponent(_) => None, |
62 | Self::StdIo(ref err: &Error) => Some(err), |
63 | } |
64 | } |
65 | } |
66 | |
67 | impl From<Format> for crate::Error { |
68 | fn from(original: Format) -> Self { |
69 | Self::Format(original) |
70 | } |
71 | } |
72 | |
73 | impl TryFrom<crate::Error> for Format { |
74 | type Error = error::DifferentVariant; |
75 | |
76 | fn try_from(err: crate::Error) -> Result<Self, Self::Error> { |
77 | match err { |
78 | crate::Error::Format(err: Format) => Ok(err), |
79 | _ => Err(error::DifferentVariant), |
80 | } |
81 | } |
82 | } |
83 | |
84 | #[cfg (feature = "serde" )] |
85 | impl Format { |
86 | /// Obtain an error type for the serializer. |
87 | #[doc (hidden)] // Exposed only for the `declare_format_string` macro |
88 | pub fn into_invalid_serde_value<S: serde::Serializer>(self) -> S::Error { |
89 | use serde::ser::Error; |
90 | S::Error::custom(self) |
91 | } |
92 | } |
93 | |