1 /* 2 * Copyright (c) 2025 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 AUDIO_HAPTIC_TOOLS_H 17 #define AUDIO_HAPTIC_TOOLS_H 18 19 #include <string> 20 #include <map> 21 #include <vector> 22 #include <unordered_map> 23 24 25 namespace OHOS { 26 namespace Media { 27 template<typename T> 28 class ObjectRefMap { 29 public: 30 static std::mutex allObjLock; 31 static std::map<T*, uint32_t> refMap; 32 static void Insert(T *obj); 33 static void Erase(T *obj); 34 static T *IncreaseRef(T *obj); 35 static void DecreaseRef(T *obj); 36 37 explicit ObjectRefMap(T *obj); 38 ~ObjectRefMap(); 39 T *GetPtr(); 40 41 private: 42 T *obj_ = nullptr; 43 }; 44 45 template <typename T> 46 std::mutex ObjectRefMap<T>::allObjLock; 47 48 template <typename T> 49 std::map<T *, uint32_t> ObjectRefMap<T>::refMap; 50 51 template <typename T> Insert(T * obj)52void ObjectRefMap<T>::Insert(T *obj) 53 { 54 std::lock_guard<std::mutex> lock(allObjLock); 55 refMap[obj] = 1; 56 } 57 58 template <typename T> Erase(T * obj)59void ObjectRefMap<T>::Erase(T *obj) 60 { 61 std::lock_guard<std::mutex> lock(allObjLock); 62 auto it = refMap.find(obj); 63 if (it != refMap.end()) { 64 refMap.erase(it); 65 } 66 } 67 68 template <typename T> IncreaseRef(T * obj)69T *ObjectRefMap<T>::IncreaseRef(T *obj) 70 { 71 std::lock_guard<std::mutex> lock(allObjLock); 72 if (refMap.count(obj)) { 73 refMap[obj]++; 74 return obj; 75 } else { 76 return nullptr; 77 } 78 } 79 80 template <typename T> DecreaseRef(T * obj)81void ObjectRefMap<T>::DecreaseRef(T *obj) 82 { 83 std::lock_guard<std::mutex> lock(allObjLock); 84 if (refMap.count(obj) && --refMap[obj] == 0) { 85 refMap.erase(obj); 86 delete obj; 87 obj = nullptr; 88 } 89 } 90 91 template <typename T> ObjectRefMap(T * obj)92ObjectRefMap<T>::ObjectRefMap(T *obj) 93 { 94 if (obj != nullptr) { 95 obj_ = ObjectRefMap::IncreaseRef(obj); 96 } 97 } 98 99 template <typename T> ~ObjectRefMap()100ObjectRefMap<T>::~ObjectRefMap() 101 { 102 if (obj_ != nullptr) { 103 ObjectRefMap::DecreaseRef(obj_); 104 } 105 } 106 107 template <typename T> GetPtr()108T *ObjectRefMap<T>::GetPtr() 109 { 110 return obj_; 111 } 112 } // namespace Media 113 } // namespace OHOS 114 #endif // AUDIO_HAPTIC_TOOLS_H 115