-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstr_impl.h
99 lines (77 loc) · 2.52 KB
/
str_impl.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#ifndef STR_IMPL_H
#define STR_IMPL_H
#include "str.h"
namespace {
template<typename T>
typename std::enable_if<false == std::is_convertible<T, std::string>::value, std::string>::type
to_string(const T &value) {
return std::to_string(value);
}
template<typename T>
typename std::enable_if<false == std::is_convertible<T, std::vector<std::string>>::value, std::string> ::type
to_string(const std::vector<T> &values) {
std::string result;
for (auto value : values) {
result.append(value);
}
return result;
}
template<typename T>
bool contains(const std::vector<T> &values, const T value) {
return std::find(values.begin(), values.end(), value) != values.end();
}
template<typename... T>
std::string join(const std::string &separator, const std::vector<T> &... values) {
std::vector<std::string> args;
std::string result;
using unused = int[];
(void) unused{0, (args.push_back(to_string(values)), 0)...};
for (const auto &s: args) {
result.append(s);
result.append(separator);
}
return result;
}
template<typename... T>
std::string format(const std::string &s, const T &... values) {
std::vector<std::string> args;
std::string result = s;
using unused = int[];
(void) unused{0, (args.push_back(to_string(values)), 0)...};
char open = '{';
char close = '}';
bool is_open = false;
uint index = 0;
uint index_length = 0;
uint start = 0;
for (uint i = 0; i < result.length(); ++i) {
char c = result.at(i);
if (c == '\\') {
i += 1;
} else if (c == open) {
is_open = true;
start = i;
} else if (c == close) {
uint one = result.length();
result.erase(start, i + 1 - start);
if (index_length > 0) {
result.insert(start, args.at(index));
}
uint two = result.length();
i -= one - two;
is_open = false;
index = 0;
index_length = 0;
} else if (is_open) {
int n = c - '0';
if (n < 0 || n > 9) {
continue;
}
index = (index * 10) + n;
++index_length;
}
}
return result;
}
}
#endif