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 <utility>
21 
22 #include "chre/util/singleton.h"
23 
24 namespace chre {
25 
26 template<typename ObjectType>
27 typename std::aligned_storage<sizeof(ObjectType), alignof(ObjectType)>::type
28     Singleton<ObjectType>::sObject;
29 
30 template<typename ObjectType>
31 bool Singleton<ObjectType>::sIsInitialized = false;
32 
33 template<typename ObjectType>
34 template<typename... Args>
init(Args &&...args)35 void Singleton<ObjectType>::init(Args&&... args) {
36   if (!sIsInitialized) {
37     sIsInitialized = true;
38     new (get()) ObjectType(std::forward<Args>(args)...);
39   }
40 }
41 
42 template<typename ObjectType>
deinit()43 void Singleton<ObjectType>::deinit() {
44   if (sIsInitialized) {
45     get()->~ObjectType();
46     sIsInitialized = false;
47   }
48 }
49 
50 template<typename ObjectType>
isInitialized()51 bool Singleton<ObjectType>::isInitialized() {
52   return sIsInitialized;
53 }
54 
55 template<typename ObjectType>
get()56 ObjectType *Singleton<ObjectType>::get() {
57   if (sIsInitialized) {
58     return reinterpret_cast<ObjectType *>(&sObject);
59   } else {
60     return nullptr;
61   }
62 }
63 
64 }  // namespace chre
65 
66 #endif  // CHRE_UTIL_SINGLETON_IMPL_H_
67