-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuffer.cpp
More file actions
55 lines (46 loc) · 1.27 KB
/
Copy pathBuffer.cpp
File metadata and controls
55 lines (46 loc) · 1.27 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
#include "Buffer.h"
#include <iostream>
#include <cerrno>
Buffer::Buffer() {
buffer_.reserve(4096);
}
ssize_t Buffer::readFromFd(int fd) {
char tmp[4096];
while (true) {
ssize_t n = recv(fd, tmp, sizeof(tmp), 0);
if (n > 0) {
buffer_.append(tmp, n);
return n;
}
if (n == 0) return 0; // 对端正常关闭
if (errno == EINTR) continue; // 被信号打断,重试
return -1; // EAGAIN 或真实错误,由调用方检查 errno
}
}
void Buffer::retrieve(size_t len) {
if (len > buffer_.size()) len = buffer_.size();
buffer_.erase(0, len);
}
void Buffer::append(const char* data, size_t len) {
buffer_.append(data, len);
}
const char* Buffer::data() const {
return buffer_.data();
}
size_t Buffer::size() const {
return buffer_.size();
}
std::string Buffer::retrieveAsString(size_t len) {
if (len > buffer_.size()) len = buffer_.size();
std::string result(buffer_.begin(), buffer_.begin() + len);
buffer_.erase(0, len);
return result;
}
void Buffer::clear() {
buffer_.clear();
}
int Buffer::findCRLF() const {
size_t pos = buffer_.find("\r\n");
if (pos == std::string::npos) return -1;
return static_cast<int>(pos);
}