-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWriter.cpp
More file actions
91 lines (80 loc) · 1.58 KB
/
Writer.cpp
File metadata and controls
91 lines (80 loc) · 1.58 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
#include "Writer.hpp"
#include "MyServer.hpp"
#include "Logger.hpp"
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cerrno>
#include <fcntl.h>
Writer::Writer(int fd, bool blocking)
{
this->fd = fd;
this->pos = 0;
if (!blocking)
{
int flags = fcntl(fd, F_GETFL);
if (flags == -1)
throw Exception("can't get flags for file descriptor\n");
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
throw Exception("can't set flags for file descriptor\n");
}
}
Writer::~Writer() {}
void Writer::flush()
{
if (empty())
return;
struct timeval tv;
fd_set wfds;
FD_ZERO(&wfds);
tv.tv_sec = 0;
tv.tv_usec = 1;
FD_SET(fd, &wfds);
if (!select(fd + 1, 0, &wfds, 0, &tv))
{
return;
}
int t = write(fd, buff.data() + pos, buff.size() - pos);
if (t == -1)
{
logger.log(LogType::ERROR, string("writer error ") + strerror(errno));
throw Writer::Exception(strerror(errno));
}
pos += t;
if (empty())
{
pos = 0;
buff.resize(0);
return;
}
}
void Writer::totalFlush()
{
while (!empty())
{
flush();
}
}
bool Writer::empty() const
{
return pos == buff.size();
}
void Writer::writeString(const std::string &str)
{
flush();
if (empty())
buff = str;
else
buff += str;
flush();
if (empty())
buff = "";
}
void Writer::writeLine(const std::string &str)
{
writeString(str);
writeString("\r\n");
}