1 /*
2  * Copyright 2015 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef GrNonAtomicRef_DEFINED
9 #define GrNonAtomicRef_DEFINED
10 
11 #include "SkNoncopyable.h"
12 #include "SkRefCnt.h"
13 #include "SkTArray.h"
14 
15 /**
16  * A simple non-atomic ref used in the GrBackendApi when we don't want to pay for the overhead of a
17  * threadsafe ref counted object
18  */
19 template<typename TSubclass> class GrNonAtomicRef : public SkNoncopyable {
20 public:
21     GrNonAtomicRef() : fRefCnt(1) {}
22 
23 #ifdef SK_DEBUG
24     ~GrNonAtomicRef() {
25         // fRefCnt can be one when a subclass is created statically
26         SkASSERT((0 == fRefCnt || 1 == fRefCnt));
27         // Set to invalid values.
28         fRefCnt = -10;
29     }
30 #endif
31 
32     bool unique() const { return 1 == fRefCnt; }
33 
34     void ref() const {
35         // Once the ref cnt reaches zero it should never be ref'ed again.
36         SkASSERT(fRefCnt > 0);
37         ++fRefCnt;
38     }
39 
40     void unref() const {
41         SkASSERT(fRefCnt > 0);
42         --fRefCnt;
43         if (0 == fRefCnt) {
44             GrTDeleteNonAtomicRef(static_cast<const TSubclass*>(this));
45             return;
46         }
47     }
48 
49 private:
50     mutable int32_t fRefCnt;
51 
52     typedef SkNoncopyable INHERITED;
53 };
54 
55 template<typename T> inline void GrTDeleteNonAtomicRef(const T* ref) {
56     delete ref;
57 }
58 
59 #endif
60