Shaka Player Embedded
pseudo_singleton.h
Go to the documentation of this file.
1 // Copyright 2017 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef SHAKA_EMBEDDED_UTIL_PSEUDO_SINGLETON_H_
16 #define SHAKA_EMBEDDED_UTIL_PSEUDO_SINGLETON_H_
17 
18 #include <glog/logging.h>
19 
20 #include <atomic>
21 #include <type_traits>
22 
23 #include "src/util/macros.h"
24 
25 namespace shaka {
26 
36 template <typename T>
38  public:
43  struct UnsetForTesting {
45  : value_(instance_.exchange(nullptr, std::memory_order_acq_rel)) {}
46 
48  T* expected = nullptr;
49  CHECK(instance_.compare_exchange_strong(expected, value_,
50  std::memory_order_acq_rel));
51  }
52 
53  private:
54  T* value_;
55  };
56 
57  // Since the base class is initialized first, the virtual pointers in *this
58  // haven't been setup yet. This means that ubsan will tell us this is an
59  // invalid cast.
60  NO_SANITIZE("vptr")
62  T* expected = nullptr;
63  CHECK(instance_.compare_exchange_strong(expected, static_cast<T*>(this),
64  std::memory_order_acq_rel));
65  }
66 
68  T* expected = static_cast<T*>(this);
69  CHECK(instance_.compare_exchange_strong(expected, nullptr,
70  std::memory_order_acq_rel));
71  }
72 
73  static T* Instance() {
74  T* ret = instance_.load(std::memory_order_acquire);
75  CHECK(ret);
76  return ret;
77  }
78 
79  static T* InstanceOrNull() {
80  return instance_.load(std::memory_order_acquire);
81  }
82 
83  private:
84  static std::atomic<T*> instance_;
85 };
86 
87 template <typename T>
88 std::atomic<T*> PseudoSingleton<T>::instance_{nullptr};
89 
90 } // namespace shaka
91 
92 #endif // SHAKA_EMBEDDED_UTIL_PSEUDO_SINGLETON_H_
#define NO_SANITIZE(name)
Definition: macros.h:40