blob: 85b5a49119092312cd052d1b2e9dbc1c356929b6 [file] [log] [blame]
Elliott Hughes845ce3c2009-11-13 17:07:00 -08001#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 */
15template <size_t STACK_BYTE_COUNT>
16class LocalArray {
17public:
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
49private:
50 char mOnStackBuffer[STACK_BYTE_COUNT];
51 char* mPtr;
52 size_t mSize;
53};
54
55#endif // LOCAL_ARRAY_H_included