Created
September 9, 2018 10:04
-
-
Save tesaguri/0032c342e6a3a9593df9a4a31b6dc585 to your computer and use it in GitHub Desktop.
Converting a `Display` into another `Display`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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