summaryrefslogtreecommitdiffstats
path: root/include
diff options
context:
space:
mode:
authorElliott Hughes <enh@google.com>2009-11-13 17:07:00 -0800
committerElliott Hughes <enh@google.com>2009-11-13 17:12:48 -0800
commit845ce3cbfd6972542b275c95eddfbb6e94469737 (patch)
tree3f4c9ac0dd9f3787bacdb67b43ab76829ed4d608 /include
parent25c2a2dcfb56959cf34e4e5e5496335be46c5e5c (diff)
downloadlibcore-845ce3cbfd6972542b275c95eddfbb6e94469737.zip
libcore-845ce3cbfd6972542b275c95eddfbb6e94469737.tar.gz
libcore-845ce3cbfd6972542b275c95eddfbb6e94469737.tar.bz2
Don't allocate arbitrary-length buffers on the stack.
A new LocalArray C++ class lets us specify a "reasonable" amount of stack to use, but transparently fall back to using the heap if we need more space. The three places I've chosen to use LocalArray in this patch are fairly random; all they have in common is that they're the places where we call GetStringUTFRegion. There are more places LocalArray will be useful: the java.io.File JNI in particular. Bug: 2257819
Diffstat (limited to 'include')
-rw-r--r--include/LocalArray.h55
1 files changed, 55 insertions, 0 deletions
diff --git a/include/LocalArray.h b/include/LocalArray.h
new file mode 100644
index 0000000..85b5a49
--- /dev/null
+++ b/include/LocalArray.h
@@ -0,0 +1,55 @@
+#ifndef LOCAL_ARRAY_H_included
+#define LOCAL_ARRAY_H_included
+
+#include <cstddef>
+#include <new>
+
+/**
+ * A fixed-size array with a size hint. That number of bytes will be allocated
+ * on the stack, and used if possible, but if more bytes are requested at
+ * construction time, a buffer will be allocated on the heap (and deallocated
+ * by the destructor).
+ *
+ * The API is intended to be a compatible subset of C++0x's std::array.
+ */
+template <size_t STACK_BYTE_COUNT>
+class LocalArray {
+public:
+ /**
+ * Allocates a new fixed-size array of the given size. If this size is
+ * less than or equal to the template parameter STACK_BYTE_COUNT, an
+ * internal on-stack buffer will be used. Otherwise a heap buffer will
+ * be allocated.
+ */
+ LocalArray(size_t desiredByteCount) : mSize(desiredByteCount) {
+ if (desiredByteCount > STACK_BYTE_COUNT) {
+ mPtr = new char[mSize];
+ } else {
+ mPtr = &mOnStackBuffer[0];
+ }
+ }
+
+ /**
+ * Frees the heap-allocated buffer, if there was one.
+ */
+ ~LocalArray() {
+ if (mPtr != &mOnStackBuffer[0]) {
+ delete[] mPtr;
+ }
+ }
+
+ // Capacity.
+ size_t size() { return mSize; }
+ bool empty() { return mSize == 0; }
+
+ // Element access.
+ char& operator[](size_t n) { return mPtr[n]; }
+ const char& operator[](size_t n) const { return mPtr[n]; }
+
+private:
+ char mOnStackBuffer[STACK_BYTE_COUNT];
+ char* mPtr;
+ size_t mSize;
+};
+
+#endif // LOCAL_ARRAY_H_included