1 /* 2 * Copyright (C) 2022 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_RAW_STORAGE_H_ 18 #define CHRE_UTIL_RAW_STORAGE_H_ 19 20 #include <new> 21 #include <type_traits> 22 23 #include "chre/util/non_copyable.h" 24 25 namespace chre { 26 27 /** 28 * A simple wrapper around std::aligned_storage that provides a region of 29 * uninitialized memory suitable for storing an array of objects, with some 30 * convenience wrappers for constructing and accessing elements. 31 * 32 * This wrapper does not keep track of which indices contain active elements and 33 * therefore does not handle invoking the destructor - this is the 34 * responsibility of the code using it. Therefore this class is geared towards 35 * usage within another data structure, e.g. chre::ArrayQueue. 36 */ 37 template <typename ElementType, size_t kCapacity> 38 class RawStorage : public NonCopyable { 39 public: capacity()40 size_t capacity() const { 41 return kCapacity; 42 } 43 data()44 ElementType *data() { 45 return std::launder(reinterpret_cast<ElementType *>(mStorage)); 46 } data()47 const ElementType *data() const { 48 return std::launder(reinterpret_cast<const ElementType *>(mStorage)); 49 } 50 51 ElementType &operator[](size_t index) { 52 return data()[index]; 53 } 54 const ElementType &operator[](size_t index) const { 55 return data()[index]; 56 } 57 58 private: 59 //! To avoid static initialization of members, std::aligned_storage is used. 60 std::aligned_storage_t<sizeof(ElementType), alignof(ElementType)> 61 mStorage[kCapacity]; 62 }; 63 64 } // namespace chre 65 66 #endif // CHRE_UTIL_RAW_STORAGE_H_