Skip to main content

dlms_cosem_kit/xdlms/
result.rs

1//! Service results and data blocks.
2
3use crate::axdr::Data;
4use crate::codec::{Decode, Encode, ErrorKind, Reader, Result, Writer};
5
6macro_rules! result_enum {
7    ($(#[$m:meta])* $name:ident { $($code:literal $variant:ident $doc:literal,)* }) => {
8        $(#[$m])*
9        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10        #[non_exhaustive]
11        pub enum $name {
12            $(
13                #[doc = $doc]
14                $variant,
15            )*
16            /// A code this crate does not name. Preserved rather than rejected: a server
17            /// may report something a later edition defines, and turning that into a
18            /// parse error would lose the only diagnostic the caller has.
19            Other(u8),
20        }
21
22        impl $name {
23            /// From the wire byte.
24            #[must_use]
25            pub const fn from_u8(v: u8) -> Self {
26                match v {
27                    $($code => Self::$variant,)*
28                    other => Self::Other(other),
29                }
30            }
31
32            /// The wire byte.
33            #[must_use]
34            pub const fn as_u8(self) -> u8 {
35                match self {
36                    $(Self::$variant => $code,)*
37                    Self::Other(v) => v,
38                }
39            }
40
41            /// True only for success.
42            #[must_use]
43            pub const fn is_success(self) -> bool {
44                matches!(self, Self::Success)
45            }
46
47            /// The result as a `core::result::Result`, so `?` works on it.
48            ///
49            /// # Errors
50            /// Returns `self` when it is not [`Self::Success`].
51            pub const fn ok(self) -> core::result::Result<(), Self> {
52                if self.is_success() { Ok(()) } else { Err(self) }
53            }
54        }
55    };
56}
57
58result_enum! {
59    /// Why a GET or SET did not return a value.
60    DataAccessResult {
61        0 Success "The attribute was read or written.",
62        1 HardwareFault "The meter's hardware could not serve the request.",
63        2 TemporaryFailure "Try again later.",
64        3 ReadWriteDenied "The association's access rights forbid this.",
65        4 ObjectUndefined "No object with that logical name and class.",
66        9 ObjectClassInconsistent "The class id does not match the object with that name.",
67        11 ObjectUnavailable "The object exists but is not accessible now.",
68        12 TypeUnmatched "The value's type is not the attribute's type.",
69        13 ScopeOfAccessViolated "Outside the range this association may address.",
70        14 DataBlockUnavailable "The requested block is gone.",
71        15 LongGetAborted "The block transfer was abandoned.",
72        16 NoLongGetInProgress "There is no block transfer to continue.",
73        17 LongSetAborted "The block transfer was abandoned.",
74        18 NoLongSetInProgress "There is no block transfer to continue.",
75        19 DataBlockNumberInvalid "The block number is not the expected one.",
76        250 OtherReason "Unspecified.",
77    }
78}
79
80result_enum! {
81    /// Why a method invocation did not succeed.
82    ActionResult {
83        0 Success "The method ran.",
84        1 HardwareFault "The meter's hardware could not serve the request.",
85        2 TemporaryFailure "Try again later.",
86        3 ReadWriteDenied "The association's access rights forbid this.",
87        4 ObjectUndefined "No object with that logical name and class.",
88        9 ObjectClassInconsistent "The class id does not match the object with that name.",
89        11 ObjectUnavailable "The object exists but is not accessible now.",
90        12 TypeUnmatched "The parameter's type is not the method's type.",
91        13 ScopeOfAccessViolated "Outside the range this association may address.",
92        14 DataBlockUnavailable "The requested block is gone.",
93        15 LongActionAborted "The block transfer was abandoned.",
94        16 NoLongActionInProgress "There is no block transfer to continue.",
95        250 OtherReason "Unspecified.",
96    }
97}
98
99/// A value, or the reason there is none.
100#[derive(Debug, Clone, Copy, PartialEq)]
101pub enum GetDataResult<'a> {
102    /// The value.
103    Data(Data<'a>),
104    /// Why there is none.
105    Error(DataAccessResult),
106}
107
108impl<'a> GetDataResult<'a> {
109    /// The value, turning an error result into an `Err`.
110    ///
111    /// # Errors
112    /// Returns the [`DataAccessResult`] when the server refused.
113    pub const fn value(self) -> core::result::Result<Data<'a>, DataAccessResult> {
114        match self {
115            Self::Data(d) => Ok(d),
116            Self::Error(e) => Err(e),
117        }
118    }
119}
120
121impl Encode for GetDataResult<'_> {
122    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
123        match self {
124            Self::Data(d) => {
125                w.write_u8(0)?;
126                d.encode(w)
127            }
128            Self::Error(e) => {
129                w.write_u8(1)?;
130                w.write_u8(e.as_u8())
131            }
132        }
133    }
134}
135
136impl<'a> Decode<'a> for GetDataResult<'a> {
137    fn decode(r: &mut Reader<'a>) -> Result<Self> {
138        match r.u8()? {
139            0 => Ok(Self::Data(Data::decode(r)?)),
140            1 => Ok(Self::Error(DataAccessResult::from_u8(r.u8()?))),
141            other => Err(r.err_back(ErrorKind::InvalidTag(other), 1)),
142        }
143    }
144}
145
146/// A block of a long GET response.
147#[derive(Debug, Clone, Copy, PartialEq)]
148pub struct DataBlockG<'a> {
149    /// True when this is the last block.
150    pub last_block: bool,
151    /// The block number, counting from one.
152    pub block_number: u32,
153    /// The block's payload, or why there is none.
154    pub result: core::result::Result<&'a [u8], DataAccessResult>,
155}
156
157impl Encode for DataBlockG<'_> {
158    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
159        w.write_u8(u8::from(self.last_block))?;
160        w.write_u32(self.block_number)?;
161        match self.result {
162            Ok(raw) => {
163                w.write_u8(0)?;
164                w.write_length_prefixed(raw)
165            }
166            Err(e) => {
167                w.write_u8(1)?;
168                w.write_u8(e.as_u8())
169            }
170        }
171    }
172}
173
174impl<'a> Decode<'a> for DataBlockG<'a> {
175    fn decode(r: &mut Reader<'a>) -> Result<Self> {
176        let last_block = r.u8()? != 0;
177        let block_number = r.u32()?;
178        let result = match r.u8()? {
179            0 => Ok(r.length_prefixed()?),
180            1 => Err(DataAccessResult::from_u8(r.u8()?)),
181            other => return Err(r.err_back(ErrorKind::InvalidTag(other), 1)),
182        };
183        Ok(Self { last_block, block_number, result })
184    }
185}
186
187/// A block of a long SET request or an ACTION parameter.
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub struct DataBlockSA<'a> {
190    /// True when this is the last block.
191    pub last_block: bool,
192    /// The block number, counting from one.
193    pub block_number: u32,
194    /// The block's payload.
195    pub raw_data: &'a [u8],
196}
197
198impl Encode for DataBlockSA<'_> {
199    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
200        w.write_u8(u8::from(self.last_block))?;
201        w.write_u32(self.block_number)?;
202        w.write_length_prefixed(self.raw_data)
203    }
204}
205
206impl<'a> Decode<'a> for DataBlockSA<'a> {
207    fn decode(r: &mut Reader<'a>) -> Result<Self> {
208        Ok(Self { last_block: r.u8()? != 0, block_number: r.u32()?, raw_data: r.length_prefixed()? })
209    }
210}
211
212/// A sequence of values with an A-XDR count in front, kept borrowed.
213///
214/// The elements are validated when the list is decoded and re-parsed when iterated,
215/// which is the same trade [`crate::axdr::Seq`] makes and for the same reason.
216#[derive(Debug, Clone, Copy)]
217pub struct List<'a, T> {
218    count: usize,
219    raw: &'a [u8],
220    /// Where these bytes started in the frame. Diagnostic only — it is what makes an
221    /// error inside an element point at the right byte of the whole APDU.
222    base: usize,
223    _marker: core::marker::PhantomData<fn() -> T>,
224}
225
226/// Two lists are equal when they hold the same elements.
227///
228/// Written by hand for the same reason [`crate::axdr::Seq`]'s is: `base` says where the
229/// bytes came from, not what they say, and deriving over it made an otherwise identical
230/// `get-response-with-list` compare unequal to itself after a round trip.
231impl<T> PartialEq for List<'_, T> {
232    fn eq(&self, other: &Self) -> bool {
233        self.count == other.count && self.raw == other.raw
234    }
235}
236
237impl<T> Eq for List<'_, T> {}
238
239impl<'a, T: Decode<'a>> List<'a, T> {
240    /// How many elements.
241    #[must_use]
242    pub const fn len(&self) -> usize {
243        self.count
244    }
245
246    /// True when empty.
247    #[must_use]
248    pub const fn is_empty(&self) -> bool {
249        self.count == 0
250    }
251
252    /// The encoded elements.
253    #[must_use]
254    pub const fn as_bytes(&self) -> &'a [u8] {
255        self.raw
256    }
257
258    /// Iterate the elements.
259    pub fn iter(&self) -> impl Iterator<Item = Result<T>> + 'a {
260        let mut r = Reader::with_base(self.raw, self.base);
261        let mut left = self.count;
262        core::iter::from_fn(move || {
263            if left == 0 {
264                return None;
265            }
266            left -= 1;
267            Some(T::decode(&mut r))
268        })
269    }
270
271    /// Build a list from elements already encoded elsewhere.
272    #[must_use]
273    pub const fn from_raw(count: usize, raw: &'a [u8]) -> Self {
274        Self { count, raw, base: 0, _marker: core::marker::PhantomData }
275    }
276}
277
278impl<'a, T: Decode<'a>> Decode<'a> for List<'a, T> {
279    fn decode(r: &mut Reader<'a>) -> Result<Self> {
280        let count = r.length()?;
281        let base = r.offset();
282        let mut probe = Reader::with_base(r.rest(), base);
283        for _ in 0..count {
284            T::decode(&mut probe)?;
285        }
286        let raw = r.take(probe.consumed())?;
287        Ok(Self { count, raw, base, _marker: core::marker::PhantomData })
288    }
289}
290
291impl<T> Encode for List<'_, T> {
292    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
293        w.write_length(self.count)?;
294        w.write_bytes(self.raw)
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use crate::codec::SliceWriter;
302
303    #[test]
304    fn results_round_trip_including_unnamed_codes() {
305        for v in 0u8..=255 {
306            assert_eq!(DataAccessResult::from_u8(v).as_u8(), v);
307            assert_eq!(ActionResult::from_u8(v).as_u8(), v);
308        }
309        assert_eq!(DataAccessResult::from_u8(200), DataAccessResult::Other(200));
310    }
311
312    #[test]
313    fn only_zero_is_success() {
314        assert!(DataAccessResult::Success.is_success());
315        assert!(!DataAccessResult::ReadWriteDenied.is_success());
316        assert!(DataAccessResult::Success.ok().is_ok());
317        assert_eq!(DataAccessResult::ObjectUndefined.ok().unwrap_err(), DataAccessResult::ObjectUndefined);
318    }
319
320    #[test]
321    fn get_data_result_discriminates_a_value_from_a_refusal() {
322        let mut buf = [0u8; 32];
323        let mut w = SliceWriter::new(&mut buf);
324        GetDataResult::Error(DataAccessResult::ReadWriteDenied).encode(&mut w).unwrap();
325        assert_eq!(w.as_slice(), [1, 3]);
326        let decoded = GetDataResult::from_bytes(&[1, 3]).unwrap();
327        assert_eq!(decoded, GetDataResult::Error(DataAccessResult::ReadWriteDenied));
328        assert!(decoded.value().is_err());
329    }
330
331    #[test]
332    fn a_data_block_carries_its_number_and_last_flag() {
333        let b = DataBlockG { last_block: false, block_number: 2, result: Ok(&[0xAA, 0xBB]) };
334        let mut buf = [0u8; 32];
335        let mut w = SliceWriter::new(&mut buf);
336        b.encode(&mut w).unwrap();
337        assert_eq!(w.as_slice(), [0, 0, 0, 0, 2, 0, 2, 0xAA, 0xBB]);
338        assert_eq!(DataBlockG::from_bytes(w.as_slice()).unwrap(), b);
339    }
340
341    #[test]
342    fn a_list_validates_every_element_before_it_is_iterated() {
343        // Two attribute descriptors, count-prefixed.
344        let raw = [
345            2u8, //
346            0x00, 0x03, 1, 0, 1, 8, 0, 255, 2, 0, //
347            0x00, 0x08, 0, 0, 1, 0, 0, 255, 2, 0,
348        ];
349        let list: List<'_, super::super::AttributeDescriptorWithSelection<'_>> =
350            List::from_bytes(&raw).unwrap();
351        assert_eq!(list.len(), 2);
352        let items: alloc::vec::Vec<_> = list.iter().map(|d| d.unwrap().descriptor.class_id).collect();
353        assert_eq!(items, [3, 8]);
354    }
355
356    #[test]
357    fn a_list_whose_elements_do_not_parse_fails_at_decode() {
358        let raw = [2u8, 0x00, 0x03, 1, 0, 1, 8, 0, 255, 2, 0];
359        let e = List::<'_, super::super::AttributeDescriptorWithSelection<'_>>::from_bytes(&raw).unwrap_err();
360        assert!(e.is_truncated());
361    }
362}