fix: make reflow wrap *before* width limit, not after it

This commit is contained in:
CJ van den Berg 2026-02-01 19:48:03 +01:00
parent 01cbdf8545
commit 4803daec3e
Signed by: neurocyte
GPG key ID: 8EB1E1BB660E3FB9

View file

@ -8,7 +8,12 @@ pub fn reflow(allocator: std.mem.Allocator, text: []const u8, width: usize) erro
var first = true;
var line_len: usize = 0;
for (words) |word| {
if (line_len == 0) {
const state: enum {
begin,
words,
} = if (line_len == 0) .begin else .words;
blk: switch (state) {
.begin => {
if (first) {
try writer.writeAll(prefix.first);
first = false;
@ -19,14 +24,19 @@ pub fn reflow(allocator: std.mem.Allocator, text: []const u8, width: usize) erro
try writer.writeByte(' ');
}
line_len += prefix.len;
continue :blk .words;
},
.words => {
if (line_len + word.len + 1 >= width) {
try writer.writeByte('\n');
line_len = 0;
continue :blk .begin;
}
if (line_len > prefix.len)
try writer.writeByte(' ');
try writer.writeAll(word);
line_len += word.len;
if (line_len >= width) {
try writer.writeByte('\n');
line_len = 0;
},
}
}