1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
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 #include "udmf_utils.h"
16 #include <random>
17 #include <sstream>
18
19 namespace OHOS {
20 namespace UDMF {
21 namespace UTILS {
22 static constexpr int ID_LEN = 32;
23 static constexpr int MINIMUM = 48;
24 static constexpr int MAXIMUM = 121;
25 constexpr char SPECIAL = '^';
26
StrSplit(const std::string & str,const std::string & delimiter)27 std::vector<std::string> StrSplit(const std::string &str, const std::string &delimiter)
28 {
29 std::vector<std::string> result;
30 size_t start = 0;
31 size_t end = str.find(delimiter);
32 while (end != std::string::npos) {
33 result.push_back(str.substr(start, end - start));
34 start = end + delimiter.length();
35 end = str.find(delimiter, start);
36 }
37 result.push_back(str.substr(start));
38 return result;
39 }
40
Random(int32_t len,int32_t minimum,int32_t maximum)41 std::vector<uint8_t> Random(int32_t len, int32_t minimum, int32_t maximum)
42 {
43 std::random_device randomDevice;
44 std::uniform_int_distribution<int> distribution(minimum, maximum);
45 std::vector<uint8_t> key(len);
46 for (int32_t i = 0; i < len; i++) {
47 key[i] = static_cast<uint8_t>(distribution(randomDevice));
48 }
49 return key;
50 }
51
GenerateId()52 std::string GenerateId()
53 {
54 std::vector<uint8_t> randomDevices = Random(ID_LEN, MINIMUM, MAXIMUM);
55 std::stringstream idStr;
56 for (auto &randomDevice : randomDevices) {
57 auto asc = randomDevice;
58 asc = asc >= SPECIAL ? asc + 1 : asc;
59 idStr << static_cast<uint8_t>(asc);
60 }
61 return idStr.str();
62 }
63 } // namespace UTILS
64 } // namespace UDMF
65 } // namespace OHOS