Debian Codegraph @

include/json/allocator.h

raw
1 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2 // Distributed under MIT license, or public domain if desired and
3 // recognized in your jurisdiction.
4 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
5
6 #ifndef JSON_ALLOCATOR_H_INCLUDED
7 #define JSON_ALLOCATOR_H_INCLUDED
8
9 #include <algorithm>
10 #include <cstring>
11 #include <memory>
12
13 #pragma pack(push)
14 #pragma pack()
15
16 namespace Json {
17 template <typename T> class SecureAllocator {
18 public:
19 // Type definitions
20 using value_type = T;
21 using pointer = T*;
22 using const_pointer = const T*;
23 using reference = T&;
24 using const_reference = const T&;
25 using size_type = std::size_t;
26 using difference_type = std::ptrdiff_t;
27
28 /**
29 * Allocate memory for N items using the standard allocator.
30 */
31 pointer allocate(size_type n) {
32 // allocate using "global operator new"
33 return static_cast<pointer>(::operator new(n * sizeof(T)));
34 }
35
36 /**
37 * Release memory which was allocated for N items at pointer P.
38 *
39 * The memory block is filled with zeroes before being released.
40 */
41 void deallocate(pointer p, size_type n) {
42 // These constructs will not be removed by the compiler during optimization,
43 // unlike memset.
44 #if defined(HAVE_MEMSET_S)
45 memset_s(p, n * sizeof(T), 0, n * sizeof(T));
46 #elif defined(_WIN32)
47 RtlSecureZeroMemory(p, n * sizeof(T));
48 #else
49 std::fill_n(reinterpret_cast<volatile unsigned char*>(p), n, 0);
50 #endif
51
52 // free using "global operator delete"
53 ::operator delete(p);
54 }
55
56 /**
57 * Construct an item in-place at pointer P.
58 */
59 template <typename... Args> void construct(pointer p, Args&&... args) {
60 // construct using "placement new" and "perfect forwarding"
61 ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
62 }
63
64 size_type max_size() const { return size_t(-1) / sizeof(T); }
65
66 pointer address(reference x) const { return std::addressof(x); }
67
68 const_pointer address(const_reference x) const { return std::addressof(x); }
69
70 /**
71 * Destroy an item in-place at pointer P.
72 */
73 void destroy(pointer p) {
74 // destroy using "explicit destructor"
75 p->~T();
76 }
77
78 // Boilerplate
79 SecureAllocator() {}
80 template <typename U> SecureAllocator(const SecureAllocator<U>&) {}
81 template <typename U> struct rebind {
82 using other = SecureAllocator<U>;
83 };
84 };
85
86 template <typename T, typename U>
87 bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
88 return true;
89 }
90
91 template <typename T, typename U>
92 bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
93 return false;
94 }
95
96 } // namespace Json
97
98 #pragma pack(pop)
99
100 #endif // JSON_ALLOCATOR_H_INCLUDED