Convenience method for writing just one byte

Viewed 1296

I have a generic function that needs to write (non-ASCII) bytes to an io::Write writer.

The shortest way to reliably write a single byte provided by the io::Write trait is AFAIK writer.write_all(&[0])?. That is a bit long and syntactically noisy to write in many places.

Does Rust's stdlib have a macro or an extension trait with a convenience method that is shorter to write?

1 Answers

Does Rust's stdlib have a macro or an extension trait with a convenience method that is shorter to write?

Not that I know of. But the nearly ubiquitous byteorder crate provides write_u8. Although it is unaffected by the machine's byte order, it was included for completeness.

use byteorder::WriteBytesExt;

writer.write_u8(0)?;

If you intend to use this method often, it might be a good idea to wrap the writer around a buffered writer such as BufWriter.

Related