1 // Copyright 2018 The Abseil Authors.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #ifndef ABSL_CONTAINER_INTERNAL_COUNTING_ALLOCATOR_H_
16 #define ABSL_CONTAINER_INTERNAL_COUNTING_ALLOCATOR_H_
23 namespace container_internal {
25 // This is a stateful allocator, but the state lives outside of the
26 // allocator (in whatever test is using the allocator). This is odd
27 // but helps in tests where the allocator is propagated into nested
28 // containers - that chain of allocators uses the same state and is
29 // thus easier to query for aggregate allocation information.
31 class CountingAllocator : public std::allocator<T> {
33 using Alloc = std::allocator<T>;
34 using pointer = typename Alloc::pointer;
35 using size_type = typename Alloc::size_type;
37 CountingAllocator() : bytes_used_(nullptr) {}
38 explicit CountingAllocator(int64_t* b) : bytes_used_(b) {}
41 CountingAllocator(const CountingAllocator<U>& x)
42 : Alloc(x), bytes_used_(x.bytes_used_) {}
44 pointer allocate(size_type n,
45 std::allocator<void>::const_pointer hint = nullptr) {
46 assert(bytes_used_ != nullptr);
47 *bytes_used_ += n * sizeof(T);
48 return Alloc::allocate(n, hint);
51 void deallocate(pointer p, size_type n) {
52 Alloc::deallocate(p, n);
53 assert(bytes_used_ != nullptr);
54 *bytes_used_ -= n * sizeof(T);
60 using other = CountingAllocator<U>;
63 friend bool operator==(const CountingAllocator& a,
64 const CountingAllocator& b) {
65 return a.bytes_used_ == b.bytes_used_;
68 friend bool operator!=(const CountingAllocator& a,
69 const CountingAllocator& b) {
76 } // namespace container_internal
79 #endif // ABSL_CONTAINER_INTERNAL_COUNTING_ALLOCATOR_H_