other-licenses/7zstub/src/Common/Buffer.h

Fri, 16 Jan 2015 18:13:44 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Fri, 16 Jan 2015 18:13:44 +0100
branch
TOR_BUG_9701
changeset 14
925c144e1f1f
permissions
-rw-r--r--

Integrate suggestion from review to improve consistency with existing code.

     1 // Common/Buffer.h
     3 #ifndef __COMMON_BUFFER_H
     4 #define __COMMON_BUFFER_H
     6 #include "Defs.h"
     8 template <class T> class CBuffer
     9 {    
    10 protected:
    11 	size_t _capacity;
    12   T *_items;
    13   void Free()
    14   {
    15     delete []_items;
    16     _items = 0;
    17     _capacity = 0;
    18   }
    19 public:
    20   CBuffer(): _capacity(0), _items(0) {};
    21   CBuffer(const CBuffer &buffer): _capacity(0), _items(0) { *this = buffer; }
    22   CBuffer(size_t size): _items(0),  _capacity(0) {  SetCapacity(size); }
    23   virtual ~CBuffer() { delete []_items; }
    24   operator T *() { return _items; };
    25   operator const T *() const { return _items; };
    26   size_t GetCapacity() const { return  _capacity; }
    27   void SetCapacity(size_t newCapacity)
    28   {
    29     if (newCapacity == _capacity)
    30       return;
    31     T *newBuffer;
    32     if (newCapacity > 0)
    33     {
    34       newBuffer = new T[newCapacity];
    35       if(_capacity > 0)
    36         memmove(newBuffer, _items, MyMin(_capacity, newCapacity) * sizeof(T));
    37     }
    38     else
    39       newBuffer = 0;
    40     delete []_items;
    41     _items = newBuffer;
    42     _capacity = newCapacity;
    43   }
    44   CBuffer& operator=(const CBuffer &buffer)
    45   {
    46     Free();
    47     if(buffer._capacity > 0)
    48     {
    49       SetCapacity(buffer._capacity);
    50       memmove(_items, buffer._items, buffer._capacity * sizeof(T));
    51     }
    52     return *this;
    53   }
    54 };
    56 template <class T>
    57 bool operator==(const CBuffer<T>& b1, const CBuffer<T>& b2)
    58 {
    59   if (b1.GetCapacity() != b2.GetCapacity())
    60     return false;
    61   for (size_t i = 0; i < b1.GetCapacity(); i++)
    62     if (b1[i] != b2[i])
    63       return false;
    64   return true;
    65 }
    67 template <class T>
    68 bool operator!=(const CBuffer<T>& b1, const CBuffer<T>& b2)
    69 {
    70   return !(b1 == b2);
    71 }
    73 typedef CBuffer<char> CCharBuffer;
    74 typedef CBuffer<wchar_t> CWCharBuffer;
    75 typedef CBuffer<unsigned char> CByteBuffer;
    77 #endif

mercurial