Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 2 additions & 49 deletions include/condy/detail/context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,69 +5,22 @@
#pragma once

#include "condy/detail/singleton.hpp"
#include <cassert>
#include <cstdint>

namespace condy {

class Runtime;

namespace detail {

template <typename T, T From = 0, T To = std::numeric_limits<T>::max()>
class IdPool {
public:
static_assert(From < To, "Invalid ID range");

T allocate() {
if (!recycled_ids_.empty()) {
T id = recycled_ids_.top();
recycled_ids_.pop();
return id;
}
if (next_id_ < To) {
return next_id_++;
}
throw std::runtime_error("ID pool exhausted");
}

void recycle(T id) noexcept {
assert(From <= id && id < next_id_ && id < To);
recycled_ids_.push(id);
}

void reset() noexcept {
next_id_ = From;
while (!recycled_ids_.empty()) {
recycled_ids_.pop();
}
}

private:
T next_id_ = From;
std::stack<T> recycled_ids_;
};

class Context : public ThreadLocalSingleton<Context> {
public:
void init(Runtime *runtime) noexcept {
runtime_ = runtime;
bgid_pool_.reset();
}
void reset() noexcept {
runtime_ = nullptr;
bgid_pool_.reset();
}
void init(Runtime *runtime) noexcept { runtime_ = runtime; }
void reset() noexcept { runtime_ = nullptr; }

Runtime *runtime() noexcept { return runtime_; }

uint16_t next_bgid() { return bgid_pool_.allocate(); }

void recycle_bgid(uint16_t bgid) noexcept { bgid_pool_.recycle(bgid); }

private:
Runtime *runtime_ = nullptr;
IdPool<uint16_t> bgid_pool_;
};

} // namespace detail
Expand Down
34 changes: 34 additions & 0 deletions include/condy/detail/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,40 @@ template <typename Func> auto defer(Func &&func) {
return Defer<std::decay_t<Func>>(std::forward<Func>(func));
}

template <typename T, T From = 0, T To = std::numeric_limits<T>::max()>
class IdPool {
public:
static_assert(From < To, "Invalid ID range");

T allocate() {
if (!recycled_ids_.empty()) {
T id = recycled_ids_.top();
recycled_ids_.pop();
return id;
}
if (next_id_ < To) {
return next_id_++;
}
throw std::runtime_error("ID pool exhausted");
}

void recycle(T id) noexcept {
assert(From <= id && id < next_id_ && id < To);
recycled_ids_.push(id);
}

void reset() noexcept {
next_id_ = From;
while (!recycled_ids_.empty()) {
recycled_ids_.pop();
}
}

private:
T next_id_ = From;
std::stack<T> recycled_ids_;
};

[[noreturn]] inline void panic_on(std::string_view msg) noexcept {
std::cerr << std::format("Panic: {}\n", msg);
#ifndef CRASH_TEST
Expand Down
Loading
Loading