• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 #pragma once
18 
19 /*
20  * See documentation in RefBase.h
21  */
22 
23 #include <atomic>
24 
25 #include <sys/types.h>
26 
27 namespace android {
28 
29 class ReferenceRenamer;
30 
31 template <class T>
32 class LightRefBase
33 {
34 public:
LightRefBase()35     inline LightRefBase() : mCount(0) { }
incStrong(const void * id)36     inline void incStrong(__attribute__((unused)) const void* id) const {
37         mCount.fetch_add(1, std::memory_order_relaxed);
38     }
decStrong(const void * id)39     inline void decStrong(__attribute__((unused)) const void* id) const {
40         if (mCount.fetch_sub(1, std::memory_order_release) == 1) {
41             std::atomic_thread_fence(std::memory_order_acquire);
42             delete static_cast<const T*>(this);
43         }
44     }
45     //! DEBUGGING ONLY: Get current strong ref count.
getStrongCount()46     inline int32_t getStrongCount() const {
47         return mCount.load(std::memory_order_relaxed);
48     }
49 
50     typedef LightRefBase<T> basetype;
51 
52 protected:
~LightRefBase()53     inline ~LightRefBase() { }
54 
55 private:
56     friend class ReferenceMover;
renameRefs(size_t,const ReferenceRenamer &)57     inline static void renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
renameRefId(T *,const void *,const void *)58     inline static void renameRefId(T* /*ref*/, const void* /*old_id*/ , const void* /*new_id*/) { }
59 
60 private:
61     mutable std::atomic<int32_t> mCount;
62 };
63 
64 
65 // This is a wrapper around LightRefBase that simply enforces a virtual
66 // destructor to eliminate the template requirement of LightRefBase
67 class VirtualLightRefBase : public LightRefBase<VirtualLightRefBase> {
68 public:
69     virtual ~VirtualLightRefBase() = default;
70 };
71 
72 }  // namespace android
73