How to write a fixed length less than buffer length to an output stream?

fn write_all(&mut self, buf: &[u8]) -> Result<()>

but i need something like

fn write_all(&mut self, buf: &[u8], len:u32) -> Result<()>

The len is the "true" length i want to write.

What should i do?

You can slice the buffer to the length you want before calling write_all, e.g. w.write_all(&buf[..len]).


Will this cost more memory and cpu time?

Almost certainly no, but it depends on exactly what you're comparing to. Either way, it doesn't use any extra memory (a subslice points right into the array it was sliced from), and it'll be a very small amount of extra time, i.e. double digit nanoseconds, or less (almost certainly closer to 1 ns than 50 ns).

A version of write_all that took a len argument would likely just do the same sort of slicing internally anyway, meaning internal or external slicing will be essentially equivalent.