-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuuid.hpp
95 lines (77 loc) · 1.97 KB
/
uuid.hpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// Guid.hpp
// ncc
//
// Created by yuki on 2022/04/28.
//
#ifndef Guid_hpp
#define Guid_hpp
#pragma once
#include <sstream>
#include <random>
#include <stdint.h>
#include <array>
/**
* UUID(GUID)を表すクラス
*/
class Uuid
{
public:
Uuid() = default;
~Uuid() = default;
Uuid(const Uuid&) = default;
Uuid& operator=(const Uuid&) = default;
Uuid(Uuid&&) = default;
Uuid& operator=(Uuid&&) = default;
// 新しいUUIDを生成する
static Uuid newUuid();
// データを文字列として取り出す。"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"形式
std::string toString();
// データを16バイトのストリームとして取り出す
std::array<unsigned char, 16> toByte();
// 比較演算子
bool operator==(const Uuid& a);
bool operator!=(const Uuid& a);
private:
// データ管理用のコンテナ
union _TempU64
{
uint64_t a;
uint32_t b[2];
uint16_t c[4];
unsigned char d[8];
};
// 一意正性を確保するためインスタンスは全部共有
static bool isInit;
static std::mt19937 mt;
static std::uniform_int_distribution<uint64_t> range;
// C#のGUIDと同じデータ構造を取る
uint32_t a;
uint16_t b;
uint16_t c;
unsigned char d[8];
// UIntSplitを乱数で埋めて返す
static _TempU64 gen();
// 16進変換 + 上位不足桁をゼロ埋め
template<typename CNT>
static std::string toHex(CNT value);
static std::string toHex(unsigned char value[], size_t vsize);
};
template<typename CNT>
inline std::string Uuid::toHex(CNT value)
{
int size = sizeof(value);
std::stringstream ss;
ss << std::hex << (int)value;
std::string str = ss.str();
std::string temp = "";
if (str.length() < size)
{
for (int i = 0; i < size - str.length(); i++)
{
temp.append("0");
}
}
return temp + str;
}
#endif /* Guid_hpp */