blob: 2ab708affc69af09fa28a3fc96ecf54211133d9b [file] [log] [blame]
Elliott Hughesb5fc5ec2009-11-19 18:32:43 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughes845ce3c2009-11-13 17:07:00 -080017#ifndef LOCAL_ARRAY_H_included
18#define LOCAL_ARRAY_H_included
19
20#include <cstddef>
21#include <new>
22
23/**
24 * A fixed-size array with a size hint. That number of bytes will be allocated
25 * on the stack, and used if possible, but if more bytes are requested at
26 * construction time, a buffer will be allocated on the heap (and deallocated
27 * by the destructor).
28 *
29 * The API is intended to be a compatible subset of C++0x's std::array.
30 */
31template <size_t STACK_BYTE_COUNT>
32class LocalArray {
33public:
34 /**
35 * Allocates a new fixed-size array of the given size. If this size is
36 * less than or equal to the template parameter STACK_BYTE_COUNT, an
37 * internal on-stack buffer will be used. Otherwise a heap buffer will
38 * be allocated.
39 */
40 LocalArray(size_t desiredByteCount) : mSize(desiredByteCount) {
41 if (desiredByteCount > STACK_BYTE_COUNT) {
42 mPtr = new char[mSize];
43 } else {
44 mPtr = &mOnStackBuffer[0];
45 }
46 }
47
48 /**
49 * Frees the heap-allocated buffer, if there was one.
50 */
51 ~LocalArray() {
52 if (mPtr != &mOnStackBuffer[0]) {
53 delete[] mPtr;
54 }
55 }
56
57 // Capacity.
58 size_t size() { return mSize; }
59 bool empty() { return mSize == 0; }
60
61 // Element access.
62 char& operator[](size_t n) { return mPtr[n]; }
63 const char& operator[](size_t n) const { return mPtr[n]; }
64
65private:
66 char mOnStackBuffer[STACK_BYTE_COUNT];
67 char* mPtr;
68 size_t mSize;
Elliott Hughes7ca6fd02010-03-29 20:51:48 -070069
70 // Disallow copy and assignment.
71 LocalArray(const LocalArray&);
72 void operator=(const LocalArray&);
Elliott Hughes845ce3c2009-11-13 17:07:00 -080073};
74
75#endif // LOCAL_ARRAY_H_included