libyuni
hexdump.hxx
1 /*
2 ** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org).
3 **
4 ** This Source Code Form is subject to the terms of the Mozilla Public License
5 ** v.2.0. If a copy of the MPL was not distributed with this file, You can
6 ** obtain one at http://mozilla.org/MPL/2.0/.
7 **
8 ** gitlab: https://gitlab.com/libyuni/libyuni/
9 ** github: https://github.com/libyuni/libyuni/ {mirror}
10 */
11 #pragma once
12 #include "hexdump.h"
13 
14 
15 
16 namespace Yuni
17 {
18 namespace Core
19 {
20 namespace Utils
21 {
22 
23  inline Hexdump::Hexdump(const char* buffer, uint size)
24  : pBuffer(buffer), pSize(size)
25  {}
26 
27 
28  inline Hexdump::Hexdump(const Hexdump& rhs)
29  : pBuffer(rhs.pBuffer), pSize(rhs.pSize)
30  {}
31 
32 
33  template<class U>
34  inline Hexdump::Hexdump(const U& buffer)
35  : pBuffer((const char *)buffer.data()), pSize(buffer.sizeInBytes())
36  {}
37 
38 
39  template <class U>
40  void Hexdump::dump(U& stream) const
41  {
42  Yuni::String line;
43  uint printed;
44  uint remains = pSize;
45 
46  for (printed = 0; printed < pSize; printed += 0x10)
47  {
48  remains = pSize - printed;
49 
50  // Print the line's address
51  line.appendFormat("%08.8p: ", (pBuffer + printed));
52 
53  // Print the next 16 bytes (or less) in hex.
54  dumpHexadecimal(line, pBuffer + printed, (remains > 0x10) ? 0x10 : remains);
55 
56  // Print the next 16 bytes (or less) in printable chars.
57  dumpPrintable(line, pBuffer + printed, (remains > 0x10) ? 0x10 : remains);
58 
59  // Add the position in the buffer, padded to 2 bytes.
60  line.appendFormat(" %04.4x-%04.4x\n", printed, printed + 0x0f);
61 
62  // Put the line in the stream
63  stream << line;
64  line.clear();
65  }
66  }
67 
68 
69  inline String Hexdump::dump() const
70  {
71  String s;
72  dump(s);
73  return s;
74  }
75 
76 
77 
78 } // namespace Utils
79 } // namespace Core
80 } // namespace Yuni
81 
82 
83 
84 
85 inline std::ostream& operator<< (std::ostream& outStream, const Yuni::Core::Utils::Hexdump& hexDumper)
86 {
87  hexDumper.dump(outStream);
88  return outStream;
89 }
CString & clear()
Empty the string.
Definition: string.hxx:693
Hexdump(const char *buffer, uint size)
Construct from a simple buffer.
Definition: hexdump.hxx:23
Definition: program.cpp:19
A simple hexadecimal buffer dumper.
Definition: hexdump.h:51
CString & appendFormat(const char *format,...)
Append formatted string.
Definition: string.hxx:2729
void dump(U &outStream) const
Dumps the current buffer to a stream.
Definition: hexdump.hxx:40
Character stringThe class manipulates and stores sequences of characters.
Definition: fwd.h:32
String dump() const
Dumps the current buffer to a string.
Definition: hexdump.hxx:69