xref: /aosp_15_r20/frameworks/minikin/include/minikin/SortedPackedVector.h (revision 834a2baab5fdfc28e9a428ee87c7ea8f6a06a53d)
1 /*
2  * Copyright (C) 2024 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 MINIKIN_SORTED_VECTOR_H
18 #define MINIKIN_SORTED_VECTOR_H
19 
20 #include <algorithm>
21 #include <vector>
22 
23 #include "minikin/PackedVector.h"
24 
25 namespace minikin {
26 
27 // An immutable packed vector that elements are sorted.
28 template <typename T, size_t ARRAY_SIZE = 2, typename SIZE_TYPE = uint32_t>
29 class SortedPackedVector {
30 public:
SortedPackedVector()31     SortedPackedVector() {}
mPacked(ptr,count)32     SortedPackedVector(const T* ptr, SIZE_TYPE count, bool sorted = false) : mPacked(ptr, count) {
33         if (!sorted) {
34             sort();
35         }
36     }
mPacked(vec)37     SortedPackedVector(const std::vector<T>& vec, bool sorted = false) : mPacked(vec) {
38         if (!sorted) {
39             sort();
40         }
41     }
mPacked(init)42     SortedPackedVector(std::initializer_list<T> init, bool sorted = false) : mPacked(init) {
43         if (!sorted) {
44             sort();
45         }
46     }
47 
48     SortedPackedVector(const SortedPackedVector& o) = default;
49     SortedPackedVector& operator=(const SortedPackedVector& o) = default;
50     SortedPackedVector(SortedPackedVector&& o) = default;
51     SortedPackedVector& operator=(SortedPackedVector&& o) = default;
52 
size()53     SIZE_TYPE size() const { return mPacked.size(); }
empty()54     bool empty() const { return size() == 0; }
55 
56     const T& operator[](SIZE_TYPE i) const { return mPacked[i]; }
data()57     const T* data() const { return mPacked.data(); }
58 
59     inline bool operator==(const SortedPackedVector& o) const { return mPacked == o.mPacked; }
60 
61     inline bool operator!=(const SortedPackedVector& o) const { return !(*this == o); }
62 
begin()63     inline const T* begin() const { return mPacked.begin(); }
end()64     inline const T* end() const { return mPacked.end(); }
65 
66 private:
sort()67     void sort() { std::sort(mPacked.begin(), mPacked.end()); }
68 
69     PackedVector<T, ARRAY_SIZE, SIZE_TYPE> mPacked;
70 };
71 
72 }  // namespace minikin
73 #endif  // MINIKIN_SORTED_VECTOR_H
74