]> git.saurik.com Git - wxWidgets.git/blob - include/wx/private/wxprintf.h
Check wxPrintf etc. arguments types.
[wxWidgets.git] / include / wx / private / wxprintf.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/private/wxprintf.h
3 // Purpose: wxWidgets wxPrintf() implementation
4 // Author: Ove Kaven
5 // Modified by: Ron Lee, Francesco Montorsi
6 // Created: 09/04/99
7 // RCS-ID: $Id$
8 // Copyright: (c) wxWidgets copyright
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifndef _WX_PRIVATE_WXPRINTF_H_
13 #define _WX_PRIVATE_WXPRINTF_H_
14
15 // ---------------------------------------------------------------------------
16 // headers and macros
17 // ---------------------------------------------------------------------------
18
19 #include "wx/crt.h"
20 #include "wx/log.h"
21 #include "wx/utils.h"
22
23 #include <string.h>
24
25 #if defined(__MWERKS__) && __MSL__ >= 0x6000
26 namespace std {}
27 using namespace std ;
28 #endif
29
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)
44
45 #define SYSTEM_SPRINTF_IS_UNSAFE
46 #endif
47
48 // ---------------------------------------------------------------------------
49 // printf format string parsing
50 // ---------------------------------------------------------------------------
51
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
56
57
58 // the conversion specifiers accepted by wxCRT_VsnprintfW
59 enum wxPrintfArgType
60 {
61 wxPAT_INVALID = -1,
62
63 wxPAT_INT, // %d, %i, %o, %u, %x, %X
64 wxPAT_LONGINT, // %ld, etc
65 #ifdef wxLongLong_t
66 wxPAT_LONGLONGINT, // %Ld, etc
67 #endif
68 wxPAT_SIZET, // %Zd, etc
69
70 wxPAT_DOUBLE, // %e, %E, %f, %g, %G
71 wxPAT_LONGDOUBLE, // %le, etc
72
73 wxPAT_POINTER, // %p
74
75 wxPAT_CHAR, // %hc (in ANSI mode: %c, too)
76 wxPAT_WCHAR, // %lc (in Unicode mode: %c, too)
77
78 wxPAT_PCHAR, // %s (related to a char *)
79 wxPAT_PWCHAR, // %s (related to a wchar_t *)
80
81 wxPAT_NINT, // %n
82 wxPAT_NSHORTINT, // %hn
83 wxPAT_NLONGINT, // %ln
84
85 wxPAT_STAR // '*' used for width or precision
86 };
87
88 // an argument passed to wxCRT_VsnprintfW
89 union wxPrintfArg
90 {
91 int pad_int; // %d, %i, %o, %u, %x, %X
92 long int pad_longint; // %ld, etc
93 #ifdef wxLongLong_t
94 wxLongLong_t pad_longlongint; // %Ld, etc
95 #endif
96 size_t pad_sizet; // %Zd, etc
97
98 double pad_double; // %e, %E, %f, %g, %G
99 long double pad_longdouble; // %le, etc
100
101 void *pad_pointer; // %p
102
103 char pad_char; // %hc (in ANSI mode: %c, too)
104 wchar_t pad_wchar; // %lc (in Unicode mode: %c, too)
105
106 void *pad_str; // %s
107
108 int *pad_nint; // %n
109 short int *pad_nshortint; // %hn
110 long int *pad_nlongint; // %ln
111 };
112
113 // helper for converting string into either char* or wchar_t* depending
114 // on the type of wxPrintfConvSpec<T> instantiation:
115 template<typename CharType> struct wxPrintfStringHelper {};
116
117 template<> struct wxPrintfStringHelper<char>
118 {
119 typedef const wxWX2MBbuf ConvertedType;
120 static ConvertedType Convert(const wxString& s) { return s.mb_str(); }
121 };
122
123 template<> struct wxPrintfStringHelper<wchar_t>
124 {
125 typedef const wxWX2WCbuf ConvertedType;
126 static ConvertedType Convert(const wxString& s) { return s.wc_str(); }
127 };
128
129
130 // Contains parsed data relative to a conversion specifier given to
131 // wxCRT_VsnprintfW and parsed from the format string
132 // NOTE: in C++ there is almost no difference between struct & classes thus
133 // there is no performance gain by using a struct here...
134 template<typename CharType>
135 class wxPrintfConvSpec
136 {
137 public:
138
139 // the position of the argument relative to this conversion specifier
140 size_t m_pos;
141
142 // the type of this conversion specifier
143 wxPrintfArgType m_type;
144
145 // the minimum and maximum width
146 // when one of this var is set to -1 it means: use the following argument
147 // in the stack as minimum/maximum width for this conversion specifier
148 int m_nMinWidth, m_nMaxWidth;
149
150 // does the argument need to the be aligned to left ?
151 bool m_bAlignLeft;
152
153 // pointer to the '%' of this conversion specifier in the format string
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_pArgPos;
157
158 // pointer to the last character of this conversion specifier in the
159 // format string
160 // NOTE: this points somewhere in the string given to the Parse() function -
161 // it's task of the caller ensure that memory is still valid !
162 const CharType *m_pArgEnd;
163
164 // a little buffer where formatting flags like #+\.hlqLZ are stored by Parse()
165 // for use in Process()
166 char m_szFlags[wxMAX_SVNPRINTF_FLAGBUFFER_LEN];
167
168
169 public:
170
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.
174 void Init();
175
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);
180
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);
185
186 // Loads the argument of this conversion specifier from given va_list.
187 bool LoadArg(wxPrintfArg *p, va_list &argptr);
188
189 private:
190 // An helper function of LoadArg() which is used to handle the '*' flag
191 void ReplaceAsteriskWith(int w);
192 };
193
194 template<typename CharType>
195 void wxPrintfConvSpec<CharType>::Init()
196 {
197 m_nMinWidth = 0;
198 m_nMaxWidth = 0xFFFF;
199 m_pos = 0;
200 m_bAlignLeft = false;
201 m_pArgPos = m_pArgEnd = NULL;
202 m_type = wxPAT_INVALID;
203
204 memset(m_szFlags, 0, sizeof(m_szFlags));
205 // this character will never be removed from m_szFlags array and
206 // is important when calling sprintf() in wxPrintfConvSpec::Process() !
207 m_szFlags[0] = '%';
208 }
209
210 template<typename CharType>
211 bool wxPrintfConvSpec<CharType>::Parse(const CharType *format)
212 {
213 bool done = false;
214
215 // temporary parse data
216 size_t flagofs = 1;
217 bool in_prec, // true if we found the dot in some previous iteration
218 prec_dot; // true if the dot has been already added to m_szFlags
219 int ilen = 0;
220
221 m_bAlignLeft = in_prec = prec_dot = false;
222 m_pArgPos = m_pArgEnd = format;
223 do
224 {
225 #define CHECK_PREC \
226 if (in_prec && !prec_dot) \
227 { \
228 m_szFlags[flagofs++] = '.'; \
229 prec_dot = true; \
230 }
231
232 // what follows '%'?
233 const CharType ch = *(++m_pArgEnd);
234 switch ( ch )
235 {
236 case wxT('\0'):
237 return false; // not really an argument
238
239 case wxT('%'):
240 return false; // not really an argument
241
242 case wxT('#'):
243 case wxT('0'):
244 case wxT(' '):
245 case wxT('+'):
246 case wxT('\''):
247 CHECK_PREC
248 m_szFlags[flagofs++] = char(ch);
249 break;
250
251 case wxT('-'):
252 CHECK_PREC
253 m_bAlignLeft = true;
254 m_szFlags[flagofs++] = char(ch);
255 break;
256
257 case wxT('.'):
258 // don't use CHECK_PREC here to avoid warning about the value
259 // assigned to prec_dot inside it being never used (because
260 // overwritten just below) from Borland in release build
261 if (in_prec && !prec_dot)
262 m_szFlags[flagofs++] = '.';
263 in_prec = true;
264 prec_dot = false;
265 m_nMaxWidth = 0;
266 // dot will be auto-added to m_szFlags if non-negative
267 // number follows
268 break;
269
270 case wxT('h'):
271 ilen = -1;
272 CHECK_PREC
273 m_szFlags[flagofs++] = char(ch);
274 break;
275
276 case wxT('l'):
277 // NB: it's safe to use flagofs-1 as flagofs always start from 1
278 if (m_szFlags[flagofs-1] == 'l') // 'll' modifier is the same as 'L' or 'q'
279 ilen = 2;
280 else
281 ilen = 1;
282 CHECK_PREC
283 m_szFlags[flagofs++] = char(ch);
284 break;
285
286 case wxT('q'):
287 case wxT('L'):
288 ilen = 2;
289 CHECK_PREC
290 m_szFlags[flagofs++] = char(ch);
291 break;
292 #ifdef __WXMSW__
293 // under Windows we support the special '%I64' notation as longlong
294 // integer conversion specifier for MSVC compatibility
295 // (it behaves exactly as '%lli' or '%Li' or '%qi')
296 case wxT('I'):
297 if (*(m_pArgEnd+1) != wxT('6') ||
298 *(m_pArgEnd+2) != wxT('4'))
299 return false; // bad format
300
301 m_pArgEnd++;
302 m_pArgEnd++;
303
304 ilen = 2;
305 CHECK_PREC
306 m_szFlags[flagofs++] = char(ch);
307 m_szFlags[flagofs++] = '6';
308 m_szFlags[flagofs++] = '4';
309 break;
310 #endif // __WXMSW__
311
312 case wxT('Z'):
313 ilen = 3;
314 CHECK_PREC
315 m_szFlags[flagofs++] = char(ch);
316 break;
317
318 case wxT('*'):
319 if (in_prec)
320 {
321 CHECK_PREC
322
323 // tell Process() to use the next argument
324 // in the stack as maxwidth...
325 m_nMaxWidth = -1;
326 }
327 else
328 {
329 // tell Process() to use the next argument
330 // in the stack as minwidth...
331 m_nMinWidth = -1;
332 }
333
334 // save the * in our formatting buffer...
335 // will be replaced later by Process()
336 m_szFlags[flagofs++] = char(ch);
337 break;
338
339 case wxT('1'): case wxT('2'): case wxT('3'):
340 case wxT('4'): case wxT('5'): case wxT('6'):
341 case wxT('7'): case wxT('8'): case wxT('9'):
342 {
343 int len = 0;
344 CHECK_PREC
345 while ( (*m_pArgEnd >= CharType('0')) &&
346 (*m_pArgEnd <= CharType('9')) )
347 {
348 m_szFlags[flagofs++] = char(*m_pArgEnd);
349 len = len*10 + (*m_pArgEnd - wxT('0'));
350 m_pArgEnd++;
351 }
352
353 if (in_prec)
354 m_nMaxWidth = len;
355 else
356 m_nMinWidth = len;
357
358 m_pArgEnd--; // the main loop pre-increments n again
359 }
360 break;
361
362 case wxT('$'): // a positional parameter (e.g. %2$s) ?
363 {
364 if (m_nMinWidth <= 0)
365 break; // ignore this formatting flag as no
366 // numbers are preceding it
367
368 // remove from m_szFlags all digits previously added
369 do {
370 flagofs--;
371 } while (m_szFlags[flagofs] >= '1' &&
372 m_szFlags[flagofs] <= '9');
373
374 // re-adjust the offset making it point to the
375 // next free char of m_szFlags
376 flagofs++;
377
378 m_pos = m_nMinWidth;
379 m_nMinWidth = 0;
380 }
381 break;
382
383 case wxT('d'):
384 case wxT('i'):
385 case wxT('o'):
386 case wxT('u'):
387 case wxT('x'):
388 case wxT('X'):
389 CHECK_PREC
390 m_szFlags[flagofs++] = char(ch);
391 if (ilen == 0)
392 m_type = wxPAT_INT;
393 else if (ilen == -1)
394 // NB: 'short int' value passed through '...'
395 // is promoted to 'int', so we have to get
396 // an int from stack even if we need a short
397 m_type = wxPAT_INT;
398 else if (ilen == 1)
399 m_type = wxPAT_LONGINT;
400 else if (ilen == 2)
401 #ifdef wxLongLong_t
402 m_type = wxPAT_LONGLONGINT;
403 #else // !wxLongLong_t
404 m_type = wxPAT_LONGINT;
405 #endif // wxLongLong_t/!wxLongLong_t
406 else if (ilen == 3)
407 m_type = wxPAT_SIZET;
408 done = true;
409 break;
410
411 case wxT('e'):
412 case wxT('E'):
413 case wxT('f'):
414 case wxT('g'):
415 case wxT('G'):
416 CHECK_PREC
417 m_szFlags[flagofs++] = char(ch);
418 if (ilen == 2)
419 m_type = wxPAT_LONGDOUBLE;
420 else
421 m_type = wxPAT_DOUBLE;
422 done = true;
423 break;
424
425 case wxT('p'):
426 m_type = wxPAT_POINTER;
427 m_szFlags[flagofs++] = char(ch);
428 done = true;
429 break;
430
431 case wxT('c'):
432 if (ilen == -1)
433 {
434 // in Unicode mode %hc == ANSI character
435 // and in ANSI mode, %hc == %c == ANSI...
436 m_type = wxPAT_CHAR;
437 }
438 else if (ilen == 1)
439 {
440 // in ANSI mode %lc == Unicode character
441 // and in Unicode mode, %lc == %c == Unicode...
442 m_type = wxPAT_WCHAR;
443 }
444 else
445 {
446 #if wxUSE_UNICODE
447 // in Unicode mode, %c == Unicode character
448 m_type = wxPAT_WCHAR;
449 #else
450 // in ANSI mode, %c == ANSI character
451 m_type = wxPAT_CHAR;
452 #endif
453 }
454 done = true;
455 break;
456
457 case wxT('s'):
458 if (ilen == -1)
459 {
460 // Unicode mode wx extension: we'll let %hs mean non-Unicode
461 // strings (when in ANSI mode, %s == %hs == ANSI string)
462 m_type = wxPAT_PCHAR;
463 }
464 else if (ilen == 1)
465 {
466 // in Unicode mode, %ls == %s == Unicode string
467 // in ANSI mode, %ls == Unicode string
468 m_type = wxPAT_PWCHAR;
469 }
470 else
471 {
472 #if wxUSE_UNICODE
473 m_type = wxPAT_PWCHAR;
474 #else
475 m_type = wxPAT_PCHAR;
476 #endif
477 }
478 done = true;
479 break;
480
481 case wxT('n'):
482 if (ilen == 0)
483 m_type = wxPAT_NINT;
484 else if (ilen == -1)
485 m_type = wxPAT_NSHORTINT;
486 else if (ilen >= 1)
487 m_type = wxPAT_NLONGINT;
488 done = true;
489 break;
490
491 default:
492 // bad format, don't consider this an argument;
493 // leave it unchanged
494 return false;
495 }
496
497 if (flagofs == wxMAX_SVNPRINTF_FLAGBUFFER_LEN)
498 {
499 wxLogDebug(wxT("Too many flags specified for a single conversion specifier!"));
500 return false;
501 }
502 }
503 while (!done);
504
505 return true; // parsing was successful
506 }
507
508 template<typename CharType>
509 void wxPrintfConvSpec<CharType>::ReplaceAsteriskWith(int width)
510 {
511 char temp[wxMAX_SVNPRINTF_FLAGBUFFER_LEN];
512
513 // find the first * in our flag buffer
514 char *pwidth = strchr(m_szFlags, '*');
515 wxCHECK_RET(pwidth, wxT("field width must be specified"));
516
517 // save what follows the * (the +1 is to skip the asterisk itself!)
518 strcpy(temp, pwidth+1);
519 if (width < 0)
520 {
521 pwidth[0] = wxT('-');
522 pwidth++;
523 }
524
525 // replace * with the actual integer given as width
526 #ifndef SYSTEM_SPRINTF_IS_UNSAFE
527 int maxlen = (m_szFlags + wxMAX_SVNPRINTF_FLAGBUFFER_LEN - pwidth) /
528 sizeof(*m_szFlags);
529 #endif
530 int offset = system_sprintf(pwidth, maxlen, "%d", abs(width));
531
532 // restore after the expanded * what was following it
533 strcpy(pwidth+offset, temp);
534 }
535
536 template<typename CharType>
537 bool wxPrintfConvSpec<CharType>::LoadArg(wxPrintfArg *p, va_list &argptr)
538 {
539 // did the '*' width/precision specifier was used ?
540 if (m_nMaxWidth == -1)
541 {
542 // take the maxwidth specifier from the stack
543 m_nMaxWidth = va_arg(argptr, int);
544 if (m_nMaxWidth < 0)
545 m_nMaxWidth = 0;
546 else
547 ReplaceAsteriskWith(m_nMaxWidth);
548 }
549
550 if (m_nMinWidth == -1)
551 {
552 // take the minwidth specifier from the stack
553 m_nMinWidth = va_arg(argptr, int);
554
555 ReplaceAsteriskWith(m_nMinWidth);
556 if (m_nMinWidth < 0)
557 {
558 m_bAlignLeft = !m_bAlignLeft;
559 m_nMinWidth = -m_nMinWidth;
560 }
561 }
562
563 switch (m_type) {
564 case wxPAT_INT:
565 p->pad_int = va_arg(argptr, int);
566 break;
567 case wxPAT_LONGINT:
568 p->pad_longint = va_arg(argptr, long int);
569 break;
570 #ifdef wxLongLong_t
571 case wxPAT_LONGLONGINT:
572 p->pad_longlongint = va_arg(argptr, wxLongLong_t);
573 break;
574 #endif // wxLongLong_t
575 case wxPAT_SIZET:
576 p->pad_sizet = va_arg(argptr, size_t);
577 break;
578 case wxPAT_DOUBLE:
579 p->pad_double = va_arg(argptr, double);
580 break;
581 case wxPAT_LONGDOUBLE:
582 p->pad_longdouble = va_arg(argptr, long double);
583 break;
584 case wxPAT_POINTER:
585 p->pad_pointer = va_arg(argptr, void *);
586 break;
587
588 case wxPAT_CHAR:
589 p->pad_char = (char)va_arg(argptr, int); // char is promoted to int when passed through '...'
590 break;
591 case wxPAT_WCHAR:
592 p->pad_wchar = (wchar_t)va_arg(argptr, int); // char is promoted to int when passed through '...'
593 break;
594
595 case wxPAT_PCHAR:
596 case wxPAT_PWCHAR:
597 p->pad_str = va_arg(argptr, void *);
598 break;
599
600 case wxPAT_NINT:
601 p->pad_nint = va_arg(argptr, int *);
602 break;
603 case wxPAT_NSHORTINT:
604 p->pad_nshortint = va_arg(argptr, short int *);
605 break;
606 case wxPAT_NLONGINT:
607 p->pad_nlongint = va_arg(argptr, long int *);
608 break;
609
610 case wxPAT_STAR:
611 // this will be handled as part of the next argument
612 return true;
613
614 case wxPAT_INVALID:
615 default:
616 return false;
617 }
618
619 return true; // loading was successful
620 }
621
622 template<typename CharType>
623 int wxPrintfConvSpec<CharType>::Process(CharType *buf, size_t lenMax, wxPrintfArg *p, size_t written)
624 {
625 // buffer to avoid dynamic memory allocation each time for small strings;
626 // note that this buffer is used only to hold results of number formatting,
627 // %s directly writes user's string in buf, without using szScratch
628 char szScratch[wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN];
629 size_t lenScratch = 0, lenCur = 0;
630
631 #define APPEND_CH(ch) \
632 { \
633 if ( lenCur == lenMax ) \
634 return -1; \
635 \
636 buf[lenCur++] = ch; \
637 }
638
639 switch ( m_type )
640 {
641 case wxPAT_INT:
642 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_int);
643 break;
644
645 case wxPAT_LONGINT:
646 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_longint);
647 break;
648
649 #ifdef wxLongLong_t
650 case wxPAT_LONGLONGINT:
651 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_longlongint);
652 break;
653 #endif // SIZEOF_LONG_LONG
654
655 case wxPAT_SIZET:
656 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_sizet);
657 break;
658
659 case wxPAT_LONGDOUBLE:
660 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_longdouble);
661 break;
662
663 case wxPAT_DOUBLE:
664 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_double);
665 break;
666
667 case wxPAT_POINTER:
668 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_pointer);
669 break;
670
671 case wxPAT_CHAR:
672 case wxPAT_WCHAR:
673 {
674 wxUniChar ch;
675 if (m_type == wxPAT_CHAR)
676 ch = p->pad_char;
677 else // m_type == wxPAT_WCHAR
678 ch = p->pad_wchar;
679
680 CharType val = ch;
681
682 size_t i;
683
684 if (!m_bAlignLeft)
685 for (i = 1; i < (size_t)m_nMinWidth; i++)
686 APPEND_CH(wxT(' '));
687
688 APPEND_CH(val);
689
690 if (m_bAlignLeft)
691 for (i = 1; i < (size_t)m_nMinWidth; i++)
692 APPEND_CH(wxT(' '));
693 }
694 break;
695
696 case wxPAT_PCHAR:
697 case wxPAT_PWCHAR:
698 {
699 wxArgNormalizedString arg(p->pad_str);
700 wxString s = arg;
701
702 if ( !arg.IsValid() && m_nMaxWidth >= 6 )
703 s = wxT("(null)");
704
705 typename wxPrintfStringHelper<CharType>::ConvertedType strbuf(
706 wxPrintfStringHelper<CharType>::Convert(s));
707
708 // at this point we are sure that m_nMaxWidth is positive or
709 // null (see top of wxPrintfConvSpec::LoadArg)
710 int len = wxMin((unsigned int)m_nMaxWidth, wxStrlen(strbuf));
711
712 int i;
713
714 if (!m_bAlignLeft)
715 {
716 for (i = len; i < m_nMinWidth; i++)
717 APPEND_CH(wxT(' '));
718 }
719
720 len = wxMin((unsigned int)len, lenMax-lenCur);
721 wxStrncpy(buf+lenCur, strbuf, len);
722 lenCur += len;
723
724 if (m_bAlignLeft)
725 {
726 for (i = len; i < m_nMinWidth; i++)
727 APPEND_CH(wxT(' '));
728 }
729 }
730 break;
731
732 case wxPAT_NINT:
733 *p->pad_nint = written;
734 break;
735
736 case wxPAT_NSHORTINT:
737 *p->pad_nshortint = (short int)written;
738 break;
739
740 case wxPAT_NLONGINT:
741 *p->pad_nlongint = written;
742 break;
743
744 case wxPAT_INVALID:
745 default:
746 return -1;
747 }
748
749 // if we used system's sprintf() then we now need to append the s_szScratch
750 // buffer to the given one...
751 switch (m_type)
752 {
753 case wxPAT_INT:
754 case wxPAT_LONGINT:
755 #ifdef wxLongLong_t
756 case wxPAT_LONGLONGINT:
757 #endif
758 case wxPAT_SIZET:
759 case wxPAT_LONGDOUBLE:
760 case wxPAT_DOUBLE:
761 case wxPAT_POINTER:
762 wxASSERT(lenScratch < wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN);
763 // NB: 1) we can compare lenMax (for CharType*, i.e. possibly
764 // wchar_t*) with lenScratch (char*) because this code is
765 // formatting integers and that will have the same length
766 // even in UTF-8 (the only case when char* length may be
767 // more than wchar_t* length of the same string)
768 // 2) wxStrncpy converts the 2nd argument to 1st argument's
769 // type transparently if their types differ, so this code
770 // works for both instantiations
771 if (lenMax < lenScratch)
772 {
773 // fill output buffer and then return -1
774 wxStrncpy(buf, szScratch, lenMax);
775 return -1;
776 }
777 wxStrncpy(buf, szScratch, lenScratch);
778 lenCur += lenScratch;
779 break;
780
781 default:
782 break; // all other cases were completed previously
783 }
784
785 return lenCur;
786 }
787
788
789 // helper that parses format string
790 template<typename CharType>
791 struct wxPrintfConvSpecParser
792 {
793 typedef wxPrintfConvSpec<CharType> ConvSpec;
794
795 wxPrintfConvSpecParser(const CharType *fmt)
796 {
797 nargs = 0;
798 posarg_present =
799 nonposarg_present = false;
800
801 memset(pspec, 0, sizeof(pspec));
802
803 // parse the format string
804 for ( const CharType *toparse = fmt; *toparse != wxT('\0'); toparse++ )
805 {
806 // skip everything except format specifications
807 if ( *toparse != '%' )
808 continue;
809
810 // also skip escaped percent signs
811 if ( toparse[1] == '%' )
812 {
813 toparse++;
814 continue;
815 }
816
817 ConvSpec *spec = &specs[nargs];
818 spec->Init();
819
820 // attempt to parse this format specification
821 if ( !spec->Parse(toparse) )
822 continue;
823
824 // advance to the end of this specifier
825 toparse = spec->m_pArgEnd;
826
827 // special handling for specifications including asterisks: we need
828 // to reserve an extra slot (or two if asterisks were used for both
829 // width and precision) in specs array in this case
830 for ( const char *f = strchr(spec->m_szFlags, '*');
831 f;
832 f = strchr(f + 1, '*') )
833 {
834 if ( nargs++ == wxMAX_SVNPRINTF_ARGUMENTS )
835 break;
836
837 // TODO: we need to support specifiers of the form "%2$*1$s"
838 // (this is the same as "%*s") as if any positional arguments
839 // are used all asterisks must be positional as well but this
840 // requires a lot of changes in this code (basically we'd need
841 // to rewrite Parse() to return "*" and conversion itself as
842 // separate entries)
843 if ( posarg_present )
844 {
845 wxFAIL_MSG
846 (
847 wxString::Format
848 (
849 "Format string \"%s\" uses both positional "
850 "parameters and '*' but this is not currently "
851 "supported by this implementation, sorry.",
852 fmt
853 )
854 );
855 }
856
857 specs[nargs] = *spec;
858
859 // make an entry for '*' and point to it from pspec
860 spec->Init();
861 spec->m_type = wxPAT_STAR;
862 pspec[nargs - 1] = spec;
863
864 spec = &specs[nargs];
865 }
866
867 // check if this is a positional or normal argument
868 if ( spec->m_pos > 0 )
869 {
870 // the positional arguments start from number 1 so we need
871 // to adjust the index
872 spec->m_pos--;
873 posarg_present = true;
874 }
875 else // not a positional argument...
876 {
877 spec->m_pos = nargs;
878 nonposarg_present = true;
879 }
880
881 // this conversion specifier is tied to the pos-th argument...
882 pspec[spec->m_pos] = spec;
883
884 if ( nargs++ == wxMAX_SVNPRINTF_ARGUMENTS )
885 break;
886 }
887
888
889 // warn if we lost any arguments (the program probably will crash
890 // anyhow because of stack corruption...)
891 if ( nargs == wxMAX_SVNPRINTF_ARGUMENTS )
892 {
893 wxFAIL_MSG
894 (
895 wxString::Format
896 (
897 "wxVsnprintf() currently supports only %d arguments, "
898 "but format string \"%s\" defines more of them.\n"
899 "You need to change wxMAX_SVNPRINTF_ARGUMENTS and "
900 "recompile if more are really needed.",
901 fmt, wxMAX_SVNPRINTF_ARGUMENTS
902 )
903 );
904 }
905 }
906
907 // total number of valid elements in specs
908 unsigned nargs;
909
910 // all format specifications in this format string in order of their
911 // appearance (which may be different from arguments order)
912 ConvSpec specs[wxMAX_SVNPRINTF_ARGUMENTS];
913
914 // pointer to specs array element for the N-th argument
915 ConvSpec *pspec[wxMAX_SVNPRINTF_ARGUMENTS];
916
917 // true if any positional/non-positional parameters are used
918 bool posarg_present,
919 nonposarg_present;
920 };
921
922 #undef APPEND_CH
923 #undef CHECK_PREC
924
925 #endif // _WX_PRIVATE_WXPRINTF_H_