hex.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /*
  2. Copyright (c) Marshall Clow 2011-2012.
  3. Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. Thanks to Nevin for his comments/help.
  6. */
  7. /*
  8. General problem - turn a sequence of integral types into a sequence of hexadecimal characters.
  9. - and back.
  10. */
  11. /// \file hex.hpp
  12. /// \brief Convert sequence of integral types into a sequence of hexadecimal
  13. /// characters and back. Based on the MySQL functions HEX and UNHEX
  14. /// \author Marshall Clow
  15. #ifndef BOOST_ALGORITHM_HEXHPP
  16. #define BOOST_ALGORITHM_HEXHPP
  17. #include <iterator> // for std::iterator_traits
  18. #include <stdexcept>
  19. #include <boost/range/begin.hpp>
  20. #include <boost/range/end.hpp>
  21. #include <boost/exception/exception.hpp>
  22. #include <boost/exception/info.hpp>
  23. #include <boost/throw_exception.hpp>
  24. #include <boost/utility/enable_if.hpp>
  25. #include <boost/type_traits/is_integral.hpp>
  26. namespace boost { namespace algorithm {
  27. /*!
  28. \struct hex_decode_error
  29. \brief Base exception class for all hex decoding errors
  30. */ /*!
  31. \struct non_hex_input
  32. \brief Thrown when a non-hex value (0-9, A-F) encountered when decoding.
  33. Contains the offending character
  34. */ /*!
  35. \struct not_enough_input
  36. \brief Thrown when the input sequence unexpectedly ends
  37. */
  38. struct hex_decode_error : virtual boost::exception, virtual std::exception {};
  39. struct not_enough_input : virtual hex_decode_error {};
  40. struct non_hex_input : virtual hex_decode_error {};
  41. typedef boost::error_info<struct bad_char_,char> bad_char;
  42. namespace detail {
  43. /// \cond DOXYGEN_HIDE
  44. template <typename T, typename OutputIterator>
  45. OutputIterator encode_one ( T val, OutputIterator out, const char * hexDigits ) {
  46. const std::size_t num_hex_digits = 2 * sizeof ( T );
  47. char res [ num_hex_digits ];
  48. char *p = res + num_hex_digits;
  49. for ( std::size_t i = 0; i < num_hex_digits; ++i, val >>= 4 )
  50. *--p = hexDigits [ val & 0x0F ];
  51. return std::copy ( res, res + num_hex_digits, out );
  52. }
  53. template <typename T>
  54. unsigned char hex_char_to_int ( T val ) {
  55. char c = static_cast<char> ( val );
  56. unsigned retval = 0;
  57. if ( c >= '0' && c <= '9' ) retval = c - '0';
  58. else if ( c >= 'A' && c <= 'F' ) retval = c - 'A' + 10;
  59. else if ( c >= 'a' && c <= 'f' ) retval = c - 'a' + 10;
  60. else BOOST_THROW_EXCEPTION (non_hex_input() << bad_char (c));
  61. return static_cast<char>(retval);
  62. }
  63. // My own iterator_traits class.
  64. // It is here so that I can "reach inside" some kinds of output iterators
  65. // and get the type to write.
  66. template <typename Iterator>
  67. struct hex_iterator_traits {
  68. typedef typename std::iterator_traits<Iterator>::value_type value_type;
  69. };
  70. template<typename Container>
  71. struct hex_iterator_traits< std::back_insert_iterator<Container> > {
  72. typedef typename Container::value_type value_type;
  73. };
  74. template<typename Container>
  75. struct hex_iterator_traits< std::front_insert_iterator<Container> > {
  76. typedef typename Container::value_type value_type;
  77. };
  78. template<typename Container>
  79. struct hex_iterator_traits< std::insert_iterator<Container> > {
  80. typedef typename Container::value_type value_type;
  81. };
  82. // ostream_iterators have three template parameters.
  83. // The first one is the output type, the second one is the character type of
  84. // the underlying stream, the third is the character traits.
  85. // We only care about the first one.
  86. template<typename T, typename charType, typename traits>
  87. struct hex_iterator_traits< std::ostream_iterator<T, charType, traits> > {
  88. typedef T value_type;
  89. };
  90. template <typename Iterator>
  91. bool iter_end ( Iterator current, Iterator last ) { return current == last; }
  92. template <typename T>
  93. bool ptr_end ( const T* ptr, const T* /*end*/ ) { return *ptr == '\0'; }
  94. // What can we assume here about the inputs?
  95. // is std::iterator_traits<InputIterator>::value_type always 'char' ?
  96. // Could it be wchar_t, say? Does it matter?
  97. // We are assuming ASCII for the values - but what about the storage?
  98. template <typename InputIterator, typename OutputIterator, typename EndPred>
  99. typename boost::enable_if<boost::is_integral<typename hex_iterator_traits<OutputIterator>::value_type>, OutputIterator>::type
  100. decode_one ( InputIterator &first, InputIterator last, OutputIterator out, EndPred pred ) {
  101. typedef typename hex_iterator_traits<OutputIterator>::value_type T;
  102. T res (0);
  103. // Need to make sure that we get can read that many chars here.
  104. for ( std::size_t i = 0; i < 2 * sizeof ( T ); ++i, ++first ) {
  105. if ( pred ( first, last ))
  106. BOOST_THROW_EXCEPTION (not_enough_input ());
  107. res = ( 16 * res ) + hex_char_to_int (*first);
  108. }
  109. *out = res;
  110. return ++out;
  111. }
  112. /// \endcond
  113. }
  114. /// \fn hex ( InputIterator first, InputIterator last, OutputIterator out )
  115. /// \brief Converts a sequence of integral types into a hexadecimal sequence of characters.
  116. ///
  117. /// \param first The start of the input sequence
  118. /// \param last One past the end of the input sequence
  119. /// \param out An output iterator to the results into
  120. /// \return The updated output iterator
  121. /// \note Based on the MySQL function of the same name
  122. template <typename InputIterator, typename OutputIterator>
  123. typename boost::enable_if<boost::is_integral<typename detail::hex_iterator_traits<InputIterator>::value_type>, OutputIterator>::type
  124. hex ( InputIterator first, InputIterator last, OutputIterator out ) {
  125. for ( ; first != last; ++first )
  126. out = detail::encode_one ( *first, out, "0123456789ABCDEF" );
  127. return out;
  128. }
  129. /// \fn hex_lower ( InputIterator first, InputIterator last, OutputIterator out )
  130. /// \brief Converts a sequence of integral types into a lower case hexadecimal sequence of characters.
  131. ///
  132. /// \param first The start of the input sequence
  133. /// \param last One past the end of the input sequence
  134. /// \param out An output iterator to the results into
  135. /// \return The updated output iterator
  136. /// \note Based on the MySQL function of the same name
  137. template <typename InputIterator, typename OutputIterator>
  138. typename boost::enable_if<boost::is_integral<typename detail::hex_iterator_traits<InputIterator>::value_type>, OutputIterator>::type
  139. hex_lower ( InputIterator first, InputIterator last, OutputIterator out ) {
  140. for ( ; first != last; ++first )
  141. out = detail::encode_one ( *first, out, "0123456789abcdef" );
  142. return out;
  143. }
  144. /// \fn hex ( const T *ptr, OutputIterator out )
  145. /// \brief Converts a sequence of integral types into a hexadecimal sequence of characters.
  146. ///
  147. /// \param ptr A pointer to a 0-terminated sequence of data.
  148. /// \param out An output iterator to the results into
  149. /// \return The updated output iterator
  150. /// \note Based on the MySQL function of the same name
  151. template <typename T, typename OutputIterator>
  152. typename boost::enable_if<boost::is_integral<T>, OutputIterator>::type
  153. hex ( const T *ptr, OutputIterator out ) {
  154. while ( *ptr )
  155. out = detail::encode_one ( *ptr++, out, "0123456789ABCDEF" );
  156. return out;
  157. }
  158. /// \fn hex_lower ( const T *ptr, OutputIterator out )
  159. /// \brief Converts a sequence of integral types into a lower case hexadecimal sequence of characters.
  160. ///
  161. /// \param ptr A pointer to a 0-terminated sequence of data.
  162. /// \param out An output iterator to the results into
  163. /// \return The updated output iterator
  164. /// \note Based on the MySQL function of the same name
  165. template <typename T, typename OutputIterator>
  166. typename boost::enable_if<boost::is_integral<T>, OutputIterator>::type
  167. hex_lower ( const T *ptr, OutputIterator out ) {
  168. while ( *ptr )
  169. out = detail::encode_one ( *ptr++, out, "0123456789abcdef" );
  170. return out;
  171. }
  172. /// \fn hex ( const Range &r, OutputIterator out )
  173. /// \brief Converts a sequence of integral types into a hexadecimal sequence of characters.
  174. ///
  175. /// \param r The input range
  176. /// \param out An output iterator to the results into
  177. /// \return The updated output iterator
  178. /// \note Based on the MySQL function of the same name
  179. template <typename Range, typename OutputIterator>
  180. typename boost::enable_if<boost::is_integral<typename detail::hex_iterator_traits<typename Range::iterator>::value_type>, OutputIterator>::type
  181. hex ( const Range &r, OutputIterator out ) {
  182. return hex (boost::begin(r), boost::end(r), out);
  183. }
  184. /// \fn hex_lower ( const Range &r, OutputIterator out )
  185. /// \brief Converts a sequence of integral types into a lower case hexadecimal sequence of characters.
  186. ///
  187. /// \param r The input range
  188. /// \param out An output iterator to the results into
  189. /// \return The updated output iterator
  190. /// \note Based on the MySQL function of the same name
  191. template <typename Range, typename OutputIterator>
  192. typename boost::enable_if<boost::is_integral<typename detail::hex_iterator_traits<typename Range::iterator>::value_type>, OutputIterator>::type
  193. hex_lower ( const Range &r, OutputIterator out ) {
  194. return hex_lower (boost::begin(r), boost::end(r), out);
  195. }
  196. /// \fn unhex ( InputIterator first, InputIterator last, OutputIterator out )
  197. /// \brief Converts a sequence of hexadecimal characters into a sequence of integers.
  198. ///
  199. /// \param first The start of the input sequence
  200. /// \param last One past the end of the input sequence
  201. /// \param out An output iterator to the results into
  202. /// \return The updated output iterator
  203. /// \note Based on the MySQL function of the same name
  204. template <typename InputIterator, typename OutputIterator>
  205. OutputIterator unhex ( InputIterator first, InputIterator last, OutputIterator out ) {
  206. while ( first != last )
  207. out = detail::decode_one ( first, last, out, detail::iter_end<InputIterator> );
  208. return out;
  209. }
  210. /// \fn unhex ( const T *ptr, OutputIterator out )
  211. /// \brief Converts a sequence of hexadecimal characters into a sequence of integers.
  212. ///
  213. /// \param ptr A pointer to a null-terminated input sequence.
  214. /// \param out An output iterator to the results into
  215. /// \return The updated output iterator
  216. /// \note Based on the MySQL function of the same name
  217. template <typename T, typename OutputIterator>
  218. OutputIterator unhex ( const T *ptr, OutputIterator out ) {
  219. // If we run into the terminator while decoding, we will throw a
  220. // malformed input exception. It would be nicer to throw a 'Not enough input'
  221. // exception - but how much extra work would that require?
  222. while ( *ptr )
  223. out = detail::decode_one ( ptr, (const T *) NULL, out, detail::ptr_end<T> );
  224. return out;
  225. }
  226. /// \fn OutputIterator unhex ( const Range &r, OutputIterator out )
  227. /// \brief Converts a sequence of hexadecimal characters into a sequence of integers.
  228. ///
  229. /// \param r The input range
  230. /// \param out An output iterator to the results into
  231. /// \return The updated output iterator
  232. /// \note Based on the MySQL function of the same name
  233. template <typename Range, typename OutputIterator>
  234. OutputIterator unhex ( const Range &r, OutputIterator out ) {
  235. return unhex (boost::begin(r), boost::end(r), out);
  236. }
  237. /// \fn String hex ( const String &input )
  238. /// \brief Converts a sequence of integral types into a hexadecimal sequence of characters.
  239. ///
  240. /// \param input A container to be converted
  241. /// \return A container with the encoded text
  242. template<typename String>
  243. String hex ( const String &input ) {
  244. String output;
  245. output.reserve (input.size () * (2 * sizeof (typename String::value_type)));
  246. (void) hex (input, std::back_inserter (output));
  247. return output;
  248. }
  249. /// \fn String hex_lower ( const String &input )
  250. /// \brief Converts a sequence of integral types into a lower case hexadecimal sequence of characters.
  251. ///
  252. /// \param input A container to be converted
  253. /// \return A container with the encoded text
  254. template<typename String>
  255. String hex_lower ( const String &input ) {
  256. String output;
  257. output.reserve (input.size () * (2 * sizeof (typename String::value_type)));
  258. (void) hex_lower (input, std::back_inserter (output));
  259. return output;
  260. }
  261. /// \fn String unhex ( const String &input )
  262. /// \brief Converts a sequence of hexadecimal characters into a sequence of characters.
  263. ///
  264. /// \param input A container to be converted
  265. /// \return A container with the decoded text
  266. template<typename String>
  267. String unhex ( const String &input ) {
  268. String output;
  269. output.reserve (input.size () / (2 * sizeof (typename String::value_type)));
  270. (void) unhex (input, std::back_inserter (output));
  271. return output;
  272. }
  273. }}
  274. #endif // BOOST_ALGORITHM_HEXHPP