bitcode/serde/
ser.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
use crate::bool::BoolEncoder;
use crate::coder::{Buffer, Encoder, Result};
use crate::error::{err, Error};
use crate::f32::F32Encoder;
use crate::int::IntEncoder;
use crate::length::LengthEncoder;
use crate::serde::variant::VariantEncoder;
use crate::serde::{default_box_slice, get_mut_or_resize, type_changed};
use crate::str::StrEncoder;
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::num::NonZeroUsize;
use serde::ser::{
    SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
    SerializeTupleStruct, SerializeTupleVariant,
};
use serde::{Serialize, Serializer};

// Redefine Result from crate::coder::Result to std::result::Result since the former isn't public.
mod inner {
    use super::*;
    use core::result::Result;

    /// Serializes a `T:` [`Serialize`] into a [`Vec<u8>`].
    ///
    /// **Warning:** The format is incompatible with [`decode`][`crate::decode`] and subject to
    /// change between major versions.
    pub fn serialize<T: Serialize + ?Sized>(t: &T) -> Result<Vec<u8>, Error> {
        let mut lazy = LazyEncoder::Unspecified {
            reserved: NonZeroUsize::new(1),
        };
        let mut index_alloc = 0;
        t.serialize(EncoderWrapper {
            lazy: &mut lazy,
            index_alloc: &mut index_alloc,
        })?;
        Ok(lazy.collect(index_alloc))
    }
}
pub use inner::serialize;

enum SpecifiedEncoder {
    Bool(BoolEncoder),
    Enum((VariantEncoder, Vec<LazyEncoder>)), // (variants, values)
    F32(F32Encoder),
    // Serialize needs separate signed integer encoders to be able to pack [0, -1, 0, -1, 0, -1].
    I8(IntEncoder<i8>),
    I16(IntEncoder<i16>),
    I32(IntEncoder<i32>),
    I64(IntEncoder<i64>),
    I128(IntEncoder<i128>),
    Map((LengthEncoder, Box<(LazyEncoder, LazyEncoder)>)), // (lengths, (keys, values))
    Seq((LengthEncoder, Box<LazyEncoder>)),                // (lengths, values)
    Str(StrEncoder),
    Tuple(Box<[LazyEncoder]>), // [field0, field1, ..]
    U8(IntEncoder<u8>),
    U16(IntEncoder<u16>),
    U32(IntEncoder<u32>),
    U64(IntEncoder<u64>),
    U128(IntEncoder<u128>),
}

impl SpecifiedEncoder {
    fn reserve(&mut self, additional: NonZeroUsize) {
        match self {
            Self::Bool(v) => v.reserve(additional),
            Self::Enum(v) => {
                v.0.reserve(additional);
                // We don't know the variants of the enums, so we can't reserve more.
            }
            Self::F32(v) => v.reserve(additional),
            Self::I8(v) => v.reserve(additional),
            Self::I16(v) => v.reserve(additional),
            Self::I32(v) => v.reserve(additional),
            Self::I64(v) => v.reserve(additional),
            Self::I128(v) => v.reserve(additional),
            Self::Map(v) => {
                v.0.reserve(additional);
                // We don't know the lengths of the maps, so we can't reserve more.
            }
            Self::Seq(v) => {
                v.0.reserve(additional);
                // We don't know the lengths of the sequences, so we can't reserve more.
            }
            Self::Str(v) => {
                v.reserve(additional);
            }
            Self::Tuple(v) => v.iter_mut().for_each(|v| v.reserve_fast(additional.get())),
            Self::U8(v) => v.reserve(additional),
            Self::U16(v) => v.reserve(additional),
            Self::U32(v) => v.reserve(additional),
            Self::U64(v) => v.reserve(additional),
            Self::U128(v) => v.reserve(additional),
        }
    }
}

enum LazyEncoder {
    Unspecified {
        reserved: Option<NonZeroUsize>,
    },
    Specified {
        specified: SpecifiedEncoder,
        index: usize,
    },
}

impl Default for LazyEncoder {
    fn default() -> Self {
        Self::Unspecified { reserved: None }
    }
}

impl LazyEncoder {
    /// Analogous [`Buffer::collect`], but requires `index_alloc` from serialization.
    fn collect(&mut self, index_alloc: usize) -> Vec<u8> {
        // If we just wrote out the buffers in field order we wouldn't be able to deserialize them
        // since we might learn their types from serde in a different order.
        //
        // Consider the value: `[(vec![], 0u8), (vec![true], 1u8)]`
        // We don't know that the Vec contains bool until we've already deserialized 0u8.
        // Serde only tells us what is in sequences that aren't empty.
        //
        // Therefore, we have to reorder the buffers to match the order serde told us about them.
        let mut buffers = default_box_slice(index_alloc);
        self.reorder(&mut buffers);

        let mut bytes = vec![];
        for buffer in Vec::from(buffers).into_iter().flatten() {
            buffer.collect_into(&mut bytes);
        }
        bytes
    }

    fn reorder<'a>(&'a mut self, buffers: &mut [Option<&'a mut dyn Buffer>]) {
        match self {
            Self::Specified { specified, index } => {
                buffers[*index] = Some(match specified {
                    SpecifiedEncoder::Bool(v) => v,
                    SpecifiedEncoder::Enum(v) => {
                        v.1.iter_mut().for_each(|v| v.reorder(buffers));
                        &mut v.0
                    }
                    SpecifiedEncoder::F32(v) => v,
                    SpecifiedEncoder::I8(v) => v,
                    SpecifiedEncoder::I16(v) => v,
                    SpecifiedEncoder::I32(v) => v,
                    SpecifiedEncoder::I64(v) => v,
                    SpecifiedEncoder::I128(v) => v,
                    SpecifiedEncoder::Map(v) => {
                        v.1 .0.reorder(buffers);
                        v.1 .1.reorder(buffers);
                        &mut v.0
                    }
                    SpecifiedEncoder::Seq(v) => {
                        v.1.reorder(buffers);
                        &mut v.0
                    }
                    SpecifiedEncoder::Str(v) => v,
                    SpecifiedEncoder::Tuple(v) => {
                        v.iter_mut().for_each(|v| v.reorder(buffers));
                        return; // Has no buffer.
                    }
                    SpecifiedEncoder::U8(v) => v,
                    SpecifiedEncoder::U16(v) => v,
                    SpecifiedEncoder::U32(v) => v,
                    SpecifiedEncoder::U64(v) => v,
                    SpecifiedEncoder::U128(v) => v,
                });
            }
            Self::Unspecified { .. } => (),
        }
    }

    /// OLD COMMENT:
    /// Only reserves if the type is unspecified to save time. Speeds up large 1 time collections
    /// without slowing down many small collections too much. Takes a `usize` instead of a
    /// [`NonZeroUsize`] to avoid branching on len.
    ///
    /// Can't be reserve_fast anymore with push_within_capacity.
    #[inline(always)]
    fn reserve_fast(&mut self, len: usize) {
        match self {
            Self::Specified { specified, .. } => {
                if let Some(len) = NonZeroUsize::new(len) {
                    specified.reserve(len);
                }
            }
            Self::Unspecified { reserved } => *reserved = NonZeroUsize::new(len),
        }
    }
}

macro_rules! specify {
    ($wrapper:ident, $variant:ident) => {{
        let lazy = &mut *$wrapper.lazy;
        match lazy {
            // Check if it's already the correct encoder. This results in 1 branch in the hot path.
            LazyEncoder::Specified { specified: SpecifiedEncoder::$variant(_), .. } => (),
            _ => {
                // Either create the correct encoder if unspecified or panic if we already have an
                // encoder since it must be a different type.
                #[cold]
                fn cold(
                    me: &mut LazyEncoder,
                    index_alloc: &mut usize,
                ) {
                    let &mut LazyEncoder::Unspecified { reserved } = me else {
                        type_changed!()
                    };
                    *me = LazyEncoder::Specified {
                        specified: SpecifiedEncoder::$variant(Default::default()),
                        index: core::mem::replace(index_alloc, *index_alloc + 1),
                    };
                    let LazyEncoder::Specified { specified, .. } = me else {
                        unreachable!();
                    };
                    if let Some(reserved) = reserved {
                        specified.reserve(reserved);
                    }
                }
                cold(lazy, &mut *$wrapper.index_alloc);
            }
        }
        let LazyEncoder::Specified { specified: SpecifiedEncoder::$variant(b), .. } = lazy else {
            // Safety: `cold` gets called when lazy isn't the correct encoder. `cold` either diverges
            // or sets lazy to the correct encoder.
            unsafe { core::hint::unreachable_unchecked() };
        };
        b
    }};
}

struct EncoderWrapper<'a> {
    lazy: &'a mut LazyEncoder,
    index_alloc: &'a mut usize,
}

impl<'a> EncoderWrapper<'a> {
    #[inline(always)]
    fn variant_index_u8(variant_index: u32) -> Result<u8> {
        if variant_index > u8::MAX as u32 {
            err("enums with more than 256 variants are unsupported")
        } else {
            Ok(variant_index as u8)
        }
    }

    #[inline(always)]
    fn serialize_enum(self, variant_index: u32) -> Result<EncoderWrapper<'a>> {
        let b = specify!(self, Enum);
        b.0.encode(&Self::variant_index_u8(variant_index)?);
        let lazy = get_mut_or_resize(&mut b.1, variant_index as usize);
        lazy.reserve_fast(1); // TODO use push instead.
        Ok(Self {
            lazy,
            index_alloc: self.index_alloc,
        })
    }
}

macro_rules! impl_ser {
    ($name:ident, $t:ty, $variant:ident) => {
        // #[inline(always)] seems to be slower than regular #[inline] in this case.
        #[inline]
        fn $name(self, v: $t) -> Result<()> {
            specify!(self, $variant).encode(&v);
            Ok(())
        }
    };
}

impl<'a> Serializer for EncoderWrapper<'a> {
    type Ok = ();
    type Error = Error;
    type SerializeSeq = SeqSerializer<'a>;
    type SerializeTuple = TupleSerializer<'a>;
    type SerializeTupleStruct = TupleSerializer<'a>;
    type SerializeTupleVariant = TupleSerializer<'a>;
    type SerializeMap = MapSerializer<'a>;
    type SerializeStruct = TupleSerializer<'a>;
    type SerializeStructVariant = TupleSerializer<'a>;

    // Use native encoders.
    impl_ser!(serialize_bool, bool, Bool);
    impl_ser!(serialize_f32, f32, F32);
    impl_ser!(serialize_i8, i8, I8);
    impl_ser!(serialize_i16, i16, I16);
    impl_ser!(serialize_i32, i32, I32);
    impl_ser!(serialize_i64, i64, I64);
    impl_ser!(serialize_i128, i128, I128);
    impl_ser!(serialize_str, &str, Str);
    impl_ser!(serialize_u8, u8, U8);
    impl_ser!(serialize_u16, u16, U16);
    impl_ser!(serialize_u32, u32, U32);
    impl_ser!(serialize_u64, u64, U64);
    impl_ser!(serialize_u128, u128, U128);

    // IntEncoder works on f64/char.
    impl_ser!(serialize_f64, f64, U64);
    impl_ser!(serialize_char, char, U32);

    #[inline(always)]
    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
        v.serialize(self)
    }

    #[inline(always)]
    fn serialize_none(self) -> Result<Self::Ok> {
        // Faster than self.serialize_enum(0)? because it skips resizing vec and reserving nothing.
        // TODO generates multiple copies of specify!(self, Enum) -> cold.
        Ok(specify!(self, Enum).0.encode(&0))
    }

    #[inline(always)]
    fn serialize_some<T: ?Sized>(self, v: &T) -> Result<Self::Ok>
    where
        T: Serialize,
    {
        v.serialize(self.serialize_enum(1)?)
    }

    #[inline(always)]
    fn serialize_unit(self) -> Result<Self::Ok> {
        Ok(())
    }

    #[inline(always)]
    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
        Ok(())
    }

    #[inline(always)]
    fn serialize_unit_variant(
        self,
        _name: &'static str,
        variant_index: u32,
        _variant: &'static str,
    ) -> Result<Self::Ok> {
        // Faster than self.serialize_enum(variant_index)? because it skips resizing vec and reserving nothing.
        Ok(specify!(self, Enum)
            .0
            .encode(&Self::variant_index_u8(variant_index)?))
    }

    #[inline(always)]
    fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Self::Ok>
    where
        T: Serialize,
    {
        value.serialize(self)
    }

    #[inline(always)]
    fn serialize_newtype_variant<T: ?Sized>(
        self,
        _name: &'static str,
        variant_index: u32,
        _variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok>
    where
        T: Serialize,
    {
        value.serialize(self.serialize_enum(variant_index)?)
    }

    #[inline(always)]
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
        let len = len.expect("sequence must have len");
        let b = specify!(self, Seq);
        b.0.encode(&len);
        b.1.reserve_fast(len);
        Ok(SeqSerializer {
            lazy: &mut b.1,
            index_alloc: self.index_alloc,
            len,
        })
    }

    #[inline(always)]
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
        // Fast path: avoid overhead of tuple for 1 element.
        if len == 1 {
            return Ok(TupleSerializer {
                encoders: core::slice::from_mut(self.lazy),
                index_alloc: self.index_alloc,
            });
        }

        // Copy of specify! macro that takes an additional len parameter to cold.
        let lazy = &mut *self.lazy;
        match lazy {
            LazyEncoder::Specified {
                specified: SpecifiedEncoder::Tuple(_),
                ..
            } => (),
            _ => {
                #[cold]
                fn cold(me: &mut LazyEncoder, len: usize) {
                    let &mut LazyEncoder::Unspecified { reserved } = me else {
                        type_changed!()
                    };
                    *me = LazyEncoder::Specified {
                        specified: SpecifiedEncoder::Tuple(default_box_slice(len)),
                        index: usize::MAX, // We never use index for SpecifiedEncoder::Tuple.
                    };
                    let LazyEncoder::Specified { specified, .. } = me else {
                        unreachable!();
                    };
                    if let Some(reserved) = reserved {
                        specified.reserve(reserved);
                    }
                }
                cold(lazy, len);
            }
        };
        let LazyEncoder::Specified {
            specified: SpecifiedEncoder::Tuple(encoders),
            ..
        } = lazy
        else {
            // Safety: see specify! macro which this is based on.
            unsafe { core::hint::unreachable_unchecked() };
        };
        if encoders.len() != len {
            type_changed!() // Removes multiple bounds checks.
        }
        Ok(TupleSerializer {
            encoders,
            index_alloc: self.index_alloc,
        })
    }

    #[inline(always)]
    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct> {
        self.serialize_tuple(len)
    }

    #[inline(always)]
    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        variant_index: u32,
        _variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleVariant> {
        self.serialize_enum(variant_index)?.serialize_tuple(len)
    }

    #[inline(always)]
    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
        let len = len.expect("sequence must have len");
        let b = specify!(self, Map);
        b.0.encode(&len);
        b.1 .0.reserve_fast(len);
        b.1 .1.reserve_fast(len);
        Ok(MapSerializer {
            encoders: &mut b.1,
            index_alloc: self.index_alloc,
            len,
            key_serialized: false, // No keys have been serialized yet, so serialize_value can't be called.
        })
    }

    #[inline(always)]
    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
        self.serialize_tuple(len)
    }

    #[inline(always)]
    fn serialize_struct_variant(
        self,
        _name: &'static str,
        variant_index: u32,
        _variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStructVariant> {
        self.serialize_enum(variant_index)?.serialize_tuple(len)
    }

    #[inline(always)]
    fn is_human_readable(&self) -> bool {
        false
    }
}

macro_rules! ok_error_end {
    () => {
        type Ok = ();
        type Error = Error;
        #[inline(always)]
        fn end(self) -> Result<Self::Ok> {
            Ok(())
        }
    };
}

struct SeqSerializer<'a> {
    lazy: &'a mut LazyEncoder,
    index_alloc: &'a mut usize,
    len: usize,
}

impl SerializeSeq for SeqSerializer<'_> {
    ok_error_end!();
    #[inline(always)]
    fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        // Safety: Make sure safe code doesn't lie about len and cause UB since we've only reserved len elements.
        self.len = self.len.checked_sub(1).expect("length mismatch");
        value.serialize(EncoderWrapper {
            lazy: &mut *self.lazy,
            index_alloc: &mut *self.index_alloc,
        })
    }
}

struct TupleSerializer<'a> {
    encoders: &'a mut [LazyEncoder], // [field0, field1, ..]
    index_alloc: &'a mut usize,
}

macro_rules! impl_tuple {
    ($tr:ty, $fun:ident $(, $key:ident)?) => {
        impl $tr for TupleSerializer<'_> {
            ok_error_end!();
            #[inline(always)]
            fn $fun<T: Serialize + ?Sized>(&mut self, $($key: &'static str,)? value: &T) -> Result<()> {
                let (lazy, remaining) = core::mem::take(&mut self.encoders)
                    .split_first_mut()
                    .expect("length mismatch");
                self.encoders = remaining;
                value.serialize(EncoderWrapper {
                    lazy,
                    index_alloc: &mut *self.index_alloc,
                })
            }

            $(
                fn skip_field(&mut self, $key: &'static str) -> Result<()> {
                    err("skip field is not supported")
                }
            )?
        }
    };
}
impl_tuple!(SerializeTuple, serialize_element);
impl_tuple!(SerializeTupleStruct, serialize_field);
impl_tuple!(SerializeTupleVariant, serialize_field);
impl_tuple!(SerializeStruct, serialize_field, _key);
impl_tuple!(SerializeStructVariant, serialize_field, _key);

struct MapSerializer<'a> {
    encoders: &'a mut (LazyEncoder, LazyEncoder), // (keys, values)
    index_alloc: &'a mut usize,
    len: usize,
    key_serialized: bool,
}

impl SerializeMap for MapSerializer<'_> {
    ok_error_end!();
    #[inline(always)]
    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>
    where
        T: Serialize,
    {
        // Safety: Make sure safe code doesn't lie about len and cause UB since we've only reserved len keys/values.
        self.len = self.len.checked_sub(1).expect("length mismatch");
        // Safety: Make sure serialize_value is called at most once after each serialize_key.
        self.key_serialized = true;
        key.serialize(EncoderWrapper {
            lazy: &mut self.encoders.0,
            index_alloc: &mut *self.index_alloc,
        })
    }

    #[inline(always)]
    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>
    where
        T: Serialize,
    {
        // Safety: Make sure serialize_value is called at most once after each serialize_key.
        assert!(
            core::mem::take(&mut self.key_serialized),
            "serialize_value before serialize_key"
        );
        value.serialize(EncoderWrapper {
            lazy: &mut self.encoders.1,
            index_alloc: &mut *self.index_alloc,
        })
    }
    // TODO implement serialize_entry to avoid checking key_serialized.
}

#[cfg(test)]
mod tests {
    use core::num::NonZeroUsize;
    use serde::ser::{SerializeMap, SerializeSeq, SerializeTuple};
    use serde::{Serialize, Serializer};

    #[test]
    fn enum_256_variants() {
        enum Enum {
            A,
            B,
        }
        impl Serialize for Enum {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                let variant_index = match self {
                    Self::A => 255,
                    Self::B => 256,
                };
                serializer.serialize_unit_variant("", variant_index, "")
            }
        }
        assert!(crate::serialize(&Enum::A).is_ok());
        assert!(crate::serialize(&Enum::B).is_err());
    }

    #[test]
    #[should_panic(expected = "type changed")]
    fn test_type_changed() {
        struct BoolOrU8(bool);
        impl Serialize for BoolOrU8 {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                if self.0 {
                    serializer.serialize_bool(false)
                } else {
                    serializer.serialize_u8(1)
                }
            }
        }
        let _ = crate::serialize(&vec![BoolOrU8(false), BoolOrU8(true)]);
    }

    #[test]
    #[should_panic(expected = "type changed")]
    fn test_tuple_len_changed() {
        struct TupleN(usize);
        impl Serialize for TupleN {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                let mut tuple = serializer.serialize_tuple(self.0)?;
                (0..self.0).try_for_each(|_| tuple.serialize_element(&false))?;
                tuple.end()
            }
        }
        let _ = crate::serialize(&vec![TupleN(1), TupleN(2)]);
    }

    // Has to be a macro because it borrows something on the stack and returns it.
    macro_rules! new_wrapper {
        () => {
            super::EncoderWrapper {
                lazy: &mut super::LazyEncoder::Unspecified {
                    reserved: NonZeroUsize::new(1),
                },
                index_alloc: &mut 0,
            }
        };
    }

    #[test]
    fn seq_valid() {
        let w = new_wrapper!();
        let mut seq = w.serialize_seq(Some(1)).unwrap();
        let _ = seq.serialize_element(&0u8); // serialize_seq 1 == serialize 1.
    }

    #[test]
    #[should_panic = "length mismatch"]
    fn seq_incorrect_len() {
        let w = new_wrapper!();
        let mut seq = w.serialize_seq(Some(1)).unwrap();
        let _ = seq.serialize_element(&0u8); // serialize_seq 1 != serialize 2.
        let _ = seq.serialize_element(&0u8);
    }

    #[test]
    fn map_valid() {
        let w = new_wrapper!();
        let mut map = w.serialize_map(Some(1)).unwrap();
        let _ = map.serialize_key(&0u8); // serialize_map 1 == (key, value).
        let _ = map.serialize_value(&0u8);
    }

    #[test]
    #[should_panic = "length mismatch"]
    fn map_incorrect_len_keys() {
        let w = new_wrapper!();
        let mut map = w.serialize_map(Some(1)).unwrap();
        let _ = map.serialize_key(&0u8); // serialize_map 1 != (key, _) (key, _)
        let _ = map.serialize_key(&0u8);
    }

    #[test]
    #[should_panic = "serialize_value before serialize_key"]
    fn map_value_before_key() {
        let w = new_wrapper!();
        let mut map = w.serialize_map(Some(1)).unwrap();
        let _ = map.serialize_value(&0u8);
    }

    #[test]
    #[should_panic = "serialize_value before serialize_key"]
    fn map_incorrect_len_values() {
        let w = new_wrapper!();
        let mut map = w.serialize_map(Some(1)).unwrap();
        let _ = map.serialize_key(&0u8); // serialize_map 1 != (key, value) (_, value).
        let _ = map.serialize_value(&0u8);
        let _ = map.serialize_value(&0u8);
    }
}