toby / serde-bencode

Serde backed Bencode encoding/decoding library for Rust.
MIT License
65 stars 16 forks source link

Can't serialize struct with Encoder #3

Closed angusturner closed 7 years ago

angusturner commented 7 years ago

I am trying to re-serialize the Info struct provided in the example code, but I am getting a stracktrace error. Basically I added a #[derive(Serialize)] to the Info struct, and then I am using the following snippet in main() to attempt to serialize...

let mut encoder = Encoder::new();
torrent.info.serialize(&mut encoder);
let info_ser: Vec<u8> = encoder.into();
let info_str: String = String::from_utf8(info_ser).unwrap();

the error being thrown is: "thread 'main' panicked at 'index out of bounds: the len is 1 but the index is 1', .../serde_bencode-0.1.1/src/encoder.rs:64"

toby commented 7 years ago

Great find. It looks like the encoder is having trouble serializing None values in structs. I have a fix in mind and will update and do another release.

Also, just fyi -- this won't work: let info_str: String = String::from_utf8(info_ser).unwrap(); because there are non utf-8 bytes in .torrent files.

angusturner commented 7 years ago

Ah, I had a feeling that might be it. Have switched to bip_bencode for the moment, but the API feels much more cumbersome. So if will be keeping an eye on this repo for potential fix :) Also you saved me so much grief by pointing out that UTF8 thing... cheers.

toby commented 7 years ago

Ok I published a fix to this, so it should work now. I need to rethink how the serialization state machine works though, it's a bit messy. Serde is currently in pretty active development so I'll probably wait for it to stabilize a bit before pushing the next version.

The fix is in version serde_bencode = "0.1.2".

Release notes: https://github.com/toby/serde-bencode/releases/tag/v0.1.2

I also put the example code you were going for in a gist: https://gist.github.com/toby/ee1a7ce4a31057d7c838bce839b92582