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