From 4036ff88edc2ee85f288e8c9bc6d9a0f393cf96e Mon Sep 17 00:00:00 2001 From: Jon Gjengset Date: Thu, 15 Aug 2024 15:50:40 +0200 Subject: [PATCH] Support (de-)serializing flattened unit struct Fixes #2801. --- serde/src/private/de.rs | 12 +++++++++++- serde/src/private/ser.rs | 6 +----- test_suite/tests/test_annotations.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/serde/src/private/de.rs b/serde/src/private/de.rs index c402d2c66..c146539ee 100644 --- a/serde/src/private/de.rs +++ b/serde/src/private/de.rs @@ -2710,6 +2710,17 @@ where visitor.visit_unit() } + fn deserialize_unit_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_unit() + } + fn deserialize_ignored_any(self, visitor: V) -> Result where V: Visitor<'de>, @@ -2734,7 +2745,6 @@ where deserialize_string() deserialize_bytes() deserialize_byte_buf() - deserialize_unit_struct(&'static str) deserialize_seq() deserialize_tuple(usize) deserialize_tuple_struct(&'static str, usize) diff --git a/serde/src/private/ser.rs b/serde/src/private/ser.rs index 9570629e9..ebfeba97e 100644 --- a/serde/src/private/ser.rs +++ b/serde/src/private/ser.rs @@ -51,8 +51,6 @@ enum Unsupported { String, ByteArray, Optional, - #[cfg(any(feature = "std", feature = "alloc"))] - UnitStruct, Sequence, Tuple, TupleStruct, @@ -69,8 +67,6 @@ impl Display for Unsupported { Unsupported::String => formatter.write_str("a string"), Unsupported::ByteArray => formatter.write_str("a byte array"), Unsupported::Optional => formatter.write_str("an optional"), - #[cfg(any(feature = "std", feature = "alloc"))] - Unsupported::UnitStruct => formatter.write_str("unit struct"), Unsupported::Sequence => formatter.write_str("a sequence"), Unsupported::Tuple => formatter.write_str("a tuple"), Unsupported::TupleStruct => formatter.write_str("a tuple struct"), @@ -1092,7 +1088,7 @@ where } fn serialize_unit_struct(self, _: &'static str) -> Result { - Err(Self::bad_type(Unsupported::UnitStruct)) + Ok(()) } fn serialize_unit_variant( diff --git a/test_suite/tests/test_annotations.rs b/test_suite/tests/test_annotations.rs index 1174be6d2..63cb3dd1b 100644 --- a/test_suite/tests/test_annotations.rs +++ b/test_suite/tests/test_annotations.rs @@ -1815,6 +1815,32 @@ fn test_flatten_unit() { ); } +#[test] +fn test_flatten_unit_struct() { + #[derive(Debug, PartialEq, Serialize, Deserialize)] + struct Response { + #[serde(flatten)] + data: T, + status: usize, + } + + #[derive(Debug, PartialEq, Serialize, Deserialize)] + struct Unit; + + assert_tokens( + &Response { + data: Unit, + status: 0, + }, + &[ + Token::Map { len: None }, + Token::Str("status"), + Token::U64(0), + Token::MapEnd, + ], + ); +} + #[test] fn test_flatten_unsupported_type() { #[derive(Debug, PartialEq, Serialize, Deserialize)]