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
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
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
//! ASN.1 identifier octets, tag classes, and universal tag numbers.
use crate::combinators::{Bind, Empty, Sum};
use crate::core::exec::input::*;
use crate::core::exec::output::*;
use crate::core::exec::{parser::*, serializer::*, ParseError, ParseErrorKind};
use crate::primitives::base128::*;
use crate::{
    combinators::{
        implicit::*,
        mapped::spec::{FnSpecMapper, SpecMap},
        Mapped, Refined, U8,
    },
    core::{proof::*, spec::*},
};
#[cfg(feature = "alloc")]
use alloc::vec;
use vstd::prelude::*;
use OutputBuf;
use Sum::Inl as L;
use Sum::Inr as R;

#[cfg(verus_only)]
use vstd::std_specs::convert::FromSpecImpl;

verus! {

/// Bit-mask for the class bits (bits 7–6) of the first tag byte.
pub const TAG_CLASS_MASK: u8 = 0b1100_0000u8;

/// Bit-mask for the "constructed" bit (bit 5) of the first tag byte.
pub const TAG_CONSTRUCTED_MASK: u8 = 0b0010_0000u8;

/// Bit-mask for the tag-number bits (bits 4–0) of the first tag byte.
pub const TAG_NUMBER_MASK: u8 = 0b0001_1111u8;

/// Sentinel value in bits 4–0 signalling the long (high-tag) form.
pub const TAG_LONG_FORM_SENTINEL: u8 = 0b0001_1111u8;

/// One identifier octet plus the maximum ten base-128 octets needed by a `u64` tag number.
pub(crate) const TAG_FMT_MAX_BYTE_LEN: usize = 11;

#[derive(StructuralEq, Clone, Copy, PartialEq, Eq, Debug)]
#[verifier::ext_equal]
#[repr(u64)]
pub enum TagNumber {
    EOC = 0,
    Boolean = 1,
    Integer = 2,
    BitString = 3,
    OctetString = 4,
    Null = 5,
    ObjectIdentifier = 6,
    Real = 9,
    Enumerated = 10,
    Utf8String = 12,
    RelativeOid = 13,
    Sequence = 16,
    Set = 17,
    NumericString = 18,
    PrintableString = 19,
    TeletexString = 20,
    VideotexString = 21,
    Ia5String = 22,
    UtcTime = 23,
    GeneralizedTime = 24,
    VisibleString = 26,
    GeneralString = 27,
    UniversalString = 28,
    BmpString = 30,
    Other { tag_num: UInt },
}

#[derive(StructuralEq, Clone, Copy, PartialEq, Eq, Debug)]
#[verifier::ext_equal]
pub enum Class {
    Universal,
    Application,
    ContextSpecific,
    Private,
}

#[derive(StructuralEq, Clone, Copy, PartialEq, Eq, Debug)]
#[verifier::ext_equal]
pub struct Tag {
    pub class: Class,
    pub constructed: bool,
    pub number: TagNumber,
}

pub open spec fn tag_num_to_uint(num: TagNumber) -> UInt {
    match num {
        TagNumber::EOC => 0,
        TagNumber::Boolean => 1,
        TagNumber::Integer => 2,
        TagNumber::BitString => 3,
        TagNumber::OctetString => 4,
        TagNumber::Null => 5,
        TagNumber::ObjectIdentifier => 6,
        TagNumber::Real => 9,
        TagNumber::Enumerated => 10,
        TagNumber::Utf8String => 12,
        TagNumber::RelativeOid => 13,
        TagNumber::Sequence => 16,
        TagNumber::Set => 17,
        TagNumber::NumericString => 18,
        TagNumber::PrintableString => 19,
        TagNumber::TeletexString => 20,
        TagNumber::VideotexString => 21,
        TagNumber::Ia5String => 22,
        TagNumber::UtcTime => 23,
        TagNumber::GeneralizedTime => 24,
        TagNumber::VisibleString => 26,
        TagNumber::GeneralString => 27,
        TagNumber::UniversalString => 28,
        TagNumber::BmpString => 30,
        TagNumber::Other { tag_num } => tag_num,
    }
}

pub open spec fn uint_to_tag_num(num: UInt) -> TagNumber {
    match num {
        0 => TagNumber::EOC,
        1 => TagNumber::Boolean,
        2 => TagNumber::Integer,
        3 => TagNumber::BitString,
        4 => TagNumber::OctetString,
        5 => TagNumber::Null,
        6 => TagNumber::ObjectIdentifier,
        9 => TagNumber::Real,
        10 => TagNumber::Enumerated,
        12 => TagNumber::Utf8String,
        13 => TagNumber::RelativeOid,
        16 => TagNumber::Sequence,
        17 => TagNumber::Set,
        18 => TagNumber::NumericString,
        19 => TagNumber::PrintableString,
        20 => TagNumber::TeletexString,
        21 => TagNumber::VideotexString,
        22 => TagNumber::Ia5String,
        23 => TagNumber::UtcTime,
        24 => TagNumber::GeneralizedTime,
        26 => TagNumber::VisibleString,
        27 => TagNumber::GeneralString,
        28 => TagNumber::UniversalString,
        30 => TagNumber::BmpString,
        other => TagNumber::Other { tag_num: other },
    }
}

pub open spec fn tag_number_wf(num: TagNumber) -> bool {
    num matches TagNumber::Other { tag_num } ==> {
        &&& !matches!(tag_num, 0 | 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 12 | 13 | 16 | 17 | 18 | 19 | 20 | 21
            | 22 | 23 | 24 | 26 | 27 | 28 | 30)
        &&& nat_to_base128(tag_num as nat).len() <= BASE128_MAX_BYTES
    }
}

#[verifier::allow_in_spec]
pub const fn tag_num_from_uint(num: u64) -> TagNumber
    returns
        uint_to_tag_num(num as UInt),
{
    match num {
        0 => TagNumber::EOC,
        1 => TagNumber::Boolean,
        2 => TagNumber::Integer,
        3 => TagNumber::BitString,
        4 => TagNumber::OctetString,
        5 => TagNumber::Null,
        6 => TagNumber::ObjectIdentifier,
        9 => TagNumber::Real,
        10 => TagNumber::Enumerated,
        12 => TagNumber::Utf8String,
        13 => TagNumber::RelativeOid,
        16 => TagNumber::Sequence,
        17 => TagNumber::Set,
        18 => TagNumber::NumericString,
        19 => TagNumber::PrintableString,
        20 => TagNumber::TeletexString,
        21 => TagNumber::VideotexString,
        22 => TagNumber::Ia5String,
        23 => TagNumber::UtcTime,
        24 => TagNumber::GeneralizedTime,
        26 => TagNumber::VisibleString,
        27 => TagNumber::GeneralString,
        28 => TagNumber::UniversalString,
        30 => TagNumber::BmpString,
        other => TagNumber::Other { tag_num: other as UInt },
    }
}

/// Return the numeric identifier represented by an ASN.1 tag number.
///
/// This is the executable counterpart of the `tag_num_to_uint` specification.
#[verifier::allow_in_spec]
pub const fn tag_number_value(number: TagNumber) -> UInt
    returns
        tag_num_to_uint(number),
{
    match number {
        TagNumber::EOC => 0,
        TagNumber::Boolean => 1,
        TagNumber::Integer => 2,
        TagNumber::BitString => 3,
        TagNumber::OctetString => 4,
        TagNumber::Null => 5,
        TagNumber::ObjectIdentifier => 6,
        TagNumber::Real => 9,
        TagNumber::Enumerated => 10,
        TagNumber::Utf8String => 12,
        TagNumber::RelativeOid => 13,
        TagNumber::Sequence => 16,
        TagNumber::Set => 17,
        TagNumber::NumericString => 18,
        TagNumber::PrintableString => 19,
        TagNumber::TeletexString => 20,
        TagNumber::VideotexString => 21,
        TagNumber::Ia5String => 22,
        TagNumber::UtcTime => 23,
        TagNumber::GeneralizedTime => 24,
        TagNumber::VisibleString => 26,
        TagNumber::GeneralString => 27,
        TagNumber::UniversalString => 28,
        TagNumber::BmpString => 30,
        TagNumber::Other { tag_num } => tag_num,
    }
}

impl DeepView for TagNumber {
    type V = Self;

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

impl DeepView for Class {
    type V = Self;

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

impl DeepView for Tag {
    type V = Self;

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

/// Return the primitive form of a tag identity.
#[verifier::allow_in_spec]
pub fn primitive_tag(tag: Tag) -> Tag
    returns
        (Tag { class: tag.class, constructed: false, number: tag.number }),
{
    Tag { class: tag.class, constructed: false, number: tag.number }
}

/// Return the constructed form of a tag identity.
#[verifier::allow_in_spec]
pub fn constructed_tag(tag: Tag) -> Tag
    returns
        (Tag { class: tag.class, constructed: true, number: tag.number }),
{
    Tag { class: tag.class, constructed: true, number: tag.number }
}

pub open spec fn class_of_first_byte(b1: u8) -> Class {
    match b1 & TAG_CLASS_MASK {
        0b0000_0000u8 => Class::Universal,
        0b0100_0000u8 => Class::Application,
        0b1000_0000u8 => Class::ContextSpecific,
        _ => Class::Private,
    }
}

pub open spec fn class_bits(class: Class) -> u8 {
    match class {
        Class::Universal => 0b0000_0000u8,
        Class::Application => 0b0100_0000u8,
        Class::ContextSpecific => 0b1000_0000u8,
        Class::Private => 0b1100_0000u8,
    }
}

pub open spec fn constructed_of_first_byte(b1: u8) -> bool {
    b1 & TAG_CONSTRUCTED_MASK != 0
}

pub open spec fn constructed_bit(constructed: bool) -> u8 {
    if constructed {
        TAG_CONSTRUCTED_MASK
    } else {
        0u8
    }
}

pub open spec fn first_byte_from_parts(class: Class, constructed: bool, low_bits: u8) -> u8 {
    class_bits(class) | constructed_bit(constructed) | (low_bits & TAG_NUMBER_MASK)
}

type TagWireFmt = Bind<U8, spec_fn(u8) -> Sum<Empty, Refined<Base128Fmt<true>, PredFnSpec<UInt>>>>;

type TagInnerFmt = Mapped<TagWireFmt, FnSpecMapper<(u8, Sum<(), UInt>), Tag>>;

#[verusfmt::skip]
pub(crate) open(crate) spec fn tag_wire() -> TagWireFmt {
    Bind(U8, |b1: u8| {
        if b1 & TAG_NUMBER_MASK == TAG_LONG_FORM_SENTINEL {
            R(Refined(Base128Fmt::<true>, |n: UInt| n >= TAG_LONG_FORM_SENTINEL as UInt))
        } else {
            L(Empty)
        }
    })
}

pub(crate) open(crate) spec fn tag_fmt() -> TagInnerFmt {
    Mapped {
        inner: tag_wire(),
        mapper: (
            |r: (u8, Sum<(), UInt>)|
                {
                    let (b1, rest) = r;
                    let num = match rest {
                        L(()) => (b1 & TAG_NUMBER_MASK) as UInt,
                        R(n) => n,
                    };
                    Tag {
                        class: class_of_first_byte(b1),
                        constructed: constructed_of_first_byte(b1),
                        number: uint_to_tag_num(num),
                    }
                },
            |tag: Tag|
                {
                    let num = tag_num_to_uint(tag.number);
                    if num < TAG_LONG_FORM_SENTINEL as UInt {
                        (first_byte_from_parts(tag.class, tag.constructed, num as u8), L(()))
                    } else {
                        (
                            first_byte_from_parts(
                                tag.class,
                                tag.constructed,
                                TAG_LONG_FORM_SENTINEL,
                            ),
                            R(num),
                        )
                    }
                },
        ),
    }
}

// ── Bit-vector helpers ────────────────────────────────────────────────────────
proof fn lemma_class_bits_roundtrip(b1: u8)
    ensures
        class_bits(class_of_first_byte(b1)) == (b1 & TAG_CLASS_MASK),
{
    let cls = b1 & TAG_CLASS_MASK;
    assert({
        ||| cls == 0b0000_0000u8
        ||| cls == 0b0100_0000u8
        ||| cls == 0b1000_0000u8
        ||| cls == 0b1100_0000u8
    }) by (bit_vector)
        requires
            cls == (b1 & TAG_CLASS_MASK),
    ;
}

proof fn lemma_class_bits_only_class_mask(class: Class)
    ensures
        class_bits(class) & TAG_CONSTRUCTED_MASK == 0u8,
        class_bits(class) & TAG_NUMBER_MASK == 0u8,
        class_bits(class) & TAG_CLASS_MASK == class_bits(class),
{
    assert(forall|cls: u8|
        {
            ||| cls == 0b0000_0000u8
            ||| cls == 0b0100_0000u8
            ||| cls == 0b1000_0000u8
            ||| cls == 0b1100_0000u8
        } ==> (cls & TAG_CONSTRUCTED_MASK == 0u8 && cls & TAG_NUMBER_MASK == 0u8 && (cls
            & TAG_CLASS_MASK) == cls)) by (bit_vector);
}

proof fn lemma_first_byte_from_parts_roundtrip(class: Class, constructed: bool, low_bits: u8)
    ensures
        class_of_first_byte(first_byte_from_parts(class, constructed, low_bits)) == class,
        constructed_of_first_byte(first_byte_from_parts(class, constructed, low_bits))
            == constructed,
        first_byte_from_parts(class, constructed, low_bits) & TAG_NUMBER_MASK == low_bits
            & TAG_NUMBER_MASK,
{
    let fb = first_byte_from_parts(class, constructed, low_bits);
    let cb = class_bits(class);
    let cbit = constructed_bit(constructed);
    lemma_class_bits_only_class_mask(class);

    assert(fb & TAG_CLASS_MASK == cb && (fb & TAG_CONSTRUCTED_MASK != 0u8) == constructed && fb
        & TAG_NUMBER_MASK == low_bits & TAG_NUMBER_MASK) by (bit_vector)
        requires
            fb == cb | cbit | (low_bits & TAG_NUMBER_MASK),
            cb & TAG_CONSTRUCTED_MASK == 0u8,
            cb & TAG_NUMBER_MASK == 0u8,
            (cb & TAG_CLASS_MASK) == cb,
            cbit == TAG_CONSTRUCTED_MASK || cbit == 0u8,
            constructed ==> cbit == TAG_CONSTRUCTED_MASK,
            !constructed ==> cbit == 0u8,
    ;
}

proof fn lemma_first_byte_roundtrip(b1: u8)
    ensures
        first_byte_from_parts(
            class_of_first_byte(b1),
            constructed_of_first_byte(b1),
            b1 & TAG_NUMBER_MASK,
        ) == b1,
{
    lemma_class_bits_roundtrip(b1);
    let fb = first_byte_from_parts(
        class_of_first_byte(b1),
        constructed_of_first_byte(b1),
        b1 & TAG_NUMBER_MASK,
    );
    let cb = class_bits(class_of_first_byte(b1));
    assert(fb == b1) by (bit_vector)
        requires
            fb == cb | constructed_bit(constructed_of_first_byte(b1)) | ((b1 & TAG_NUMBER_MASK)
                & TAG_NUMBER_MASK),
            cb == (b1 & TAG_CLASS_MASK),
    ;
}

proof fn lemma_tag_fmt_sound_nonmal_inv()
    ensures
        tag_fmt().sound_inv(),
        tag_fmt().nonmal_inv(),
{
    let fmt = tag_fmt();
    assert forall|v| fmt.inner.consistent(v) implies (fmt.mapper.1)((fmt.mapper.0)(v)) == v by {
        let (b1, rest) = v;
        lemma_first_byte_roundtrip(b1);
        if b1 & TAG_NUMBER_MASK == TAG_LONG_FORM_SENTINEL {
        } else {
            let num = (b1 & TAG_NUMBER_MASK) as UInt;
            assert(num < TAG_LONG_FORM_SENTINEL as UInt) by (bit_vector)
                requires
                    (b1 & TAG_NUMBER_MASK) != TAG_LONG_FORM_SENTINEL,
                    num == (b1 & TAG_NUMBER_MASK) as UInt,
            ;
        }
    }
}

proof fn lemma_tag_fmt_unambiguous(tag: Tag)
    requires
        tag_fmt().consistent(tag),
        tag_number_wf(tag.number),
    ensures
        (tag_fmt().mapper.0)((tag_fmt().mapper.1)(tag)) == tag,
{
    let num = tag_num_to_uint(tag.number);
    if num < TAG_LONG_FORM_SENTINEL as UInt {
        let low = num as u8;
        lemma_first_byte_from_parts_roundtrip(tag.class, tag.constructed, low);
        assert(low & TAG_NUMBER_MASK == low) by (bit_vector)
            requires
                low == num as u8,
                num < TAG_LONG_FORM_SENTINEL as UInt,
        ;
    } else {
        lemma_first_byte_from_parts_roundtrip(tag.class, tag.constructed, TAG_LONG_FORM_SENTINEL);
    }
}

proof fn lemma_tag_wf_implies_tag_fmt_consistent(tag: Tag)
    requires
        tag_number_wf(tag.number),
    ensures
        tag_fmt().consistent(tag),
{
    let num = tag_num_to_uint(tag.number);
    assert(TAG_LONG_FORM_SENTINEL & TAG_NUMBER_MASK == TAG_LONG_FORM_SENTINEL) by (bit_vector);
    if num < TAG_LONG_FORM_SENTINEL as UInt {
        let low = num as u8;
        lemma_first_byte_from_parts_roundtrip(tag.class, tag.constructed, low);
        assert(low & TAG_NUMBER_MASK == low) by (bit_vector)
            requires
                low == num as u8,
                num < TAG_LONG_FORM_SENTINEL as UInt,
        ;
    } else {
        lemma_first_byte_from_parts_roundtrip(tag.class, tag.constructed, TAG_LONG_FORM_SENTINEL);
        lemma_base128_fmt_consistent::<true>(num);
    }
}

/// Exposes tag-format consistency to external combinator proofs without revealing
/// the implementation of [`TagFmt`](super::TagFmt).
pub broadcast proof fn lemma_tag_wf_implies_tag_consistent(tag: Tag)
    requires
        tag_number_wf(tag.number),
    ensures
        #[trigger] super::TagFmt.consistent(tag),
{
}

pub(crate) broadcast proof fn lemma_tag_fmt_byte_len_bound(tag: Tag)
    ensures
        #[trigger] super::TagFmt.byte_len(tag) <= TAG_FMT_MAX_BYTE_LEN,
{
    let num = tag_num_to_uint(tag.number);
    lemma_to_base128_len_bounds();
    lemma_base128_fmt_byte_len::<true>(num);
}

mod derived_specs {
    use super::*;
    use super::super::TagFmt;

    impl SpecParser for TagFmt {
        type PVal = Tag;

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

    impl Consistency for TagFmt {
        type Val = Tag;

        open(crate) spec fn consistent(&self, v: Self::Val) -> bool {
            tag_number_wf(v.number)
        }
    }

    impl SpecSerializerDps for TagFmt {
        type SValue = Tag;

        open(crate) spec fn spec_serialize_dps(&self, v: Self::SValue, obuf: Seq<u8>) -> Seq<u8> {
            tag_fmt().spec_serialize_dps(v, obuf)
        }
    }

    impl SpecSerializer for TagFmt {
        type SVal = Tag;

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

    impl SpecByteLen for TagFmt {
        type T = Tag;

        open(crate) spec fn byte_len(&self, v: Self::T) -> nat {
            tag_fmt().byte_len(v)
        }
    }

}

mod derived_proofs {
    use super::*;
    use super::super::TagFmt;

    impl SafeParser for TagFmt {
        proof fn lemma_parse_safe(&self, ibuf: Seq<u8>) {
            tag_fmt().lemma_parse_safe(ibuf);
        }
    }

    impl Productive for TagFmt {
        proof fn lemma_productive(&self, s: Seq<u8>) {
            tag_fmt().lemma_productive(s);
        }
    }

    impl SoundParser for TagFmt {
        proof fn lemma_parse_sound_consumption(&self, ibuf: Seq<u8>) {
            lemma_tag_fmt_sound_nonmal_inv();
            tag_fmt().lemma_parse_sound_consumption(ibuf);
        }

        proof fn lemma_parse_sound_value(&self, ibuf: Seq<u8>) {
            lemma_tag_fmt_sound_nonmal_inv();
            tag_fmt().lemma_parse_sound_value(ibuf);
        }
    }

    impl NonTailFmt for TagFmt {
        proof fn lemma_serialize_dps_prepend(&self, v: Self::SValue, obuf: Seq<u8>) {
            tag_fmt().lemma_serialize_dps_prepend(v, obuf);
        }

        proof fn lemma_serialize_dps_len(&self, v: Self::SValue, obuf: Seq<u8>) {
            tag_fmt().lemma_serialize_dps_len(v, obuf);
        }
    }

    impl GoodSerializer for TagFmt {
        proof fn lemma_serialize_len(&self, v: Self::SVal) {
            tag_fmt().lemma_serialize_len(v);
        }
    }

    impl SPRoundTripDps for TagFmt {
        proof fn theorem_serialize_dps_parse_roundtrip(&self, v: Self::T, obuf: Seq<u8>) {
            lemma_tag_wf_implies_tag_fmt_consistent(v);
            lemma_tag_fmt_unambiguous(v);
            tag_fmt().inner.theorem_serialize_dps_parse_roundtrip(tag_fmt().mapper.1(v), obuf);
        }
    }

    impl NoLookAhead for TagFmt {
        proof fn lemma_no_lookahead(&self, i1: Seq<u8>, i2: Seq<u8>) {
            tag_fmt().lemma_no_lookahead(i1, i2);
        }
    }

    impl NonMalleable for TagFmt {
        proof fn lemma_parse_non_malleable(&self, buf1: Seq<u8>, buf2: Seq<u8>) {
            lemma_tag_fmt_sound_nonmal_inv();
            tag_fmt().lemma_parse_non_malleable(buf1, buf2);
        }
    }

    impl EquivSerializersGeneral for TagFmt {
        proof fn lemma_serialize_equiv(&self, v: Self::SVal, obuf: Seq<u8>) {
            tag_fmt().lemma_serialize_equiv(v, obuf);
        }
    }

    impl EquivSerializers for TagFmt {
        proof fn lemma_serialize_equiv_on_empty(&self, v: Self::SVal) {
            tag_fmt().lemma_serialize_equiv_on_empty(v);
        }
    }

}

impl Parser<&[u8]> for super::TagFmt {
    type PT = Tag;

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

        let _ = ibuf.len();

        let (n1, b1): (usize, u8) = U8.parse(ibuf)?;
        let rest = ibuf.skip(n1);

        let (n2, num) = if b1 & TAG_NUMBER_MASK == TAG_LONG_FORM_SENTINEL {
            let (n2, num) = Base128Fmt::<true>.parse(&rest)?;
            if num < TAG_LONG_FORM_SENTINEL as UInt {
                return Err(ParseError::non_canonical());
            }
            (n2, num)
        } else {
            (0, (b1 & TAG_NUMBER_MASK) as UInt)
        };

        let class = match b1 & TAG_CLASS_MASK {
            0b0000_0000u8 => Class::Universal,
            0b0100_0000u8 => Class::Application,
            0b1000_0000u8 => Class::ContextSpecific,
            _ => Class::Private,
        };
        let constructed = b1 & TAG_CONSTRUCTED_MASK != 0;
        let number = match num {
            0 => TagNumber::EOC,
            1 => TagNumber::Boolean,
            2 => TagNumber::Integer,
            3 => TagNumber::BitString,
            4 => TagNumber::OctetString,
            5 => TagNumber::Null,
            6 => TagNumber::ObjectIdentifier,
            9 => TagNumber::Real,
            10 => TagNumber::Enumerated,
            12 => TagNumber::Utf8String,
            13 => TagNumber::RelativeOid,
            16 => TagNumber::Sequence,
            17 => TagNumber::Set,
            18 => TagNumber::NumericString,
            19 => TagNumber::PrintableString,
            20 => TagNumber::TeletexString,
            21 => TagNumber::VideotexString,
            22 => TagNumber::Ia5String,
            23 => TagNumber::UtcTime,
            24 => TagNumber::GeneralizedTime,
            26 => TagNumber::VisibleString,
            27 => TagNumber::GeneralString,
            28 => TagNumber::UniversalString,
            30 => TagNumber::BmpString,
            other => TagNumber::Other { tag_num: other },
        };

        Ok((n1 + n2, Tag { class, constructed, number }))
    }
}

impl<Output: OutputBuf> Serializer<Output, Tag> for super::TagFmt {
    fn serialize_into(&self, v: &Tag, obuf: &mut Output) {
        broadcast use crate::core::exec::output::outbuf_lemmas;

        let num = tag_number_value(v.number);

        let class_bits = match v.class {
            Class::Universal => 0b0000_0000u8,
            Class::Application => 0b0100_0000u8,
            Class::ContextSpecific => 0b1000_0000u8,
            Class::Private => 0b1100_0000u8,
        };
        let constructed_bit = if v.constructed {
            TAG_CONSTRUCTED_MASK
        } else {
            0u8
        };
        proof {
            lemma_tag_wf_implies_tag_fmt_consistent(*v);
        }
        if num < TAG_LONG_FORM_SENTINEL as UInt {
            let low = num as u8;
            let b1 = class_bits | constructed_bit | (low & TAG_NUMBER_MASK);
            U8.serialize_into(&b1, obuf);
        } else {
            let b1 = class_bits | constructed_bit | TAG_LONG_FORM_SENTINEL & TAG_NUMBER_MASK;
            U8.serialize_into(&b1, obuf);
            Base128Fmt::<true>.serialize_into(&num, obuf);
        }
    }
}

impl Prepare<Tag> for super::TagFmt {
    fn prepare(&self, v: &Tag) -> Result<usize, PreSerializeError> {
        if let TagNumber::Other { tag_num } = v.number {
            if matches!(tag_num, 0 | 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 12 | 13 | 16 | 17 | 18 | 19 | 20 | 21
                | 22 | 23 | 24 | 26 | 27 | 28 | 30) {
                return Err(PreSerializeError::custom("Invalid tag number"));
            }
        }
        let num = tag_number_value(v.number);

        proof {
            lemma_to_base128_len_bounds();
            lemma_base128_fmt_byte_len::<true>(num);
        }
        let nbytes = Base128Fmt::<true>.length(&num);
        if nbytes > BASE128_MAX_BYTES {
            return Err(PreSerializeError::length_too_large());
        }
        proof {
            assert(tag_number_wf(v.deep_view().number));
            lemma_tag_wf_implies_tag_fmt_consistent(v.deep_view());
        }

        if num < TAG_LONG_FORM_SENTINEL as UInt {
            Ok(1)
        } else {
            Ok(1 + nbytes)
        }
    }
}

impl ByteLen<Tag> for super::TagFmt {
    fn length(&self, v: &Tag) -> usize {
        let num = tag_number_value(v.number);

        proof {
            lemma_to_base128_len_bounds();
            lemma_base128_fmt_byte_len::<true>(num);
            lemma_first_byte_from_parts_roundtrip(v.class, v.constructed, TAG_LONG_FORM_SENTINEL);
            assert(TAG_LONG_FORM_SENTINEL & TAG_NUMBER_MASK == TAG_LONG_FORM_SENTINEL)
                by (bit_vector);
        }
        let nbytes = Base128Fmt::<true>.length(&num);

        if num < TAG_LONG_FORM_SENTINEL as UInt {
            1
        } else {
            1 + nbytes
        }
    }
}

impl super::TagFmt {
    pub const EOC: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::EOC,
    };

    pub const BOOLEAN: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::Boolean,
    };

    pub const INTEGER: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::Integer,
    };

    pub const NULL: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::Null,
    };

    pub const OBJECT_IDENTIFIER: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::ObjectIdentifier,
    };

    pub const REAL: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::Real,
    };

    pub const ENUMERATED: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::Enumerated,
    };

    pub const RELATIVE_OID: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::RelativeOid,
    };

    pub const BIT_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::BitString,
    };

    pub const OCTET_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::OctetString,
    };

    pub const UTF8_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::Utf8String,
    };

    pub const NUMERIC_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::NumericString,
    };

    pub const PRINTABLE_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::PrintableString,
    };

    pub const TELETEX_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::TeletexString,
    };

    pub const VIDEOTEX_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::VideotexString,
    };

    pub const IA5_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::Ia5String,
    };

    pub const UTC_TIME: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::UtcTime,
    };

    pub const GENERALIZED_TIME: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::GeneralizedTime,
    };

    pub const VISIBLE_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::VisibleString,
    };

    pub const GENERAL_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::GeneralString,
    };

    pub const UNIVERSAL_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::UniversalString,
    };

    pub const BMP_STRING: Tag = Tag {
        class: Class::Universal,
        constructed: false,
        number: TagNumber::BmpString,
    };

    pub const BIT_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::BitString,
    };

    pub const OCTET_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::OctetString,
    };

    pub const UTF8_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::Utf8String,
    };

    pub const NUMERIC_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::NumericString,
    };

    pub const PRINTABLE_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::PrintableString,
    };

    pub const TELETEX_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::TeletexString,
    };

    pub const VIDEOTEX_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::VideotexString,
    };

    pub const IA5_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::Ia5String,
    };

    pub const UTC_TIME_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::UtcTime,
    };

    pub const GENERALIZED_TIME_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::GeneralizedTime,
    };

    pub const VISIBLE_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::VisibleString,
    };

    pub const GENERAL_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::GeneralString,
    };

    pub const UNIVERSAL_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::UniversalString,
    };

    pub const BMP_STRING_CONSTRUCTED: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::BmpString,
    };

    pub const SEQUENCE: Tag = Tag {
        class: Class::Universal,
        constructed: true,
        number: TagNumber::Sequence,
    };

    pub const SET: Tag = Tag { class: Class::Universal, constructed: true, number: TagNumber::Set };
}

use crate::combinators::Const;

pub broadcast proof fn lemma_const_tag_fmt_exec_inv(fmt: Const<super::TagFmt, Tag>)
    ensures
        #![all_triggers]
        <_ as Parser<&[u8]>>::exec_inv(&fmt),
        <_ as Prepare<Tag>>::exec_inv(&fmt),
{
    crate::core::exec::bridge_lemmas::lemma_const_parser_exec_inv::<&[u8], _, _>(&fmt);
    crate::core::exec::bridge_lemmas::lemma_const_prepare_exec_inv::<_, _>(&fmt);
}

} // verus!
/*
*
some test functions
*/
verus! {

#[cfg(feature = "alloc")]
fn test_exec_const_fmt(buf: &&[u8]) -> PResult<u16> {
    use crate::combinators::U16Be;
    let const_u16_fmt = Const(U16Be, 0x1234u16);
    let (n, v) = const_u16_fmt.parse(buf)?;
    if let Ok(len) = const_u16_fmt.prepare(&v) {
        let mut obuf = vec![0; len];
        const_u16_fmt.serialize(&v, &mut obuf);
        proof {
            const_u16_fmt.theorem_parse_serialize_roundtrip(buf@);
            assert(obuf@ == buf@[0..n]);
        }
    }
    Err(ParseError::custom("Test function, not meant to succeed"))
}

#[cfg(feature = "alloc")]
fn test_exec_tag_fmt(buf: &&[u8]) -> PResult<Tag> {
    broadcast use lemma_const_tag_fmt_exec_inv;

    let asn_bool_tag_fmt = Const(super::TagFmt, super::TagFmt::BOOLEAN);
    let (n, tag) = asn_bool_tag_fmt.parse(buf)?;
    if let Ok(len) = asn_bool_tag_fmt.prepare(&tag) {
        let mut obuf = vec![0; len];
        asn_bool_tag_fmt.serialize(&tag, &mut obuf);

        proof {
            asn_bool_tag_fmt.theorem_parse_serialize_roundtrip(buf@);
            assert(obuf@ == buf@[0..n]);
        }
    }
    Err(ParseError::custom("Test function, not meant to succeed"))
}

} // verus!
/*
// somehow needed for regular `cargo check/build/test`
 *
 */
#[cfg(not(verus_keep_ghost))]
unsafe impl Structural for TagNumber {}
#[cfg(not(verus_keep_ghost))]
unsafe impl Structural for Class {}
#[cfg(not(verus_keep_ghost))]
unsafe impl Structural for Tag {}