diff --git a/src/serde/ser.rs b/src/serde/ser.rs index 00090eb..3a0d2c6 100644 --- a/src/serde/ser.rs +++ b/src/serde/ser.rs @@ -796,18 +796,6 @@ impl serde::ser::SerializeStruct for SerializeStruct<'_, '_, W> { value.serialize(&mut *self.ser) } - fn skip_field(&mut self, _key: &'static str) -> Result<(), Self::Error> { - if self.len >= self.expected_len { - return Err(SerializerError::IncorrectElementsCount { - expected: self.expected_len, - // + 1 for currently added field - actual: self.len + 1, - }); - } - self.len += 1; - Ok(()) - } - fn end(self) -> Result { if self.len < self.expected_len { return Err(SerializerError::IncorrectElementsCount { @@ -850,18 +838,6 @@ impl serde::ser::SerializeStructVariant for SerializeStructVarian value.serialize(&mut *self.ser) } - fn skip_field(&mut self, _key: &'static str) -> Result<(), Self::Error> { - if self.len >= self.expected_len { - return Err(SerializerError::IncorrectElementsCount { - expected: self.expected_len, - // + 1 for currently added field - actual: self.len + 1, - }); - } - self.len += 1; - Ok(()) - } - fn end(self) -> Result { if self.len < self.expected_len { return Err(SerializerError::IncorrectElementsCount { @@ -1739,7 +1715,7 @@ mod tests { assert_serialized_cmp!( |s| { - let mut struc = s.serialize_struct("name", 3)?; + let mut struc = s.serialize_struct("name", 2)?; struc.serialize_field("key1", &1)?; struc.skip_field("skipped")?; struc.serialize_field("key2", &2)?; @@ -1781,7 +1757,7 @@ mod tests { assert_serialized_cmp!( |s| { - let mut struc = s.serialize_struct_variant("name", 1, "variant", 3)?; + let mut struc = s.serialize_struct_variant("name", 1, "variant", 2)?; struc.serialize_field("key1", &1)?; struc.skip_field("skipped")?; struc.serialize_field("key2", &2)?; diff --git a/tests/serde_serialize_test.rs b/tests/serde_serialize_test.rs index e36214d..f68559a 100644 --- a/tests/serde_serialize_test.rs +++ b/tests/serde_serialize_test.rs @@ -145,3 +145,40 @@ fn serialize_unit_variant() { assert_serialized(E::A, "\"A\""); } + +#[test] +fn serialize_skipped_field() { + #[derive(Serialize)] + struct S { + a: u32, + #[allow(dead_code)] + #[serde(skip)] + b: u32, + } + + assert_serialized(S { a: 1, b: 2 }, r#"{"a":1}"#); +} + +#[test] +fn serialize_conditional_skipped_field() { + #[derive(Serialize)] + struct S { + a: u32, + #[serde(skip_serializing_if = "Option::is_none")] + b: Option, + } + + assert_serialized(S { a: 1, b: Some(2) }, r#"{"a":1,"b":2}"#); + assert_serialized(S { a: 1, b: None }, r#"{"a":1}"#); + + #[derive(Serialize)] + enum E { + S { + a: u32, + #[serde(skip_serializing_if = "Option::is_none")] + b: Option, + }, + } + assert_serialized(E::S { a: 1, b: Some(2) }, r#"{"S":{"a":1,"b":2}}"#); + assert_serialized(E::S { a: 1, b: None }, r#"{"S":{"a":1}}"#); +}