1use alloc::boxed::Box;
4use core::fmt;
5use std::io;
6
7use crate::error;
8
9#[non_exhaustive]
11#[derive(Debug)]
12pub enum Format {
13 #[non_exhaustive]
15 InsufficientTypeInformation,
16 InvalidComponent(&'static str),
20 ComponentRange(Box<error::ComponentRange>),
22 StdIo(io::Error),
24}
25
26impl fmt::Display for Format {
27 #[inline]
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 match self {
30 Self::InsufficientTypeInformation => f.write_str(
31 "The type being formatted does not contain sufficient information to format a \
32 component.",
33 ),
34 Self::InvalidComponent(component) => write!(
35 f,
36 "The {component} component cannot be formatted into the requested format."
37 ),
38 Self::ComponentRange(err) => err.fmt(f),
39 Self::StdIo(err) => err.fmt(f),
40 }
41 }
42}
43
44impl From<error::ComponentRange> for Format {
45 #[inline]
46 fn from(err: error::ComponentRange) -> Self {
47 Self::ComponentRange(Box::new(err))
48 }
49}
50
51impl From<io::Error> for Format {
52 #[inline]
53 fn from(err: io::Error) -> Self {
54 Self::StdIo(err)
55 }
56}
57
58impl TryFrom<Format> for error::ComponentRange {
59 type Error = error::DifferentVariant;
60
61 #[inline]
62 fn try_from(err: Format) -> Result<Self, Self::Error> {
63 match err {
64 Format::ComponentRange(err) => Ok(*err),
65 _ => Err(error::DifferentVariant),
66 }
67 }
68}
69
70impl TryFrom<Format> for io::Error {
71 type Error = error::DifferentVariant;
72
73 #[inline]
74 fn try_from(err: Format) -> Result<Self, Self::Error> {
75 match err {
76 Format::StdIo(err) => Ok(err),
77 _ => Err(error::DifferentVariant),
78 }
79 }
80}
81
82impl core::error::Error for Format {
83 #[inline]
84 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
85 match self {
86 Self::InsufficientTypeInformation | Self::InvalidComponent(_) => None,
87 Self::ComponentRange(err) => Some(&**err),
88 Self::StdIo(err) => Some(err),
89 }
90 }
91}
92
93impl From<Format> for crate::Error {
94 #[inline]
95 fn from(original: Format) -> Self {
96 Self::Format(original)
97 }
98}
99
100impl TryFrom<crate::Error> for Format {
101 type Error = error::DifferentVariant;
102
103 #[inline]
104 fn try_from(err: crate::Error) -> Result<Self, Self::Error> {
105 match err {
106 crate::Error::Format(err) => Ok(err),
107 _ => Err(error::DifferentVariant),
108 }
109 }
110}
111
112#[cfg(feature = "serde")]
113impl Format {
114 #[doc(hidden)] #[inline]
117 pub fn into_invalid_serde_value<S: serde::Serializer>(self) -> S::Error {
118 use serde::ser::Error;
119 S::Error::custom(self)
120 }
121}