#![allow(dead_code)]
use ek_event::{Event, EventEngine, HandlerId};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
pub struct Capture<T> {
inner: Arc<Mutex<Vec<T>>>,
}
impl<T: Clone + Send + Sync + 'static> Capture<T> {
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn register_on(&self, eng: &EventEngine, key: impl Into<String>) -> HandlerId {
let inner = Arc::clone(&self.inner);
eng.register(
key.into(),
Arc::new(move |e: &Event| {
if let Some(d) = e.data.downcast_ref::<T>() {
inner.lock().unwrap().push(d.clone());
}
}),
)
}
pub fn len(&self) -> usize {
self.inner.lock().unwrap().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn all(&self) -> Vec<T> {
self.inner.lock().unwrap().clone()
}
pub fn last(&self) -> Option<T> {
self.inner.lock().unwrap().last().cloned()
}
pub fn drain(&self) -> Vec<T> {
std::mem::take(&mut *self.inner.lock().unwrap())
}
}
pub fn wait_until(timeout: Duration, mut f: impl FnMut() -> bool) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if f() {
return true;
}
std::thread::sleep(Duration::from_millis(5));
}
f()
}
pub fn drained(eng: &EventEngine, n: usize) -> Capture<i32> {
let s = Capture::<i32>::new();
s.register_on(eng, "eTest.settle.");
for i in 0..n {
eng.put(Event::with_data("eTest.settle.", Arc::new(i as i32)))
.unwrap();
}
s
}
pub mod fixture {
use ek_data::{DtNs, parse_civil};
pub fn t0() -> DtNs {
parse_civil("2024-12-25 09:30:01.500000000").expect("fixed scene time")
}
}