-
Notifications
You must be signed in to change notification settings - Fork 5
/
connection.cpp
82 lines (69 loc) · 1.88 KB
/
connection.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
// Copyright (c) 2017 Suneido Software Corp. All rights reserved
// Licensed under GPLv2
#include "connection.h"
#include "sockets.h"
#include <algorithm>
#include "except.h"
#include "fatal.h"
#include "exceptimp.h"
using std::min;
using std::max;
// NOTE: passes SocketConnect wrbuf to Serializer to access directly
Connection::Connection(SocketConnect* sc_)
: Serializer(rdbuf, sc_->wrbuf), sc(*sc_) {
}
/// @post At least n bytes are available in rdbuf
void Connection::need(int n) {
const int READSIZE = 1024;
// NOTE: this is our rdbuf, not sc.rdbuf
int toRead = n - rdbuf.remaining();
if (toRead <= 0)
return;
int maxRead = max(toRead, READSIZE);
char* buf = rdbuf.ensure(maxRead);
int nr = sc.read(buf, toRead, maxRead);
except_if(nr == 0, "lost connection");
rdbuf.added(nr);
}
void Connection::read(char* dst, int n) {
if (rdbuf.remaining()) {
int take = min(n, rdbuf.remaining());
memcpy(dst, rdbuf.getBuf(take), take);
if (take == n)
return; // got it all from rdbuf
n -= take;
dst += take;
}
int nr = sc.read(dst, n);
except_if(nr == 0, "lost connection");
}
/// Write buffered data
void Connection::write() {
write("", 0);
}
/// Write buffered data plus buf
void Connection::write(const char* buf, int n) {
LIMIT(n);
sc.write(buf, n);
rdbuf.clear();
// can't clear sc.wrbuf if using async because it doesn't block
}
void Connection::close() {
sc.close();
}
//--------------------------------------------------------------------------------
#define DO(fn) \
try { \
fn; \
} catch (const Except& e) { \
fatal("lost connection:", e.str()); \
}
void ClientConnection::need(int n) {
DO(Connection::need(n));
}
void ClientConnection::write(const char* buf, int n) {
DO(Connection::write(buf, n));
}
void ClientConnection::read(char* dst, int n) {
DO(Connection::read(dst, n));
}