SHARE
TWEET

Untitled

a guest Jun 25th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::fmt::{self, Write, Alignment};
  2.  
  3. struct ExtraWidth {
  4.     num: u32,
  5.     width: usize,
  6. }
  7.  
  8. impl fmt::Display for ExtraWidth {
  9.     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  10.         let width = self.width + f.width().unwrap_or(0);
  11.        
  12.         let mut buff = String::new();
  13.         write!(buff, "{}", self.num)?;
  14.        
  15.         let padding = width.saturating_sub(buff.len());
  16.         let (pre_padding, post_padding) = match f.align() {
  17.             None => (0, padding),
  18.             Some(Alignment::Left) => (0, padding),
  19.             Some(Alignment::Right) => (padding, 0),
  20.             Some(Alignment::Center) => (padding / 2, (padding + 1) / 2),
  21.         };
  22.        
  23.         for _ in 0..pre_padding {
  24.             write!(f, "{}", f.fill())?;
  25.         }
  26.  
  27.         f.write_str(&buff)?;
  28.  
  29.         for _ in 0..post_padding {
  30.             write!(f, "{}", f.fill())?;
  31.         }
  32.  
  33.         Ok(())
  34.     }
  35. }
  36.  
  37. fn main() {
  38.     println!("{:0>2}", ExtraWidth { num: 1, width: 2 });
  39. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top