maquette 0.1.0

A simulated HDMI sink for tests: SCDC and EDID registers, a DDC bus, a PHY and a clock under deterministic time, with faults and conformance checks for hdmi-hal's traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! The transcript: one ordered, typed record of everything the bench and the sink did.

use core::fmt;

use hdmi_hal::ddc::{DdcErrorKind, EddcTarget, NoAcknowledgeSource};
use hdmi_hal::time::Timestamp;

use crate::config::RefusalKind;
use crate::fault::{Effect, FaultId, Point};
use crate::line::{ErrorRates, Line, LinkLanes};
use crate::phy::{PhyCall, PhyErrorKind};

/// One entry of the transcript: what happened, and when.
///
/// The bench makes records and a test reads them: like [`Event`] and [`BusRecord`], it is
/// `#[non_exhaustive]`, so a test compares the fields it cares about, not a built value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Record {
    /// When it happened: for a bus operation, when it started.
    pub at: Timestamp,
    /// What happened.
    pub event: Event,
}

/// What a [`Record`] records.
///
/// The bench makes the records; a test reads them. Each variant with fields is
/// `#[non_exhaustive]`, so it may gain one without a breaking change: match it with `..`,
/// and compare what a test cares about rather than a whole built `Event`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event {
    /// A `DdcBus` call, or one piece of a split `read_segmented`: what was asked and how it
    /// ended, refused calls included.
    Bus(BusRecord),
    /// A register of a built-in target changed, by the source or by the sink.
    #[non_exhaustive]
    Register {
        /// The target's address.
        addr: u8,
        /// The register.
        reg: u8,
        /// Its value before.
        from: u8,
        /// Its value after.
        to: u8,
        /// Who changed it.
        by: Actor,
    },
    /// A built-in target ignored a write, and why.
    #[non_exhaustive]
    IgnoredWrite {
        /// The target's address.
        addr: u8,
        /// The register or offset written.
        reg: u8,
        /// The value written.
        value: u8,
        /// Why it was ignored.
        why: Ignored,
    },
    /// What the source transmits changed ([`Bench::set_line`](crate::Bench::set_line)).
    Line(Line),
    /// The character errors on the link changed
    /// ([`Bench::set_character_errors`](crate::Bench::set_character_errors)).
    CharacterErrors(ErrorRates),
    /// The lanes' limits in FRL link training changed
    /// ([`Bench::set_lane_limits`](crate::Bench::set_lane_limits)).
    LaneLimits(LinkLanes),
    /// HPD changed.
    #[non_exhaustive]
    Hpd {
        /// Whether HPD is now high.
        high: bool,
    },
    /// The sink was unplugged or plugged in.
    #[non_exhaustive]
    Plug {
        /// Whether the sink is now plugged in.
        plugged: bool,
    },
    /// The adapter was detached or reattached.
    #[non_exhaustive]
    Adapter {
        /// Whether the adapter is now attached.
        attached: bool,
    },
    /// The sink refused to set the scrambling bit right away (`SinkConfig`'s refusals).
    #[non_exhaustive]
    Refusal {
        /// Which attempt, counted from 1: a write of `TMDS_Config` with `Scrambling_Enable`
        /// set.
        attempt: u32,
        /// How it refused.
        kind: RefusalKind,
    },
    /// A scheduled fault struck a bus operation: the last bus record before it, after which
    /// the operation's own records (a register written before a fault after it, for
    /// instance) may come first.
    #[non_exhaustive]
    Fault {
        /// The fault.
        id: FaultId,
        /// What it did.
        effect: Effect,
        /// Where it struck.
        point: Point,
    },
    /// A call of the simulated PHY, and how it ended, recorded when it returned.
    #[non_exhaustive]
    Phy {
        /// The call, with its arguments.
        call: PhyCall,
        /// How it ended.
        result: Result<(), PhyErrorKind>,
    },
    /// A test's target's own event, recorded with [`Env::note`](crate::Env::note).
    #[non_exhaustive]
    Note {
        /// The address the target noted it for.
        addr: u8,
        /// The target's own code for the event.
        code: u32,
        /// A value that goes with it.
        value: u32,
    },
    /// A scheduled action came: the events it makes follow.
    #[non_exhaustive]
    Action {
        /// The id [`Bench::schedule_action`](crate::Bench::schedule_action) returned.
        id: FaultId,
    },
}

/// A bus operation as the transcript records it: read, not built (see [`Record`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BusRecord {
    /// The operation.
    pub op: BusOp,
    /// The address of the operation: for `read_segmented`, the target's.
    pub addr: u8,
    /// The first byte written (an offset or a register), if any: for `read_segmented`, the
    /// offset of this piece.
    pub first: Option<u8>,
    /// How many bytes were written, the segment pointer's included; saturates at
    /// `u16::MAX`.
    pub written: u16,
    /// How many bytes were read; saturates at `u16::MAX`.
    pub read: u16,
    /// How it ended.
    pub result: Result<(), DdcErrorKind>,
}

/// The kind of a bus operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BusOp {
    /// `DdcBus::write`.
    Write,
    /// `DdcBus::write_read` with something to write; one with nothing to write is a `Read`.
    WriteRead,
    /// `DdcBus::read`.
    Read,
    /// `DdcBus::read_segmented`, or one piece of it.
    ReadSegmented {
        /// The structure read.
        target: EddcTarget,
        /// The segment read.
        segment: u8,
    },
}

/// The method's name; for a `read_segmented`, the structure and the segment too.
impl fmt::Display for BusOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Write => f.write_str("write"),
            Self::WriteRead => f.write_str("write_read"),
            Self::Read => f.write_str("read"),
            Self::ReadSegmented { target, segment } => {
                let target = match target {
                    EddcTarget::Edid => "the EDID",
                    EddcTarget::DisplayId => "the DisplayID",
                    _ => "a structure",
                };
                write!(f, "read_segmented of {target}, segment {segment}")
            }
        }
    }
}

/// Writes what `kind` means, in words: hdmi-hal's kinds have no `Display`.
pub(crate) fn describe_ddc(kind: DdcErrorKind, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(match kind {
        DdcErrorKind::NoAcknowledge(NoAcknowledgeSource::Address) => {
            "the address was not acknowledged"
        }
        DdcErrorKind::NoAcknowledge(NoAcknowledgeSource::Data) => {
            "a data byte was not acknowledged"
        }
        DdcErrorKind::NoAcknowledge(_) => "a byte was not acknowledged",
        DdcErrorKind::Timeout => "it timed out",
        DdcErrorKind::Busy => "the bus was busy",
        DdcErrorKind::Unsupported => "unsupported",
        DdcErrorKind::Detached => "the adapter is detached",
        DdcErrorKind::Other => "it failed",
        other => return write!(f, "{other:?}"),
    })
}

/// Who changed a register.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Actor {
    /// The source, by a bus write.
    Source,
    /// The sink, on its own.
    Sink,
    /// The test, by a preset.
    Test,
}

/// Why a built-in target ignored a write.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Ignored {
    /// The register is the sink's to set, not the source's.
    SinkOwned,
    /// The structure is not writable: the EDID and DisplayID after the offset byte.
    ReadOnly,
    /// The test's [`ScdcHook`](crate::ScdcHook) dropped or refused it.
    Hook,
}

/// The transcript's storage: a ring of `LOG` records, addressed by sequence number (the
/// count of records pushed before), and a count of those it did not keep. It keeps the
/// oldest by default, or the newest.
#[derive(Debug)]
pub(crate) struct Transcript<const LOG: usize> {
    records: [Option<Record>; LOG],
    /// The sequence number of the oldest record kept.
    first: usize,
    len: usize,
    overflow: usize,
    keep_newest: bool,
}

impl<const LOG: usize> Transcript<LOG> {
    pub(crate) const fn new() -> Self {
        Self {
            records: [None; LOG],
            first: 0,
            len: 0,
            overflow: 0,
            keep_newest: false,
        }
    }

    /// Keeps the newest records once full, dropping the oldest.
    pub(crate) const fn keeping_newest(mut self) -> Self {
        self.keep_newest = true;
        self
    }

    /// Appends `record`, returning its sequence number, or counts it when it is not kept:
    /// once full, the record itself, or the oldest it replaces when keeping the newest.
    pub(crate) fn push(&mut self, record: Record) -> Option<usize> {
        if LOG == 0 {
            self.overflow = self.overflow.saturating_add(1);
            return None;
        }
        let seq = self.first + self.len;
        if self.len < LOG {
            self.len += 1;
        } else if self.keep_newest {
            self.first += 1;
            self.overflow = self.overflow.saturating_add(1);
        } else {
            self.overflow = self.overflow.saturating_add(1);
            return None;
        }
        self.records[seq % LOG] = Some(record);
        Some(seq)
    }

    /// Sets the result of the bus record numbered `seq`, if it is still kept.
    pub(crate) fn set_result(&mut self, seq: Option<usize>, result: Result<(), DdcErrorKind>) {
        let Some(seq) = seq.filter(|&seq| seq >= self.first && seq < self.first + self.len) else {
            return;
        };
        if let Some(Record {
            event: Event::Bus(bus),
            ..
        }) = &mut self.records[seq % LOG]
        {
            bus.result = result;
        }
    }

    /// The `index`-th record kept, oldest first.
    pub(crate) fn get(&self, index: usize) -> Option<Record> {
        if index >= self.len {
            return None;
        }
        self.records[(self.first + index) % LOG]
    }

    pub(crate) fn len(&self) -> usize {
        self.len
    }

    pub(crate) fn overflow(&self) -> usize {
        self.overflow
    }

    pub(crate) fn clear(&mut self) {
        self.records = [None; LOG];
        self.first = 0;
        self.len = 0;
        self.overflow = 0;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn note(code: u32) -> Record {
        Record {
            at: Timestamp::from_micros(u64::from(code)),
            event: Event::Note {
                addr: 0x37,
                code,
                value: 0,
            },
        }
    }

    fn bus() -> Record {
        Record {
            at: Timestamp::from_micros(0),
            event: Event::Bus(BusRecord {
                op: BusOp::Write,
                addr: 0x54,
                first: Some(0x20),
                written: 2,
                read: 0,
                result: Ok(()),
            }),
        }
    }

    #[test]
    fn keeps_records_in_order_and_counts_the_overflow() {
        let mut transcript = Transcript::<2>::new();
        assert_eq!(transcript.push(note(1)), Some(0));
        assert_eq!(transcript.push(note(2)), Some(1));
        assert_eq!(transcript.push(note(3)), None);
        assert_eq!(transcript.len(), 2);
        assert_eq!(transcript.overflow(), 1);
        assert_eq!(transcript.get(0), Some(note(1)));
        assert_eq!(transcript.get(1), Some(note(2)));
        assert_eq!(transcript.get(2), None);
        transcript.clear();
        assert_eq!((transcript.len(), transcript.overflow()), (0, 0));
        assert_eq!(transcript.get(0), None);
    }

    #[test]
    fn sets_a_bus_records_result_only() {
        let mut transcript = Transcript::<2>::new();
        let index = transcript.push(bus());
        transcript.set_result(index, Err(DdcErrorKind::Busy));
        assert!(matches!(
            transcript.get(0),
            Some(Record {
                event: Event::Bus(BusRecord {
                    result: Err(DdcErrorKind::Busy),
                    ..
                }),
                ..
            })
        ));
        // Not a bus record, an overflowed one, an index out of range: nothing changes.
        let index = transcript.push(note(1));
        transcript.set_result(index, Err(DdcErrorKind::Busy));
        transcript.set_result(None, Err(DdcErrorKind::Busy));
        transcript.set_result(Some(7), Err(DdcErrorKind::Busy));
        assert_eq!(transcript.get(1), Some(note(1)));
    }

    #[test]
    fn a_transcript_of_no_capacity_counts_everything() {
        let mut transcript = Transcript::<0>::new();
        assert_eq!(transcript.push(note(1)), None);
        assert_eq!(transcript.overflow(), 1);
    }

    #[test]
    fn keeping_the_newest_drops_the_oldest_and_counts_them() {
        let mut transcript = Transcript::<2>::new().keeping_newest();
        assert_eq!(transcript.push(note(1)), Some(0));
        assert_eq!(transcript.push(note(2)), Some(1));
        assert_eq!(transcript.push(note(3)), Some(2));
        assert_eq!(transcript.len(), 2);
        assert_eq!(transcript.overflow(), 1);
        assert_eq!(transcript.get(0), Some(note(2)));
        assert_eq!(transcript.get(1), Some(note(3)));
        assert_eq!(transcript.get(2), None);
        transcript.clear();
        assert_eq!(transcript.push(note(4)), Some(0));
        assert_eq!(transcript.get(0), Some(note(4)));
    }

    #[test]
    fn a_result_reaches_only_a_bus_record_still_kept() {
        let mut transcript = Transcript::<2>::new().keeping_newest();
        let first = transcript.push(bus());
        transcript.push(note(1));
        transcript.push(note(2));
        // The bus record was dropped: its slot holds a note now, which keeps its own event.
        transcript.set_result(first, Err(DdcErrorKind::Busy));
        assert_eq!(transcript.get(1), Some(note(2)));
        let kept = transcript.push(bus());
        transcript.set_result(kept, Err(DdcErrorKind::Busy));
        assert!(matches!(
            transcript.get(1).unwrap().event,
            Event::Bus(BusRecord {
                result: Err(DdcErrorKind::Busy),
                ..
            })
        ));
        // A transcript of no records keeps none.
        let mut none = Transcript::<0>::new().keeping_newest();
        assert_eq!(none.push(note(1)), None);
        assert_eq!(none.overflow(), 1);
    }
}