| 6 |
| 7 | #include "base/atomic_sequence_num.h" |
| 8 | #include "base/logging.h" |
| 9 | #include "base/rand_util.h" |
| 10 |
| 11 | namespace base { |
| 12 |
| 13 | namespace { |
| 14 |
| 15 | const int64_t kLowBitsMask = (INT64_C(1) << 32) - 1; |
| 16 | const int64_t kNumTypeBits = static_cast<int64_t>(UkmSourceId::Type::kMaxValue); |
| 17 | const int64_t kTypeMask = (INT64_C(1) << kNumTypeBits) - 1; |
| 18 |
| 19 | } // namespace |
| 20 |
| 21 | // static |
| 22 | UkmSourceId UkmSourceId::New() { |
| 23 | // Generate some bits which are unique to this process, so we can generate |
| 24 | // IDs independently in different processes. IDs generated by this method may |
| 25 | // collide, but it should be sufficiently rare enough to not impact data |
| 26 | // quality. |
| 27 | const static int64_t process_id_bits = |
| 28 | static_cast<int64_t>(RandUint64()) & ~kLowBitsMask; |
| 29 | // Generate some bits which are unique within the process, using a counter. |
| 30 | static AtomicSequenceNumber seq; |
| 31 | UkmSourceId local_id = FromOtherId(seq.GetNext() + 1, UkmSourceId::Type::UKM); |
| 32 | // Combine the local and process bits to generate a unique ID. |
| 33 | return UkmSourceId((local_id.value_ & kLowBitsMask) | process_id_bits); |
| 34 | } |
| 35 |
| 36 | // static |
| 37 | UkmSourceId UkmSourceId::FromOtherId(int64_t other_id, UkmSourceId::Type type) { |
| 38 | const int64_t type_bits = static_cast<int64_t>(type); |
| 39 | DCHECK_EQ(type_bits, type_bits & kTypeMask); |
| 40 | // Stores the the type ID in the low bits of the source id, and shift the rest |
| 41 | // of the ID to make room. This could cause the original ID to overflow, but |
| 42 | // that should be rare enough that it won't matter for UKM's purposes. |
| 43 | return UkmSourceId((other_id << kNumTypeBits) | type_bits); |
| 44 | } |
| 45 |
| 46 | UkmSourceId::Type UkmSourceId::GetType() const { |
| 47 | return static_cast<UkmSourceId::Type>(value_ & kTypeMask); |
| 48 | } |
| 49 |
| 50 | } // namespace base |
| 51 |