Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add backwards compatible support for fmt::Write #407

Closed
wants to merge 12 commits into from
19 changes: 19 additions & 0 deletions src/date.rs
Expand Up @@ -824,6 +824,25 @@ impl Date {
output: &mut impl io::Write,
format: &(impl Formattable + ?Sized),
) -> Result<usize, error::Format> {
format.format_into_old(output, Some(self), None, None)
}

/// Format the `Date` using the provided [format description](crate::format_description).
///
/// Exactly like [`Date::format_into`] but accepts a [`fmt::Write`] instead of an [`io::Write`]
/// ```rust
/// # use time::{format_description, macros::date};
/// let format = format_description::parse("[year]-[month]-[day]")?;
/// let mut buf = String::new();
/// date!(2020 - 01 - 02).format_into_fmt_writer(&mut buf, &format)?;
/// assert_eq!(buf, "2020-01-02");
/// # Ok::<_, time::Error>(())
/// ```
pub fn format_into_fmt_writer(
self,
output: &mut impl fmt::Write,
format: &(impl Formattable + ?Sized),
) -> Result<(), error::Format> {
format.format_into(output, Some(self), None, None)
}

Expand Down
10 changes: 10 additions & 0 deletions src/error/format.rs
Expand Up @@ -21,6 +21,8 @@ pub enum Format {
InvalidComponent(&'static str),
/// A value of `std::io::Error` was returned internally.
StdIo(io::Error),
/// A value of `std::fmt::Error` was returned internally.
StdFmt(fmt::Error),
}

impl fmt::Display for Format {
Expand All @@ -36,6 +38,7 @@ impl fmt::Display for Format {
component
),
Self::StdIo(err) => err.fmt(f),
Self::StdFmt(err) => err.fmt(f),
}
}
}
Expand All @@ -46,6 +49,12 @@ impl From<io::Error> for Format {
}
}

impl From<fmt::Error> for Format {
fn from(err: fmt::Error) -> Self {
Self::StdFmt(err)
}
}

impl TryFrom<Format> for io::Error {
type Error = error::DifferentVariant;

Expand All @@ -63,6 +72,7 @@ impl std::error::Error for Format {
match *self {
Self::InsufficientTypeInformation | Self::InvalidComponent(_) => None,
Self::StdIo(ref err) => Some(err),
Self::StdFmt(ref err) => Some(err),
}
}
}
Expand Down