-
Notifications
You must be signed in to change notification settings - Fork 0
/
FlagParser.hpp
64 lines (56 loc) · 1.98 KB
/
FlagParser.hpp
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
/*
* BSD 3-Clause License, see file labled 'LICENSE' for the full License.
* Copyright (c) 2024, Peter Ferranti
* All rights reserved.
*/
#include <string>
#include <vector>
#include <algorithm>
namespace FlagParser {
typedef struct Token {
std::string flag;
std::vector<std::string> params;
Token(std::string flag) :
flag(flag) {}
} Token;
class Parser {
public:
inline static const Token EmptyToken{""};
Parser(int& argc, char** argv) {
if(!argc) return;
m_tokens.emplace_back(argv[0]);
for(int i{1}; i < argc; i++) {
std::string str{argv[i]};
std::for_each(str.begin(), str.end(), [](char& c){ c = tolower(c); });
if(str.substr(0, 2) == "--") {
m_tokens.emplace_back(str.substr(2, str.length()));
}
else if(m_tokens.size() > 1) {
m_tokens.back().params.emplace_back(str);
}
}
}
const bool hasFlag(const std::string flag) const {
for(auto itt{m_tokens.begin()}; itt != m_tokens.end(); itt++)
if((*itt).flag == flag) return true;
return false;
}
const std::vector<std::string>& getFlagParams(const std::string flag) const {
for(auto itt{m_tokens.begin()}; itt != m_tokens.end(); itt++)
if((*itt).flag == flag) return (*itt).params;
return EmptyToken.params;
}
const std::string getFirstFlag() const {
if(m_tokens.size() > 0)
return m_tokens[0].flag;
return EmptyToken.flag;
}
const Token& operator[](const size_t idx) const {
if(m_tokens.size() > 0 && m_tokens.size() > idx)
return m_tokens[idx];
return EmptyToken;
}
private:
std::vector<Token> m_tokens;
};
}