Skip to content

Commit e13f3f8

Browse files
committed
serialize tuple struct in the same way as sequence
1 parent b56c7b4 commit e13f3f8

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

src/ser/mod.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ impl<'a, 'b: 'a> ser::Serializer for &'a mut Serializer<'b> {
178178
type Error = Error;
179179
type SerializeSeq = SerializeSeq<'a, 'b>;
180180
type SerializeTuple = SerializeSeq<'a, 'b>;
181-
type SerializeTupleStruct = Unreachable;
181+
type SerializeTupleStruct = SerializeSeq<'a, 'b>;
182182
type SerializeTupleVariant = Unreachable;
183183
type SerializeMap = SerializeMap<'a, 'b>;
184184
type SerializeStruct = SerializeStruct<'a, 'b>;
@@ -385,9 +385,9 @@ impl<'a, 'b: 'a> ser::Serializer for &'a mut Serializer<'b> {
385385
fn serialize_tuple_struct(
386386
self,
387387
_name: &'static str,
388-
_len: usize,
388+
len: usize,
389389
) -> Result<Self::SerializeTupleStruct> {
390-
unreachable!()
390+
self.serialize_seq(Some(len))
391391
}
392392

393393
fn serialize_tuple_variant(
@@ -822,6 +822,19 @@ mod tests {
822822
);
823823
}
824824

825+
#[test]
826+
fn test_tuple_struct() {
827+
#[derive(Serialize)]
828+
struct A<'a>(u32, Option<&'a str>, u16, bool);
829+
830+
let a = A(42, Some("A string"), 720, false);
831+
832+
assert_eq!(
833+
&*crate::to_string::<_, N>(&a).unwrap(),
834+
r#"[42,"A string",720,false]"#
835+
);
836+
}
837+
825838
#[test]
826839
fn test_serialize_bytes() {
827840
use core::fmt::Write;

src/ser/seq.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,19 @@ impl<'a, 'b: 'a> ser::SerializeTuple for SerializeSeq<'a, 'b> {
5151
ser::SerializeSeq::end(self)
5252
}
5353
}
54+
55+
impl<'a, 'b: 'a> ser::SerializeTupleStruct for SerializeSeq<'a, 'b> {
56+
type Ok = ();
57+
type Error = Error;
58+
59+
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
60+
where
61+
T: ser::Serialize,
62+
{
63+
ser::SerializeSeq::serialize_element(self, value)
64+
}
65+
66+
fn end(self) -> Result<Self::Ok> {
67+
ser::SerializeSeq::end(self)
68+
}
69+
}

0 commit comments

Comments
 (0)