Skip to main content

temporal_control/dispatch/
network.rs

1//! Ground-side container for a dispatchable network.
2
3use alloc::vec;
4use alloc::vec::Vec;
5
6use super::encoding::{self, DecodeError, EncodeError, Encoded};
7use super::source::{self, Source};
8use super::{DispatchEdge, DispatchError, Dispatcher, Index, PointKind, Wait};
9
10/// A dispatchable network produced on the ground, ready to load into a [`Dispatcher`].
11///
12/// Produced by [`Stn::dispatchable`](crate::Stn::dispatchable) and
13/// [`Stnu::dispatchable`](crate::Stnu::dispatchable). Point indices match the source network.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct DispatchableNetwork {
16    /// Kind of every time point, indexed by [`TimePoint`](crate::TimePoint).
17    points: Vec<PointKind>,
18    /// Edges the dispatcher propagates along.
19    edges: Vec<DispatchEdge>,
20    /// Waits of executable points on contingent points. Empty for STNs.
21    waits: Vec<Wait>,
22}
23
24impl DispatchableNetwork {
25    /// Bundles the parts of a dispatchable network.
26    pub(crate) fn new(points: Vec<PointKind>, edges: Vec<DispatchEdge>, waits: Vec<Wait>) -> Self {
27        Self {
28            points,
29            edges,
30            waits,
31        }
32    }
33
34    /// Kind of every time point.
35    #[must_use]
36    pub fn points(&self) -> &[PointKind] {
37        &self.points
38    }
39
40    /// Dispatchable edges.
41    #[must_use]
42    pub fn edges(&self) -> &[DispatchEdge] {
43        &self.edges
44    }
45
46    /// Waits on contingent points.
47    #[must_use]
48    pub fn waits(&self) -> &[Wait] {
49        &self.waits
50    }
51
52    /// Adjacency entries a [`Dispatcher`] needs: two per edge plus one per wait.
53    #[must_use]
54    pub fn entry_count(&self) -> usize {
55        2 * self.edges.len() + self.waits.len()
56    }
57
58    /// Loads this network into a new fixed-capacity dispatcher.
59    ///
60    /// The index type `I` is usually inferred from the annotated result type, e.g.
61    /// `let d: Dispatcher<8, 64> = net.dispatcher()?` (with the default `usize`) or
62    /// `Dispatcher<8, 64, u16>`. To load into an existing dispatcher in place, use
63    /// [`Dispatcher::load`] with [`Self::points`], [`Self::edges`] and [`Self::waits`].
64    ///
65    /// # Errors
66    ///
67    /// As for [`Dispatcher::load`].
68    pub fn dispatcher<const N: usize, const E: usize, I: Index>(
69        &self,
70    ) -> Result<Dispatcher<N, E, I>, DispatchError> {
71        Dispatcher::new(&self.points, &self.edges, &self.waits)
72    }
73
74    /// Encodes this network in the compact checksummed format of [`encoding`].
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// use temporal_control::{Budget, Dispatcher, DispatchableNetwork, Stn, Ticks, Verdict};
80    ///
81    /// let mut stn = Stn::new();
82    /// let a = stn.add_time_point().expect("fits");
83    /// let b = stn.add_time_point().expect("fits");
84    /// stn.add_constraint(a, b, Some(Ticks(5)), Some(Ticks(15))).expect("exists");
85    /// let Verdict::Consistent(net) = stn.dispatchable(&Budget::UNLIMITED).expect("fits") else {
86    ///     panic!("consistent");
87    /// };
88    ///
89    /// let bytes = net.encode().expect("small");
90    /// assert_eq!(DispatchableNetwork::decode(&bytes), Ok(net));
91    ///
92    /// let mut d = Dispatcher::<2, 8>::EMPTY;
93    /// d.load_encoded(&bytes).expect("valid");
94    /// ```
95    ///
96    /// # Errors
97    ///
98    /// [`EncodeError::TooLarge`] if a count or index exceeds `u32::MAX`.
99    pub fn encode(&self) -> Result<Vec<u8>, EncodeError> {
100        let len = encoding::encoded_len(self.points.len(), self.edges.len(), self.waits.len())
101            .ok_or(EncodeError::TooLarge)?;
102        let mut out = vec![0; len];
103        encoding::encode_into(&self.points, &self.edges, &self.waits, &mut out)?;
104        Ok(out)
105    }
106
107    /// Decodes and validates an encoding, for ground-side checks of what will be uplinked.
108    ///
109    /// Accepts exactly the encodings that a dispatcher of unlimited capacity with `usize`
110    /// indices accepts.
111    ///
112    /// # Errors
113    ///
114    /// As for [`Dispatcher::load_encoded`], except that capacities never apply.
115    pub fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
116        let encoded = Encoded::parse(bytes)?;
117        source::validate::<usize>(&encoded, usize::MAX, usize::MAX)
118            .map_err(DecodeError::Network)?;
119
120        let invalid = DecodeError::Network(DispatchError::InvalidNetwork);
121        let points = (0..encoded.point_count()).map(|i| encoded.point(i));
122        let edges = (0..encoded.edge_count()).map(|i| encoded.edge(i));
123        let waits = (0..encoded.wait_count()).map(|i| encoded.wait(i));
124
125        Ok(Self::new(
126            points.collect::<Option<_>>().ok_or(invalid)?,
127            edges.collect::<Option<_>>().ok_or(invalid)?,
128            waits.collect::<Option<_>>().ok_or(invalid)?,
129        ))
130    }
131}