staticlib_io  1.2.11
 All Classes Namespaces Files Functions Variables
memory_sink.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2018, 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: memory_sink.hpp
19  * Author: alex
20  *
21  * Created on June 8, 2018, 8:40 PM
22  */
23 
24 #ifndef STATICLIB_IO_MEMORY_SINK_HPP
25 #define STATICLIB_IO_MEMORY_SINK_HPP
26 
27 #include <cstring>
28 #include <ios>
29 
30 #include "staticlib/config.hpp"
31 #include "staticlib/support.hpp"
32 
34 #include "staticlib/io/span.hpp"
35 
36 namespace staticlib {
37 namespace io {
38 
43 class memory_sink {
44 
48  span<char> dest;
52  size_t idx = 0;
53 public:
58  dest(dest) { }
59 
65  memory_sink(const memory_sink& other) :
66  dest(other.dest),
67  idx(other.idx) { }
68 
76  dest = other.dest;
77  idx = other.idx;
78  return *this;
79  }
80 
86  memory_sink(memory_sink&& other) STATICLIB_NOEXCEPT :
87  dest(std::move(other.dest)),
88  idx(other.idx) { }
89 
96  memory_sink& operator=(memory_sink&& other) STATICLIB_NOEXCEPT {
97  dest = std::move(other.dest);
98  idx = other.idx;
99  return *this;
100  }
101 
108  std::streamsize write(span<const char> span) {
109  if (span.size() <= dest.size() - idx) {
110  std::memcpy(dest.data() + idx, span.data(), span.size());
111  idx += span.size();
112  return span.size_signed();
113  }
114  throw io_exception(TRACEMSG("Write overflow," +
115  " req: [" + sl::support::to_string(span.size()) + "]," +
116  " avail: [" + sl::support::to_string(dest.size() - idx) + "]"));
117  }
118 
124  std::streamsize flush() {
125  // no-op
126  return 0;
127  }
128 
129 };
130 
131 } // namespace
132 }
133 
134 
135 #endif /* STATICLIB_IO_MEMORY_SINK_HPP */
136