zig icon indicating copy to clipboard operation
zig copied to clipboard

format: do not force user to provide an alignment field when it's not necessary

Open eric-saintetienne opened this issue 2 years ago • 0 comments

Hi guys,

In this changelist I'm suggesting to improve upon the existing Format Options parsing to make it a little more flexible, closer actually to the defaults that C programmers are used to and that most languages implement. To me, it follows the following principles from the Zen:

  • Incremental improvements,
  • Edge cases matter,
  • Minimize energy spent on coding style,
  • Together we serve end users.

Padding with 0 is very common for hexadecimal output: in many languages 04x left-pads with zeroes, but in Zig {x:04} left-pads with blanks. However for most fill characters like zero, adding an alignment specifier is actually not necessary (it's only necessary for 1-9 and .)

The new behaviour is non-breaking (e.g current unit tests pass) and feels more natural and closer to how other languages handle zero-padding in their format options:

    std.debug.print("{:04}",   .{42}); // "0042"
    std.debug.print("{:10}",   .{42}); // "        42"
    std.debug.print("{:0>3}",  .{1});  // "001"
    std.debug.print("{:1<03}", .{9});  // "911"
    std.debug.print("{:>03}" , .{1});  // "  1"
    std.debug.print("{:5^03}", .{1});  // "515"
    std.debug.print("{:_4}",   .{42}); // "__42"
    std.debug.print("{: 4}",   .{42}); // "  42"
    std.debug.print("{d:.3}", .{1.2345});  // "1.234"

I've also added new unit tests for the new cases.

eric-saintetienne avatar Feb 23 '24 15:02 eric-saintetienne