Action Engine
Loading...
Searching...
No Matches
random.h
1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef ACTIONENGINE_UTIL_RANDOM_H_
16#define ACTIONENGINE_UTIL_RANDOM_H_
17
18#include <iomanip>
19#include <sstream>
20#include <string>
21
22#include <absl/random/distributions.h>
23#include <absl/random/random.h>
24
25namespace act {
26
27inline std::string GenerateUUID4() {
28 // TODO(hpnkv): Check this for correctness
29 absl::BitGen gen; // Abseil random number generator
30
31 // Generate 16 random bytes
32 std::array<uint8_t, 16> bytes{};
33 for (int i = 0; i < 16; ++i) {
34 bytes[i] = absl::Uniform<int>(gen, 0, 256); // Generate random byte (0-255)
35 }
36
37 // Set the version (UUID version 4) - The 7th nibble (most significant nibble of 13th byte) must be 4
38 bytes[6] = (bytes[6] & 0x0f) | 0x40;
39
40 // Set the variant (the 9th nibble must be 8, 9, A, or B)
41 bytes[8] = (bytes[8] & 0x3f) | 0x80;
42
43 // Convert to string (UUID format: 8-4-4-4-12)
44 std::ostringstream oss;
45 for (size_t i = 0; i < bytes.size(); ++i) {
46 if (i == 4 || i == 6 || i == 8 || i == 10) {
47 oss << "-";
48 }
49 oss << std::hex << std::setw(2) << std::setfill('0')
50 << static_cast<int>(bytes[i]);
51 }
52
53 return oss.str();
54}
55
56} // namespace act
57
58#endif // ACTIONENGINE_UTIL_RANDOM_H_