• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 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 #ifndef ID_FACTORY_H
16 #define ID_FACTORY_H
17 
18 #include <set>
19 
20 #include "nocopyable.h"
21 
22 namespace OHOS {
23 namespace Msdp {
24 namespace DeviceStatus {
25 template<typename T>
26 class IdFactory {
27 public:
IdFactory()28     IdFactory() : IdFactory(1) {}
IdFactory(T seed)29     explicit IdFactory(T seed) : seed_(seed) {}
30     DISALLOW_COPY_AND_MOVE(IdFactory);
31     virtual ~IdFactory() = default;
32 
GenerateId()33     T GenerateId()
34     {
35         if (ids_.empty()) {
36             if (seed_ == maxLimit_) {
37                 return 0;
38             }
39             return seed_++;
40         }
41         T id = *ids_.begin();
42         ids_.erase(ids_.begin());
43         return id;
44     }
RecoveryId(T id)45     void RecoveryId(T id)
46     {
47         if (id > seed_) {
48             return;
49         }
50         ids_.insert(id);
51     }
52 
53 private:
54     T seed_ { 0 };
55     const T maxLimit_ = std::numeric_limits<T>::max();
56     std::set<T> ids_;
57 };
58 } // namespace DeviceStatus
59 } // namespace Msdp
60 } // namespace OHOS
61 #endif // ID_FACTORY_H
62