1 // Common/DynamicBuffer.h
2 
3 #ifndef __COMMON_DYNAMIC_BUFFER_H
4 #define __COMMON_DYNAMIC_BUFFER_H
5 
6 template <class T> class CDynamicBuffer
7 {
8   T *_items;
9   size_t _size;
10   size_t _pos;
11 
12   CDynamicBuffer(const CDynamicBuffer &buffer);
13   void operator=(const CDynamicBuffer &buffer);
14 
Grow(size_t size)15   void Grow(size_t size)
16   {
17     size_t delta = _size >= 64 ? _size : 64;
18     if (delta < size)
19       delta = size;
20     size_t newCap = _size + delta;
21     if (newCap < delta)
22     {
23       newCap = _size + size;
24       if (newCap < size)
25         throw 20120116;
26     }
27 
28     T *newBuffer = new T[newCap];
29     if (_pos != 0)
30       memcpy(newBuffer, _items, _pos * sizeof(T));
31     delete []_items;
32     _items = newBuffer;
33     _size = newCap;
34   }
35 
36 public:
CDynamicBuffer()37   CDynamicBuffer(): _items(0), _size(0), _pos(0) {}
38   // operator T *() { return _items; }
39   operator const T *() const { return _items; }
~CDynamicBuffer()40   ~CDynamicBuffer() { delete []_items; }
41 
GetCurPtrAndGrow(size_t addSize)42   T *GetCurPtrAndGrow(size_t addSize)
43   {
44     size_t rem = _size - _pos;
45     if (rem < addSize)
46       Grow(addSize - rem);
47     T *res = _items + _pos;
48     _pos += addSize;
49     return res;
50   }
51 
AddData(const T * data,size_t size)52   void AddData(const T *data, size_t size)
53   {
54     memcpy(GetCurPtrAndGrow(size), data, size * sizeof(T));
55   }
56 
GetPos()57   const size_t GetPos() const { return _pos; }
58 
59   // void Empty() { _pos = 0; }
60 };
61 
62 typedef CDynamicBuffer<unsigned char> CByteDynamicBuffer;
63 
64 #endif
65