WriteBytesExt in byteorder - Rust on a &mut [u8]?

I know that I can use WriteBytesExt in byteorder - Rust on a let mut out = vec![] , so I can do things like out.write_i32(...).

My question is: is there a way to do this on a &mut [u8] ? I.e. the mut slice already exists, and I want to use the .write_### directly on it, (instead of writing into a vec then copying it over).

Did you just try it? &mut [u8] is Write and there's a blanket implementation for WriteBytesExt...

1 Like

No. Sorry, how does this even work? With a Vec<u8>, when we do a .write_### it can push to the end. With a &mut [u8] how is writing to it possible unless we explicitly store a 'cursor' (which afaik &mut [u8] does not) ?

I.e. suppose we have:

let x: &mut [u8] = ...;

how does it know, on the 2nd write, that it should be 4 bytes after the first, given that &mut [u8] has no internal store of a 'cursor' ?

Oh, this line

Note that writing updates the slice to point to the yet unwritten part. The slice will be empty when it has been completely overwritten.

Okay, this makes sense now. Thanks! :slight_smile:

It works on &mut [u8] not on [u8] (&mut self is &mut &mut [u8]), so (as the docs say) it updates the slice as it goes so that it covers the unwritten portion.

(Meant to finish the example before my first post, oops.)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.