use std::fmt::Display;
#[derive(Debug)]
pub struct Tick {
tick: u64,
log: bool,
}
impl Tick {
pub(crate) const fn start() -> Self {
Self {
tick: 0,
log: false,
}
}
pub const fn log(&mut self, log: bool) {
self.log = log;
}
pub fn advance(&mut self) {
self.advance_by(1);
}
pub fn advance_by(&mut self, ticks: u64) {
self.tick = self.tick.checked_add(ticks).expect("Tick overflow. Well done you've found an exploit! Or you would have if `https://github.com/albertsgarde/rustorio/issues/3` hadn't beaten you to it!");
if self.log {
println!("{self}");
}
}
pub fn advance_to_tick(&mut self, target_tick: u64) {
if target_tick > self.tick {
self.advance_by(target_tick - self.tick);
}
}
pub fn advance_until<F>(&mut self, mut condition: F, max_ticks: u64) -> bool
where
F: FnMut(&Tick) -> bool,
{
let start_tick = self.tick;
while !condition(self) && self.tick - start_tick < max_ticks {
self.advance();
}
self.tick - start_tick < max_ticks
}
pub const fn cur(&self) -> u64 {
self.tick
}
}
impl From<&Tick> for u64 {
fn from(tick: &Tick) -> Self {
tick.tick
}
}
impl PartialOrd<u64> for &Tick {
fn partial_cmp(&self, other: &u64) -> Option<std::cmp::Ordering> {
Some(self.tick.cmp(other))
}
}
impl PartialOrd<&Tick> for u64 {
fn partial_cmp(&self, other: &&Tick) -> Option<std::cmp::Ordering> {
Some(self.cmp(&other.tick))
}
}
impl PartialEq<u64> for &Tick {
fn eq(&self, other: &u64) -> bool {
self.tick == *other
}
}
impl PartialEq<&Tick> for u64 {
fn eq(&self, other: &&Tick) -> bool {
*self == other.tick
}
}
impl Display for Tick {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Tick {}", self.tick)
}
}