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};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Record {
pub at: Timestamp,
pub event: Event,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event {
Bus(BusRecord),
#[non_exhaustive]
Register {
addr: u8,
reg: u8,
from: u8,
to: u8,
by: Actor,
},
#[non_exhaustive]
IgnoredWrite {
addr: u8,
reg: u8,
value: u8,
why: Ignored,
},
Line(Line),
CharacterErrors(ErrorRates),
LaneLimits(LinkLanes),
#[non_exhaustive]
Hpd {
high: bool,
},
#[non_exhaustive]
Plug {
plugged: bool,
},
#[non_exhaustive]
Adapter {
attached: bool,
},
#[non_exhaustive]
Refusal {
attempt: u32,
kind: RefusalKind,
},
#[non_exhaustive]
Fault {
id: FaultId,
effect: Effect,
point: Point,
},
#[non_exhaustive]
Phy {
call: PhyCall,
result: Result<(), PhyErrorKind>,
},
#[non_exhaustive]
Note {
addr: u8,
code: u32,
value: u32,
},
#[non_exhaustive]
Action {
id: FaultId,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BusRecord {
pub op: BusOp,
pub addr: u8,
pub first: Option<u8>,
pub written: u16,
pub read: u16,
pub result: Result<(), DdcErrorKind>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BusOp {
Write,
WriteRead,
Read,
ReadSegmented {
target: EddcTarget,
segment: u8,
},
}
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}")
}
}
}
}
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:?}"),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Actor {
Source,
Sink,
Test,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Ignored {
SinkOwned,
ReadOnly,
Hook,
}
#[derive(Debug)]
pub(crate) struct Transcript<const LOG: usize> {
records: [Option<Record>; LOG],
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,
}
}
pub(crate) const fn keeping_newest(mut self) -> Self {
self.keep_newest = true;
self
}
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)
}
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;
}
}
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),
..
}),
..
})
));
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));
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),
..
})
));
let mut none = Transcript::<0>::new().keeping_newest();
assert_eq!(none.push(note(1)), None);
assert_eq!(none.overflow(), 1);
}
}