I want to serialize data into a buffer, but not starting at the first byte, so I tried passing a slice to the serializer.
The serializer works if you pass the whole Vec
like this:
let mut buffer = Vec::new();
let mut serializer = Serializer::new(&mut buffer);
but it fails to serialize if you pass a slice because it's zero length
let mut buffer = Vec::new();
let mut serializer = Serializer::new(&mut buffer[..]);
I can fix the serializer by resizing the buffer like this:
let mut buffer = Vec::new();
buffer.resize(20, 0);
let mut serializer = Serializer::new(&mut buffer[..]);
but I then have no way to figure out how many bytes were written to the buffer by the serializer.
I feel like I am missing something. Do I need custom implementation of the Write
trait to accomplish this?
I got this figured out, and was actually quite close.
The important part is that the serializer appends to the buffer, so if you resize the buffer first, then pass it to the serializer, it will append the serialization.
This rmp-serde
example works, and starts writing the serialized data at the 9th byte. Any other serializer would work the same way:
use rmp_serde::Serializer;
let mut buffer = Vec::new();
buffer.resize(8, 0);
let mut serializer = Serializer::new(&mut buffer);