Buffer.h 1.7 KB

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