ona/source/coral/format.zig

46 lines
1.1 KiB
Zig
Raw Normal View History

2023-04-19 01:25:35 +02:00
const io = @import("./io.zig");
pub const Value = union(enum) {
newline: void,
string: []const u8,
unsigned: u128,
};
pub fn print(writer: io.Writer, values: []const Value) io.WriteError!usize {
var written: usize = 0;
for (values) |value| written += switch (value) {
2023-05-06 03:47:52 +02:00
.newline => try writer.invoke("\n"),
.string => |string| try writer.invoke(string),
2023-04-19 01:25:35 +02:00
.unsigned => |unsigned| try print_unsigned(writer, unsigned),
};
return written;
}
pub fn print_unsigned(writer: io.Writer, value: u128) io.WriteError!usize {
2023-05-06 03:47:52 +02:00
if (value == 0) return writer.invoke("0");
2023-04-19 01:25:35 +02:00
var buffer = [_]u8{0} ** 39;
var buffer_count: usize = 0;
var split_value = value;
while (split_value != 0) : (buffer_count += 1) {
const radix = 10;
buffer[buffer_count] = @intCast(u8, (split_value % radix) + '0');
split_value = (split_value / radix);
}
{
const half_buffer_count = buffer_count / 2;
var index: usize = 0;
while (index < half_buffer_count) : (index += 1) {
io.swap(u8, &buffer[index], &buffer[buffer_count - index - 1]);
}
}
2023-05-06 03:47:52 +02:00
return writer.invoke(buffer[0 .. buffer_count]);
2023-04-19 01:25:35 +02:00
}