staticlib_io  1.2.11
 All Classes Namespaces Files Functions Variables
string_sink.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2015, alex at staticlibs.net
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /*
18  * File: string_sink.hpp
19  * Author: alex
20  *
21  * Created on November 6, 2015, 3:59 PM
22  */
23 
24 #ifndef STATICLIB_IO_STRING_SINK_HPP
25 #define STATICLIB_IO_STRING_SINK_HPP
26 
27 #include <cstdint>
28 #include <cstring>
29 #include <ios>
30 #include <string>
31 
32 #include "staticlib/config.hpp"
33 
35 #include "staticlib/io/span.hpp"
36 
37 namespace staticlib {
38 namespace io {
39 
43 class string_sink {
47  std::string str;
48 
49 public:
54 
60  explicit string_sink(std::string&& str) :
61  str(std::move(str)) { }
62 
68  string_sink(const string_sink&) = delete;
69 
76  string_sink& operator=(const string_sink&) = delete;
77 
83  string_sink(string_sink&& other) STATICLIB_NOEXCEPT :
84  str(std::move(other.str)) { }
85 
92  string_sink& operator=(string_sink&& other) STATICLIB_NOEXCEPT {
93  str = std::move(other.str);
94  return *this;
95  }
96 
103  std::streamsize write(span<const char> span) {
104  size_t ulen = span.size();
105  size_t size = str.size();
106  if (!sl::support::is_streamsize(size)) throw io_exception(TRACEMSG(
107  "Target string size limit exceeded, length: [" + sl::support::to_string(str.size()) + "]"));
108  str.resize(size + ulen);
109  std::memcpy(std::addressof(str.front()) + size, span.data(), ulen);
110  return static_cast<std::streamsize> (ulen);
111  }
112 
118  std::string& get_string() {
119  return str;
120  }
121 
127  std::streamsize flush() {
128  // no-op
129  return 0;
130  }
131 
132 };
133 
134 } // namespace
135 }
136 
137 
138 #endif /* STATICLIB_IO_STRING_SINK_HPP */
139