1 #ifndef __BUFFEREDDATA_H__ 2 #define __BUFFEREDDATA_H__ 3 4 #include <gtest/gtest.h> 5 #include <stddef.h> 6 #include <stdlib.h> 7 #include "../test_stdint.h" 8 #include <algorithm> 9 10 class BufferedData { 11 public: BufferedData()12 BufferedData() : data_ (NULL), capacity_ (0), length_ (0) {} 13 ~BufferedData()14 ~BufferedData() { 15 free (data_); 16 } 17 PushBack(uint8_t c)18 bool PushBack (uint8_t c) { 19 if (!EnsureCapacity (length_ + 1)) { 20 return false; 21 } 22 data_[length_++] = c; 23 return true; 24 } 25 PushBack(const uint8_t * data,size_t len)26 bool PushBack (const uint8_t* data, size_t len) { 27 if (!EnsureCapacity (length_ + len)) { 28 return false; 29 } 30 memcpy (data_ + length_, data, len); 31 length_ += len; 32 return true; 33 } 34 PopFront(uint8_t * ptr,size_t len)35 size_t PopFront (uint8_t* ptr, size_t len) { 36 len = std::min (length_, len); 37 memcpy (ptr, data_, len); 38 memmove (data_, data_ + len, length_ - len); 39 if (-1 == SetLength (length_ - len)) 40 return -1; 41 return len; 42 } 43 Clear()44 void Clear() { 45 length_ = 0; 46 } 47 SetLength(size_t newLen)48 int SetLength (size_t newLen) { 49 if (EnsureCapacity (newLen)) { 50 length_ = newLen; 51 } else { 52 Clear(); 53 //FAIL () << "unable to alloc memory in SetLength()"; 54 std::cout << "unable to alloc memory in SetLength()" << std::endl; 55 return -1; 56 } 57 58 return 0; 59 } 60 Length()61 size_t Length() const { 62 return length_; 63 } 64 data()65 uint8_t* data() { 66 return data_; 67 } 68 69 private: EnsureCapacity(size_t capacity)70 bool EnsureCapacity (size_t capacity) { 71 if (capacity > capacity_) { 72 size_t newsize = capacity * 2; 73 74 uint8_t* data = static_cast<uint8_t*> (realloc (data_, newsize)); 75 76 if (!data) 77 return false; 78 79 data_ = data; 80 capacity_ = newsize; 81 return true; 82 } 83 return true; 84 } 85 86 uint8_t* data_; 87 size_t capacity_; 88 size_t length_; 89 }; 90 91 #endif //__BUFFEREDDATA_H__ 92