UEFI string formatting

Hello all,

recently I started programming a bootloader. Now I wanted to do some debug output, but that debug output should not only contain strings, but also numbers (as hexadecimals) …
So, has anyone here an idea how I could do std.fmt things with UEFI as “operating system”?

Looking forwards,
Samuel Fiedler

Have you taken a look at std.fmt.bufPrint? There’s also allocPrint and comptimePrint.

var buf: [32]u8 = undefined;
// Note: the only possible error is `NoSpaceLeft`, so it may make
// sense to use `catch unreachable` instead of `try` if you know
// there's no possibility of overflow
const formatted = try std.fmt.bufPrint(&buf, "{X}", .{1234});
// formatted will be a slice with the contents "4D2"
1 Like

Thank you for pointing me to bufPrint! I had allocPrint in my head but I was not sure if the allocators would work with uefi…

Just another small question: Can I use the buf multiple times or only one time?

Some of them should work, like the FixedBufferAllocator for example.
I think you can even create a GeneralPurposeAllocator that uses a FixedBufferAllocator in the background.

You can re-use it as long as you don’t need the previous value anymore. For example:

var buf: [32]u8 = undefined;

for (some_list_of_ints) |int| {
    // as long as it's okay to overwrite the memory of buf each iteration, this is fine
    const formatted = try std.fmt.bufPrint(&buf, "{X}", .{int});
    // note: this function must not store the slice, it must treat the string as a temporary
    //       that will be destroyed after the function returns
    doSomethingWithString(formatted);
}

// if you still need access to any of the formatted slices, this pattern won't work
2 Likes

Okay, thanks!

1 Like