use core::fmt;
use core::time::Duration;
use hdmi_hal::ddc::DdcErrorKind;
use hdmi_hal::time::Timestamp;
use crate::action::{Action, When};
use crate::phy::{PhyCall, PhyFault};
use crate::transcript::{BusOp, BusRecord};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Fault {
pub filter: Filter,
pub nth: u32,
pub times: Times,
pub effect: Effect,
pub point: Point,
}
impl Fault {
pub const fn new(effect: Effect) -> Self {
Self {
filter: Filter::ANY,
nth: 1,
times: Times::Count(1),
effect,
point: Point::Before,
}
}
#[must_use]
pub const fn on(self, filter: Filter) -> Self {
Self { filter, ..self }
}
#[must_use]
pub const fn nth(self, n: u32) -> Self {
Self { nth: n, ..self }
}
#[must_use]
pub const fn times(self, times: Times) -> Self {
Self { times, ..self }
}
#[must_use]
pub const fn at(self, point: Point) -> Self {
Self { point, ..self }
}
fn matches(&self, record: &BusRecord) -> bool {
self.filter.matches(record)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Filter {
pub addr: Option<u8>,
pub op: Option<OpKind>,
pub first: Option<u8>,
}
impl Filter {
pub const ANY: Self = Self {
addr: None,
op: None,
first: None,
};
#[must_use]
pub const fn with_addr(self, addr: u8) -> Self {
Self {
addr: Some(addr),
..self
}
}
#[must_use]
pub const fn with_op(self, op: OpKind) -> Self {
Self {
op: Some(op),
..self
}
}
#[must_use]
pub const fn with_first(self, first: u8) -> Self {
Self {
first: Some(first),
..self
}
}
}
impl Filter {
pub(crate) fn matches(&self, record: &BusRecord) -> bool {
self.addr.is_none_or(|addr| addr == record.addr)
&& self.op.is_none_or(|op| op == OpKind::of(record.op))
&& self.first.is_none_or(|first| Some(first) == record.first)
}
}
impl Default for Filter {
fn default() -> Self {
Self::ANY
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OpKind {
Write,
WriteRead,
Read,
ReadSegmented,
}
impl OpKind {
fn of(op: BusOp) -> Self {
match op {
BusOp::Write => Self::Write,
BusOp::WriteRead => Self::WriteRead,
BusOp::Read => Self::Read,
BusOp::ReadSegmented { .. } => Self::ReadSegmented,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Times {
Count(u32),
UntilCleared,
For(Duration),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Effect {
Fail(DdcErrorKind),
Slow(Duration),
Corrupt {
byte: u16,
xor: u8,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Point {
Before,
After,
Partway {
byte: u16,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FaultId(pub(crate) u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScheduleFull;
impl fmt::Display for ScheduleFull {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the fault schedule is full; clear a fault or give the bench more")
}
}
impl core::error::Error for ScheduleFull {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Strike {
pub(crate) id: FaultId,
pub(crate) effect: Effect,
pub(crate) point: Point,
}
#[derive(Debug, Clone, Copy)]
enum Kind<'a> {
Bus(Fault),
Phy(PhyFault),
Action(Action<'a>, When),
}
#[derive(Debug, Clone, Copy)]
struct Scheduled<'a> {
id: FaultId,
kind: Kind<'a>,
seen: u32,
first_at: Option<Timestamp>,
due: bool,
}
fn count(
seen: &mut u32,
first_at: &mut Option<Timestamp>,
nth: u32,
times: Times,
now: Timestamp,
) -> (bool, bool) {
*seen = seen.saturating_add(1);
let first = nth.max(1);
match times {
Times::For(window) => {
if *seen < first {
return (false, false);
}
let start = *first_at.get_or_insert(now);
let over = start.checked_add(window).is_none_or(|end| now >= end);
(!over, over)
}
Times::Count(count) => {
let end = first.saturating_add(count);
(*seen >= first && *seen < end, seen.saturating_add(1) >= end)
}
Times::UntilCleared => (*seen >= first, false),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Moment {
Before,
After,
Time,
}
#[derive(Debug)]
pub(crate) struct Schedule<'a, const FAULTS: usize> {
slots: [Option<Scheduled<'a>>; FAULTS],
next_id: u32,
}
impl<'a, const FAULTS: usize> Schedule<'a, FAULTS> {
pub(crate) const fn new() -> Self {
Self {
slots: [None; FAULTS],
next_id: 0,
}
}
fn insert(&mut self, kind: Kind<'a>) -> Result<FaultId, ScheduleFull> {
let slot = self
.slots
.iter_mut()
.find(|slot| slot.is_none())
.ok_or(ScheduleFull)?;
let id = FaultId(self.next_id);
self.next_id = self.next_id.wrapping_add(1);
*slot = Some(Scheduled {
id,
kind,
seen: 0,
first_at: None,
due: false,
});
Ok(id)
}
pub(crate) fn add(&mut self, fault: Fault) -> Result<FaultId, ScheduleFull> {
self.insert(Kind::Bus(fault))
}
pub(crate) fn add_phy(&mut self, fault: PhyFault) -> Result<FaultId, ScheduleFull> {
self.insert(Kind::Phy(fault))
}
pub(crate) fn add_action(
&mut self,
action: Action<'a>,
when: When,
) -> Result<FaultId, ScheduleFull> {
self.insert(Kind::Action(action, when))
}
pub(crate) fn phy_actions(&mut self, call: &PhyCall) {
for scheduled in self.slots.iter_mut().flatten() {
if let Kind::Action(_, When::PhyCall { kind, nth }) = scheduled.kind {
if kind.is_none_or(|kind| kind == call.kind()) {
let (now, _) = count(
&mut scheduled.seen,
&mut scheduled.first_at,
nth,
Times::Count(1),
Timestamp::from_micros(0),
);
scheduled.due |= now;
}
}
}
}
pub(crate) fn time_actions(&mut self, now: Timestamp) {
for scheduled in self.slots.iter_mut().flatten() {
if let Kind::Action(_, When::At(at)) = scheduled.kind {
scheduled.due |= now >= at;
}
}
}
pub(crate) fn take_due(&mut self, moment: Moment) -> Option<(FaultId, Action<'a>)> {
let slot = self.slots.iter_mut().find(|slot| match slot {
Some(Scheduled {
kind: Kind::Action(_, when),
due: true,
..
}) => match when {
When::BeforeOp { .. } => moment == Moment::Before,
When::AfterOp { .. } | When::PhyCall { .. } => moment == Moment::After,
When::At(_) => true,
},
_ => false,
})?;
let scheduled = slot.take()?;
match scheduled.kind {
Kind::Action(action, _) => Some((scheduled.id, action)),
_ => None,
}
}
pub(crate) fn remove(&mut self, id: FaultId) -> bool {
match self
.slots
.iter_mut()
.find(|slot| matches!(slot, Some(s) if s.id == id))
{
Some(slot) => {
*slot = None;
true
}
None => false,
}
}
pub(crate) fn clear(&mut self) {
self.slots = [None; FAULTS];
}
pub(crate) fn len(&self) -> usize {
self.slots.iter().flatten().count()
}
pub(crate) fn strike(&mut self, record: &BusRecord, now: Timestamp) -> Option<Strike> {
let mut strike = None;
for slot in self.slots.iter_mut() {
let Some(scheduled) = slot else {
continue;
};
let fault = match scheduled.kind {
Kind::Bus(fault) => fault,
Kind::Action(_, When::BeforeOp { filter, nth } | When::AfterOp { filter, nth }) => {
if filter.matches(record) {
let (now, _) = count(
&mut scheduled.seen,
&mut scheduled.first_at,
nth,
Times::Count(1),
Timestamp::from_micros(0),
);
scheduled.due |= now;
}
continue;
}
_ => continue,
};
if !fault.matches(record) {
continue;
}
let (strikes, last) = count(
&mut scheduled.seen,
&mut scheduled.first_at,
fault.nth,
fault.times,
now,
);
if strikes && strike.is_none() {
strike = Some(Strike {
id: scheduled.id,
effect: fault.effect,
point: fault.point,
});
}
if last {
*slot = None;
}
}
strike
}
pub(crate) fn strike_phy(&mut self, call: &PhyCall, now: Timestamp) -> Option<(FaultId, bool)> {
let mut strike = None;
for slot in self.slots.iter_mut() {
let Some(scheduled) = slot else {
continue;
};
let Kind::Phy(fault) = scheduled.kind else {
continue;
};
if !fault.matches(call) {
continue;
}
let (strikes, last) = count(
&mut scheduled.seen,
&mut scheduled.first_at,
fault.nth,
fault.times,
now,
);
if strikes && strike.is_none() {
strike = Some((scheduled.id, fault.took_effect));
}
if last {
*slot = None;
}
}
strike
}
}