Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenience method for writing just one byte

Tags:

rust

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?

like image 926
Kornel Avatar asked Jan 29 '23 06:01

Kornel


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.

like image 164
E_net4 stands with Ukraine Avatar answered Feb 03 '23 13:02

E_net4 stands with Ukraine