-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.h
78 lines (70 loc) · 2.39 KB
/
parse.h
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
#ifndef SIK_UDP_PARSE_H
#define SIK_UDP_PARSE_H
#include <exception>
#include <string>
#include <boost/lexical_cast.hpp>
#include "error.h"
#include "protocol.h"
namespace sik {
/**
* Exception thrown when parsing error occurs.
*/
class ParseException : public Exception {
public:
explicit ParseException(const std::string &message) : Exception(
message) {}
explicit ParseException(std::string &&message) : Exception(
std::move(message)) {}
};
/**
* Converts string to port number.
* @param input string to convert.
* @return port number.
* @throws ArgumentException if input is not a valid port number.
*/
uint16_t parse_port(const std::string &input) {
try {
uint16_t port = boost::lexical_cast<uint16_t>(input);
if (boost::lexical_cast<std::string>(port) != input || port == 0) {
throw ParseException(
"Port must be an integer between 1 and 65,535");
}
return port;
} catch (const boost::bad_lexical_cast &) {
throw ParseException(
"Port must be an integer between 1 and 65,535");
}
}
/**
* Converts string to a single character.
* @param input string to convert.
* @return single character.
* @throws ArgumentException if input is not a single character.
*/
char parse_character(const std::string &input) {
if (input.length() != 1) {
throw ParseException("Character must be a single character");
}
return input[0];
}
/**
* Converts string to timestamp.
* @param input string to convert.
* @return timestamp.
* @throws ArgumentException if input is not a valid timestamp.
*/
timestamp_t parse_timestamp(const std::string &input) {
try {
timestamp_t timestamp = boost::lexical_cast<timestamp_t>(input);
if (boost::lexical_cast<std::string>(timestamp) != input
|| !is_proper_timestamp(timestamp)) {
throw ParseException(
"Timestamp must be a 64-bit unsigned number");
}
return timestamp;
} catch (const boost::bad_lexical_cast &) {
throw ParseException("Timestamp must be a 64-bit unsigned number");
}
}
}
#endif //SIK_UDP_PARSE_H