staticlib_io  1.2.11
 All Classes Namespaces Files Functions Variables
string_source.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_source.hpp
19  * Author: alex
20  *
21  * Created on November 6, 2015, 3:59 PM
22  */
23 
24 #ifndef STATICLIB_IO_STRING_SOURCE_HPP
25 #define STATICLIB_IO_STRING_SOURCE_HPP
26 
27 #include <ios>
28 #include <string>
29 #include <cstdint>
30 #include <cstring>
31 
32 #include "staticlib/config.hpp"
33 
35 #include "staticlib/io/span.hpp"
36 
37 namespace staticlib {
38 namespace io {
39 
47  std::string str;
51  size_t idx;
55  size_t str_len;
56 
57 public:
63  string_source(std::string&& str) :
64  str(std::move(str)),
65  idx(0),
66  str_len(this->str.length()) { }
67 
73  string_source(const std::string& str) :
74  string_source(std::string(str.data(), str.length())) { }
75 
83  string_source(std::string&& str, size_t from, size_t to) :
84  str(std::move(str)),
85  idx(from),
86  str_len(to) { }
87 
93  string_source(const string_source&) = delete;
94 
101  string_source& operator=(const string_source&) = delete;
102 
108  string_source(string_source&& other) STATICLIB_NOEXCEPT :
109  str(std::move(other.str)),
110  idx(other.idx),
111  str_len(other.str_len) {
112  other.idx = 0;
113  other.str_len = 0;
114  }
115 
122  string_source& operator=(string_source&& other) STATICLIB_NOEXCEPT {
123  str = std::move(other.str);
124  idx = other.idx;
125  other.idx = 0;
126  str_len = other.str_len;
127  other.str_len = 0;
128  return *this;
129  }
130 
137  std::streamsize read(span<char> span) {
138  size_t ulen = span.size();
139  size_t avail = str_len - idx;
140  if (avail > 0) {
141  size_t len = ulen <= avail ? ulen : avail;
142  std::memcpy(span.data(), std::addressof(str.front()) + idx, len);
143  this->idx += len;
144  return static_cast<std::streamsize> (len);
145  } else return std::char_traits<char>::eof();
146  }
147 
153  std::string& get_string() {
154  return str;
155  }
156 
157 };
158 
159 } // namespace
160 }
161 
162 #endif /* STATICLIB_IO_STRING_SOURCE_HPP */
163