admin管理员组

文章数量:1125887

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 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?

Share Improve this question edited Jan 9 at 3:41 bikeman868 asked Jan 9 at 1:51 bikeman868bikeman868 2,59730 silver badges34 bronze badges 1
  • 4 What is Serializer? – kmdreko Commented Jan 9 at 2:14
Add a comment  | 

1 Answer 1

Reset to default 0

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 works, and starts writing the serialized data at the 9th byte:

let mut buffer = Vec::new();
buffer.resize(8, 0);
let mut serializer = Serializer::new(&mut buffer);

本文标签: rustHow to serialize data at an offset from the start of a vectorStack Overflow