Skip to main content

microrti_encoding/
time.rs

1//! Logical time elements (12.3, 12.4): a time or interval travels inside attribute and parameter values as
2//! the MIM array datatypes `HLAlogicalTime` and `HLAtimeInterval`, `HLAvariableArray`s of `HLAbyte`
3//! holding the encoded form of the value.
4//!
5//! The encoded form does not say which time representation it uses, so the elements keep the octets and
6//! the caller names the representation of its federation execution when it wants the value.
7
8use microrti_core::{LogicalTime, LogicalTimeInterval, TimeKind};
9
10use crate::error::DecoderError;
11use crate::strings::octet_array_element;
12
13/// Encoded size of both standardized time representations.
14const TIME_SIZE: usize = 8;
15
16fn check_size(type_name: &'static str, octets: &[u8]) -> Result<(), DecoderError> {
17    if octets.len() == TIME_SIZE {
18        Ok(())
19    } else {
20        Err(DecoderError::CountMismatch { type_name, expected: TIME_SIZE, found: octets.len() })
21    }
22}
23
24octet_array_element! {
25    /// `HLAlogicalTime`: the encoded form of a logical time.
26    HLAlogicalTime
27}
28
29impl HLAlogicalTime {
30    /// The element carrying `time`.
31    pub fn from_time(time: LogicalTime) -> Self {
32        Self(time.encode().to_vec())
33    }
34
35    /// Interprets the octets as a time of the given representation.
36    pub fn time(&self, kind: TimeKind) -> Result<LogicalTime, DecoderError> {
37        check_size("HLAlogicalTime", &self.0)?;
38        kind.decode_time(&self.0).map_err(|error| DecoderError::InvalidValue {
39            type_name: "HLAlogicalTime",
40            detail: error.message,
41        })
42    }
43}
44
45impl From<LogicalTime> for HLAlogicalTime {
46    fn from(time: LogicalTime) -> Self {
47        Self::from_time(time)
48    }
49}
50
51octet_array_element! {
52    /// `HLAlogicalTimeInterval` (MIM datatype `HLAtimeInterval`): the encoded form of a time interval.
53    HLAlogicalTimeInterval
54}
55
56impl HLAlogicalTimeInterval {
57    /// The element carrying `interval`.
58    pub fn from_interval(interval: LogicalTimeInterval) -> Self {
59        Self(interval.encode().to_vec())
60    }
61
62    /// Interprets the octets as an interval of the given representation.
63    pub fn interval(&self, kind: TimeKind) -> Result<LogicalTimeInterval, DecoderError> {
64        check_size("HLAlogicalTimeInterval", &self.0)?;
65        kind.decode_interval(&self.0).map_err(|error| DecoderError::InvalidValue {
66            type_name: "HLAlogicalTimeInterval",
67            detail: error.message,
68        })
69    }
70}
71
72impl From<LogicalTimeInterval> for HLAlogicalTimeInterval {
73    fn from(interval: LogicalTimeInterval) -> Self {
74        Self::from_interval(interval)
75    }
76}