1 //===-- vector.h ------------------------------------------------*- 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 SCUDO_VECTOR_H_
10 #define SCUDO_VECTOR_H_
18 // A low-level vector based on map. May incur a significant memory overhead for
19 // small vectors. The current implementation supports only POD types.
20 template <typename T> class VectorNoCtor {
22 void init(uptr InitialCapacity) {
26 reserve(InitialCapacity);
30 unmap(Data, CapacityBytes);
32 T &operator[](uptr I) {
36 const T &operator[](uptr I) const {
40 void push_back(const T &Element) {
41 DCHECK_LE(Size, capacity());
42 if (Size == capacity()) {
43 const uptr NewCapacity = roundUpToPowerOfTwo(Size + 1);
44 reallocate(NewCapacity);
46 memcpy(&Data[Size++], &Element, sizeof(T));
50 return Data[Size - 1];
56 uptr size() const { return Size; }
57 const T *data() const { return Data; }
58 T *data() { return Data; }
59 uptr capacity() const { return CapacityBytes / sizeof(T); }
60 void reserve(uptr NewSize) {
61 // Never downsize internal buffer.
62 if (NewSize > capacity())
65 void resize(uptr NewSize) {
68 memset(&Data[Size], 0, sizeof(T) * (NewSize - Size));
73 void clear() { Size = 0; }
74 bool empty() const { return size() == 0; }
76 const T *begin() const { return data(); }
77 T *begin() { return data(); }
78 const T *end() const { return data() + size(); }
79 T *end() { return data() + size(); }
82 void reallocate(uptr NewCapacity) {
83 DCHECK_GT(NewCapacity, 0);
84 DCHECK_LE(Size, NewCapacity);
85 const uptr NewCapacityBytes =
86 roundUpTo(NewCapacity * sizeof(T), getPageSizeCached());
87 T *NewData = (T *)map(nullptr, NewCapacityBytes, "scudo:vector");
89 memcpy(NewData, Data, Size * sizeof(T));
90 unmap(Data, CapacityBytes);
93 CapacityBytes = NewCapacityBytes;
101 template <typename T> class Vector : public VectorNoCtor<T> {
103 Vector() { VectorNoCtor<T>::init(1); }
104 explicit Vector(uptr Count) {
105 VectorNoCtor<T>::init(Count);
108 ~Vector() { VectorNoCtor<T>::destroy(); }
109 // Disallow copies and moves.
110 Vector(const Vector &) = delete;
111 Vector &operator=(const Vector &) = delete;
112 Vector(Vector &&) = delete;
113 Vector &operator=(Vector &&) = delete;
118 #endif // SCUDO_VECTOR_H_