Skip to main content

dlms_cosem_kit/axdr/
data.rs

1//! The A-XDR `Data` type.
2
3use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, Writer};
4
5use super::{CompactArray, Date, DateTime, Time};
6
7/// The deepest nesting a decoder will follow before refusing.
8///
9/// Structures nest legitimately — a profile buffer is an array of structures, and a
10/// capture-object entry is a structure inside it — but nothing in the Blue Book nests
11/// anywhere near this deep, and unbounded recursion on attacker-controlled input is how
12/// a decoder is turned into a stack overflow.
13pub const MAX_DEPTH: u8 = 16;
14
15/// The tag byte that introduces a value.
16///
17/// Every variant is a tag the Blue Book defines. An unknown tag is refused rather than
18/// skipped: without a length, an unknown value cannot be stepped over safely.
19#[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    /// Classify a tag byte.
58    #[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    /// The tag byte.
97    #[must_use]
98    pub const fn as_u8(self) -> u8 {
99        self as u8
100    }
101
102    /// The fixed encoded length of the value body, for tags that have one.
103    ///
104    /// `None` for the variable-length tags: strings, arrays, structures, bit strings and
105    /// compact arrays.
106    #[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    /// True for one of the six delta types added in Green Book edition 10.
132    #[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/// A bit string: a bit count and the bytes holding it, most significant bit first.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct BitStr<'a> {
149    bits: usize,
150    bytes: &'a [u8],
151}
152
153impl<'a> BitStr<'a> {
154    /// A bit string over `bytes`, of which the first `bits` are significant.
155    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    /// The number of significant bits.
163    #[must_use]
164    pub const fn len(&self) -> usize {
165        self.bits
166    }
167
168    /// True when there are no bits.
169    #[must_use]
170    pub const fn is_empty(&self) -> bool {
171        self.bits == 0
172    }
173
174    /// The backing bytes.
175    #[must_use]
176    pub const fn as_bytes(&self) -> &'a [u8] {
177        self.bytes
178    }
179
180    /// Bit `i`, counting from the most significant bit of the first byte — which is how
181    /// the Blue Book numbers them, and the opposite of the usual little-endian habit.
182    #[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    /// The bits as a big-endian integer, most significant bit first.
191    ///
192    /// The conformance block and the version-3 access-right masks are bit strings that
193    /// are used as integers; this is the conversion, and it saturates rather than
194    /// wrapping for a longer string than `u32` can hold.
195    #[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/// A borrowed array or structure: an element count and the bytes they live in.
206///
207/// Elements are validated when the sequence is decoded — every one is walked to find
208/// where the sequence ends — and re-parsed when iterated. That is one extra pass over
209/// the bytes in exchange for never allocating and never holding an index table.
210#[derive(Debug, Clone, Copy)]
211pub struct Seq<'a> {
212    count: usize,
213    raw: &'a [u8],
214    /// Where these bytes started in the frame they were decoded from. Diagnostic only:
215    /// it is what makes an error inside the sequence point at the right byte.
216    base: usize,
217    /// How deep this sequence sits, so its children inherit the remaining budget.
218    depth: u8,
219}
220
221/// Two sequences are equal when they hold the same elements.
222///
223/// Written by hand rather than derived, because `base` and `depth` describe *where the
224/// bytes came from* and not what they say. The derived version made an array decoded at
225/// offset 3 unequal to the identical array decoded at offset 0 — so comparing two APDUs,
226/// deduplicating readings, or asserting a round trip all reported differences that were
227/// not there.
228impl 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    /// The number of elements.
238    #[must_use]
239    pub const fn len(&self) -> usize {
240        self.count
241    }
242
243    /// True when there are no elements.
244    #[must_use]
245    pub const fn is_empty(&self) -> bool {
246        self.count == 0
247    }
248
249    /// The encoded elements, tags included.
250    #[must_use]
251    pub const fn as_bytes(&self) -> &'a [u8] {
252        self.raw
253    }
254
255    /// Iterate the elements.
256    #[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    /// The element at `index`, decoded by walking from the start.
262    ///
263    /// `O(index)`. For a structure of a handful of fields — which is what the Blue Book
264    /// defines — that is cheaper than any index this could have built instead.
265    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/// Iterator over the elements of a [`Seq`].
280#[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/// A value, borrowed from the buffer it was decoded out of.
306#[derive(Debug, Clone, Copy, PartialEq)]
307#[allow(missing_docs)]
308pub enum Data<'a> {
309    /// No value. In a profile buffer with null-data compression it also means
310    /// "unchanged from the previous row".
311    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    /// An ISO 646 string. Not validated as UTF-8 — meters put arbitrary bytes here.
320    VisibleString(&'a [u8]),
321    /// Bytes tagged as UTF-8. Validated on access through [`Data::as_str`], not on decode.
322    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    /// A wildcard used in access descriptors to mean "any".
344    DontCare,
345}
346
347impl<'a> Data<'a> {
348    /// The tag this value encodes with.
349    #[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    /// Decode one value with the depth budget already spent by enclosing sequences.
387    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    /// Walk one value without building it, to find where it ends.
444    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    /// The value as an integer, for any of the signed or unsigned integer tags.
475    ///
476    /// Returns `None` for a value that is not an integer, and for a `u64` that does not
477    /// fit in an `i128`'s positive range — which cannot happen, and is written as a
478    /// conversion rather than a cast so that it stays impossible.
479    #[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    /// The value as an unsigned integer, when it is one and is not negative.
496    #[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    /// The decimal value of a binary-coded-decimal byte.
505    ///
506    /// `bcd` is *not* an integer, and this is deliberately not part of
507    /// [`Data::as_i64`]: the byte `0x25` is the number twenty-five, and reading it as an
508    /// integer gives thirty-seven. Both are plausible-looking meter readings, which is
509    /// what makes the confusion expensive — so a caller has to say which one it means.
510    ///
511    /// `None` when either nibble is not a decimal digit.
512    #[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    /// The value as a `bool`.
526    #[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    /// The bytes of an octet string or either string type.
535    #[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    /// A string value, validated as UTF-8 here rather than at decode time.
544    #[must_use]
545    pub fn as_str(&self) -> Option<&'a str> {
546        core::str::from_utf8(self.as_bytes()?).ok()
547    }
548
549    /// The elements of an array or structure.
550    #[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    /// The elements of a structure, refusing an array.
559    ///
560    /// A structure is a record with a fixed shape and an array is a repetition; a
561    /// decoder that accepts either where the specification says one is how a field gets
562    /// read out of the wrong position.
563    #[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    /// The elements of an array, refusing a structure.
572    #[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    /// Field `index` of a structure.
581    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    /// A six-byte octet string read as a logical name.
586    #[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    /// True for one of the six delta types.
593    #[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    /// Decode a value that borrows `bytes`, requiring all of them to be used.
642    ///
643    /// The same as [`Decode::from_bytes`], named so it can be called where the lifetime
644    /// of the buffer, rather than of a reader, is what matters.
645    pub fn from_bytes_in(bytes: &'a [u8]) -> Result<Self> {
646        <Self as Decode<'a>>::from_bytes(bytes)
647    }
648}
649
650/// An owned `Data` tree.
651#[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        /// Significant bits.
661        bits: usize,
662        /// Backing bytes.
663        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    /// The value as a signed integer, for any integer type that fits — including the
695    /// delta types and an enum's code.
696    #[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    /// The value as an unsigned integer, for any integer type that holds a non-negative
712    /// value.
713    #[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    /// The value as a boolean.
722    #[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    /// The bytes of an octet, visible or UTF-8 string.
728    #[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    /// A visible or UTF-8 string, when it is valid UTF-8.
737    #[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    /// The elements of an array.
746    #[must_use]
747    pub fn as_array(&self) -> Option<&[Self]> {
748        if let Self::Array(v) = self { Some(v) } else { None }
749    }
750
751    /// The fields of a structure.
752    #[must_use]
753    pub fn as_structure(&self) -> Option<&[Self]> {
754        if let Self::Structure(v) = self { Some(v) } else { None }
755    }
756
757    /// The date-time, when it is one.
758    #[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    /// An OBIS code carried as a six-byte octet string, as logical names are.
764    #[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    /// Copy a borrowed value into an owned one.
771    ///
772    /// A compact array is expanded into an array of its rows, because the compact
773    /// encoding is a transfer syntax rather than a distinct type.
774    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    /// Decode an owned value from bytes.
816    pub fn parse(bytes: &[u8]) -> Result<Self> {
817        Self::from_data(&Data::from_bytes(bytes)?)
818    }
819}
820
821/// A compact, human-readable rendering: integers as numbers, strings quoted, octet
822/// strings in hex, arrays in `[…]` and structures in `{…}`, dates and times as the
823/// standard writes them.
824///
825/// ```
826/// use dlms_cosem_kit::axdr::DataBuf;
827/// let row = DataBuf::Structure(vec![DataBuf::DoubleLongUnsigned(1_000_000), DataBuf::OctetString(vec![0xAB, 0x01])]);
828/// assert_eq!(row.to_string(), "{1000000, ab01}");
829/// ```
830#[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    /// Equality is about the elements, not about where the bytes were found.
957    ///
958    /// The derived implementation compared the diagnostic offset and the nesting depth,
959    /// so the same array decoded at two positions was unequal to itself — which is a
960    /// wrong answer for anything that compares two decoded APDUs, and it is silent.
961    #[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        // The same array, nested inside a structure, so it decodes at a different offset
966        // and a deeper level.
967        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    /// `bcd` looks like an integer on the wire and is not one.
980    #[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        // A nibble above nine is not a decimal digit.
990        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        // And nothing else answers to it.
994        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}