openMSX
HexDump.cc
Go to the documentation of this file.
1 #include "HexDump.hh"
2 #include "strCat.hh"
3 #include "xrange.hh"
4 #include <algorithm>
5 #include <cassert>
6 
7 namespace HexDump {
8 
10 
11 [[nodiscard]] static constexpr char encode2(uint8_t x)
12 {
13  return (x < 10) ? char(x + '0') : char(x - 10 + 'A');
14 }
15 [[nodiscard]] static auto encode(uint8_t x)
16 {
17  return tmpStrCat(encode2(x >> 4), encode2(x & 15));
18 }
19 std::string encode(const uint8_t* input, size_t len, bool newlines)
20 {
21  std::string ret;
22  while (len) {
23  if (newlines && !ret.empty()) ret += '\n';
24  int t = int(std::min<size_t>(16, len));
25  for (auto i : xrange(t)) {
26  ret += encode(*input++);
27  if (i != (t - 1)) ret += ' ';
28  }
29  len -= t;
30  }
31  return ret;
32 }
33 
34 [[nodiscard]] static constexpr int decode(char x)
35 {
36  if (('0' <= x) && (x <= '9')) {
37  return x - '0';
38  } else if (('A' <= x) && (x <= 'F')) {
39  return x - 'A' + 10;
40  } else if (('a' <= x) && (x <= 'f')) {
41  return x - 'a' + 10;
42  } else {
43  return -1;
44  }
45 }
46 std::pair<MemBuffer<uint8_t>, size_t> decode(std::string_view input)
47 {
48  auto inSize = input.size();
49  auto outSize = inSize / 2; // overestimation
50  MemBuffer<uint8_t> ret(outSize); // too big
51 
52  size_t out = 0;
53  bool flip = true;
54  uint8_t tmp = 0;
55  for (char c : input) {
56  int d = decode(c);
57  if (d == -1) continue;
58  if (flip) {
59  tmp = d;
60  } else {
61  ret[out++] = (tmp << 4) | d;
62  }
63  flip = !flip;
64  }
65 
66  assert(outSize >= out);
67  ret.resize(out); // shrink to correct size
68  return {std::move(ret), out};
69 }
70 
71 bool decode_inplace(std::string_view input, uint8_t* output, size_t outSize)
72 {
73  size_t out = 0;
74  bool flip = true;
75  uint8_t tmp = 0;
76  for (char c : input) {
77  int d = decode(c);
78  if (d == -1) continue;
79  if (flip) {
80  tmp = d;
81  } else {
82  if (out == outSize) [[unlikely]] return false;
83  output[out++] = (tmp << 4) | d;
84  }
85  flip = !flip;
86  }
87 
88  return out == outSize;
89 }
90 
91 } // namespace HexDump
TclObject t
This class manages the lifetime of a block of memory.
Definition: MemBuffer.hh:29
void resize(size_t size)
Grow or shrink the memory block.
Definition: MemBuffer.hh:111
bool decode_inplace(std::string_view input, uint8_t *output, size_t outSize)
Definition: HexDump.cc:71
constexpr KeyMatrixPosition x
Keyboard bindings.
Definition: Keyboard.cc:127
TemporaryString tmpStrCat(Ts &&... ts)
Definition: strCat.hh:617
constexpr auto xrange(T e)
Definition: xrange.hh:133