blob: db7eea2c9a47f154cf896fd7ba20a88f9cd5436f [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "include/core/SkRefCnt.h"
12#include "include/private/SkNoncopyable.h"
13#include "include/private/SkTArray.h"
joshualitt2419b362015-07-13 09:29:42 -070014
15/**
Greg Danielbdf12ad2018-10-12 09:31:11 -040016 * A simple non-atomic ref used in the GrBackendApi when we don't want to pay for the overhead of a
joshualitt2419b362015-07-13 09:29:42 -070017 * 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
Brian Salomona036f0d2019-08-29 11:16:04 -040034 // We allow this getter because this type is not thread-safe, meaning only one thread should
35 // have ownership and be manipulating the ref count or querying this.
36 int refCnt() const { return fRefCnt; }
37
joshualitt2419b362015-07-13 09:29:42 -070038 void ref() const {
39 // Once the ref cnt reaches zero it should never be ref'ed again.
40 SkASSERT(fRefCnt > 0);
41 ++fRefCnt;
42 }
43
44 void unref() const {
45 SkASSERT(fRefCnt > 0);
46 --fRefCnt;
47 if (0 == fRefCnt) {
cdalton4833f392016-02-02 22:46:16 -080048 GrTDeleteNonAtomicRef(static_cast<const TSubclass*>(this));
joshualitt2419b362015-07-13 09:29:42 -070049 return;
50 }
51 }
52
53private:
54 mutable int32_t fRefCnt;
55
56 typedef SkNoncopyable INHERITED;
57};
58
cdalton4833f392016-02-02 22:46:16 -080059template<typename T> inline void GrTDeleteNonAtomicRef(const T* ref) {
60 delete ref;
61}
62
joshualitt2419b362015-07-13 09:29:42 -070063#endif