blob: 8fad52413055a94efda2716406365e2afb8b45a4 (
plain)
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
77
78
79
80
81
82
83
|
/*
* NetworkBuffer.cpp
*
* Created on: 24 Dec 2016
* Author: David
*/
#include "NetworkBuffer.h"
#include <cstring>
NetworkBuffer *NetworkBuffer::freelist = nullptr;
NetworkBuffer::NetworkBuffer(NetworkBuffer *n) : next(n), dataLength(0), readPointer(0)
{
}
// Release this buffer and return the next one in the chain
NetworkBuffer *NetworkBuffer::Release()
{
NetworkBuffer *ret = next;
next = freelist;
freelist = this;
return ret;
}
// Read 1 character, returning true if successful, false if no data left
bool NetworkBuffer::ReadChar(char& b)
{
if (readPointer < dataLength)
{
b = data[readPointer++];
return true;
}
b = 0;
return false;
}
// Read some data, but not more than the amount in the first buffer
size_t NetworkBuffer::ReadBuffer(uint8_t *buffer, size_t maxLen)
{
if (maxLen > Remaining())
{
maxLen = Remaining();
}
memcpy((void*)buffer, data + readPointer, maxLen);
readPointer += maxLen;
return maxLen;
}
// Return the amount of data available, including continuation buffers
size_t NetworkBuffer::TotalRemaining() const
{
const NetworkBuffer *b = this;
size_t ret = 0;
while (b != nullptr)
{
ret += b->Remaining();
}
return ret;
}
/*static*/ NetworkBuffer *NetworkBuffer::Allocate()
{
NetworkBuffer *ret = freelist;
if (ret != nullptr)
{
freelist = ret->next;
ret->next = nullptr;
}
return ret;
}
/*static*/ void NetworkBuffer::AllocateBuffers(unsigned int number)
{
while (number != 0)
{
freelist = new NetworkBuffer(freelist);
--number;
}
}
// End
|