blob: f719c2e0bf0bdcd8229192ae5b43e94b6ecdb82e [file] [log] [blame]
mtkleine9e0dea2014-10-21 12:20:04 -07001#include "Test.h"
2#include "SkLazyPtr.h"
3#include "SkTaskGroup.h"
4
5namespace {
6
7struct CreateIntFromFloat {
8 CreateIntFromFloat(float val) : fVal(val) {}
9 int* operator()() const { return SkNEW_ARGS(int, ((int)fVal)); }
10 float fVal;
11};
12
13// As a template argument this must have external linkage.
14void custom_destroy(int* ptr) { *ptr = 99; }
15
16} // namespace
17
18DEF_TEST(LazyPtr, r) {
19 // Basic usage: calls SkNEW(int).
20 SkLazyPtr<int> lazy;
21 int* ptr = lazy.get();
22 REPORTER_ASSERT(r, ptr);
23 REPORTER_ASSERT(r, lazy.get() == ptr);
24
25 // Advanced usage: calls a functor.
26 SkLazyPtr<int> lazyFunctor;
27 int* six = lazyFunctor.get(CreateIntFromFloat(6.4f));
28 REPORTER_ASSERT(r, six);
29 REPORTER_ASSERT(r, 6 == *six);
30
31 // Just makes sure this is safe.
32 SkLazyPtr<double> neverRead;
33
34 // SkLazyPtr supports custom destroy methods.
35 {
36 SkLazyPtr<int, custom_destroy> customDestroy;
37 ptr = customDestroy.get();
38 // custom_destroy called here.
39 }
40 REPORTER_ASSERT(r, ptr);
41 REPORTER_ASSERT(r, 99 == *ptr);
42 // Since custom_destroy didn't actually delete ptr, we do now.
43 SkDELETE(ptr);
44}
45
46namespace {
47
48struct Racer : public SkRunnable {
49 Racer() : fLazy(NULL), fSeen(NULL) {}
50
51 virtual void run() SK_OVERRIDE { fSeen = fLazy->get(); }
52
53 SkLazyPtr<int>* fLazy;
54 int* fSeen;
55};
56
57} // namespace
58
59DEF_TEST(LazyPtr_Threaded, r) {
60 static const int kRacers = 321;
61
62 SkLazyPtr<int> lazy;
63
64 Racer racers[kRacers];
65 for (int i = 0; i < kRacers; i++) {
66 racers[i].fLazy = &lazy;
67 }
68
69 SkTaskGroup tg;
70 for (int i = 0; i < kRacers; i++) {
71 tg.add(racers + i);
72 }
73 tg.wait();
74
75 for (int i = 1; i < kRacers; i++) {
76 REPORTER_ASSERT(r, racers[i].fSeen);
77 REPORTER_ASSERT(r, racers[i].fSeen == racers[0].fSeen);
78 }
79}