CsCrypto  1.0.1
hex.h
1 /***********************************************************************
2 *
3 * Copyright (c) 2021-2024 Tim van Deurzen
4 * Copyright (c) 2021-2024 Barbara Geller
5 * Copyright (c) 2021-2024 Ansel Sermersheim
6 *
7 * This file is part of CsCrypto.
8 *
9 * CsCrypto is free software, released under the BSD 2-Clause license.
10 * For license details refer to LICENSE provided with this project.
11 *
12 * CsCrypto is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 *
16 * https://opensource.org/licenses/BSD-2-Clause
17 *
18 ***********************************************************************/
19 
20 #ifndef CS_CRYPTO_UTIL_HEX_H
21 #define CS_CRYPTO_UTIL_HEX_H
22 
23 #include <util/conversions/byte.h>
24 #include <util/tools/crypto_traits.h>
25 
26 #include <cstddef>
27 #include <iterator>
28 #include <string>
29 
30 namespace cs_crypto::util {
31 
32 struct hex_byte {
33  char high;
34  char low;
35 };
36 
37 constexpr hex_byte to_hex_char(const unsigned char value) noexcept
38 {
39  constexpr char const chars[] = "0123456789abcdef";
40  return {chars[value >> 4], chars[value & 0x0f]};
41 }
42 
43 constexpr hex_byte to_hex_char(const std::byte value) noexcept
44 {
45  return to_hex_char(std::to_integer<unsigned char>(value));
46 }
47 
48 template <typename Iter, typename Sentinel>
49 std::string hex(Iter iter, const Sentinel last)
50 {
51  std::string result;
52 
53  const auto distance = std::distance(iter, last);
54  result.reserve(distance * 2);
55 
56  while (iter != last) {
57  auto [high, low] = to_hex_char(*iter);
58  result.push_back(high);
59  result.push_back(low);
60  iter = std::next(iter);
61  }
62 
63  return result;
64 }
65 
66 template <typename Range, typename = std::enable_if_t<cs_crypto::traits::is_iterable_v<Range>>>
67 std::string hex(Range &&input)
68 {
69  return hex(std::begin(input), std::end(input));
70 }
71 
72 } // namespace cs_crypto::util
73 
74 #endif