Thrill  0.1
appendline.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/string/appendline.cpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2019 Timo Bingmann <[email protected]>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
12 
13 #include <algorithm>
14 
15 namespace tlx {
16 
17 std::istream& appendline(std::istream& is, std::string& str, char delim) {
18  size_t size = str.size();
19  size_t capacity = str.capacity();
20  std::streamsize rest = capacity - size;
21 
22  if (rest == 0) {
23  // if rest is zero, already expand string
24  capacity = std::max(static_cast<size_t>(8), capacity * 2);
25  rest = capacity - size;
26  }
27 
28  // give getline access to all of capacity
29  str.resize(capacity);
30 
31  // get until delim or rest is filled
32  is.getline(const_cast<char*>(str.data()) + size, rest, delim);
33 
34  // gcount includes the delimiter
35  size_t new_size = size + is.gcount();
36 
37  // is failbit set?
38  if (!is) {
39  // if string ran out of space, expand, and retry
40  if (is.gcount() + 1 == rest) {
41  is.clear();
42  str.resize(new_size);
43  str.reserve(capacity * 2);
44  return appendline(is, str, delim);
45  }
46  // else fall through and deliver error
47  }
48  else if (!is.eof()) {
49  // subtract delimiter
50  --new_size;
51  }
52 
53  // resize string to fit its contents
54  str.resize(new_size);
55  return is;
56 }
57 
58 } // namespace tlx
59 
60 /******************************************************************************/
static uint_pair max()
return an uint_pair instance containing the largest value possible
Definition: uint_types.hpp:226
std::basic_string< char, std::char_traits< char >, Allocator< char > > string
string with Manager tracking
Definition: allocator.hpp:220
std::istream & appendline(std::istream &is, std::string &str, char delim)
Definition: appendline.cpp:17