SkRefCnt.h revision 4ae94ffce5ecf1b71cb5e295b68bf4ec9e697443
1
2/*
3 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10#ifndef SkRefCnt_DEFINED
11#define SkRefCnt_DEFINED
12
13#include "SkDynamicAnnotations.h"
14#include "SkThread.h"
15#include "SkInstCnt.h"
16#include "SkTemplates.h"
17
18/** \class SkRefCntBase
19
20    SkRefCntBase is the base class for objects that may be shared by multiple
21    objects. When an existing owner wants to share a reference, it calls ref().
22    When an owner wants to release its reference, it calls unref(). When the
23    shared object's reference count goes to zero as the result of an unref()
24    call, its (virtual) destructor is called. It is an error for the
25    destructor to be called explicitly (or via the object going out of scope on
26    the stack or calling delete) if getRefCnt() > 1.
27*/
28class SK_API SkRefCntBase : SkNoncopyable {
29public:
30    SK_DECLARE_INST_COUNT_ROOT(SkRefCntBase)
31
32    /** Default construct, initializing the reference count to 1.
33    */
34    SkRefCntBase() : fRefCnt(1) {}
35
36    /** Destruct, asserting that the reference count is 1.
37    */
38    virtual ~SkRefCntBase() {
39#ifdef SK_DEBUG
40        SkASSERTF(fRefCnt == 1, "fRefCnt was %d", fRefCnt);
41        fRefCnt = 0;    // illegal value, to catch us if we reuse after delete
42#endif
43    }
44
45#ifdef SK_DEBUG
46    /** Return the reference count. Use only for debugging. */
47    int32_t getRefCnt() const { return fRefCnt; }
48#endif
49
50    /** May return true if the caller is the only owner.
51     *  Ensures that all previous owner's actions are complete.
52     */
53    bool unique() const {
54        // We believe we're reading fRefCnt in a safe way here, so we stifle the TSAN warning about
55        // an unproctected read.  Generally, don't read fRefCnt, and don't stifle this warning.
56        bool const unique = (1 == SK_ANNOTATE_UNPROTECTED_READ(fRefCnt));
57        if (unique) {
58            // Acquire barrier (L/SL), if not provided by load of fRefCnt.
59            // Prevents user's 'unique' code from happening before decrements.
60            //TODO: issue the barrier.
61        }
62        return unique;
63    }
64
65    /** Increment the reference count. Must be balanced by a call to unref().
66    */
67    void ref() const {
68        SkASSERT(fRefCnt > 0);
69        sk_atomic_inc(&fRefCnt);  // No barrier required.
70    }
71
72    /** Decrement the reference count. If the reference count is 1 before the
73        decrement, then delete the object. Note that if this is the case, then
74        the object needs to have been allocated via new, and not on the stack.
75    */
76    void unref() const {
77        SkASSERT(fRefCnt > 0);
78        // Release barrier (SL/S), if not provided below.
79        if (sk_atomic_dec(&fRefCnt) == 1) {
80            // Acquire barrier (L/SL), if not provided above.
81            // Prevents code in dispose from happening before the decrement.
82            sk_membar_acquire__after_atomic_dec();
83            internal_dispose();
84        }
85    }
86
87#ifdef SK_DEBUG
88    void validate() const {
89        SkASSERT(fRefCnt > 0);
90    }
91#endif
92
93protected:
94    /**
95     *  Allow subclasses to call this if they've overridden internal_dispose
96     *  so they can reset fRefCnt before the destructor is called. Should only
97     *  be called right before calling through to inherited internal_dispose()
98     *  or before calling the destructor.
99     */
100    void internal_dispose_restore_refcnt_to_1() const {
101#ifdef SK_DEBUG
102        SkASSERT(0 == fRefCnt);
103        fRefCnt = 1;
104#endif
105    }
106
107private:
108    /**
109     *  Called when the ref count goes to 0.
110     */
111    virtual void internal_dispose() const {
112        this->internal_dispose_restore_refcnt_to_1();
113        SkDELETE(this);
114    }
115
116    // The following friends are those which override internal_dispose()
117    // and conditionally call SkRefCnt::internal_dispose().
118    friend class GrTexture;
119    friend class SkWeakRefCnt;
120
121    mutable int32_t fRefCnt;
122
123    // Used by tests.
124    friend bool RefCntIs(const SkRefCntBase&, int32_t);
125
126    typedef SkNoncopyable INHERITED;
127};
128
129#ifdef SK_REF_CNT_MIXIN_INCLUDE
130// It is the responsibility of the following include to define the type SkRefCnt.
131// This SkRefCnt should normally derive from SkRefCntBase.
132#include SK_REF_CNT_MIXIN_INCLUDE
133#else
134class SK_API SkRefCnt : public SkRefCntBase { };
135#endif
136
137///////////////////////////////////////////////////////////////////////////////
138
139/** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for
140    null in on each side of the assignment, and ensuring that ref() is called
141    before unref(), in case the two pointers point to the same object.
142 */
143#define SkRefCnt_SafeAssign(dst, src)   \
144    do {                                \
145        if (src) src->ref();            \
146        if (dst) dst->unref();          \
147        dst = src;                      \
148    } while (0)
149
150
151/** Call obj->ref() and return obj. The obj must not be NULL.
152 */
153template <typename T> static inline T* SkRef(T* obj) {
154    SkASSERT(obj);
155    obj->ref();
156    return obj;
157}
158
159/** Check if the argument is non-null, and if so, call obj->ref() and return obj.
160 */
161template <typename T> static inline T* SkSafeRef(T* obj) {
162    if (obj) {
163        obj->ref();
164    }
165    return obj;
166}
167
168/** Check if the argument is non-null, and if so, call obj->unref()
169 */
170template <typename T> static inline void SkSafeUnref(T* obj) {
171    if (obj) {
172        obj->unref();
173    }
174}
175
176template<typename T> static inline void SkSafeSetNull(T*& obj) {
177    if (NULL != obj) {
178        obj->unref();
179        obj = NULL;
180    }
181}
182
183///////////////////////////////////////////////////////////////////////////////
184
185/**
186 *  Utility class that simply unref's its argument in the destructor.
187 */
188template <typename T> class SkAutoTUnref : SkNoncopyable {
189public:
190    explicit SkAutoTUnref(T* obj = NULL) : fObj(obj) {}
191    ~SkAutoTUnref() { SkSafeUnref(fObj); }
192
193    T* get() const { return fObj; }
194
195    T* reset(T* obj) {
196        SkSafeUnref(fObj);
197        fObj = obj;
198        return obj;
199    }
200
201    void swap(SkAutoTUnref* other) {
202        T* tmp = fObj;
203        fObj = other->fObj;
204        other->fObj = tmp;
205    }
206
207    /**
208     *  Return the hosted object (which may be null), transferring ownership.
209     *  The reference count is not modified, and the internal ptr is set to NULL
210     *  so unref() will not be called in our destructor. A subsequent call to
211     *  detach() will do nothing and return null.
212     */
213    T* detach() {
214        T* obj = fObj;
215        fObj = NULL;
216        return obj;
217    }
218
219    /**
220     *  BlockRef<B> is a type which inherits from B, cannot be created,
221     *  cannot be deleted, and makes ref and unref private.
222     */
223    template<typename B> class BlockRef : public B {
224    private:
225        BlockRef();
226        ~BlockRef();
227        void ref() const;
228        void unref() const;
229    };
230
231    /** If T is const, the type returned from operator-> will also be const. */
232    typedef typename SkTConstType<BlockRef<T>, SkTIsConst<T>::value>::type BlockRefType;
233
234    /**
235     *  SkAutoTUnref assumes ownership of the ref. As a result, it is an error
236     *  for the user to ref or unref through SkAutoTUnref. Therefore
237     *  SkAutoTUnref::operator-> returns BlockRef<T>*. This prevents use of
238     *  skAutoTUnrefInstance->ref() and skAutoTUnrefInstance->unref().
239     */
240    BlockRefType *operator->() const {
241        return static_cast<BlockRefType*>(fObj);
242    }
243    operator T*() { return fObj; }
244
245private:
246    T*  fObj;
247};
248// Can't use the #define trick below to guard a bare SkAutoTUnref(...) because it's templated. :(
249
250class SkAutoUnref : public SkAutoTUnref<SkRefCnt> {
251public:
252    SkAutoUnref(SkRefCnt* obj) : SkAutoTUnref<SkRefCnt>(obj) {}
253};
254#define SkAutoUnref(...) SK_REQUIRE_LOCAL_VAR(SkAutoUnref)
255
256class SkAutoRef : SkNoncopyable {
257public:
258    SkAutoRef(SkRefCnt* obj) : fObj(obj) { SkSafeRef(obj); }
259    ~SkAutoRef() { SkSafeUnref(fObj); }
260private:
261    SkRefCnt* fObj;
262};
263#define SkAutoRef(...) SK_REQUIRE_LOCAL_VAR(SkAutoRef)
264
265/** Wrapper class for SkRefCnt pointers. This manages ref/unref of a pointer to
266    a SkRefCnt (or subclass) object.
267 */
268template <typename T> class SkRefPtr {
269public:
270    SkRefPtr() : fObj(NULL) {}
271    SkRefPtr(T* obj) : fObj(obj) { SkSafeRef(fObj); }
272    SkRefPtr(const SkRefPtr& o) : fObj(o.fObj) { SkSafeRef(fObj); }
273    ~SkRefPtr() { SkSafeUnref(fObj); }
274
275    SkRefPtr& operator=(const SkRefPtr& rp) {
276        SkRefCnt_SafeAssign(fObj, rp.fObj);
277        return *this;
278    }
279    SkRefPtr& operator=(T* obj) {
280        SkRefCnt_SafeAssign(fObj, obj);
281        return *this;
282    }
283
284    T* get() const { return fObj; }
285    T& operator*() const { return *fObj; }
286    T* operator->() const { return fObj; }
287
288    typedef T* SkRefPtr::*unspecified_bool_type;
289    operator unspecified_bool_type() const {
290        return fObj ? &SkRefPtr::fObj : NULL;
291    }
292
293private:
294    T* fObj;
295};
296
297#endif
298