1use crate::error::{Error, ErrorCode, Result, bail};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum ElementType {
11 SignedInt(Width),
13 UnsignedInt(Width),
15 Bool(bool),
17 Float,
19 Double,
21 Utf8(Width),
23 Octets(Width),
25 Null,
27 Structure,
29 Array,
31 List,
33 EndOfContainer,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub enum Width {
43 One = 0,
45 Two = 1,
47 Four = 2,
49 Eight = 3,
51}
52
53impl Width {
54 #[must_use]
56 pub const fn octets(self) -> usize {
57 match self {
58 Self::One => 1,
59 Self::Two => 2,
60 Self::Four => 4,
61 Self::Eight => 8,
62 }
63 }
64
65 const fn from_bits(bits: u8) -> Self {
66 match bits & 0b11 {
67 0 => Self::One,
68 1 => Self::Two,
69 2 => Self::Four,
70 _ => Self::Eight,
71 }
72 }
73
74 #[must_use]
76 pub const fn for_unsigned(value: u64) -> Self {
77 if value <= u8::MAX as u64 {
78 Self::One
79 } else if value <= u16::MAX as u64 {
80 Self::Two
81 } else if value <= u32::MAX as u64 {
82 Self::Four
83 } else {
84 Self::Eight
85 }
86 }
87
88 #[must_use]
90 pub const fn for_signed(value: i64) -> Self {
91 if value >= i8::MIN as i64 && value <= i8::MAX as i64 {
92 Self::One
93 } else if value >= i16::MIN as i64 && value <= i16::MAX as i64 {
94 Self::Two
95 } else if value >= i32::MIN as i64 && value <= i32::MAX as i64 {
96 Self::Four
97 } else {
98 Self::Eight
99 }
100 }
101}
102
103impl ElementType {
104 pub(crate) const fn from_bits(bits: u8) -> Result<Self> {
110 let t = bits & 0x1F;
111 Ok(match t {
112 0x00..=0x03 => Self::SignedInt(Width::from_bits(t)),
113 0x04..=0x07 => Self::UnsignedInt(Width::from_bits(t)),
114 0x08 => Self::Bool(false),
115 0x09 => Self::Bool(true),
116 0x0A => Self::Float,
117 0x0B => Self::Double,
118 0x0C..=0x0F => Self::Utf8(Width::from_bits(t)),
119 0x10..=0x13 => Self::Octets(Width::from_bits(t)),
120 0x14 => Self::Null,
121 0x15 => Self::Structure,
122 0x16 => Self::Array,
123 0x17 => Self::List,
124 0x18 => Self::EndOfContainer,
125 _ => return Err(Error::new(ErrorCode::TlvInvalidControl)),
127 })
128 }
129
130 #[must_use]
132 pub const fn bits(self) -> u8 {
133 match self {
134 Self::SignedInt(w) => w as u8,
136 Self::UnsignedInt(w) => 0x04 | w as u8,
137 Self::Bool(false) => 0x08,
138 Self::Bool(true) => 0x09,
139 Self::Float => 0x0A,
140 Self::Double => 0x0B,
141 Self::Utf8(w) => 0x0C | w as u8,
142 Self::Octets(w) => 0x10 | w as u8,
143 Self::Null => 0x14,
144 Self::Structure => 0x15,
145 Self::Array => 0x16,
146 Self::List => 0x17,
147 Self::EndOfContainer => 0x18,
148 }
149 }
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
154pub enum ContainerKind {
155 Structure,
157 Array,
159 List,
161}
162
163impl ContainerKind {
164 #[must_use]
166 pub const fn element_type(self) -> ElementType {
167 match self {
168 Self::Structure => ElementType::Structure,
169 Self::Array => ElementType::Array,
170 Self::List => ElementType::List,
171 }
172 }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177#[repr(u8)]
178enum TagControl {
179 Anonymous = 0b000,
180 ContextSpecific = 0b001,
181 CommonProfile2 = 0b010,
182 CommonProfile4 = 0b011,
183 ImplicitProfile2 = 0b100,
184 ImplicitProfile4 = 0b101,
185 FullyQualified6 = 0b110,
186 FullyQualified8 = 0b111,
187}
188
189impl TagControl {
190 const fn from_bits(bits: u8) -> Self {
191 match bits >> 5 {
192 0b000 => Self::Anonymous,
193 0b001 => Self::ContextSpecific,
194 0b010 => Self::CommonProfile2,
195 0b011 => Self::CommonProfile4,
196 0b100 => Self::ImplicitProfile2,
197 0b101 => Self::ImplicitProfile4,
198 0b110 => Self::FullyQualified6,
199 _ => Self::FullyQualified8,
201 }
202 }
203
204 const fn octets(self) -> usize {
206 match self {
207 Self::Anonymous => 0,
208 Self::ContextSpecific => 1,
209 Self::CommonProfile2 | Self::ImplicitProfile2 => 2,
210 Self::CommonProfile4 | Self::ImplicitProfile4 => 4,
211 Self::FullyQualified6 => 6,
212 Self::FullyQualified8 => 8,
213 }
214 }
215}
216
217pub const COMMON_PROFILE: u16 = 0x0000;
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
227pub enum Tag {
228 Anonymous,
231 Context(u8),
234 Common(u32),
236 Implicit(u32),
239 FullyQualified {
241 vendor: u16,
243 profile: u16,
245 number: u32,
247 },
248}
249
250impl Tag {
251 #[must_use]
253 pub const fn is_anonymous(self) -> bool {
254 matches!(self, Self::Anonymous)
255 }
256
257 #[must_use]
259 pub const fn context(self) -> Option<u8> {
260 match self {
261 Self::Context(n) => Some(n),
262 _ => None,
263 }
264 }
265
266 const fn control(self) -> TagControl {
268 match self {
269 Self::Anonymous => TagControl::Anonymous,
270 Self::Context(_) => TagControl::ContextSpecific,
271 Self::Common(n) => {
272 if n < 0x1_0000 {
273 TagControl::CommonProfile2
274 } else {
275 TagControl::CommonProfile4
276 }
277 }
278 Self::Implicit(n) => {
279 if n < 0x1_0000 {
280 TagControl::ImplicitProfile2
281 } else {
282 TagControl::ImplicitProfile4
283 }
284 }
285 Self::FullyQualified { number, .. } => {
286 if number < 0x1_0000 {
287 TagControl::FullyQualified6
288 } else {
289 TagControl::FullyQualified8
290 }
291 }
292 }
293 }
294
295 #[must_use]
297 pub const fn encoded_len(self) -> usize {
298 self.control().octets()
299 }
300
301 pub(crate) const fn control_bits(self) -> u8 {
303 (self.control() as u8) << 5
304 }
305
306 pub(crate) fn encode(self, out: &mut [u8]) -> Result<usize> {
310 let n = self.encoded_len();
311 let Some(dst) = out.get_mut(..n) else {
312 bail!(BufferTooSmall)
313 };
314 match self {
315 Self::Anonymous => {}
316 Self::Context(t) => {
317 let Some(b) = dst.first_mut() else {
318 bail!(BufferTooSmall)
319 };
320 *b = t;
321 }
322 Self::Common(number) | Self::Implicit(number) => {
323 write_le(dst, u64::from(number), n)?;
324 }
325 Self::FullyQualified {
326 vendor,
327 profile,
328 number,
329 } => {
330 let Some(head) = dst.get_mut(..4) else {
331 bail!(BufferTooSmall)
332 };
333 write_le(head, u64::from(vendor), 2)?;
334 let Some(prof) = head.get_mut(2..4) else {
335 bail!(BufferTooSmall)
336 };
337 write_le(prof, u64::from(profile), 2)?;
338 let Some(num) = dst.get_mut(4..) else {
339 bail!(BufferTooSmall)
340 };
341 write_le(num, u64::from(number), n.saturating_sub(4))?;
343 }
344 }
345 Ok(n)
346 }
347
348 #[expect(
352 clippy::cast_possible_truncation,
353 reason = "Appendix A's fully-qualified tag takes vendor and profile from two-octet fields"
354 )]
355 pub(crate) fn decode(control_bits: u8, buf: &[u8]) -> Result<(Self, usize)> {
356 let control = TagControl::from_bits(control_bits);
357 let n = control.octets();
358 let Some(src) = buf.get(..n) else {
359 bail!(TlvTruncated)
360 };
361 let tag = match control {
362 TagControl::Anonymous => Self::Anonymous,
363 TagControl::ContextSpecific => {
364 let Some(&b) = src.first() else {
365 bail!(TlvTruncated)
366 };
367 Self::Context(b)
368 }
369 TagControl::CommonProfile2 | TagControl::CommonProfile4 => {
370 Self::Common(read_le_u32(src)?)
371 }
372 TagControl::ImplicitProfile2 | TagControl::ImplicitProfile4 => {
373 Self::Implicit(read_le_u32(src)?)
374 }
375 TagControl::FullyQualified6 | TagControl::FullyQualified8 => {
376 let Some(vendor) = src.get(..2) else {
377 bail!(TlvTruncated)
378 };
379 let Some(profile) = src.get(2..4) else {
380 bail!(TlvTruncated)
381 };
382 let Some(number) = src.get(4..) else {
383 bail!(TlvTruncated)
384 };
385 Self::FullyQualified {
386 vendor: read_le_u32(vendor)? as u16,
387 profile: read_le_u32(profile)? as u16,
388 number: read_le_u32(number)?,
389 }
390 }
391 };
392 Ok((tag, n))
393 }
394
395 #[must_use]
405 pub fn canonical_cmp(self, other: Self) -> core::cmp::Ordering {
406 fn key(t: Tag) -> (u8, u16, u16, u32) {
407 match t {
408 Tag::Anonymous => (0, 0, 0, 0),
410 Tag::Context(n) => (1, 0, 0, u32::from(n)),
412 Tag::Common(n) => (2, COMMON_PROFILE, 0, n),
413 Tag::Implicit(n) => (3, 0, 0, n),
414 Tag::FullyQualified {
415 vendor,
416 profile,
417 number,
418 } => (4, vendor, profile, number),
419 }
420 }
421 key(self).cmp(&key(other))
422 }
423}
424
425pub(crate) fn write_le(out: &mut [u8], value: u64, n: usize) -> Result<()> {
427 let Some(dst) = out.get_mut(..n) else {
428 bail!(BufferTooSmall)
429 };
430 let bytes = value.to_le_bytes();
431 for (i, slot) in dst.iter_mut().enumerate() {
432 let Some(&b) = bytes.get(i) else {
434 bail!(BufferTooSmall)
435 };
436 *slot = b;
437 }
438 Ok(())
439}
440
441pub(crate) fn read_le_u64(src: &[u8]) -> Result<u64> {
443 if src.len() > 8 {
444 bail!(TlvOutOfRange)
445 }
446 let mut out = 0u64;
447 for (i, &b) in src.iter().enumerate() {
448 let shift = u32::try_from(i)
450 .ok()
451 .and_then(|i| i.checked_mul(8))
452 .ok_or(Error::new(ErrorCode::TlvOutOfRange))?;
453 out |= u64::from(b) << shift;
454 }
455 Ok(out)
456}
457
458fn read_le_u32(src: &[u8]) -> Result<u32> {
459 u32::try_from(read_le_u64(src)?).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
460}
461
462#[expect(
464 clippy::cast_possible_wrap,
465 reason = "a two's-complement reinterpretation, which is what Appendix A's signed integers are"
466)]
467pub(crate) fn read_le_i64(src: &[u8]) -> Result<i64> {
468 let raw = read_le_u64(src)?;
469 let bits = u32::try_from(src.len())
470 .ok()
471 .and_then(|n| n.checked_mul(8))
472 .ok_or(Error::new(ErrorCode::TlvOutOfRange))?;
473 if bits == 0 || bits >= 64 {
474 return Ok(raw as i64);
477 }
478 let shift = 64u32.saturating_sub(bits);
479 Ok(((raw << shift) as i64) >> shift)
481}
482
483#[cfg(test)]
484#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
485mod tests {
486 use super::*;
487
488 #[test]
489 fn element_type_round_trips_through_bits() {
490 for raw in 0u8..=0x18 {
491 let Ok(t) = ElementType::from_bits(raw) else {
492 continue;
493 };
494 assert_eq!(t.bits(), raw, "type {t:?} from 0x{raw:02x}");
495 }
496 }
497
498 #[test]
499 fn reserved_element_types_are_refused() {
500 for raw in 0x19u8..=0x1F {
501 assert_eq!(
502 ElementType::from_bits(raw).unwrap_err().code(),
503 ErrorCode::TlvInvalidControl
504 );
505 }
506 }
507
508 #[test]
509 fn tag_widths_follow_a8() {
510 assert_eq!(Tag::Anonymous.encoded_len(), 0);
511 assert_eq!(Tag::Context(1).encoded_len(), 1);
512 assert_eq!(Tag::Common(1).encoded_len(), 2);
513 assert_eq!(Tag::Common(100_000).encoded_len(), 4);
514 assert_eq!(Tag::Implicit(1).encoded_len(), 2);
515 assert_eq!(Tag::Implicit(0x1_0000).encoded_len(), 4);
516 assert_eq!(
517 Tag::FullyQualified {
518 vendor: 0xFFF1,
519 profile: 0xDEED,
520 number: 1
521 }
522 .encoded_len(),
523 6
524 );
525 assert_eq!(
526 Tag::FullyQualified {
527 vendor: 0xFFF1,
528 profile: 0xDEED,
529 number: 0xAA55_FEED
530 }
531 .encoded_len(),
532 8
533 );
534 }
535
536 #[test]
537 fn sign_extension() {
538 assert_eq!(read_le_i64(&[0xEF]).unwrap(), -17);
539 assert_eq!(read_le_i64(&[0x2A]).unwrap(), 42);
540 assert_eq!(read_le_i64(&[0xF0, 0x67, 0xFD, 0xFF]).unwrap(), -170_000);
541 assert_eq!(
542 read_le_i64(&[0x00, 0x90, 0x2F, 0x50, 0x09, 0x00, 0x00, 0x00]).unwrap(),
543 40_000_000_000
544 );
545 }
546
547 #[test]
548 fn minimal_widths() {
549 assert_eq!(Width::for_unsigned(42), Width::One);
550 assert_eq!(Width::for_unsigned(256), Width::Two);
551 assert_eq!(Width::for_signed(-17), Width::One);
552 assert_eq!(Width::for_signed(-170_000), Width::Four);
553 assert_eq!(Width::for_signed(128), Width::Two, "128 needs a sign bit");
554 assert_eq!(Width::for_signed(-128), Width::One);
555 }
556
557 #[test]
558 fn canonical_order_is_a24() {
559 let mut tags = [
560 Tag::FullyQualified {
561 vendor: 1,
562 profile: 1,
563 number: 1,
564 },
565 Tag::Context(5),
566 Tag::Anonymous,
567 Tag::Context(1),
568 Tag::FullyQualified {
569 vendor: 1,
570 profile: 0,
571 number: 9,
572 },
573 ];
574 tags.sort_by(|a, b| a.canonical_cmp(*b));
575 assert_eq!(tags[0], Tag::Anonymous);
576 assert_eq!(tags[1], Tag::Context(1));
577 assert_eq!(tags[2], Tag::Context(5));
578 assert_eq!(
580 tags[3],
581 Tag::FullyQualified {
582 vendor: 1,
583 profile: 0,
584 number: 9
585 }
586 );
587 }
588}