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 number formatting #15

Merged
merged 2 commits into from Dec 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 0 additions & 62 deletions src/fmtf64.rs

This file was deleted.

59 changes: 0 additions & 59 deletions src/fmti64.rs

This file was deleted.

121 changes: 121 additions & 0 deletions src/fmtnum.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
macro_rules! fmtint {
($($t:ident)*) => ($(
#[allow(unused_comparisons)]
impl<'a, 'b> Formatter<'a, 'b> {
pub fn $t(&mut self, x: $t) -> Result<()> {
let ty = match self.ty() {
None => ' ',
Some(c) => c,
};

if !self.is_int_type() {
let mut msg = String::new();
write!(msg, "Unknown format code {:?} for type", ty).unwrap();
return Err(FmtError::TypeError(msg));
}

if self.precision() != None {
return Err(FmtError::TypeError("precision not allowed for integers".to_string()));
}

if self.thousands() {
return Err(FmtError::Invalid("thousands specifier not yet supported".to_string()));
}

if self.fill() == '0' && self.align() == Alignment::Right {
return Err(FmtError::Invalid("sign aware 0 padding not yet supported".to_string()));
}

let mut s = String::new();

if x >= 0 && self.sign_plus() {
self.write_str("+").unwrap();
}

if self.alternate() {
match ty {
'b' => self.write_str("0b").unwrap(),
'o' => self.write_str("0o").unwrap(),
'x' | 'X' => self.write_str("0x").unwrap(),
_ => {
let mut msg = String::new();
write!(msg, "alternate ('#') cannot be used with type {:?}", ty).unwrap();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when I first wrote this lib I didn't know about format!(). Please use that instead here. You can even get rid of msg variable alltogether.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whoops, I'll handle it in a separate commit... maybe (who really cares, haha).

Thanks for the PR!

return Err(FmtError::Invalid(msg));
}
}
}

match ty {
' ' => write!(s, "{}", x).unwrap(),
'b' => write!(s, "{:b}", x).unwrap(),
'o' => write!(s, "{:o}", x).unwrap(),
'x' => write!(s, "{:x}", x).unwrap(),
'X' => write!(s, "{:X}", x).unwrap(),
_ => unreachable!(),
}

self.str_unchecked(s.as_str())
}
})*)
}

macro_rules! fmtfloat {
($($t:ident)*) => ($(
impl<'a, 'b> Formatter<'a, 'b> {
pub fn $t(&mut self, x: $t) -> Result<()> {
let ty = match self.ty() {
None => 'f',
Some(c) => c,
};

if !self.is_float_type() {
let mut msg = String::new();
write!(msg, "Unknown format code {:?} for type", ty).unwrap();
return Err(FmtError::TypeError(msg));
}

if self.alternate() {
return Err(FmtError::TypeError("Alternate form (#) not allowed for floats".to_string()));
}

if self.thousands() {
return Err(FmtError::Invalid("thousands specifier not yet supported".to_string()));
}

if self.fill() == '0' && self.align() == Alignment::Right {
return Err(FmtError::Invalid("sign aware 0 padding not yet supported".to_string()));
}

let mut s = String::new();

if x >= (0 as $t) && self.sign_plus() {
self.write_str("+").unwrap();
}

match self.precision() {
None => {
match ty {
'f' => write!(s, "{}", x).unwrap(),
'e' => write!(s, "{:e}", x).unwrap(),
'E' => write!(s, "{:E}", x).unwrap(),
_ => unreachable!(),
}
}
Some(p) => {
match ty {
'f' => write!(s, "{:.*}", p, x).unwrap(),
'e' => write!(s, "{:.*e}", p, x).unwrap(),
'E' => write!(s, "{:.*E}", p, x).unwrap(),
_ => unreachable!(),
}
}
}

let prev_prec = self.precision();
self.set_precision(None);
let out = self.str_unchecked(s.as_str());
self.set_precision(prev_prec);
out
}
})*)
}
8 changes: 6 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@ mod tests;
mod types;
mod formatter;
mod fmtstr;
mod fmtf64;
mod fmti64;

#[macro_use]
mod fmtnum;

pub use types::{Result, FmtError, Alignment, Sign};
pub use fmtstr::strfmt_map;
pub use formatter::Formatter;

// u128 & i128 unstable (see https://github.com/rust-lang/rust/issues/35118)
fmtint!(u8 i8 u16 i16 u32 i32 u64 i64 usize isize);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whoa! I didn't know this was possible, I thought they would have to each be their own line. Good work!

fmtfloat!(f32 f64);

/// Rust-style format a string given a `HashMap` of the variables.
pub fn strfmt<T: fmt::Display>(fmtstr: &str, vars: &HashMap<String, T>) -> Result<String> {
Expand Down
Loading