I'm trying to write a function that converts hundreds of seconds to hours, minutes and seconds. E.g.: 1000 => "10 seconds"
pub fn formatTime(hundreds_of_seconds: u32) ![]const u8 {
const total_seconds = hundreds_of_seconds / 100;
const hours = total_seconds / 3600;
const minutes = (total_seconds / 60) % 60;
const seconds = total_seconds % 60;
var buffer: [100]u8 = undefined;
var fixed_buffer_stream = std.io.fixedBufferStream(&buffer);
var buffer_writer = fixed_buffer_stream.writer();
if (hours > 0) {
try buffer_writer.print("{d} hours, ", .{hours});
}
if (minutes > 0) {
try buffer_writer.print("{d} minutes, ", .{minutes});
}
try buffer_writer.print("{d} seconds", .{seconds});
return buffer[0..];
}
This is where I use the function and print out the return value:
try stdout.print("Drive time from {d} to {d}: {s}\n", .{ start_node_id, target_node_id, try common.formatTime(dijkstra_drive_time) });
For some reason when I print out the return value, all the data is garbage and semi-random non-printable characters. Is this because the lifetime of the buffer is only within the function scope and it gets deallocated once the function returns replacing that memory space with random bytes? What is the correct way of returning a formatted string ([]const u8)?