[scudo] Make Vector() constexpr
A `Vector` that doesn't require an initial `reserve()` (eg: with a
default, or small enough capacity) can have a constant initializer.
This changes the code in a few places to make that possible:
- mark a few other functions as `constexpr`
- do without any `reinterpret_cast`
- allow to skip `reserve` from `init`
Differential Revision: https://reviews.llvm.org/D107308
GitOrigin-RevId: 23a94af44939b094f9ba2d6bb969f5a48b78fa8c
diff --git a/vector.h b/vector.h
index 2c9a6e2..eae774b 100644
--- a/vector.h
+++ b/vector.h
@@ -19,13 +19,14 @@
// small vectors. The current implementation supports only POD types.
template <typename T> class VectorNoCtor {
public:
- void init(uptr InitialCapacity = 0) {
- Data = reinterpret_cast<T *>(&LocalData[0]);
+ constexpr void init(uptr InitialCapacity = 0) {
+ Data = &LocalData[0];
CapacityBytes = sizeof(LocalData);
- reserve(InitialCapacity);
+ if (InitialCapacity > capacity())
+ reserve(InitialCapacity);
}
void destroy() {
- if (Data != reinterpret_cast<T *>(&LocalData[0]))
+ if (Data != &LocalData[0])
unmap(Data, CapacityBytes);
}
T &operator[](uptr I) {
@@ -55,7 +56,7 @@
uptr size() const { return Size; }
const T *data() const { return Data; }
T *data() { return Data; }
- uptr capacity() const { return CapacityBytes / sizeof(T); }
+ constexpr uptr capacity() const { return CapacityBytes / sizeof(T); }
void reserve(uptr NewSize) {
// Never downsize internal buffer.
if (NewSize > capacity())
@@ -91,14 +92,14 @@
}
T *Data = nullptr;
- u8 LocalData[256] = {};
+ T LocalData[256 / sizeof(T)] = {};
uptr CapacityBytes = 0;
uptr Size = 0;
};
template <typename T> class Vector : public VectorNoCtor<T> {
public:
- Vector() { VectorNoCtor<T>::init(); }
+ constexpr Vector() { VectorNoCtor<T>::init(); }
explicit Vector(uptr Count) {
VectorNoCtor<T>::init(Count);
this->resize(Count);