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
#![allow(clippy::upper_case_acronyms)]

pub(crate) use self::consts::*;
use alloc::string::ToString;

/// The class of tag identifying its category.
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub enum Class {
    /// Types defined in X.680.
    Universal = 0,
    /// Application specific types.
    Application,
    /// Context specific types (e.g. fields in a struct)
    Context,
    /// Private types.
    Private,
}

impl Class {
    /// Instantiate a `Class` from a u8.
    ///
    /// # Panics
    /// If `value` is greater than 3.
    pub fn from_u8(value: u8) -> Self {
        match value {
            0 => Class::Universal,
            1 => Class::Application,
            2 => Class::Context,
            3 => Class::Private,
            num => panic!("'{}' is not a valid class.", num),
        }
    }

    /// Returns whether the given class is universal.
    pub fn is_universal(self) -> bool {
        self == Class::Universal
    }
}

impl core::fmt::Display for Class {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.write_str(match self {
            Self::Universal => "universal",
            Self::Application => "application",
            Self::Context => "context",
            Self::Private => "private",
        })
    }
}

/// An abstract representation of an ASN.1 tag that uniquely identifies a type
/// within a ASN.1 module for codecs.
#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
pub struct Tag {
    /// The class of the tag.
    pub class: Class,
    /// The sub-class of the tag.
    pub value: u32,
}

/// Implement display for Tag; represents `class` as string and `value` as number.
impl core::fmt::Display for Tag {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.write_str(match self.class {
            Class::Universal => "Universal",
            Class::Application => "Application",
            Class::Context => "Context",
            Class::Private => "Private",
        })?;
        f.write_str(" ")?;
        f.write_str(&self.value.to_string())
    }
}

macro_rules! consts {
    ($($name:ident = $value:expr),+) => {
        #[allow(missing_docs)]
        impl Tag {
            $(
                pub const $name: Tag = Tag::new(Class::Universal, $value);
            )+
        }

        #[allow(non_camel_case_types)]
        pub mod consts {
            use super::*;

            $(
                #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
                pub struct $name;

                impl crate::types::AsnType for $name {
                    const TAG: Tag = Tag::$name;
                }
            )+
        }

    }
}

consts! {
    EOC = 0,
    BOOL = 1,
    INTEGER = 2,
    BIT_STRING = 3,
    OCTET_STRING = 4,
    NULL = 5,
    OBJECT_IDENTIFIER = 6,
    OBJECT_DESCRIPTOR = 7,
    EXTERNAL = 8,
    REAL = 9,
    ENUMERATED = 10,
    EMBEDDED_PDV = 11,
    UTF8_STRING = 12,
    RELATIVE_OID = 13,
    SEQUENCE = 16,
    SET = 17,
    NUMERIC_STRING = 18,
    PRINTABLE_STRING = 19,
    TELETEX_STRING = 20,
    VIDEOTEX_STRING = 21,
    IA5_STRING = 22,
    UTC_TIME = 23,
    GENERALIZED_TIME = 24,
    GRAPHIC_STRING = 25,
    VISIBLE_STRING = 26,
    GENERAL_STRING = 27,
    UNIVERSAL_STRING = 28,
    CHARACTER_STRING = 29,
    BMP_STRING = 30
}

impl Tag {
    /// The `Tag` constant to use to represent `CHOICE` type's `AsnType::TAG`.
    pub const CHOICE: Self = Self::EOC;

    /// Create a new tag from `class` and `value`.
    pub const fn new(class: Class, value: u32) -> Self {
        Self { class, value }
    }

    /// Create a new `APPLICATION` tag from `value`.
    pub const fn new_application(value: u32) -> Self {
        Self::new(Class::Application, value)
    }

    /// Create a new `CONTEXT` tag from `value`.
    pub const fn new_context(value: u32) -> Self {
        Self::new(Class::Context, value)
    }

    /// Create a new `PRIVATE` tag from `value`.
    pub const fn new_private(value: u32) -> Self {
        Self::new(Class::Private, value)
    }

    /// Set the value of the tag.
    pub fn set_value(mut self, value: u32) -> Self {
        self.value = value;
        self
    }

    #[doc(hidden)]
    pub const fn const_eq(self, rhs: &Self) -> bool {
        self.class as u8 == rhs.class as u8 && self.value == rhs.value
    }

    #[doc(hidden)]
    pub const fn const_less_than(self, rhs: Self) -> bool {
        (self.class as u8) < (rhs.class as u8) && self.value < rhs.value
    }

    /// Returns whether `Tag` is defined as `Tag::EOC`, and thus is an invalid
    /// tag and must be CHOICE structure.
    pub const fn is_choice(&self) -> bool {
        self.const_eq(&Tag::CHOICE)
    }
}

/// The root or node in tree representing all of potential tags in a ASN.1 type.
/// For most types this is only ever one level deep, except for CHOICE enums
/// which will contain a set of nodes, that either point to a `Leaf` or another
/// level of `Choice`.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TagTree {
    /// The end of branch in the tree.
    Leaf(Tag),
    /// A branch in the tree.
    Choice(&'static [TagTree]),
}

impl TagTree {
    pub const fn empty() -> Self {
        Self::Choice(&[])
    }

    pub const fn smallest_tag(&self) -> Tag {
        match self {
            Self::Leaf(tag) => *tag,
            Self::Choice(tree) => {
                let mut i = 0;
                let mut tag: Tag = Tag::new_private(u32::MAX);

                while i < tree.len() {
                    let next_tag = tree[i].smallest_tag();
                    if next_tag.const_less_than(tag) {
                        tag = next_tag;
                    }

                    i += 1;
                }

                tag
            }
        }
    }

    /// Returns whether a given `TagTree` only contains unique entries.
    pub const fn is_unique(&self) -> bool {
        match self {
            Self::Choice(tree) => Self::is_unique_set(tree),
            Self::Leaf(_) => true,
        }
    }

    /// Checks whether a given set of nodes only contains unique entries.
    pub(crate) const fn is_unique_set(nodes: &'static [Self]) -> bool {
        let mut index = 0;

        while index < nodes.len() {
            match &nodes[index] {
                TagTree::Choice(inner_tags) => {
                    if !Self::is_unique_set(inner_tags) {
                        return false;
                    }

                    let mut inner_index = 0;
                    while inner_index < inner_tags.len() {
                        if Self::tree_contains(
                            &inner_tags[inner_index],
                            konst::slice::slice_from(nodes, index + 1),
                        ) {
                            return false;
                        }

                        inner_index += 1;
                    }
                }

                TagTree::Leaf(tag) => {
                    // We're at the last element so there's nothing more to
                    // compare to.
                    if index + 1 == nodes.len() {
                        return true;
                    }

                    if Self::tag_contains(tag, konst::slice::slice_from(nodes, index + 1)) {
                        return false;
                    }
                }
            }

            index += 1;
        }

        true
    }

    /// Whether any `Leaf` in `needle` matches any `Leaf`s in `nodes`.
    const fn tree_contains(needle: &TagTree, nodes: &'static [TagTree]) -> bool {
        match needle {
            TagTree::Choice(inner_tags) => {
                let mut inner_index = 0;
                while inner_index < inner_tags.len() {
                    if Self::tree_contains(&inner_tags[inner_index], nodes) {
                        return true;
                    }

                    inner_index += 1;
                }
                false
            }

            TagTree::Leaf(tag) => {
                if Self::tag_contains(tag, nodes) {
                    return true;
                }

                false
            }
        }
    }

    /// Whether `needle` matches any `Leaf`s in `nodes`.
    pub const fn tag_contains(needle: &Tag, nodes: &[TagTree]) -> bool {
        let mut index = 0;

        while index < nodes.len() {
            match &nodes[index] {
                TagTree::Choice(nodes) => {
                    if Self::tag_contains(needle, nodes) {
                        return true;
                    }
                }

                TagTree::Leaf(tag) => {
                    if tag.const_eq(needle) {
                        return true;
                    }
                }
            }

            index += 1;
        }

        false
    }
}

impl PartialOrd for TagTree {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for TagTree {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.smallest_tag().cmp(&other.smallest_tag())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const _EXPECTED: TagTree = TagTree::Choice(&[
        TagTree::Leaf(Tag::CHOICE),
        TagTree::Leaf(Tag::BIT_STRING),
        TagTree::Choice(&[
            TagTree::Leaf(Tag::new(Class::Application, 0)),
            TagTree::Leaf(Tag::new(Class::Application, 1)),
        ]),
        TagTree::Choice(&[
            TagTree::Leaf(Tag::new(Class::Context, 0)),
            TagTree::Leaf(Tag::new(Class::Context, 2)),
        ]),
        TagTree::Leaf(Tag::new(Class::Private, 0)),
        TagTree::Leaf(Tag::new(Class::Private, 1)),
    ]);

    const _INVALID_FLAT: TagTree = TagTree::Choice(&[
        TagTree::Leaf(Tag::BIT_STRING),
        TagTree::Leaf(Tag::new(Class::Application, 0)),
        TagTree::Leaf(Tag::new(Class::Application, 0)),
        TagTree::Leaf(Tag::new(Class::Context, 0)),
        TagTree::Leaf(Tag::new(Class::Context, 0)),
        TagTree::Leaf(Tag::new(Class::Private, 0)),
        TagTree::Leaf(Tag::new(Class::Private, 0)),
    ]);

    const _INVALID_NESTED: TagTree = TagTree::Choice(&[
        TagTree::Leaf(Tag::CHOICE),
        TagTree::Leaf(Tag::BIT_STRING),
        TagTree::Choice(&[
            TagTree::Leaf(Tag::new(Class::Application, 0)),
            TagTree::Leaf(Tag::new(Class::Application, 1)),
        ]),
        TagTree::Choice(&[
            TagTree::Choice(&[TagTree::Leaf(Tag::new(Class::Application, 0))]),
            TagTree::Leaf(Tag::new(Class::Application, 0)),
            TagTree::Leaf(Tag::new(Class::Context, 2)),
        ]),
        TagTree::Leaf(Tag::new(Class::Private, 1)),
        TagTree::Leaf(Tag::new(Class::Private, 1)),
    ]);

    #[test]
    fn is_unique() {
        const _: () = assert!(_EXPECTED.is_unique());
        const _: () = assert!(!_INVALID_FLAT.is_unique());
        const _: () = assert!(!_INVALID_NESTED.is_unique());
    }

    #[test]
    fn canonical_ordering() {
        let mut tags = [
            Tag::CHOICE,
            Tag::new(Class::Application, 0),
            Tag::BIT_STRING,
            Tag::new(Class::Application, 1),
            Tag::new(Class::Private, 1),
            Tag::new(Class::Private, 0),
            Tag::new(Class::Context, 2),
            Tag::new(Class::Context, 0),
        ];
        let expected = [
            Tag::CHOICE,
            Tag::BIT_STRING,
            Tag::new(Class::Application, 0),
            Tag::new(Class::Application, 1),
            Tag::new(Class::Context, 0),
            Tag::new(Class::Context, 2),
            Tag::new(Class::Private, 0),
            Tag::new(Class::Private, 1),
        ];

        tags.sort();

        assert_eq!(tags, expected);
    }
}