michael@0: /* michael@0: * Copyright (C) 2009 The Android Open Source Project michael@0: * michael@0: * Licensed under the Apache License, Version 2.0 (the "License"); michael@0: * you may not use this file except in compliance with the License. michael@0: * You may obtain a copy of the License at michael@0: * michael@0: * http://www.apache.org/licenses/LICENSE-2.0 michael@0: * michael@0: * Unless required by applicable law or agreed to in writing, software michael@0: * distributed under the License is distributed on an "AS IS" BASIS, michael@0: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. michael@0: * See the License for the specific language governing permissions and michael@0: * limitations under the License. michael@0: */ michael@0: michael@0: #ifndef LOCAL_ARRAY_H_included michael@0: #define LOCAL_ARRAY_H_included michael@0: michael@0: #include michael@0: #include michael@0: michael@0: /** michael@0: * A fixed-size array with a size hint. That number of bytes will be allocated michael@0: * on the stack, and used if possible, but if more bytes are requested at michael@0: * construction time, a buffer will be allocated on the heap (and deallocated michael@0: * by the destructor). michael@0: * michael@0: * The API is intended to be a compatible subset of C++0x's std::array. michael@0: */ michael@0: template michael@0: class LocalArray { michael@0: public: michael@0: /** michael@0: * Allocates a new fixed-size array of the given size. If this size is michael@0: * less than or equal to the template parameter STACK_BYTE_COUNT, an michael@0: * internal on-stack buffer will be used. Otherwise a heap buffer will michael@0: * be allocated. michael@0: */ michael@0: LocalArray(size_t desiredByteCount) : mSize(desiredByteCount) { michael@0: if (desiredByteCount > STACK_BYTE_COUNT) { michael@0: mPtr = new char[mSize]; michael@0: } else { michael@0: mPtr = &mOnStackBuffer[0]; michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Frees the heap-allocated buffer, if there was one. michael@0: */ michael@0: ~LocalArray() { michael@0: if (mPtr != &mOnStackBuffer[0]) { michael@0: delete[] mPtr; michael@0: } michael@0: } michael@0: michael@0: // Capacity. michael@0: size_t size() { return mSize; } michael@0: bool empty() { return mSize == 0; } michael@0: michael@0: // Element access. michael@0: char& operator[](size_t n) { return mPtr[n]; } michael@0: const char& operator[](size_t n) const { return mPtr[n]; } michael@0: michael@0: private: michael@0: char mOnStackBuffer[STACK_BYTE_COUNT]; michael@0: char* mPtr; michael@0: size_t mSize; michael@0: michael@0: // Disallow copy and assignment. michael@0: LocalArray(const LocalArray&); michael@0: void operator=(const LocalArray&); michael@0: }; michael@0: michael@0: #endif // LOCAL_ARRAY_H_included