use core::ops::Deref;
use super::{Event, EventList};
#[expect(
clippy::cast_precision_loss,
reason = "the limit is compared with a float, as in the C library"
)]
const MAX_TIME_SEC: f32 = (u32::MAX / 1000) as f32;
#[derive(Clone, Debug)]
pub struct EventListPlayer<T> {
events: T,
current_index: usize,
}
impl<T: Deref<Target = EventList>> EventListPlayer<T> {
pub const fn new(events: T) -> Self {
Self {
events,
current_index: 0,
}
}
pub fn events(&self) -> &EventList {
&self.events
}
pub const fn current_index(&self) -> usize {
self.current_index
}
pub fn peek_next_event(&self) -> Option<&Event> {
self.events.get(self.current_index)
}
pub fn next_event(&mut self) -> Option<&Event> {
let event = self.events.get(self.current_index)?;
self.current_index += 1;
Some(event)
}
pub fn next_event_not_later_than(&mut self, time_sec: f32) -> Option<&Event> {
if time_sec.is_nan() || time_sec < 0.0 {
return None;
}
let time_msec = sec_to_msec(time_sec);
let event = self
.events
.get(self.current_index)
.filter(|event| event.time_msec <= time_msec)?;
self.current_index += 1;
Some(event)
}
pub const fn rewind(&mut self) {
self.current_index = 0;
}
pub fn seek(&mut self, time_sec: f32) {
self.current_index = 0;
if time_sec.is_nan() || time_sec <= 0.0 {
return;
}
let time_msec = sec_to_msec(time_sec);
while self
.events
.get(self.current_index)
.is_some_and(|event| event.time_msec < time_msec)
{
self.current_index += 1;
}
}
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "the time is non-negative and below the limit, and is truncated as in the C library"
)]
fn sec_to_msec(time_sec: f32) -> u32 {
if time_sec > MAX_TIME_SEC {
u32::MAX
} else {
(time_sec * 1000.0) as u32
}
}