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