blob: 5a4e8d1dbb5c3effe1953806693b3a7311c00912 [file] [log] [blame]
joshualitt2419b362015-07-13 09:29:42 -07001/*
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
Ben Wagnerd5148e32018-07-16 17:44:06 -040011#include "SkNoncopyable.h"
joshualitt2419b362015-07-13 09:29:42 -070012#include "SkRefCnt.h"
13#include "SkTArray.h"
14
15/**
16 * A simple non-atomic ref used in the GrBackend when we don't want to pay for the overhead of a
17 * threadsafe ref counted object
18 */
cdalton4833f392016-02-02 22:46:16 -080019template<typename TSubclass> class GrNonAtomicRef : public SkNoncopyable {
joshualitt2419b362015-07-13 09:29:42 -070020public:
21 GrNonAtomicRef() : fRefCnt(1) {}
cdalton4833f392016-02-02 22:46:16 -080022
23#ifdef SK_DEBUG
24 ~GrNonAtomicRef() {
joshualitt2419b362015-07-13 09:29:42 -070025 // fRefCnt can be one when a subclass is created statically
26 SkASSERT((0 == fRefCnt || 1 == fRefCnt));
27 // Set to invalid values.
cdalton4833f392016-02-02 22:46:16 -080028 fRefCnt = -10;
joshualitt2419b362015-07-13 09:29:42 -070029 }
cdalton4833f392016-02-02 22:46:16 -080030#endif
joshualitt2419b362015-07-13 09:29:42 -070031
csmartdalton28341fa2016-08-17 10:00:21 -070032 bool unique() const { return 1 == fRefCnt; }
33
joshualitt2419b362015-07-13 09:29:42 -070034 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) {
cdalton4833f392016-02-02 22:46:16 -080044 GrTDeleteNonAtomicRef(static_cast<const TSubclass*>(this));
joshualitt2419b362015-07-13 09:29:42 -070045 return;
46 }
47 }
48
49private:
50 mutable int32_t fRefCnt;
51
52 typedef SkNoncopyable INHERITED;
53};
54
cdalton4833f392016-02-02 22:46:16 -080055template<typename T> inline void GrTDeleteNonAtomicRef(const T* ref) {
56 delete ref;
57}
58
joshualitt2419b362015-07-13 09:29:42 -070059#endif