microrti-encoding 0.2.2

HLA 4 data encoding of IEEE 1516.2-2025: basic types, strings, handles, arrays, records, variant records and a FOM-driven codec.
Documentation
//! Errors of the FOM-driven codec.

use std::fmt;

use microrti_core::{ExceptionKind, RtiError};

use crate::error::{DecoderError, EncoderError};

/// Why a value could not be encoded or decoded.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Reason {
    /// The octets are not a complete, well-formed encoding: truncated input, an impossible element
    /// count, octets left after the value, an alternative that does not fill its announced length.
    #[error(transparent)]
    Decoder(#[from] DecoderError),
    /// The value exceeds a limit of the encoding itself: element count or alternative length.
    #[error(transparent)]
    Encoder(#[from] EncoderError),
    /// The value does not have the shape the data type needs (encoding).
    #[error("expected {expected}, found {found}")]
    TypeMismatch {
        /// What the data type needs.
        expected: String,
        /// Kind of the value that was given.
        found: String,
    },
    /// A number, a character or an element count is outside the range of the data type (encoding).
    #[error("{detail}")]
    OutOfRange {
        /// Human readable explanation.
        detail: String,
    },
    /// A name or a number is not an enumerator of the enumerated data type (encoding).
    #[error("{detail}")]
    UnknownEnumerator {
        /// Human readable explanation.
        detail: String,
    },
    /// The discriminant of a variant record selects no alternative, or the value does not match the
    /// alternative it selects.
    #[error("{detail}")]
    Alternative {
        /// Human readable explanation.
        detail: String,
    },
    /// A record value lacks a field, repeats one or has one the data type does not define (encoding).
    #[error("{detail}")]
    Field {
        /// Human readable explanation.
        detail: String,
    },
    /// The octets do not form a legal value of the data type (decoding).
    #[error("{detail}")]
    InvalidValue {
        /// Human readable explanation.
        detail: String,
    },
}

/// Where and why encoding or decoding a value failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
    /// The attribute or parameter, when the codec was called with a handle: `attribute
    /// HLAobjectRoot.HLAmanager.HLAfederate.HLAfederateName`.
    pub member: Option<String>,
    /// The place inside the value, starting with the name of the data type:
    /// `HLAinteractionSubList[3].HLAinteractionClass`.
    pub path: String,
    /// Offset from the start of the value, in octets: where decoding stopped, or how many octets had
    /// been written when encoding stopped. While encoding the alternative of an
    /// `HLAextendableVariantRecord` the offset counts from the start of that alternative.
    pub offset: usize,
    /// What went wrong.
    pub reason: Reason,
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(member) = &self.member {
            write!(f, "{member}: ")?;
        }
        write!(f, "{} at offset {}: {}", self.path, self.offset, self.reason)
    }
}

/// Errors of [`FomCodec`](super::FomCodec).
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CodecError {
    /// A data type of the FDD contains itself. `cycle` lists the names: `Node -> NodeList -> Node`.
    #[error("recursive data type definition: {cycle}")]
    RecursiveDataType {
        /// The data types of the cycle, joined by ` -> `; the first name is repeated at the end.
        cycle: String,
    },
    /// Data types nest deeper than the codec accepts.
    #[error("the data type '{data_type}' nests data types deeper than {limit} levels")]
    NestingTooDeep {
        /// The data type at which the limit was exceeded.
        data_type: String,
        /// The limit.
        limit: usize,
    },
    /// The FDD has no data type of this name.
    #[error("the FDD has no data type '{name}'")]
    UnknownDataType {
        /// The name that was looked up.
        name: String,
    },
    /// A handle is outside the tables of the FDD the codec was built from.
    #[error("the FDD has no {kind} with the handle {handle}")]
    UnknownHandle {
        /// `attribute`, `parameter`, `object class` or `interaction class`.
        kind: &'static str,
        /// The handle value.
        handle: u32,
    },
    /// A name or handle is not an available attribute (parameter) of the class.
    #[error("'{member}' is not {kind} of the class {class}")]
    NotAMember {
        /// `an attribute` or `a parameter`.
        kind: &'static str,
        /// Fully qualified class name.
        class: String,
        /// The name that was looked up.
        member: String,
    },
    /// A value cannot be encoded as its data type.
    #[error("cannot encode {0}")]
    Encode(Box<Failure>),
    /// Octets cannot be decoded as the data type.
    #[error("cannot decode {0}")]
    Decode(Box<Failure>),
}

impl CodecError {
    /// The place and reason of an [`CodecError::Encode`] or [`CodecError::Decode`] error.
    pub fn failure(&self) -> Option<&Failure> {
        match self {
            CodecError::Encode(failure) | CodecError::Decode(failure) => Some(failure),
            _ => None,
        }
    }

    /// The place inside the value: `HLAinteractionSubList[3].HLAinteractionClass`.
    pub fn path(&self) -> Option<&str> {
        self.failure().map(|failure| failure.path.as_str())
    }

    /// Offset in octets from the start of the value.
    pub fn offset(&self) -> Option<usize> {
        self.failure().map(|failure| failure.offset)
    }

    /// What went wrong inside the value.
    pub fn reason(&self) -> Option<&Reason> {
        self.failure().map(|failure| &failure.reason)
    }

    /// Names the attribute or parameter the failing value belongs to.
    pub(crate) fn with_member(mut self, member: impl FnOnce() -> String) -> Self {
        if let CodecError::Encode(failure) | CodecError::Decode(failure) = &mut self {
            failure.member = Some(member());
        }
        self
    }
}

/// `CouldNotEncode` and `CouldNotDecode` for values, `InconsistentFOM` for data type tables the codec
/// rejects, `RTIinternalError` for names and handles the FDD does not have.
impl From<CodecError> for RtiError {
    fn from(error: CodecError) -> Self {
        let kind = match &error {
            CodecError::Encode(_) => ExceptionKind::CouldNotEncode,
            CodecError::Decode(_) => ExceptionKind::CouldNotDecode,
            CodecError::RecursiveDataType { .. } | CodecError::NestingTooDeep { .. } => {
                ExceptionKind::InconsistentFOM
            }
            CodecError::UnknownDataType { .. }
            | CodecError::UnknownHandle { .. }
            | CodecError::NotAMember { .. } => ExceptionKind::RTIinternalError,
        };
        RtiError::new(kind, error.to_string())
    }
}

/// A failure on its way out of the value: the path is collected innermost segment first.
#[derive(Debug)]
pub(crate) struct Fail {
    segments: Vec<String>,
    offset: usize,
    reason: Reason,
}

impl Fail {
    pub(crate) fn new(offset: usize, reason: Reason) -> Self {
        Self { segments: Vec::new(), offset, reason }
    }

    /// A failure of the byte reader. `at` is where the read started; a truncation knows better.
    pub(crate) fn decoder(at: usize, error: DecoderError) -> Self {
        let offset = match &error {
            DecoderError::Truncated { offset, .. } => *offset,
            _ => at,
        };
        Self::new(offset, Reason::Decoder(error))
    }

    /// Adds the path segment of the enclosing element: `[3]` or `.Field`.
    pub(crate) fn inside(mut self, segment: String) -> Self {
        self.segments.push(segment);
        self
    }

    /// The public form, with the path rooted at the data type name.
    pub(crate) fn into_failure(self, root: &str) -> Box<Failure> {
        let mut path = root.to_owned();
        for segment in self.segments.iter().rev() {
            path.push_str(segment);
        }
        Box::new(Failure { member: None, path, offset: self.offset, reason: self.reason })
    }
}