]> git.ipfire.org Git - thirdparty/squid.git/blob - src/mem/AllocatorProxy.h
Source Format Enforcement (#763)
[thirdparty/squid.git] / src / mem / AllocatorProxy.h
1 /*
2 * Copyright (C) 1996-2021 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 #ifndef _SQUID_SRC_MEM_ALLOCATORPROXY_H
10 #define _SQUID_SRC_MEM_ALLOCATORPROXY_H
11
12 class MemAllocator;
13 class MemPoolStats;
14 class MemPoolMeter;
15
16 /**
17 * \hideinitializer
18 *
19 * Pool and account the memory used for the CLASS object.
20 * This macro is intended for use within the declaration of a class.
21 *
22 * The memory block allocated by operator new is not zeroed; it is the
23 * responsibility of users to ensure that constructors correctly
24 * initialize all data members.
25 */
26 #define MEMPROXY_CLASS(CLASS) \
27 private: \
28 static inline Mem::AllocatorProxy &Pool() { \
29 static Mem::AllocatorProxy thePool(#CLASS, sizeof(CLASS), false); \
30 return thePool; \
31 } \
32 public: \
33 void *operator new(size_t byteCount) { \
34 /* derived classes with different sizes must implement their own new */ \
35 assert(byteCount == sizeof(CLASS)); \
36 return Pool().alloc(); \
37 } \
38 void operator delete(void *address) { \
39 if (address) \
40 Pool().freeOne(address); \
41 } \
42 static int UseCount() { return Pool().inUseCount(); } \
43 private:
44
45 namespace Mem
46 {
47
48 /**
49 * Support late binding of pool type for allocator agnostic classes
50 */
51 class AllocatorProxy
52 {
53 public:
54 AllocatorProxy(char const *aLabel, size_t const &aSize, bool doZeroBlocks = true):
55 label(aLabel),
56 size(aSize),
57 theAllocator(nullptr),
58 doZero(doZeroBlocks)
59 {}
60
61 /// Allocate one element from the pool
62 void *alloc();
63
64 /// Free a element allocated by Mem::AllocatorProxy::alloc()
65 void freeOne(void *);
66
67 int inUseCount() const;
68 size_t objectSize() const {return size;}
69 char const * objectType() const {return label;}
70
71 MemPoolMeter const &getMeter() const;
72
73 /**
74 * \param stats Object to be filled with statistical data about pool.
75 * \retval Number of objects in use, ie. allocated.
76 */
77 int getStats(MemPoolStats * stats);
78
79 void zeroBlocks(bool doIt);
80
81 private:
82 MemAllocator *getAllocator() const;
83
84 const char *label;
85 size_t size;
86 mutable MemAllocator *theAllocator;
87 bool doZero;
88 };
89
90 } // namespace Mem
91
92 #endif /* _SQUID_SRC_MEM_ALLOCATORPROXY_H */
93