blob: db1204168e613eba60f2dfc53a4ef557b965f83b [file] [log] [blame]
William A. Kennington IIIb594fc32022-08-18 01:47:48 -07001#include <cstring>
William A. Kennington III9a512c92022-08-12 15:15:55 -07002#include <stdplus/exception.hpp>
3#include <stdplus/fd/line.hpp>
4#include <stdplus/fd/ops.hpp>
5
6namespace stdplus
7{
8namespace fd
9{
10
11LineReader::LineReader(Fd& fd) : fd(fd)
12{
13}
14
15const std::string* LineReader::readLine()
16{
17 if (hit_eof)
18 {
19 throw exception::Eof("readLine");
20 }
21 if (line_complete)
22 {
23 line.clear();
24 }
25 while (true)
26 {
27 if (buf_data.empty())
28 {
29 try
30 {
31 buf_data = read(fd, buf);
32 if (buf_data.empty())
33 {
34 return nullptr;
35 }
36 }
37 catch (const exception::Eof&)
38 {
39 hit_eof = true;
40 return &line;
41 }
42 }
43 line_complete = false;
44 for (size_t i = 0; i < buf_data.size(); ++i)
45 {
46 if (buf_data[i] == '\n')
47 {
William A. Kennington IIIb594fc32022-08-18 01:47:48 -070048 auto oldsize = line.size();
49 line.resize(oldsize + i);
50 std::memcpy(line.data() + oldsize, buf_data.data(), i);
William A. Kennington III9a512c92022-08-12 15:15:55 -070051 buf_data = buf_data.subspan(i + 1);
52 line_complete = true;
53 return &line;
54 }
55 }
William A. Kennington IIIb594fc32022-08-18 01:47:48 -070056 auto oldsize = line.size();
57 line.resize(oldsize + buf_data.size());
58 std::memcpy(line.data() + oldsize, buf_data.data(), buf_data.size());
William A. Kennington III9a512c92022-08-12 15:15:55 -070059 buf_data = {};
60 }
61}
62
63} // namespace fd
64} // namespace stdplus