1 // Copyright 2017 The Dawn Authors 2 // 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 COMMON_REFCOUNTED_H_ 16 #define COMMON_REFCOUNTED_H_ 17 18 #include "common/RefBase.h" 19 20 #include <atomic> 21 #include <cstdint> 22 23 class RefCounted { 24 public: 25 RefCounted(uint64_t payload = 0); 26 27 uint64_t GetRefCountForTesting() const; 28 uint64_t GetRefCountPayload() const; 29 30 void Reference(); 31 void Release(); 32 33 void APIReference(); 34 void APIRelease(); 35 36 protected: 37 virtual ~RefCounted() = default; 38 // A Derived class may override this if they require a custom deleter. 39 virtual void DeleteThis(); 40 41 private: 42 std::atomic<uint64_t> mRefCount; 43 }; 44 45 template <typename T> 46 struct RefCountedTraits { 47 static constexpr T* kNullValue = nullptr; ReferenceRefCountedTraits48 static void Reference(T* value) { 49 value->Reference(); 50 } ReleaseRefCountedTraits51 static void Release(T* value) { 52 value->Release(); 53 } 54 }; 55 56 template <typename T> 57 class Ref : public RefBase<T*, RefCountedTraits<T>> { 58 public: 59 using RefBase<T*, RefCountedTraits<T>>::RefBase; 60 }; 61 62 template <typename T> AcquireRef(T * pointee)63Ref<T> AcquireRef(T* pointee) { 64 Ref<T> ref; 65 ref.Acquire(pointee); 66 return ref; 67 } 68 69 #endif // COMMON_REFCOUNTED_H_ 70