blob: 89443f9a808e7cafd5291e4e42b0604e162aa4ad [file] [log] [blame]
mtklein00b621c2015-06-17 15:26:15 -07001/*
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
mtkleine9e0dea2014-10-21 12:20:04 -07008#include "Test.h"
9#include "SkLazyPtr.h"
reed89889b62014-10-29 12:36:45 -070010#include "SkRunnable.h"
mtkleine9e0dea2014-10-21 12:20:04 -070011#include "SkTaskGroup.h"
12
13namespace {
14
15struct CreateIntFromFloat {
16 CreateIntFromFloat(float val) : fVal(val) {}
17 int* operator()() const { return SkNEW_ARGS(int, ((int)fVal)); }
18 float fVal;
19};
20
21// As a template argument this must have external linkage.
22void custom_destroy(int* ptr) { *ptr = 99; }
23
24} // namespace
25
26DEF_TEST(LazyPtr, r) {
27 // Basic usage: calls SkNEW(int).
28 SkLazyPtr<int> lazy;
29 int* ptr = lazy.get();
30 REPORTER_ASSERT(r, ptr);
31 REPORTER_ASSERT(r, lazy.get() == ptr);
32
33 // Advanced usage: calls a functor.
34 SkLazyPtr<int> lazyFunctor;
35 int* six = lazyFunctor.get(CreateIntFromFloat(6.4f));
36 REPORTER_ASSERT(r, six);
37 REPORTER_ASSERT(r, 6 == *six);
38
39 // Just makes sure this is safe.
40 SkLazyPtr<double> neverRead;
41
42 // SkLazyPtr supports custom destroy methods.
43 {
44 SkLazyPtr<int, custom_destroy> customDestroy;
45 ptr = customDestroy.get();
46 // custom_destroy called here.
47 }
48 REPORTER_ASSERT(r, ptr);
49 REPORTER_ASSERT(r, 99 == *ptr);
50 // Since custom_destroy didn't actually delete ptr, we do now.
51 SkDELETE(ptr);
52}
53
mtkleine9e0dea2014-10-21 12:20:04 -070054DEF_TEST(LazyPtr_Threaded, r) {
55 static const int kRacers = 321;
56
mtklein00b621c2015-06-17 15:26:15 -070057 // Race to intialize the pointer by calling .get().
mtkleine9e0dea2014-10-21 12:20:04 -070058 SkLazyPtr<int> lazy;
mtklein00b621c2015-06-17 15:26:15 -070059 int* seen[kRacers];
mtkleine9e0dea2014-10-21 12:20:04 -070060
mtklein00b621c2015-06-17 15:26:15 -070061 sk_parallel_for(kRacers, [&](int i) {
62 seen[i] = lazy.get();
63 });
mtkleine9e0dea2014-10-21 12:20:04 -070064
mtklein00b621c2015-06-17 15:26:15 -070065 // lazy.get() should return the same pointer to all threads.
mtkleine9e0dea2014-10-21 12:20:04 -070066 for (int i = 1; i < kRacers; i++) {
mtklein00b621c2015-06-17 15:26:15 -070067 REPORTER_ASSERT(r, seen[i] != nullptr);
68 REPORTER_ASSERT(r, seen[i] == seen[0]);
mtkleine9e0dea2014-10-21 12:20:04 -070069 }
70}