In Rust, when using the bincode crate to serialize data into a slice, you can absolutely use a Vec<u8> as the backing storage for that slice instead of a fixed-size array. The key is to make sure the Vec has enough capacity to hold the serialized data.
Here's how you can do it:
✅ Use a Vec<u8> as the output buffer
rust
use bincode;
let input = /* your serializable data */;
// Create a Vec with enough capacity (you can also start small and let it grow if needed)
let mut buffer = Vec::with_capacity(128); // initial capacity, adjust as needed
// SAFETY: vec is zero-initialized, but not all bytes are valid in all contexts.
// However, bincode requires a mutable slice to write into.
//
// We set the length to zero initially; we will write into it and update the length manually.
unsafe {
buffer.set_len(buffer.capacity());
}
let encoded_size = bincode::encode_into_slice(
&input,
&mut buffer,
bincode::config::standard(),
).unwrap();
// Now shrink the vector to fit the actual encoded size
buffer.resize(encoded_size, 0);
// `buffer` now contains only the encoded data
🔍 Explanation
Vec::with_capacity(n): Allocates memory without initializing it.
unsafe { buffer.set_len(buffer.capacity()) }:
This sets the length of the vector to its full capacity so that the slice &mut buffer is long enough for writing.
It's unsafe because the memory is uninitialized, but bincode expects a valid slice to write into.
If you're unsure, you can initialize it with zeros via vec![0u8; capacity] instead.
resize(): After encoding, we resize the vector to the number of bytes actually written.
✅ Alternative: Safe version using zeroed buffer
If you want to avoid unsafe, you can just create a zeroed vector:
rust
let mut buffer = vec![0u8; 128]; // initial size, adjust as needed
let encoded_size = bincode::encode_into_slice(
&input,
&mut buffer,
bincode::config::standard(),
).unwrap();
buffer.truncate(encoded_size); // shrink to fit
buffer.shrink_to_fit(); // optional
This is safe, but it initializes the whole buffer with zeroes first, which may be unnecessary overhead.
🧠 Pro Tip
If you don't know the required size ahead of time, you can let bincode tell you by using bincode::serialized_size():
rust
let size = bincode::serialized_size(&input, bincode::config::standard()).unwrap() as usize;
let mut buffer = vec![0u8; size];
let encoded_size = bincode::encode_into_slice(
&input,
&mut buffer,
bincode::config::standard(),
).unwrap();
debug_assert_eq!(encoded_size, size);
This ensures the buffer is exactly the right size.
Let me know if you're working with a specific type for input — I can tailor the example more precisely!