aboutsummaryrefslogtreecommitdiff
path: root/libcommon/buffer.hxx
blob: 41b7e46358a2454fc8fdae14cbf160a034d604e8 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// file      : libcommon/buffer.hxx
// license   : GNU GPL v2; see accompanying LICENSE file

#ifndef LIBCOMMON_BUFFER_HXX
#define LIBCOMMON_BUFFER_HXX

#include <new>
#include <cstddef> // std::size_t
#include <cstring> // std::{memcmp,memcpy}

struct basic_buffer_base
{
  ~basic_buffer_base ()
  {
    operator delete (data_);
  }

  basic_buffer_base ()
      : data_ (0), size_ (0)
  {
  }

  basic_buffer_base (const void* data, std::size_t size)
      : data_ (0), size_ (size)
  {
    data_ = operator new (size_);
    std::memcpy (data_, data, size_);
  }

  basic_buffer_base (const basic_buffer_base& y)
      : data_ (0), size_ (0)
  {
    assign (y.data_, y.size_);
  }

  basic_buffer_base&
  operator= (const basic_buffer_base& y)
  {
    if (this != &y)
      assign (y.data_, y.size_);

    return *this;
  }

  void
  assign (const void* data, std::size_t size)
  {
    if (size_ < size)
    {
      void *p (operator new (size));
      operator delete (data_);
      data_ = p;
    }

    std::memcpy (data_, data, size);
    size_ = size;
  }

  std::size_t
  size () const
  {
    return size_;
  }

  bool
  operator== (const basic_buffer_base& y) const
  {
    return size_ == y.size_ && std::memcmp (data_, y.data_, size_) == 0;
  }

protected:
  void* data_;
  std::size_t size_;
};

template <typename T>
struct basic_buffer: basic_buffer_base
{
  basic_buffer ()
  {
  }

  basic_buffer (const T* data, std::size_t size)
      : basic_buffer_base (data, size)
  {
  }

  T*
  data ()
  {
    return static_cast<T*> (data_);
  }

  const T*
  data () const
  {
    return static_cast<const T*> (data_);
  }
};

typedef basic_buffer<char> buffer;
typedef basic_buffer<unsigned char> ubuffer;

#endif // LIBCOMMON_BUFFER_HXX