1 | /** |
2 | * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | * |
16 | * \author guonix |
17 | * \date Nov 2020 |
18 | * \brief |
19 | */ |
20 | |
21 | #include "uuid_helper.h" |
22 | #include <iostream> |
23 | #include <random> |
24 | #include <sstream> |
25 | #include <ailego/utility/string_helper.h> |
26 | |
27 | namespace proxima { |
28 | namespace be { |
29 | |
30 | static uint32_t random_char() { |
31 | std::random_device rd; |
32 | std::mt19937 gen(rd()); |
33 | std::uniform_int_distribution<> dis(0, 255); |
34 | return dis(gen); |
35 | } |
36 | |
37 | std::string gen_uuid(const std::string &sep) { |
38 | return ailego::StringHelper::Concat(generate_hex(4), sep, generate_hex(2), |
39 | sep, generate_hex(2), sep, |
40 | generate_hex(8)); |
41 | } |
42 | |
43 | bool valid_uuid(const std::string &uuid) { |
44 | return uuid.length() == 32; |
45 | } |
46 | |
47 | std::string generate_hex(const uint32_t len) { |
48 | std::stringstream ss; |
49 | for (uint32_t i = 0; i < len; i++) { |
50 | const auto rc = random_char(); |
51 | std::stringstream stream; |
52 | stream << std::hex << rc; |
53 | auto hex = stream.str(); |
54 | ss << (hex.length() < 2 ? '0' + hex : hex); |
55 | } |
56 | return ss.str(); |
57 | } |
58 | |
59 | } // namespace be |
60 | } // namespace proxima |