Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "idManager.h"
- #include <random>
- #include <iostream>
- #include <chrono>
- #include "utils.h"
- #define ID_BYTES 4
- #define ID_LENGTH (ID_BYTES) * 8
- using namespace std;
- using namespace std::chrono;
- unsigned long long flipOrder(unsigned long long l) {
- unsigned long long res;
- int numOfBits = sizeof(long long) * 8;
- while (numOfBits-- > 0) {
- res <<= 1;
- res ^= l & 1;
- l >>= 1;
- }
- return res;
- }
- class RandomIdGenerator {
- private:
- minstd_rand _engine;
- uniform_int_distribution<char> _distribution; // a byte distribution
- public:
- RandomIdGenerator() : _distribution(0, 255) {
- // use current microseconds as a seed for the random generator
- chrono::microseconds ms = duration_cast<chrono::microseconds>(system_clock::now().time_since_epoch());
- unsigned long long seed = flipOrder(ms.count());
- _engine.seed(seed);
- }
- string randomId() {
- string output;
- int bytesRemaining = ID_BYTES;
- while (bytesRemaining-- > 0)
- output += _distribution(_engine);
- return output;
- }
- };
- RandomIdGenerator idGen;
- map<string, ID*> ids = { };
- bool idExists(const string& id) {
- // ids.find(id) returns ids.end() iff ids doesn't contain id
- return ids.find(id) != ids.end();
- }
- ID* getId(const string& id) {
- // this function gets a pointer to a given existing id
- return ids[id];
- }
- void registerId(const string& id) {
- // this function registers an id as a used id
- if (idExists(id)) {
- throw "Id already exists!";
- }
- ids[id] = nullptr;
- }
- void setId(const string& id, ID* object) {
- // this function adds an id object to the map
- ids[id] = object;
- }
- string nextId(const string& prefix) {
- // this function generates a new id
- string id;
- bool keep;
- do {
- id = prefix + idGen.randomId();
- keep = idExists(id);
- } while (idExists(id));
- return id;
- }
- BaseID::BaseID() : _id(nextId(string(""))) {
- setId(_id, this);
- }
- BaseID::BaseID(const type_info& type) : _id(nextId(type.name())) {
- setId(_id, this);
- }
- BaseID::BaseID(string& id) : _id(id) {
- setId(_id, this);
- }
- string BaseID::getID() {
- return _id;
- }
- BaseID::~BaseID() { /* empty destructor */ }
- ostream& operator<<(ostream& out, ID& id) {
- printHexValue(out, id.getID());
- return out;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement