1 /* 2 * Copyright (C) 2025 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef CHRE_UTIL_SYSTEM_INTRUSIVE_REF_BASE_H_ 18 #define CHRE_UTIL_SYSTEM_INTRUSIVE_REF_BASE_H_ 19 20 #include "chre/platform/atomic.h" 21 #include "pw_intrusive_ptr/intrusive_ptr.h" 22 23 namespace chre { 24 25 //! Base class for any type used with pw::IntrusivePtr that needs to support 26 //! reference counting. 27 class IntrusiveRefBase { 28 public: 29 //! Increments reference counter. AddRef()30 void AddRef() const { mRefCount.fetch_increment(); } 31 32 //! Decrements reference count and returns true if the object should be 33 //! deleted. ReleaseRef()34 [[nodiscard]] bool ReleaseRef() const { 35 return mRefCount.fetch_decrement() == 1; 36 } 37 38 //! Reference count ref_count()39 [[nodiscard]] int32_t ref_count() const { 40 return static_cast<int32_t>(mRefCount.load()); 41 } 42 43 protected: 44 constexpr IntrusiveRefBase() = default; 45 IntrusiveRefBase(const IntrusiveRefBase &) = delete; 46 IntrusiveRefBase &operator=(const IntrusiveRefBase &) = delete; 47 IntrusiveRefBase(IntrusiveRefBase &&) = delete; 48 IntrusiveRefBase &operator=(IntrusiveRefBase &&) = delete; 49 virtual ~IntrusiveRefBase() = default; 50 51 private: 52 template <typename T> 53 friend class pw::IntrusivePtr; 54 55 //! Reference count 56 mutable AtomicUint32 mRefCount{0}; 57 }; 58 59 } // namespace chre 60 61 #endif // CHRE_UTIL_SYSTEM_INTRUSIVE_REF_BASE_H_ 62