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