Skip to content

Commit

Permalink
Introduce id_dispenser class
Browse files Browse the repository at this point in the history
  • Loading branch information
pwojcikdev committed Sep 26, 2023
1 parent a40bdcd commit 91dba8d
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions nano/lib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ add_library(
epoch.cpp
errors.hpp
errors.cpp
id_dispenser.hpp
ipc.hpp
ipc.cpp
ipc_client.hpp
Expand Down
62 changes: 62 additions & 0 deletions nano/lib/id_dispenser.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#pragma once

#include <atomic>
#include <random>

namespace nano
{
class id_dispenser
{
public:
enum class mode
{
sequential,
random,
};

// Using pointer type for prettier and more concise output in logs (hex)
using id_t = void *;

public:
explicit id_dispenser (mode mode = mode::random) :
mode_m{ mode }
{
}

id_t next_id ()
{
switch (mode_m)
{
case mode::sequential:
return reinterpret_cast<id_t> (current_id_m.fetch_add (1));
case mode::random:
auto value = get_dist () (get_rng ());
if (value < min_m)
{
value += min_m;
}
return reinterpret_cast<id_t> (value);
}
return 0;
}

private:
// Avoid IDs with leading 0s for nicer output in logs
static constexpr uint64_t min_m{ 0x1000000000000000 };

mode mode_m;
std::atomic<uint64_t> current_id_m{ min_m };

static std::mt19937 & get_rng ()
{
static thread_local std::mt19937 rng{ std::random_device{}() };
return rng;
}

static std::uniform_int_distribution<uint64_t> & get_dist ()
{
static thread_local std::uniform_int_distribution<uint64_t> dist;
return dist;
}
};
}

0 comments on commit 91dba8d

Please sign in to comment.