Source
pub fn formatBuf(
buf: []const u8,
options: FormatOptions,
writer: anytype,
) !void {
if (options.width) |min_width| {
// In case of error assume the buffer content is ASCII-encoded
const width = unicode.utf8CountCodepoints(buf) catch buf.len;
const padding = if (width < min_width) min_width - width else 0;
if (padding == 0)
return writer.writeAll(buf);
var fill_buffer: [4]u8 = undefined;
const fill_utf8 = if (unicode.utf8Encode(options.fill, &fill_buffer)) |len|
fill_buffer[0..len]
else |err| switch (err) {
error.Utf8CannotEncodeSurrogateHalf,
error.CodepointTooLarge,
=> &unicode.utf8EncodeComptime(unicode.replacement_character),
};
switch (options.alignment) {
.left => {
try writer.writeAll(buf);
try writer.writeBytesNTimes(fill_utf8, padding);
},
.center => {
const left_padding = padding / 2;
const right_padding = (padding + 1) / 2;
try writer.writeBytesNTimes(fill_utf8, left_padding);
try writer.writeAll(buf);
try writer.writeBytesNTimes(fill_utf8, right_padding);
},
.right => {
try writer.writeBytesNTimes(fill_utf8, padding);
try writer.writeAll(buf);
},
}
} else {
// Fast path, avoid counting the number of codepoints
try writer.writeAll(buf);
}
}