-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDataBuffer.cpp
More file actions
76 lines (63 loc) · 2.33 KB
/
DataBuffer.cpp
File metadata and controls
76 lines (63 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "DataBuffer.h"
#include "log.h"
#include <stdlib.h>
#include "app_exceptions.h"
DataBuffer::DataBuffer(int initial_size) {
_bytes_allocated = initial_size;
_storage = (char *) malloc(initial_size);
_position = 0;
_bytes_written = 0;
_CHUNK_SIZE_ = 8192;
}
DataBuffer::~DataBuffer() {
free(_storage);
}
void DataBuffer::read_next_chunk(SOCKET socket) {
reserve_capacity_from_end(_CHUNK_SIZE_);
int count = recv(socket, end_of_data(), _CHUNK_SIZE_, 0);
if(count <= 0) {
// socket is broken
// // LOGE << "DataBuffer::read_next_chunk returned <= 0";
throw EventConnectionBroken();
}
_bytes_written += count;
}
void DataBuffer::reserve_capacity_from_start(int amount_needed) {
int existing_space = _bytes_allocated - _position;
if(existing_space < amount_needed) {
int space_to_allocate = _position + amount_needed + (_CHUNK_SIZE_ * 4); // add extra space to allocation to reduce number of realloc()'s
_storage = (char *) realloc(_storage, space_to_allocate);
if(_storage == NULL) {
LOGE << "DataBuffer::reserve_capacity_from_start realloc() error amount_needed=" << amount_needed << " space_to_allocate=" << space_to_allocate;
throw ErrorOutOfMemory("DataBuffer::realloc()");
}
_bytes_allocated = space_to_allocate;
}
}
void DataBuffer::reserve_capacity_from_end(int amount_needed) {
if(_bytes_allocated < amount_needed + _bytes_written) {
int space_to_allocate = amount_needed + _bytes_written + (_CHUNK_SIZE_ * 4); // add extra space to allocation to reduce number of realloc()'s
_storage = (char *) realloc(_storage, space_to_allocate);
if(_storage == NULL) {
LOGE << "DataBuffer::reserve_capacity_from_end realloc() error amount_needed=" << amount_needed << " space_to_allocate=" << space_to_allocate;
throw ErrorOutOfMemory("DataBuffer::realloc()");
}
_bytes_allocated = space_to_allocate;
}
}
void DataBuffer::clear() {
_bytes_written = 0;
_position = 0;
}
void DataBuffer::write_to_end(const char * data, int amount) {
reserve_capacity_from_end(amount);
memcpy(end_of_data(), data, amount);
_bytes_written += amount;
}
DataBuffer::DataBuffer() {
_bytes_allocated = 0;
_storage = NULL;
_position = 0;
_bytes_written = 0;
_CHUNK_SIZE_ = 8192;
}