vitaminc-aead 0.7.0

Authenticated Encryption with Associated Data (AEAD) primitives. Part of the Vitamin-C cryptographic suite.
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
//! Rust types as [`Encrypt`] sources.
//!
//! Byte strings (`Vec<u8>`, `[u8; N]`, `&[u8]`, `String`, `&str`) are byte
//! and text leaves, as they were for 0.5's `Encrypt` trait. For the same reason
//! as then, `u8` on its own is not a source: if it were, the generic `Vec<T>`
//! sequence impl would overlap the `Vec<u8>` byte leaf. An 8-bit value from
//! a host still arrives as [`Int::U8`]; a Rust caller that needs one uses
//! [`Raw`].

use std::collections::{BTreeMap, HashMap};

use vitaminc_protected::{Controlled, OpaqueDebug, Protected};
use zeroize::Zeroize;

use super::kinds::{Float, Logical, Physical};
use super::{depth, visit_seq, Encrypt, MapSink, SeqSink, Sink};

macro_rules! int {
    ($($ty:ty),* $(,)?) => {
        $(
            impl Encrypt for $ty {
                const DEPTH: Option<usize> = depth::SCALAR;
                fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
                    sink.scalar(None, Physical::Int(self.into()))
                }
            }

            impl Encrypt for &$ty {

                const DEPTH: Option<usize> = depth::SCALAR;
                fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
                    (*self).visit(sink)
                }
            }
        )*
    };
}

int!(i8, i16, i32, i64, i128, u16, u32, u64, u128);

impl Encrypt for bool {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Bool(self))
    }
}

impl Encrypt for f32 {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Float(Float::F32(self)))
    }
}

impl Encrypt for f64 {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Float(Float::F64(self)))
    }
}

/// A borrowed copy scalar is the same scalar, so a borrowed container of
/// them (`&Vec<u32>`, `&[bool]`, `&Option<f64>`) is a source too.
macro_rules! by_ref {
    ($($ty:ty),* $(,)?) => {
        $(
            impl Encrypt for &$ty {
                const DEPTH: Option<usize> = depth::SCALAR;
                fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
                    (*self).visit(sink)
                }
            }
        )*
    };
}

by_ref!(bool, f32, f64);

impl Encrypt for &str {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Text(self))
    }
}

/// An owned byte or text leaf wraps itself before the sink sees it, as 0.5's
/// `Encrypt` impl did, and walks as a borrow of the wrapped value.
/// So a bare leaf that a container moved out, or that a caller handed over
/// bare, still has its buffer wiped when the walk is done with it.
impl Encrypt for String {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        Protected::new(self).visit(sink)
    }
}

impl Encrypt for &String {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Text(self))
    }
}

impl Encrypt for &[u8] {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Bytes(self))
    }
}

/// `Vec<u8>` is a byte leaf, not a sequence of `u8` elements: the same
/// shape `String` describes, and the shape `Vec<u8>` will read back.
impl Encrypt for Vec<u8> {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        Protected::new(self).visit(sink)
    }
}

impl<const N: usize> Encrypt for [u8; N] {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        Protected::new(self).visit(sink)
    }
}

/// Borrowed byte leaves: the caller owns the buffer and its wiping.
impl Encrypt for &Vec<u8> {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Bytes(self))
    }
}

impl<const N: usize> Encrypt for &[u8; N] {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Bytes(self))
    }
}

/// A byte string borrowed from anywhere, for callers holding a slice whose
/// element type would otherwise read as a sequence.
/// `Debug` is redacted, as for every plaintext scalar.
#[derive(Clone, Copy, OpaqueDebug)]
pub struct Bytes<'a>(pub &'a [u8]);

impl Encrypt for Bytes<'_> {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(None, Physical::Bytes(self.0))
    }
}

impl Encrypt for &Bytes<'_> {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        (*self).visit(sink)
    }
}

/// Any scalar, as given: a logical type and a physical value.
///
/// `Debug` is redacted, as for every plaintext scalar.
#[derive(Clone, Copy, OpaqueDebug)]
pub struct Raw<'a>(pub Option<Logical>, pub Physical<'a>);

impl Encrypt for Raw<'_> {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(self.0, self.1)
    }
}

impl Encrypt for &Raw<'_> {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        (*self).visit(sink)
    }
}

/// A borrow of a borrowed source is the same source. This is what a
/// derived struct with a borrowed field (`&'a str`, `&'a [u8]`,
/// `Option<&'a str>`) needs when it is walked by reference, as it is from
/// inside a `Protected`: each field is then visited as `&&'a str`.
impl<'b, T: ?Sized> Encrypt for &&'b T
where
    &'b T: Encrypt,
{
    const DEPTH: Option<usize> = <&'b T as Encrypt>::DEPTH;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        (*self).visit(sink)
    }
}

/// `None` is a null. There is no separate "absent" in the data model, so a
/// host null and a Rust `None` are the same leaf.
impl<T: Encrypt> Encrypt for Option<T> {
    const DEPTH: Option<usize> = T::DEPTH;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        match self {
            Some(v) => v.visit(sink),
            None => sink.scalar(None, Physical::Null),
        }
    }
}

impl<'a, T> Encrypt for &'a Option<T>
where
    &'a T: Encrypt,
{
    const DEPTH: Option<usize> = <&'a T as Encrypt>::DEPTH;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        match self {
            Some(v) => v.visit(sink),
            None => sink.scalar(None, Physical::Null),
        }
    }
}

/// A protected value walks as a borrow of what it wraps, so nothing leaves
/// the wrapper during the walk, and everything in it, visited or not, is
/// zeroized when the wrapper drops at the end of it.
impl<T: Zeroize> Encrypt for Protected<T>
where
    for<'a> &'a T: Encrypt,
{
    const DEPTH: Option<usize> = <&T as Encrypt>::DEPTH;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        self.risky_ref().visit(sink)
        // `self` drops here and zeroizes the whole value.
    }
}

/// A borrowed protected value is the same borrow; the caller's wrapper
/// does the wiping.
impl<'a, T: Zeroize> Encrypt for &'a Protected<T>
where
    &'a T: Encrypt,
{
    const DEPTH: Option<usize> = <&'a T as Encrypt>::DEPTH;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        self.risky_ref().visit(sink)
    }
}

/// An owned sequence takes its elements out one at a time, so a walk that
/// stops part way never drops an unvisited element bare: the elements the
/// walk did not reach are walked into a sink that discards them before they
/// drop, which wipes every owned leaf among them the way a completed walk
/// would. (Inside a `Protected`, a sequence is walked as a borrow instead,
/// and is zeroized whole with its wrapper.)
impl<T: Encrypt> Encrypt for Vec<T> {
    const DEPTH: Option<usize> = depth::container(T::DEPTH);
    fn visit<S: Sink>(mut self, sink: S) -> Result<S::Ok, S::Error> {
        let result = visit_popping(sink, &mut self);
        discard(self);
        result
    }
}

/// Walk `items` in order, popping each element only once its sink exists,
/// so on an error every element not yet visited is still in `items`.
fn visit_popping<S: Sink, T: Encrypt>(sink: S, items: &mut Vec<T>) -> Result<S::Ok, S::Error> {
    items.reverse();
    let mut seq = sink.seq(Some(items.len()))?;
    for _ in 0..items.len() {
        let element = seq.element()?;
        if let Some(item) = items.pop() {
            item.visit(element)?;
        }
    }
    seq.end()
}

/// Visit each of `items` into [`Discard`], so the owned leaves among them
/// wrap themselves and are wiped as they drop.
fn discard<T: Encrypt>(items: Vec<T>) {
    for item in items {
        discard_one(item);
    }
}

/// Walk `value` into a sink that keeps nothing, so every owned leaf in it
/// wraps itself and is wiped as it drops, the way a completed walk would
/// have wiped it. For a source that has to give up part way: a derived
/// struct walks the fields it has not reached through here when an entry
/// fails, as a bare `Vec<T>` does its leftover elements.
#[doc(hidden)]
pub fn discard_one<P: Encrypt>(value: P) {
    // `Discard` never fails, and a source error is no longer anyone's
    // concern once the walk has already failed.
    let _ = value.visit(Discard);
}

/// A sink that keeps nothing. Walking a value into it runs the value's own
/// wiping without sending its contents anywhere.
struct Discard;

/// [`Discard`] never fails on its own; this only carries a source's error.
struct Discarded;

impl super::Error for Discarded {
    fn source(_: super::SourceError) -> Self {
        Discarded
    }
}

impl Sink for Discard {
    type Ok = ();
    type Error = Discarded;
    type Seq = Discard;
    type Map = Discard;

    fn scalar(self, _: Option<Logical>, _: Physical<'_>) -> Result<(), Discarded> {
        Ok(())
    }

    fn seq(self, _: Option<usize>) -> Result<Discard, Discarded> {
        Ok(Discard)
    }

    fn map(self, _: Option<usize>) -> Result<Discard, Discarded> {
        Ok(Discard)
    }

    /// Passthrough is cleartext by contract, so it is not walked.
    fn passthrough<P: Encrypt + Clone>(self, _: P) -> Result<(), Discarded> {
        Ok(())
    }
}

impl SeqSink for Discard {
    type Ok = ();
    type Error = Discarded;
    type Element<'s> = Discard;

    fn element(&mut self) -> Result<Discard, Discarded> {
        Ok(Discard)
    }

    fn end(self) -> Result<(), Discarded> {
        Ok(())
    }
}

impl MapSink for Discard {
    type Ok = ();
    type Error = Discarded;
    type Entry<'s> = Discard;

    fn entry(&mut self, _: &str) -> Result<Discard, Discarded> {
        Ok(Discard)
    }

    fn end(self) -> Result<(), Discarded> {
        Ok(())
    }
}

impl<'a, T> Encrypt for &'a Vec<T>
where
    &'a T: Encrypt,
{
    const DEPTH: Option<usize> = depth::container(<&'a T as Encrypt>::DEPTH);
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        visit_seq(sink, Some(self.len()), self.iter())
    }
}

impl<'a, T> Encrypt for &'a [T]
where
    &'a T: Encrypt,
{
    const DEPTH: Option<usize> = depth::container(<&'a T as Encrypt>::DEPTH);
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        visit_seq(sink, Some(self.len()), self.iter())
    }
}

/// One impl covers compile-time keys (`&'static str`) and runtime keys
/// (`String`), as 0.5's `Encrypt` impl did.
impl<K: AsRef<str>, V: Encrypt> Encrypt for HashMap<K, V> {
    const DEPTH: Option<usize> = depth::container(V::DEPTH);
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        let mut map = sink.map(Some(self.len()))?;
        for (key, value) in self {
            value.visit(map.entry(key.as_ref())?)?;
        }
        map.end()
    }
}

impl<K: AsRef<str>, V: Encrypt> Encrypt for BTreeMap<K, V> {
    const DEPTH: Option<usize> = depth::container(V::DEPTH);
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        let mut map = sink.map(Some(self.len()))?;
        for (key, value) in self {
            value.visit(map.entry(key.as_ref())?)?;
        }
        map.end()
    }
}

impl<'a, K: AsRef<str>, V> Encrypt for &'a HashMap<K, V>
where
    &'a V: Encrypt,
{
    const DEPTH: Option<usize> = depth::container(<&'a V as Encrypt>::DEPTH);
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        let mut map = sink.map(Some(self.len()))?;
        for (key, value) in self {
            value.visit(map.entry(key.as_ref())?)?;
        }
        map.end()
    }
}

impl<'a, K: AsRef<str>, V> Encrypt for &'a BTreeMap<K, V>
where
    &'a V: Encrypt,
{
    const DEPTH: Option<usize> = depth::container(<&'a V as Encrypt>::DEPTH);
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        let mut map = sink.map(Some(self.len()))?;
        for (key, value) in self {
            value.visit(map.entry(key.as_ref())?)?;
        }
        map.end()
    }
}

// The chrono and rust_decimal types are logical types over an int. Each
// source says which, and the int it stands for.

#[cfg(feature = "chrono")]
mod chrono_sources {
    use super::*;
    use crate::plaintext::kinds::{chrono as conv, Int, TimeUnit};
    use crate::plaintext::{Error, SourceError};
    use ::chrono::{DateTime, NaiveDate, Utc};

    impl Encrypt for NaiveDate {
        const DEPTH: Option<usize> = depth::SCALAR;
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            sink.scalar(
                Some(Logical::Date),
                Physical::Int(Int::I32(conv::date_days(self))),
            )
        }
    }

    /// Stored as nanoseconds, the unit of the `TIMESTAMP` tag. A leap second
    /// has no count and stops the walk; a [`Timestamp`](crate::Timestamp)
    /// field refuses it when the value is built instead.
    impl Encrypt for DateTime<Utc> {
        const DEPTH: Option<usize> = depth::SCALAR;
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            let nanos = conv::timestamp_nanos(self).ok_or_else(|| {
                S::Error::source(SourceError::msg(
                    "a leap second has no count of nanoseconds",
                ))
            })?;
            sink.scalar(
                Some(Logical::Timestamp(TimeUnit::Nanos)),
                Physical::Int(Int::I128(nanos)),
            )
        }
    }

    impl Encrypt for &NaiveDate {
        const DEPTH: Option<usize> = depth::SCALAR;
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            (*self).visit(sink)
        }
    }

    impl Encrypt for &DateTime<Utc> {
        const DEPTH: Option<usize> = depth::SCALAR;
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            (*self).visit(sink)
        }
    }
}

#[cfg(feature = "rust_decimal")]
impl Encrypt for rust_decimal::Decimal {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        let (scale, mantissa) = super::kinds::decimal::parts(self);
        sink.scalar(
            Some(Logical::Decimal { scale }),
            Physical::Int(super::kinds::Int::I128(mantissa)),
        )
    }
}

#[cfg(feature = "rust_decimal")]
impl Encrypt for &rust_decimal::Decimal {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        (*self).visit(sink)
    }
}

#[cfg(feature = "uuid")]
impl Encrypt for uuid::Uuid {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        sink.scalar(Some(Logical::Uuid), Physical::Bytes(self.as_bytes()))
    }
}

#[cfg(feature = "uuid")]
impl Encrypt for &uuid::Uuid {
    const DEPTH: Option<usize> = depth::SCALAR;
    fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
        (*self).visit(sink)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plaintext::kinds::Int;
    use crate::plaintext::record::{record, Event, Owned, RecordError};
    use crate::plaintext::{Error, SeqSink, SourceError};

    fn scalar(v: Owned) -> Event {
        Event::Scalar(None, v)
    }

    #[test]
    fn primitives_are_scalars() {
        assert_eq!(
            record(34u32).expect("ok"),
            [scalar(Owned::Int(Int::U32(34)))]
        );
        assert_eq!(record(-1i8).expect("ok"), [scalar(Owned::Int(Int::I8(-1)))]);
        assert_eq!(record(true).expect("ok"), [scalar(Owned::Bool(true))]);
        assert_eq!(
            record(1.5f64).expect("ok"),
            [scalar(Owned::Float(Float::F64(1.5)))]
        );
        assert_eq!(
            record("hi").expect("ok"),
            [scalar(Owned::Text("hi".into()))]
        );
        assert_eq!(
            record(String::from("hi")).expect("ok"),
            [scalar(Owned::Text("hi".into()))]
        );
    }

    // The borrows are the point: each one picks the reference impl.
    #[allow(clippy::needless_borrows_for_generic_args, clippy::op_ref)]
    #[test]
    fn floats_and_borrowed_scalars_are_scalars() {
        assert_eq!(
            record(1.5f32).expect("ok"),
            [scalar(Owned::Float(Float::F32(1.5)))]
        );
        assert_eq!(record(&1.5f32).expect("ok"), record(1.5f32).expect("ok"));
        assert_eq!(record(&1.5f64).expect("ok"), record(1.5f64).expect("ok"));
        assert_eq!(record(&true).expect("ok"), record(true).expect("ok"));
        assert_eq!(record(&7u64).expect("ok"), record(7u64).expect("ok"));
        let owned = String::from("hi");
        assert_eq!(
            record(&owned).expect("ok"),
            [scalar(Owned::Text("hi".into()))]
        );
    }

    #[test]
    fn a_source_error_keeps_its_cause() {
        use core::error::Error as _;

        #[derive(Debug)]
        struct Getter(std::io::Error);
        impl core::fmt::Display for Getter {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_str("getter threw")
            }
        }
        impl core::error::Error for Getter {
            fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
                Some(&self.0)
            }
        }

        let err = SourceError::new(Getter(std::io::Error::other("disk gone")));
        assert_eq!(err.to_string(), "getter threw");
        assert!(err.inner().is::<Getter>());
        assert_eq!(
            err.source().map(|cause| cause.to_string()),
            Some("disk gone".into())
        );
        assert!(SourceError::msg("plain").source().is_none());
    }

    #[test]
    fn byte_strings_are_byte_leaves_not_sequences() {
        assert_eq!(
            record(vec![1u8, 2]).expect("ok"),
            [scalar(Owned::Bytes(vec![1, 2]))]
        );
        assert_eq!(
            record([1u8, 2]).expect("ok"),
            [scalar(Owned::Bytes(vec![1, 2]))]
        );
        assert_eq!(
            record(&[1u8, 2][..]).expect("ok"),
            [scalar(Owned::Bytes(vec![1, 2]))]
        );
        assert_eq!(
            record(Bytes(&[9])).expect("ok"),
            [scalar(Owned::Bytes(vec![9]))]
        );
    }

    #[test]
    fn protected_leaves_reach_the_sink_still_wrapped() {
        // The sink sees the bytes; the only copy is inside `Protected`.
        assert_eq!(
            record(Protected::new(vec![1u8, 2])).expect("ok"),
            [scalar(Owned::Bytes(vec![1, 2]))]
        );
        assert_eq!(
            record(Protected::new(String::from("pw"))).expect("ok"),
            [scalar(Owned::Text("pw".into()))]
        );
        assert_eq!(
            record(Protected::new([7u8; 4])).expect("ok"),
            [scalar(Owned::Bytes(vec![7; 4]))]
        );
        // A composite takes the default path: unwrap, then walk.
        assert_eq!(
            record(Protected::new(vec![1u16, 2])).expect("ok"),
            [
                Event::Seq(Some(2)),
                Event::Element,
                scalar(Owned::Int(Int::U16(1))),
                Event::Element,
                scalar(Owned::Int(Int::U16(2))),
                Event::EndSeq,
            ]
        );
    }

    /// A leaf that wraps itself the way the byte leaves do, and counts
    /// its wipes, so a test can see whether a container's protected path
    /// reaches it.
    #[derive(Clone, Default)]
    struct Counted(std::rc::Rc<std::cell::Cell<usize>>);

    impl Zeroize for Counted {
        fn zeroize(&mut self) {
            self.0.set(self.0.get() + 1);
        }
    }

    impl Encrypt for Counted {
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            Protected::new(self).visit(sink)
        }
    }

    impl Encrypt for &Counted {
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            sink.scalar(None, Physical::Null)
        }
    }

    #[test]
    fn a_protected_container_wipes_each_leaf() {
        let wipes = Counted::default();
        record(Protected::new(vec![wipes.clone(), wipes.clone()])).expect("ok");
        assert_eq!(wipes.0.get(), 2);

        let wipes = Counted::default();
        record(Protected::new(Some(wipes.clone()))).expect("ok");
        assert_eq!(wipes.0.get(), 1);
    }

    /// A borrowed protected value is walked as a borrow of what it wraps,
    /// so nothing leaves the wrapper.
    #[test]
    fn a_borrowed_protected_value_walks_as_its_borrow() {
        let secret = Protected::new(String::from("pw"));
        assert_eq!(
            record(&secret).expect("records"),
            [scalar(Owned::Text("pw".into()))]
        );
        let key = Protected::new([7u8; 4]);
        assert_eq!(
            record(&key).expect("records"),
            [scalar(Owned::Bytes(vec![7; 4]))]
        );
        assert_eq!(secret.risky_ref(), "pw");
    }

    /// A leaf that counts its wipes but does not wrap itself when visited,
    /// so only zeroizing the container it sits in can wipe it.
    #[derive(Clone, Default)]
    struct Tracked(std::rc::Rc<std::cell::Cell<usize>>);

    impl Zeroize for Tracked {
        fn zeroize(&mut self) {
            self.0.set(self.0.get() + 1);
        }
    }

    impl Encrypt for Tracked {
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            sink.scalar(None, Physical::Null)
        }
    }

    impl Encrypt for &Tracked {
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            sink.scalar(None, Physical::Null)
        }
    }

    /// A sink that hands out `elements` element sinks in all, across every
    /// sequence in the walk, and fails on the next one.
    struct StopAfter(std::rc::Rc<std::cell::Cell<usize>>);

    impl StopAfter {
        fn new(elements: usize) -> Self {
            Self(std::rc::Rc::new(std::cell::Cell::new(elements)))
        }
    }

    impl Sink for StopAfter {
        type Ok = ();
        type Error = RecordError;
        type Seq = Self;
        type Map = Self;

        fn scalar(self, _: Option<Logical>, _: Physical<'_>) -> Result<(), RecordError> {
            Ok(())
        }

        fn seq(self, _: Option<usize>) -> Result<Self, RecordError> {
            Ok(self)
        }

        fn map(self, _: Option<usize>) -> Result<Self, RecordError> {
            Ok(self)
        }

        fn passthrough<P: Encrypt + Clone>(self, _: P) -> Result<(), RecordError> {
            Ok(())
        }
    }

    impl SeqSink for StopAfter {
        type Ok = ();
        type Error = RecordError;
        type Element<'s> = Self;

        fn element(&mut self) -> Result<Self, RecordError> {
            match self.0.get() {
                0 => Err(RecordError("stopped".into())),
                left => {
                    self.0.set(left - 1);
                    Ok(Self(self.0.clone()))
                }
            }
        }

        fn end(self) -> Result<(), RecordError> {
            Ok(())
        }
    }

    impl MapSink for StopAfter {
        type Ok = ();
        type Error = RecordError;
        type Entry<'s> = Self;

        fn entry(&mut self, _: &str) -> Result<Self, RecordError> {
            Ok(Self(self.0.clone()))
        }

        fn end(self) -> Result<(), RecordError> {
            Ok(())
        }
    }

    #[test]
    fn a_protected_vec_zeroizes_what_a_failed_walk_did_not_reach() {
        // One element is visited, then the sink fails. The walk borrowed,
        // so all three are still inside the `Protected` and are zeroized
        // with it.
        let wipes = Tracked::default();
        let items = Protected::new(vec![wipes.clone(), wipes.clone(), wipes.clone()]);
        items.visit(StopAfter::new(1)).expect_err("should stop");
        assert_eq!(wipes.0.get(), 3);

        // A failure before the first element leaves everything protected.
        let wipes = Tracked::default();
        let items = Protected::new(vec![wipes.clone(), wipes.clone()]);
        items.visit(StopAfter::new(0)).expect_err("should stop");
        assert_eq!(wipes.0.get(), 2);
    }

    #[test]
    fn a_protected_vec_wipes_every_leaf_when_the_walk_fails() {
        // Nothing leaves the vector during the walk, so all three are
        // zeroized with it, visited or not.
        let wipes = Counted::default();
        let items = Protected::new(vec![wipes.clone(), wipes.clone(), wipes.clone()]);
        items.visit(StopAfter::new(1)).expect_err("should stop");
        assert_eq!(wipes.0.get(), 3);
    }

    #[test]
    fn a_failed_walk_still_wipes_the_owned_leaves_it_did_not_reach() {
        // Bare, the leaves the walk did not reach are walked into a
        // discarding sink, which wipes them as a finished walk would.
        let wipes = Counted::default();
        let items = vec![wipes.clone(), wipes.clone(), wipes.clone()];
        items.visit(StopAfter::new(1)).expect_err("should stop");
        assert_eq!(wipes.0.get(), 3);

        // Nested in a protected vector, the inner vector is walked bare
        // once taken out, and fails after its first element.
        let wipes = Counted::default();
        let items = Protected::new(vec![vec![wipes.clone(), wipes.clone(), wipes.clone()]]);
        items.visit(StopAfter::new(2)).expect_err("should stop");
        assert_eq!(wipes.0.get(), 3);
    }

    #[test]
    fn discarding_walks_every_kind_of_node() {
        // Containers, scalars and passthrough all go to the discarding
        // sink without failing.
        let mut map = BTreeMap::new();
        map.insert("k", vec![String::from("v")]);
        assert!(map.visit(Discard).is_ok());
        assert!(Failing.visit(Discard).is_err());
        assert!(Discard.passthrough(1u32).is_ok());
        assert!(Discard.map(None).and_then(MapSink::end).is_ok());
    }

    // The borrows are the point: each one picks the reference impl.
    #[allow(clippy::needless_borrows_for_generic_args)]
    #[test]
    fn borrowed_containers_are_sources() {
        let ints = vec![1u32, 2];
        assert_eq!(
            record(&ints).expect("ok"),
            record(ints.clone()).expect("ok")
        );
        assert_eq!(record(&ints[..]).expect("ok"), record(ints).expect("ok"));
        assert_eq!(
            record(&vec![true]).expect("ok"),
            record(vec![true]).expect("ok")
        );
        assert_eq!(
            record(&Some(1.5f64)).expect("ok"),
            record(Some(1.5f64)).expect("ok")
        );
        assert_eq!(record(&None::<i8>).expect("ok"), [scalar(Owned::Null)]);
        // A borrowed `Vec<u8>` is still a byte leaf, not a sequence.
        assert_eq!(
            record(&vec![1u8, 2]).expect("ok"),
            [scalar(Owned::Bytes(vec![1, 2]))]
        );
        assert_eq!(
            record(&[1u8, 2]).expect("ok"),
            [scalar(Owned::Bytes(vec![1, 2]))]
        );
        let mut hash = HashMap::new();
        hash.insert(String::from("k"), vec![String::from("v")]);
        let borrowed = record(&hash).expect("ok");
        assert_eq!(borrowed, record(hash).expect("ok"));
        let mut tree = BTreeMap::new();
        tree.insert("a", 1i64);
        tree.insert("b", 2i64);
        let borrowed = record(&tree).expect("ok");
        assert_eq!(borrowed, record(tree).expect("ok"));
    }

    #[test]
    fn option_none_is_null() {
        assert_eq!(record(None::<u32>).expect("ok"), [scalar(Owned::Null)]);
        assert_eq!(
            record(Some(1u32)).expect("ok"),
            [scalar(Owned::Int(Int::U32(1)))]
        );
    }

    #[test]
    fn containers_push_each_child_into_its_own_sink() {
        let mut map = BTreeMap::new();
        map.insert("a", vec![1i32]);
        map.insert("b", vec![]);
        assert_eq!(
            record(map).expect("ok"),
            [
                Event::Map(Some(2)),
                Event::Entry("a".into()),
                Event::Seq(Some(1)),
                Event::Element,
                scalar(Owned::Int(Int::I32(1))),
                Event::EndSeq,
                Event::Entry("b".into()),
                Event::Seq(Some(0)),
                Event::EndSeq,
                Event::EndMap,
            ]
        );
        let mut hash = HashMap::new();
        hash.insert(String::from("k"), 2u64);
        assert_eq!(
            record(hash).expect("ok"),
            [
                Event::Map(Some(1)),
                Event::Entry("k".into()),
                scalar(Owned::Int(Int::U64(2))),
                Event::EndMap,
            ]
        );
    }

    #[test]
    fn raw_passes_the_logical_type_through() {
        assert_eq!(
            record(Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 16]))).expect("ok"),
            [Event::Scalar(
                Some(Logical::Uuid),
                Owned::Bytes(vec![0; 16])
            )]
        );
    }

    /// A source that fails part way through, as a host getter might.
    struct Failing;

    impl Encrypt for Failing {
        fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
            let mut seq = sink.seq(None)?;
            1u32.visit(seq.element()?)?;
            Err(S::Error::source(SourceError::msg("getter threw")))
        }
    }

    #[test]
    fn a_source_can_stop_the_walk_with_its_own_error() {
        let err = record(Failing).expect_err("should fail");
        assert_eq!(err.0, "getter threw");
    }

    #[cfg(feature = "chrono")]
    #[test]
    fn chrono_types_are_logical_types_over_an_int() {
        use crate::plaintext::kinds::TimeUnit;
        use ::chrono::{DateTime, NaiveDate};
        let date = NaiveDate::from_ymd_opt(2000, 3, 1).expect("ok");
        assert_eq!(
            record(date).expect("ok"),
            [Event::Scalar(
                Some(Logical::Date),
                Owned::Int(Int::I32(11_017))
            )]
        );
        let ts = DateTime::from_timestamp(1, 5).expect("ok");
        assert_eq!(
            record(ts).expect("ok"),
            [Event::Scalar(
                Some(Logical::Timestamp(TimeUnit::Nanos)),
                Owned::Int(Int::I128(1_000_000_005))
            )]
        );
        let leap = NaiveDate::from_ymd_opt(2016, 12, 31)
            .expect("ok")
            .and_hms_nano_opt(23, 59, 59, 1_500_000_000)
            .expect("ok")
            .and_utc();
        assert_eq!(
            record(leap).expect_err("should fail").0,
            "a leap second has no count of nanoseconds"
        );
    }

    // The borrows are the point: each one picks the reference impl.
    #[allow(clippy::needless_borrows_for_generic_args)]
    #[cfg(all(feature = "chrono", feature = "rust_decimal", feature = "uuid"))]
    #[test]
    fn borrowed_logical_sources_walk_as_the_owned_ones() {
        let date = ::chrono::NaiveDate::from_ymd_opt(2000, 3, 1).expect("ok");
        assert_eq!(record(&date).expect("ok"), record(date).expect("ok"));
        let ts = ::chrono::DateTime::from_timestamp(1, 5).expect("ok");
        assert_eq!(record(&ts).expect("ok"), record(ts).expect("ok"));
        let d: rust_decimal::Decimal = "-1.50".parse().expect("ok");
        assert_eq!(record(&d).expect("ok"), record(d).expect("ok"));
        let id = uuid::Uuid::from_bytes([3; 16]);
        assert_eq!(record(&id).expect("ok"), record(id).expect("ok"));
    }

    #[cfg(feature = "rust_decimal")]
    #[test]
    fn decimal_is_a_scale_and_a_mantissa() {
        let d: rust_decimal::Decimal = "1.50".parse().expect("ok");
        assert_eq!(
            record(d).expect("ok"),
            [Event::Scalar(
                Some(Logical::Decimal { scale: 2 }),
                Owned::Int(Int::I128(150))
            )]
        );
    }

    #[cfg(feature = "uuid")]
    #[test]
    fn uuid_is_sixteen_bytes() {
        let id = uuid::Uuid::from_bytes([3; 16]);
        assert_eq!(
            record(id).expect("ok"),
            [Event::Scalar(
                Some(Logical::Uuid),
                Owned::Bytes(vec![3; 16])
            )]
        );
    }
}