OLD | NEW |
| (Empty) |
1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
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 COMPONENTS_METRICS_LEAK_DETECTOR_STL_ALLOCATOR_H_ | |
6 #define COMPONENTS_METRICS_LEAK_DETECTOR_STL_ALLOCATOR_H_ | |
7 | |
8 #include <stddef.h> | |
9 | |
10 #include <limits> | |
11 #include <memory> | |
12 | |
13 #include "base/logging.h" | |
14 | |
15 // Generic allocator class for STL objects. | |
16 // deallocate() to use the template class Alloc's allocation. | |
17 // that uses a given type-less allocator Alloc, which must provide: | |
18 // static void* Alloc::Allocate(size_t size); | |
19 // static void Alloc::Free(void* ptr, size_t size); | |
20 // | |
21 // Inherits from the default allocator, std::allocator. Overrides allocate() and | |
22 // deallocate() and some other functions. | |
23 // | |
24 // STLAllocator<T, MyAlloc> provides the same thread-safety guarantees as | |
25 // MyAlloc. | |
26 // | |
27 // Usage example: | |
28 // set<T, less<T>, STLAllocator<T, MyAlloc> > my_set; | |
29 | |
30 template <typename T, class Alloc> | |
31 class STLAllocator : public std::allocator<T> { | |
32 public: | |
33 typedef size_t size_type; | |
34 typedef T* pointer; | |
35 | |
36 template <class T1> | |
37 struct rebind { | |
38 typedef STLAllocator<T1, Alloc> other; | |
39 }; | |
40 | |
41 STLAllocator() {} | |
42 explicit STLAllocator(const STLAllocator&) {} | |
43 template <class T1> | |
44 STLAllocator(const STLAllocator<T1, Alloc>&) {} | |
45 ~STLAllocator() {} | |
46 | |
47 pointer allocate(size_type n, const void* = 0) { | |
48 // Make sure the computation of the total allocation size does not cause an | |
49 // integer overflow. | |
50 RAW_CHECK(n < max_size()); | |
51 return static_cast<T*>(Alloc::Allocate(n * sizeof(T))); | |
52 } | |
53 | |
54 void deallocate(pointer p, size_type n) { Alloc::Free(p, n * sizeof(T)); } | |
55 | |
56 size_type max_size() const { | |
57 return std::numeric_limits<size_t>::max() / sizeof(T); | |
58 } | |
59 }; | |
60 | |
61 #endif // COMPONENTS_METRICS_LEAK_DETECTOR_STL_ALLOCATOR_H_ | |
OLD | NEW |