From 8aedaea5fb92d9cfed0a3e1f959f903fca713ec3 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Fri, 11 Jan 2019 06:00:41 -0800 Subject: [PATCH] Add a flexible array template container --- common/almalloc.h | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/common/almalloc.h b/common/almalloc.h index 15d0263a..a2abc200 100644 --- a/common/almalloc.h +++ b/common/almalloc.h @@ -90,6 +90,48 @@ template std::unique_ptr make_unique(ArgsT&&...args) { return std::unique_ptr{new T{std::forward(args)...}}; } + +/* A flexible array type. Used either standalone or at the end of a parent + * struct, with placement new, to have a run-time-sized array that's embedded + * with its size. + */ +template +struct FlexArray { + const size_t mSize; + alignas(alignment) T mArray[]; + + static constexpr size_t CalcSizeof(size_t count) noexcept + { return std::max(offsetof(FlexArray, mArray) + sizeof(T)*count, sizeof(FlexArray)); } + + FlexArray(size_t size) : mSize{size} + { new (mArray) T[mSize]; } + ~FlexArray() + { + for(size_t i{0u};i < mSize;++i) + mArray[i].~T(); + } + + FlexArray(const FlexArray&) = delete; + FlexArray& operator=(const FlexArray&) = delete; + + size_t size() const noexcept { return mSize; } + + T *data() noexcept { return mArray; } + const T *data() const noexcept { return mArray; } + + T& operator[](size_t i) noexcept { return mArray[i]; } + const T& operator[](size_t i) const noexcept { return mArray[i]; } + + T *begin() noexcept { return mArray; } + const T *begin() const noexcept { return mArray; } + const T *cbegin() const noexcept { return mArray; } + T *end() noexcept { return mArray + mSize; } + const T *end() const noexcept { return mArray + mSize; } + const T *cend() const noexcept { return mArray + mSize; } + + DEF_PLACE_NEWDEL() +}; + } // namespace al #endif /* AL_MALLOC_H */ -- 2.11.4.GIT