Line data Source code
1 : #include "Getline.hpp"
2 :
3 : namespace Soldank
4 : {
5 : // Implementation copied from https://gist.github.com/josephwb/df09e3a71679461fc104
6 0 : std::istream& GetlineSafe(std::istream& is, std::string& t)
7 : {
8 0 : t.clear();
9 :
10 : // The characters in the stream are read one-by-one using a std::streambuf.
11 : // That is faster than reading them one-by-one using the std::istream.
12 : // Code that uses streambuf this way must be guarded by a sentry object.
13 : // The sentry object performs various tasks,
14 : // such as thread synchronization and updating the stream state.
15 :
16 0 : std::istream::sentry se(is, true);
17 0 : std::streambuf* sb = is.rdbuf();
18 :
19 : for (;;) {
20 0 : int c = sb->sbumpc();
21 0 : switch (c) {
22 0 : case '\n':
23 0 : return is;
24 0 : case '\r':
25 0 : if (sb->sgetc() == '\n') {
26 0 : sb->sbumpc();
27 : }
28 0 : return is;
29 0 : case EOF:
30 : // Also handle the case when the last line has no line ending
31 0 : if (t.empty()) {
32 0 : is.setstate(std::ios::eofbit);
33 : }
34 0 : return is;
35 0 : default:
36 0 : t += (char)c;
37 : }
38 0 : }
39 : }
40 : } // namespace Soldank
|