2 // This file is part of the aMule Project.
4 // Copyright (c) 2005-2011 aMule Team ( admin@amule.org / http://www.amule.org )
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
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
31 #if defined HAVE_STDINT_H
33 #elif defined HAVE_INTTYPES_H
34 # include <inttypes.h>
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
)
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 `%%'.
74 /** Returns true if the char is a valid flag. */
75 inline bool isFlagChar(wxChar c
)
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
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.
87 case wxT('I'): // For decimal integer conversion (i, d, u) the output uses the locale's alternative output digits, if any.
94 /** Returns true if the char is a valid length modifier. */
95 inline bool isLengthChar(wxChar 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.
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")) ||
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
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
;
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];
197 state
= stringParser
[state
][2];
200 case esInvalidFormat
:
201 wxFAIL_MSG(wxT("Invalid format specifier: ") + str
.Mid(formatStart
, pos
- formatStart
+ 1));
209 fs
.startPos
= formatStart
;
211 fs
.result
= str
.Mid(formatStart
, pos
- formatStart
+ 1);
212 m_formats
.push_back(fs
);
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("%%")) {
226 it
->result
= wxT("%");
229 it
->argIndex
= ++formatCount
;
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];
257 if ((c
>= wxT('0')) && (c
<= wxT('9'))) {
259 num
+= (c
- wxT('0'));
277 } else if (num
> 0) {
282 if (!isValidLength(lengthModifier
)) {
289 } else if (num
> 0) {
296 #if defined(HAVE_STRERROR) || defined(HAVE_STRERROR_R)
297 unsigned buflen
= 256;
301 char* buf
= new char[buflen
];
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
) {
308 ProcessArgument
<const wxString
&>(it
, wxString::Format(_("Unknown error %d"), errnum
));
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
));
318 done
= ((result
== 0) || (errno
!= ERANGE
));
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
));
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
337 if (state
== efError
) {
338 it
= m_formats
.erase(it
);
347 wxString
CFormat::GetString() const
350 FormatList::const_iterator it
= m_formats
.begin();
351 if (it
== m_formats
.end()) {
352 result
= m_formatString
;
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
);
365 wxString
CFormat::GetModifiers(FormatList::const_iterator it
) const
367 wxString result
= wxT("%");
368 if (it
->flag
!= wxT('\0')) {
372 result
+= wxString::Format(wxT("%u"), it
->width
);
374 if (it
->precision
>= 0) {
375 result
+= wxString::Format(wxT(".%u"), it
->precision
);
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
385 void CFormat::ProcessArgument(FormatList::iterator it
, double value
)
401 wxFAIL_MSG(wxT("Floating-point value passed for non-floating-point format field: ") + it
->result
);
404 it
->result
= wxString::Format(GetModifiers(it
) + it
->type
, value
);
407 // Processing a wxChar argument
409 void CFormat::ProcessArgument(FormatList::iterator it
, wxChar value
)
423 ProcessArgument(it
, (unsigned long long)value
);
433 ProcessArgument(it
, (double)value
);
436 wxFAIL_MSG(wxT("Character value passed to non-character format field: ") + it
->result
);
439 it
->result
= wxString::Format(GetModifiers(it
) + it
->type
, value
);
442 // Processing a signed long long argument
444 void CFormat::ProcessArgument(FormatList::iterator it
, signed long long value
)
448 ProcessArgument(it
, (wxChar
)value
);
455 ProcessArgument(it
, (unsigned long long)value
);
470 ProcessArgument(it
, (double)value
);
473 wxFAIL_MSG(wxT("Integer value passed for non-integer format field: ") + it
->result
);
476 it
->result
= wxString::Format(GetModifiers(it
) + WXLONGLONGFMTSPEC
+ it
->type
, value
);
479 // Processing an unsigned long long argument
481 void CFormat::ProcessArgument(FormatList::iterator it
, unsigned long long value
)
485 ProcessArgument(it
, (wxChar
)value
);
505 ProcessArgument(it
, (double)value
);
508 wxFAIL_MSG(wxT("Integer value passed for non-integer format field: ") + it
->result
);
511 it
->result
= wxString::Format(GetModifiers(it
) + WXLONGLONGFMTSPEC
+ it
->type
, value
);
514 // Processing a wxString argument
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
);
521 if (it
->precision
>= 0) {
522 it
->result
= value
.Left(it
->precision
);
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(' '));
530 it
->result
= wxString(it
->width
-it
->result
.length(), wxT(' ')) + it
->result
;
536 // Processing pointer arguments
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) {
548 it
->result
= wxString::Format(wxString(wxT("0x%016")) + WXLONGLONGFMTSPEC
+ wxT("x"), (uintptr_t)value
);
551 it
->result
= wxString::Format(wxT("0x%08x"), (uintptr_t)value
);
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
)
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
);
569 wxFAIL_MSG(wxT("Not supported conversion type in format field: ") + it
->result
);
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