Neat! Just a couple of very minor notes on the implementation. As it’s a relatively straightforward program, it’s already pretty close to idiomatic Zig.
I’ve implemented a simple little set of helper functions to write u32 and u64 to the output. I believe there are better ways to do that, but this works fine. Much of this is really pretty close to the rust source, maybe surprisingly so.
Yep! Zig’s Writer interface has writeIntLittle and writeIntBig methods. Internally they’re implemented similarly to yours.
You also probably want to use writeAll rather than write, as write isn’t guaranteed to write every byte to the file; it returns the number of bytes written (a value that your code ignores).
_ = try file.write("RIFF"); // may truncate
try file.writeAll("RIFF"); // won't truncate unless there's an error
Finally, it’s better practice to use defer to cleanup resources, rather than closing them at the end of the function. This guarantees that they’ll be cleaned up even if an early return occurs (such as if try fails).
Neat! Just a couple of very minor notes on the implementation. As it’s a relatively straightforward program, it’s already pretty close to idiomatic Zig.
Yep! Zig’s Writer interface has
writeIntLittle
andwriteIntBig
methods. Internally they’re implemented similarly to yours.You also probably want to use
writeAll
rather thanwrite
, aswrite
isn’t guaranteed towrite
every byte to the file; it returns the number of bytes written (a value that your code ignores).Finally, it’s better practice to use
defer
to cleanup resources, rather than closing them at the end of the function. This guarantees that they’ll be cleaned up even if an early return occurs (such as iftry
fails).These and a few other suggestions were nicely written up by xq here: https://zig.news/xq/re-makin-wavs-with-zig-1jjd
Some nice suggestions there that I missed!