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 "SkAtomics.h"
14#include "SkInstCnt.h"
15#include "SkTemplates.h"
16
17/** \class SkRefCntBase
18
19    SkRefCntBase is the base class for objects that may be shared by multiple
20    objects. When an existing owner wants to share a reference, it calls ref().
21    When an owner wants to release its reference, it calls unref(). When the
22    shared object's reference count goes to zero as the result of an unref()
23    call, its (virtual) destructor is called. It is an error for the
24    destructor to be called explicitly (or via the object going out of scope on
25    the stack or calling delete) if getRefCnt() > 1.
26*/
27class SK_API SkRefCntBase : SkNoncopyable {
28public:
29    SK_DECLARE_INST_COUNT(SkRefCntBase)
30
31    /** Default construct, initializing the reference count to 1.
32    */
33    SkRefCntBase() : fRefCnt(1) {}
34
35    /** Destruct, asserting that the reference count is 1.
36    */
37    virtual ~SkRefCntBase() {
38#ifdef SK_DEBUG
39        SkASSERTF(fRefCnt == 1, "fRefCnt was %d", fRefCnt);
40        fRefCnt = 0;    // illegal value, to catch us if we reuse after delete
41#endif
42    }
43
44#ifdef SK_DEBUG
45    /** Return the reference count. Use only for debugging. */
46    int32_t getRefCnt() const { return fRefCnt; }
47#endif
48
49    /** May return true if the caller is the only owner.
50     *  Ensures that all previous owner's actions are complete.
51     */
52    bool unique() const {
53        if (1 == sk_atomic_load(&fRefCnt, sk_memory_order_acquire)) {
54            // The acquire barrier is only really needed if we return true.  It
55            // prevents code conditioned on the result of unique() from running
56            // until previous owners are all totally done calling unref().
57            return true;
58        }
59        return false;
60    }
61
62    /** Increment the reference count. Must be balanced by a call to unref().
63    */
64    void ref() const {
65        SkASSERT(fRefCnt > 0);
66        (void)sk_atomic_fetch_add(&fRefCnt, +1, sk_memory_order_relaxed);  // No barrier required.
67    }
68
69    /** Decrement the reference count. If the reference count is 1 before the
70        decrement, then delete the object. Note that if this is the case, then
71        the object needs to have been allocated via new, and not on the stack.
72    */
73    void unref() const {
74        SkASSERT(fRefCnt > 0);
75        // A release here acts in place of all releases we "should" have been doing in ref().
76        if (1 == sk_atomic_fetch_add(&fRefCnt, -1, sk_memory_order_acq_rel)) {
77            // Like unique(), the acquire is only needed on success, to make sure
78            // code in internal_dispose() doesn't happen before the decrement.
79            this->internal_dispose();
80        }
81    }
82
83#ifdef SK_DEBUG
84    void validate() const {
85        SkASSERT(fRefCnt > 0);
86    }
87#endif
88
89protected:
90    /**
91     *  Allow subclasses to call this if they've overridden internal_dispose
92     *  so they can reset fRefCnt before the destructor is called. Should only
93     *  be called right before calling through to inherited internal_dispose()
94     *  or before calling the destructor.
95     */
96    void internal_dispose_restore_refcnt_to_1() const {
97#ifdef SK_DEBUG
98        SkASSERT(0 == fRefCnt);
99        fRefCnt = 1;
100#endif
101    }
102
103private:
104    /**
105     *  Called when the ref count goes to 0.
106     */
107    virtual void internal_dispose() const {
108        this->internal_dispose_restore_refcnt_to_1();
109        SkDELETE(this);
110    }
111
112    // The following friends are those which override internal_dispose()
113    // and conditionally call SkRefCnt::internal_dispose().
114    friend class SkWeakRefCnt;
115
116    mutable int32_t fRefCnt;
117
118    typedef SkNoncopyable INHERITED;
119};
120
121#ifdef SK_REF_CNT_MIXIN_INCLUDE
122// It is the responsibility of the following include to define the type SkRefCnt.
123// This SkRefCnt should normally derive from SkRefCntBase.
124#include SK_REF_CNT_MIXIN_INCLUDE
125#else
126class SK_API SkRefCnt : public SkRefCntBase { };
127#endif
128
129///////////////////////////////////////////////////////////////////////////////
130
131/** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for
132    null in on each side of the assignment, and ensuring that ref() is called
133    before unref(), in case the two pointers point to the same object.
134 */
135#define SkRefCnt_SafeAssign(dst, src)   \
136    do {                                \
137        if (src) src->ref();            \
138        if (dst) dst->unref();          \
139        dst = src;                      \
140    } while (0)
141
142
143/** Call obj->ref() and return obj. The obj must not be NULL.
144 */
145template <typename T> static inline T* SkRef(T* obj) {
146    SkASSERT(obj);
147    obj->ref();
148    return obj;
149}
150
151/** Check if the argument is non-null, and if so, call obj->ref() and return obj.
152 */
153template <typename T> static inline T* SkSafeRef(T* obj) {
154    if (obj) {
155        obj->ref();
156    }
157    return obj;
158}
159
160/** Check if the argument is non-null, and if so, call obj->unref()
161 */
162template <typename T> static inline void SkSafeUnref(T* obj) {
163    if (obj) {
164        obj->unref();
165    }
166}
167
168template<typename T> static inline void SkSafeSetNull(T*& obj) {
169    if (obj) {
170        obj->unref();
171        obj = NULL;
172    }
173}
174
175///////////////////////////////////////////////////////////////////////////////
176
177/**
178 *  Utility class that simply unref's its argument in the destructor.
179 */
180template <typename T> class SkAutoTUnref : SkNoncopyable {
181public:
182    explicit SkAutoTUnref(T* obj = NULL) : fObj(obj) {}
183    ~SkAutoTUnref() { SkSafeUnref(fObj); }
184
185    T* get() const { return fObj; }
186
187    T* reset(T* obj) {
188        SkSafeUnref(fObj);
189        fObj = obj;
190        return obj;
191    }
192
193    void swap(SkAutoTUnref* other) {
194        T* tmp = fObj;
195        fObj = other->fObj;
196        other->fObj = tmp;
197    }
198
199    /**
200     *  Return the hosted object (which may be null), transferring ownership.
201     *  The reference count is not modified, and the internal ptr is set to NULL
202     *  so unref() will not be called in our destructor. A subsequent call to
203     *  detach() will do nothing and return null.
204     */
205    T* detach() {
206        T* obj = fObj;
207        fObj = NULL;
208        return obj;
209    }
210
211    T* operator->() const { return fObj; }
212    operator T*() const { return fObj; }
213
214private:
215    T*  fObj;
216};
217// Can't use the #define trick below to guard a bare SkAutoTUnref(...) because it's templated. :(
218
219class SkAutoUnref : public SkAutoTUnref<SkRefCnt> {
220public:
221    SkAutoUnref(SkRefCnt* obj) : SkAutoTUnref<SkRefCnt>(obj) {}
222};
223#define SkAutoUnref(...) SK_REQUIRE_LOCAL_VAR(SkAutoUnref)
224
225// This is a variant of SkRefCnt that's Not Virtual, so weighs 4 bytes instead of 8 or 16.
226// There's only benefit to using this if the deriving class does not otherwise need a vtable.
227template <typename Derived>
228class SkNVRefCnt : SkNoncopyable {
229public:
230    SkNVRefCnt() : fRefCnt(1) {}
231    ~SkNVRefCnt() { SkASSERTF(1 == fRefCnt, "NVRefCnt was %d", fRefCnt); }
232
233    // Implementation is pretty much the same as SkRefCntBase. All required barriers are the same:
234    //   - unique() needs acquire when it returns true, and no barrier if it returns false;
235    //   - ref() doesn't need any barrier;
236    //   - unref() needs a release barrier, and an acquire if it's going to call delete.
237
238    bool unique() const { return 1 == sk_atomic_load(&fRefCnt, sk_memory_order_acquire); }
239    void    ref() const { (void)sk_atomic_fetch_add(&fRefCnt, +1, sk_memory_order_relaxed); }
240    void  unref() const {
241        if (1 == sk_atomic_fetch_add(&fRefCnt, -1, sk_memory_order_acq_rel)) {
242            SkDEBUGCODE(fRefCnt = 1;)   // restore the 1 for our destructor's assert
243            SkDELETE((const Derived*)this);
244        }
245    }
246    void  deref() const { this->unref(); }
247
248private:
249    mutable int32_t fRefCnt;
250};
251
252#endif
253