src/format.h

changeset 72
03e4d9db3fd9
child 73
1ee9b312dc18
equal deleted inserted replaced
71:11f23fabf8a6 72:03e4d9db3fd9
1 #ifndef BOTC_FORMAT_H
2 #define BOTC_FORMAT_H
3
4 #include "str.h"
5 #include "containers.h"
6
7 class format_arg
8 {
9 public:
10 format_arg (const string& a)
11 {
12 m_string = a;
13 }
14
15 format_arg (int a)
16 {
17 m_string.sprintf ("%d", a);
18 }
19
20 format_arg (long a)
21 {
22 m_string.sprintf ("%ld", a);
23 }
24
25 format_arg (uint a)
26 {
27 m_string.sprintf ("%u", a);
28 }
29
30 format_arg (ulong a)
31 {
32 m_string.sprintf ("%lu", a);
33 }
34
35 format_arg (const char* a)
36 {
37 m_string = a;
38 }
39
40 format_arg (void* a)
41 {
42 m_string.sprintf ("%p", a);
43 }
44
45 format_arg (const void* a)
46 {
47 m_string.sprintf ("%p", a);
48 }
49
50 template<class T> format_arg (const list<T>& list)
51 {
52 if (list.is_empty())
53 {
54 m_string = "{}";
55 return;
56 }
57
58 m_string = "{ ";
59
60 for (const T & a : list)
61 {
62 if (&a != &list[0])
63 m_string += ", ";
64
65 m_string += format_arg (a).as_string();
66 }
67
68 m_string += " }";
69 }
70
71 /*
72 template<class T, class R> format_arg (const std::map<T, R>& a)
73 {
74 if (a.size() == 0)
75 {
76 m_string = "{}";
77 return;
78 }
79
80 m_string = "{ ";
81
82 for (std::pair<T, R> it : a)
83 {
84 if (m_string != "{ ")
85 m_string += ", ";
86
87 m_string += format_arg (it.first).as_string() + "=" +
88 format_arg (it.second).as_string();
89 }
90
91 m_string += " }";
92 }
93 */
94
95 inline const string& as_string() const
96 {
97 return m_string;
98 }
99
100 private:
101 string m_string;
102 };
103
104 template<class T> string custom_format (T a, const char* fmtstr)
105 {
106 string out;
107 out.sprintf (fmtstr, a);
108 return out;
109 }
110
111 inline string hex (ulong a)
112 {
113 return custom_format (a, "0x%X");
114 }
115
116 inline string charnum (char a)
117 {
118 return custom_format (a, "%d");
119 }
120
121 string format_args (const list<format_arg>& args);
122 void print_args (FILE* fp, const list<format_arg>& args);
123 void do_fatal (const list<format_arg>& args);
124
125 #ifndef IN_IDE_PARSER
126 #define format(...) format_args({ __VA_ARGS__ })
127 #define fprint(A, ...) print_args( A, { __VA_ARGS__ })
128 #define print(...) print_args( stdout, { __VA_ARGS__ })
129 #define fatal(...) do_fatal({ __VA_ARGS__ })
130 #else
131 string format (void, ...);
132 void fprint (FILE* fp, ...);
133 void print (void, ...);
134 void fatal (void, ...);
135 #endif
136
137 #ifndef IN_IDE_PARSER
138 # ifdef DEBUG
139 # define devf(...) fprint( stderr, __VA_ARGS__ )
140 # define dvalof( A ) fprint( stderr, "value of '%1' = %2\n", #A, A )
141 # else
142 # define devf(...)
143 # define dvalof( A )
144 # endif // DEBUG
145 #else
146 void devf (void, ...);
147 void dvalof (void a);
148 #endif // IN_IDE_PARSER
149
150 #endif // BOTC_FORMAT_H

mercurial