• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef CHRE_UTIL_SINGLETON_IMPL_H_
18 #define CHRE_UTIL_SINGLETON_IMPL_H_
19 
20 #include <new>
21 #include <utility>
22 
23 #include "chre/util/singleton.h"
24 
25 namespace chre {
26 
27 template<typename ObjectType>
28 typename std::aligned_storage<sizeof(ObjectType), alignof(ObjectType)>::type
29     Singleton<ObjectType>::sObject;
30 
31 template<typename ObjectType>
32 bool Singleton<ObjectType>::sIsInitialized = false;
33 
34 template<typename ObjectType>
35 template<typename... Args>
init(Args &&...args)36 void Singleton<ObjectType>::init(Args&&... args) {
37   if (!sIsInitialized) {
38     sIsInitialized = true;
39     new (get()) ObjectType(std::forward<Args>(args)...);
40   }
41 }
42 
43 template<typename ObjectType>
deinit()44 void Singleton<ObjectType>::deinit() {
45   if (sIsInitialized) {
46     get()->~ObjectType();
47     sIsInitialized = false;
48   }
49 }
50 
51 template<typename ObjectType>
isInitialized()52 bool Singleton<ObjectType>::isInitialized() {
53   return sIsInitialized;
54 }
55 
56 template<typename ObjectType>
get()57 ObjectType *Singleton<ObjectType>::get() {
58   return reinterpret_cast<ObjectType *>(&sObject);
59 }
60 
61 template<typename ObjectType>
safeGet()62 ObjectType *Singleton<ObjectType>::safeGet() {
63   if (sIsInitialized) {
64     return reinterpret_cast<ObjectType *>(&sObject);
65   } else {
66     return nullptr;
67   }
68 }
69 
70 }  // namespace chre
71 
72 #endif  // CHRE_UTIL_SINGLETON_IMPL_H_
73