Skip to main content

resource_timeline/
codec.rs

1//! A compact, checksummed byte encoding of profiles and timelines, without allocation.
2//!
3//! For downlink, persistence across a reset, or handing a timeline to another processor, a
4//! [`LevelProfile`], a [`Timeline`] and a [`StateTimeline`] can be written into a caller's
5//! byte buffer and read back into any storage. The format is fixed-size per element and
6//! little-endian:
7//!
8//! | Field | Size | Content |
9//! | --- | --- | --- |
10//! | magic | 4 | `RTPF` (profile), `RTTL` (timeline) or `RTST` (state timeline) |
11//! | version | 1 | [`VERSION`] |
12//! | flags | 1 | zero, reserved |
13//! | body | varies | the fields below |
14//! | checksum | 4 | CRC-32 (IEEE) of every byte before it |
15//!
16//! - profile body: the breakpoint count `n` (`u32`), then `n` breakpoints of `at`, `level`,
17//!   `slope` (`i64` each);
18//! - timeline body: kind (`u8`, 0 depletable, 1 claimable), start, initial, min, max (`i64`),
19//!   budget (`u64`), impact count and target count (`u32`), then each impact as activity
20//!   (`u32`), tag (`u8`: 0 step, 1 claim, 2 rate) and three `i64` (`at, delta, 0` for a step,
21//!   `start, end, amount` or `start, end, per_tick` otherwise), then each target as `at, min`;
22//! - state timeline body: start (`i64`), initial (`u32`), budget (`u64`), impact count
23//!   (`u32`), then each impact as activity (`u32`), tag (`u8`: 0 set, 1 require), two `i64`
24//!   (`at, 0` or `start, end`) and the value (`u32`).
25//!
26//! `decode_in` reads into any storage; `decode` is its heap shorthand (feature `alloc`), so
27//! that `Timeline::decode(bytes)` needs no type annotation.
28//!
29//! Decoding checks the magic, version, length and checksum before it looks at the body, then
30//! rebuilds the value through the normal, validating constructors, so a decoded timeline obeys
31//! every invariant and capacity of its storage. Insertion order is preserved.
32//!
33//! # Examples
34//!
35//! ```
36//! use resource_timeline::storage::Fixed;
37//! use resource_timeline::{ActivityId, Bounds, Impact, Target, Timeline};
38//!
39//! let mut battery = Timeline::<Fixed<8>>::depletable_in(0, 50, Bounds::new(10, 100)?, 8)?;
40//! battery.add(ActivityId(1), Impact::Rate { start: 0, end: 20, per_tick: -2 })?;
41//! battery.add_target(Target { at: 30, min: 20 })?;
42//!
43//! let mut bytes = [0_u8; 256];
44//! let written = battery.encode(&mut bytes)?;
45//! assert_eq!(written, battery.encoded_len());
46//! let restored = Timeline::<Fixed<8>>::decode_in(&bytes[..written])?;
47//! assert_eq!(restored, battery);
48//!
49//! // A flipped bit is caught by the checksum.
50//! bytes[20] ^= 1;
51//! assert!(Timeline::<Fixed<8>>::decode_in(&bytes[..written]).is_err());
52//! # Ok::<(), resource_timeline::Error>(())
53//! ```
54
55use crate::storage::{Seq, Storage};
56use crate::{
57    ActivityId, Bounds, Breakpoint, Container, Error, Impact, Kind, LevelProfile, StateImpact,
58    StateTimeline, Target, Timeline,
59};
60
61/// The format version written and accepted.
62pub const VERSION: u8 = 1;
63
64/// Magic of an encoded [`LevelProfile`].
65const PROFILE: [u8; 4] = *b"RTPF";
66/// Magic of an encoded [`Timeline`].
67const TIMELINE: [u8; 4] = *b"RTTL";
68/// Magic of an encoded [`StateTimeline`].
69const STATE: [u8; 4] = *b"RTST";
70
71/// Bytes of the magic, version and flags.
72const HEADER: usize = 6;
73/// Bytes of the checksum.
74const CHECKSUM: usize = 4;
75/// Bytes of one encoded breakpoint.
76const BREAKPOINT: usize = 24;
77/// Bytes of one encoded numeric impact.
78const IMPACT: usize = 29;
79/// Bytes of one encoded target.
80const TARGET: usize = 16;
81/// Bytes of one encoded state impact.
82const STATE_IMPACT: usize = 25;
83/// Bytes of the fixed part of a timeline body.
84const TIMELINE_FIELDS: usize = 1 + 4 * 8 + 8 + 4 + 4;
85/// Bytes of the fixed part of a state timeline body.
86const STATE_FIELDS: usize = 8 + 4 + 8 + 4;
87
88impl<S: Storage> LevelProfile<S> {
89    /// The number of bytes [`encode`](Self::encode) writes.
90    #[must_use]
91    pub fn encoded_len(&self) -> usize {
92        HEADER + 4 + self.len() * BREAKPOINT + CHECKSUM
93    }
94
95    /// Writes the profile into `out` and returns the number of bytes written; see the
96    /// [`codec`](crate::codec) module for the format.
97    ///
98    /// # Errors
99    ///
100    /// [`Error::BufferTooSmall`] if `out` is shorter than [`encoded_len`](Self::encoded_len);
101    /// nothing is written then. [`Error::Overflow`] if the breakpoint count exceeds `u32`.
102    pub fn encode(&self, out: &mut [u8]) -> Result<usize, Error> {
103        let mut writer = Writer::start(out, self.encoded_len(), PROFILE)?;
104        writer.u32(count(self.len())?);
105        for point in self.breakpoints() {
106            writer.i64(point.at);
107            writer.i64(point.level);
108            writer.i64(point.slope);
109        }
110
111        Ok(writer.finish())
112    }
113
114    /// Reads a profile written by [`encode`](Self::encode), into storage `S`.
115    ///
116    /// # Errors
117    ///
118    /// - [`Error::Malformed`] if the magic, the length or the content is wrong (breakpoints
119    ///   must be strictly increasing in tick).
120    /// - [`Error::UnsupportedVersion`] for another format version.
121    /// - [`Error::ChecksumMismatch`] if the bytes were corrupted.
122    /// - [`Error::CapacityExceeded`] or [`Error::OutOfMemory`] if `S` cannot hold the
123    ///   breakpoints.
124    pub fn decode_in(bytes: &[u8]) -> Result<Self, Error> {
125        let mut reader = Reader::open(bytes, PROFILE)?;
126        let len = reader.count(BREAKPOINT)?;
127        let mut points = (0..len).map(|_| Breakpoint {
128            at: reader.i64_unchecked(),
129            level: reader.i64_unchecked(),
130            slope: reader.i64_unchecked(),
131        });
132        let origin = points.next().ok_or(Error::Malformed)?;
133        let mut changes = <S::DoubleList<Breakpoint> as Seq<_>>::EMPTY;
134        let mut previous = origin.at;
135        for point in points {
136            if point.at <= previous {
137                return Err(Error::Malformed);
138            }
139
140            previous = point.at;
141            changes.try_push(point, Container::ChangePoints)?;
142        }
143
144        reader.end()?;
145        Ok(Self::from_parts(origin, changes))
146    }
147}
148
149impl<S: Storage> Timeline<S> {
150    /// The number of bytes [`encode`](Self::encode) writes.
151    #[must_use]
152    pub fn encoded_len(&self) -> usize {
153        HEADER
154            + TIMELINE_FIELDS
155            + self.impacts().len() * IMPACT
156            + self.targets().len() * TARGET
157            + CHECKSUM
158    }
159
160    /// Writes the timeline (kind, start, initial level, bounds, budget, impacts in insertion
161    /// order, targets) into `out` and returns the number of bytes written; see the
162    /// [`codec`](crate::codec) module for the format and an example.
163    ///
164    /// # Errors
165    ///
166    /// [`Error::BufferTooSmall`] if `out` is shorter than [`encoded_len`](Self::encoded_len);
167    /// nothing is written then. [`Error::Overflow`] if a count exceeds `u32`.
168    pub fn encode(&self, out: &mut [u8]) -> Result<usize, Error> {
169        let mut writer = Writer::start(out, self.encoded_len(), TIMELINE)?;
170        writer.u8(match self.kind() {
171            Kind::Depletable => 0,
172            Kind::Claimable => 1,
173        });
174        writer.i64(self.start());
175        writer.i64(self.initial());
176        writer.i64(self.bounds().min());
177        writer.i64(self.bounds().max());
178        writer.u64(u64::try_from(self.budget()).map_err(|_| Error::Overflow)?);
179        writer.u32(count(self.impacts().len())?);
180        writer.u32(count(self.targets().len())?);
181        for &(activity, impact) in self.impacts() {
182            writer.u32(activity.0);
183            let (tag, a, b, c) = match impact {
184                Impact::Step { at, delta } => (0, at, delta, 0),
185                Impact::Claim { start, end, amount } => (1, start, end, amount),
186                Impact::Rate {
187                    start,
188                    end,
189                    per_tick,
190                } => (2, start, end, per_tick),
191            };
192            writer.u8(tag);
193            writer.i64(a);
194            writer.i64(b);
195            writer.i64(c);
196        }
197
198        for target in self.targets() {
199            writer.i64(target.at);
200            writer.i64(target.min);
201        }
202
203        Ok(writer.finish())
204    }
205
206    /// Reads a timeline written by [`encode`](Self::encode), into storage `S`.
207    ///
208    /// # Errors
209    ///
210    /// - [`Error::Malformed`], [`Error::UnsupportedVersion`] or [`Error::ChecksumMismatch`]
211    ///   as for [`LevelProfile::decode_in`].
212    /// - The errors of [`Timeline::claimable_in`], [`Timeline::add`] and
213    ///   [`Timeline::add_target`] for the decoded content, including capacity errors if `S`
214    ///   is smaller than the encoded timeline.
215    pub fn decode_in(bytes: &[u8]) -> Result<Self, Error> {
216        let mut reader = Reader::open(bytes, TIMELINE)?;
217        reader.need(TIMELINE_FIELDS)?;
218        let kind = reader.u8_unchecked();
219        let (start, initial) = (reader.i64_unchecked(), reader.i64_unchecked());
220        let (min, max) = (reader.i64_unchecked(), reader.i64_unchecked());
221        let budget = usize::try_from(reader.u64_unchecked()).map_err(|_| Error::Malformed)?;
222        let impacts = usize::try_from(reader.u32_unchecked()).map_err(|_| Error::Malformed)?;
223        let targets = usize::try_from(reader.u32_unchecked()).map_err(|_| Error::Malformed)?;
224        reader.need(
225            impacts
226                .saturating_mul(IMPACT)
227                .saturating_add(targets.saturating_mul(TARGET)),
228        )?;
229
230        let mut timeline = match kind {
231            0 => Self::depletable_in(start, initial, Bounds::new(min, max)?, budget)?,
232            1 if min == 0 && initial == max => Self::claimable_in(start, max, budget)?,
233            _ => return Err(Error::Malformed),
234        };
235        for _ in 0..impacts {
236            let activity = ActivityId(reader.u32_unchecked());
237            let tag = reader.u8_unchecked();
238            let (a, b, c) = (
239                reader.i64_unchecked(),
240                reader.i64_unchecked(),
241                reader.i64_unchecked(),
242            );
243            let impact = match tag {
244                0 if c == 0 => Impact::Step { at: a, delta: b },
245                1 => Impact::Claim {
246                    start: a,
247                    end: b,
248                    amount: c,
249                },
250                2 => Impact::Rate {
251                    start: a,
252                    end: b,
253                    per_tick: c,
254                },
255                _ => return Err(Error::Malformed),
256            };
257            timeline.add(activity, impact)?;
258        }
259
260        for _ in 0..targets {
261            let target = Target {
262                at: reader.i64_unchecked(),
263                min: reader.i64_unchecked(),
264            };
265            timeline.add_target(target)?;
266        }
267
268        reader.end()?;
269        Ok(timeline)
270    }
271}
272
273impl<S: Storage> StateTimeline<S> {
274    /// The number of bytes [`encode`](Self::encode) writes.
275    #[must_use]
276    pub fn encoded_len(&self) -> usize {
277        HEADER + STATE_FIELDS + self.impacts().len() * STATE_IMPACT + CHECKSUM
278    }
279
280    /// Writes the state timeline (start, initial value, budget, impacts in insertion order)
281    /// into `out` and returns the number of bytes written; see the [`codec`](crate::codec)
282    /// module for the format.
283    ///
284    /// # Errors
285    ///
286    /// [`Error::BufferTooSmall`] if `out` is shorter than [`encoded_len`](Self::encoded_len);
287    /// nothing is written then. [`Error::Overflow`] if the impact count exceeds `u32`.
288    pub fn encode(&self, out: &mut [u8]) -> Result<usize, Error> {
289        let mut writer = Writer::start(out, self.encoded_len(), STATE)?;
290        writer.i64(self.start());
291        writer.u32(self.initial());
292        writer.u64(u64::try_from(self.budget()).map_err(|_| Error::Overflow)?);
293        writer.u32(count(self.impacts().len())?);
294        for &(activity, impact) in self.impacts() {
295            writer.u32(activity.0);
296            let (tag, a, b, value) = match impact {
297                StateImpact::Set { at, value } => (0, at, 0, value),
298                StateImpact::Require { start, end, value } => (1, start, end, value),
299            };
300            writer.u8(tag);
301            writer.i64(a);
302            writer.i64(b);
303            writer.u32(value);
304        }
305
306        Ok(writer.finish())
307    }
308
309    /// Reads a state timeline written by [`encode`](Self::encode), into storage `S`.
310    ///
311    /// # Errors
312    ///
313    /// - [`Error::Malformed`], [`Error::UnsupportedVersion`] or [`Error::ChecksumMismatch`]
314    ///   as for [`LevelProfile::decode_in`].
315    /// - The errors of [`StateTimeline::add`] for the decoded content, including capacity
316    ///   errors if `S` is smaller than the encoded timeline.
317    pub fn decode_in(bytes: &[u8]) -> Result<Self, Error> {
318        let mut reader = Reader::open(bytes, STATE)?;
319        reader.need(STATE_FIELDS)?;
320        let start = reader.i64_unchecked();
321        let initial = reader.u32_unchecked();
322        let budget = usize::try_from(reader.u64_unchecked()).map_err(|_| Error::Malformed)?;
323        let impacts = usize::try_from(reader.u32_unchecked()).map_err(|_| Error::Malformed)?;
324        reader.need(impacts.saturating_mul(STATE_IMPACT))?;
325
326        let mut timeline = Self::new_in(start, initial, budget);
327        for _ in 0..impacts {
328            let activity = ActivityId(reader.u32_unchecked());
329            let tag = reader.u8_unchecked();
330            let (a, b) = (reader.i64_unchecked(), reader.i64_unchecked());
331            let value = reader.u32_unchecked();
332            let impact = match tag {
333                0 if b == 0 => StateImpact::Set { at: a, value },
334                1 => StateImpact::Require {
335                    start: a,
336                    end: b,
337                    value,
338                },
339                _ => return Err(Error::Malformed),
340            };
341            timeline.add(activity, impact)?;
342        }
343
344        reader.end()?;
345        Ok(timeline)
346    }
347}
348
349#[cfg(feature = "alloc")]
350impl LevelProfile {
351    /// [`decode_in`](Self::decode_in) into heap storage.
352    ///
353    /// # Errors
354    ///
355    /// As for [`decode_in`](Self::decode_in).
356    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
357        Self::decode_in(bytes)
358    }
359}
360
361#[cfg(feature = "alloc")]
362impl Timeline {
363    /// [`decode_in`](Self::decode_in) into heap storage.
364    ///
365    /// # Errors
366    ///
367    /// As for [`decode_in`](Self::decode_in).
368    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
369        Self::decode_in(bytes)
370    }
371}
372
373#[cfg(feature = "alloc")]
374impl StateTimeline {
375    /// [`decode_in`](Self::decode_in) into heap storage.
376    ///
377    /// # Errors
378    ///
379    /// As for [`decode_in`](Self::decode_in).
380    pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
381        Self::decode_in(bytes)
382    }
383}
384
385/// `len` as a `u32` count.
386fn count(len: usize) -> Result<u32, Error> {
387    u32::try_from(len).map_err(|_| Error::Overflow)
388}
389
390/// Writes into a buffer that was checked to be long enough.
391struct Writer<'a> {
392    /// The output, exactly as long as the encoding.
393    out: &'a mut [u8],
394    /// The next byte to write.
395    at: usize,
396}
397
398impl<'a> Writer<'a> {
399    /// Checks the room and writes the header.
400    fn start(out: &'a mut [u8], len: usize, magic: [u8; 4]) -> Result<Self, Error> {
401        let out = out
402            .get_mut(..len)
403            .ok_or(Error::BufferTooSmall { needed: len })?;
404        let mut writer = Self { out, at: 0 };
405        writer.bytes(&magic);
406        writer.u8(VERSION);
407        writer.u8(0);
408        Ok(writer)
409    }
410
411    /// Appends raw bytes.
412    fn bytes(&mut self, bytes: &[u8]) {
413        self.out[self.at..self.at + bytes.len()].copy_from_slice(bytes);
414        self.at += bytes.len();
415    }
416
417    /// Appends a byte.
418    fn u8(&mut self, value: u8) {
419        self.bytes(&[value]);
420    }
421
422    /// Appends a little-endian `u32`.
423    fn u32(&mut self, value: u32) {
424        self.bytes(&value.to_le_bytes());
425    }
426
427    /// Appends a little-endian `u64`.
428    fn u64(&mut self, value: u64) {
429        self.bytes(&value.to_le_bytes());
430    }
431
432    /// Appends a little-endian `i64`.
433    fn i64(&mut self, value: i64) {
434        self.bytes(&value.to_le_bytes());
435    }
436
437    /// Appends the checksum and returns the total length.
438    fn finish(mut self) -> usize {
439        let checksum = crc32(&self.out[..self.at]);
440        self.u32(checksum);
441        self.at
442    }
443}
444
445/// Reads a buffer whose header, length and checksum were verified.
446struct Reader<'a> {
447    /// The body, without header and checksum.
448    body: &'a [u8],
449    /// The next byte to read.
450    at: usize,
451}
452
453impl<'a> Reader<'a> {
454    /// Verifies the magic, the version and the checksum, and positions after the header.
455    fn open(bytes: &'a [u8], magic: [u8; 4]) -> Result<Self, Error> {
456        if bytes.len() < HEADER + CHECKSUM || bytes[..4] != magic {
457            return Err(Error::Malformed);
458        }
459
460        if bytes[4] != VERSION {
461            return Err(Error::UnsupportedVersion { version: bytes[4] });
462        }
463
464        if bytes[5] != 0 {
465            return Err(Error::Malformed);
466        }
467
468        let (content, checksum) = bytes.split_at(bytes.len() - CHECKSUM);
469        let expected = u32::from_le_bytes(checksum.try_into().map_err(|_| Error::Malformed)?);
470        if crc32(content) != expected {
471            return Err(Error::ChecksumMismatch);
472        }
473
474        Ok(Self {
475            body: &content[HEADER..],
476            at: 0,
477        })
478    }
479
480    /// Fails unless `len` more bytes are left.
481    fn need(&self, len: usize) -> Result<(), Error> {
482        if self.body.len() - self.at < len {
483            return Err(Error::Malformed);
484        }
485
486        Ok(())
487    }
488
489    /// Reads an element count and checks that that many elements of `size` bytes follow.
490    fn count(&mut self, size: usize) -> Result<usize, Error> {
491        self.need(4)?;
492        let len = usize::try_from(self.u32_unchecked()).map_err(|_| Error::Malformed)?;
493        self.need(len.saturating_mul(size))?;
494        Ok(len)
495    }
496
497    /// Fails unless every byte was read.
498    fn end(&self) -> Result<(), Error> {
499        if self.at == self.body.len() {
500            Ok(())
501        } else {
502            Err(Error::Malformed)
503        }
504    }
505
506    /// The next `N` bytes; [`need`](Self::need) must have checked them.
507    fn take<const N: usize>(&mut self) -> [u8; N] {
508        let mut out = [0; N];
509        out.copy_from_slice(&self.body[self.at..self.at + N]);
510        self.at += N;
511        out
512    }
513
514    /// The next byte.
515    fn u8_unchecked(&mut self) -> u8 {
516        self.take::<1>()[0]
517    }
518
519    /// The next little-endian `u32`.
520    fn u32_unchecked(&mut self) -> u32 {
521        u32::from_le_bytes(self.take())
522    }
523
524    /// The next little-endian `u64`.
525    fn u64_unchecked(&mut self) -> u64 {
526        u64::from_le_bytes(self.take())
527    }
528
529    /// The next little-endian `i64`.
530    fn i64_unchecked(&mut self) -> i64 {
531        i64::from_le_bytes(self.take())
532    }
533}
534
535/// The CRC-32 lookup table (IEEE 802.3, reflected polynomial `0xEDB8_8320`).
536const CRC_TABLE: [u32; 256] = {
537    let mut table = [0_u32; 256];
538    let (mut index, mut seed) = (0_usize, 0_u32);
539    while index < 256 {
540        let mut value = seed;
541        let mut bit = 0;
542        while bit < 8 {
543            value = if value & 1 == 1 {
544                (value >> 1) ^ 0xEDB8_8320
545            } else {
546                value >> 1
547            };
548            bit += 1;
549        }
550
551        table[index] = value;
552        index += 1;
553        seed += 1;
554    }
555
556    table
557};
558
559/// The CRC-32 (IEEE) of `bytes`, as used by zlib and Ethernet.
560#[must_use]
561pub fn crc32(bytes: &[u8]) -> u32 {
562    let mut crc = u32::MAX;
563    for &byte in bytes {
564        crc = (crc >> 8) ^ CRC_TABLE[((crc ^ u32::from(byte)) & 0xFF) as usize];
565    }
566
567    !crc
568}
569
570#[cfg(test)]
571mod tests {
572    //! The checksum against the standard check value.
573
574    use super::crc32;
575
576    /// The CRC-32 check value of the ASCII digits 1 to 9.
577    #[test]
578    fn check_value() {
579        assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
580    }
581}