commit c96533b97d7287ce978702dc73d3962195e38932
parent d09ea3b720bda1a31ba7bc7aa4095644ba271e6d
Author: Ember Sawady <ecs@d2evs.net>
Date: Mon, 6 Nov 2023 21:08:00 +0000
fmt: add center-alignment
Signed-off-by: Ember Sawady <ecs@d2evs.net>
Diffstat:
4 files changed, 9 insertions(+), 0 deletions(-)
diff --git a/fmt/+test.ha b/fmt/+test.ha
@@ -66,6 +66,9 @@ use strconv;
assert(bsprintf(buf, "{:.1}", 123.0) == "100");
assert(bsprintf(buf, "{:.5}", 123.0) == "123");
+ assert(bsprintf(buf, "{:=5}", "hi") == " hi ");
+ assert(bsprintf(buf, "{:=6}", "hi") == " hi ");
+
assert(bsprintf(buf, "{} {} {} {} {}", true, false, null, 'x', void)
== "true false (null) x void");
};
diff --git a/fmt/README b/fmt/README
@@ -26,6 +26,9 @@ A format modifier can be any of the following:
and the padding character is " " (a space).
- "-": Left-align the value, inserting padding characters inserted on the right
side of the value in order to meet the width requirement.
+- "=": Center-align the value, inserting the same amount of padding on the left
+ as on the right. If an odd number of padding characters need to be placed, the
+ extra one will be on the left of the value.
- "_" followed by a rune: Use the given rune as the padding character rather
than the default of " " (a space).
- " " (a space): Insert a space before positive integers, where "-" would be if
diff --git a/fmt/iter.ha b/fmt/iter.ha
@@ -25,6 +25,7 @@ export type neg = enum {
// Specifies how to align an argument within a given width.
export type alignment = enum {
RIGHT,
+ CENTER,
LEFT,
};
@@ -130,6 +131,7 @@ fn scan_modifiers(it: *iterator, mod: *mods) void = {
for (true) switch (getrune(it)) {
// alignment
case '-' => mod.alignment = alignment::LEFT;
+ case '=' => mod.alignment = alignment::CENTER;
// padding
case '_' => mod.pad = getrune(it);
// negation
diff --git a/fmt/print.ha b/fmt/print.ha
@@ -56,6 +56,7 @@ fn format(
switch (mod.alignment) {
case alignment::LEFT => abort();
+ case alignment::CENTER => start = (pad + 1) / 2;
case alignment::RIGHT => start = pad;
};
};