UUID的封装类

UUID,即通用唯一识别码,产生的随机数据重复概率几乎为零,平时写程序的时候还是会用到,所以封装了一下,使用起来更简单了。
头文件:

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
namespace God {  

struct Uuid {
public:
DEFINE_PTR(Uuid);
typedef uint16_t size_type;

enum {
UUID_LENGTH = sizeof(uuid_t),
};

public:
Uuid(bool empty = false) {
reset(empty);
}

Uuid(const byte_t *data, size_type len) {
reset(data, len);
}

Uuid(const std::string &str) {
reset(str.c_str());
}

Uuid(const char *str) {
reset(str);
}

void reset(bool empty = false);

void reset(const byte_t *data, size_type len);

void reset(const std::string &str) {
reset(str.c_str());
}

void reset(const char *str);

bool empty() const;

size_type toByteArray(byte_t *data, size_type len) const;

std::string toString() const;

bool operator < (const Uuid &rhs) const;

bool operator == (const Uuid &rhs) const;

bool operator != (const Uuid &rhs) const;

public:
const static Uuid Empty;

private:
uuid_t m_data;
};

}

实现文件:

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
namespace God {  

const Uuid Uuid::Empty(true);

void Uuid::reset(bool empty) {
if (empty) {
uuid_clear(m_data);
} else {
uuid_generate(m_data);
}
}

void Uuid::reset(const byte_t *data, size_type len) {
if (len != (size_type)UUID_LENGTH) {
GOD_THROW_EXCEPTION(InvalidArgumentException("len"));
}
memcpy(m_data, data, (size_type)UUID_LENGTH);
}

void Uuid::reset(const char *str) {
if (uuid_parse(str, m_data) == -1) {
GOD_THROW_EXCEPTION_FROM_LAST_ERROR_WITH_API("uuid_parse");
}
}

bool Uuid::empty() const {
return uuid_is_null(m_data) != 0;
}

Uuid::size_type Uuid::toByteArray(byte_t *data, size_type len) const {
size_type copyLen = std::min(len, (size_type)UUID_LENGTH);
memcpy(data, m_data, copyLen);
return copyLen;
}

std::string Uuid::toString() const {
return hexstringFromData(m_data, (size_type)UUID_LENGTH);
}

bool Uuid::operator < (const Uuid &rhs) const {
return memcmp(m_data, rhs.m_data, (size_type)UUID_LENGTH) < 0;
}

bool Uuid::operator == (const Uuid &rhs) const {
return memcmp(m_data, rhs.m_data, (size_type)UUID_LENGTH) == 0;
}

bool Uuid::operator != (const Uuid &rhs) const {
return memcmp(m_data, rhs.m_data, (size_type)UUID_LENGTH) != 0;
}

}

有需要的直接拿去用吧,呵呵..

文章目录