UUID,即通用惟一识别码,产生的随机数据重复几率几乎为零,平时写程序的时候仍是会用到,因此封装了一下,使用起来更简单了。
头文件:并发
- 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;
- };
-
- }
实现文件:高并发
- 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;
- }
-
- }
想偷懒的直接拿去用吧,呵呵..ui
详情请访问libgod官网..spa