blob: 9d8b9fc9cfe881a84c32972a205333c5e85b4bdb [file] [log] [blame]
dawescf8674c62016-03-06 11:42:11 -06001// Copyright 2007-2010 Baptiste Lepilleur
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 CPPTL_JSON_ALLOCATOR_H_INCLUDED
7#define CPPTL_JSON_ALLOCATOR_H_INCLUDED
8
9#include <cstring>
10#include <memory>
11
12namespace Json {
13template<typename T>
14class SecureAllocator {
15 public:
16 // Type definitions
17 using value_type = T;
18 using pointer = T*;
19 using const_pointer = const T*;
20 using reference = T&;
21 using const_reference = const T&;
22 using size_type = std::size_t;
23 using difference_type = std::ptrdiff_t;
24
25 /**
26 * Allocate memory for N items using the standard allocator.
27 */
28 pointer allocate(size_type n) {
29 // allocate using "global operator new"
30 return static_cast<pointer>(::operator new(n * sizeof(T)));
31 }
32
33 /**
34 * Release memory which was allocated for N items at pointer P.
35 *
36 * The memory block is filled with zeroes before being released.
37 * The pointer argument is tagged as "volatile" to prevent the
38 * compiler optimizing out this critical step.
39 */
40 void deallocate(volatile pointer p, size_type n) {
41 std::memset(p, 0, n * sizeof(T));
42 // free using "global operator delete"
43 ::operator delete(p);
44 }
45
46 /**
47 * Construct an item in-place at pointer P.
48 */
49 template<typename... Args>
50 void construct(pointer p, Args&&... args) {
51 // construct using "placement new" and "perfect forwarding"
52 ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
53 }
54
55 size_type max_size() const {
56 return size_t(-1) / sizeof(T);
57 }
58
59 pointer address( reference x ) const {
60 return std::addressof(x);
61 }
62
63 const_pointer address( const_reference x ) const {
64 return std::addressof(x);
65 }
66
67 /**
68 * Destroy an item in-place at pointer P.
69 */
70 void destroy(pointer p) {
71 // destroy using "explicit destructor"
72 p->~T();
73 }
74
75 // Boilerplate
76 SecureAllocator() {}
77 template<typename U> SecureAllocator(const SecureAllocator<U>&) {}
78 template<typename U> struct rebind { using other = SecureAllocator<U>; };
79};
80
81
82template<typename T, typename U>
83bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
84 return true;
85}
86
87template<typename T, typename U>
88bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
89 return false;
90}
91
92} //namespace Json
93
94#endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED