-
Notifications
You must be signed in to change notification settings - Fork 0
/
Buffer.cpp
executable file
·49 lines (44 loc) · 1.05 KB
/
Buffer.cpp
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
#include "Buffer.h"
namespace netlib{
char* Buffer::makeRoom(size_t len) {
if (e_ + len <= cap_) {
} else if (size() + len < cap_ / 2) {
moveHead();
} else {
expand(len);
}
return end();
}
void Buffer::expand(size_t len) {
size_t ncap = std::max(exp_, std::max(2*cap_, size()+len));
char* p = new char[ncap];
std::copy(begin(), end(), p);
e_ -= b_;
b_ = 0;
delete[] buf_;
buf_ = p;
cap_ = ncap;
}
void Buffer::copyFrom(const Buffer& b) {
memcpy(this, &b, sizeof b);
if (size()) {
buf_ = new char[cap_];
memcpy(data(), b.begin(), b.size());
}
}
Buffer& Buffer::absorb(Buffer& buf) {
if (&buf != this) {
if (size() == 0) {
char b[sizeof buf];
memcpy(b, this, sizeof b);
memcpy(this, &buf, sizeof b);
memcpy(&buf, b, sizeof b);
std::swap(exp_, buf.exp_); //keep the origin exp_
} else {
append(buf.begin(), buf.size());
buf.clear();
}
}
return *this;
}
}