CCF
Loading...
Searching...
No Matches
hex.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
5#define FMT_HEADER_ONLY
6#include <fmt/format.h>
7#include <fmt/ranges.h>
8#include <span>
9#include <string>
10#include <vector>
11
12namespace ccf::ds
13{
14 static uint8_t hex_char_to_int(char c)
15 {
16 if (c <= '9')
17 {
18 return c - '0';
19 }
20 else if (c <= 'F')
21 {
22 return c - 'A' + 10;
23 }
24 else if (c <= 'f')
25 {
26 return c - 'a' + 10;
27 }
28 return c;
29 }
30
31 // Notes: uses lowercase for 'abcdef' characters
32 template <typename Iter>
33 inline static std::string to_hex(Iter begin, Iter end)
34 {
35 return fmt::format("{:02x}", fmt::join(begin, end, ""));
36 }
37
38 template <typename T>
39 inline static std::string to_hex(const T& data)
40 {
41 return to_hex(data.begin(), data.end());
42 }
43
44 inline static std::string to_hex(std::span<const uint8_t> buf)
45 {
46 std::string r;
47 for (auto c : buf)
48 r += fmt::format("{:02x}", c);
49 return r;
50 }
51
52 template <typename Iter>
53 static void from_hex(const std::string& str, Iter begin, Iter end)
54 {
55 if ((str.size() & 1) != 0)
56 {
57 throw std::logic_error(fmt::format(
58 "Input string '{}' is not of even length: {}", str, str.size()));
59 }
60
61 if (std::distance(begin, end) != str.size() / 2)
62 {
63 throw std::logic_error(fmt::format(
64 "Output container of size {} cannot fit decoded hex str {}",
65 std::distance(begin, end),
66 str.size() / 2));
67 }
68
69 auto it = begin;
70 for (size_t i = 0; i < str.size(); i += 2, ++it)
71 {
72 *it = 16 * hex_char_to_int(str[i]) + hex_char_to_int(str[i + 1]);
73 }
74 }
75
76 inline static std::vector<uint8_t> from_hex(const std::string& str)
77 {
78 std::vector<uint8_t> ret(str.size() / 2);
79 from_hex(str, ret.begin(), ret.end());
80 return ret;
81 }
82
83 template <typename T>
84 inline static void from_hex(const std::string& str, T& out)
85 {
86 from_hex(str, out.begin(), out.end());
87 }
88}
Definition contiguous_set.h:12