diff options
author | rubidium <rubidium@openttd.org> | 2009-02-23 17:54:02 +0000 |
---|---|---|
committer | rubidium <rubidium@openttd.org> | 2009-02-23 17:54:02 +0000 |
commit | 9ab8a2aab1783199fd5c33665ed891e4b487a7e8 (patch) | |
tree | 52608fad0b8c58f9fc141f8ff4e5d203be54f7fc /src/core | |
parent | 44821e60eb6bc9cb4eb1561c8a6d11c98a8f07ae (diff) | |
download | openttd-9ab8a2aab1783199fd5c33665ed891e4b487a7e8.tar.xz |
(svn r15556) -Change: don't temporary malloc+free when encoding sprites, just reuse the same piece of allocated memory for each encoding.
Diffstat (limited to 'src/core')
-rw-r--r-- | src/core/alloc_type.hpp | 55 |
1 files changed, 55 insertions, 0 deletions
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 @@ -71,6 +71,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 <typename T> +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<T>(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<T>(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. */ |