vest_lib 0.2.2

Verified parser and serializer combinators in Verus
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
//! CBOR initial-byte and argument formats.
use crate::combinators::{
    mapped::spec::{LosslessMapper, LossyMapper, SpecMap, SpecMapper},
    Bind, Bits, Const, Empty, Mapped, Refined, Sum, U16Be, U32Be, U64Be, Void, U8,
};
use crate::core::exec::{
    input::{InputBuf, InputSlice},
    output::OutputBuf,
    parser::{PResult, Parser},
    serializer::{ByteLen, PreSerializeError, Prepare, Serializer},
    ParseError,
};
use crate::core::{proof::*, spec::*};
use crate::Never;
use vstd::assert_seqs_equal;
use vstd::prelude::*;

use super::CborFloat;
use Sum::Inl as L;
use Sum::Inr as R;

verus! {

pub const ADDITIONAL_INFO_MASK: u8 = 0x1fu8;

/// The two bit fields in a CBOR initial byte (RFC 8949 section 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Structural)]
pub struct CborInitial {
    /// Three-bit major-type code.
    pub major: u8,
    /// Five-bit additional-information value.
    pub additional: u8,
}

impl DeepView for CborInitial {
    type V = Self;

    open spec fn deep_view(&self) -> Self::V {
        *self
    }
}

#[verifier::allow_in_spec]
pub fn unpack_initial(raw: u8) -> (fields: (u8, u8))
    returns
        ((raw >> 5, raw & ADDITIONAL_INFO_MASK)),
{
    (raw >> 5, raw & ADDITIONAL_INFO_MASK)
}

#[verifier::allow_in_spec]
pub fn pack_initial(major: u8, additional: u8) -> (raw: u8)
    returns
        ((major << 5) | additional),
{
    (major << 5) | additional
}

#[verifier::allow_in_spec]
pub fn initial_fields_in_bounds(major: u8, additional: u8) -> (valid: bool)
    returns
        (major < 8u8 && additional < 32u8),
{
    major < 8u8 && additional < 32u8
}

pub broadcast proof fn lemma_initial_unpack_pack(raw: u8)
    by (bit_vector)
    ensures
        #[trigger] pack_initial(unpack_initial(raw).0, unpack_initial(raw).1) == raw,
{
}

pub broadcast proof fn lemma_initial_pack_unpack(major: u8, additional: u8)
    by (bit_vector)
    requires
        #[trigger] initial_fields_in_bounds(major, additional),
    ensures
        unpack_initial(pack_initial(major, additional)).0 == major,
        unpack_initial(pack_initial(major, additional)).1 == additional,
{
}

pub broadcast proof fn lemma_initial_unpack_in_bounds(raw: u8)
    by (bit_vector)
    ensures
        #[trigger] initial_fields_in_bounds(unpack_initial(raw).0, unpack_initial(raw).1),
{
}

type CborInitialInnerFmt = Bits<U8, (u8, u8), CborInitial>;

pub open spec fn cbor_initial_fmt() -> CborInitialInnerFmt {
    Bits {
        repr: U8,
        unpack: |raw: u8| unpack_initial(raw),
        pack: |fields: (u8, u8)| pack_initial(fields.0, fields.1),
        refinement: |_fields: (u8, u8)| true,
        ctor: |fields: (u8, u8)| CborInitial { major: fields.0, additional: fields.1 },
        dtor: |initial: CborInitial| (initial.major, initial.additional),
        consistent: |initial: CborInitial|
            { initial_fields_in_bounds(initial.major, initial.additional) },
    }
}

/// The fixed-width initial-byte bit-field format.
#[derive(Debug, Clone, Copy)]
pub struct CborInitialFmt;

impl<'i> Parser<&'i [u8]> for CborInitialFmt {
    type PT = CborInitial;

    fn parse(&self, input: &&'i [u8]) -> PResult<Self::PT> {
        let (n, raw) = U8.parse(input)?;
        let (major, additional) = unpack_initial(raw);
        Ok((n, CborInitial { major, additional }))
    }
}

impl<Output: OutputBuf> Serializer<Output, CborInitial> for CborInitialFmt {
    fn serialize_into(&self, value: &CborInitial, out: &mut Output) {
        broadcast use crate::core::exec::output::outbuf_lemmas;

        let ghost old_out = out@;
        let r = pack_initial(value.major, value.additional);
        U8.serialize_into(&r, out);
        assert(out@ == old_out + self.spec_serialize(value.deep_view()));
    }
}

impl Prepare<CborInitial> for CborInitialFmt {
    fn prepare(&self, value: &CborInitial) -> Result<usize, PreSerializeError> {
        if !initial_fields_in_bounds(value.major, value.additional) {
            Err(PreSerializeError::custom("CBOR initial-byte field is out of range"))
        } else {
            let r = pack_initial(value.major, value.additional);
            U8.prepare(&r)
        }
    }
}

impl ByteLen<CborInitial> for CborInitialFmt {
    fn length(&self, value: &CborInitial) -> usize {
        let r = pack_initial(value.major, value.additional);
        U8.length(&r)
    }
}

/// The eight CBOR major types from RFC 8949 section 3.1.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Structural)]
pub enum MajorType {
    Unsigned,
    Negative,
    Bytes,
    Text,
    Array,
    Map,
    Tag,
    Simple,
}

impl DeepView for MajorType {
    type V = Self;

    open spec fn deep_view(&self) -> Self::V {
        *self
    }
}

/// Semantic payload carried by a decoded CBOR head.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Structural)]
pub enum CborHeadValue {
    Argument(u64),
    Indefinite,
    Simple(u8),
    Float(CborFloat),
    Break,
}

impl DeepView for CborHeadValue {
    type V = Self;

    open spec fn deep_view(&self) -> Self::V {
        *self
    }
}

/// A normalized CBOR initial byte and its optional argument.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Structural)]
pub struct CborHead {
    pub major: MajorType,
    pub value: CborHeadValue,
}

impl DeepView for CborHead {
    type V = Self;

    open spec fn deep_view(&self) -> Self::V {
        *self
    }
}

#[verifier::allow_in_spec]
pub fn major_from_code(code: u8) -> MajorType
    returns
        (match code {
            0 => MajorType::Unsigned,
            1 => MajorType::Negative,
            2 => MajorType::Bytes,
            3 => MajorType::Text,
            4 => MajorType::Array,
            5 => MajorType::Map,
            6 => MajorType::Tag,
            _ => MajorType::Simple,
        }),
{
    match code {
        0 => MajorType::Unsigned,
        1 => MajorType::Negative,
        2 => MajorType::Bytes,
        3 => MajorType::Text,
        4 => MajorType::Array,
        5 => MajorType::Map,
        6 => MajorType::Tag,
        _ => MajorType::Simple,
    }
}

#[verifier::allow_in_spec]
pub fn major_code(major: MajorType) -> u8
    returns
        (match major {
            MajorType::Unsigned => 0u8,
            MajorType::Negative => 1u8,
            MajorType::Bytes => 2u8,
            MajorType::Text => 3u8,
            MajorType::Array => 4u8,
            MajorType::Map => 5u8,
            MajorType::Tag => 6u8,
            MajorType::Simple => 7u8,
        }),
{
    match major {
        MajorType::Unsigned => 0u8,
        MajorType::Negative => 1u8,
        MajorType::Bytes => 2u8,
        MajorType::Text => 3u8,
        MajorType::Array => 4u8,
        MajorType::Map => 5u8,
        MajorType::Tag => 6u8,
        MajorType::Simple => 7u8,
    }
}

#[verifier::allow_in_spec]
pub fn valid_simple(value: u8) -> bool
    returns
        (value <= 23u8 || value >= 32u8),
{
    value <= 23u8 || value >= 32u8
}

#[verifier::allow_in_spec]
pub fn valid_head<const DET: bool>(head: CborHead) -> bool
    returns
        (match head.value {
            CborHeadValue::Argument(_) => head.major != MajorType::Simple,
            CborHeadValue::Indefinite => !DET && {
                head.major == MajorType::Bytes || head.major == MajorType::Text || head.major
                    == MajorType::Array || head.major == MajorType::Map
            },
            CborHeadValue::Simple(value) => head.major == MajorType::Simple && valid_simple(value),
            CborHeadValue::Float(_) => head.major == MajorType::Simple,
            CborHeadValue::Break => head.major == MajorType::Simple,
        }),
{
    match head.value {
        CborHeadValue::Argument(_) => head.major != MajorType::Simple,
        CborHeadValue::Indefinite => !DET && {
            head.major == MajorType::Bytes || head.major == MajorType::Text || head.major
                == MajorType::Array || head.major == MajorType::Map
        },
        CborHeadValue::Simple(value) => head.major == MajorType::Simple && valid_simple(value),
        CborHeadValue::Float(_) => head.major == MajorType::Simple,
        CborHeadValue::Break => head.major == MajorType::Simple,
    }
}

#[verifier::allow_in_spec]
pub fn minimal_u8_argument(value: u8) -> bool
    returns
        (value >= 24u8),
{
    value >= 24u8
}

#[verifier::allow_in_spec]
pub fn minimal_u16_argument(value: u16) -> bool
    returns
        (value > u8::MAX as u16),
{
    value > u8::MAX as u16
}

#[verifier::allow_in_spec]
pub fn minimal_u32_argument(value: u32) -> bool
    returns
        (value > u16::MAX as u32),
{
    value > u16::MAX as u32
}

#[verifier::allow_in_spec]
pub fn minimal_u64_argument(value: u64) -> bool
    returns
        (value > u32::MAX as u64),
{
    value > u32::MAX as u64
}

type HeadWireValue = Sum<(), Sum<u8, Sum<u16, Sum<u32, Sum<u64, Sum<(), Never>>>>>>;

type HeadBranchesFmt = Sum<Empty, Sum<U8, Sum<U16Be, Sum<U32Be, Sum<U64Be, Sum<Empty, Void>>>>>>;

type HeadWireFmt<const DET: bool> = Bind<CborInitialFmt, spec_fn(CborInitial) -> HeadBranchesFmt>;

type RefinedHeadWireFmt<const DET: bool> = Refined<
    HeadWireFmt<DET>,
    PredFnSpec<(CborInitial, HeadWireValue)>,
>;

type HeadMappedFmt<const DET: bool> = Mapped<RefinedHeadWireFmt<DET>, HeadMapper<DET>>;

pub open spec fn head_wire<const DET: bool>() -> HeadWireFmt<DET> {
    Bind(
        CborInitialFmt,
        |initial: CborInitial|
            {
                let major = major_from_code(initial.major);
                match initial.additional {
                    ai if ai <= 23u8 => L(Empty),
                    24u8 => R(L(U8)),
                    25u8 => R(R(L(U16Be))),
                    26u8 => R(R(R(L(U32Be)))),
                    27u8 => R(R(R(R(L(U64Be))))),
                    31u8 if major == MajorType::Bytes || major == MajorType::Text || major
                        == MajorType::Array || major == MajorType::Map || major
                        == MajorType::Simple => R(R(R(R(R(L(Empty)))))),
                    _ => R(R(R(R(R(R(Void("Reserved or invalid CBOR additional information"))))))),
                }
            },
    )
}

pub open spec fn valid_head_wire<const DET: bool>(wire: (CborInitial, HeadWireValue)) -> bool {
    let major = major_from_code(wire.0.major);
    match wire.1 {
        L(()) => true,
        R(L(value)) => {
            if major == MajorType::Simple {
                value >= 32u8
            } else {
                DET ==> minimal_u8_argument(value)
            }
        },
        R(R(L(value))) => major == MajorType::Simple || (DET ==> minimal_u16_argument(value)),
        R(R(R(L(value)))) => major == MajorType::Simple || (DET ==> minimal_u32_argument(value)),
        R(R(R(R(L(value))))) => major == MajorType::Simple || (DET ==> minimal_u64_argument(value)),
        R(R(R(R(R(L(())))))) => major == MajorType::Simple || !DET,
        _ => false,
    }
}

pub open spec fn decode_head_wire(wire: (CborInitial, HeadWireValue)) -> CborHead {
    let (initial, rest) = wire;
    let major = major_from_code(initial.major);
    let ai = initial.additional;
    let value = match rest {
        L(()) => {
            if major == MajorType::Simple {
                CborHeadValue::Simple(ai)
            } else {
                CborHeadValue::Argument(ai as u64)
            }
        },
        R(L(value)) => {
            if major == MajorType::Simple {
                CborHeadValue::Simple(value)
            } else {
                CborHeadValue::Argument(value as u64)
            }
        },
        R(R(L(value))) => {
            if major == MajorType::Simple {
                CborHeadValue::Float(CborFloat::F16(value))
            } else {
                CborHeadValue::Argument(value as u64)
            }
        },
        R(R(R(L(value)))) => {
            if major == MajorType::Simple {
                CborHeadValue::Float(CborFloat::F32(value))
            } else {
                CborHeadValue::Argument(value as u64)
            }
        },
        R(R(R(R(L(value))))) => {
            if major == MajorType::Simple {
                CborHeadValue::Float(CborFloat::F64(value))
            } else {
                CborHeadValue::Argument(value)
            }
        },
        R(R(R(R(R(L(())))))) => {
            if major == MajorType::Simple {
                CborHeadValue::Break
            } else {
                CborHeadValue::Indefinite
            }
        },
        _ => arbitrary(),
    };
    CborHead { major, value }
}

pub open spec fn encode_head_wire(head: CborHead) -> (CborInitial, HeadWireValue) {
    let major = major_code(head.major);
    match head.value {
        CborHeadValue::Argument(value) => {
            if value <= 23u64 {
                (CborInitial { major, additional: value as u8 }, L(()))
            } else if value <= u8::MAX as u64 {
                (CborInitial { major, additional: 24u8 }, R(L(value as u8)))
            } else if value <= u16::MAX as u64 {
                (CborInitial { major, additional: 25u8 }, R(R(L(value as u16))))
            } else if value <= u32::MAX as u64 {
                (CborInitial { major, additional: 26u8 }, R(R(R(L(value as u32)))))
            } else {
                (CborInitial { major, additional: 27u8 }, R(R(R(R(L(value))))))
            }
        },
        CborHeadValue::Indefinite => (
            CborInitial { major, additional: 31u8 },
            R(R(R(R(R(L(())))))),
        ),
        CborHeadValue::Simple(value) => {
            if value <= 23u8 {
                (CborInitial { major, additional: value }, L(()))
            } else {
                (CborInitial { major, additional: 24u8 }, R(L(value)))
            }
        },
        CborHeadValue::Float(CborFloat::F16(value)) => {
            (CborInitial { major, additional: 25u8 }, R(R(L(value))))
        },
        CborHeadValue::Float(CborFloat::F32(value)) => {
            (CborInitial { major, additional: 26u8 }, R(R(R(L(value)))))
        },
        CborHeadValue::Float(CborFloat::F64(value)) => {
            (CborInitial { major, additional: 27u8 }, R(R(R(R(L(value))))))
        },
        CborHeadValue::Break => (CborInitial { major, additional: 31u8 }, R(R(R(R(R(L(()))))))),
    }
}

#[derive(Clone, Copy)]
pub struct HeadMapper<const DET: bool>;

impl<const DET: bool> SpecMapper for HeadMapper<DET> {
    type In = (CborInitial, HeadWireValue);

    type Out = CborHead;

    open spec fn spec_map(&self, wire: Self::In) -> Self::Out {
        decode_head_wire(wire)
    }

    open spec fn spec_map_rev(&self, head: Self::Out) -> Self::In {
        encode_head_wire(head)
    }

    open spec fn wf_in(&self, wire: Self::In) -> bool {
        &&& head_wire::<DET>().consistent(wire)
        &&& valid_head_wire::<DET>(wire)
    }

    open spec fn wf_out(&self, head: Self::Out) -> bool {
        valid_head::<DET>(head)
    }
}

impl<const DET: bool> LossyMapper for HeadMapper<DET> {
    proof fn lemma_sound_mapper(&self, head: Self::Out) {
        match head.value {
            CborHeadValue::Argument(value) => {
                if value <= 23u64 {
                    assert((value as u8) as u64 == value) by (bit_vector)
                        requires
                            value <= 23u64,
                    ;
                } else if value <= u8::MAX as u64 {
                    assert((value as u8) as u64 == value) by (bit_vector)
                        requires
                            value <= u8::MAX as u64,
                    ;
                } else if value <= u16::MAX as u64 {
                    assert((value as u16) as u64 == value) by (bit_vector)
                        requires
                            value <= u16::MAX as u64,
                    ;
                } else if value <= u32::MAX as u64 {
                    assert((value as u32) as u64 == value) by (bit_vector)
                        requires
                            value <= u32::MAX as u64,
                    ;
                }
            },
            _ => {},
        }
    }

    proof fn lemma_mapper_wf_out_in(&self, head: Self::Out) {
    }
}

impl LosslessMapper for HeadMapper<true> {
    proof fn lemma_lossless_mapper(&self, wire: Self::In) {
    }

    proof fn lemma_mapper_wf_in_out(&self, wire: Self::In) {
    }
}

pub open spec fn cbor_head_fmt<const DET: bool>() -> HeadMappedFmt<DET> {
    Mapped {
        inner: Refined(
            head_wire::<DET>(),
            |wire: (CborInitial, HeadWireValue)| valid_head_wire::<DET>(wire),
        ),
        mapper: HeadMapper::<DET>,
    }
}

/// One normalized CBOR head.
///
/// `DET = true` rejects nonminimal integer, length, and tag arguments and
/// rejects indefinite-length heads. Floating-point payload widths remain an
/// explicit part of [`CborFloat`] and are not shortened here.
#[derive(Debug, Clone, Copy)]
pub struct CborHeadFmt<const DET: bool>;

pub type BreakFmt = Const<U8, u8>;

/// The CBOR break stop code (`0xff`).
pub const BREAK: BreakFmt = Const(U8, 0xffu8);

impl<'i, const DET: bool> Parser<&'i [u8]> for CborHeadFmt<DET> {
    type PT = CborHead;

    fn parse(&self, input: &&'i [u8]) -> PResult<Self::PT> {
        broadcast use crate::core::spec::SafeParser::lemma_parse_safe;

        let (n1, initial) = CborInitialFmt.parse(input)?;
        let major = major_from_code(initial.major);
        let ai = initial.additional;
        let rest = input.skip(n1);

        match ai {
            0..=23 => {
                let value = if major == MajorType::Simple {
                    CborHeadValue::Simple(ai)
                } else {
                    CborHeadValue::Argument(ai as u64)
                };
                Ok((1, CborHead { major, value }))
            },
            24 => {
                let (_, value) = U8.parse(&rest)?;
                if major == MajorType::Simple {
                    if value < 32 {
                        Err(ParseError::invalid_tag())
                    } else {
                        Ok((2, CborHead { major, value: CborHeadValue::Simple(value) }))
                    }
                } else if DET && !minimal_u8_argument(value) {
                    Err(ParseError::non_canonical())
                } else {
                    Ok((2, CborHead { major, value: CborHeadValue::Argument(value as u64) }))
                }
            },
            25 => {
                let (_, value) = U16Be.parse(&rest)?;
                if major == MajorType::Simple {
                    Ok((3, CborHead { major, value: CborHeadValue::Float(CborFloat::F16(value)) }))
                } else if DET && !minimal_u16_argument(value) {
                    Err(ParseError::non_canonical())
                } else {
                    Ok((3, CborHead { major, value: CborHeadValue::Argument(value as u64) }))
                }
            },
            26 => {
                let (_, value) = U32Be.parse(&rest)?;
                if major == MajorType::Simple {
                    Ok((5, CborHead { major, value: CborHeadValue::Float(CborFloat::F32(value)) }))
                } else if DET && !minimal_u32_argument(value) {
                    Err(ParseError::non_canonical())
                } else {
                    Ok((5, CborHead { major, value: CborHeadValue::Argument(value as u64) }))
                }
            },
            27 => {
                let (_, value) = U64Be.parse(&rest)?;
                if major == MajorType::Simple {
                    Ok((9, CborHead { major, value: CborHeadValue::Float(CborFloat::F64(value)) }))
                } else if DET && !minimal_u64_argument(value) {
                    Err(ParseError::non_canonical())
                } else {
                    Ok((9, CborHead { major, value: CborHeadValue::Argument(value) }))
                }
            },
            31 => {
                if !DET && (major == MajorType::Bytes || major == MajorType::Text || major
                    == MajorType::Array || major == MajorType::Map) {
                    Ok((1, CborHead { major, value: CborHeadValue::Indefinite }))
                } else if major == MajorType::Simple {
                    Ok((1, CborHead { major, value: CborHeadValue::Break }))
                } else {
                    Err(ParseError::invalid_tag())
                }
            },
            _ => Err(ParseError::invalid_tag()),
        }
    }
}

impl<Output: OutputBuf, const DET: bool> Serializer<Output, CborHead> for CborHeadFmt<DET> {
    fn serialize_into(&self, head: &CborHead, out: &mut Output) {
        broadcast use crate::core::exec::output::outbuf_lemmas;

        let ghost old_out = out@;
        let major = major_code(head.major);
        match head.value {
            CborHeadValue::Argument(value) => {
                if value <= 23 {
                    CborInitialFmt.serialize_into(
                        &CborInitial { major, additional: value as u8 },
                        out,
                    );
                } else if value <= u8::MAX as u64 {
                    CborInitialFmt.serialize_into(&CborInitial { major, additional: 24 }, out);
                    U8.serialize_into(&(value as u8), out);
                } else if value <= u16::MAX as u64 {
                    CborInitialFmt.serialize_into(&CborInitial { major, additional: 25 }, out);
                    U16Be.serialize_into(&(value as u16), out);
                } else if value <= u32::MAX as u64 {
                    CborInitialFmt.serialize_into(&CborInitial { major, additional: 26 }, out);
                    U32Be.serialize_into(&(value as u32), out);
                } else {
                    CborInitialFmt.serialize_into(&CborInitial { major, additional: 27 }, out);
                    U64Be.serialize_into(&value, out);
                }
            },
            CborHeadValue::Indefinite => {
                CborInitialFmt.serialize_into(&CborInitial { major, additional: 31 }, out);
            },
            CborHeadValue::Simple(value) => {
                if value <= 23 {
                    CborInitialFmt.serialize_into(&CborInitial { major, additional: value }, out);
                } else {
                    CborInitialFmt.serialize_into(&CborInitial { major, additional: 24 }, out);
                    U8.serialize_into(&value, out);
                }
            },
            CborHeadValue::Float(CborFloat::F16(value)) => {
                CborInitialFmt.serialize_into(&CborInitial { major, additional: 25 }, out);
                U16Be.serialize_into(&value, out);
            },
            CborHeadValue::Float(CborFloat::F32(value)) => {
                CborInitialFmt.serialize_into(&CborInitial { major, additional: 26 }, out);
                U32Be.serialize_into(&value, out);
            },
            CborHeadValue::Float(CborFloat::F64(value)) => {
                CborInitialFmt.serialize_into(&CborInitial { major, additional: 27 }, out);
                U64Be.serialize_into(&value, out);
            },
            CborHeadValue::Break => {
                CborInitialFmt.serialize_into(
                    &CborInitial { major: major_code(MajorType::Simple), additional: 31 },
                    out,
                );
            },
        }

        assert(out@ =~= old_out + self.spec_serialize(head.deep_view()));
    }
}

pub fn head_len<const DET: bool>(head: &CborHead) -> (len: usize)
    ensures
        len == CborHeadFmt::<DET>.byte_len(head.deep_view()),
{
    let len = match head.value {
        CborHeadValue::Argument(value) => {
            if value <= 23 {
                1
            } else if value <= u8::MAX as u64 {
                2
            } else if value <= u16::MAX as u64 {
                3
            } else if value <= u32::MAX as u64 {
                5
            } else {
                9
            }
        },
        CborHeadValue::Indefinite => 1,
        CborHeadValue::Simple(value) => if value <= 23 {
            1
        } else {
            2
        },
        CborHeadValue::Float(CborFloat::F16(_)) => 3,
        CborHeadValue::Float(CborFloat::F32(_)) => 5,
        CborHeadValue::Float(CborFloat::F64(_)) => 9,
        CborHeadValue::Break => 1,
    };
    len
}

impl<const DET: bool> Prepare<CborHead> for CborHeadFmt<DET> {
    fn prepare(&self, head: &CborHead) -> Result<usize, PreSerializeError> {
        if !valid_head::<DET>(*head) {
            Err(PreSerializeError::custom("Invalid CBOR head"))
        } else {
            let len = head_len::<DET>(head);
            Ok(len)
        }
    }
}

impl<const DET: bool> ByteLen<CborHead> for CborHeadFmt<DET> {
    fn length(&self, head: &CborHead) -> usize {
        head_len::<DET>(head)
    }
}

mod derived_specs {
    use super::*;

    impl SpecParser for CborInitialFmt {
        type PVal = CborInitial;

        open spec fn spec_parse(&self, input: Seq<u8>) -> Option<(int, Self::PVal)> {
            cbor_initial_fmt().spec_parse(input)
        }
    }

    impl Consistency for CborInitialFmt {
        type Val = CborInitial;

        open spec fn consistent(&self, value: Self::Val) -> bool {
            cbor_initial_fmt().consistent(value)
        }
    }

    impl SpecSerializerDps for CborInitialFmt {
        type SValue = CborInitial;

        open spec fn spec_serialize_dps(&self, value: Self::SValue, out: Seq<u8>) -> Seq<u8> {
            cbor_initial_fmt().spec_serialize_dps(value, out)
        }
    }

    impl SpecSerializer for CborInitialFmt {
        type SVal = CborInitial;

        open spec fn spec_serialize(&self, value: Self::SVal) -> Seq<u8> {
            cbor_initial_fmt().spec_serialize(value)
        }
    }

    impl SpecByteLen for CborInitialFmt {
        type T = CborInitial;

        open spec fn byte_len(&self, value: Self::T) -> nat {
            cbor_initial_fmt().byte_len(value)
        }
    }

    impl<const DET: bool> SpecParser for CborHeadFmt<DET> {
        type PVal = CborHead;

        open spec fn spec_parse(&self, input: Seq<u8>) -> Option<(int, Self::PVal)> {
            cbor_head_fmt::<DET>().spec_parse(input)
        }
    }

    impl<const DET: bool> Consistency for CborHeadFmt<DET> {
        type Val = CborHead;

        open spec fn consistent(&self, value: Self::Val) -> bool {
            cbor_head_fmt::<DET>().consistent(value)
        }
    }

    impl<const DET: bool> SpecSerializerDps for CborHeadFmt<DET> {
        type SValue = CborHead;

        open spec fn spec_serialize_dps(&self, value: Self::SValue, out: Seq<u8>) -> Seq<u8> {
            cbor_head_fmt::<DET>().spec_serialize_dps(value, out)
        }
    }

    impl<const DET: bool> SpecSerializer for CborHeadFmt<DET> {
        type SVal = CborHead;

        open spec fn spec_serialize(&self, value: Self::SVal) -> Seq<u8> {
            cbor_head_fmt::<DET>().spec_serialize(value)
        }
    }

    impl<const DET: bool> SpecByteLen for CborHeadFmt<DET> {
        type T = CborHead;

        open spec fn byte_len(&self, value: Self::T) -> nat {
            cbor_head_fmt::<DET>().byte_len(value)
        }
    }

}

mod derived_proofs {
    use super::*;

    impl SafeParser for CborInitialFmt {
        proof fn lemma_parse_safe(&self, input: Seq<u8>) {
            cbor_initial_fmt().lemma_parse_safe(input);
        }
    }

    impl Productive for CborInitialFmt {
        proof fn lemma_productive(&self, input: Seq<u8>) {
            cbor_initial_fmt().lemma_productive(input);
        }
    }

    impl SoundParser for CborInitialFmt {
        proof fn lemma_parse_sound_consumption(&self, input: Seq<u8>) {
            broadcast use lemma_initial_unpack_pack, lemma_initial_unpack_in_bounds;

            let fmt = cbor_initial_fmt();
            assert(fmt.sound_inv());
            fmt.lemma_parse_sound_consumption(input);
        }

        proof fn lemma_parse_sound_value(&self, input: Seq<u8>) {
            broadcast use lemma_initial_unpack_pack, lemma_initial_unpack_in_bounds;

            let fmt = cbor_initial_fmt();
            assert(fmt.sound_inv());
            fmt.lemma_parse_sound_value(input);
        }
    }

    impl NonTailFmt for CborInitialFmt {
        proof fn lemma_serialize_dps_prepend(&self, value: Self::SValue, out: Seq<u8>) {
            cbor_initial_fmt().lemma_serialize_dps_prepend(value, out);
        }

        proof fn lemma_serialize_dps_len(&self, value: Self::SValue, out: Seq<u8>) {
            cbor_initial_fmt().lemma_serialize_dps_len(value, out);
        }
    }

    impl GoodSerializer for CborInitialFmt {
        proof fn lemma_serialize_len(&self, value: Self::SVal) {
            cbor_initial_fmt().lemma_serialize_len(value);
        }
    }

    impl SPRoundTripDps for CborInitialFmt {
        proof fn theorem_serialize_dps_parse_roundtrip(&self, value: Self::T, out: Seq<u8>) {
            broadcast use lemma_initial_pack_unpack;

            let fmt = cbor_initial_fmt();
            assert(fmt.unambiguous());
            fmt.theorem_serialize_dps_parse_roundtrip(value, out);
        }
    }

    impl NonMalleable for CborInitialFmt {
        proof fn lemma_parse_non_malleable(&self, left: Seq<u8>, right: Seq<u8>) {
            broadcast use lemma_initial_unpack_pack, lemma_initial_unpack_in_bounds;

            cbor_initial_fmt().lemma_parse_non_malleable(left, right);
        }
    }

    impl NoLookAhead for CborInitialFmt {
        proof fn lemma_no_lookahead(&self, left: Seq<u8>, right: Seq<u8>) {
            cbor_initial_fmt().lemma_no_lookahead(left, right);
        }
    }

    impl EquivSerializersGeneral for CborInitialFmt {
        proof fn lemma_serialize_equiv(&self, value: Self::SVal, out: Seq<u8>) {
            cbor_initial_fmt().lemma_serialize_equiv(value, out);
        }
    }

    impl EquivSerializers for CborInitialFmt {
        proof fn lemma_serialize_equiv_on_empty(&self, value: Self::SVal) {
            cbor_initial_fmt().lemma_serialize_equiv_on_empty(value);
        }
    }

    impl<const DET: bool> SafeParser for CborHeadFmt<DET> {
        proof fn lemma_parse_safe(&self, input: Seq<u8>) {
            cbor_head_fmt::<DET>().lemma_parse_safe(input);
        }
    }

    impl<const DET: bool> Productive for CborHeadFmt<DET> {
        proof fn lemma_productive(&self, input: Seq<u8>) {
            cbor_head_fmt::<DET>().lemma_productive(input);
        }
    }

    impl SoundParser for CborHeadFmt<true> {
        proof fn lemma_parse_sound_consumption(&self, input: Seq<u8>) {
            cbor_head_fmt::<true>().lemma_parse_sound_consumption(input);
        }

        proof fn lemma_parse_sound_value(&self, input: Seq<u8>) {
            cbor_head_fmt::<true>().lemma_parse_sound_value(input);
        }
    }

    impl<const DET: bool> GoodSerializer for CborHeadFmt<DET> {
        proof fn lemma_serialize_len(&self, value: Self::SVal) {
            cbor_head_fmt::<DET>().lemma_serialize_len(value);
        }
    }

    impl<const DET: bool> NonTailFmt for CborHeadFmt<DET> {
        proof fn lemma_serialize_dps_prepend(&self, value: Self::SValue, out: Seq<u8>) {
            cbor_head_fmt::<DET>().lemma_serialize_dps_prepend(value, out);
        }

        proof fn lemma_serialize_dps_len(&self, value: Self::SValue, out: Seq<u8>) {
            cbor_head_fmt::<DET>().lemma_serialize_dps_len(value, out);
        }
    }

    impl<const DET: bool> SPRoundTripDps for CborHeadFmt<DET> {
        proof fn theorem_serialize_dps_parse_roundtrip(&self, value: Self::T, out: Seq<u8>) {
            cbor_head_fmt::<DET>().theorem_serialize_dps_parse_roundtrip(value, out);
        }
    }

    impl NonMalleable for CborHeadFmt<true> {
        proof fn lemma_parse_non_malleable(&self, left: Seq<u8>, right: Seq<u8>) {
            cbor_head_fmt::<true>().lemma_parse_non_malleable(left, right);
        }
    }

    impl<const DET: bool> NoLookAhead for CborHeadFmt<DET> {
        proof fn lemma_no_lookahead(&self, i1: Seq<u8>, i2: Seq<u8>) {
            cbor_head_fmt::<DET>().lemma_no_lookahead(i1, i2);
        }
    }

    impl<const DET: bool> EquivSerializersGeneral for CborHeadFmt<DET> {
        proof fn lemma_serialize_equiv(&self, value: Self::SVal, out: Seq<u8>) {
            cbor_head_fmt::<DET>().lemma_serialize_equiv(value, out);
        }
    }

    impl<const DET: bool> EquivSerializers for CborHeadFmt<DET> {
        proof fn lemma_serialize_equiv_on_empty(&self, value: Self::SVal) {
            cbor_head_fmt::<DET>().lemma_serialize_equiv_on_empty(value);
        }
    }

}

} // verus!