Skip to content

Commit 60a4492

Browse files
committedFeb 20, 2025
Refactored connection handling for better resource management
1 parent 8fc0f85 commit 60a4492

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
 

‎src/conn.h

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <cstdint>
2+
#include <stddef.h>
3+
#include <vector>
4+
#include "command.h"
5+
#include "utils.h"
6+
7+
#pragma once
8+
9+
enum ConnState {
10+
STATE_READ,
11+
STATE_WRITE,
12+
STATE_END
13+
};
14+
15+
/**
16+
* Conn struct: a structure that represents a connection
17+
*
18+
* This struct contains the following fields:
19+
* int fd; : the file descriptor of the connection
20+
* ConnState state{}; : state of the connection -> whether the server needs to read from the socket, or send a reply.
21+
* size_t rbuf_roffset{}; : read buffer's read offset (used when consuming data on buffer)
22+
* size_t rbuf_woffset{}; : read bufer's write offset (used when reading from network to read buffer)
23+
* size_t wbuf_offset{}; : write buffer's write offset (used when writing data to the network)
24+
* size_t pending_write_len{}; : amount of data still pending in the write buffer
25+
* char* rbuf; : pointer to the read buffer
26+
* char* wbuf; : pointer to the write buffer
27+
*
28+
*/
29+
struct Conn {
30+
Conn()
31+
: Conn(-1)
32+
{}
33+
34+
Conn(int fd)
35+
: fd{fd},
36+
state{STATE_READ},
37+
rbuf(Consts::SIZE_HEADER_LEN + Consts::MAX_MSG_LEN),
38+
wbuf(Consts::SIZE_HEADER_LEN + Consts::MAX_MSG_LEN)
39+
{}
40+
41+
// Conn(const Conn& other) = delete;
42+
// Conn& operator=(const Conn& other) = delete;
43+
44+
// Conn(Conn&& other) = default;
45+
// Conn& operator=(Conn&& other) = default;
46+
47+
void reset() {
48+
fd = -1;
49+
state = STATE_READ;
50+
rbuf_roffset = 0;
51+
rbuf_woffset = 0;
52+
wbuf_offset = 0;
53+
pending_write_len = 0;
54+
cmd.reset();
55+
}
56+
57+
void init(int fd) {
58+
reset();
59+
this->fd = fd;
60+
}
61+
62+
int fd;
63+
ConnState state{};
64+
size_t rbuf_roffset{};
65+
size_t rbuf_woffset{};
66+
size_t wbuf_offset{};
67+
size_t pending_write_len{};
68+
Command cmd{};
69+
std::vector<char> rbuf;
70+
std::vector<char> wbuf;
71+
};

0 commit comments

Comments
 (0)
Please sign in to comment.