-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_config.h
More file actions
88 lines (77 loc) · 2.88 KB
/
Copy pathserver_config.h
File metadata and controls
88 lines (77 loc) · 2.88 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
/*
// server_config.h - ServerConfig struct and command-line parsing for the Kayles server.
// Covers:
// - ServerConfig struct for holding parsed command-line parameters
// - parse_args() function to parse command-line arguments into ServerConfig
*/
#ifndef SERVER_CONFIG_H
#define SERVER_CONFIG_H
#include "helpers.h"
#include <cstdio>
#include <cstdlib>
#include <string>
struct ServerConfig {
std::string pawn_row_str;
std::string address;
uint16_t port {0};
int server_timeout {0};
};
static ServerConfig parse_args(int argc, char *argv[]) {
ServerConfig cfg;
bool got_r = false, got_a = false, got_p = false, got_t = false;
for (int i = 1; i < argc; ++i) {
const std::string flag = argv[i];
auto require_next = [&](const char *name) -> const char * {
if (i + 1 >= argc)
kaylescommon::die("missing argument for %s", name);
return argv[++i];
};
if (flag == "-r") {
if (got_r) {
std::fprintf(stderr,
"warning: -r given more than once; using last value\n");
}
cfg.pawn_row_str = require_next("-r");
got_r = true;
} else if (flag == "-a") {
if (got_a) {
std::fprintf(stderr,
"warning: -a given more than once; using last value\n");
}
cfg.address = require_next("-a");
got_a = true;
} else if (flag == "-p") {
if (got_p) {
std::fprintf(stderr,
"warning: -p given more than once; using last value\n");
}
const char *val = require_next("-p");
char *end = nullptr;
const long v = std::strtol(val, &end, 10);
if (*end != '\0' || v < 0 || v > 65535)
kaylescommon::die("invalid port: %s", val);
cfg.port = static_cast<uint16_t>(v);
got_p = true;
} else if (flag == "-t") {
if (got_t) {
std::fprintf(stderr,
"warning: -t given more than once; using last value\n");
}
const char *val = require_next("-t");
char *end = nullptr;
const long v = std::strtol(val, &end, 10);
if (*end != '\0' || v < 1 || v > 99)
kaylescommon::die("invalid timeout: %s", val);
cfg.server_timeout = static_cast<int>(v);
got_t = true;
} else {
kaylescommon::die("unknown argument: %s", argv[i]);
}
}
if (!got_r) kaylescommon::die("missing required parameter -r");
if (!got_a) kaylescommon::die("missing required parameter -a");
if (!got_p) kaylescommon::die("missing required parameter -p");
if (!got_t) kaylescommon::die("missing required parameter -t");
return cfg;
}
#endif // SERVER_CONFIG_H