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
use super::{
    error::{Error, ExpectedTag},
    io::{Reader, Writer},
};

// byte0:
// bits 7-4 tag_num
// bit  3   class (0 = application tag_num, 1 = context specific tag_num)
// bits 2-0 length / value / type
//
// Can use additional bytes as specified in bits 2-0 above

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum ApplicationTagNumber {
    Null = 0,
    Boolean = 1,
    UnsignedInt = 2,
    SignedInt = 3,
    Real = 4,
    Double = 5,
    OctetString = 6,
    CharacterString = 7,
    BitString = 8,
    Enumerated = 9,
    Date = 10,
    Time = 11,
    ObjectId = 12,
    Reserve1 = 13,
    Reserve2 = 14,
    Reserve3 = 15,
}

impl From<u8> for ApplicationTagNumber {
    fn from(tag_number: u8) -> Self {
        match tag_number {
            0 => Self::Null,
            1 => Self::Boolean,
            2 => Self::UnsignedInt,
            3 => Self::SignedInt,
            4 => Self::Real,
            5 => Self::Double,
            6 => Self::OctetString,
            7 => Self::CharacterString,
            8 => Self::BitString,
            9 => Self::Enumerated,
            10 => Self::Date,
            11 => Self::Time,
            12 => Self::ObjectId,
            13 => Self::Reserve1,
            14 => Self::Reserve2,
            15 => Self::Reserve3,
            _ => unreachable!(), // tag_number is only 4 bits
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TagNumber {
    Application(ApplicationTagNumber),
    ContextSpecific(u8),
    ContextSpecificOpening(u8),
    ContextSpecificClosing(u8),
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Tag {
    pub number: TagNumber,
    pub value: u32,
}

impl Tag {
    pub fn new(number: TagNumber, value: u32) -> Self {
        Self { number, value }
    }

    pub fn encode(&self, writer: &mut Writer) {
        let mut buf: [u8; 10] = [0; 10];
        let mut len = 1;

        match &self.number {
            TagNumber::Application(num) => {
                buf[0] |= (num.clone() as u8) << 4;
            }
            TagNumber::ContextSpecificOpening(num) => {
                let num = *num;
                buf[0] |= 0b1000; // set class to context specific

                if num <= 14 {
                    buf[0] |= num << 4;
                } else {
                    buf[0] |= 0xF0;
                    buf[1] = num;
                    len += 1;
                }

                // set type field to opening tag
                buf[0] |= 6;
            }
            TagNumber::ContextSpecificClosing(num) => {
                let num = *num;
                buf[0] |= 0b1000; // set class to context specific

                if num <= 14 {
                    buf[0] |= num << 4;
                } else {
                    buf[0] |= 0xF0;
                    buf[1] = num;
                    len += 1;
                }

                // set type field to closing tag
                buf[0] |= 7;
            }
            TagNumber::ContextSpecific(num) => {
                let num = *num;
                buf[0] |= 0b1000; // set class to context specific

                if num <= 14 {
                    buf[0] |= num << 4;
                } else {
                    buf[0] |= 0xF0;
                    buf[1] = num;
                    len += 1;
                }
            }
        }

        if self.value <= 4 {
            buf[0] |= self.value as u8;
        } else {
            buf[0] |= 5;

            if self.value <= 253 {
                buf[len] = self.value as u8;
                len += 1;
            } else if self.value < u16::MAX as u32 {
                buf[len] = self.value as u8;
                len += 1;
                let tmp = u16::to_be_bytes(self.value as u16);
                buf[len..len + tmp.len()].copy_from_slice(&tmp);
                len += tmp.len();
            } else {
                buf[len] = self.value as u8;
                len += 1;
                let tmp = u32::to_be_bytes(self.value);
                buf[len..len + tmp.len()].copy_from_slice(&tmp);
                len += tmp.len();
            }
        }

        writer.extend_from_slice(&buf[..len]);
    }

    pub fn decode(reader: &mut Reader, buf: &[u8]) -> Result<Self, Error> {
        let (number, byte0) = decode_tag_number(reader, buf)?;

        let value = if is_extended_value(byte0) {
            let byte = reader.read_byte(buf)?;
            match byte {
                // tagged as u32
                255 => {
                    let bytes = reader.read_bytes(buf)?;
                    let value = u32::from_be_bytes(bytes);
                    Self { number, value }
                }
                // tagged as u16
                254 => {
                    let bytes = reader.read_bytes(buf)?;
                    let value = u16::from_be_bytes(bytes) as u32;
                    Self { number, value }
                }
                // no tag
                _ => Self {
                    number,
                    value: byte.into(),
                },
            }
        } else if is_opening_tag(byte0) | is_closing_tag(byte0) {
            Self { number, value: 0 }
        } else {
            let value = (byte0 & 0x07).into();
            Self { number, value }
        };

        Ok(value)
    }

    pub fn decode_expected(
        reader: &mut Reader,
        buf: &[u8],
        expected: TagNumber,
        context: &'static str,
    ) -> Result<Self, Error> {
        let tag = Self::decode(reader, buf)?;
        if tag.number == expected {
            Ok(tag)
        } else {
            Err(Error::ExpectedTag(ExpectedTag {
                context,
                expected,
                actual: tag.number,
            }))
        }
    }

    pub fn expect_value(&self, context: &'static str, value: u32) -> Result<(), Error> {
        if self.value != value {
            Err(Error::TagValueInvalid((context, self.clone(), value)))
        } else {
            Ok(())
        }
    }

    pub fn expect_number(&self, context: &'static str, tag_number: TagNumber) -> Result<(), Error> {
        if self.number == tag_number {
            Ok(())
        } else {
            Err(Error::ExpectedTag(ExpectedTag {
                actual: self.number.clone(),
                expected: tag_number,
                context,
            }))
        }
    }
}

// returns tag_number and byte0 because we need to reuse byte0 elsewhere
fn decode_tag_number(reader: &mut Reader, buf: &[u8]) -> Result<(TagNumber, u8), Error> {
    let byte0 = reader.read_byte(buf)?;

    let value = if is_context_specific(byte0) {
        // context specific tag num
        if is_extended_tag_number(byte0) {
            let num = reader.read_byte(buf)?;
            (TagNumber::ContextSpecific(num), byte0)
        } else {
            let num = byte0 >> 4;
            if is_opening_tag(byte0) {
                (TagNumber::ContextSpecificOpening(num), 0)
            } else if is_closing_tag(byte0) {
                (TagNumber::ContextSpecificClosing(num), 0)
            } else {
                (TagNumber::ContextSpecific(num), byte0)
            }
        }
    } else {
        // application tag num
        let num = (byte0 >> 4).into();
        (TagNumber::Application(num), byte0)
    };

    Ok(value)
}

fn is_extended_tag_number(byte0: u8) -> bool {
    byte0 & 0xF0 == 0xF0
}

fn is_extended_value(byte0: u8) -> bool {
    byte0 & 0x07 == 0x05
}

fn is_context_specific(byte0: u8) -> bool {
    byte0 & 0x08 == 0x08
}

fn is_opening_tag(byte0: u8) -> bool {
    byte0 & 0x07 == 0x06
}

fn is_closing_tag(byte0: u8) -> bool {
    byte0 & 0x07 == 0x07
}