summaryrefslogtreecommitdiffstats
path: root/noinitvector.hh
blob: cc7efc30e0af2bd4aab5a696ebc628299e126fc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#pragma once

#include <memory>
#include <new>
#include <utility>
#include <vector>

// based on boost::core::noinit_adaptor
// The goal is to avoid initialization of the content of a container,
// because setting several kB of uint8_t to 0 has a real cost if you
// do 100k times per second.
template<class Allocator>
struct noinit_adaptor: Allocator
{
  template<class U>
  struct rebind {
    typedef noinit_adaptor<typename std::allocator_traits<Allocator>::template
                           rebind_alloc<U> > other;
    };

  noinit_adaptor(): Allocator() { }

  template<class U>
  noinit_adaptor(U&& u) noexcept : Allocator(std::forward<U>(u)) { }

  template<class U>
  noinit_adaptor(const noinit_adaptor<U>& u) noexcept : Allocator(static_cast<const U&>(u)) { }

  template<class U>
  void construct(U* p) {
    ::new((void*)p) U;
  }

  template<class U, class V, class... Args>
  void construct(U* p, V&& v, Args&&... args) {
    ::new((void*)p) U(std::forward<V>(v), std::forward<Args>(args)...);
  }

  template<class U>
  void destroy(U* p) {
    p->~U();
  }
};

template<class T, class U>
inline bool operator==(const noinit_adaptor<T>& lhs,
                       const noinit_adaptor<U>& rhs) noexcept
{
  return static_cast<const T&>(lhs) == static_cast<const U&>(rhs);
}

template<class T, class U>
inline bool operator!=(const noinit_adaptor<T>& lhs,
                       const noinit_adaptor<U>& rhs) noexcept
{
  return !(lhs == rhs);
}

template<class Allocator>
inline noinit_adaptor<Allocator> noinit_adapt(const Allocator& a) noexcept
{
  return noinit_adaptor<Allocator>(a);
}

template<class T> using NoInitVector = std::vector<T, noinit_adaptor<std::allocator<T>>>;

using PacketBuffer = NoInitVector<uint8_t>;