forked from ifsmirnov/jngen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
range_option.h
108 lines (90 loc) · 2.39 KB
/
range_option.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
100
101
102
103
104
105
106
107
108
#pragma once
#include "common.h"
#include <iterator>
#include <sstream>
#include <string>
namespace jngen {
namespace options {
struct Range {
int first;
int last;
int step;
Range(int first, int last, int step = 1) :
first(first),
last(last),
step(step)
{
ensure(first <= last);
ensure(step > 0);
}
class iterator {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = int;
using reference = const int&;
using pointer = const int*;
using difference_type = int;
iterator(int value, int step, int last) :
value_(value),
step_(step),
last_(last)
{ }
iterator& operator++() {
ensure(value_ <= last_, "Cannot increment past-the-end iterator");
value_ += step_;
return *this;
}
iterator operator++(int) {
iterator copy = *this;
++*this;
return copy;
}
int operator*() const {
ensure(value_ <= last_, "Cannot dereference past-the-end iterator");
return value_;
}
bool operator==(const iterator& other) const {
if (value_ <= last_) {
return value_ == other.value_;
}
return other.value_ > last_;
}
bool operator!=(const iterator& other) const {
return !(*this == other);
}
private:
int value_;
int step_;
int last_;
};
iterator begin() const {
return { first, step, last };
}
iterator end() const {
return { last + 1, step, last };
}
static Range fromString(std::string s) {
for (char& c: s) {
ensure(c != ' ', "No spaces allowed in range description");
if (c == ':') {
c = ' ';
}
}
std::istringstream ss(s);
int first = 1;
int last = std::numeric_limits<int>::max() - 1;
int step = 1;
if (!(ss >> first)) {
ensure(false, "Failed to parse range");
}
if (!(ss >> last)) {
return Range(first, last, step);
}
if (!(ss >> step)) {
return Range(first, last, step);
}
return Range(first, last, step);
}
};
} // namespace options
} // namespace jngen