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