xref: /aosp_15_r20/system/chre/util/include/chre/util/copyable_fixed_size_vector.h (revision 84e339476a462649f82315436d70fd732297a399)
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_COPYABLE_FIXED_SIZE_VECTOR_H_
18 #define CHRE_UTIL_COPYABLE_FIXED_SIZE_VECTOR_H_
19 
20 #include <cstring>
21 #include <type_traits>
22 
23 #include "chre/util/fixed_size_vector.h"
24 
25 namespace chre {
26 
27 /**
28  * Equivalent to FixedSizeVector, but for situations where there's an explicit
29  * need for it to be copyable. This implies that we've weighed alternatives and
30  * are OK with the potential overhead involved, for example if we know this is
31  * a small size collection that we'd otherwise use a plain array for.
32  */
33 template <typename ElementType, size_t kCapacity>
34 class CopyableFixedSizeVector : public FixedSizeVector<ElementType, kCapacity> {
35  public:
36   CopyableFixedSizeVector() = default;
37 
CopyableFixedSizeVector(const CopyableFixedSizeVector & other)38   CopyableFixedSizeVector(const CopyableFixedSizeVector &other) {
39     copyFrom(other);
40   }
41 
42   CopyableFixedSizeVector &operator=(const CopyableFixedSizeVector &other) {
43     copyFrom(other);
44     return *this;
45   }
46 
47  private:
copyFrom(const CopyableFixedSizeVector & other)48   void copyFrom(const CopyableFixedSizeVector &other) {
49     this->mSize = other.mSize;
50     if (std::is_trivially_copy_constructible<ElementType>::value) {
51       std::memcpy(this->data(), other.data(),
52                   sizeof(ElementType) * this->mSize);
53     } else {
54       for (size_t i = 0; i < this->mSize; i++) {
55         new (&this->data()[i]) ElementType(other[i]);
56       }
57     }
58   }
59 };
60 
61 }  // namespace chre
62 
63 #endif  // CHRE_UTIL_COPYABLE_FIXED_SIZE_VECTOR_H_