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 | 3ba802e99524797571e69ba57b6a30a12b031b72 (patch) | |
tree | 52608fad0b8c58f9fc141f8ff4e5d203be54f7fc /src/core | |
parent | 0c1b8ea602de72a96573b7e3301589e8e3249ca1 (diff) | |
download | openttd-3ba802e99524797571e69ba57b6a30a12b031b72.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. */ |