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