1use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, Writer};
4
5use super::{CompactArray, Date, DateTime, Time};
6
7pub const MAX_DEPTH: u8 = 16;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20#[repr(u8)]
21#[allow(missing_docs)]
22pub enum DataTag {
23 NullData = 0,
24 Array = 1,
25 Structure = 2,
26 Boolean = 3,
27 BitString = 4,
28 DoubleLong = 5,
29 DoubleLongUnsigned = 6,
30 OctetString = 9,
31 VisibleString = 10,
32 Utf8String = 12,
33 Bcd = 13,
34 Integer = 15,
35 Long = 16,
36 Unsigned = 17,
37 LongUnsigned = 18,
38 CompactArray = 19,
39 Long64 = 20,
40 Long64Unsigned = 21,
41 Enum = 22,
42 Float32 = 23,
43 Float64 = 24,
44 DateTime = 25,
45 Date = 26,
46 Time = 27,
47 DeltaInteger = 28,
48 DeltaLong = 29,
49 DeltaDoubleLong = 30,
50 DeltaUnsigned = 31,
51 DeltaLongUnsigned = 32,
52 DeltaDoubleLongUnsigned = 33,
53 DontCare = 255,
54}
55
56impl DataTag {
57 #[must_use]
59 pub const fn from_u8(v: u8) -> Option<Self> {
60 Some(match v {
61 0 => Self::NullData,
62 1 => Self::Array,
63 2 => Self::Structure,
64 3 => Self::Boolean,
65 4 => Self::BitString,
66 5 => Self::DoubleLong,
67 6 => Self::DoubleLongUnsigned,
68 9 => Self::OctetString,
69 10 => Self::VisibleString,
70 12 => Self::Utf8String,
71 13 => Self::Bcd,
72 15 => Self::Integer,
73 16 => Self::Long,
74 17 => Self::Unsigned,
75 18 => Self::LongUnsigned,
76 19 => Self::CompactArray,
77 20 => Self::Long64,
78 21 => Self::Long64Unsigned,
79 22 => Self::Enum,
80 23 => Self::Float32,
81 24 => Self::Float64,
82 25 => Self::DateTime,
83 26 => Self::Date,
84 27 => Self::Time,
85 28 => Self::DeltaInteger,
86 29 => Self::DeltaLong,
87 30 => Self::DeltaDoubleLong,
88 31 => Self::DeltaUnsigned,
89 32 => Self::DeltaLongUnsigned,
90 33 => Self::DeltaDoubleLongUnsigned,
91 255 => Self::DontCare,
92 _ => return None,
93 })
94 }
95
96 #[must_use]
98 pub const fn as_u8(self) -> u8 {
99 self as u8
100 }
101
102 #[must_use]
107 pub const fn fixed_len(self) -> Option<usize> {
108 Some(match self {
109 Self::NullData | Self::DontCare => 0,
110 Self::Boolean
111 | Self::Bcd
112 | Self::Integer
113 | Self::Unsigned
114 | Self::Enum
115 | Self::DeltaInteger
116 | Self::DeltaUnsigned => 1,
117 Self::Long | Self::LongUnsigned | Self::DeltaLong | Self::DeltaLongUnsigned => 2,
118 Self::DoubleLong
119 | Self::DoubleLongUnsigned
120 | Self::Float32
121 | Self::DeltaDoubleLong
122 | Self::DeltaDoubleLongUnsigned => 4,
123 Self::Time => 4,
124 Self::Date => 5,
125 Self::Long64 | Self::Long64Unsigned | Self::Float64 => 8,
126 Self::DateTime => 12,
127 _ => return None,
128 })
129 }
130
131 #[must_use]
133 pub const fn is_delta(self) -> bool {
134 matches!(
135 self,
136 Self::DeltaInteger
137 | Self::DeltaLong
138 | Self::DeltaDoubleLong
139 | Self::DeltaUnsigned
140 | Self::DeltaLongUnsigned
141 | Self::DeltaDoubleLongUnsigned
142 )
143 }
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct BitStr<'a> {
149 bits: usize,
150 bytes: &'a [u8],
151}
152
153impl<'a> BitStr<'a> {
154 pub fn new(bits: usize, bytes: &'a [u8]) -> Result<Self> {
156 if bytes.len() != bits.div_ceil(8) {
157 return Err(Error::new(ErrorKind::InvalidLength, 0));
158 }
159 Ok(Self { bits, bytes })
160 }
161
162 #[must_use]
164 pub const fn len(&self) -> usize {
165 self.bits
166 }
167
168 #[must_use]
170 pub const fn is_empty(&self) -> bool {
171 self.bits == 0
172 }
173
174 #[must_use]
176 pub const fn as_bytes(&self) -> &'a [u8] {
177 self.bytes
178 }
179
180 #[must_use]
183 pub fn bit(&self, i: usize) -> bool {
184 if i >= self.bits {
185 return false;
186 }
187 self.bytes[i / 8] & (0x80 >> (i % 8)) != 0
188 }
189
190 #[must_use]
196 pub fn to_u32(&self) -> u32 {
197 let mut v = 0u32;
198 for i in 0..self.bits.min(32) {
199 v = (v << 1) | u32::from(self.bit(i));
200 }
201 v
202 }
203}
204
205#[derive(Debug, Clone, Copy)]
211pub struct Seq<'a> {
212 count: usize,
213 raw: &'a [u8],
214 base: usize,
217 depth: u8,
219}
220
221impl PartialEq for Seq<'_> {
229 fn eq(&self, other: &Self) -> bool {
230 self.count == other.count && self.raw == other.raw
231 }
232}
233
234impl Eq for Seq<'_> {}
235
236impl<'a> Seq<'a> {
237 #[must_use]
239 pub const fn len(&self) -> usize {
240 self.count
241 }
242
243 #[must_use]
245 pub const fn is_empty(&self) -> bool {
246 self.count == 0
247 }
248
249 #[must_use]
251 pub const fn as_bytes(&self) -> &'a [u8] {
252 self.raw
253 }
254
255 #[must_use]
257 pub fn iter(&self) -> SeqIter<'a> {
258 SeqIter { reader: Reader::with_base(self.raw, self.base), left: self.count, depth: self.depth }
259 }
260
261 pub fn get(&self, index: usize) -> Result<Data<'a>> {
266 self.iter().nth(index).ok_or_else(|| Error::new(ErrorKind::InvalidLength, self.base))?
267 }
268}
269
270impl<'a> IntoIterator for &Seq<'a> {
271 type Item = Result<Data<'a>>;
272 type IntoIter = SeqIter<'a>;
273
274 fn into_iter(self) -> Self::IntoIter {
275 self.iter()
276 }
277}
278
279#[derive(Debug, Clone)]
281pub struct SeqIter<'a> {
282 reader: Reader<'a>,
283 left: usize,
284 depth: u8,
285}
286
287impl<'a> Iterator for SeqIter<'a> {
288 type Item = Result<Data<'a>>;
289
290 fn next(&mut self) -> Option<Self::Item> {
291 if self.left == 0 {
292 return None;
293 }
294 self.left -= 1;
295 Some(Data::decode_at(&mut self.reader, self.depth))
296 }
297
298 fn size_hint(&self) -> (usize, Option<usize>) {
299 (self.left, Some(self.left))
300 }
301}
302
303impl ExactSizeIterator for SeqIter<'_> {}
304
305#[derive(Debug, Clone, Copy, PartialEq)]
307#[allow(missing_docs)]
308pub enum Data<'a> {
309 Null,
312 Array(Seq<'a>),
313 Structure(Seq<'a>),
314 Boolean(bool),
315 BitString(BitStr<'a>),
316 DoubleLong(i32),
317 DoubleLongUnsigned(u32),
318 OctetString(&'a [u8]),
319 VisibleString(&'a [u8]),
321 Utf8String(&'a [u8]),
323 Bcd(i8),
324 Integer(i8),
325 Long(i16),
326 Unsigned(u8),
327 LongUnsigned(u16),
328 CompactArray(CompactArray<'a>),
329 Long64(i64),
330 Long64Unsigned(u64),
331 Enum(u8),
332 Float32(f32),
333 Float64(f64),
334 DateTime(DateTime),
335 Date(Date),
336 Time(Time),
337 DeltaInteger(i8),
338 DeltaLong(i16),
339 DeltaDoubleLong(i32),
340 DeltaUnsigned(u8),
341 DeltaLongUnsigned(u16),
342 DeltaDoubleLongUnsigned(u32),
343 DontCare,
345}
346
347impl<'a> Data<'a> {
348 #[must_use]
350 pub const fn tag(&self) -> DataTag {
351 match self {
352 Self::Null => DataTag::NullData,
353 Self::Array(_) => DataTag::Array,
354 Self::Structure(_) => DataTag::Structure,
355 Self::Boolean(_) => DataTag::Boolean,
356 Self::BitString(_) => DataTag::BitString,
357 Self::DoubleLong(_) => DataTag::DoubleLong,
358 Self::DoubleLongUnsigned(_) => DataTag::DoubleLongUnsigned,
359 Self::OctetString(_) => DataTag::OctetString,
360 Self::VisibleString(_) => DataTag::VisibleString,
361 Self::Utf8String(_) => DataTag::Utf8String,
362 Self::Bcd(_) => DataTag::Bcd,
363 Self::Integer(_) => DataTag::Integer,
364 Self::Long(_) => DataTag::Long,
365 Self::Unsigned(_) => DataTag::Unsigned,
366 Self::LongUnsigned(_) => DataTag::LongUnsigned,
367 Self::CompactArray(_) => DataTag::CompactArray,
368 Self::Long64(_) => DataTag::Long64,
369 Self::Long64Unsigned(_) => DataTag::Long64Unsigned,
370 Self::Enum(_) => DataTag::Enum,
371 Self::Float32(_) => DataTag::Float32,
372 Self::Float64(_) => DataTag::Float64,
373 Self::DateTime(_) => DataTag::DateTime,
374 Self::Date(_) => DataTag::Date,
375 Self::Time(_) => DataTag::Time,
376 Self::DeltaInteger(_) => DataTag::DeltaInteger,
377 Self::DeltaLong(_) => DataTag::DeltaLong,
378 Self::DeltaDoubleLong(_) => DataTag::DeltaDoubleLong,
379 Self::DeltaUnsigned(_) => DataTag::DeltaUnsigned,
380 Self::DeltaLongUnsigned(_) => DataTag::DeltaLongUnsigned,
381 Self::DeltaDoubleLongUnsigned(_) => DataTag::DeltaDoubleLongUnsigned,
382 Self::DontCare => DataTag::DontCare,
383 }
384 }
385
386 fn decode_at(r: &mut Reader<'a>, depth: u8) -> Result<Self> {
388 if depth >= MAX_DEPTH {
389 return Err(r.err(ErrorKind::DepthExceeded));
390 }
391 let tag_byte = r.u8()?;
392 let tag = DataTag::from_u8(tag_byte).ok_or_else(|| r.err_back(ErrorKind::InvalidTag(tag_byte), 1))?;
393 Ok(match tag {
394 DataTag::NullData => Self::Null,
395 DataTag::DontCare => Self::DontCare,
396 DataTag::Array | DataTag::Structure => {
397 let count = r.length()?;
398 let start = r.offset();
399 let before = r.rest();
400 let mut probe = Reader::with_base(before, start);
401 for _ in 0..count {
402 Self::skip(&mut probe, depth + 1)?;
403 }
404 let used = probe.consumed();
405 let raw = r.take(used)?;
406 let seq = Seq { count, raw, base: start, depth: depth + 1 };
407 if tag == DataTag::Array { Self::Array(seq) } else { Self::Structure(seq) }
408 }
409 DataTag::Boolean => Self::Boolean(r.u8()? != 0),
410 DataTag::BitString => {
411 let bits = r.length()?;
412 let bytes = r.take(bits.div_ceil(8))?;
413 Self::BitString(BitStr { bits, bytes })
414 }
415 DataTag::DoubleLong => Self::DoubleLong(r.i32()?),
416 DataTag::DoubleLongUnsigned => Self::DoubleLongUnsigned(r.u32()?),
417 DataTag::OctetString => Self::OctetString(r.length_prefixed()?),
418 DataTag::VisibleString => Self::VisibleString(r.length_prefixed()?),
419 DataTag::Utf8String => Self::Utf8String(r.length_prefixed()?),
420 DataTag::Bcd => Self::Bcd(r.i8()?),
421 DataTag::Integer => Self::Integer(r.i8()?),
422 DataTag::Long => Self::Long(r.i16()?),
423 DataTag::Unsigned => Self::Unsigned(r.u8()?),
424 DataTag::LongUnsigned => Self::LongUnsigned(r.u16()?),
425 DataTag::CompactArray => Self::CompactArray(CompactArray::decode_body(r, depth + 1)?),
426 DataTag::Long64 => Self::Long64(r.i64()?),
427 DataTag::Long64Unsigned => Self::Long64Unsigned(r.u64()?),
428 DataTag::Enum => Self::Enum(r.u8()?),
429 DataTag::Float32 => Self::Float32(f32::from_bits(r.u32()?)),
430 DataTag::Float64 => Self::Float64(f64::from_bits(r.u64()?)),
431 DataTag::DateTime => Self::DateTime(DateTime::from_bytes(r.array()?)),
432 DataTag::Date => Self::Date(Date::from_bytes(r.array()?)),
433 DataTag::Time => Self::Time(Time::from_bytes(r.array()?)),
434 DataTag::DeltaInteger => Self::DeltaInteger(r.i8()?),
435 DataTag::DeltaLong => Self::DeltaLong(r.i16()?),
436 DataTag::DeltaDoubleLong => Self::DeltaDoubleLong(r.i32()?),
437 DataTag::DeltaUnsigned => Self::DeltaUnsigned(r.u8()?),
438 DataTag::DeltaLongUnsigned => Self::DeltaLongUnsigned(r.u16()?),
439 DataTag::DeltaDoubleLongUnsigned => Self::DeltaDoubleLongUnsigned(r.u32()?),
440 })
441 }
442
443 fn skip(r: &mut Reader<'a>, depth: u8) -> Result<()> {
445 if depth >= MAX_DEPTH {
446 return Err(r.err(ErrorKind::DepthExceeded));
447 }
448 let tag_byte = r.u8()?;
449 let tag = DataTag::from_u8(tag_byte).ok_or_else(|| r.err_back(ErrorKind::InvalidTag(tag_byte), 1))?;
450 if let Some(n) = tag.fixed_len() {
451 return r.skip(n);
452 }
453 match tag {
454 DataTag::Array | DataTag::Structure => {
455 let count = r.length()?;
456 for _ in 0..count {
457 Self::skip(r, depth + 1)?;
458 }
459 Ok(())
460 }
461 DataTag::BitString => {
462 let bits = r.length()?;
463 r.skip(bits.div_ceil(8))
464 }
465 DataTag::OctetString | DataTag::VisibleString | DataTag::Utf8String => {
466 let n = r.length()?;
467 r.skip(n)
468 }
469 DataTag::CompactArray => CompactArray::skip_body(r, depth + 1),
470 _ => Err(r.err(ErrorKind::InvalidTag(tag_byte))),
471 }
472 }
473
474 #[must_use]
480 pub fn as_i64(&self) -> Option<i64> {
481 Some(match *self {
482 Self::Integer(v) | Self::DeltaInteger(v) => i64::from(v),
483 Self::Long(v) | Self::DeltaLong(v) => i64::from(v),
484 Self::DoubleLong(v) | Self::DeltaDoubleLong(v) => i64::from(v),
485 Self::Long64(v) => v,
486 Self::Unsigned(v) | Self::DeltaUnsigned(v) => i64::from(v),
487 Self::LongUnsigned(v) | Self::DeltaLongUnsigned(v) => i64::from(v),
488 Self::DoubleLongUnsigned(v) | Self::DeltaDoubleLongUnsigned(v) => i64::from(v),
489 Self::Long64Unsigned(v) => i64::try_from(v).ok()?,
490 Self::Enum(v) => i64::from(v),
491 _ => return None,
492 })
493 }
494
495 #[must_use]
497 pub fn as_u64(&self) -> Option<u64> {
498 match *self {
499 Self::Long64Unsigned(v) => Some(v),
500 _ => u64::try_from(self.as_i64()?).ok(),
501 }
502 }
503
504 #[must_use]
513 pub const fn as_bcd(&self) -> Option<u8> {
514 let Self::Bcd(v) = *self else {
515 return None;
516 };
517 let b = v as u8;
518 let (high, low) = (b >> 4, b & 0x0F);
519 if high > 9 || low > 9 {
520 return None;
521 }
522 Some(high * 10 + low)
523 }
524
525 #[must_use]
527 pub const fn as_bool(&self) -> Option<bool> {
528 match *self {
529 Self::Boolean(v) => Some(v),
530 _ => None,
531 }
532 }
533
534 #[must_use]
536 pub const fn as_bytes(&self) -> Option<&'a [u8]> {
537 match *self {
538 Self::OctetString(b) | Self::VisibleString(b) | Self::Utf8String(b) => Some(b),
539 _ => None,
540 }
541 }
542
543 #[must_use]
545 pub fn as_str(&self) -> Option<&'a str> {
546 core::str::from_utf8(self.as_bytes()?).ok()
547 }
548
549 #[must_use]
551 pub const fn as_seq(&self) -> Option<Seq<'a>> {
552 match *self {
553 Self::Array(s) | Self::Structure(s) => Some(s),
554 _ => None,
555 }
556 }
557
558 #[must_use]
564 pub const fn as_structure(&self) -> Option<Seq<'a>> {
565 match *self {
566 Self::Structure(s) => Some(s),
567 _ => None,
568 }
569 }
570
571 #[must_use]
573 pub const fn as_array(&self) -> Option<Seq<'a>> {
574 match *self {
575 Self::Array(s) => Some(s),
576 _ => None,
577 }
578 }
579
580 pub fn field(&self, index: usize) -> Result<Data<'a>> {
582 self.as_structure().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?.get(index)
583 }
584
585 #[must_use]
587 pub fn as_obis(&self) -> Option<crate::obis::Obis> {
588 let b: [u8; 6] = self.as_bytes()?.try_into().ok()?;
589 Some(crate::obis::Obis(b))
590 }
591
592 #[must_use]
594 pub const fn is_delta(&self) -> bool {
595 self.tag().is_delta()
596 }
597}
598
599impl Encode for Data<'_> {
600 fn encode(&self, w: &mut dyn Writer) -> Result<()> {
601 w.write_u8(self.tag().as_u8())?;
602 match self {
603 Self::Null | Self::DontCare => Ok(()),
604 Self::Array(s) | Self::Structure(s) => {
605 w.write_length(s.len())?;
606 w.write_bytes(s.as_bytes())
607 }
608 Self::Boolean(v) => w.write_u8(u8::from(*v)),
609 Self::BitString(b) => {
610 w.write_length(b.len())?;
611 w.write_bytes(b.as_bytes())
612 }
613 Self::DoubleLong(v) => w.write_u32(*v as u32),
614 Self::DoubleLongUnsigned(v) => w.write_u32(*v),
615 Self::OctetString(b) | Self::VisibleString(b) | Self::Utf8String(b) => w.write_length_prefixed(b),
616 Self::Bcd(v) | Self::Integer(v) | Self::DeltaInteger(v) => w.write_u8(*v as u8),
617 Self::Long(v) | Self::DeltaLong(v) => w.write_u16(*v as u16),
618 Self::Unsigned(v) | Self::Enum(v) | Self::DeltaUnsigned(v) => w.write_u8(*v),
619 Self::LongUnsigned(v) | Self::DeltaLongUnsigned(v) => w.write_u16(*v),
620 Self::CompactArray(c) => c.encode_body(w),
621 Self::Long64(v) => w.write_u64(*v as u64),
622 Self::Long64Unsigned(v) => w.write_u64(*v),
623 Self::Float32(v) => w.write_u32(v.to_bits()),
624 Self::Float64(v) => w.write_u64(v.to_bits()),
625 Self::DateTime(v) => w.write_bytes(&v.to_bytes()),
626 Self::Date(v) => w.write_bytes(&v.to_bytes()),
627 Self::Time(v) => w.write_bytes(&v.to_bytes()),
628 Self::DeltaDoubleLong(v) => w.write_u32(*v as u32),
629 Self::DeltaDoubleLongUnsigned(v) => w.write_u32(*v),
630 }
631 }
632}
633
634impl<'a> Decode<'a> for Data<'a> {
635 fn decode(r: &mut Reader<'a>) -> Result<Self> {
636 Self::decode_at(r, 0)
637 }
638}
639
640impl<'a> Data<'a> {
641 pub fn from_bytes_in(bytes: &'a [u8]) -> Result<Self> {
646 <Self as Decode<'a>>::from_bytes(bytes)
647 }
648}
649
650#[cfg(feature = "alloc")]
652#[derive(Debug, Clone, PartialEq)]
653#[allow(missing_docs)]
654pub enum DataBuf {
655 Null,
656 Array(alloc::vec::Vec<DataBuf>),
657 Structure(alloc::vec::Vec<DataBuf>),
658 Boolean(bool),
659 BitString {
660 bits: usize,
662 bytes: alloc::vec::Vec<u8>,
664 },
665 DoubleLong(i32),
666 DoubleLongUnsigned(u32),
667 OctetString(alloc::vec::Vec<u8>),
668 VisibleString(alloc::vec::Vec<u8>),
669 Utf8String(alloc::vec::Vec<u8>),
670 Bcd(i8),
671 Integer(i8),
672 Long(i16),
673 Unsigned(u8),
674 LongUnsigned(u16),
675 Long64(i64),
676 Long64Unsigned(u64),
677 Enum(u8),
678 Float32(f32),
679 Float64(f64),
680 DateTime(DateTime),
681 Date(Date),
682 Time(Time),
683 DeltaInteger(i8),
684 DeltaLong(i16),
685 DeltaDoubleLong(i32),
686 DeltaUnsigned(u8),
687 DeltaLongUnsigned(u16),
688 DeltaDoubleLongUnsigned(u32),
689 DontCare,
690}
691
692#[cfg(feature = "alloc")]
693impl DataBuf {
694 #[must_use]
697 pub fn as_i64(&self) -> Option<i64> {
698 Some(match *self {
699 Self::Integer(v) | Self::DeltaInteger(v) => i64::from(v),
700 Self::Long(v) | Self::DeltaLong(v) => i64::from(v),
701 Self::DoubleLong(v) | Self::DeltaDoubleLong(v) => i64::from(v),
702 Self::Long64(v) => v,
703 Self::Unsigned(v) | Self::Enum(v) | Self::DeltaUnsigned(v) => i64::from(v),
704 Self::LongUnsigned(v) | Self::DeltaLongUnsigned(v) => i64::from(v),
705 Self::DoubleLongUnsigned(v) | Self::DeltaDoubleLongUnsigned(v) => i64::from(v),
706 Self::Long64Unsigned(v) => i64::try_from(v).ok()?,
707 _ => return None,
708 })
709 }
710
711 #[must_use]
714 pub fn as_u64(&self) -> Option<u64> {
715 match *self {
716 Self::Long64Unsigned(v) => Some(v),
717 _ => self.as_i64().and_then(|v| u64::try_from(v).ok()),
718 }
719 }
720
721 #[must_use]
723 pub const fn as_bool(&self) -> Option<bool> {
724 if let Self::Boolean(b) = *self { Some(b) } else { None }
725 }
726
727 #[must_use]
729 pub fn as_bytes(&self) -> Option<&[u8]> {
730 match self {
731 Self::OctetString(b) | Self::VisibleString(b) | Self::Utf8String(b) => Some(b),
732 _ => None,
733 }
734 }
735
736 #[must_use]
738 pub fn as_str(&self) -> Option<&str> {
739 match self {
740 Self::VisibleString(b) | Self::Utf8String(b) => core::str::from_utf8(b).ok(),
741 _ => None,
742 }
743 }
744
745 #[must_use]
747 pub fn as_array(&self) -> Option<&[Self]> {
748 if let Self::Array(v) = self { Some(v) } else { None }
749 }
750
751 #[must_use]
753 pub fn as_structure(&self) -> Option<&[Self]> {
754 if let Self::Structure(v) = self { Some(v) } else { None }
755 }
756
757 #[must_use]
759 pub const fn as_datetime(&self) -> Option<DateTime> {
760 if let Self::DateTime(d) = *self { Some(d) } else { None }
761 }
762
763 #[must_use]
765 pub fn as_obis(&self) -> Option<crate::obis::Obis> {
766 let bytes: [u8; 6] = self.as_bytes()?.try_into().ok()?;
767 Some(crate::obis::Obis::from_bytes(bytes))
768 }
769
770 pub fn from_data(d: &Data<'_>) -> Result<Self> {
775 use alloc::vec::Vec;
776 Ok(match *d {
777 Data::Null => Self::Null,
778 Data::DontCare => Self::DontCare,
779 Data::Array(s) => {
780 Self::Array(s.iter().map(|e| Self::from_data(&e?)).collect::<Result<Vec<_>>>()?)
781 }
782 Data::Structure(s) => {
783 Self::Structure(s.iter().map(|e| Self::from_data(&e?)).collect::<Result<Vec<_>>>()?)
784 }
785 Data::Boolean(v) => Self::Boolean(v),
786 Data::BitString(b) => Self::BitString { bits: b.len(), bytes: b.as_bytes().to_vec() },
787 Data::DoubleLong(v) => Self::DoubleLong(v),
788 Data::DoubleLongUnsigned(v) => Self::DoubleLongUnsigned(v),
789 Data::OctetString(b) => Self::OctetString(b.to_vec()),
790 Data::VisibleString(b) => Self::VisibleString(b.to_vec()),
791 Data::Utf8String(b) => Self::Utf8String(b.to_vec()),
792 Data::Bcd(v) => Self::Bcd(v),
793 Data::Integer(v) => Self::Integer(v),
794 Data::Long(v) => Self::Long(v),
795 Data::Unsigned(v) => Self::Unsigned(v),
796 Data::LongUnsigned(v) => Self::LongUnsigned(v),
797 Data::CompactArray(c) => Self::Array(c.to_rows()?),
798 Data::Long64(v) => Self::Long64(v),
799 Data::Long64Unsigned(v) => Self::Long64Unsigned(v),
800 Data::Enum(v) => Self::Enum(v),
801 Data::Float32(v) => Self::Float32(v),
802 Data::Float64(v) => Self::Float64(v),
803 Data::DateTime(v) => Self::DateTime(v),
804 Data::Date(v) => Self::Date(v),
805 Data::Time(v) => Self::Time(v),
806 Data::DeltaInteger(v) => Self::DeltaInteger(v),
807 Data::DeltaLong(v) => Self::DeltaLong(v),
808 Data::DeltaDoubleLong(v) => Self::DeltaDoubleLong(v),
809 Data::DeltaUnsigned(v) => Self::DeltaUnsigned(v),
810 Data::DeltaLongUnsigned(v) => Self::DeltaLongUnsigned(v),
811 Data::DeltaDoubleLongUnsigned(v) => Self::DeltaDoubleLongUnsigned(v),
812 })
813 }
814
815 pub fn parse(bytes: &[u8]) -> Result<Self> {
817 Self::from_data(&Data::from_bytes(bytes)?)
818 }
819}
820
821#[cfg(feature = "alloc")]
831impl core::fmt::Display for DataBuf {
832 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
833 fn list(
834 f: &mut core::fmt::Formatter<'_>,
835 open: &str,
836 items: &[DataBuf],
837 close: &str,
838 ) -> core::fmt::Result {
839 f.write_str(open)?;
840 for (i, item) in items.iter().enumerate() {
841 if i > 0 {
842 f.write_str(", ")?;
843 }
844 write!(f, "{item}")?;
845 }
846 f.write_str(close)
847 }
848 match self {
849 Self::Null => f.write_str("null"),
850 Self::DontCare => f.write_str("dont-care"),
851 Self::Array(v) => list(f, "[", v, "]"),
852 Self::Structure(v) => list(f, "{", v, "}"),
853 Self::Boolean(b) => write!(f, "{b}"),
854 Self::BitString { bits, bytes } => {
855 for i in 0..*bits {
856 let byte = bytes.get(i / 8).copied().unwrap_or(0);
857 f.write_str(if byte & (0x80 >> (i % 8)) != 0 { "1" } else { "0" })?;
858 }
859 Ok(())
860 }
861 Self::OctetString(b) => {
862 for byte in b {
863 write!(f, "{byte:02x}")?;
864 }
865 Ok(())
866 }
867 Self::VisibleString(b) | Self::Utf8String(b) => {
868 write!(f, "{:?}", alloc::string::String::from_utf8_lossy(b))
869 }
870 Self::Float32(v) => write!(f, "{v}"),
871 Self::Float64(v) => write!(f, "{v}"),
872 Self::DateTime(d) => write!(f, "{d}"),
873 Self::Date(d) => write!(f, "{d}"),
874 Self::Time(t) => write!(f, "{t}"),
875 Self::Bcd(v) => write!(f, "{v}"),
876 other => match other.as_i64() {
877 Some(v) => write!(f, "{v}"),
878 None => write!(f, "{}", other.as_u64().unwrap_or_default()),
879 },
880 }
881 }
882}
883
884#[cfg(feature = "alloc")]
885impl Encode for DataBuf {
886 fn encode(&self, w: &mut dyn Writer) -> Result<()> {
887 let tag = match self {
888 Self::Null => 0,
889 Self::Array(_) => 1,
890 Self::Structure(_) => 2,
891 Self::Boolean(_) => 3,
892 Self::BitString { .. } => 4,
893 Self::DoubleLong(_) => 5,
894 Self::DoubleLongUnsigned(_) => 6,
895 Self::OctetString(_) => 9,
896 Self::VisibleString(_) => 10,
897 Self::Utf8String(_) => 12,
898 Self::Bcd(_) => 13,
899 Self::Integer(_) => 15,
900 Self::Long(_) => 16,
901 Self::Unsigned(_) => 17,
902 Self::LongUnsigned(_) => 18,
903 Self::Long64(_) => 20,
904 Self::Long64Unsigned(_) => 21,
905 Self::Enum(_) => 22,
906 Self::Float32(_) => 23,
907 Self::Float64(_) => 24,
908 Self::DateTime(_) => 25,
909 Self::Date(_) => 26,
910 Self::Time(_) => 27,
911 Self::DeltaInteger(_) => 28,
912 Self::DeltaLong(_) => 29,
913 Self::DeltaDoubleLong(_) => 30,
914 Self::DeltaUnsigned(_) => 31,
915 Self::DeltaLongUnsigned(_) => 32,
916 Self::DeltaDoubleLongUnsigned(_) => 33,
917 Self::DontCare => 255,
918 };
919 w.write_u8(tag)?;
920 match self {
921 Self::Null | Self::DontCare => Ok(()),
922 Self::Array(v) | Self::Structure(v) => {
923 w.write_length(v.len())?;
924 for e in v {
925 e.encode(w)?;
926 }
927 Ok(())
928 }
929 Self::Boolean(v) => w.write_u8(u8::from(*v)),
930 Self::BitString { bits, bytes } => {
931 w.write_length(*bits)?;
932 w.write_bytes(bytes)
933 }
934 Self::DoubleLong(v) => w.write_u32(*v as u32),
935 Self::DoubleLongUnsigned(v) => w.write_u32(*v),
936 Self::OctetString(b) | Self::VisibleString(b) | Self::Utf8String(b) => w.write_length_prefixed(b),
937 Self::Bcd(v) | Self::Integer(v) | Self::DeltaInteger(v) => w.write_u8(*v as u8),
938 Self::Long(v) | Self::DeltaLong(v) => w.write_u16(*v as u16),
939 Self::Unsigned(v) | Self::Enum(v) | Self::DeltaUnsigned(v) => w.write_u8(*v),
940 Self::LongUnsigned(v) | Self::DeltaLongUnsigned(v) => w.write_u16(*v),
941 Self::Long64(v) => w.write_u64(*v as u64),
942 Self::Long64Unsigned(v) => w.write_u64(*v),
943 Self::Float32(v) => w.write_u32(v.to_bits()),
944 Self::Float64(v) => w.write_u64(v.to_bits()),
945 Self::DateTime(v) => w.write_bytes(&v.to_bytes()),
946 Self::Date(v) => w.write_bytes(&v.to_bytes()),
947 Self::Time(v) => w.write_bytes(&v.to_bytes()),
948 Self::DeltaDoubleLong(v) => w.write_u32(*v as u32),
949 Self::DeltaDoubleLongUnsigned(v) => w.write_u32(*v),
950 }
951 }
952}
953
954#[cfg(test)]
955mod tests {
956 #[test]
962 fn two_identical_sequences_are_equal_wherever_they_were_decoded() {
963 use super::*;
964 let bare = [0x01u8, 0x02, 0x11, 0x07, 0x11, 0x09];
965 let nested = [0x02u8, 0x01, 0x01, 0x02, 0x11, 0x07, 0x11, 0x09];
968
969 let a = Data::from_bytes(&bare).unwrap();
970 let outer = Data::from_bytes(&nested).unwrap();
971 let b = outer.as_structure().unwrap().get(0).unwrap();
972
973 assert_eq!(a, b, "the same array is the same array wherever it was found");
974 assert_eq!(a.as_array().unwrap(), b.as_array().unwrap());
975 }
976
977 use super::*;
978
979 #[test]
981 fn a_bcd_byte_is_not_the_integer_it_looks_like() {
982 let d = Data::Bcd(0x25);
983 assert_eq!(d.as_bcd(), Some(25), "0x25 reads as twenty-five");
984 assert_eq!(
985 d.as_i64(),
986 None,
987 "and must not quietly answer thirty-seven to a caller asking for an integer"
988 );
989 assert_eq!(Data::Bcd(0x1A).as_bcd(), None);
991 assert_eq!(Data::Bcd(0xA1u8 as i8).as_bcd(), None);
992 assert_eq!(Data::Bcd(0x99u8 as i8).as_bcd(), Some(99));
993 assert_eq!(Data::Unsigned(0x25).as_bcd(), None);
995 assert_eq!(Data::Unsigned(0x25).as_i64(), Some(37));
996 }
997
998 #[test]
999 fn a_bit_string_is_numbered_from_its_most_significant_bit() {
1000 let bytes = [0b1010_0000u8];
1001 let b = BitStr::new(3, &bytes).unwrap();
1002 assert!(b.bit(0));
1003 assert!(!b.bit(1));
1004 assert!(b.bit(2));
1005 assert!(!b.bit(3), "past the end is false, not a panic");
1006 assert_eq!(b.to_u32(), 0b101);
1007 }
1008}