OpenTTD Source  20241120-master-g6d3adc6169
alloc_type.hpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #ifndef ALLOC_TYPE_HPP
11 #define ALLOC_TYPE_HPP
12 
13 #include "alloc_func.hpp"
14 
23 template <typename T>
25 private:
26  T *buffer;
27  size_t count;
28 
29 public:
31  ReusableBuffer() : buffer(nullptr), count(0) {}
33  ~ReusableBuffer() { free(this->buffer); }
34 
42  T *Allocate(size_t count)
43  {
44  if (this->count < count) {
45  free(this->buffer);
46  this->buffer = MallocT<T>(count);
47  this->count = count;
48  }
49  return this->buffer;
50  }
51 
59  T *ZeroAllocate(size_t count)
60  {
61  if (this->count < count) {
62  free(this->buffer);
63  this->buffer = CallocT<T>(count);
64  this->count = count;
65  } else {
66  memset(this->buffer, 0, sizeof(T) * count);
67  }
68  return this->buffer;
69  }
70 
75  inline const T *GetBuffer() const
76  {
77  return this->buffer;
78  }
79 };
80 
86 {
87 public:
89  virtual ~ZeroedMemoryAllocator() = default;
90 
96  inline void *operator new(size_t size) { return CallocT<uint8_t>(size); }
97 
103  inline void *operator new[](size_t size) { return CallocT<uint8_t>(size); }
104 
109  inline void operator delete(void *ptr) { free(ptr); }
110 
115  inline void operator delete[](void *ptr) { free(ptr); }
116 };
117 
118 #endif /* ALLOC_TYPE_HPP */
Functions related to the allocation of memory.
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition: alloc_type.hpp:24
ReusableBuffer()
Create a new buffer.
Definition: alloc_type.hpp:31
T * ZeroAllocate(size_t count)
Get buffer of at least count times T with zeroed memory.
Definition: alloc_type.hpp:59
const T * GetBuffer() const
Get the currently allocated buffer.
Definition: alloc_type.hpp:75
T * buffer
The real data buffer.
Definition: alloc_type.hpp:26
size_t count
Number of T elements in the buffer.
Definition: alloc_type.hpp:27
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition: alloc_type.hpp:42
~ReusableBuffer()
Clear the buffer.
Definition: alloc_type.hpp:33
Base class that provides memory initialization on dynamically created objects.
Definition: alloc_type.hpp:86
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:334