Skip to content

Commit

Permalink
Fix OpenTTD#12509: Maintain timer sort invariants when changing period
Browse files Browse the repository at this point in the history
  • Loading branch information
JGRennison committed Apr 20, 2024
1 parent 2848d64 commit a3c8592
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/timer/timer.h
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class IntervalTimer : public BaseTimer<TTimerType> {
*/
void SetInterval(const TPeriod interval, bool reset = true)
{
this->period = interval;
TimerManager<TTimerType>::ChangeRegisteredTimerPeriod(*this, interval);
if (reset) this->storage = {};
}

Expand Down Expand Up @@ -150,7 +150,7 @@ class TimeoutTimer : public BaseTimer<TTimerType> {
*/
void Reset(const TPeriod timeout)
{
this->period = timeout;
TimerManager<TTimerType>::ChangeRegisteredTimerPeriod(*this, timeout);
this->fired = false;
this->storage = {};
}
Expand Down
14 changes: 14 additions & 0 deletions src/timer/timer_manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ class TimerManager {
GetTimers().erase(&timer);
}

/**
* Change the period of a registered timer.
*
* @param timer The timer to change the period of.
* @param new_period The new period value.
*/
static void ChangeRegisteredTimerPeriod(BaseTimer<TTimerType> &timer, TPeriod new_period)
{
/* Unregistration and re-registration is necessary because the period is used as the sort key in base_timer_sorter */
UnregisterTimer(timer);
timer.period = new_period;
RegisterTimer(timer);
}

#ifdef WITH_ASSERT
/**
* Validate that a new period is actually valid.
Expand Down

0 comments on commit a3c8592

Please sign in to comment.