Converting from UUID timestamp to seconds since EPOCH seems quite easy based on the specs, also based on Cassandra's C++ driver source code based on its struct definition.
However, when I try to do it, I always get the wrong value. I'm doing something wrong and I'm unable to figure out what it's.
For that, I used sample UUID values provided from here and here.
All one has to do is take the first uint64_t
from the UUID raw data, mask its first four MSb, subtract a difference and divide by a number.
Here's my minimum complete example:
#include <boost/date_time.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <cstdint>
#include <iostream>
uint64_t TimestampFromUUID(const boost::uuids::uuid& uuid) {
static constexpr const int UUID_SIZE = 16;
static_assert(sizeof(uuid) == UUID_SIZE, "Invalid size of uuid");
static constexpr const int MS_FROM_100NS_FACTOR = 10000;
static constexpr const uint64_t OFFSET_FROM_15_10_1582_TO_EPOCH = 122192928000000000;
struct two64s {
uint64_t n1;
uint64_t n2;
} contents;
std::memcpy(&contents, uuid.data, UUID_SIZE);
// contents.n1 = __builtin_bswap64(contents.n1);
uint64_t timestamp = contents.n1 & UINT64_C(0x0FFFFFFFFFFFFFFF);
return (timestamp - OFFSET_FROM_15_10_1582_TO_EPOCH) / MS_FROM_100NS_FACTOR;
}
int main() {
std::cout << "Time now: " << (boost::posix_time::second_clock::universal_time() - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_milliseconds() << std::endl;
auto gen = boost::uuids::string_generator();
std::cout << "UUID: " << gen("49cbda60-961b-11e8-9854-134d5b3f9cf8") << std::endl;
std::cout << "Time from UUID: " << TimestampFromUUID(gen("49cbda60-961b-11e8-9854-134d5b3f9cf8")) << std::endl;
std::cout << "UUID: " << gen("58e0a7d7-eebc-11d8-9669-0800200c9a66") << std::endl;
std::cout << "Time from UUID: " << TimestampFromUUID(gen("58e0a7d7-eebc-11d8-9669-0800200c9a66")) << std::endl;
return 0;
}
The output of this program is:
Time now: 1571735685000
UUID: 49cbda60-961b-11e8-9854-134d5b3f9cf8
Time from UUID: 45908323159150
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
Time from UUID: 45926063291384
You can play with this source code here.
Why are my results not even close to current timestamp? What am I doing wrong?