toby / serde-bencode

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

Deserialization for enums with `#[serde(flatten)]` is not working #39

Open josecelano opened 1 year ago

josecelano commented 1 year ago

I think these two failing tests could be the same problem because they both use #[serde(flatten)] for an enum field.

Failing test 1

$ cargo test ser_de_flattened_enum -- --nocapture
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/torrust_serde_bencode-61b7eea2ea5618bf)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/tests.rs (target/debug/deps/tests-b55451bec73c8180)

running 1 test
bytes: "d12:message_type8:Responsee"
bytes: "d12:message_type8:Responsee"
thread 'ser_de_flattened_enum' panicked at tests/tests.rs:34:41:
called `Result::unwrap()` on an `Err` value: InvalidType("Invalid Type: byte array (expected: `string or map`)")
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
test ser_de_flattened_enum ... FAILED

failures:

failures:
    ser_de_flattened_enum

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 42 filtered out; finished in 0.00s

error: test failed, to rerun pass `--test tests`

Failing test 2

$ cargo test ser_de_flattened_adjacently_tagged_enum -- --nocapture
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/torrust_serde_bencode-61b7eea2ea5618bf)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/tests.rs (target/debug/deps/tests-b55451bec73c8180)

running 1 test
bytes: "d7:contentd5:tokeni456ee2:idi123e4:type7:Requeste"
thread 'ser_de_flattened_adjacently_tagged_enum' panicked at tests/tests.rs:34:41:
called `Result::unwrap()` on an `Err` value: InvalidType("Invalid Type: byte array (expected: `string or map`)")
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
test ser_de_flattened_adjacently_tagged_enum ... FAILED

failures:

failures:
    ser_de_flattened_adjacently_tagged_enum

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 42 filtered out; finished in 0.00s

error: test failed, to rerun pass `--test tests`

Related commits

ngoquang2708 commented 4 months ago

Using "tag" and "content" at the same time on the enum have the same issue:

#[derive(Deserialize, Serialize)]
struct A {
    #[serde(flatten)]
    b: B,
}

#[derive(Deserialize, Serialize)]
#[serde(tag = "a", content = "b")]
enum B {
    C,
}

let a = A { b: B::C };
let s = serde_bencode::to_string(&a).unwrap();
let _: A = serde_bencode::from_bytes(s.as_bytes()).unwrap();