-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.cc
70 lines (60 loc) · 1.34 KB
/
protocol.cc
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
#include <cstdlib>
#include <cstring>
#include <string_view>
#include "protocol.hh"
static CmdType getCmdType(std::string_view cmd_name);
/************************/
/*** PUBLIC FUNCTIONS ***/
/************************/
std::unique_ptr<Cmd> parse_cmd(const char *buf) {
auto cmd{std::make_unique<Cmd>()};
if (*buf != '*') {
cmd->type = CmdTypeInvalid;
return cmd;
}
int arglen = 0;
buf++;
while (*buf != '\r') {
arglen = (arglen * 10) + (*buf - '0');
buf++;
}
cmd->argc = arglen;
for (int i = 0; i < arglen; i++) {
int tokenlen = 0;
buf += 3;
while (*buf != '\r') {
tokenlen = (tokenlen * 10) + (*buf - '0');
buf++;
}
buf += 2;
std::string arg(buf, tokenlen);
cmd->argv.push_back(arg);
buf += tokenlen;
}
if ((cmd->type = getCmdType(cmd->argv[0])) == CmdTypeInvalid) {
cmd->type = CmdTypeInvalid;
return cmd;
}
return cmd;
}
/*************************/
/*** PRIVATE FUNCTIONS ***/
/*************************/
static CmdType getCmdType(std::string_view cmd_name) {
if (cmd_name == "PING") {
return CmdTypePing;
}
if (cmd_name == "COMMAND") {
return CmdTypeCommand;
}
if (cmd_name == "GET") {
return CmdTypeGet;
}
if (cmd_name == "SET") {
return CmdTypeSet;
}
if (cmd_name == "DEL") {
return CmdTypeDel;
}
return CmdTypeInvalid;
}