use crate::{MainWindow, RetargetModel};
use slint::ComponentHandle;
use std::{cell::RefCell, collections::BTreeMap};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(in crate::gui::editor) enum ResultKind {
Retarget,
}
thread_local! {
static STAMPS: RefCell<BTreeMap<ResultKind, u64>> = const { RefCell::new(BTreeMap::new()) };
}
pub(in crate::gui::editor) fn stamp(kind: ResultKind, generation: u64) {
STAMPS.with(|cell| {
cell.borrow_mut().insert(kind, generation);
});
}
pub(in crate::gui::editor) fn clear(kind: ResultKind) {
STAMPS.with(|cell| {
cell.borrow_mut().remove(&kind);
});
}
pub(in crate::gui::editor) fn refresh_badges(ui: &MainWindow, live_generation: u64) {
let stamped = |kind: ResultKind| STAMPS.with(|cell| cell.borrow().get(&kind).copied());
ui.global::<RetargetModel>()
.set_stale(super::state::result_is_stale(
stamped(ResultKind::Retarget),
live_generation,
));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_kind_with_no_stamp_is_never_stale() {
STAMPS.with(|cell| cell.borrow_mut().clear());
assert_eq!(
STAMPS.with(|cell| cell.borrow().get(&ResultKind::Retarget).copied()),
None
);
}
#[test]
fn stamping_then_reading_back_the_same_generation_round_trips() {
STAMPS.with(|cell| cell.borrow_mut().clear());
stamp(ResultKind::Retarget, 7);
assert_eq!(
STAMPS.with(|cell| cell.borrow().get(&ResultKind::Retarget).copied()),
Some(7)
);
}
#[test]
fn clearing_a_stamped_kind_forgets_it() {
STAMPS.with(|cell| cell.borrow_mut().clear());
stamp(ResultKind::Retarget, 3);
clear(ResultKind::Retarget);
assert_eq!(
STAMPS.with(|cell| cell.borrow().get(&ResultKind::Retarget).copied()),
None
);
}
#[test]
fn restamping_overwrites_the_previous_generation() {
STAMPS.with(|cell| cell.borrow_mut().clear());
stamp(ResultKind::Retarget, 1);
stamp(ResultKind::Retarget, 2);
assert_eq!(
STAMPS.with(|cell| cell.borrow().get(&ResultKind::Retarget).copied()),
Some(2)
);
}
#[test]
fn result_is_stale_agrees_with_a_stamped_then_moved_generation() {
STAMPS.with(|cell| cell.borrow_mut().clear());
stamp(ResultKind::Retarget, 5);
let stamped = STAMPS.with(|cell| cell.borrow().get(&ResultKind::Retarget).copied());
assert!(!super::super::state::result_is_stale(stamped, 5));
assert!(super::super::state::result_is_stale(stamped, 6));
}
}