-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice.hpp
110 lines (89 loc) · 2.32 KB
/
slice.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
#ifndef __SLICE_HPP
#define __SLICE_HPP
#include <cstddef>
#include <cstring>
#include <string>
class BadSlice {};
class BadIndex {};
class SliceIterator;
class Slice {
public:
Slice(std::string s) {
auto l = s.length();
_begin = new char [l + 1];
strcpy(_begin, s.c_str());
_allocated = true;
_end = _begin + l;
}
~Slice() {
if (_allocated) delete[] _begin;
_allocated = false;
}
Slice operator() (int start, int stop) const {
if (stop < 0) {
stop += len();
}
if (start < 0) {
start += len();
}
if (stop < 0 || start < 0 || stop < start || (unsigned)stop > len()) {
throw BadSlice {};
}
return Slice{_begin + start, _begin + stop};
}
std::size_t len() const {
return _end - _begin;
}
char& operator[] (int i) {
if (i < 0 || (unsigned)i >= len()) {
throw BadIndex {};
}
return _begin[i];
}
SliceIterator begin();
SliceIterator end();
operator std::string() {
return std::string(_begin, len());
}
private:
char *_begin;
char *_end;
bool _allocated;
Slice(char *begin, char *end) {
if (_end < _begin) {
throw BadSlice {};
}
_begin = begin;
_end = end;
_allocated = false;
}
};
class SliceIterator {
public:
bool operator!=(const SliceIterator& other) const {
return _index != other._index && _index <= _max;
}
char operator* () const {
return _buf[_index];
}
const SliceIterator& operator++ () {
++_index;
return *this;
}
SliceIterator(const Slice& s, char *p) {
_max = s.len();
_index = 0;
_buf = p;
}
private:
size_t _index;
char* _buf;
size_t _max;
};
SliceIterator Slice::begin() {
return SliceIterator(*this, _begin);
}
SliceIterator Slice::end() {
return SliceIterator(*this, _end);
}
#endif