-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathstream_iterator.hpp
119 lines (89 loc) · 2.8 KB
/
stream_iterator.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
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
109
110
111
112
113
114
115
116
117
118
119
#ifndef STREAM_ITERATOR_HPP
#define STREAM_ITERATOR_HPP
#include "parser_combinators.hpp"
using namespace std;
#ifdef USE_MMAP
#include "File-Vector/file_vector.hpp"
class stream_range {
file_vector<char> file;
public:
using iterator = file_vector<char>::const_iterator;
iterator const last;
iterator const first;
stream_range(stream_range const&) = delete;
stream_range(char const* name) : file(name), first(file.cbegin()), last(file.cend()) {}
stream_range(string const& name) : stream_range(name.c_str()) {}
};
#else // USE_MMAP
#include <streambuf>
#include <fstream>
class stream_range {
fstream file;
streambuf *rd;
streamoff pos;
public:
class iterator {
friend class stream_range;
iterator(stream_range *r, streamoff pos) : r(r), pos(pos), sym(r->rd->sgetc()) {
r->pos = pos;
}
stream_range *r;
streamoff pos;
int sym;
public:
int operator* () const {
return sym;
}
bool operator== (iterator const& i) const {
return (r == i.r) && (sym == i.sym) && (pos == i.pos);
}
bool operator!= (iterator const& i) const {
return (r != i.r) || (sym != i.sym) || (pos != i.pos);
}
streamoff operator- (iterator const& i) const {
return pos - i.pos;
}
iterator& operator++ () {
if (r->pos != pos) {
r->pos = r->rd->pubseekoff(++pos, ios_base::beg);
sym = r->rd->sgetc();
} else {
r->pos = ++pos;
sym = r->rd->snextc();
}
return *this;
}
iterator& operator-- () {
--pos;
if (r->pos != pos) {
r->pos = r->rd->pubseekoff(pos, ios_base::beg);
}
sym = r->rd->sgetc();
return *this;
}
iterator& operator= (iterator const& i) {
r = i.r;
pos = i.pos;
sym = i.sym;
return *this;
}
};
friend class stream_range::iterator;
iterator const last;
iterator const first;
stream_range(stream_range const&) = delete;
stream_range(char const* name) : file(name, ios_base::in),
rd(file.rdbuf()), pos(0),
last(this, rd->pubseekoff(0, ios_base::end)),
first(this, rd->pubseekoff(0, ios_base::beg)
) {
if (!file.is_open()) {
throw runtime_error("unable to open file");
}
}
stream_range(string const& name) : stream_range(name.c_str()) {}
};
#endif // USE_MMAP
template <typename Synthesize = void, typename Inherit = default_inherited>
using pstream_handle = parser_handle<stream_range::iterator, stream_range, Synthesize, Inherit>;
#endif // STREAM_ITERATOR_HPP