Turi Create  4.0
string_stream_internals.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef TURI_STRING_STREAM_INTERNALS_H_
7 #define TURI_STRING_STREAM_INTERNALS_H_
8 
9 #include <iostream>
10 
11 ////////////////////////////////////////////////////////////////////////////////
12 
13 namespace turi { namespace gl_string_internals {
14 
15 template<class _Traits>
16 std::basic_istream<char, _Traits>& stream_in(std::basic_istream<char, _Traits>& is, gl_string& str) {
17 
18  using namespace std;
19 
20  try {
21  typename basic_istream<char, _Traits>::sentry sen(is);
22 
23  if (sen) {
24  str.clear();
25  streamsize n = is.width();
26  if (n <= 0)
27  n = str.max_size();
28  if (n <= 0)
29  n = numeric_limits<streamsize>::max();
30  streamsize c = 0;
31  const ctype<char>& ct = use_facet<ctype<char> >(is.getloc());
32  ios_base::iostate err = ios_base::goodbit;
33  while (c < n)
34  {
35  typename _Traits::int_type i = is.rdbuf()->sgetc();
36  if (_Traits::eq_int_type(i, _Traits::eof()))
37  {
38  err |= ios_base::eofbit;
39  break;
40  }
41  char ch = _Traits::to_char_type(i);
42  if (ct.is(ct.space, ch))
43  break;
44  str.push_back(ch);
45  ++c;
46  is.rdbuf()->sbumpc();
47  }
48  is.width(0);
49  if (c == 0)
50  err |= ios_base::failbit;
51  is.setstate(err);
52  }
53  else
54  is.setstate(ios_base::failbit);
55  }
56  catch (...)
57  {
58  is.setstate(ios_base::badbit);
59  }
60  return is;
61 }
62 
63 template <class _Traits>
64 std::basic_istream<char, _Traits>&
65 getline(std::basic_istream<char, _Traits>& is, gl_string& str, char dlm) {
66 
67  using namespace std;
68  try {
69  typename basic_istream<char, _Traits>::sentry sen(is, true);
70  if (sen) {
71  str.clear();
72  ios_base::iostate err = ios_base::goodbit;
73  streamsize extr = 0;
74  while (true) {
75  typename _Traits::int_type i = is.rdbuf()->sbumpc();
76  if (_Traits::eq_int_type(i, _Traits::eof())) {
77  err |= ios_base::eofbit;
78  break;
79  }
80  ++extr;
81  char ch = _Traits::to_char_type(i);
82  if (_Traits::eq(ch, dlm))
83  break;
84  str.push_back(ch);
85  if (str.size() == str.max_size()) {
86  err |= ios_base::failbit;
87  break;
88  }
89  }
90  if (extr == 0)
91  err |= ios_base::failbit;
92  is.setstate(err);
93  }
94  } catch (...) {
95  is.setstate(ios_base::badbit);
96  }
97  return is;
98 }
99 
100 }}
101 
102 #endif /* _STRING_STREAM_INTERNALS_H_ */
STL namespace.