Debian Codegraph @

inst/include/sourcetools/cursor/TextCursor.h

raw
1 #ifndef SOURCETOOLS_CURSOR_TEXT_CURSOR_H
2 #define SOURCETOOLS_CURSOR_TEXT_CURSOR_H
3
4 #include <string>
5
6 #include <sourcetools/core/macros.h>
7 #include <sourcetools/collection/Position.h>
8
9 namespace sourcetools {
10 namespace cursors {
11
12 class TextCursor
13 {
14 public:
15
16 TextCursor(const char* text, std::size_t n)
17 : text_(text),
18 n_(n),
19 offset_(0),
20 position_(0, 0)
21 {
22 }
23
24 char peek(std::size_t offset = 0)
25 {
26 std::size_t index = offset_ + offset;
27 if (UNLIKELY(index >= n_))
28 return '\0';
29 return text_[index];
30 }
31
32 void advance(std::size_t times = 1)
33 {
34 for (std::size_t i = 0; i < times; ++i) {
35 if (peek() == '\n') {
36 ++position_.row;
37 position_.column = 0;
38 } else {
39 ++position_.column;
40 }
41 ++offset_;
42 }
43 }
44
45 operator const char*() const { return text_ + offset_; }
46
47 std::size_t offset() const { return offset_; }
48
49 const collections::Position& position() const { return position_; }
50 std::size_t row() const { return position_.row; }
51 std::size_t column() const { return position_.column; }
52
53 const char* begin() const { return text_; }
54 const char* end() const { return text_ + n_; }
55
56 private:
57 const char* text_;
58 std::size_t n_;
59 std::size_t offset_;
60 collections::Position position_;
61 };
62
63 } // namespace cursors
64 } // namespace sourcetools
65
66 #endif /* SOURCETOOLS_CURSOR_TEXT_CURSOR_H */