2013-12-24 09:25:30 +01:00
|
|
|
#ifndef __BUFFEREDDATA_H__
|
|
|
|
#define __BUFFEREDDATA_H__
|
|
|
|
|
2014-01-14 08:48:20 +01:00
|
|
|
#include <stddef.h>
|
|
|
|
#include <stdlib.h>
|
2014-01-24 09:29:27 +01:00
|
|
|
#include "../test_stdint.h"
|
2014-02-06 09:55:12 +01:00
|
|
|
#include <algorithm>
|
2013-12-24 09:25:30 +01:00
|
|
|
|
2014-01-08 04:42:58 +01:00
|
|
|
class BufferedData {
|
|
|
|
public:
|
|
|
|
BufferedData() : data_(NULL), capacity_(0), length_(0) {}
|
2013-12-24 09:25:30 +01:00
|
|
|
|
|
|
|
~BufferedData() {
|
|
|
|
free(data_);
|
|
|
|
}
|
|
|
|
|
2014-02-05 11:04:32 +01:00
|
|
|
bool PushBack(uint8_t c) {
|
2013-12-24 09:25:30 +01:00
|
|
|
if (!EnsureCapacity(length_ + 1)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
data_[length_++] = c;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2014-02-05 11:04:32 +01:00
|
|
|
bool PushBack(const uint8_t* data, size_t len) {
|
2014-01-18 12:31:54 +01:00
|
|
|
if (!EnsureCapacity(length_ + len)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
memcpy(data_ + length_, data, len);
|
|
|
|
length_ += len;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2014-02-05 11:04:32 +01:00
|
|
|
size_t PopFront(uint8_t* ptr, size_t len) {
|
2014-01-18 12:31:54 +01:00
|
|
|
len = std::min(length_, len);
|
|
|
|
memcpy(ptr, data_, len);
|
2014-02-05 11:04:32 +01:00
|
|
|
memmove(data_, data_ + len, length_ - len);
|
2014-01-18 12:31:54 +01:00
|
|
|
SetLength(length_ - len);
|
|
|
|
return len;
|
|
|
|
}
|
|
|
|
|
2013-12-24 09:25:30 +01:00
|
|
|
void Clear() {
|
|
|
|
length_ = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void SetLength(size_t newLen) {
|
|
|
|
if (EnsureCapacity(newLen)) {
|
|
|
|
length_ = newLen;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t Length() const {
|
|
|
|
return length_;
|
|
|
|
}
|
|
|
|
|
|
|
|
uint8_t* data() {
|
|
|
|
return data_;
|
|
|
|
}
|
|
|
|
|
2014-01-08 04:42:58 +01:00
|
|
|
private:
|
2013-12-24 09:25:30 +01:00
|
|
|
bool EnsureCapacity(size_t capacity) {
|
|
|
|
if (capacity > capacity_) {
|
|
|
|
size_t newsize = capacity * 2;
|
|
|
|
|
|
|
|
uint8_t* data = static_cast<uint8_t*>(realloc(data_, newsize));
|
|
|
|
|
|
|
|
if (!data)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
data_ = data;
|
|
|
|
capacity_ = newsize;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
uint8_t* data_;
|
|
|
|
size_t capacity_;
|
|
|
|
size_t length_;
|
|
|
|
};
|
|
|
|
|
|
|
|
#endif //__BUFFEREDDATA_H__
|