Skip to content
Repos

DevPlaceApp

C++ 1.5 KB60 lines Opens in site

Directory Raw Download

#include "core/Timer.hpp"

#include <SDL3/SDL.h>

#include <atomic>
#include <memory>

#include "core/Log.hpp"
#include "core/UiQueue.hpp"
#include "spec/MockSpec.hpp"

namespace dp {

namespace {

struct Slot {
  std::function<void()> fn;
  CancelPtr cancel;
};

std::atomic<unsigned> g_pending{0};

Uint32 onTimer(void* userdata, SDL_TimerID, Uint32) {
  auto* holder = static_cast<std::shared_ptr<Slot>*>(userdata);
  std::shared_ptr<Slot> slot = *holder;
  delete holder;
  UiQueue::instance().post([slot] {
    g_pending.fetch_sub(1);
    if (!slot->cancel->cancelled()) slot->fn();
  });
  return 0;
}

}  // namespace

unsigned Timer::pending() { return g_pending.load(); }

CancelPtr Timer::after(unsigned delayMs, std::function<void()> fn) {
  auto cancel = std::make_shared<CancelToken>();
  if (g_pending.load() >= spec::TimerLimits::kMaxPending) {
    Log::warn("timer refused: pending cap reached");
    cancel->cancel();
    return cancel;
  }
  if (delayMs > spec::TimerLimits::kMaxDelayMs) delayMs = spec::TimerLimits::kMaxDelayMs;
  auto slot = std::make_shared<Slot>(Slot{std::move(fn), cancel});
  g_pending.fetch_add(1);
  auto* holder = new std::shared_ptr<Slot>(slot);
  if (SDL_AddTimer(delayMs == 0 ? 1 : delayMs, onTimer, holder) == 0) {
    Log::error(std::string("SDL_AddTimer failed: ") + SDL_GetError());
    delete holder;
    UiQueue::instance().post([slot] {
      g_pending.fetch_sub(1);
      if (!slot->cancel->cancelled()) slot->fn();
    });
  }
  return cancel;
}

}  // namespace dp
44.3ms