2

I'm using the bincode crate to write a structure into a file. The structure contains a slice with a fixed size. How can I force bincode to write only the slice's content without the slice's length?

#![allow(unstable)]
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]

extern crate serde;
extern crate bincode;

use std::fs::File;
use bincode::serde::serialize_into;
use bincode::SizeLimit;

#[derive(Serialize)]
struct Foo([u8; 16]);

fn main() {
    let data = Foo([0; 16]);
    let mut writer = File::create("test.bin").unwrap();
    serialize_into::<File, Foo>(&mut writer, &data, SizeLimit::Infinite).unwrap();
}

File 'test.bin' has 24 bytes size instead of 16.

I saw related remark in documentation of bincode, but I did not understand how to use it.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user2616346
  • 465
  • 1
  • 5
  • 12
  • I *think* that I am already doing something similar: https://stackoverflow.com/questions/67168397/how-does-serde-bincode-serialize-byte-arrays but I do not understand how it is working. – fadedbee Apr 19 '21 at 19:47

1 Answers1

3

a slice with a fixed size

[u8; 16] is not a slice. It is an array which may be coerced to a slice.

Anyway... I do not believe that you can. The important function appears to be Serializer::serialize_fixed_size_array which is not implemented by the current serializer. That means it defaults to behaving the same as a slice.

Since slices do not have a length known at compile time, they must have their size written when serialized.

If no one else can provide a better suggestion, it's possible that the maintainer could find a way to make this happen. You may want to politely ask the maintainer for this feature or offer to help with the work.


Beyond that, it sounds like you are trying to make the bincode output fit a pre-existing format. That doesn't really make sense; bincode is its own format and had already made various choices and tradeoffs.

If you need to, you could implement your own encoder / decoder (either using serde or not). If you are concerned about file size, you can combine bincode with a compression step as well.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366