YPC  0.2.0
zallocator.h
1 #pragma once
2 
3 #include <memory>
4 #include <openssl/evp.h>
5 #include <stdexcept>
6 #include <string>
7 
8 namespace ypc {
9 namespace openssl {
10 template <typename T> struct zallocator {
11 public:
12  typedef T value_type;
13  typedef value_type *pointer;
14  typedef const value_type *const_pointer;
15  typedef value_type &reference;
16  typedef const value_type &const_reference;
17  typedef std::size_t size_type;
18  typedef std::ptrdiff_t difference_type;
19 
20  pointer address(reference v) const { return &v; }
21  const_pointer address(const_reference v) const { return &v; }
22 
23  pointer allocate(size_type n, const void *hint = 0) {
24  if (n > std::numeric_limits<size_type>::max() / sizeof(T))
25  throw std::bad_alloc();
26  return static_cast<pointer>(::operator new(n * sizeof(value_type)));
27  }
28 
29  void deallocate(pointer p, size_type n) {
30  OPENSSL_cleanse(p, n * sizeof(T));
31  ::operator delete(p);
32  }
33 
34  size_type max_size() const {
35  return std::numeric_limits<size_type>::max() / sizeof(T);
36  }
37 
38  template <typename U> struct rebind { typedef zallocator<U> other; };
39 
40  void construct(pointer ptr, const T &val) {
41  new (static_cast<T *>(ptr)) T(val);
42  }
43 
44  void destroy(pointer ptr) { static_cast<T *>(ptr)->~T(); }
45 
46 #if __cpluplus >= 201103L
47  template <typename U, typename... Args>
48  void construct(U *ptr, Args &&... args) {
49  ::new (static_cast<void *>(ptr)) U(std::forward<Args>(args)...);
50  }
51 
52  template <typename U> void destroy(U *ptr) { ptr->~U(); }
53 #endif
54 };
55 
56 typedef std::basic_string<char, std::char_traits<char>, zallocator<char>>
57  secure_string;
58 using EVP_CIPHER_CTX_free_ptr =
59  std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>;
60 
61 } // namespace terminus
62 } // namespace ypc
ypc::openssl::zallocator
Definition: zallocator.h:10
ypc::openssl::zallocator::rebind
Definition: zallocator.h:38