Skip to main content

microrti_encoding/fom/
error.rs

1//! Errors of the FOM-driven codec.
2
3use std::fmt;
4
5use microrti_core::{ExceptionKind, RtiError};
6
7use crate::error::{DecoderError, EncoderError};
8
9/// Why a value could not be encoded or decoded.
10#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
11#[non_exhaustive]
12pub enum Reason {
13    /// The octets are not a complete, well-formed encoding: truncated input, an impossible element
14    /// count, octets left after the value, an alternative that does not fill its announced length.
15    #[error(transparent)]
16    Decoder(#[from] DecoderError),
17    /// The value exceeds a limit of the encoding itself: element count or alternative length.
18    #[error(transparent)]
19    Encoder(#[from] EncoderError),
20    /// The value does not have the shape the data type needs (encoding).
21    #[error("expected {expected}, found {found}")]
22    TypeMismatch {
23        /// What the data type needs.
24        expected: String,
25        /// Kind of the value that was given.
26        found: String,
27    },
28    /// A number, a character or an element count is outside the range of the data type (encoding).
29    #[error("{detail}")]
30    OutOfRange {
31        /// Human readable explanation.
32        detail: String,
33    },
34    /// A name or a number is not an enumerator of the enumerated data type (encoding).
35    #[error("{detail}")]
36    UnknownEnumerator {
37        /// Human readable explanation.
38        detail: String,
39    },
40    /// The discriminant of a variant record selects no alternative, or the value does not match the
41    /// alternative it selects.
42    #[error("{detail}")]
43    Alternative {
44        /// Human readable explanation.
45        detail: String,
46    },
47    /// A record value lacks a field, repeats one or has one the data type does not define (encoding).
48    #[error("{detail}")]
49    Field {
50        /// Human readable explanation.
51        detail: String,
52    },
53    /// The octets do not form a legal value of the data type (decoding).
54    #[error("{detail}")]
55    InvalidValue {
56        /// Human readable explanation.
57        detail: String,
58    },
59}
60
61/// Where and why encoding or decoding a value failed.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct Failure {
64    /// The attribute or parameter, when the codec was called with a handle: `attribute
65    /// HLAobjectRoot.HLAmanager.HLAfederate.HLAfederateName`.
66    pub member: Option<String>,
67    /// The place inside the value, starting with the name of the data type:
68    /// `HLAinteractionSubList[3].HLAinteractionClass`.
69    pub path: String,
70    /// Offset from the start of the value, in octets: where decoding stopped, or how many octets had
71    /// been written when encoding stopped. While encoding the alternative of an
72    /// `HLAextendableVariantRecord` the offset counts from the start of that alternative.
73    pub offset: usize,
74    /// What went wrong.
75    pub reason: Reason,
76}
77
78impl fmt::Display for Failure {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        if let Some(member) = &self.member {
81            write!(f, "{member}: ")?;
82        }
83        write!(f, "{} at offset {}: {}", self.path, self.offset, self.reason)
84    }
85}
86
87/// Errors of [`FomCodec`](super::FomCodec).
88#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
89#[non_exhaustive]
90pub enum CodecError {
91    /// A data type of the FDD contains itself. `cycle` lists the names: `Node -> NodeList -> Node`.
92    #[error("recursive data type definition: {cycle}")]
93    RecursiveDataType {
94        /// The data types of the cycle, joined by ` -> `; the first name is repeated at the end.
95        cycle: String,
96    },
97    /// Data types nest deeper than the codec accepts.
98    #[error("the data type '{data_type}' nests data types deeper than {limit} levels")]
99    NestingTooDeep {
100        /// The data type at which the limit was exceeded.
101        data_type: String,
102        /// The limit.
103        limit: usize,
104    },
105    /// The FDD has no data type of this name.
106    #[error("the FDD has no data type '{name}'")]
107    UnknownDataType {
108        /// The name that was looked up.
109        name: String,
110    },
111    /// A handle is outside the tables of the FDD the codec was built from.
112    #[error("the FDD has no {kind} with the handle {handle}")]
113    UnknownHandle {
114        /// `attribute`, `parameter`, `object class` or `interaction class`.
115        kind: &'static str,
116        /// The handle value.
117        handle: u32,
118    },
119    /// A name or handle is not an available attribute (parameter) of the class.
120    #[error("'{member}' is not {kind} of the class {class}")]
121    NotAMember {
122        /// `an attribute` or `a parameter`.
123        kind: &'static str,
124        /// Fully qualified class name.
125        class: String,
126        /// The name that was looked up.
127        member: String,
128    },
129    /// A value cannot be encoded as its data type.
130    #[error("cannot encode {0}")]
131    Encode(Box<Failure>),
132    /// Octets cannot be decoded as the data type.
133    #[error("cannot decode {0}")]
134    Decode(Box<Failure>),
135}
136
137impl CodecError {
138    /// The place and reason of an [`CodecError::Encode`] or [`CodecError::Decode`] error.
139    pub fn failure(&self) -> Option<&Failure> {
140        match self {
141            CodecError::Encode(failure) | CodecError::Decode(failure) => Some(failure),
142            _ => None,
143        }
144    }
145
146    /// The place inside the value: `HLAinteractionSubList[3].HLAinteractionClass`.
147    pub fn path(&self) -> Option<&str> {
148        self.failure().map(|failure| failure.path.as_str())
149    }
150
151    /// Offset in octets from the start of the value.
152    pub fn offset(&self) -> Option<usize> {
153        self.failure().map(|failure| failure.offset)
154    }
155
156    /// What went wrong inside the value.
157    pub fn reason(&self) -> Option<&Reason> {
158        self.failure().map(|failure| &failure.reason)
159    }
160
161    /// Names the attribute or parameter the failing value belongs to.
162    pub(crate) fn with_member(mut self, member: impl FnOnce() -> String) -> Self {
163        if let CodecError::Encode(failure) | CodecError::Decode(failure) = &mut self {
164            failure.member = Some(member());
165        }
166        self
167    }
168}
169
170/// `CouldNotEncode` and `CouldNotDecode` for values, `InconsistentFOM` for data type tables the codec
171/// rejects, `RTIinternalError` for names and handles the FDD does not have.
172impl From<CodecError> for RtiError {
173    fn from(error: CodecError) -> Self {
174        let kind = match &error {
175            CodecError::Encode(_) => ExceptionKind::CouldNotEncode,
176            CodecError::Decode(_) => ExceptionKind::CouldNotDecode,
177            CodecError::RecursiveDataType { .. } | CodecError::NestingTooDeep { .. } => {
178                ExceptionKind::InconsistentFOM
179            }
180            CodecError::UnknownDataType { .. }
181            | CodecError::UnknownHandle { .. }
182            | CodecError::NotAMember { .. } => ExceptionKind::RTIinternalError,
183        };
184        RtiError::new(kind, error.to_string())
185    }
186}
187
188/// A failure on its way out of the value: the path is collected innermost segment first.
189#[derive(Debug)]
190pub(crate) struct Fail {
191    segments: Vec<String>,
192    offset: usize,
193    reason: Reason,
194}
195
196impl Fail {
197    pub(crate) fn new(offset: usize, reason: Reason) -> Self {
198        Self { segments: Vec::new(), offset, reason }
199    }
200
201    /// A failure of the byte reader. `at` is where the read started; a truncation knows better.
202    pub(crate) fn decoder(at: usize, error: DecoderError) -> Self {
203        let offset = match &error {
204            DecoderError::Truncated { offset, .. } => *offset,
205            _ => at,
206        };
207        Self::new(offset, Reason::Decoder(error))
208    }
209
210    /// Adds the path segment of the enclosing element: `[3]` or `.Field`.
211    pub(crate) fn inside(mut self, segment: String) -> Self {
212        self.segments.push(segment);
213        self
214    }
215
216    /// The public form, with the path rooted at the data type name.
217    pub(crate) fn into_failure(self, root: &str) -> Box<Failure> {
218        let mut path = root.to_owned();
219        for segment in self.segments.iter().rev() {
220            path.push_str(segment);
221        }
222        Box::new(Failure { member: None, path, offset: self.offset, reason: self.reason })
223    }
224}