1 /*
2 * Copyright (c) 2022 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
16 #include "dm_random.h"
17
18 #include <random>
19
20 #include "dm_log.h"
21
22 #if defined(__LITEOS_M__)
23 #include <time.h>
24 #endif
25
26 namespace OHOS {
27 namespace DistributedHardware {
28 namespace {
29 const int32_t DM_MIN_RANDOM = 1;
30 const int32_t DM_MAX_RANDOM_UINT16 = INT16_MAX;
31 const int32_t DM_INVALID_FLAG_ID = 0;
32 }
33
GenRandInt(int32_t randMin,int32_t randMax)34 int32_t GenRandInt(int32_t randMin, int32_t randMax)
35 {
36 #if defined(__LITEOS_M__)
37 srandom(time(NULL));
38 return (randMin + random() % (randMax - randMin));
39 #else
40 std::random_device randDevice;
41 std::mt19937 genRand(randDevice());
42 std::uniform_int_distribution<int> disRand(randMin, randMax);
43 return disRand(genRand);
44 #endif
45 }
46
GenRandLongLong(int64_t randMin,int64_t randMax)47 DM_EXPORT int64_t GenRandLongLong(int64_t randMin, int64_t randMax)
48 {
49 std::random_device randDevice;
50 std::mt19937 genRand(randDevice());
51 std::uniform_int_distribution<long long> disRand(randMin, randMax);
52 return disRand(genRand);
53 }
54
GenRandUint(uint16_t randMin,uint16_t randMax)55 uint16_t GenRandUint(uint16_t randMin, uint16_t randMax)
56 {
57 std::random_device randDevice;
58 std::mt19937 genRand(randDevice());
59 std::uniform_int_distribution<int> disRand(randMin, randMax);
60 return disRand(genRand);
61 }
62
GenUniqueRandUint(std::set<uint16_t> & randUint16Set)63 uint16_t GenUniqueRandUint(std::set<uint16_t> &randUint16Set)
64 {
65 uint16_t randUint = DM_INVALID_FLAG_ID;
66 bool isExist = false;
67 do {
68 randUint = GenRandInt(DM_MIN_RANDOM, DM_MAX_RANDOM_UINT16);
69 if (randUint16Set.find(randUint) != randUint16Set.end()) {
70 LOGE("The randUint: %{public}d is exist.", randUint);
71 isExist = true;
72 } else {
73 isExist = false;
74 }
75 } while (isExist);
76 randUint16Set.emplace(randUint);
77 return randUint;
78 }
79 } // namespace DistributedHardware
80 } // namespace OHOS
81