From 3ba802e99524797571e69ba57b6a30a12b031b72 Mon Sep 17 00:00:00 2001 From: rubidium Date: Mon, 23 Feb 2009 17:54:02 +0000 Subject: (svn r15556) -Change: don't temporary malloc+free when encoding sprites, just reuse the same piece of allocated memory for each encoding. --- src/core/alloc_type.hpp | 55 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) (limited to 'src/core/alloc_type.hpp') diff --git a/src/core/alloc_type.hpp b/src/core/alloc_type.hpp index a2bda93e4..887ba7237 100644 --- a/src/core/alloc_type.hpp +++ b/src/core/alloc_type.hpp @@ -70,6 +70,61 @@ struct SmallStackSafeStackAlloc { } }; +/** + * A reusable buffer that can be used for places that temporary allocate + * a bit of memory and do that very often, or for places where static + * memory is allocated that might need to be reallocated sometimes. + * + * Every time Allocate or ZeroAllocate is called previous results of both + * functions will become invalid. + */ +template +class ReusableBuffer { +private: + T *buffer; ///< The real data buffer + size_t count; ///< Number of T elements in the buffer + +public: + /** Create a new buffer */ + ReusableBuffer() : buffer(NULL), count(0) {} + /** Clear the buffer */ + ~ReusableBuffer() { free(this->buffer); } + + /** + * Get buffer of at least count times T. + * @note the buffer might be bigger + * @note calling this function invalidates any previous buffers given + * @param count the minimum buffer size + * @return the buffer + */ + T *Allocate(size_t count) + { + if (this->count < count) { + free(this->buffer); + this->buffer = MallocT(count); + } + return this->buffer; + } + + /** + * Get buffer of at least count times T with zeroed memory. + * @note the buffer might be bigger + * @note calling this function invalidates any previous buffers given + * @param count the minimum buffer size + * @return the buffer + */ + T *ZeroAllocate(size_t count) + { + if (this->count < count) { + free(this->buffer); + this->buffer = CallocT(count); + } else { + memset(this->buffer, 0, sizeof(T) * count); + } + return this->buffer; + } +}; + /** * Base class that provides memory initialization on dynamically created objects. * All allocated memory will be zeroed. -- cgit v1.2.3-54-g00ecf