1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/private/wxprintf.h
3 // Purpose: wxWidgets wxPrintf() implementation
5 // Modified by: Ron Lee, Francesco Montorsi
7 // Copyright: (c) wxWidgets copyright
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 #ifndef _WX_PRIVATE_WXPRINTF_H_
12 #define _WX_PRIVATE_WXPRINTF_H_
14 // ---------------------------------------------------------------------------
16 // ---------------------------------------------------------------------------
24 // prefer snprintf over sprintf
25 #if defined(__VISUALC__) || \
26 (defined(__BORLANDC__) && __BORLANDC__ >= 0x540)
27 #define system_sprintf(buff, max, flags, data) \
28 ::_snprintf(buff, max, flags, data)
29 #elif defined(HAVE_SNPRINTF)
30 #define system_sprintf(buff, max, flags, data) \
31 ::snprintf(buff, max, flags, data)
32 #else // NB: at least sprintf() should always be available
33 // since 'max' is not used in this case, wxVsnprintf() should always
34 // ensure that 'buff' is big enough for all common needs
35 // (see wxMAX_SVNPRINTF_FLAGBUFFER_LEN and wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN)
36 #define system_sprintf(buff, max, flags, data) \
37 ::sprintf(buff, flags, data)
39 #define SYSTEM_SPRINTF_IS_UNSAFE
42 // ---------------------------------------------------------------------------
43 // printf format string parsing
44 // ---------------------------------------------------------------------------
46 // some limits of our implementation
47 #define wxMAX_SVNPRINTF_ARGUMENTS 64
48 #define wxMAX_SVNPRINTF_FLAGBUFFER_LEN 32
49 #define wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN 512
52 // the conversion specifiers accepted by wxCRT_VsnprintfW
57 wxPAT_INT
, // %d, %i, %o, %u, %x, %X
58 wxPAT_LONGINT
, // %ld, etc
60 wxPAT_LONGLONGINT
, // %Ld, etc
62 wxPAT_SIZET
, // %zd, etc
64 wxPAT_DOUBLE
, // %e, %E, %f, %g, %G
65 wxPAT_LONGDOUBLE
, // %le, etc
69 wxPAT_CHAR
, // %hc (in ANSI mode: %c, too)
70 wxPAT_WCHAR
, // %lc (in Unicode mode: %c, too)
72 wxPAT_PCHAR
, // %s (related to a char *)
73 wxPAT_PWCHAR
, // %s (related to a wchar_t *)
76 wxPAT_NSHORTINT
, // %hn
77 wxPAT_NLONGINT
, // %ln
79 wxPAT_STAR
// '*' used for width or precision
82 // an argument passed to wxCRT_VsnprintfW
85 int pad_int
; // %d, %i, %o, %u, %x, %X
86 long int pad_longint
; // %ld, etc
88 wxLongLong_t pad_longlongint
; // %Ld, etc
90 size_t pad_sizet
; // %zd, etc
92 double pad_double
; // %e, %E, %f, %g, %G
93 long double pad_longdouble
; // %le, etc
95 void *pad_pointer
; // %p
97 char pad_char
; // %hc (in ANSI mode: %c, too)
98 wchar_t pad_wchar
; // %lc (in Unicode mode: %c, too)
103 short int *pad_nshortint
; // %hn
104 long int *pad_nlongint
; // %ln
107 // helper for converting string into either char* or wchar_t* depending
108 // on the type of wxPrintfConvSpec<T> instantiation:
109 template<typename CharType
> struct wxPrintfStringHelper
{};
111 template<> struct wxPrintfStringHelper
<char>
113 typedef const wxWX2MBbuf ConvertedType
;
114 static ConvertedType
Convert(const wxString
& s
) { return s
.mb_str(); }
117 template<> struct wxPrintfStringHelper
<wchar_t>
119 typedef const wxWX2WCbuf ConvertedType
;
120 static ConvertedType
Convert(const wxString
& s
) { return s
.wc_str(); }
124 // Contains parsed data relative to a conversion specifier given to
125 // wxCRT_VsnprintfW and parsed from the format string
126 // NOTE: in C++ there is almost no difference between struct & classes thus
127 // there is no performance gain by using a struct here...
128 template<typename CharType
>
129 class wxPrintfConvSpec
133 // the position of the argument relative to this conversion specifier
136 // the type of this conversion specifier
137 wxPrintfArgType m_type
;
139 // the minimum and maximum width
140 // when one of this var is set to -1 it means: use the following argument
141 // in the stack as minimum/maximum width for this conversion specifier
142 int m_nMinWidth
, m_nMaxWidth
;
144 // does the argument need to the be aligned to left ?
147 // pointer to the '%' of this conversion specifier in the format string
148 // NOTE: this points somewhere in the string given to the Parse() function -
149 // it's task of the caller ensure that memory is still valid !
150 const CharType
*m_pArgPos
;
152 // pointer to the last character of this conversion specifier in the
154 // NOTE: this points somewhere in the string given to the Parse() function -
155 // it's task of the caller ensure that memory is still valid !
156 const CharType
*m_pArgEnd
;
158 // a little buffer where formatting flags like #+\.hlqLz are stored by Parse()
159 // for use in Process()
160 char m_szFlags
[wxMAX_SVNPRINTF_FLAGBUFFER_LEN
];
165 // we don't declare this as a constructor otherwise it would be called
166 // automatically and we don't want this: to be optimized, wxCRT_VsnprintfW
167 // calls this function only on really-used instances of this class.
170 // Parses the first conversion specifier in the given string, which must
171 // begin with a '%'. Returns false if the first '%' does not introduce a
172 // (valid) conversion specifier and thus should be ignored.
173 bool Parse(const CharType
*format
);
175 // Process this conversion specifier and puts the result in the given
176 // buffer. Returns the number of characters written in 'buf' or -1 if
177 // there's not enough space.
178 int Process(CharType
*buf
, size_t lenMax
, wxPrintfArg
*p
, size_t written
);
180 // Loads the argument of this conversion specifier from given va_list.
181 bool LoadArg(wxPrintfArg
*p
, va_list &argptr
);
184 // An helper function of LoadArg() which is used to handle the '*' flag
185 void ReplaceAsteriskWith(int w
);
188 template<typename CharType
>
189 void wxPrintfConvSpec
<CharType
>::Init()
192 m_nMaxWidth
= 0xFFFF;
194 m_bAlignLeft
= false;
195 m_pArgPos
= m_pArgEnd
= NULL
;
196 m_type
= wxPAT_INVALID
;
198 memset(m_szFlags
, 0, sizeof(m_szFlags
));
199 // this character will never be removed from m_szFlags array and
200 // is important when calling sprintf() in wxPrintfConvSpec::Process() !
204 template<typename CharType
>
205 bool wxPrintfConvSpec
<CharType
>::Parse(const CharType
*format
)
209 // temporary parse data
211 bool in_prec
, // true if we found the dot in some previous iteration
212 prec_dot
; // true if the dot has been already added to m_szFlags
215 m_bAlignLeft
= in_prec
= prec_dot
= false;
216 m_pArgPos
= m_pArgEnd
= format
;
220 if (in_prec && !prec_dot) \
222 m_szFlags[flagofs++] = '.'; \
227 const CharType ch
= *(++m_pArgEnd
);
231 return false; // not really an argument
234 return false; // not really an argument
242 m_szFlags
[flagofs
++] = char(ch
);
248 m_szFlags
[flagofs
++] = char(ch
);
252 // don't use CHECK_PREC here to avoid warning about the value
253 // assigned to prec_dot inside it being never used (because
254 // overwritten just below) from Borland in release build
255 if (in_prec
&& !prec_dot
)
256 m_szFlags
[flagofs
++] = '.';
260 // dot will be auto-added to m_szFlags if non-negative
267 m_szFlags
[flagofs
++] = char(ch
);
271 // NB: it's safe to use flagofs-1 as flagofs always start from 1
272 if (m_szFlags
[flagofs
-1] == 'l') // 'll' modifier is the same as 'L' or 'q'
277 m_szFlags
[flagofs
++] = char(ch
);
284 m_szFlags
[flagofs
++] = char(ch
);
287 // under Windows we support the special '%I64' notation as longlong
288 // integer conversion specifier for MSVC compatibility
289 // (it behaves exactly as '%lli' or '%Li' or '%qi')
291 if (*(m_pArgEnd
+1) == wxT('6') &&
292 *(m_pArgEnd
+2) == wxT('4'))
299 m_szFlags
[flagofs
++] = char(ch
);
300 m_szFlags
[flagofs
++] = '6';
301 m_szFlags
[flagofs
++] = '4';
304 // else: fall-through, 'I' is MSVC equivalent of C99 'z'
305 #endif // __WINDOWS__
309 // 'z' is C99 standard for size_t and ptrdiff_t, 'Z' was used
310 // for this purpose in libc5 and by wx <= 2.8
313 m_szFlags
[flagofs
++] = char(ch
);
321 // tell Process() to use the next argument
322 // in the stack as maxwidth...
327 // tell Process() to use the next argument
328 // in the stack as minwidth...
332 // save the * in our formatting buffer...
333 // will be replaced later by Process()
334 m_szFlags
[flagofs
++] = char(ch
);
337 case wxT('1'): case wxT('2'): case wxT('3'):
338 case wxT('4'): case wxT('5'): case wxT('6'):
339 case wxT('7'): case wxT('8'): case wxT('9'):
343 while ( (*m_pArgEnd
>= CharType('0')) &&
344 (*m_pArgEnd
<= CharType('9')) )
346 m_szFlags
[flagofs
++] = char(*m_pArgEnd
);
347 len
= len
*10 + (*m_pArgEnd
- wxT('0'));
356 m_pArgEnd
--; // the main loop pre-increments n again
360 case wxT('$'): // a positional parameter (e.g. %2$s) ?
362 if (m_nMinWidth
<= 0)
363 break; // ignore this formatting flag as no
364 // numbers are preceding it
366 // remove from m_szFlags all digits previously added
369 } while (m_szFlags
[flagofs
] >= '1' &&
370 m_szFlags
[flagofs
] <= '9');
372 // re-adjust the offset making it point to the
373 // next free char of m_szFlags
388 m_szFlags
[flagofs
++] = char(ch
);
392 // NB: 'short int' value passed through '...'
393 // is promoted to 'int', so we have to get
394 // an int from stack even if we need a short
397 m_type
= wxPAT_LONGINT
;
400 m_type
= wxPAT_LONGLONGINT
;
401 #else // !wxLongLong_t
402 m_type
= wxPAT_LONGINT
;
403 #endif // wxLongLong_t/!wxLongLong_t
405 m_type
= wxPAT_SIZET
;
415 m_szFlags
[flagofs
++] = char(ch
);
417 m_type
= wxPAT_LONGDOUBLE
;
419 m_type
= wxPAT_DOUBLE
;
424 m_type
= wxPAT_POINTER
;
425 m_szFlags
[flagofs
++] = char(ch
);
432 // in Unicode mode %hc == ANSI character
433 // and in ANSI mode, %hc == %c == ANSI...
438 // in ANSI mode %lc == Unicode character
439 // and in Unicode mode, %lc == %c == Unicode...
440 m_type
= wxPAT_WCHAR
;
445 // in Unicode mode, %c == Unicode character
446 m_type
= wxPAT_WCHAR
;
448 // in ANSI mode, %c == ANSI character
458 // Unicode mode wx extension: we'll let %hs mean non-Unicode
459 // strings (when in ANSI mode, %s == %hs == ANSI string)
460 m_type
= wxPAT_PCHAR
;
464 // in Unicode mode, %ls == %s == Unicode string
465 // in ANSI mode, %ls == Unicode string
466 m_type
= wxPAT_PWCHAR
;
471 m_type
= wxPAT_PWCHAR
;
473 m_type
= wxPAT_PCHAR
;
483 m_type
= wxPAT_NSHORTINT
;
485 m_type
= wxPAT_NLONGINT
;
490 // bad format, don't consider this an argument;
491 // leave it unchanged
495 if (flagofs
== wxMAX_SVNPRINTF_FLAGBUFFER_LEN
)
497 wxLogDebug(wxT("Too many flags specified for a single conversion specifier!"));
503 return true; // parsing was successful
506 template<typename CharType
>
507 void wxPrintfConvSpec
<CharType
>::ReplaceAsteriskWith(int width
)
509 char temp
[wxMAX_SVNPRINTF_FLAGBUFFER_LEN
];
511 // find the first * in our flag buffer
512 char *pwidth
= strchr(m_szFlags
, '*');
513 wxCHECK_RET(pwidth
, wxT("field width must be specified"));
515 // save what follows the * (the +1 is to skip the asterisk itself!)
516 strcpy(temp
, pwidth
+1);
519 pwidth
[0] = wxT('-');
523 // replace * with the actual integer given as width
524 #ifndef SYSTEM_SPRINTF_IS_UNSAFE
525 int maxlen
= (m_szFlags
+ wxMAX_SVNPRINTF_FLAGBUFFER_LEN
- pwidth
) /
528 int offset
= system_sprintf(pwidth
, maxlen
, "%d", abs(width
));
530 // restore after the expanded * what was following it
531 strcpy(pwidth
+offset
, temp
);
534 template<typename CharType
>
535 bool wxPrintfConvSpec
<CharType
>::LoadArg(wxPrintfArg
*p
, va_list &argptr
)
537 // did the '*' width/precision specifier was used ?
538 if (m_nMaxWidth
== -1)
540 // take the maxwidth specifier from the stack
541 m_nMaxWidth
= va_arg(argptr
, int);
545 ReplaceAsteriskWith(m_nMaxWidth
);
548 if (m_nMinWidth
== -1)
550 // take the minwidth specifier from the stack
551 m_nMinWidth
= va_arg(argptr
, int);
553 ReplaceAsteriskWith(m_nMinWidth
);
556 m_bAlignLeft
= !m_bAlignLeft
;
557 m_nMinWidth
= -m_nMinWidth
;
563 p
->pad_int
= va_arg(argptr
, int);
566 p
->pad_longint
= va_arg(argptr
, long int);
569 case wxPAT_LONGLONGINT
:
570 p
->pad_longlongint
= va_arg(argptr
, wxLongLong_t
);
572 #endif // wxLongLong_t
574 p
->pad_sizet
= va_arg(argptr
, size_t);
577 p
->pad_double
= va_arg(argptr
, double);
579 case wxPAT_LONGDOUBLE
:
580 p
->pad_longdouble
= va_arg(argptr
, long double);
583 p
->pad_pointer
= va_arg(argptr
, void *);
587 p
->pad_char
= (char)va_arg(argptr
, int); // char is promoted to int when passed through '...'
590 p
->pad_wchar
= (wchar_t)va_arg(argptr
, int); // char is promoted to int when passed through '...'
595 p
->pad_str
= va_arg(argptr
, void *);
599 p
->pad_nint
= va_arg(argptr
, int *);
601 case wxPAT_NSHORTINT
:
602 p
->pad_nshortint
= va_arg(argptr
, short int *);
605 p
->pad_nlongint
= va_arg(argptr
, long int *);
609 // this will be handled as part of the next argument
617 return true; // loading was successful
620 template<typename CharType
>
621 int wxPrintfConvSpec
<CharType
>::Process(CharType
*buf
, size_t lenMax
, wxPrintfArg
*p
, size_t written
)
623 // buffer to avoid dynamic memory allocation each time for small strings;
624 // note that this buffer is used only to hold results of number formatting,
625 // %s directly writes user's string in buf, without using szScratch
626 char szScratch
[wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
];
627 size_t lenScratch
= 0, lenCur
= 0;
629 #define APPEND_CH(ch) \
631 if ( lenCur == lenMax ) \
634 buf[lenCur++] = ch; \
640 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_int
);
644 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_longint
);
648 case wxPAT_LONGLONGINT
:
649 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_longlongint
);
651 #endif // SIZEOF_LONG_LONG
654 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_sizet
);
657 case wxPAT_LONGDOUBLE
:
658 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_longdouble
);
662 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_double
);
666 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_pointer
);
673 if (m_type
== wxPAT_CHAR
)
675 else // m_type == wxPAT_WCHAR
683 for (i
= 1; i
< (size_t)m_nMinWidth
; i
++)
689 for (i
= 1; i
< (size_t)m_nMinWidth
; i
++)
700 if ( m_nMaxWidth
>= 6 )
703 else if (m_type
== wxPAT_PCHAR
)
704 s
.assign(static_cast<const char *>(p
->pad_str
));
705 else // m_type == wxPAT_PWCHAR
706 s
.assign(static_cast<const wchar_t *>(p
->pad_str
));
708 typename wxPrintfStringHelper
<CharType
>::ConvertedType
strbuf(
709 wxPrintfStringHelper
<CharType
>::Convert(s
));
711 // at this point we are sure that m_nMaxWidth is positive or
712 // null (see top of wxPrintfConvSpec::LoadArg)
713 int len
= wxMin((unsigned int)m_nMaxWidth
, wxStrlen(strbuf
));
719 for (i
= len
; i
< m_nMinWidth
; i
++)
723 len
= wxMin((unsigned int)len
, lenMax
-lenCur
);
724 wxStrncpy(buf
+lenCur
, strbuf
, len
);
729 for (i
= len
; i
< m_nMinWidth
; i
++)
736 *p
->pad_nint
= written
;
739 case wxPAT_NSHORTINT
:
740 *p
->pad_nshortint
= (short int)written
;
744 *p
->pad_nlongint
= written
;
752 // if we used system's sprintf() then we now need to append the s_szScratch
753 // buffer to the given one...
759 case wxPAT_LONGLONGINT
:
762 case wxPAT_LONGDOUBLE
:
765 wxASSERT(lenScratch
< wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
);
766 // NB: 1) we can compare lenMax (for CharType*, i.e. possibly
767 // wchar_t*) with lenScratch (char*) because this code is
768 // formatting integers and that will have the same length
769 // even in UTF-8 (the only case when char* length may be
770 // more than wchar_t* length of the same string)
771 // 2) wxStrncpy converts the 2nd argument to 1st argument's
772 // type transparently if their types differ, so this code
773 // works for both instantiations
774 if (lenMax
< lenScratch
)
776 // fill output buffer and then return -1
777 wxStrncpy(buf
, szScratch
, lenMax
);
780 wxStrncpy(buf
, szScratch
, lenScratch
);
781 lenCur
+= lenScratch
;
785 break; // all other cases were completed previously
792 // helper that parses format string
793 template<typename CharType
>
794 struct wxPrintfConvSpecParser
796 typedef wxPrintfConvSpec
<CharType
> ConvSpec
;
798 wxPrintfConvSpecParser(const CharType
*fmt
)
802 nonposarg_present
= false;
804 memset(pspec
, 0, sizeof(pspec
));
806 // parse the format string
807 for ( const CharType
*toparse
= fmt
; *toparse
!= wxT('\0'); toparse
++ )
809 // skip everything except format specifications
810 if ( *toparse
!= '%' )
813 // also skip escaped percent signs
814 if ( toparse
[1] == '%' )
820 ConvSpec
*spec
= &specs
[nargs
];
823 // attempt to parse this format specification
824 if ( !spec
->Parse(toparse
) )
827 // advance to the end of this specifier
828 toparse
= spec
->m_pArgEnd
;
830 // special handling for specifications including asterisks: we need
831 // to reserve an extra slot (or two if asterisks were used for both
832 // width and precision) in specs array in this case
833 if ( const char *f
= strchr(spec
->m_szFlags
, '*') )
835 unsigned numAsterisks
= 1;
836 if ( strchr(++f
, '*') )
839 for ( unsigned n
= 0; n
< numAsterisks
; n
++ )
841 if ( nargs
++ == wxMAX_SVNPRINTF_ARGUMENTS
)
844 // TODO: we need to support specifiers of the form "%2$*1$s"
845 // (this is the same as "%*s") as if any positional arguments
846 // are used all asterisks must be positional as well but this
847 // requires a lot of changes in this code (basically we'd need
848 // to rewrite Parse() to return "*" and conversion itself as
850 if ( posarg_present
)
856 "Format string \"%s\" uses both positional "
857 "parameters and '*' but this is not currently "
858 "supported by this implementation, sorry.",
864 specs
[nargs
] = *spec
;
866 // make an entry for '*' and point to it from pspec
868 spec
->m_type
= wxPAT_STAR
;
869 pspec
[nargs
- 1] = spec
;
871 spec
= &specs
[nargs
];
876 // check if this is a positional or normal argument
877 if ( spec
->m_pos
> 0 )
879 // the positional arguments start from number 1 so we need
880 // to adjust the index
882 posarg_present
= true;
884 else // not a positional argument...
887 nonposarg_present
= true;
890 // this conversion specifier is tied to the pos-th argument...
891 pspec
[spec
->m_pos
] = spec
;
893 if ( nargs
++ == wxMAX_SVNPRINTF_ARGUMENTS
)
898 // warn if we lost any arguments (the program probably will crash
899 // anyhow because of stack corruption...)
900 if ( nargs
== wxMAX_SVNPRINTF_ARGUMENTS
)
906 "wxVsnprintf() currently supports only %d arguments, "
907 "but format string \"%s\" defines more of them.\n"
908 "You need to change wxMAX_SVNPRINTF_ARGUMENTS and "
909 "recompile if more are really needed.",
910 fmt
, wxMAX_SVNPRINTF_ARGUMENTS
916 // total number of valid elements in specs
919 // all format specifications in this format string in order of their
920 // appearance (which may be different from arguments order)
921 ConvSpec specs
[wxMAX_SVNPRINTF_ARGUMENTS
];
923 // pointer to specs array element for the N-th argument
924 ConvSpec
*pspec
[wxMAX_SVNPRINTF_ARGUMENTS
];
926 // true if any positional/non-positional parameters are used
934 #endif // _WX_PRIVATE_WXPRINTF_H_