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     memcpy(newBuffer, _items, _pos * sizeof(T));
30     delete []_items;
31     _items = newBuffer;
32     _size = newCap;
33   }
34 
35 public:
CDynamicBuffer()36   CDynamicBuffer(): _items(0), _size(0), _pos(0) {}
37   // operator T *() { return _items; };
38   operator const T *() const { return _items; };
~CDynamicBuffer()39   ~CDynamicBuffer() { delete []_items; }
40 
GetCurPtrAndGrow(size_t addSize)41   T *GetCurPtrAndGrow(size_t addSize)
42   {
43     size_t rem = _size - _pos;
44     if (rem < addSize)
45       Grow(addSize - rem);
46     T *res = _items + _pos;
47     _pos += addSize;
48     return res;
49   }
50 
GetPos()51   const size_t GetPos() const { return _pos; }
52 
53   // void Empty() { _pos = 0; }
54 };
55 
56 typedef CDynamicBuffer<unsigned char> CByteDynamicBuffer;
57 
58 #endif
59