-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.cpp
144 lines (130 loc) · 3 KB
/
buffer.cpp
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include "myxml/buffer.hpp"
namespace myxml
{
void buffer::update_loc(char ch)
{
if (ch == '\n')
{
_column = 0;
_line++;
}
else
{
_column++;
}
}
void buffer::update_loc(std::string_view strv)
{
for (auto ch : strv)
{
this->update_loc(ch);
}
}
std::optional<char> buffer::peek() const
{
auto [ptr, len] = this->base();
if (_offset >= len)
{
return std::nullopt;
}
return ptr[_offset];
}
std::optional<std::string_view> buffer::peek_n(int n) const
{
if (n < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset + n >= len)
{
return std::nullopt;
}
return std::string_view(ptr + _offset, n);
}
std::optional<char> buffer::after_n(int n) const
{
if (n < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset + n > len)
{
return std::nullopt;
}
return ptr[_offset + n];
}
std::optional<std::string_view> buffer::after_n_m(int n, int m) const
{
if (n < 0 || m < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset + n + m > len)
{
return std::nullopt;
}
return std::string_view(ptr + _offset + n, m);
}
std::optional<char> buffer::take()
{
auto [ptr, len] = this->base();
if (_offset >= len)
{
return std::nullopt;
}
auto ch = ptr[_offset++];
this->update_loc(ch);
return ch;
}
std::optional<std::string_view> buffer::take_n(int n)
{
if (n < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset + n > len)
{
return std::nullopt;
}
std::string_view strv(ptr + _offset, n);
this->update_loc(strv);
_offset += n;
return strv;
}
std::tuple<std::size_t, std::size_t> buffer::cur_loc()
{
return {_line, _column};
}
string_buffer::string_buffer(std::string_view inner)
: _inner(inner)
{
}
string_buffer::string_buffer(std::string &&inner)
: _inner(inner)
{
}
string_buffer::string_buffer(const char *ptr)
: string_buffer(std::string_view(ptr))
{
}
std::tuple<const char *, std::size_t> string_buffer::base() const
{
auto view = this->view();
return {view.data(), view.length()};
}
std::string_view string_buffer::view() const
{
if (std::holds_alternative<std::string>(_inner))
{
return std::string_view(std::get<std::string>(_inner));
}
else
{
return std::get<std::string_view>(_inner);
}
}
}