]> git.ipfire.org Git - thirdparty/squid.git/blob - src/mem/AllocatorProxy.h
Refactor memory pools statistics gathering (#1186)
[thirdparty/squid.git] / src / mem / AllocatorProxy.h
1 /*
2 * Copyright (C) 1996-2022 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 // XXX: remove AllocatorProxy.h include from mem/forward.h
13 namespace Mem {
14 class Allocator;
15 class PoolStats;
16 }
17
18 /**
19 * \hideinitializer
20 *
21 * Pool and account the memory used for the CLASS object.
22 * This macro is intended for use within the declaration of a class.
23 *
24 * The memory block allocated by operator new is not zeroed; it is the
25 * responsibility of users to ensure that constructors correctly
26 * initialize all data members.
27 */
28 #define MEMPROXY_CLASS(CLASS) \
29 private: \
30 static inline Mem::AllocatorProxy &Pool() { \
31 static Mem::AllocatorProxy thePool(#CLASS, sizeof(CLASS), false); \
32 return thePool; \
33 } \
34 public: \
35 void *operator new(size_t byteCount) { \
36 /* derived classes with different sizes must implement their own new */ \
37 assert(byteCount == sizeof(CLASS)); \
38 return Pool().alloc(); \
39 } \
40 void operator delete(void *address) { \
41 if (address) \
42 Pool().freeOne(address); \
43 } \
44 static int UseCount() { return Pool().inUseCount(); } \
45 private:
46
47 namespace Mem
48 {
49
50 class PoolMeter;
51
52 /**
53 * Support late binding of pool type for allocator agnostic classes
54 */
55 class AllocatorProxy
56 {
57 public:
58 AllocatorProxy(char const *aLabel, size_t const &aSize, bool doZeroBlocks = true):
59 label(aLabel),
60 size(aSize),
61 theAllocator(nullptr),
62 doZero(doZeroBlocks)
63 {}
64
65 /// Allocate one element from the pool
66 void *alloc();
67
68 /// Free a element allocated by Mem::AllocatorProxy::alloc()
69 void freeOne(void *);
70
71 int inUseCount() const;
72 size_t objectSize() const {return size;}
73 char const * objectType() const {return label;}
74
75 PoolMeter const &getMeter() const;
76
77 /**
78 * \param stats Object to be filled with statistical data about pool.
79 * \retval Number of objects in use, ie. allocated.
80 */
81 size_t getStats(PoolStats &stats);
82
83 void zeroBlocks(bool doIt);
84
85 private:
86 Allocator *getAllocator() const;
87
88 const char *label;
89 size_t size;
90 mutable Allocator *theAllocator;
91 bool doZero;
92 };
93
94 } // namespace Mem
95
96 #endif /* _SQUID_SRC_MEM_ALLOCATORPROXY_H */
97