staticlib_io  1.2.11
 All Classes Namespaces Files Functions Variables
counting_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: counting_sink.hpp
19  * Author: alex
20  *
21  * Created on October 9, 2015, 12:23 PM
22  */
23 
24 #ifndef STATICLIB_IO_COUNTING_SINK_HPP
25 #define STATICLIB_IO_COUNTING_SINK_HPP
26 
27 #include <ios>
28 
29 #include "staticlib/config.hpp"
30 
32 #include "staticlib/io/span.hpp"
33 
34 namespace staticlib {
35 namespace io {
36 
40 template<typename Sink>
45  Sink sink;
49  size_t count = 0;
50 
51 public:
58  explicit counting_sink(Sink&& sink) :
59  sink(std::move(sink)) { }
60 
66  counting_sink(const counting_sink&) = delete;
67 
74  counting_sink& operator=(const counting_sink&) = delete;
75 
81  counting_sink(counting_sink&& other) STATICLIB_NOEXCEPT :
82  sink(std::move(other.sink)),
83  count(other.count) {
84  other.count = 0;
85  }
86 
93  counting_sink& operator=(counting_sink&& other) STATICLIB_NOEXCEPT {
94  sink = std::move(other.sink);
95  count = other.count;
96  other.count = 0;
97  return *this;
98  }
99 
106  std::streamsize write(span<const char> span) {
107  std::streamsize res = sink.write(span);
108  if (sl::support::is_sizet(res)) {
109  count += static_cast<size_t>(res);
110  }
111  return res;
112  }
113 
119  std::streamsize flush() {
120  return sink.flush();
121  }
122 
128  size_t get_count() {
129  return count;
130  }
131 
137  Sink& get_sink() {
138  return sink;
139  }
140 
141 };
142 
150 template <typename Sink,
151  class = typename std::enable_if<!std::is_lvalue_reference<Sink>::value>::type>
153  return counting_sink<Sink>(std::move(sink));
154 }
155 
163 template <typename Sink>
166 }
167 
168 } // namespace
169 }
170 
171 #endif /* STATICLIB_IO_COUNTING_SINK_HPP */
172