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 #ifndef ID_FACTORY_H
17 #define ID_FACTORY_H
18 
19 #include <set>
20 
21 #include "nocopyable.h"
22 
23 namespace OHOS {
24 namespace MMI {
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     virtual ~IdFactory() = default;
31     DISALLOW_COPY_AND_MOVE(IdFactory);
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 MMI
59 } // namespace OHOS
60 #endif // ID_FACTORY_H
61