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