1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_FOR_TESTING_H_ 6 #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_FOR_TESTING_H_ 7 8 #include "base/allocator/partition_allocator/partition_alloc.h" 9 10 namespace partition_alloc { 11 namespace internal { 12 13 constexpr bool AllowLeaks = true; 14 constexpr bool DisallowLeaks = false; 15 16 // A subclass of PartitionAllocator for testing. It will free all resources, 17 // i.e. allocated memory, memory inside freelist, and so on, when destructing 18 // it or when manually invoking reset(). 19 // If need to check if there are any memory allocated but not freed yet, 20 // use allow_leaks=false. We will see CHECK failure inside reset() if any 21 // leak is detected. Otherwise (e.g. intentional leaks), use allow_leaks=true. 22 template <bool thread_safe, bool allow_leaks> 23 struct PartitionAllocatorForTesting : public PartitionAllocator<thread_safe> { PartitionAllocatorForTestingPartitionAllocatorForTesting24 PartitionAllocatorForTesting() : PartitionAllocator<thread_safe>() {} 25 PartitionAllocatorForTestingPartitionAllocatorForTesting26 explicit PartitionAllocatorForTesting(PartitionOptions opts) 27 : PartitionAllocator<thread_safe>() { 28 PartitionAllocator<thread_safe>::init(opts); 29 } 30 ~PartitionAllocatorForTestingPartitionAllocatorForTesting31 ~PartitionAllocatorForTesting() { reset(); } 32 resetPartitionAllocatorForTesting33 PA_ALWAYS_INLINE void reset() { 34 PartitionAllocator<thread_safe>::root()->ResetForTesting(allow_leaks); 35 } 36 }; 37 38 } // namespace internal 39 40 using PartitionAllocatorForTesting = 41 internal::PartitionAllocatorForTesting<internal::ThreadSafe, 42 internal::DisallowLeaks>; 43 44 using PartitionAllocatorAllowLeaksForTesting = 45 internal::PartitionAllocatorForTesting<internal::ThreadSafe, 46 internal::AllowLeaks>; 47 48 } // namespace partition_alloc 49 50 #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_FOR_TESTING_H_ 51