aboutsummaryrefslogtreecommitdiff
path: root/source/10-common/Uid.cpp
blob: 58dfffdacbbbc2a755254cffabef8d9b2ec1e589 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "Uid.hpp"

#include "RapidJsonHelper.hpp"

#include <rapidjson/document.h>
#include <cstring>
#include <random>

Uid Uid::Create() {
	std::random_device rd;
	std::mt19937_64 gen(rd());
	std::uniform_int_distribution<uint64_t> dist(
		std::numeric_limits<uint64_t>::min(),
		std::numeric_limits<uint64_t>::max());

	Uid uid;
	uid.upper = dist(gen);
	uid.lower = dist(gen);
	return uid;
}

bool Uid::IsNull() const {
	return upper == 0 && lower == 0;
}

void Uid::ReadString(std::string_view str) {
	sscanf(str.data(), BRUSSEL_Uid_SCAN_STR, &upper, &lower);
}

std::string Uid::WriteString() {
	char buf[256];
	snprintf(buf, sizeof(buf), BRUSSEL_Uid_FORMAT_STR, upper, lower);
	return std::string(buf);
}

void Uid::Read(const rapidjson::Value& value) {
	if (value.IsString()) {
		ReadString(rapidjson::AsStringView(value));
	} else if (value.IsArray()) {
		// Compatibility support
		assert(value.Size() == 2);
		auto& upper = value[0];
		assert(upper.IsUint64());
		auto& lower = value[1];
		assert(lower.IsUint64());

		this->upper = upper.GetUint64();
		this->lower = lower.GetUint64();
	} else {
		assert(false);
	}
}

void Uid::WriteInto(rapidjson::Value& value, rapidjson::Document& root) const {
#if BRUSSEL_Uid_WRITE_USE_ARRAY
	value.Reserve(2, root.GetAllocator());
	value.PushBack((uint64_t)upper, root.GetAllocator());
	value.PushBack((uint64_t)lower, root.GetAllocator());
#else
	char buf[256];
	int len = snprintf(buf, sizeof(buf), BRUSSEL_Uid_FORMAT_STR, upper, lower);
	value.SetString(buf, len, root.GetAllocator());
#endif
}

rapidjson::Value Uid::Write(rapidjson::Document& root) const {
	rapidjson::Value result(rapidjson::kArrayType);
	WriteInto(result, root);
	return result;
}