]> git.localhorst.tv Git - gong.git/blob - src/io/LineBuffer.hpp
code, assets, and other stuff stolen from blank
[gong.git] / src / io / LineBuffer.hpp
1 #ifndef GONG_IO_LINEBUFFER_HPP_
2 #define GONG_IO_LINEBUFFER_HPP_
3
4 #include <algorithm>
5 #include <cassert>
6 #include <string>
7
8
9 namespace gong {
10 namespace io {
11
12 template<std::size_t size>
13 class LineBuffer {
14
15 public:
16         explicit LineBuffer(char term = '\n') noexcept
17         : buffer{0}
18         , term(term)
19         , head(buffer) { }
20
21         char *begin() noexcept {
22                 return buffer;
23         }
24         const char *begin() const noexcept {
25                 return buffer;
26         }
27         char *end() noexcept {
28                 return head;
29         }
30         const char *end() const noexcept {
31                 return head;
32         }
33
34         /// extract one line from the buffer, terminator not included
35         /// @return false if the buffer does not contain a complete line
36         bool Extract(std::string &line) {
37                 char *line_end = std::find(begin(), end(), term);
38                 if (line_end == end()) {
39                         return false;
40                 }
41                 line.assign(begin(), line_end);
42                 ++line_end;
43                 std::move(line_end, end(), begin());
44                 head -= std::distance(begin(), line_end);
45                 return true;
46         }
47
48         /// get a pointer to append data to the buffer
49         /// it is safe to write at most Remain() bytes
50         char *WriteHead() noexcept {
51                 return head;
52         }
53
54         // call when data has been written to WriteHead()
55         void Update(std::size_t written) {
56                 assert(written <= Remain());
57                 head += written;
58         }
59
60         std::size_t Remain() const noexcept {
61                 return std::distance(end(), buffer + size);
62         }
63
64 private:
65         char buffer[size];
66         char term;
67         char *head;
68
69 };
70
71 }
72 }
73
74 #endif