wavefst/block/
blackout.rs

1use crate::encoding::{decode_varint, encode_varint};
2use crate::error::{Error, Result};
3
4/// Represents a single dump on/off event.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub struct BlackoutEvent {
7    /// `true` when dumping is enabled, `false` when disabled.
8    pub is_on: bool,
9    /// Absolute simulation time (after accumulated deltas) associated with the event.
10    pub time: u64,
11}
12
13/// Parsed blackout block.
14#[derive(Debug, Clone, Default)]
15pub struct BlackoutBlock {
16    /// Chronologically ordered blackout events decoded from the block payload.
17    pub events: Vec<BlackoutEvent>,
18}
19
20impl BlackoutBlock {
21    /// Serializes the block to a buffer.
22    pub fn encode(&self, out: &mut Vec<u8>) {
23        encode_varint(self.events.len() as u64, out);
24        let mut prev = 0u64;
25        for event in &self.events {
26            out.push(if event.is_on { 1 } else { 0 });
27            let delta = event.time.saturating_sub(prev);
28            encode_varint(delta, out);
29            prev = event.time;
30        }
31    }
32
33    /// Decodes the block from raw bytes.
34    pub fn decode(mut data: &[u8]) -> Result<Self> {
35        let count = decode_varint(&mut data)?;
36        let mut events = Vec::with_capacity(count as usize);
37        let mut time = 0u64;
38        for _ in 0..count {
39            let (flag, rest) = data
40                .split_first()
41                .ok_or_else(|| Error::decode("unexpected end of blackout data"))?;
42            data = rest;
43            let delta = decode_varint(&mut data)?;
44            time = time
45                .checked_add(delta)
46                .ok_or_else(|| Error::decode("blackout time overflow"))?;
47            events.push(BlackoutEvent {
48                is_on: *flag != 0,
49                time,
50            });
51        }
52        Ok(Self { events })
53    }
54}