allocator.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. #ifndef JSON_ALLOCATOR_H_INCLUDED
  6. #define JSON_ALLOCATOR_H_INCLUDED
  7. #include <cstring>
  8. #include <memory>
  9. #pragma pack(push)
  10. #pragma pack()
  11. namespace Json {
  12. template <typename T> class SecureAllocator {
  13. public:
  14. // Type definitions
  15. using value_type = T;
  16. using pointer = T*;
  17. using const_pointer = const T*;
  18. using reference = T&;
  19. using const_reference = const T&;
  20. using size_type = std::size_t;
  21. using difference_type = std::ptrdiff_t;
  22. /**
  23. * Allocate memory for N items using the standard allocator.
  24. */
  25. pointer allocate(size_type n) {
  26. // allocate using "global operator new"
  27. return static_cast<pointer>(::operator new(n * sizeof(T)));
  28. }
  29. /**
  30. * Release memory which was allocated for N items at pointer P.
  31. *
  32. * The memory block is filled with zeroes before being released.
  33. */
  34. void deallocate(pointer p, size_type n) {
  35. // memset_s is used because memset may be optimized away by the compiler
  36. memset_s(p, n * sizeof(T), 0, n * sizeof(T));
  37. // free using "global operator delete"
  38. ::operator delete(p);
  39. }
  40. /**
  41. * Construct an item in-place at pointer P.
  42. */
  43. template <typename... Args> void construct(pointer p, Args&&... args) {
  44. // construct using "placement new" and "perfect forwarding"
  45. ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
  46. }
  47. size_type max_size() const { return size_t(-1) / sizeof(T); }
  48. pointer address(reference x) const { return std::addressof(x); }
  49. const_pointer address(const_reference x) const { return std::addressof(x); }
  50. /**
  51. * Destroy an item in-place at pointer P.
  52. */
  53. void destroy(pointer p) {
  54. // destroy using "explicit destructor"
  55. p->~T();
  56. }
  57. // Boilerplate
  58. SecureAllocator() {}
  59. template <typename U> SecureAllocator(const SecureAllocator<U>&) {}
  60. template <typename U> struct rebind { using other = SecureAllocator<U>; };
  61. };
  62. template <typename T, typename U>
  63. bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
  64. return true;
  65. }
  66. template <typename T, typename U>
  67. bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
  68. return false;
  69. }
  70. } // namespace Json
  71. #pragma pack(pop)
  72. #endif // JSON_ALLOCATOR_H_INCLUDED