Avoid the build warnings: 'this statement may fall through'
[amule.git] / src / libs / common / Format.cpp
blobf3aa552c8ea63e790a518e1db43187b6aaf8c5f3
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2005-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 //
6 // Any parts of this program derived from the xMule, lMule or eMule project,
7 // or contributed by third-party developers are copyrighted by their
8 // respective authors.
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "Format.h"
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #if defined HAVE_STDINT_H
32 # include <stdint.h>
33 #elif defined HAVE_INTTYPES_H
34 # include <inttypes.h>
35 #endif
37 #include <wx/intl.h> // Needed for _()
39 #include <errno.h> // Needed for errno and EINVAL
40 #include "strerror_r.h" // Needed for mule_strerror_r()
42 /** Returns true if the char is a format-type. */
43 inline bool isTypeChar(wxChar c)
45 switch (c) {
46 case wxT('s'): // String of characters
47 case wxT('u'): // Unsigned decimal integer
48 case wxT('i'): // Signed decimal integer
49 case wxT('d'): // Signed decimal integer
50 case wxT('c'): // Character
51 case wxT('f'): // Decimal floating point
52 case wxT('F'): // Decimal floating point
53 case wxT('x'): // Unsigned hexadecimal integer
54 case wxT('X'): // Unsigned hexadecimal integer (capital letters)
55 case wxT('o'): // Unsigned octal
56 case wxT('e'): // Scientific notation (mantise/exponent) using e character
57 case wxT('E'): // Scientific notation (mantise/exponent) using E character
58 case wxT('g'): // Use shorter %e or %f
59 case wxT('G'): // Use shorter %E or %F
60 case wxT('p'): // Pointer
61 case wxT('n'): // Not supported, still needs to be caught though
62 case wxT('a'): // (C99; not in SUSv2) Double in hexadecimal notation.
63 case wxT('A'): // (C99; not in SUSv2) Double in hexadecimal notation (capital letters).
64 case wxT('C'): // (Not in C99, but in SUSv2.) Synonym for lc. Don't use. Not supported.
65 case wxT('S'): // (Not in C99, but in SUSv2.) Synonym for ls. Don't use. Not supported.
66 case wxT('m'): // (Glibc extension.) Print output of strerror(errno). No argument is required.
67 // case wxT('%'): // A `%' is written. No argument is converted. The complete conversion specification is `%%'.
68 return true;
71 return false;
74 /** Returns true if the char is a valid flag. */
75 inline bool isFlagChar(wxChar c)
77 switch (c) {
78 // C standard flags
79 case wxT('+'): // Include sign for integers
80 case wxT('-'): // Left-align output
81 case wxT('#'): // Alternate form, varies
82 case wxT(' '): // Pad with spaces
83 case wxT('0'): // Pad with zeros
84 // SUSv2
85 case wxT('\''): // For decimal conversion (i, d, u, f, F, g, G) the output is to be grouped with thousands' grouping characters if the locale information indicates any.
86 // glibc 2.2
87 case wxT('I'): // For decimal integer conversion (i, d, u) the output uses the locale's alternative output digits, if any.
88 return true;
91 return false;
94 /** Returns true if the char is a valid length modifier. */
95 inline bool isLengthChar(wxChar c)
97 switch (c) {
98 case wxT('h'): // Short ('hh') and char ('h')
99 case wxT('l'): // Long ('l') and long long ('ll')
100 case wxT('L'): // Double long
101 case wxT('z'): // size_t
102 case wxT('j'): // intmax_t
103 case wxT('t'): // ptrdiff_t
104 case wxT('q'): // quad. Synonym for 'll'. Don't use.
105 return true;
108 return false;
111 /** Returns true if the argument is a valid length modifier */
112 inline bool isValidLength(const wxString& str)
114 return ((str == wxT("hh")) || (str == wxT("h")) ||
115 (str == wxT("l")) || (str == wxT("ll")) ||
116 (str == wxT("L")) || (str == wxT("z")) ||
117 (str == wxT("j")) || (str == wxT("t")) ||
118 (str == wxT("q")));
122 enum eStringParserStates {
123 esNonFormat = 0, // Not in a format string
124 esFormatStart, // Start of a format string
125 esFormat, // Inside a format string
126 esFormatEnd, // Finished reading a format string
127 esInvalidFormat // Invalid (incomplete) format specifier
131 * State machine to extract format specifiers from the string
133 * All format strings will be extracted, regardless whether they are valid or
134 * not. Also '%%' is considered to be special format string which requires no
135 * arguments, thus it will be extracted too (that is because it has to be
136 * converted to '%').
138 static eStringParserStates stringParser[][3] = {
139 /* %-sign, type-char, other */
140 /* esNonFormat */ { esFormatStart, esNonFormat, esNonFormat },
141 /* esFormatStart */ { esFormatEnd, esFormatEnd, esFormat },
142 /* esFormat */ { esInvalidFormat, esFormatEnd, esFormat },
143 /* esFormatEnd */ { esFormatStart, esNonFormat, esNonFormat },
144 /* esInvalidFormat */ { esFormatEnd, esFormatEnd, esFormat }
147 enum eFormatParserStates {
148 efStart = 0, // Format string start
149 efArgIndex, // Argument index
150 efArgIndexEnd, // End of the argument index ('$' sign)
151 efFlagChar, // Flag character
152 efWidth, // Width field
153 efPrecStart, // Precision field start ('.' character)
154 efPrecision, // Precision field
155 efLength, // Length field
156 // The following two are terminal states, they terminate processing
157 efType, // Type character
158 efError // Invalid format specifier
162 * State machine to parse format specifiers
164 * Format specifiers are expected to follow the following structure:
165 * %[argIndex$][Flags][Width][.Precision][Length]<Type>
167 static eFormatParserStates formatParser[][7] = {
168 /* [1-9], '0', flagChar, '.', lengthChar, typeChar, '$' */
169 /* efStart */ { efArgIndex, efFlagChar, efFlagChar, efPrecStart, efLength, efType, efError, },
170 /* efArgIndex */ { efArgIndex, efArgIndex, efError, efPrecStart, efLength, efType, efArgIndexEnd, },
171 /* efArgIndexEnd */ { efWidth, efFlagChar, efFlagChar, efPrecStart, efLength, efType, efError, },
172 /* efFlagChar */ { efWidth, efError, efError, efPrecStart, efLength, efType, efError, },
173 /* efWidth */ { efWidth, efWidth, efError, efPrecStart, efLength, efType, efError, },
174 /* efPrecStart */ { efPrecision, efPrecision, efError, efError, efLength, efType, efError, },
175 /* efPrecision */ { efPrecision, efPrecision, efError, efError, efLength, efType, efError, },
176 /* efLength */ { efError, efError, efError, efError, efLength, efType, efError, }
179 // Forward-declare the specialization for const wxString&, needed by the parser
180 template<> void CFormat::ProcessArgument(FormatList::iterator, const wxString&);
182 void CFormat::Init(const wxString& str)
184 m_formatString = str;
185 m_argIndex = 0;
187 // Extract format-string-like substrings from the input
189 size_t formatStart = 0;
190 eStringParserStates state = esNonFormat;
191 for (size_t pos = 0; pos < str.length(); ++pos) {
192 if (str[pos] == wxT('%')) {
193 state = stringParser[state][0];
194 } else if (isTypeChar(str[pos])) {
195 state = stringParser[state][1];
196 } else {
197 state = stringParser[state][2];
199 switch (state) {
200 case esInvalidFormat:
201 wxFAIL_MSG(wxT("Invalid format specifier: ") + str.Mid(formatStart, pos - formatStart + 1));
202 /* fall through */
203 case esFormatStart:
204 formatStart = pos;
205 break;
206 case esFormatEnd:
208 FormatSpecifier fs;
209 fs.startPos = formatStart;
210 fs.endPos = pos;
211 fs.result = str.Mid(formatStart, pos - formatStart + 1);
212 m_formats.push_back(fs);
214 default:
215 break;
218 wxASSERT_MSG((state == esFormatEnd) || (state == esNonFormat), wxT("Incomplete format specifier: ") + str.Mid(formatStart));
221 // Parse the extracted format specifiers, removing invalid ones
222 unsigned formatCount = 0;
223 for (FormatList::iterator it = m_formats.begin(); it != m_formats.end();) {
224 if (it->result == wxT("%%")) {
225 it->argIndex = 0;
226 it->result = wxT("%");
227 ++it;
228 } else {
229 it->argIndex = ++formatCount;
230 it->flag = '\0';
231 it->width = 0;
232 it->precision = -1;
233 it->type = '\0';
234 unsigned num = 0;
235 wxString lengthModifier;
236 bool isPrecision = false;
237 eFormatParserStates state = efStart;
238 for (size_t pos = 1; pos < it->result.length(); ++pos) {
239 wxChar c = it->result[pos];
240 if ((c >= wxT('1')) && (c <= wxT('9'))) {
241 state = formatParser[state][0];
242 } else if (c == wxT('0')) {
243 state = formatParser[state][1];
244 } else if (isFlagChar(c)) {
245 state = formatParser[state][2];
246 } else if (c == wxT('.')) {
247 state = formatParser[state][3];
248 } else if (isLengthChar(c)) {
249 state = formatParser[state][4];
250 } else if (isTypeChar(c)) {
251 state = formatParser[state][5];
252 } else if (c == wxT('$')) {
253 state = formatParser[state][6];
254 } else {
255 state = efError;
257 if ((c >= wxT('0')) && (c <= wxT('9'))) {
258 num *= 10;
259 num += (c - wxT('0'));
261 switch (state) {
262 case efArgIndexEnd:
263 it->argIndex = num;
264 num = 0;
265 break;
266 case efFlagChar:
267 it->flag = c;
268 break;
269 case efPrecStart:
270 it->width = num;
271 num = 0;
272 isPrecision = true;
273 break;
274 case efLength:
275 if (isPrecision) {
276 it->precision = num;
277 } else if (num > 0) {
278 it->width = num;
280 num = 0;
281 lengthModifier += c;
282 if (!isValidLength(lengthModifier)) {
283 state = efError;
285 break;
286 case efType:
287 if (isPrecision) {
288 it->precision = num;
289 } else if (num > 0) {
290 it->width = num;
292 if (c == wxT('m')) {
293 it->argIndex = 0;
294 it->type = wxT('s');
295 int errnum = errno;
296 #if defined(HAVE_STRERROR) || defined(HAVE_STRERROR_R)
297 unsigned buflen = 256;
298 bool done = false;
299 do {
300 errno = 0;
301 char* buf = new char[buflen];
302 *buf = '\0';
303 int result = mule_strerror_r(errnum, buf, buflen);
304 if ((result == 0) || (buflen > 1024)) {
305 ProcessArgument<const wxString&>(it, wxString(buf, wxConvLocal));
306 } else if (errno == EINVAL) {
307 if (*buf == '\0') {
308 ProcessArgument<const wxString&>(it, wxString::Format(_("Unknown error %d"), errnum));
309 } else {
310 ProcessArgument<const wxString&>(it, wxString(buf, wxConvLocal));
312 } else if (errno != ERANGE) {
313 ProcessArgument<const wxString&>(it, wxString::Format(_("Unable to get error description for error %d"), errnum));
314 } else {
315 buflen <<= 1;
317 delete [] buf;
318 done = ((result == 0) || (errno != ERANGE));
319 } while (!done);
320 #else
321 wxFAIL_MSG(wxString::Format(wxT("Unable to get error description for error %d."), errnum));
322 ProcessArgument<const wxString&>(it, wxString::Format(_("Unable to get error description for error %d"), errnum));
323 #endif
324 } else {
325 it->type = c;
327 default:
328 break;
330 wxCHECK2_MSG(state != efError, break, wxT("Invalid format specifier: ") + it->result);
331 if (state == efType) {
332 // Needed by the '%m' conversion, which takes place immediately,
333 // overwriting it->result
334 break;
337 if (state == efError) {
338 it = m_formats.erase(it);
339 --formatCount;
340 } else {
341 ++it;
347 wxString CFormat::GetString() const
349 wxString result;
350 FormatList::const_iterator it = m_formats.begin();
351 if (it == m_formats.end()) {
352 result = m_formatString;
353 } else {
354 unsigned lastEnd = 0;
355 for (; it != m_formats.end(); ++it) {
356 result += m_formatString.Mid(lastEnd, it->startPos - lastEnd);
357 result += it->result;
358 lastEnd = it->endPos + 1;
360 result += m_formatString.Mid(lastEnd);
362 return result;
365 wxString CFormat::GetModifiers(FormatList::const_iterator it) const
367 wxString result = wxT("%");
368 if (it->flag != wxT('\0')) {
369 result += it->flag;
371 if (it->width > 0) {
372 result += wxString::Format(wxT("%u"), it->width);
374 if (it->precision >= 0) {
375 result += wxString::Format(wxT(".%u"), it->precision);
377 return result;
380 // Forward-declare the specialization for unsigned long long
381 template<> void CFormat::ProcessArgument(FormatList::iterator, unsigned long long);
383 // Processing a double-precision floating-point argument
384 template<>
385 void CFormat::ProcessArgument(FormatList::iterator it, double value)
387 switch (it->type) {
388 case wxT('a'):
389 case wxT('A'):
390 case wxT('e'):
391 case wxT('E'):
392 case wxT('f'):
393 case wxT('F'):
394 case wxT('g'):
395 case wxT('G'):
396 break;
397 case wxT('s'):
398 it->type = wxT('g');
399 break;
400 default:
401 wxFAIL_MSG(wxT("Floating-point value passed for non-floating-point format field: ") + it->result);
402 return;
404 it->result = wxString::Format(GetModifiers(it) + it->type, value);
407 // Processing a wxChar argument
408 template<>
409 void CFormat::ProcessArgument(FormatList::iterator it, wxChar value)
411 switch (it->type) {
412 case wxT('c'):
413 break;
414 case wxT('s'):
415 it->type = wxT('c');
416 break;
417 case wxT('u'):
418 case wxT('d'):
419 case wxT('i'):
420 case wxT('o'):
421 case wxT('x'):
422 case wxT('X'):
423 ProcessArgument(it, (unsigned long long)value);
424 return;
425 case wxT('a'):
426 case wxT('A'):
427 case wxT('e'):
428 case wxT('E'):
429 case wxT('f'):
430 case wxT('F'):
431 case wxT('g'):
432 case wxT('G'):
433 ProcessArgument(it, (double)value);
434 return;
435 default:
436 wxFAIL_MSG(wxT("Character value passed to non-character format field: ") + it->result);
437 return;
439 it->result = wxString::Format(GetModifiers(it) + it->type, value);
442 // Processing a signed long long argument
443 template<>
444 void CFormat::ProcessArgument(FormatList::iterator it, signed long long value)
446 switch (it->type) {
447 case wxT('c'):
448 ProcessArgument(it, (wxChar)value);
449 return;
450 case wxT('i'):
451 break;
452 case wxT('o'):
453 case wxT('x'):
454 case wxT('X'):
455 ProcessArgument(it, (unsigned long long)value);
456 return;
457 case wxT('u'):
458 case wxT('d'):
459 case wxT('s'):
460 it->type = wxT('i');
461 break;
462 case wxT('a'):
463 case wxT('A'):
464 case wxT('e'):
465 case wxT('E'):
466 case wxT('f'):
467 case wxT('F'):
468 case wxT('g'):
469 case wxT('G'):
470 ProcessArgument(it, (double)value);
471 return;
472 default:
473 wxFAIL_MSG(wxT("Integer value passed for non-integer format field: ") + it->result);
474 return;
476 it->result = wxString::Format(GetModifiers(it) + WXLONGLONGFMTSPEC + it->type, value);
479 // Processing an unsigned long long argument
480 template<>
481 void CFormat::ProcessArgument(FormatList::iterator it, unsigned long long value)
483 switch (it->type) {
484 case wxT('c'):
485 ProcessArgument(it, (wxChar)value);
486 return;
487 case wxT('u'):
488 case wxT('o'):
489 case wxT('x'):
490 case wxT('X'):
491 break;
492 case wxT('i'):
493 case wxT('d'):
494 case wxT('s'):
495 it->type = wxT('u');
496 break;
497 case wxT('a'):
498 case wxT('A'):
499 case wxT('e'):
500 case wxT('E'):
501 case wxT('f'):
502 case wxT('F'):
503 case wxT('g'):
504 case wxT('G'):
505 ProcessArgument(it, (double)value);
506 return;
507 default:
508 wxFAIL_MSG(wxT("Integer value passed for non-integer format field: ") + it->result);
509 return;
511 it->result = wxString::Format(GetModifiers(it) + WXLONGLONGFMTSPEC + it->type, value);
514 // Processing a wxString argument
515 template<>
516 void CFormat::ProcessArgument(FormatList::iterator it, const wxString& value)
518 if (it->type != wxT('s')) {
519 wxFAIL_MSG(wxT("String value passed for non-string format field: ") + it->result);
520 } else {
521 if (it->precision >= 0) {
522 it->result = value.Left(it->precision);
523 } else {
524 it->result = value;
526 if ((it->width > 0) && (it->result.length() < it->width)) {
527 if (it->flag == wxT('-')) {
528 it->result += wxString(it->width - it->result.length(), wxT(' '));
529 } else {
530 it->result = wxString(it->width -it->result.length(), wxT(' ')) + it->result;
536 // Processing pointer arguments
537 template<>
538 void CFormat::ProcessArgument(FormatList::iterator it, void * value)
540 if ((it->type == wxT('p')) || (it->type == wxT('s'))) {
541 // Modifiers (if any) are ignored for pointer conversions
542 // built-in Format for pointer is not consistent:
543 // - Windows: uppercase, no leading 0x
544 // - Linux: leading zeros missing
545 // -> format it as hex
546 if (sizeof(void*) == 8) {
547 // 64 bit
548 it->result = wxString::Format(wxString(wxT("0x%016")) + WXLONGLONGFMTSPEC + wxT("x"), (uintptr_t)value);
549 } else {
550 // 32 bit
551 it->result = wxString::Format(wxT("0x%08x"), (uintptr_t)value);
553 } else {
554 wxFAIL_MSG(wxT("Pointer value passed for non-pointer format field: ") + it->result);
559 // Generic argument processor template
560 template<typename _Tp>
561 CFormat& CFormat::operator%(_Tp value)
563 m_argIndex++;
564 for (FormatList::iterator it = m_formats.begin(); it != m_formats.end(); ++it) {
565 if (it->argIndex == m_argIndex) {
566 if ((it->type != wxT('n')) && (it->type != wxT('C')) && (it->type != wxT('S'))) {
567 ProcessArgument<_Tp>(it, value);
568 } else {
569 wxFAIL_MSG(wxT("Not supported conversion type in format field: ") + it->result);
573 return *this;
576 // explicit instatiation for the types we handle
577 template CFormat& CFormat::operator%<double>(double);
578 template CFormat& CFormat::operator%<wxChar>(wxChar);
579 template CFormat& CFormat::operator%<signed long long>(signed long long);
580 template CFormat& CFormat::operator%<unsigned long long>(unsigned long long);
581 template CFormat& CFormat::operator%<const wxString&>(const wxString&);
582 template CFormat& CFormat::operator%<void *>(void *);
584 // File_checked_for_headers