temporal_control/dispatch/encoding.rs
1//! Compact, checksummed binary encoding of a dispatchable network.
2//!
3//! The ground side encodes a network once ([`encode_into`], or
4//! [`DispatchableNetwork::encode`](crate::DispatchableNetwork::encode) with `alloc`); the
5//! onboard side validates and loads it with
6//! [`Dispatcher::load_encoded`](super::Dispatcher::load_encoded), which reads the records
7//! directly from the received bytes, needs no `alloc` and never panics.
8//!
9//! # Format, version 1
10//!
11//! All integers are little-endian and fixed-width; there is no padding or alignment.
12//!
13//! | Offset | Size | Field |
14//! | --- | --- | --- |
15//! | 0 | 4 | magic `TCDN` (`54 43 44 4E`) |
16//! | 4 | 2 | format version, `u16`, currently [`VERSION`] = 1 |
17//! | 6 | 2 | reserved, `u16`, must be 0 |
18//! | 8 | 4 | point count `n`, `u32` |
19//! | 12 | 4 | edge count `e`, `u32` |
20//! | 16 | 4 | wait count `w`, `u32` |
21//! | 20 | `21 n` | point records |
22//! | `20 + 21 n` | `16 e` | edge records |
23//! | `20 + 21 n + 16 e` | `16 w` | wait records |
24//! | end - 4 | 4 | CRC-32/ISO-HDLC ([`crc32()`]) of every byte before it, `u32` |
25//!
26//! Records (point indices are `u32`, ticks `i64`):
27//!
28//! - point: tag `u8` (0 executable, 1 contingent), activation `u32`, `lo` `i64`, `hi` `i64`;
29//! an executable point has all 20 bytes after the tag zero;
30//! - edge `t_to - t_from <= weight`: `from` `u32`, `to` `u32`, `weight` `i64`;
31//! - wait: `waiter` `u32`, `contingent` `u32`, `delay` `i64`.
32//!
33//! Fixed-width records give random access to record `i`, which the validator needs to
34//! follow activation chains without copying the network. The total length is
35//! `24 + 21 n + 16 (e + w)` bytes and must match the buffer exactly.
36//!
37//! # Decoding
38//!
39//! Checks, in order, each with its own [`DecodeError`]: at least a header and a checksum
40//! ([`DecodeError::Truncated`]), magic, version, exact length from the counts, the CRC, the
41//! reserved field and point tags (canonical form), then everything
42//! [`Dispatcher::load`](super::Dispatcher::load) checks (indices, contingent bounds,
43//! activation chains, waits, capacities, index type). A decoder for a later version is
44//! expected to reject version 1 encodings it cannot read explicitly, never by checksum
45//! failure: the magic and version come first so that the checksum location may change.
46//!
47//! # Examples
48//!
49//! ```
50//! use temporal_control::dispatch::encoding::{self, encoded_len};
51//! use temporal_control::{DispatchEdge, Dispatcher, PointKind, Ticks, TimePoint};
52//!
53//! let points = [PointKind::Executable; 2];
54//! let edges = [DispatchEdge { from: TimePoint(0), to: TimePoint(1), weight: Ticks(10) }];
55//! let mut buf = [0u8; 128];
56//! let len = encoding::encode_into(&points, &edges, &[], &mut buf).expect("fits");
57//! assert_eq!(Some(len), encoded_len(2, 1, 0));
58//!
59//! let mut d = Dispatcher::<2, 2>::EMPTY;
60//! d.load_encoded(&buf[..len]).expect("valid");
61//! ```
62
63mod crc32;
64
65use core::fmt;
66
67use super::source::Source;
68use super::{DispatchEdge, DispatchError, PointKind, Wait};
69use crate::{Ticks, TimePoint};
70
71pub use crc32::crc32;
72
73/// First four bytes of every encoding.
74pub const MAGIC: [u8; 4] = *b"TCDN";
75
76/// Format version written by [`encode_into`] and accepted by the decoder.
77pub const VERSION: u16 = 1;
78
79/// Length of the fixed header in bytes.
80const HEADER_LEN: usize = 20;
81
82/// Length of the trailing checksum in bytes.
83const CRC_LEN: usize = 4;
84
85/// Length of a point record in bytes.
86const POINT_LEN: usize = 21;
87
88/// Length of an edge or wait record in bytes.
89const PAIR_LEN: usize = 16;
90
91/// Point record tag of an executable point.
92const TAG_EXECUTABLE: u8 = 0;
93
94/// Point record tag of a contingent point.
95const TAG_CONTINGENT: u8 = 1;
96
97/// Reasons an encoding was rejected.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99#[non_exhaustive]
100pub enum DecodeError {
101 /// Shorter than a header plus a checksum.
102 Truncated,
103 /// The first four bytes are not [`MAGIC`].
104 BadMagic,
105 /// The version field is not [`VERSION`]; carries the version found.
106 UnsupportedVersion(u16),
107 /// The buffer length differs from the length the header's counts imply (truncated, or
108 /// trailing bytes).
109 LengthMismatch {
110 /// Length implied by the counts, in bytes.
111 expected: u64,
112 /// Length of the buffer, in bytes.
113 actual: usize,
114 },
115 /// The CRC-32 does not match the content.
116 ChecksumMismatch,
117 /// The reserved field is not zero, a point tag is unknown, or an executable point record
118 /// has non-zero payload bytes.
119 NonCanonical,
120 /// The records decode, but the network is rejected as by
121 /// [`Dispatcher::load`](super::Dispatcher::load).
122 Network(DispatchError),
123}
124
125impl fmt::Display for DecodeError {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 match self {
128 Self::Truncated => f.write_str("encoding shorter than header and checksum"),
129 Self::BadMagic => f.write_str("not a dispatchable network encoding (bad magic)"),
130 Self::UnsupportedVersion(v) => write!(f, "unsupported encoding version {v}"),
131 Self::LengthMismatch { expected, actual } => {
132 write!(f, "encoding is {actual} bytes, header implies {expected}")
133 }
134 Self::ChecksumMismatch => f.write_str("encoding checksum mismatch"),
135 Self::NonCanonical => f.write_str("encoding not in canonical form"),
136 Self::Network(e) => write!(f, "encoded network rejected: {e}"),
137 }
138 }
139}
140
141impl core::error::Error for DecodeError {
142 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
143 match self {
144 Self::Network(e) => Some(e),
145 _ => None,
146 }
147 }
148}
149
150/// Reasons a network could not be encoded.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152#[non_exhaustive]
153pub enum EncodeError {
154 /// The output buffer is shorter than the encoding.
155 BufferTooSmall {
156 /// Bytes the encoding needs.
157 needed: usize,
158 },
159 /// A count or a point index does not fit `u32`, or the length does not fit `usize`.
160 TooLarge,
161}
162
163impl fmt::Display for EncodeError {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 match self {
166 Self::BufferTooSmall { needed } => write!(f, "encoding needs {needed} bytes"),
167 Self::TooLarge => f.write_str("network too large for the encoding"),
168 }
169 }
170}
171
172impl core::error::Error for EncodeError {}
173
174/// Length in bytes of the encoding of a network with the given counts, or `None` if a count
175/// exceeds `u32::MAX` or the length overflows `usize`.
176#[must_use]
177pub fn encoded_len(points: usize, edges: usize, waits: usize) -> Option<usize> {
178 let counts = [points, edges, waits].map(|c| u32::try_from(c).ok());
179 let [Some(n), Some(e), Some(w)] = counts else {
180 return None;
181 };
182
183 usize::try_from(length_of(n, e, w)).ok()
184}
185
186/// Length of an encoding with these counts, computed in `u64` so it cannot overflow even
187/// where `usize` has 32 bits.
188fn length_of(points: u32, edges: u32, waits: u32) -> u64 {
189 let fixed = (HEADER_LEN + CRC_LEN) as u64;
190 let pairs = u64::from(edges) + u64::from(waits);
191
192 fixed + POINT_LEN as u64 * u64::from(points) + PAIR_LEN as u64 * pairs
193}
194
195/// Encodes a network into `out` and returns the number of bytes written.
196///
197/// The network is not validated here; the decoder validates it. Bytes of `out` after the
198/// returned length are left untouched.
199///
200/// # Errors
201///
202/// - [`EncodeError::TooLarge`] if a count or a point index exceeds `u32::MAX`.
203/// - [`EncodeError::BufferTooSmall`] if `out` is shorter than [`encoded_len`].
204pub fn encode_into(
205 points: &[PointKind],
206 edges: &[DispatchEdge],
207 waits: &[Wait],
208 out: &mut [u8],
209) -> Result<usize, EncodeError> {
210 let len = encoded_len(points.len(), edges.len(), waits.len()).ok_or(EncodeError::TooLarge)?;
211 let buf = out
212 .get_mut(..len)
213 .ok_or(EncodeError::BufferTooSmall { needed: len })?;
214 let mut w = Writer { buf, at: 0 };
215
216 w.header(points.len(), edges.len(), waits.len())?;
217
218 for &p in points {
219 w.point(p)?;
220 }
221
222 for e in edges {
223 w.pair(e.from, e.to, e.weight)?;
224 }
225
226 for x in waits {
227 w.pair(x.waiter, x.contingent, x.delay)?;
228 }
229
230 w.checksum()?;
231 Ok(len)
232}
233
234/// Sequential writer into a buffer of exactly the encoding's length.
235struct Writer<'a> {
236 /// Destination, exactly [`encoded_len`] bytes.
237 buf: &'a mut [u8],
238 /// Bytes written so far.
239 at: usize,
240}
241
242impl Writer<'_> {
243 /// Appends `bytes`.
244 ///
245 /// # Errors
246 ///
247 /// [`EncodeError::BufferTooSmall`] if they do not fit (not reachable when the buffer has
248 /// the computed length).
249 fn put(&mut self, bytes: &[u8]) -> Result<(), EncodeError> {
250 let needed = self.buf.len();
251 let end = self.at.saturating_add(bytes.len());
252 let dst = self
253 .buf
254 .get_mut(self.at..end)
255 .ok_or(EncodeError::BufferTooSmall { needed })?;
256 dst.copy_from_slice(bytes);
257 self.at = end;
258 Ok(())
259 }
260
261 /// Appends a `u32` count or point index.
262 ///
263 /// # Errors
264 ///
265 /// [`EncodeError::TooLarge`] if `value` exceeds `u32::MAX`, or as for [`Self::put`].
266 fn put_u32(&mut self, value: usize) -> Result<(), EncodeError> {
267 let v = u32::try_from(value).map_err(|_| EncodeError::TooLarge)?;
268 self.put(&v.to_le_bytes())
269 }
270
271 /// Appends a tick value.
272 ///
273 /// # Errors
274 ///
275 /// As for [`Self::put`].
276 fn put_ticks(&mut self, t: Ticks) -> Result<(), EncodeError> {
277 self.put(&t.0.to_le_bytes())
278 }
279
280 /// Writes the header.
281 ///
282 /// # Errors
283 ///
284 /// As for [`Self::put_u32`].
285 fn header(&mut self, points: usize, edges: usize, waits: usize) -> Result<(), EncodeError> {
286 self.put(&MAGIC)?;
287 self.put(&VERSION.to_le_bytes())?;
288 self.put(&0u16.to_le_bytes())?;
289 self.put_u32(points)?;
290 self.put_u32(edges)?;
291 self.put_u32(waits)
292 }
293
294 /// Writes a point record.
295 ///
296 /// # Errors
297 ///
298 /// As for [`Self::put_u32`].
299 fn point(&mut self, kind: PointKind) -> Result<(), EncodeError> {
300 match kind {
301 PointKind::Executable => self.put(&[0; POINT_LEN]),
302 PointKind::Contingent { activation, lo, hi } => {
303 self.put(&[TAG_CONTINGENT])?;
304 self.put_u32(activation.0)?;
305 self.put_ticks(lo)?;
306 self.put_ticks(hi)
307 }
308 }
309 }
310
311 /// Writes an edge or wait record.
312 ///
313 /// # Errors
314 ///
315 /// As for [`Self::put_u32`].
316 fn pair(&mut self, a: TimePoint, b: TimePoint, t: Ticks) -> Result<(), EncodeError> {
317 self.put_u32(a.0)?;
318 self.put_u32(b.0)?;
319 self.put_ticks(t)
320 }
321
322 /// Writes the CRC of everything written so far.
323 ///
324 /// # Errors
325 ///
326 /// As for [`Self::put`].
327 fn checksum(&mut self) -> Result<(), EncodeError> {
328 let crc = crc32(self.buf.get(..self.at).unwrap_or_default());
329 self.put(&crc.to_le_bytes())
330 }
331}
332
333/// An encoding whose header, length, checksum and record tags have been checked.
334///
335/// Records are read on demand from the borrowed bytes through [`Source`].
336#[derive(Debug, Clone, Copy)]
337pub(crate) struct Encoded<'a> {
338 /// The whole encoding, checksum included.
339 bytes: &'a [u8],
340 /// Number of point records.
341 points: usize,
342 /// Number of edge records.
343 edges: usize,
344 /// Number of wait records.
345 waits: usize,
346}
347
348impl<'a> Encoded<'a> {
349 /// Checks the framing of `bytes`: everything except the network's structure.
350 ///
351 /// # Errors
352 ///
353 /// Every [`DecodeError`] except [`DecodeError::Network`], in the order of the module docs.
354 pub(crate) fn parse(bytes: &'a [u8]) -> Result<Self, DecodeError> {
355 if bytes.len() < HEADER_LEN + CRC_LEN {
356 return Err(DecodeError::Truncated);
357 }
358
359 if bytes.get(..4) != Some(&MAGIC[..]) {
360 return Err(DecodeError::BadMagic);
361 }
362
363 let version = read_u16(bytes, 4).ok_or(DecodeError::Truncated)?;
364
365 if version != VERSION {
366 return Err(DecodeError::UnsupportedVersion(version));
367 }
368
369 let encoded = Self::framed(bytes)?;
370 encoded.verify_checksum()?;
371 encoded.verify_canonical()?;
372 Ok(encoded)
373 }
374
375 /// [`Self::parse`] after the magic and version checks, without the checksum: the Kani
376 /// harnesses use it to reach the structural checks without a CRC over symbolic bytes, which
377 /// is what made them too large for CBMC. The checksum is checked by its own harness.
378 ///
379 /// # Errors
380 ///
381 /// [`DecodeError::LengthMismatch`], [`DecodeError::Truncated`] or
382 /// [`DecodeError::NonCanonical`].
383 #[cfg(kani)]
384 pub(crate) fn parse_without_checksum(bytes: &'a [u8]) -> Result<Self, DecodeError> {
385 let encoded = Self::framed(bytes)?;
386 encoded.verify_canonical()?;
387 Ok(encoded)
388 }
389
390 /// An encoding of `points` point and `edges` edge records that is taken as already
391 /// framed and canonical, for the Kani harnesses of the loader (the canonical-form check
392 /// over symbolic records has its own harness).
393 #[cfg(kani)]
394 pub(crate) fn assume_valid_framing(bytes: &'a [u8], points: usize, edges: usize) -> Self {
395 Self {
396 bytes,
397 points,
398 edges,
399 waits: 0,
400 }
401 }
402
403 /// Reads the counts and checks that they match the buffer length exactly.
404 ///
405 /// # Errors
406 ///
407 /// [`DecodeError::LengthMismatch`].
408 fn framed(bytes: &'a [u8]) -> Result<Self, DecodeError> {
409 let count = |at| read_u32(bytes, at).ok_or(DecodeError::Truncated);
410 let (n, e, w) = (count(8)?, count(12)?, count(16)?);
411 let expected = length_of(n, e, w);
412
413 if u64::try_from(bytes.len()).ok() != Some(expected) {
414 return Err(DecodeError::LengthMismatch {
415 expected,
416 actual: bytes.len(),
417 });
418 }
419
420 let widen = |c: u32| usize::try_from(c).map_err(|_| DecodeError::Truncated);
421
422 Ok(Self {
423 bytes,
424 points: widen(n)?,
425 edges: widen(e)?,
426 waits: widen(w)?,
427 })
428 }
429
430 /// Compares the trailing CRC with the CRC of the content.
431 ///
432 /// # Errors
433 ///
434 /// [`DecodeError::ChecksumMismatch`].
435 fn verify_checksum(&self) -> Result<(), DecodeError> {
436 let body_len = self.bytes.len().saturating_sub(CRC_LEN);
437 let (body, stored) = self.bytes.split_at(body_len);
438 let stored = stored.try_into().ok().map(u32::from_le_bytes);
439
440 if stored != Some(crc32(body)) {
441 return Err(DecodeError::ChecksumMismatch);
442 }
443
444 Ok(())
445 }
446
447 /// Checks the reserved field and every point record's tag and padding.
448 ///
449 /// # Errors
450 ///
451 /// [`DecodeError::NonCanonical`].
452 fn verify_canonical(&self) -> Result<(), DecodeError> {
453 let reserved_zero = read_u16(self.bytes, 6) == Some(0);
454 let records_ok = (0..self.points).all(|i| {
455 self.point_record(i).is_some_and(|r| match r[0] {
456 TAG_EXECUTABLE => r[1..].iter().all(|&b| b == 0),
457 TAG_CONTINGENT => true,
458 _ => false,
459 })
460 });
461
462 if !(reserved_zero && records_ok) {
463 return Err(DecodeError::NonCanonical);
464 }
465
466 Ok(())
467 }
468
469 /// Raw point record `i`.
470 fn point_record(&self, i: usize) -> Option<[u8; POINT_LEN]> {
471 if i >= self.points {
472 return None;
473 }
474
475 let at = HEADER_LEN.checked_add(i.checked_mul(POINT_LEN)?)?;
476 read(self.bytes, at)
477 }
478
479 /// Edge or wait record `i` of the section starting after `skip` pair records.
480 fn pair_record(&self, skip: usize, i: usize) -> Option<(TimePoint, TimePoint, Ticks)> {
481 let points_len = self.points.checked_mul(POINT_LEN)?;
482 let index = skip.checked_add(i)?.checked_mul(PAIR_LEN)?;
483 let at = HEADER_LEN.checked_add(points_len)?.checked_add(index)?;
484 let r: [u8; PAIR_LEN] = read(self.bytes, at)?;
485
486 Some((point_at(&r, 0)?, point_at(&r, 4)?, ticks_at(&r, 8)?))
487 }
488}
489
490impl Source for Encoded<'_> {
491 fn point_count(&self) -> usize {
492 self.points
493 }
494
495 fn edge_count(&self) -> usize {
496 self.edges
497 }
498
499 fn wait_count(&self) -> usize {
500 self.waits
501 }
502
503 fn point(&self, i: usize) -> Option<PointKind> {
504 let r = self.point_record(i)?;
505
506 match r[0] {
507 TAG_EXECUTABLE => Some(PointKind::Executable),
508 TAG_CONTINGENT => Some(PointKind::Contingent {
509 activation: point_at(&r, 1)?,
510 lo: ticks_at(&r, 5)?,
511 hi: ticks_at(&r, 13)?,
512 }),
513 _ => None,
514 }
515 }
516
517 fn edge(&self, i: usize) -> Option<DispatchEdge> {
518 if i >= self.edges {
519 return None;
520 }
521
522 let (from, to, weight) = self.pair_record(0, i)?;
523 Some(DispatchEdge { from, to, weight })
524 }
525
526 fn wait(&self, i: usize) -> Option<Wait> {
527 if i >= self.waits {
528 return None;
529 }
530
531 let (waiter, contingent, delay) = self.pair_record(self.edges, i)?;
532 Some(Wait {
533 waiter,
534 contingent,
535 delay,
536 })
537 }
538}
539
540/// The `W` bytes at offset `at`, or `None` if out of range.
541fn read<const W: usize>(bytes: &[u8], at: usize) -> Option<[u8; W]> {
542 bytes.get(at..at.checked_add(W)?)?.try_into().ok()
543}
544
545/// Little-endian `u16` at offset `at`.
546fn read_u16(bytes: &[u8], at: usize) -> Option<u16> {
547 read(bytes, at).map(u16::from_le_bytes)
548}
549
550/// Little-endian `u32` at offset `at`.
551fn read_u32(bytes: &[u8], at: usize) -> Option<u32> {
552 read(bytes, at).map(u32::from_le_bytes)
553}
554
555/// Point index (`u32`) at offset `at`. An index that does not fit `usize` (only possible
556/// where `usize` has 16 bits) becomes `usize::MAX`, which validation rejects as out of range.
557fn point_at(bytes: &[u8], at: usize) -> Option<TimePoint> {
558 read_u32(bytes, at).map(|v| TimePoint(usize::try_from(v).unwrap_or(usize::MAX)))
559}
560
561/// Tick value (`i64`) at offset `at`.
562fn ticks_at(bytes: &[u8], at: usize) -> Option<Ticks> {
563 read(bytes, at).map(|b| Ticks(i64::from_le_bytes(b)))
564}
565
566#[cfg(test)]
567mod tests {
568 //! Unit tests for the CRC and the framing checks.
569
570 use super::*;
571
572 /// The standard check value of CRC-32/ISO-HDLC.
573 #[test]
574 fn crc_check_value() {
575 assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
576 assert_eq!(crc32(b""), 0);
577 assert_eq!(crc32(b"a"), 0xE8B7_BE43);
578 }
579
580 /// The length formula matches the documented layout.
581 #[test]
582 fn length_formula() {
583 assert_eq!(encoded_len(0, 0, 0), Some(24));
584 assert_eq!(encoded_len(2, 3, 1), Some(24 + 42 + 64));
585 assert_eq!(
586 length_of(u32::MAX, u32::MAX, u32::MAX),
587 24 + 53 * u64::from(u32::MAX)
588 );
589 }
590}