SkLazyPtr.h revision 78358bf624c7e7c09ffccf638c50870808d884d6
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;
67
68namespace Private {
69
70template <typename T> void sk_delete(T* ptr) { SkDELETE(ptr); }
71
72// Set *dst to ptr if *dst is NULL.  Returns value of *dst, destroying ptr if not swapped in.
73// Issues the same memory barriers as sk_atomic_cas: acquire on failure, release on success.
74template <typename P, void (*Destroy)(P)>
75static P try_cas(void** dst, P ptr) {
76    P prev = (P)sk_atomic_cas(dst, NULL, ptr);
77
78    if (prev) {
79        // We need an acquire barrier before returning prev, which sk_atomic_cas provided.
80        Destroy(ptr);
81        return prev;
82    } else {
83        // We need a release barrier before returning ptr, which sk_atomic_cas provided.
84        return ptr;
85    }
86}
87
88// This has no constructor and must be zero-initalized (the macro above does this).
89template <typename T, T* (*Create)(), void (*Destroy)(T*) = sk_delete<T> >
90class SkLazyPtr {
91public:
92    T* get() {
93        // If fPtr has already been filled, we need an acquire barrier when loading it.
94        // If not, we need a release barrier when setting it.  try_cas will do that.
95        T* ptr = (T*)sk_acquire_load(&fPtr);
96        return ptr ? ptr : try_cas<T*, Destroy>(&fPtr, Create());
97    }
98
99#ifdef SK_DEVELOPER
100    // FIXME: We know we leak refs on some classes.  For now, let them leak.
101    void cleanup(SkFontConfigInterface*) {}
102    template <typename U> void cleanup(U* ptr) { Destroy(ptr); }
103
104    ~SkLazyPtr() {
105        this->cleanup((T*)fPtr);
106        fPtr = NULL;
107    }
108#endif
109
110private:
111    void* fPtr;
112};
113
114// This has no constructor and must be zero-initalized (the macro above does this).
115template <typename T, int N, T* (*Create)(int), void (*Destroy)(T*) = sk_delete<T> >
116class SkLazyPtrArray {
117public:
118    T* operator[](int i) {
119        SkASSERT(i >= 0 && i < N);
120        // If fPtr has already been filled, we need an acquire barrier when loading it.
121        // If not, we need a release barrier when setting it.  try_cas will do that.
122        T* ptr = (T*)sk_acquire_load(&fArray[i]);
123        return ptr ? ptr : try_cas<T*, Destroy>(&fArray[i], Create(i));
124    }
125
126#ifdef SK_DEVELOPER
127    ~SkLazyPtrArray() {
128        for (int i = 0; i < N; i++) {
129            Destroy((T*)fArray[i]);
130            fArray[i] = NULL;
131        }
132    }
133#endif
134
135private:
136    void* fArray[N];
137};
138
139}  // namespace Private
140
141#endif//SkLazyPtr_DEFINED
142