-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuffer.cpp
137 lines (127 loc) · 2.94 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//#define _GNU_SOURCE
#include "Buffer.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <string.h>
#include <unistd.h>
#include <strings.h>
#include <sys/socket.h>
Buffer::Buffer(int size):m_capacity(size)
{
m_data = (char*)malloc(size);
bzero(m_data, size);
}
Buffer::~Buffer()
{
if (m_data != nullptr)
{
free(m_data);
}
}
void Buffer::extendRoom(int size)
{
// 1. 内存够用 - 不需要扩容
if (writeableSize() >= size)
{
return;
}
// 2. 内存需要合并才够用 - 不需要扩容
// 剩余的可写的内存 + 已读的内存 > size
else if (m_readPos + writeableSize() >= size)
{
// 得到未读的内存大小
int readable = readableSize();
// 移动内存
memcpy(m_data, m_data + m_readPos, readable);
// 更新位置
m_readPos = 0;
m_writePos = readable;
}
// 3. 内存不够用 - 扩容
else
{
void* temp = realloc(m_data, m_capacity + size);
if (temp == NULL)
{
return; // 失败了
}
memset((char*)temp + m_capacity, 0, size);
// 更新数据
m_data = static_cast<char*>(temp);
m_capacity += size;
}
}
int Buffer::appendString(const char* data, int size)
{
if (data == nullptr || size <= 0)
{
return -1;
}
// 扩容
extendRoom(size);
// 数据拷贝
memcpy(m_data + m_writePos, data, size);
m_writePos += size;
return 0;
}
int Buffer::appendString(const char* data)
{
int size = strlen(data);
int ret = appendString(data, size);
return ret;
}
int Buffer::appendString(const string data)
{
int ret = appendString(data.data());
return ret;
}
int Buffer::socketRead(int fd)
{
// read/recv/readv
struct iovec vec[2];
// 初始化数组元素
int writeable = writeableSize();
vec[0].iov_base = m_data + m_writePos;
vec[0].iov_len = writeable;
char* tmpbuf = (char*)malloc(40960);
vec[1].iov_base = tmpbuf;
vec[1].iov_len = 40960;
int result = readv(fd, vec, 2);
if (result == -1)
{
return -1;
}
else if (result <= writeable)
{
m_writePos += result;
}
else
{
m_writePos = m_capacity;
appendString(tmpbuf, result - writeable);
}
free(tmpbuf);
return result;
}
char* Buffer::findCRLF()
{
char* ptr = (char*)memmem(m_data + m_readPos, readableSize(), "\r\n", 2);
return ptr;
}
int Buffer::sendData(int socket)
{
// 判断有无数据
int readable = readableSize();
if (readable > 0)
{
int count = send(socket, m_data + m_readPos, readable, MSG_NOSIGNAL);
if (count > 0)
{
m_readPos += count;
usleep(1);
}
return count;
}
return 0;
}