Skip to content

Commit

Permalink
Support (de-)serializing flattened unit struct
Browse files Browse the repository at this point in the history
Fixes #2801.
  • Loading branch information
jonhoo committed Aug 15, 2024
1 parent 1b4da41 commit 4036ff8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 6 deletions.
12 changes: 11 additions & 1 deletion serde/src/private/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2710,6 +2710,17 @@ where
visitor.visit_unit()
}

fn deserialize_unit_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_unit()
}

fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
Expand All @@ -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)
Expand Down
6 changes: 1 addition & 5 deletions serde/src/private/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ enum Unsupported {
String,
ByteArray,
Optional,
#[cfg(any(feature = "std", feature = "alloc"))]
UnitStruct,
Sequence,
Tuple,
TupleStruct,
Expand All @@ -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"),
Expand Down Expand Up @@ -1092,7 +1088,7 @@ where
}

fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
Err(Self::bad_type(Unsupported::UnitStruct))
Ok(())
}

fn serialize_unit_variant(
Expand Down
26 changes: 26 additions & 0 deletions test_suite/tests/test_annotations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1815,6 +1815,32 @@ fn test_flatten_unit() {
);
}

#[test]
fn test_flatten_unit_struct() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Response<T> {
#[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)]
Expand Down

0 comments on commit 4036ff8

Please sign in to comment.