-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReader.cpp
More file actions
137 lines (120 loc) · 2.6 KB
/
Reader.cpp
File metadata and controls
137 lines (120 loc) · 2.6 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
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
#include "Reader.hpp"
#include "StringBuffer.hpp"
#include "Utils.hpp"
#include "Logger.hpp"
#include <unistd.h>
#include <cstring>
#include <cerrno>
#include <fcntl.h>
#include <sys/select.h>
Reader::Reader(int fd, size_t len)
{
this->fd = fd;
this->buffLen = len;
this->pos = 0;
buffUpdate();
}
Reader::~Reader()
{
}
bool Reader::empty() const
{
return eof() && pos == buff.size();
}
bool Reader::eof() const
{
return endOfFile;
}
size_t Reader::buffUpdate()
{
if (endOfFile)
return 0;
if (pos == buff.size())
{
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
tv.tv_sec = 0;
tv.tv_usec = 1;
FD_SET(fd, &rfds);
if (!select(fd + 1, &rfds, 0, 0, &tv))
{
return 0;
}
char *tmp = new char[buffLen];
int nRead;
if ((nRead = read(fd, tmp, buffLen)) == -1)
{
logger.log(LogType::FATAL, string("can't read ") + strerror(errno));
throw Exception(string("can't read ") + strerror(errno));
}
if (nRead == 0)
{
endOfFile = true;
}
buff = string(tmp, nRead);
pos = 0;
delete[] tmp;
}
return buff.size() - pos;
}
std::string Reader::getLine()
{
StringBuffer sb;
while (!endOfFile)
{
buffUpdate();
size_t e = buff.find_first_of("\n", pos);
if (e == string::npos)
{
sb.add(buff.substr(pos, buff.size() - pos));
pos = buff.size();
continue;
}
sb.add(buff.substr(pos, e - pos));
pos = e + 1;
break;
}
string tmp = sb.toStr();
if(tmp[tmp.size() - 1] == '\r')
return tmp.substr(0, tmp.size() - 1);
return tmp;
}
std::string Reader::getNBytes(size_t n)
{
std::string res;
res.reserve(n);
while (!eof() && res.size() < n)
{
buffUpdate();
size_t needToRead = n - res.size();
size_t availInBuff = buff.size() - pos;
size_t toRead = (needToRead < availInBuff) ? needToRead : availInBuff;
res += buff.substr(pos, toRead);
pos += toRead;
}
return res;
}
std::string Reader::getToEnd()
{
StringBuffer sb;
while (!eof())
{
size_t nBytes = buffUpdate();
sb.add(getNBytes(nBytes));
}
return sb.toStr();
}
std::string Reader::getAvail()
{
StringBuffer sb;
while (!eof())
{
size_t nBytes = buffUpdate();
if(nBytes == 0)
break;
sb.add(buff.substr(pos, buff.size() - pos));
pos = buff.size();
}
return sb.toStr();
}