2 * Copyright 2014 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef SkCachedData_DEFINED
9 #define SkCachedData_DEFINED
13 class SkDiscardableMemory;
15 class SkCachedData : ::SkNoncopyable {
17 SkCachedData(void* mallocData, size_t size);
18 SkCachedData(size_t size, SkDiscardableMemory*);
19 virtual ~SkCachedData();
21 size_t size() const { return fSize; }
22 const void* data() const { return fData; }
24 void* writable_data() { return fData; }
26 void ref() const { this->internalRef(false); }
27 void unref() const { this->internalUnref(false); }
29 int testing_only_getRefCnt() const { return fRefCnt; }
30 bool testing_only_isLocked() const { return fIsLocked; }
31 bool testing_only_isInCache() const { return fInCache; }
34 // called when fData changes. could be NULL.
35 virtual void onDataChange(void* oldData, void* newData) {}
38 SkMutex fMutex; // could use a pool of these...
41 kDiscardableMemory_StorageType,
46 SkDiscardableMemory* fDM;
51 int fRefCnt; // low-bit means we're owned by the cache
52 StorageType fStorageType;
56 void internalRef(bool fromCache) const;
57 void internalUnref(bool fromCache) const;
59 void inMutexRef(bool fromCache);
60 bool inMutexUnref(bool fromCache); // returns true if we should delete "this"
64 // called whenever our fData might change (lock or unlock)
65 void setData(void* newData) {
66 if (newData != fData) {
67 // notify our subclasses of the change
68 this->onDataChange(fData, newData);
73 class AutoMutexWritable;
77 void validate() const;
79 void validate() const {}
83 * Attaching a data to to a SkResourceCache (only one at a time) enables the data to be
84 * unlocked when the cache is the only owner, thus freeing it to be purged (assuming the
85 * data is backed by a SkDiscardableMemory).
87 * When attached, it also automatically attempts to "lock" the data when the first client
88 * ref's the data (typically from a find(key, visitor) call).
90 * Thus the data will always be "locked" when a non-cache has a ref on it (whether or not
91 * the lock succeeded to recover the memory -- check data() to see if it is NULL).
95 * Call when adding this instance to a SkResourceCache::Rec subclass
96 * (typically in the Rec's constructor).
98 void attachToCacheAndRef() const { this->internalRef(true); }
101 * Call when removing this instance from a SkResourceCache::Rec subclass
102 * (typically in the Rec's destructor).
104 void detachFromCacheAndUnref() const { this->internalUnref(true); }