I have a count: u32
that I need to push through a TCP stream as its ASCII byte representation. For example if the value is 42, I want to write the bytes [52, 50]
(ASCII for "42") to the stream.
I can do this by first creating a String
with:
use std::io::prelude::*;
fn write_number<T: Write>(writer: &mut T, num: u32) -> std::io::Result<usize> {
let num_as_str: String = num.to_string();
let num_as_bytes = num_as_str.as_bytes();
writer.write(num_as_bytes)
}
Is this is a wasteful way of doing this? I don't feel that allocating a String
should be necessary for this task. Is there a more efficient way to implement write_number
? I've tried going through str
, but str
does not implement From<u32>
.