SkLazyPtr.h revision 97de357270e54be53acb17e1cb4b4d5e25bacc01
1/*
2 * Copyright 2014 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 SkLazyPtr_DEFINED
9#define SkLazyPtr_DEFINED
10
11/** Declare a lazily-chosen static pointer (or array of pointers) of type F.
12 *
13 *  Example usage:
14 *
15 *  Foo* CreateFoo() { return SkNEW(Foo); }
16 *  Foo* GetSingletonFoo() {
17 *      SK_DECLARE_STATIC_LAZY_PTR(Foo, singleton, CreateFoo);  // Clean up with SkDELETE.
18 *      return singleton.get();
19 *  }
20 *
21 *  These macros take an optional void (*Destroy)(T*) at the end. If not given, we'll use SkDELETE.
22 *  This option is most useful when T doesn't have a public destructor.
23 *
24 *  void CustomCleanup(Foo* ptr) { ... }
25 *  Foo* GetSingletonFooWithCustomCleanup() {
26 *      SK_DECLARE_STATIC_LAZY_PTR(Foo, singleton, CreateFoo, CustomCleanup);
27 *      return singleton.get();
28 *  }
29 *
30 *  If you have a bunch of related static pointers of the same type, you can
31 *  declare an array of lazy pointers together:
32 *
33 *  Foo* CreateFoo(int i) { return ...; }
34 *  Foo* GetCachedFoo(Foo::Enum enumVal) {
35 *      SK_DECLARE_STATIC_LAZY_PTR_ARRAY(Foo, Foo::kEnumCount, cachedFoos, CreateFoo);
36 *      return cachedFoos[enumVal];
37 *  }
38 *
39 *
40 *  You can think of SK_DECLARE_STATIC_LAZY_PTR as a cheaper specialization of
41 *  SkOnce.  There is no mutex or extra storage used past the pointer itself.
42 *  In debug mode, each lazy pointer will be cleaned up at process exit so we
43 *  can check that we've not leaked or freed them early.
44 *
45 *  We may call Create more than once, but all threads will see the same pointer
46 *  returned from get().  Any extra calls to Create will be cleaned up.
47 *
48 *  These macros must be used in a global or function scope, not as a class member.
49 */
50
51#define SK_DECLARE_STATIC_LAZY_PTR(T, name, Create, ...) \
52    static Private::SkLazyPtr<T, Create, ##__VA_ARGS__> name
53
54#define SK_DECLARE_STATIC_LAZY_PTR_ARRAY(T, name, N, Create, ...) \
55    static Private::SkLazyPtrArray<T, N, Create, ##__VA_ARGS__> name
56
57
58
59// Everything below here is private implementation details.  Don't touch, don't even look.
60
61#include "SkDynamicAnnotations.h"
62#include "SkThread.h"
63#include "SkThreadPriv.h"
64
65// See FIXME below.
66class SkFontConfigInterface;
67class SkTypeface;
68
69namespace Private {
70
71template <typename T> void sk_delete(T* ptr) { SkDELETE(ptr); }
72
73// Set *dst to ptr if *dst is NULL.  Returns value of *dst, destroying ptr if not swapped in.
74// Issues the same memory barriers as sk_atomic_cas: acquire on failure, release on success.
75template <typename P, void (*Destroy)(P)>
76static P try_cas(void** dst, P ptr) {
77    P prev = (P)sk_atomic_cas(dst, NULL, ptr);
78
79    if (prev) {
80        // We need an acquire barrier before returning prev, which sk_atomic_cas provided.
81        Destroy(ptr);
82        return prev;
83    } else {
84        // We need a release barrier before returning ptr, which sk_atomic_cas provided.
85        return ptr;
86    }
87}
88
89// This has no constructor and must be zero-initalized (the macro above does this).
90template <typename T, T* (*Create)(), void (*Destroy)(T*) = sk_delete<T> >
91class SkLazyPtr {
92public:
93    T* get() {
94        // If fPtr has already been filled, we need an acquire barrier when loading it.
95        // If not, we need a release barrier when setting it.  try_cas will do that.
96        T* ptr = (T*)sk_acquire_load(&fPtr);
97        return ptr ? ptr : try_cas<T*, Destroy>(&fPtr, Create());
98    }
99
100#ifdef SK_DEBUG
101    // FIXME: We know we leak refs on some classes.  For now, let them leak.
102    void cleanup(SkFontConfigInterface*) {}
103    void cleanup(SkTypeface*) {}
104    template <typename U> void cleanup(U* ptr) { Destroy(ptr); }
105
106    ~SkLazyPtr() {
107        this->cleanup((T*)fPtr);
108        fPtr = NULL;
109    }
110#endif
111
112private:
113    void* fPtr;
114};
115
116// This has no constructor and must be zero-initalized (the macro above does this).
117template <typename T, int N, T* (*Create)(int), void (*Destroy)(T*) = sk_delete<T> >
118class SkLazyPtrArray {
119public:
120    T* operator[](int i) {
121        SkASSERT(i >= 0 && i < N);
122        // If fPtr has already been filled, we need an acquire barrier when loading it.
123        // If not, we need a release barrier when setting it.  try_cas will do that.
124        T* ptr = (T*)sk_acquire_load(&fArray[i]);
125        return ptr ? ptr : try_cas<T*, Destroy>(&fArray[i], Create(i));
126    }
127
128#ifdef SK_DEBUG
129    ~SkLazyPtrArray() {
130        for (int i = 0; i < N; i++) {
131            Destroy((T*)fArray[i]);
132            fArray[i] = NULL;
133        }
134    }
135#endif
136
137private:
138    void* fArray[N];
139};
140
141}  // namespace Private
142
143#endif//SkLazyPtr_DEFINED
144