]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/configuration/sgconfig/dumphelpers.h
Explicit prohibition of the PLUGIN_LOGGER assignment.
[stg.git] / projects / stargazer / plugins / configuration / sgconfig / dumphelpers.h
1 #ifndef __STG_DUMP_HELPERS_H__
2 #define __STG_DUMP_HELPERS_H__
3
4 #include "stg/common.h"
5
6 #include <string>
7 #include <fstream>
8 #include <sstream>
9 #include <iomanip>
10
11 #include <cstddef>
12 #include <ctime>
13
14 namespace STG
15 {
16
17 class Dumper
18 {
19     public:
20         explicit Dumper(const std::string& tag)
21             : m_stream(getName(tag).c_str())
22         {
23         }
24         ~Dumper() {}
25
26         void write(const void* data, size_t size)
27         {
28             writePrefix();
29             m_stream << " ";
30             writeHEX(data, size);
31         }
32
33     private:
34         std::ofstream m_stream;
35
36         tm getTime() const
37         {
38             time_t now = time(NULL);
39             tm localTime;
40             localtime_r(&now, &localTime);
41             return localTime;
42         }
43
44         std::string getName(const std::string& tag) const
45         {
46             tm localTime = getTime();
47
48             std::ostringstream res;
49             res << tag
50                 << "-" << (localTime.tm_year + 1900) << twoDigit(localTime.tm_mon + 1) << twoDigit(localTime.tm_mday)
51                 << "-" << twoDigit(localTime.tm_hour) << twoDigit(localTime.tm_min) << twoDigit(localTime.tm_sec)
52                 << ".data";
53
54             return res.str();
55         }
56
57         void writePrefix()
58         {
59             tm localTime = getTime();
60             m_stream << "[" << (localTime.tm_year + 1900) << "-" << twoDigit(localTime.tm_mon + 1) << "-" << twoDigit(localTime.tm_mday)
61                      << " " << twoDigit(localTime.tm_hour) << ":" << twoDigit(localTime.tm_min) << ":" << twoDigit(localTime.tm_sec)
62                      << "]";
63         }
64
65         void writeHEX(const void* data, size_t size)
66         {
67             m_stream << "(" << std::setw(4) << std::setfill(' ') << size << ") ";
68             const unsigned char* pos = static_cast<const unsigned char*>(data);
69             for (size_t i = 0; i < size; ++i)
70                 m_stream << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(*pos++);
71             m_stream << std::dec << "\n";
72         }
73
74         std::string twoDigit(int value) const
75         {
76             std::string res = x2str(value);
77             if (res.length() < 2)
78                 res = "0" + res;
79             return res;
80         }
81 };
82
83 } // namespace Caster
84
85 #endif