| Elliott Hughes | 845ce3c | 2009-11-13 17:07:00 -0800 | [diff] [blame] | 1 | #ifndef LOCAL_ARRAY_H_included |
| 2 | #define LOCAL_ARRAY_H_included |
| 3 | |
| 4 | #include <cstddef> |
| 5 | #include <new> |
| 6 | |
| 7 | /** |
| 8 | * A fixed-size array with a size hint. That number of bytes will be allocated |
| 9 | * on the stack, and used if possible, but if more bytes are requested at |
| 10 | * construction time, a buffer will be allocated on the heap (and deallocated |
| 11 | * by the destructor). |
| 12 | * |
| 13 | * The API is intended to be a compatible subset of C++0x's std::array. |
| 14 | */ |
| 15 | template <size_t STACK_BYTE_COUNT> |
| 16 | class LocalArray { |
| 17 | public: |
| 18 | /** |
| 19 | * Allocates a new fixed-size array of the given size. If this size is |
| 20 | * less than or equal to the template parameter STACK_BYTE_COUNT, an |
| 21 | * internal on-stack buffer will be used. Otherwise a heap buffer will |
| 22 | * be allocated. |
| 23 | */ |
| 24 | LocalArray(size_t desiredByteCount) : mSize(desiredByteCount) { |
| 25 | if (desiredByteCount > STACK_BYTE_COUNT) { |
| 26 | mPtr = new char[mSize]; |
| 27 | } else { |
| 28 | mPtr = &mOnStackBuffer[0]; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Frees the heap-allocated buffer, if there was one. |
| 34 | */ |
| 35 | ~LocalArray() { |
| 36 | if (mPtr != &mOnStackBuffer[0]) { |
| 37 | delete[] mPtr; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // Capacity. |
| 42 | size_t size() { return mSize; } |
| 43 | bool empty() { return mSize == 0; } |
| 44 | |
| 45 | // Element access. |
| 46 | char& operator[](size_t n) { return mPtr[n]; } |
| 47 | const char& operator[](size_t n) const { return mPtr[n]; } |
| 48 | |
| 49 | private: |
| 50 | char mOnStackBuffer[STACK_BYTE_COUNT]; |
| 51 | char* mPtr; |
| 52 | size_t mSize; |
| 53 | }; |
| 54 | |
| 55 | #endif // LOCAL_ARRAY_H_included |