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