1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/private/wxprintf.h
3 // Purpose: wxWidgets wxPrintf() implementation
5 // Modified by: Ron Lee, Francesco Montorsi
8 // Copyright: (c) wxWidgets copyright
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #ifndef _WX_PRIVATE_WXPRINTF_H_
13 #define _WX_PRIVATE_WXPRINTF_H_
15 // ---------------------------------------------------------------------------
17 // ---------------------------------------------------------------------------
25 #if defined(__MWERKS__) && __MSL__ >= 0x6000
30 // prefer snprintf over sprintf
31 #if defined(__VISUALC__) || \
32 (defined(__BORLANDC__) && __BORLANDC__ >= 0x540)
33 #define system_sprintf(buff, max, flags, data) \
34 ::_snprintf(buff, max, flags, data)
35 #elif defined(HAVE_SNPRINTF)
36 #define system_sprintf(buff, max, flags, data) \
37 ::snprintf(buff, max, flags, data)
38 #else // NB: at least sprintf() should always be available
39 // since 'max' is not used in this case, wxVsnprintf() should always
40 // ensure that 'buff' is big enough for all common needs
41 // (see wxMAX_SVNPRINTF_FLAGBUFFER_LEN and wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN)
42 #define system_sprintf(buff, max, flags, data) \
43 ::sprintf(buff, flags, data)
45 #define SYSTEM_SPRINTF_IS_UNSAFE
48 // ---------------------------------------------------------------------------
49 // printf format string parsing
50 // ---------------------------------------------------------------------------
52 // some limits of our implementation
53 #define wxMAX_SVNPRINTF_ARGUMENTS 64
54 #define wxMAX_SVNPRINTF_FLAGBUFFER_LEN 32
55 #define wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN 512
58 // the conversion specifiers accepted by wxCRT_VsnprintfW
59 enum wxPrintfArgType
{
62 wxPAT_INT
, // %d, %i, %o, %u, %x, %X
63 wxPAT_LONGINT
, // %ld, etc
65 wxPAT_LONGLONGINT
, // %Ld, etc
67 wxPAT_SIZET
, // %Zd, etc
69 wxPAT_DOUBLE
, // %e, %E, %f, %g, %G
70 wxPAT_LONGDOUBLE
, // %le, etc
74 wxPAT_CHAR
, // %hc (in ANSI mode: %c, too)
75 wxPAT_WCHAR
, // %lc (in Unicode mode: %c, too)
77 wxPAT_PCHAR
, // %s (related to a char *)
78 wxPAT_PWCHAR
, // %s (related to a wchar_t *)
81 wxPAT_NSHORTINT
, // %hn
85 // an argument passed to wxCRT_VsnprintfW
87 int pad_int
; // %d, %i, %o, %u, %x, %X
88 long int pad_longint
; // %ld, etc
90 wxLongLong_t pad_longlongint
; // %Ld, etc
92 size_t pad_sizet
; // %Zd, etc
94 double pad_double
; // %e, %E, %f, %g, %G
95 long double pad_longdouble
; // %le, etc
97 void *pad_pointer
; // %p
99 char pad_char
; // %hc (in ANSI mode: %c, too)
100 wchar_t pad_wchar
; // %lc (in Unicode mode: %c, too)
105 short int *pad_nshortint
; // %hn
106 long int *pad_nlongint
; // %ln
109 // helper for converting string into either char* or wchar_t* dependening
110 // on the type of wxPrintfConvSpec<T> instantiation:
111 template<typename CharType
> struct wxPrintfStringHelper
{};
113 template<> struct wxPrintfStringHelper
<char>
115 typedef const wxWX2MBbuf ConvertedType
;
116 static ConvertedType
Convert(const wxString
& s
) { return s
.mb_str(); }
119 template<> struct wxPrintfStringHelper
<wchar_t>
121 typedef const wxWX2WCbuf ConvertedType
;
122 static ConvertedType
Convert(const wxString
& s
) { return s
.wc_str(); }
126 // Contains parsed data relative to a conversion specifier given to
127 // wxCRT_VsnprintfW and parsed from the format string
128 // NOTE: in C++ there is almost no difference between struct & classes thus
129 // there is no performance gain by using a struct here...
130 template<typename CharType
>
131 class wxPrintfConvSpec
135 // the position of the argument relative to this conversion specifier
138 // the type of this conversion specifier
139 wxPrintfArgType m_type
;
141 // the minimum and maximum width
142 // when one of this var is set to -1 it means: use the following argument
143 // in the stack as minimum/maximum width for this conversion specifier
144 int m_nMinWidth
, m_nMaxWidth
;
146 // does the argument need to the be aligned to left ?
149 // pointer to the '%' of this conversion specifier in the format string
150 // NOTE: this points somewhere in the string given to the Parse() function -
151 // it's task of the caller ensure that memory is still valid !
152 const CharType
*m_pArgPos
;
154 // pointer to the last character of this conversion specifier in the
156 // NOTE: this points somewhere in the string given to the Parse() function -
157 // it's task of the caller ensure that memory is still valid !
158 const CharType
*m_pArgEnd
;
160 // a little buffer where formatting flags like #+\.hlqLZ are stored by Parse()
161 // for use in Process()
162 // NB: even if this buffer is used only for numeric conversion specifiers
163 // and thus could be safely declared as a char[] buffer, we want it to
164 // be wchar_t so that in Unicode builds we can avoid to convert its
165 // contents to Unicode chars when copying it in user's buffer.
166 char m_szFlags
[wxMAX_SVNPRINTF_FLAGBUFFER_LEN
];
171 // we don't declare this as a constructor otherwise it would be called
172 // automatically and we don't want this: to be optimized, wxCRT_VsnprintfW
173 // calls this function only on really-used instances of this class.
176 // Parses the first conversion specifier in the given string, which must
177 // begin with a '%'. Returns false if the first '%' does not introduce a
178 // (valid) conversion specifier and thus should be ignored.
179 bool Parse(const CharType
*format
);
181 // Process this conversion specifier and puts the result in the given
182 // buffer. Returns the number of characters written in 'buf' or -1 if
183 // there's not enough space.
184 int Process(CharType
*buf
, size_t lenMax
, wxPrintfArg
*p
, size_t written
);
186 // Loads the argument of this conversion specifier from given va_list.
187 bool LoadArg(wxPrintfArg
*p
, va_list &argptr
);
190 // An helper function of LoadArg() which is used to handle the '*' flag
191 void ReplaceAsteriskWith(int w
);
194 template<typename CharType
>
195 void wxPrintfConvSpec
<CharType
>::Init()
198 m_nMaxWidth
= 0xFFFF;
200 m_bAlignLeft
= false;
201 m_pArgPos
= m_pArgEnd
= NULL
;
202 m_type
= wxPAT_INVALID
;
204 // this character will never be removed from m_szFlags array and
205 // is important when calling sprintf() in wxPrintfConvSpec::Process() !
209 template<typename CharType
>
210 bool wxPrintfConvSpec
<CharType
>::Parse(const CharType
*format
)
214 // temporary parse data
216 bool in_prec
, // true if we found the dot in some previous iteration
217 prec_dot
; // true if the dot has been already added to m_szFlags
220 m_bAlignLeft
= in_prec
= prec_dot
= false;
221 m_pArgPos
= m_pArgEnd
= format
;
225 if (in_prec && !prec_dot) \
227 m_szFlags[flagofs++] = '.'; \
232 const CharType ch
= *(++m_pArgEnd
);
236 return false; // not really an argument
239 return false; // not really an argument
247 m_szFlags
[flagofs
++] = char(ch
);
253 m_szFlags
[flagofs
++] = char(ch
);
261 // dot will be auto-added to m_szFlags if non-negative
268 m_szFlags
[flagofs
++] = char(ch
);
272 // NB: it's safe to use flagofs-1 as flagofs always start from 1
273 if (m_szFlags
[flagofs
-1] == 'l') // 'll' modifier is the same as 'L' or 'q'
278 m_szFlags
[flagofs
++] = char(ch
);
285 m_szFlags
[flagofs
++] = char(ch
);
288 // under Windows we support the special '%I64' notation as longlong
289 // integer conversion specifier for MSVC compatibility
290 // (it behaves exactly as '%lli' or '%Li' or '%qi')
292 if (*(m_pArgEnd
+1) != wxT('6') ||
293 *(m_pArgEnd
+2) != wxT('4'))
294 return false; // bad format
301 m_szFlags
[flagofs
++] = char(ch
);
302 m_szFlags
[flagofs
++] = '6';
303 m_szFlags
[flagofs
++] = '4';
310 m_szFlags
[flagofs
++] = char(ch
);
318 // tell Process() to use the next argument
319 // in the stack as maxwidth...
324 // tell Process() to use the next argument
325 // in the stack as minwidth...
329 // save the * in our formatting buffer...
330 // will be replaced later by Process()
331 m_szFlags
[flagofs
++] = char(ch
);
334 case wxT('1'): case wxT('2'): case wxT('3'):
335 case wxT('4'): case wxT('5'): case wxT('6'):
336 case wxT('7'): case wxT('8'): case wxT('9'):
340 while ( (*m_pArgEnd
>= CharType('0')) &&
341 (*m_pArgEnd
<= CharType('9')) )
343 m_szFlags
[flagofs
++] = char(*m_pArgEnd
);
344 len
= len
*10 + (*m_pArgEnd
- wxT('0'));
353 m_pArgEnd
--; // the main loop pre-increments n again
357 case wxT('$'): // a positional parameter (e.g. %2$s) ?
359 if (m_nMinWidth
<= 0)
360 break; // ignore this formatting flag as no
361 // numbers are preceding it
363 // remove from m_szFlags all digits previously added
366 } while (m_szFlags
[flagofs
] >= '1' &&
367 m_szFlags
[flagofs
] <= '9');
369 // re-adjust the offset making it point to the
370 // next free char of m_szFlags
385 m_szFlags
[flagofs
++] = char(ch
);
386 m_szFlags
[flagofs
] = '\0';
390 // NB: 'short int' value passed through '...'
391 // is promoted to 'int', so we have to get
392 // an int from stack even if we need a short
395 m_type
= wxPAT_LONGINT
;
398 m_type
= wxPAT_LONGLONGINT
;
399 #else // !wxLongLong_t
400 m_type
= wxPAT_LONGINT
;
401 #endif // wxLongLong_t/!wxLongLong_t
403 m_type
= wxPAT_SIZET
;
413 m_szFlags
[flagofs
++] = char(ch
);
414 m_szFlags
[flagofs
] = '\0';
416 m_type
= wxPAT_LONGDOUBLE
;
418 m_type
= wxPAT_DOUBLE
;
423 m_type
= wxPAT_POINTER
;
424 m_szFlags
[flagofs
++] = char(ch
);
425 m_szFlags
[flagofs
] = '\0';
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
, _T("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 *);
613 return true; // loading was successful
616 template<typename CharType
>
617 int wxPrintfConvSpec
<CharType
>::Process(CharType
*buf
, size_t lenMax
, wxPrintfArg
*p
, size_t written
)
619 // buffer to avoid dynamic memory allocation each time for small strings;
620 // note that this buffer is used only to hold results of number formatting,
621 // %s directly writes user's string in buf, without using szScratch
622 char szScratch
[wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
];
623 size_t lenScratch
= 0, lenCur
= 0;
625 #define APPEND_CH(ch) \
627 if ( lenCur == lenMax ) \
630 buf[lenCur++] = ch; \
636 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_int
);
640 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_longint
);
644 case wxPAT_LONGLONGINT
:
645 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_longlongint
);
647 #endif // SIZEOF_LONG_LONG
650 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_sizet
);
653 case wxPAT_LONGDOUBLE
:
654 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_longdouble
);
658 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_double
);
662 lenScratch
= system_sprintf(szScratch
, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
, m_szFlags
, p
->pad_pointer
);
669 if (m_type
== wxPAT_CHAR
)
671 else // m_type == wxPAT_WCHAR
679 for (i
= 1; i
< (size_t)m_nMinWidth
; i
++)
685 for (i
= 1; i
< (size_t)m_nMinWidth
; i
++)
693 wxArgNormalizedString
arg(p
->pad_str
);
696 if ( !arg
.IsValid() && m_nMaxWidth
>= 6 )
699 typename wxPrintfStringHelper
<CharType
>::ConvertedType
strbuf(
700 wxPrintfStringHelper
<CharType
>::Convert(s
));
702 // at this point we are sure that m_nMaxWidth is positive or
703 // null (see top of wxPrintfConvSpec::LoadArg)
704 int len
= wxMin((unsigned int)m_nMaxWidth
, wxStrlen(strbuf
));
710 for (i
= len
; i
< m_nMinWidth
; i
++)
714 len
= wxMin((unsigned int)len
, lenMax
-lenCur
);
715 wxStrncpy(buf
+lenCur
, strbuf
, len
);
720 for (i
= len
; i
< m_nMinWidth
; i
++)
727 *p
->pad_nint
= written
;
730 case wxPAT_NSHORTINT
:
731 *p
->pad_nshortint
= (short int)written
;
735 *p
->pad_nlongint
= written
;
743 // if we used system's sprintf() then we now need to append the s_szScratch
744 // buffer to the given one...
750 case wxPAT_LONGLONGINT
:
753 case wxPAT_LONGDOUBLE
:
756 wxASSERT(lenScratch
< wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN
);
757 // NB: 1) we can compare lenMax (for CharType*, i.e. possibly
758 // wchar_t*) with lenScratch (char*) because this code is
759 // formatting integers and that will have the same length
760 // even in UTF-8 (the only case when char* length may be
761 // more than wchar_t* length of the same string)
762 // 2) wxStrncpy converts the 2nd argument to 1st argument's
763 // type transparently if their types differ, so this code
764 // works for both instantiations
765 if (lenMax
< lenScratch
)
767 // fill output buffer and then return -1
768 wxStrncpy(buf
, szScratch
, lenMax
);
771 wxStrncpy(buf
, szScratch
, lenScratch
);
772 lenCur
+= lenScratch
;
776 break; // all other cases were completed previously
783 // helper that parses format string
784 template<typename CharType
>
785 struct wxPrintfConvSpecParser
787 wxPrintfConvSpecParser(const CharType
*format
)
788 : posarg_present(false), nonposarg_present(false),
791 memset(pspec
, 0, sizeof(pspec
));
793 const CharType
*toparse
= format
;
795 // parse the format string
796 for (; *toparse
!= wxT('\0'); toparse
++)
798 if (*toparse
== wxT('%') )
802 // let's see if this is a (valid) conversion specifier...
803 if (arg
[nargs
].Parse(toparse
))
806 wxPrintfConvSpec
<CharType
> *current
= &arg
[nargs
];
808 // make toparse point to the end of this specifier
809 toparse
= current
->m_pArgEnd
;
811 if (current
->m_pos
> 0)
813 // the positionals start from number 1... adjust the index
815 posarg_present
= true;
819 // not a positional argument...
820 current
->m_pos
= nargs
;
821 nonposarg_present
= true;
824 // this conversion specifier is tied to the pos-th argument...
825 pspec
[current
->m_pos
] = current
;
828 if (nargs
== wxMAX_SVNPRINTF_ARGUMENTS
)
830 wxLogDebug(wxT("A single call to wxVsnprintf() has more than %d arguments; ")
831 wxT("ignoring all remaining arguments."), wxMAX_SVNPRINTF_ARGUMENTS
);
832 break; // cannot handle any additional conv spec
837 // it's safe to look in the next character of toparse as at
838 // worst we'll hit its \0
839 if (*(toparse
+1) == wxT('%'))
841 // the Parse() returned false because we've found a %%
849 wxPrintfConvSpec
<CharType
> arg
[wxMAX_SVNPRINTF_ARGUMENTS
];
850 wxPrintfConvSpec
<CharType
> *pspec
[wxMAX_SVNPRINTF_ARGUMENTS
];
851 bool posarg_present
, nonposarg_present
;
858 #endif // _WX_PRIVATE_WXPRINTF_H_