1 //===-- A data structure for a fixed capacity data store --------*- C++ -*-===//
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
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;
23 constexpr FixedVector() = default;
25 bool push_back(const T
&obj
) {
26 if (item_count
== CAPACITY
)
28 store
[item_count
] = obj
;
33 const T
&back() const { return store
[item_count
- 1]; }
35 T
&back() { return store
[item_count
- 1]; }
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