Skip to content

Instantly share code, notes, and snippets.

@tesaguri
Created September 9, 2018 10:04
Show Gist options
  • Save tesaguri/0032c342e6a3a9593df9a4a31b6dc585 to your computer and use it in GitHub Desktop.
Save tesaguri/0032c342e6a3a9593df9a4a31b6dc585 to your computer and use it in GitHub Desktop.
Converting a `Display` into another `Display`
use std::fmt::{self, Display, Formatter, Write};
pub struct Uppercase<T>(T);
impl<T: Display> Display for Uppercase<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
struct Adapter<'a, 'b: 'a>(&'a mut Formatter<'b>);
impl<'a, 'b: 'a> Write for Adapter<'a, 'b> {
fn write_str(&mut self, s: &str) -> fmt::Result {
s.chars().try_for_each(|c| self.write_char(c))
}
fn write_char(&mut self, c: char) -> fmt::Result {
self.0.write_char(c.to_ascii_uppercase())
}
}
write!(Adapter(f), "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
assert_eq!("HELLO, WORLD!", Uppercase("Hello, world!").to_string());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment