[NFC][Py Reformat] Added more commits to .git-blame-ignore-revs
[llvm-project.git] / libc / src / __support / fixedvector.h
blob9e36a9e10b272e56caa1d4ed68ccf2b3626d000c
1 //===-- A data structure for a fixed capacity data store --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SUPPORT_FIXEDVECTOR_H
10 #define LLVM_LIBC_SUPPORT_FIXEDVECTOR_H
12 #include "src/__support/CPP/array.h"
14 namespace __llvm_libc {
16 // A fixed size data store backed by an underlying cpp::array data structure. It
17 // supports vector like API but is not resizable like a vector.
18 template <typename T, size_t CAPACITY> class FixedVector {
19 cpp::array<T, CAPACITY> store;
20 size_t item_count = 0;
22 public:
23 constexpr FixedVector() = default;
25 bool push_back(const T &obj) {
26 if (item_count == CAPACITY)
27 return false;
28 store[item_count] = obj;
29 ++item_count;
30 return true;
33 const T &back() const { return store[item_count - 1]; }
35 T &back() { return store[item_count - 1]; }
37 bool pop_back() {
38 if (item_count == 0)
39 return false;
40 --item_count;
41 return true;
44 bool empty() const { return item_count == 0; }
46 // Empties the store for all practical purposes.
47 void reset() { item_count = 0; }
49 // This static method does not free up the resources held by |store|,
50 // say by calling `free` or something similar. It just does the equivalent
51 // of the `reset` method. Considering that FixedVector is of fixed storage,
52 // a `destroy` method like this should not be required. However, FixedVector
53 // is used in a few places as an alternate for data structures which use
54 // dynamically allocated storate. So, the `destroy` method like this
55 // matches the `destroy` API of those other data structures so that users
56 // can easily swap one data structure for the other.
57 static void destroy(FixedVector<T, CAPACITY> *store) { store->reset(); }
60 } // namespace __llvm_libc
62 #endif // LLVM_LIBC_SUPPORT_FIXEDVECTOR_H