]> git.proxmox.com Git - ceph.git/blob - ceph/src/common/allocator.h
buildsys: switch source download to quincy
[ceph.git] / ceph / src / common / allocator.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3
4 #ifndef CEPH_COMMON_ALLOCATOR_H
5 #define CEPH_COMMON_ALLOCATOR_H
6
7 #include "acconfig.h"
8
9 #ifdef LIBTCMALLOC_MISSING_ALIGNED_ALLOC
10 #include <malloc.h>
11 #include <new>
12 #endif
13 #include <memory>
14
15 namespace ceph {
16
17 #ifdef LIBTCMALLOC_MISSING_ALIGNED_ALLOC
18
19 // If libtcmalloc is missing 'aligned_alloc', provide a new allocator class that
20 // uses memalign which is what newer versions of tcmalloc do internally. C++17
21 // will automatically use 'operator new(size_t, align_val_t)' for aligned
22 // structures, which will invoke the missing 'aligned_alloc' tcmalloc function.
23 // This method was added to tcmalloc (gperftools) in commit d406f228 after
24 // the 2.6.1 release was tagged.
25 template <typename T>
26 struct allocator : public std::allocator<T> {
27 using pointer = typename std::allocator<T>::pointer;
28 using size_type = typename std::allocator<T>::size_type;
29
30 template<class U>
31 struct rebind {
32 typedef allocator<U> other;
33 };
34
35 allocator() noexcept {
36 }
37
38 allocator(const allocator& other) noexcept : std::allocator<T>(other) {
39 }
40
41 template <class U>
42 allocator(const allocator<U>& other) noexcept : std::allocator<T>(other) {
43 }
44
45 pointer allocate(size_type n, const void* hint = nullptr) {
46 if (n > this->max_size()) {
47 throw std::bad_alloc();
48 }
49
50 if (alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
51 return static_cast<T*>(memalign(alignof(T), n * sizeof(T)));
52 }
53 return std::allocator<T>::allocate(n, hint);
54 }
55 };
56
57 #else // LIBTCMALLOC_MISSING_ALIGNED_ALLOC
58
59 // re-use the full std::allocator implementation if tcmalloc is functional
60
61 template <typename T>
62 using allocator = std::allocator<T>;
63
64 #endif // LIBTCMALLOC_MISSING_ALIGNED_ALLOC
65
66 } // namespace ceph
67
68 #endif // CEPH_COMMON_ALLOCATOR_H
69