staticlib_io  1.2.11
 All Classes Namespaces Files Functions Variables
hex_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: hex_sink.hpp
19  * Author: alex
20  *
21  * Created on June 2, 2018, 10:53 PM
22  */
23 
24 #ifndef STATICLIB_IO_HEX_SINK_HPP
25 #define STATICLIB_IO_HEX_SINK_HPP
26 
27 #include <ios>
28 
29 #include "staticlib/config.hpp"
30 
34 #include "staticlib/io/span.hpp"
35 
36 namespace staticlib {
37 namespace io {
38 
39 namespace hex_sink_detail {
40 
41 const std::array<char, 16> symbols = {{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}};
42 
43 } // namespace
44 
48 template<typename Sink>
49 class hex_sink {
57  std::array<char, 2> hbuf;
58 
59 public:
66  explicit hex_sink(Sink&& sink) :
67  sink(make_buffered_sink(std::move(sink))) {
68  hbuf[0] = '\0';
69  hbuf[1] = '\0';
70  }
71 
77  hex_sink(const hex_sink&) = delete;
78 
85  hex_sink& operator=(const hex_sink&) = delete;
86 
92  hex_sink(hex_sink&& other) STATICLIB_NOEXCEPT :
93  sink(std::move(other.sink)),
94  hbuf(std::move(other.hbuf)) { }
95 
102  hex_sink& operator=(hex_sink&& other) STATICLIB_NOEXCEPT {
103  sink = std::move(other.sink);
104  hbuf = std::move(other.hbuf);
105  return *this;
106  }
107 
114  std::streamsize write(span<const char> span) {
115  for (size_t i = 0; i < span.size(); i++) {
116  char ch = span.data()[i];
117  // http://stackoverflow.com/a/18025541/314015
118  unsigned char uch = static_cast<unsigned char>(ch);
119  hbuf[0] = hex_sink_detail::symbols[static_cast<size_t>(uch >> 4)];
120  hbuf[1] = hex_sink_detail::symbols[static_cast<size_t>(uch & 0x0f)];
121  sl::io::write_all(sink, {hbuf.data(), hbuf.size()});
122  }
123  return span.size_signed();
124  }
125 
131  std::streamsize flush() {
132  return sink.flush();
133  }
134 
140  Sink& get_sink() {
141  return sink.get_sink();
142  }
143 
144 };
145 
153 template <typename Sink,
154  class = typename std::enable_if<!std::is_lvalue_reference<Sink>::value>::type>
156  return hex_sink<Sink>(std::move(sink));
157 }
158 
166 template <typename Sink>
169 }
170 
171 } // namespace
172 }
173 
174 #endif /* STATICLIB_IO_HEX_SINK_HPP */
175