secure-types 0.5.16

Secure data types that protect sensitive data in memory via locking and zeroization.
Documentation
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! The codec encoder, exercised through the public API.

#![cfg(feature = "codec")]

use core::fmt;
use std::collections::BTreeMap;

use secure_types::{EncodeError, FORMAT_VERSION, SecureBytes, SecureVec};
use serde::Serialize;
use serde::ser::{self, SerializeMap as _, SerializeSeq as _, SerializeStruct as _};

#[test]
fn test_scalars_are_little_endian_and_fixed_width() {
   assert_encodes_to(&true, &[FORMAT_VERSION, 0x01]);
   assert_encodes_to(&false, &[FORMAT_VERSION, 0x00]);

   assert_encodes_to(&1u8, &[FORMAT_VERSION, 0x01]);
   assert_encodes_to(&0x0102u16, &[FORMAT_VERSION, 0x02, 0x01]);
   assert_encodes_to(&1u32, &[FORMAT_VERSION, 0x01, 0x00, 0x00, 0x00]);
   assert_encodes_to(
      &1u64,
      &[FORMAT_VERSION, 0x01, 0, 0, 0, 0, 0, 0, 0],
   );
   assert_encodes_to(
      &1u128,
      &[
         FORMAT_VERSION,
         0x01,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
         0,
      ],
   );

   assert_encodes_to(&(-1i8), &[FORMAT_VERSION, 0xFF]);
   assert_encodes_to(&(-2i16), &[FORMAT_VERSION, 0xFE, 0xFF]);
   assert_encodes_to(
      &(-1i32),
      &[FORMAT_VERSION, 0xFF, 0xFF, 0xFF, 0xFF],
   );
   assert_encodes_to(
      &(-1i64),
      &[
         FORMAT_VERSION,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
      ],
   );
   assert_encodes_to(
      &(-1i128),
      &[
         FORMAT_VERSION,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
         0xFF,
      ],
   );

   assert_encodes_to(&1.5f32, &[FORMAT_VERSION, 0x00, 0x00, 0xC0, 0x3F]);
   assert_encodes_to(
      &1.5f64,
      &[
         FORMAT_VERSION,
         0x00,
         0x00,
         0x00,
         0x00,
         0x00,
         0x00,
         0xF8,
         0x3F,
      ],
   );

   assert_encodes_to(&'A', &[FORMAT_VERSION, 0x41, 0x00, 0x00, 0x00]);
}

#[test]
fn test_str_is_length_prefixed_raw_utf8() {
   assert_encodes_to(&"", &[FORMAT_VERSION, 0x00]);
   assert_encodes_to(&"ab", &[FORMAT_VERSION, 0x02, b'a', b'b']);

   // Multi-byte UTF-8 is length-prefixed in bytes, not chars, and is not
   // escaped in any way.
   assert_encodes_to(&"é", &[FORMAT_VERSION, 0x02, 0xC3, 0xA9]);
}

#[test]
fn test_bytes_are_a_single_length_prefixed_blob() {
   // `SecureVec<u8>` serializes through `serialize_bytes`, so a key is one
   // framed blob rather than an element-per-byte sequence.
   let secret = SecureVec::from_slice(&[1u8, 2, 3]).unwrap();

   assert_encodes_to(&secret, &[FORMAT_VERSION, 0x03, 0x01, 0x02, 0x03]);
}

#[test]
fn test_option_unit_and_newtype() {
   assert_encodes_to(&Option::<u8>::None, &[FORMAT_VERSION, 0x00]);
   assert_encodes_to(&Some(7u8), &[FORMAT_VERSION, 0x01, 0x07]);

   assert_encodes_to(&(), &[FORMAT_VERSION]);
   assert_encodes_to(&UnitStruct, &[FORMAT_VERSION]);

   assert_encodes_to(&NewtypeStruct(9), &[FORMAT_VERSION, 0x09]);
}

#[test]
fn test_sequences_and_tuples_carry_their_length() {
   assert_encodes_to(
      &[1u8, 2, 3],
      &[FORMAT_VERSION, 0x03, 0x01, 0x02, 0x03],
   );
   assert_encodes_to(
      &[1u8, 2, 3][..],
      &[FORMAT_VERSION, 0x03, 0x01, 0x02, 0x03],
   );
   assert_encodes_to(
      &(1u8, 2u16),
      &[FORMAT_VERSION, 0x02, 0x01, 0x02, 0x00],
   );

   // A long count takes a multi-byte varint, so the prefix is not always one byte.
   let long = [0u8; 200];
   encoded(&long[..]).unlock_slice(|bytes| {
      assert_eq!(&bytes[..3], &[FORMAT_VERSION, 0xC8, 0x01]);
      assert_eq!(bytes.len(), 1 + 2 + 200);
   });
}

#[test]
fn test_maps() {
   let mut map = BTreeMap::new();
   map.insert("a", 1u8);
   assert_encodes_to(&map, &[FORMAT_VERSION, 0x01, 0x01, b'a', 0x01]);

   let mut pair = BTreeMap::new();
   pair.insert("a", 1u8);
   pair.insert("b", 2u8);
   assert_encodes_to(
      &pair,
      &[FORMAT_VERSION, 0x02, 0x01, b'a', 0x01, 0x01, b'b', 0x02],
   );
}

/// Pins the whole field layout: count, then name, `u32` length, and body.
#[test]
fn test_struct_field_layout() {
   assert_encodes_to(
      &Point { x: 1, y: 300 },
      &[
         FORMAT_VERSION,
         0x02,
         0x01,
         b'x',
         0x01,
         0x00,
         0x00,
         0x00,
         0x01,
         0x01,
         b'y',
         0x02,
         0x00,
         0x00,
         0x00,
         0x2C,
         0x01,
      ],
   );
}

/// The frame of `point` must cover the nested struct's whole encoding and
/// nothing more: a nested struct's first field must not close the frame of
/// the field holding it.
#[test]
fn test_nested_struct_frames_close_only_their_own_scope() {
   assert_encodes_to(
      &Outer {
         name: "ab",
         point: Point { x: 1, y: 300 },
      },
      &[
         FORMAT_VERSION,
         0x02,
         // "name" -> 2-byte string "ab"
         0x04,
         b'n',
         b'a',
         b'm',
         b'e',
         0x03,
         0x00,
         0x00,
         0x00,
         0x02,
         b'a',
         b'b',
         // "point" -> 16-byte nested struct
         0x05,
         b'p',
         b'o',
         b'i',
         b'n',
         b't',
         0x10,
         0x00,
         0x00,
         0x00,
         0x02,
         0x01,
         b'x',
         0x01,
         0x00,
         0x00,
         0x00,
         0x01,
         0x01,
         b'y',
         0x02,
         0x00,
         0x00,
         0x00,
         0x2C,
         0x01,
      ],
   );
}

#[test]
fn test_empty_and_fully_skipped_structs_emit_a_zero_count() {
   assert_encodes_to(&EmptyStruct {}, &[FORMAT_VERSION, 0x00]);
}

#[test]
fn test_skipped_fields_shift_the_count_and_nothing_else() {
   assert_encodes_to(
      &MidSkip {
         first: 1,
         middle: None,
         last: 2,
      },
      &[
         FORMAT_VERSION,
         0x02,
         0x05,
         b'f',
         b'i',
         b'r',
         b's',
         b't',
         0x01,
         0x00,
         0x00,
         0x00,
         0x01,
         0x04,
         b'l',
         b'a',
         b's',
         b't',
         0x01,
         0x00,
         0x00,
         0x00,
         0x02,
      ],
   );

   assert_encodes_to(
      &MidSkip {
         first: 1,
         middle: Some(9),
         last: 2,
      },
      &[
         FORMAT_VERSION,
         0x03,
         0x05,
         b'f',
         b'i',
         b'r',
         b's',
         b't',
         0x01,
         0x00,
         0x00,
         0x00,
         0x01,
         0x06,
         b'm',
         b'i',
         b'd',
         b'd',
         b'l',
         b'e',
         0x02,
         0x00,
         0x00,
         0x00,
         0x01,
         0x09,
         0x04,
         b'l',
         b'a',
         b's',
         b't',
         0x01,
         0x00,
         0x00,
         0x00,
         0x02,
      ],
   );
}

#[test]
fn test_skip_serializing_removes_the_field_entirely() {
   assert_encodes_to(
      &WithNever { kept: 1, never: 9 },
      &[
         FORMAT_VERSION,
         0x01,
         0x04,
         b'k',
         b'e',
         b'p',
         b't',
         0x01,
         0x00,
         0x00,
         0x00,
         0x01,
      ],
   );
}

#[test]
fn test_enum_variants_are_name_tagged() {
   assert_encodes_to(
      &Shape::Unit,
      &[FORMAT_VERSION, 0x04, b'U', b'n', b'i', b't'],
   );
   assert_encodes_to(
      &Shape::New(7),
      &[FORMAT_VERSION, 0x03, b'N', b'e', b'w', 0x07],
   );
   assert_encodes_to(
      &Shape::Tup(1, 300),
      &[
         FORMAT_VERSION,
         0x03,
         b'T',
         b'u',
         b'p',
         0x02,
         0x01,
         0x2C,
         0x01,
      ],
   );
   assert_encodes_to(
      &Shape::Named { a: 5 },
      &[
         FORMAT_VERSION,
         0x05,
         b'N',
         b'a',
         b'm',
         b'e',
         b'd',
         0x01,
         0x01,
         b'a',
         0x01,
         0x00,
         0x00,
         0x00,
         0x05,
      ],
   );
}

/// `serde`'s `collect_seq` passes `None` whenever `size_hint` is not exact,
/// so this path is reachable without a hand-written `Serialize` impl.
#[test]
fn test_unknown_length_seq_is_buffered_in_locked_memory() {
   assert_encodes_to(
      &UnknownLengthSeq,
      &[FORMAT_VERSION, 0x03, 0x01, 0x02, 0x03],
   );
}

#[test]
fn test_unknown_length_map_counts_entries_not_values() {
   assert_encodes_to(
      &UnknownLengthMap,
      &[FORMAT_VERSION, 0x02, 0x01, b'a', 0x01, 0x01, b'b', 0x02],
   );
}

/// A length prefix that lies about the payload would decode subtly wrong, so
/// a mis-counting `Serialize` impl is rejected instead of producing a buffer.
#[test]
fn test_element_count_mismatches_are_rejected() {
   assert!(matches!(
      secure_types::encode(&DeclaresTooMany),
      Err(EncodeError::ElementCountMismatch)
   ));

   assert!(matches!(
      secure_types::encode(&WritesMoreThanDeclared),
      Err(EncodeError::ElementCountMismatch)
   ));

   assert!(matches!(
      secure_types::encode(&StructDeclaresTooMany),
      Err(EncodeError::ElementCountMismatch)
   ));
}

/// `serde`'s default `collect_str` would build this string in a plain
/// `String`; ours streams it into locked memory and encodes it as a `str`.
#[test]
fn test_collect_str_encodes_as_a_length_prefixed_str() {
   assert_encodes_to(
      &Displays(7),
      &[FORMAT_VERSION, 0x04, b'i', b'd', b'-', b'7'],
   );
}

#[test]
fn test_is_not_human_readable() {
   struct RecordsReadability;

   impl Serialize for RecordsReadability {
      fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
      where
         S: ser::Serializer,
      {
         let readable = serializer.is_human_readable();
         serializer.serialize_bool(readable)
      }
   }

   assert_encodes_to(&RecordsReadability, &[FORMAT_VERSION, 0x00]);
}

// Brings in the `Serialize` *derive* as well as the trait, which is what the
// fixtures below are written with.
// Needed to call the sink methods on the associated types the manual
// `Serialize` impls below build. `as _` keeps the names out of the way.

/// Encodes `value` into a fresh locked buffer, version byte included.
fn encoded<T>(value: &T) -> SecureBytes
where
   T: ?Sized + Serialize,
{
   secure_types::encode(value).unwrap()
}

fn assert_encodes_to<T>(value: &T, expected: &[u8])
where
   T: ?Sized + Serialize,
{
   encoded(value).unlock_slice(|bytes| {
      assert_eq!(
         bytes, expected,
         "\n  actual:   {bytes:02X?}\n  expected: {expected:02X?}"
      )
   });
}

#[derive(Serialize)]
struct EmptyStruct {}

#[derive(Serialize)]
struct UnitStruct;

#[derive(Serialize)]
struct NewtypeStruct(u8);

#[derive(Serialize)]
struct Point {
   x: u8,
   y: u16,
}

#[derive(Serialize)]
struct Outer {
   name: &'static str,
   point: Point,
}

#[derive(Serialize)]
struct MidSkip {
   first: u8,
   #[serde(skip_serializing_if = "Option::is_none")]
   middle: Option<u8>,
   last: u8,
}

#[derive(Serialize)]
struct WithNever {
   kept: u8,
   #[serde(skip_serializing)]
   #[allow(dead_code)]
   never: u8,
}

#[derive(Serialize)]
enum Shape {
   Unit,
   New(u8),
   Tup(u8, u16),
   Named { a: u8 },
}

struct UnknownLengthSeq;

impl Serialize for UnknownLengthSeq {
   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   where
      S: ser::Serializer,
   {
      let mut seq = serializer.serialize_seq(None)?;
      seq.serialize_element(&1u8)?;
      seq.serialize_element(&2u8)?;
      seq.serialize_element(&3u8)?;
      seq.end()
   }
}

struct UnknownLengthMap;

impl Serialize for UnknownLengthMap {
   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   where
      S: ser::Serializer,
   {
      let mut map = serializer.serialize_map(None)?;
      map.serialize_entry("a", &1u8)?;
      map.serialize_entry("b", &2u8)?;
      map.end()
   }
}

struct DeclaresTooMany;

impl Serialize for DeclaresTooMany {
   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   where
      S: ser::Serializer,
   {
      let mut seq = serializer.serialize_seq(Some(3))?;
      seq.serialize_element(&1u8)?;
      seq.serialize_element(&2u8)?;
      seq.end()
   }
}

struct WritesMoreThanDeclared;

impl Serialize for WritesMoreThanDeclared {
   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   where
      S: ser::Serializer,
   {
      let mut seq = serializer.serialize_seq(Some(1))?;
      seq.serialize_element(&1u8)?;
      seq.serialize_element(&2u8)?;
      seq.end()
   }
}

struct StructDeclaresTooMany;

impl Serialize for StructDeclaresTooMany {
   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   where
      S: ser::Serializer,
   {
      let mut structure = serializer.serialize_struct("Short", 3)?;
      structure.serialize_field("a", &1u8)?;
      structure.end()
   }
}

struct Displays(u8);

impl fmt::Display for Displays {
   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
      write!(f, "id-{}", self.0)
   }
}

impl Serialize for Displays {
   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   where
      S: ser::Serializer,
   {
      serializer.collect_str(self)
   }
}

/// The encode-side half of the property the decoder pins in
/// `codec_decoder.rs::test_error_messages_never_echo_wire_bytes`: an error must
/// never carry payload bytes, in `Display` or `Debug`.
#[test]
fn test_encode_errors_never_echo_payload_bytes() {
   const MARKER: &str = "SEED-PHRASE-MARKER-ENCODE";

   /// Writes a secret, then declares a different element count, so encoding
   /// fails *after* the secret has already been written.
   struct FailsAfterWritingTheSecret;

   impl Serialize for FailsAfterWritingTheSecret {
      fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
      where
         S: ser::Serializer,
      {
         let mut seq = serializer.serialize_seq(Some(2))?;
         seq.serialize_element(MARKER)?;
         seq.end()
      }
   }

   // `SecureBytes` deliberately does not implement `Debug`, so `unwrap_err()`
   // (which needs `T: Debug`) is not available here.
   let error = match secure_types::encode(&FailsAfterWritingTheSecret) {
      Ok(_) => panic!("encoding a mismatched element count should have failed"),
      Err(error) => error,
   };

   assert!(
      matches!(&error, EncodeError::ElementCountMismatch),
      "expected the count mismatch to fail the encoding, got {error:?}"
   );

   for form in [error.to_string(), format!("{error:?}")] {
      assert!(
         !form.contains(MARKER),
         "an encode error echoed payload bytes: {form}"
      );
   }
}

/// A `Serialize` impl's own rejection message must not reach the error either.
///
/// `serde::ser::Error::custom` is the only way an impl can attach text, and it is free to
/// format a secret into that text — which is exactly why the codec must not keep it. This is
/// the encode-side counterpart of the decoder's `test_wire_names_never_reach_the_error_message`;
/// before `Custom` lost its payload the marker below was rendered by both `Display` and `Debug`.
#[test]
fn test_a_serialize_impls_rejection_message_never_reaches_the_error() {
   const MARKER: &str = "SEED-PHRASE-MARKER-ENCODE-CUSTOM";

   struct RejectsWithTheSecret;

   impl Serialize for RejectsWithTheSecret {
      fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
      where
         S: ser::Serializer,
      {
         // A hand-written impl can put payload into its message; the codec discards it
         // rather than render it, so nothing reaches a log.
         let _ = serializer;
         Err(ser::Error::custom(format!(
            "refusing to encode {MARKER}"
         )))
      }
   }

   // `SecureBytes` deliberately does not implement `Debug`, so `unwrap_err()` is unavailable.
   let error = match secure_types::encode(&RejectsWithTheSecret) {
      Ok(_) => panic!("a rejected value should not encode"),
      Err(error) => error,
   };

   assert!(
      matches!(&error, EncodeError::Custom),
      "expected the message-free `Custom` variant, got {error:?}"
   );

   for form in [error.to_string(), format!("{error:?}")] {
      assert!(
         !form.contains(MARKER),
         "the encode error echoed the impl's message: {form}"
      );
   }
}

/// Encodes `value` into a fresh locked buffer, for comparison.
fn locked_bytes<T>(value: &T) -> Vec<u8>
where
   T: ?Sized + Serialize,
{
   secure_types::encode(value)
      .unwrap()
      .unlock_slice(<[u8]>::to_vec)
}

/// `encode_to_vec` and `encode_to_vec_with_capacity` must produce the same
/// document as `encode`, byte for byte, whatever the initial capacity was.
fn assert_vec_encoding_matches<T>(value: &T)
where
   T: ?Sized + Serialize,
{
   let expected = locked_bytes(value);

   let plain = secure_types::encode_to_vec(value).unwrap();
   assert_eq!(
      plain, expected,
      "\n  encode_to_vec: {plain:02X?}\n  encode:        {expected:02X?}"
   );
   assert_eq!(plain.first(), Some(&FORMAT_VERSION));

   // The initial capacity is a sizing hint, never part of the document: an
   // under-sized and an exactly-sized buffer must land on the same bytes.
   for capacity in [0, 1, expected.len()] {
      let sized = secure_types::encode_to_vec_with_capacity(value, capacity).unwrap();
      assert_eq!(
         sized, expected,
         "encode_to_vec_with_capacity({capacity}) disagreed with encode"
      );
   }
}

#[test]
fn test_encode_to_vec_matches_encode() {
   // Scalars, strings and the containers that exercise the varint length
   // prefixes.
   assert_vec_encoding_matches(&true);
   assert_vec_encoding_matches(&(-1i64));
   assert_vec_encoding_matches(&u64::MAX);
   assert_vec_encoding_matches(&'x');
   assert_vec_encoding_matches(&"a string");
   assert_vec_encoding_matches(&Some(7u8));
   assert_vec_encoding_matches(&Option::<u8>::None);
   assert_vec_encoding_matches(&vec![1u8, 2, 3]);
   assert_vec_encoding_matches(&BTreeMap::from([("k", 1u8)]));

   // Structs, enums, and the shapes whose length is only known at the end.
   assert_vec_encoding_matches(&EmptyStruct {});
   assert_vec_encoding_matches(&UnitStruct);
   assert_vec_encoding_matches(&NewtypeStruct(7));
   assert_vec_encoding_matches(&Point { x: 1, y: 0x0102 });
   assert_vec_encoding_matches(&Outer {
      name: "vault",
      point: Point { x: 3, y: 4 },
   });
   assert_vec_encoding_matches(&MidSkip {
      first: 1,
      middle: None,
      last: 2,
   });
   assert_vec_encoding_matches(&WithNever { kept: 1, never: 2 });
   assert_vec_encoding_matches(&Shape::Unit);
   assert_vec_encoding_matches(&Shape::New(1));
   assert_vec_encoding_matches(&Shape::Tup(1, 2));
   assert_vec_encoding_matches(&Shape::Named { a: 1 });
   assert_vec_encoding_matches(&UnknownLengthSeq);
   assert_vec_encoding_matches(&UnknownLengthMap);
   assert_vec_encoding_matches(&Displays(7));
}

/// The pattern `encode_into_vec` exists for: a codec tag in front of the
/// document, written once into the buffer the caller keeps.
#[test]
fn test_encode_into_vec_appends_after_a_prefix() {
   const VAULT_PAYLOAD_CODEC: u8 = 0x07;

   let value = Outer {
      name: "vault",
      point: Point { x: 1, y: 2 },
   };
   let document = locked_bytes(&value);

   let mut buffer = Vec::new();
   buffer.push(VAULT_PAYLOAD_CODEC);

   secure_types::encode_into_vec(&mut buffer, &value).unwrap();

   assert_eq!(buffer[0], VAULT_PAYLOAD_CODEC);
   assert_eq!(
      &buffer[1..],
      document.as_slice(),
      "the document must be appended after the prefix, unchanged"
   );
}

/// A failed encoding must not leave a partial document in a buffer this crate
/// cannot wipe — and must leave whatever the caller already had in it alone.
///
/// `DeclaresTooMany` fails at `end()`, after the version byte and two of its
/// three declared elements have already been written, so there is always
/// something to erase. `rollback` wipes those bytes and restores the length;
/// a bare `truncate` would only forget them.
#[test]
fn test_encode_into_vec_erases_its_partial_document_on_failure() {
   const PREFIX: &[u8] = b"tag";

   let mut buffer = PREFIX.to_vec();

   let error = secure_types::encode_into_vec(&mut buffer, &DeclaresTooMany)
      .expect_err("a mismatched element count should fail the encoding");

   assert!(matches!(error, EncodeError::ElementCountMismatch));
   assert_eq!(
      buffer, PREFIX,
      "the failed encoding left bytes behind in the caller's buffer"
   );
}

/// `encoded_len` must equal the document `encode` writes, whatever the shape.
///
/// The length is measured by the same serializer that produces the document, so
/// the cases that matter most are the ones whose size is only known at the end:
/// the sequences and maps with no declared length, and `collect_str`.
fn assert_encoded_len_matches<T>(value: &T)
where
   T: ?Sized + Serialize,
{
   let document = locked_bytes(value);

   assert_eq!(
      secure_types::encoded_len(value).unwrap(),
      document.len(),
      "encoded_len disagreed with the encoded document"
   );
}

#[test]
fn test_encoded_len_matches_the_document() {
   assert_encoded_len_matches(&EmptyStruct {});
   assert_encoded_len_matches(&UnitStruct);
   assert_encoded_len_matches(&NewtypeStruct(7));
   assert_encoded_len_matches(&true);
   assert_encoded_len_matches(&"a string");
   assert_encoded_len_matches(&Some(7u8));
   assert_encoded_len_matches(&Option::<u8>::None);
   assert_encoded_len_matches(&vec![1u8, 2, 3]);
   assert_encoded_len_matches(&BTreeMap::from([("k", 1u8)]));
   assert_encoded_len_matches(&Point { x: 1, y: 0x0102 });
   assert_encoded_len_matches(&Outer {
      name: "vault",
      point: Point { x: 3, y: 4 },
   });
   assert_encoded_len_matches(&MidSkip {
      first: 1,
      middle: None,
      last: 2,
   });
   assert_encoded_len_matches(&WithNever { kept: 1, never: 2 });
   assert_encoded_len_matches(&Shape::Unit);
   assert_encoded_len_matches(&Shape::New(1));
   assert_encoded_len_matches(&Shape::Tup(1, 2));
   assert_encoded_len_matches(&Shape::Named { a: 1 });

   // A length prefix changes width at 128, so the count has to come from the
   // varint the encoder actually wrote rather than from `len()`.
   assert_encoded_len_matches(&"x".repeat(127));
   assert_encoded_len_matches(&"x".repeat(128));

   // Sizes that are only known once the value has been walked.
   assert_encoded_len_matches(&UnknownLengthSeq);
   assert_encoded_len_matches(&UnknownLengthMap);
   assert_encoded_len_matches(&Displays(7));
}

/// Measuring has the same failure modes as writing: a value that cannot be
/// encoded has no length, and the partial count is never returned.
#[test]
fn test_encoded_len_fails_where_encode_fails() {
   let error = secure_types::encoded_len(&DeclaresTooMany)
      .expect_err("a mismatched element count should fail the measurement");

   assert!(matches!(error, EncodeError::ElementCountMismatch));
}