79 lines
1.9 KiB
C++
79 lines
1.9 KiB
C++
#include "Uuid.h"
|
|
|
|
#include "bts_array_size.h"
|
|
#include "bts_assert.h"
|
|
#include "lib/os/os.h"
|
|
#include <algorithm>
|
|
#include <cstring>
|
|
#include <sstream>
|
|
|
|
namespace bts {
|
|
namespace utils {
|
|
|
|
std::string uuid() { return Uuid().to_text_string(); }
|
|
|
|
Uuid::Uuid(std::string const &uuid, bool is_byte_string) {
|
|
if (is_byte_string) {
|
|
bts_assert(uuid.size() == sizeof(_id));
|
|
std::copy(uuid.begin(), uuid.end(), _id);
|
|
} else {
|
|
std::istringstream in(uuid);
|
|
in >> *this;
|
|
}
|
|
}
|
|
|
|
Uuid::~Uuid() {}
|
|
|
|
Uuid::Uuid() { os::gen_uuid(_id); }
|
|
|
|
std::string Uuid::to_byte_string() const {
|
|
std::string publisher_id_string(BTS_ARRAYSIZE(_id), 0);
|
|
std::copy(_id, _id + BTS_ARRAYSIZE(_id), publisher_id_string.begin());
|
|
return publisher_id_string;
|
|
}
|
|
|
|
std::string Uuid::to_text_string() const {
|
|
std::ostringstream out;
|
|
out << *this;
|
|
return out.str();
|
|
}
|
|
|
|
std::istream &operator>>(std::istream &stream, Uuid &sid) {
|
|
for (size_t i = 0; i < sizeof(sid._id); i++) {
|
|
char high_nibble, low_nibble;
|
|
stream >> high_nibble >> low_nibble;
|
|
if (high_nibble >= 'a')
|
|
high_nibble = high_nibble - 'a' + 10;
|
|
else
|
|
high_nibble -= '0';
|
|
|
|
if (low_nibble >= 'a')
|
|
low_nibble = low_nibble - 'a' + 10;
|
|
else
|
|
low_nibble -= '0';
|
|
sid._id[i] = (high_nibble << 4) + low_nibble;
|
|
}
|
|
return stream;
|
|
}
|
|
|
|
std::ostream &operator<<(std::ostream &stream, Uuid const &sid) {
|
|
for (size_t i = 0; i < sizeof(sid._id); i++) {
|
|
char high_nibble = (sid._id[i] & 0xf0) >> 4;
|
|
char low_nibble = sid._id[i] & 0x0f;
|
|
if (high_nibble >= 10)
|
|
high_nibble = (high_nibble - 10) + 'a';
|
|
else
|
|
high_nibble += '0';
|
|
if (low_nibble >= 10)
|
|
low_nibble = (low_nibble - 10) + 'a';
|
|
else
|
|
low_nibble += '0';
|
|
stream << high_nibble << low_nibble;
|
|
}
|
|
|
|
return stream;
|
|
}
|
|
|
|
} // namespace utils
|
|
} // namespace bts
|