From a803ec1c1fb3715a7d442d00a587d2e543163abf Mon Sep 17 00:00:00 2001 From: Max Froehlich Date: Sat, 18 Feb 2023 12:49:23 -0800 Subject: [PATCH] Allow bytes for adjantly tagged enums --- serde/src/private/de.rs | 13 +++++++ test_suite/tests/test_annotations.rs | 53 ++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs index e9c693d4d..411525693 100644 --- a/serde/src/private/de.rs +++ b/serde/src/private/de.rs @@ -990,6 +990,19 @@ mod content { Ok(TagContentOtherField::Other) } } + + fn visit_bytes(self, field: &[u8]) -> Result + where + E: de::Error, + { + if field == self.tag.as_bytes() { + Ok(TagContentOtherField::Tag) + } else if field == self.content.as_bytes() { + Ok(TagContentOtherField::Content) + } else { + Ok(TagContentOtherField::Other) + } + } } /// Not public API diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs index f32c22c1a..f5b8269ae 100644 --- a/test_suite/tests/test_annotations.rs +++ b/test_suite/tests/test_annotations.rs @@ -2317,6 +2317,59 @@ fn test_internally_tagged_enum_new_type_with_unit() { ); } +#[test] +fn test_adjacently_tagged_enum_bytes() { + #[derive(Serialize, Deserialize, PartialEq, Debug)] + #[serde(tag = "t", content = "c")] + enum Data { + A { a: i32 }, + } + + let data = Data::A { a: 0 }; + + assert_tokens( + &data, + &[ + Token::Struct { + name: "Data", + len: 2, + }, + Token::Str("t"), + Token::Str("A"), + Token::Str("c"), + Token::Struct { + name: "A", + len: 1, + }, + Token::Str("a"), + Token::I32(0), + Token::StructEnd, + Token::StructEnd, + ], + ); + + assert_de_tokens( + &data, + &[ + Token::Struct { + name: "Data", + len: 2, + }, + Token::Bytes(b"t"), + Token::Str("A"), + Token::Bytes(b"c"), + Token::Struct { + name: "A", + len: 1, + }, + Token::Str("a"), + Token::I32(0), + Token::StructEnd, + Token::StructEnd, + ], + ); +} + #[test] fn test_adjacently_tagged_enum_containing_flatten() { #[derive(Serialize, Deserialize, PartialEq, Debug)]