William A. Kennington III | b594fc3 | 2022-08-18 01:47:48 -0700 | [diff] [blame] | 1 | #include <cstring> |
William A. Kennington III | 9a512c9 | 2022-08-12 15:15:55 -0700 | [diff] [blame] | 2 | #include <stdplus/exception.hpp> |
| 3 | #include <stdplus/fd/line.hpp> |
| 4 | #include <stdplus/fd/ops.hpp> |
| 5 | |
| 6 | namespace stdplus |
| 7 | { |
| 8 | namespace fd |
| 9 | { |
| 10 | |
| 11 | LineReader::LineReader(Fd& fd) : fd(fd) |
| 12 | { |
| 13 | } |
| 14 | |
| 15 | const 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 III | b594fc3 | 2022-08-18 01:47:48 -0700 | [diff] [blame] | 48 | auto oldsize = line.size(); |
| 49 | line.resize(oldsize + i); |
| 50 | std::memcpy(line.data() + oldsize, buf_data.data(), i); |
William A. Kennington III | 9a512c9 | 2022-08-12 15:15:55 -0700 | [diff] [blame] | 51 | buf_data = buf_data.subspan(i + 1); |
| 52 | line_complete = true; |
| 53 | return &line; |
| 54 | } |
| 55 | } |
William A. Kennington III | b594fc3 | 2022-08-18 01:47:48 -0700 | [diff] [blame] | 56 | 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 III | 9a512c9 | 2022-08-12 15:15:55 -0700 | [diff] [blame] | 59 | buf_data = {}; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | } // namespace fd |
| 64 | } // namespace stdplus |