forked from nanocurrency/nano-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a40bdcd
commit 91dba8d
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -36,6 +36,7 @@ add_library( | |
epoch.cpp | ||
errors.hpp | ||
errors.cpp | ||
id_dispenser.hpp | ||
ipc.hpp | ||
ipc.cpp | ||
ipc_client.hpp | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; | ||
} |