Skip to content

Commit

Permalink
Change how the 0 flag works in format!
Browse files Browse the repository at this point in the history
Now it always implies right-alignment, so that padding zeroes are placed after the sign (if any) and before the digits. In other words, it always takes precedence over explicitly specified `[[fill]align]`. This also affects the '#' flag: zeroes are placed after the prefix (0b, 0o, 0x) and before the digits.

           :05     :<05    :>05    :^05
before   |-0001| |-1000| |-0001| |-0100|
after    |-0001| |-0001| |-0001| |-0001|
          :#05x   :<#05x  :>#05x  :^#05x
before   |0x001| |0x100| |000x1| |0x010|
after    |0x001| |0x001| |0x001| |0x001|

Fixes #39997 [breaking-change]
  • Loading branch information
Sawyer47 authored and alexcrichton committed Mar 15, 2017
1 parent 6f10e2f commit ff63866
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/libcollections/fmt.rs
Expand Up @@ -366,6 +366,10 @@
//! like `{:08}` would yield `00000001` for the integer `1`, while the
//! same format would yield `-0000001` for the integer `-1`. Notice that
//! the negative version has one fewer zero than the positive version.
//! Note that padding zeroes are always placed after the sign (if any)
//! and before the digits. When used together with the `#` flag, a similar
//! rule applies: padding zeroes are inserted after the prefix but before
//! the digits.
//!
//! ## Width
//!
Expand Down
1 change: 1 addition & 0 deletions src/libcore/fmt/mod.rs
Expand Up @@ -1045,6 +1045,7 @@ impl<'a> Formatter<'a> {
// is zero
Some(min) if self.sign_aware_zero_pad() => {
self.fill = '0';
self.align = rt::v1::Alignment::Right;
write_prefix(self)?;
self.with_padding(min - width, rt::v1::Alignment::Right, |f| {
f.buf.write_str(buf)
Expand Down
16 changes: 16 additions & 0 deletions src/test/run-pass/ifmt.rs
Expand Up @@ -160,6 +160,22 @@ pub fn main() {
t!(format!("{:?}", -0.0), "-0");
t!(format!("{:?}", 0.0), "0");

// sign aware zero padding
t!(format!("{:<3}", 1), "1 ");
t!(format!("{:>3}", 1), " 1");
t!(format!("{:^3}", 1), " 1 ");
t!(format!("{:03}", 1), "001");
t!(format!("{:<03}", 1), "001");
t!(format!("{:>03}", 1), "001");
t!(format!("{:^03}", 1), "001");
t!(format!("{:+03}", 1), "+01");
t!(format!("{:<+03}", 1), "+01");
t!(format!("{:>+03}", 1), "+01");
t!(format!("{:^+03}", 1), "+01");
t!(format!("{:#05x}", 1), "0x001");
t!(format!("{:<#05x}", 1), "0x001");
t!(format!("{:>#05x}", 1), "0x001");
t!(format!("{:^#05x}", 1), "0x001");

// Ergonomic format_args!
t!(format!("{0:x} {0:X}", 15), "f F");
Expand Down

0 comments on commit ff63866

Please sign in to comment.