Bug 1769628 [wpt PR 34081] - Update wpt metadata, a=testonly
[gecko.git] / mozglue / misc / Printf.cpp
blobc53766308ea970e8ddba4746b9eaefd5dd13f95c
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /*
8 * Portable safe sprintf code.
10 * Author: Kipp E.B. Hickman
13 #include "double-conversion/double-conversion.h"
14 #include "mozilla/AllocPolicy.h"
15 #include "mozilla/Likely.h"
16 #include "mozilla/Printf.h"
17 #include "mozilla/Sprintf.h"
18 #include "mozilla/UniquePtrExtensions.h"
19 #include "mozilla/Vector.h"
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
26 #if defined(XP_WIN)
27 # include <windows.h>
28 #endif
30 using double_conversion::DoubleToStringConverter;
31 using DTSC = DoubleToStringConverter;
34 * Numbered Argument State
36 struct NumArgState {
37 int type; // type of the current ap
38 va_list ap; // point to the corresponding position on ap
41 using NumArgStateVector =
42 mozilla::Vector<NumArgState, 20, mozilla::MallocAllocPolicy>;
44 // For values up to and including TYPE_DOUBLE, the lowest bit indicates
45 // whether the type is signed (0) or unsigned (1).
46 #define TYPE_SHORT 0
47 #define TYPE_USHORT 1
48 #define TYPE_INTN 2
49 #define TYPE_UINTN 3
50 #define TYPE_LONG 4
51 #define TYPE_ULONG 5
52 #define TYPE_LONGLONG 6
53 #define TYPE_ULONGLONG 7
54 #define TYPE_DOUBLE 8
55 #define TYPE_STRING 9
56 #define TYPE_INTSTR 10
57 #define TYPE_POINTER 11
58 #if defined(XP_WIN)
59 # define TYPE_WSTRING 12
60 #endif
61 #define TYPE_SCHAR 14
62 #define TYPE_UCHAR 15
63 #define TYPE_UNKNOWN 20
65 #define FLAG_LEFT 0x1
66 #define FLAG_SIGNED 0x2
67 #define FLAG_SPACED 0x4
68 #define FLAG_ZEROS 0x8
69 #define FLAG_NEG 0x10
71 static const char hex[] = "0123456789abcdef";
72 static const char HEX[] = "0123456789ABCDEF";
74 // Fill into the buffer using the data in src
75 bool mozilla::PrintfTarget::fill2(const char* src, int srclen, int width,
76 int flags) {
77 char space = ' ';
79 width -= srclen;
80 if (width > 0 && (flags & FLAG_LEFT) == 0) { // Right adjusting
81 if (flags & FLAG_ZEROS) {
82 space = '0';
84 while (--width >= 0) {
85 if (!emit(&space, 1)) {
86 return false;
91 // Copy out the source data
92 if (!emit(src, srclen)) {
93 return false;
96 if (width > 0 && (flags & FLAG_LEFT) != 0) { // Left adjusting
97 while (--width >= 0) {
98 if (!emit(&space, 1)) {
99 return false;
103 return true;
107 * Fill a number. The order is: optional-sign zero-filling conversion-digits
109 bool mozilla::PrintfTarget::fill_n(const char* src, int srclen, int width,
110 int prec, int type, int flags) {
111 int zerowidth = 0;
112 int precwidth = 0;
113 int signwidth = 0;
114 int leftspaces = 0;
115 int rightspaces = 0;
116 int cvtwidth;
117 char sign;
119 if ((type & 1) == 0) {
120 if (flags & FLAG_NEG) {
121 sign = '-';
122 signwidth = 1;
123 } else if (flags & FLAG_SIGNED) {
124 sign = '+';
125 signwidth = 1;
126 } else if (flags & FLAG_SPACED) {
127 sign = ' ';
128 signwidth = 1;
131 cvtwidth = signwidth + srclen;
133 if (prec > 0 && (type != TYPE_DOUBLE)) {
134 if (prec > srclen) {
135 precwidth = prec - srclen; // Need zero filling
136 cvtwidth += precwidth;
140 if ((flags & FLAG_ZEROS) && ((type == TYPE_DOUBLE) || (prec < 0))) {
141 if (width > cvtwidth) {
142 zerowidth = width - cvtwidth; // Zero filling
143 cvtwidth += zerowidth;
147 if (flags & FLAG_LEFT) {
148 if (width > cvtwidth) {
149 // Space filling on the right (i.e. left adjusting)
150 rightspaces = width - cvtwidth;
152 } else {
153 if (width > cvtwidth) {
154 // Space filling on the left (i.e. right adjusting)
155 leftspaces = width - cvtwidth;
158 while (--leftspaces >= 0) {
159 if (!emit(" ", 1)) {
160 return false;
163 if (signwidth) {
164 if (!emit(&sign, 1)) {
165 return false;
168 while (--precwidth >= 0) {
169 if (!emit("0", 1)) {
170 return false;
173 while (--zerowidth >= 0) {
174 if (!emit("0", 1)) {
175 return false;
178 if (!emit(src, uint32_t(srclen))) {
179 return false;
181 while (--rightspaces >= 0) {
182 if (!emit(" ", 1)) {
183 return false;
186 return true;
189 // All that the cvt_* functions care about as far as the TYPE_* constants is
190 // that the low bit is set to indicate unsigned, or unset to indicate signed.
191 // So we don't try to hard to ensure that the passed TYPE_* constant lines
192 // up with the actual size of the number being printed here. The main printf
193 // code, below, does have to care so that the correct bits are extracted from
194 // the varargs list.
195 bool mozilla::PrintfTarget::appendIntDec(int32_t num) {
196 int flags = 0;
197 long n = num;
198 if (n < 0) {
199 n = -n;
200 flags |= FLAG_NEG;
202 return cvt_l(n, -1, -1, 10, TYPE_INTN, flags, hex);
205 bool mozilla::PrintfTarget::appendIntDec(uint32_t num) {
206 return cvt_l(num, -1, -1, 10, TYPE_UINTN, 0, hex);
209 bool mozilla::PrintfTarget::appendIntOct(uint32_t num) {
210 return cvt_l(num, -1, -1, 8, TYPE_UINTN, 0, hex);
213 bool mozilla::PrintfTarget::appendIntHex(uint32_t num) {
214 return cvt_l(num, -1, -1, 16, TYPE_UINTN, 0, hex);
217 bool mozilla::PrintfTarget::appendIntDec(int64_t num) {
218 int flags = 0;
219 if (num < 0) {
220 num = -num;
221 flags |= FLAG_NEG;
223 return cvt_ll(num, -1, -1, 10, TYPE_INTN, flags, hex);
226 bool mozilla::PrintfTarget::appendIntDec(uint64_t num) {
227 return cvt_ll(num, -1, -1, 10, TYPE_UINTN, 0, hex);
230 bool mozilla::PrintfTarget::appendIntOct(uint64_t num) {
231 return cvt_ll(num, -1, -1, 8, TYPE_UINTN, 0, hex);
234 bool mozilla::PrintfTarget::appendIntHex(uint64_t num) {
235 return cvt_ll(num, -1, -1, 16, TYPE_UINTN, 0, hex);
238 /* Convert a long into its printable form. */
239 bool mozilla::PrintfTarget::cvt_l(long num, int width, int prec, int radix,
240 int type, int flags, const char* hexp) {
241 char cvtbuf[100];
242 char* cvt;
243 int digits;
245 // according to the man page this needs to happen
246 if ((prec == 0) && (num == 0)) {
247 return fill_n("", 0, width, prec, type, flags);
250 // Converting decimal is a little tricky. In the unsigned case we
251 // need to stop when we hit 10 digits. In the signed case, we can
252 // stop when the number is zero.
253 cvt = cvtbuf + sizeof(cvtbuf);
254 digits = 0;
255 while (num) {
256 int digit = (((unsigned long)num) % radix) & 0xF;
257 *--cvt = hexp[digit];
258 digits++;
259 num = (long)(((unsigned long)num) / radix);
261 if (digits == 0) {
262 *--cvt = '0';
263 digits++;
266 // Now that we have the number converted without its sign, deal with
267 // the sign and zero padding.
268 return fill_n(cvt, digits, width, prec, type, flags);
271 /* Convert a 64-bit integer into its printable form. */
272 bool mozilla::PrintfTarget::cvt_ll(int64_t num, int width, int prec, int radix,
273 int type, int flags, const char* hexp) {
274 // According to the man page, this needs to happen.
275 if (prec == 0 && num == 0) {
276 return fill_n("", 0, width, prec, type, flags);
279 // Converting decimal is a little tricky. In the unsigned case we
280 // need to stop when we hit 10 digits. In the signed case, we can
281 // stop when the number is zero.
282 int64_t rad = int64_t(radix);
283 char cvtbuf[100];
284 char* cvt = cvtbuf + sizeof(cvtbuf);
285 int digits = 0;
286 while (num != 0) {
287 int64_t quot = uint64_t(num) / rad;
288 int64_t rem = uint64_t(num) % rad;
289 int32_t digit = int32_t(rem);
290 *--cvt = hexp[digit & 0xf];
291 digits++;
292 num = quot;
294 if (digits == 0) {
295 *--cvt = '0';
296 digits++;
299 // Now that we have the number converted without its sign, deal with
300 // the sign and zero padding.
301 return fill_n(cvt, digits, width, prec, type, flags);
304 template <size_t N>
305 constexpr static size_t lengthof(const char (&)[N]) {
306 return N - 1;
309 // Longest possible output from ToFixed for positive numbers:
310 // [0-9]{kMaxFixedDigitsBeforePoint}\.[0-9]{kMaxFixedDigitsAfterPoint}?
311 constexpr int FIXED_MAX_CHARS =
312 DTSC::kMaxFixedDigitsBeforePoint + 1 + DTSC::kMaxFixedDigitsAfterPoint;
314 // Longest possible output from ToExponential:
315 // [1-9]\.[0-9]{kMaxExponentialDigits}e[+-][0-9]{1,3}
316 // (std::numeric_limits<double>::max() has exponent 308).
317 constexpr int EXPONENTIAL_MAX_CHARS =
318 lengthof("1.") + DTSC::kMaxExponentialDigits + lengthof("e+999");
320 // Longest possible output from ToPrecise:
321 // [0-9\.]{kMaxPrecisionDigits+1} or
322 // [1-9]\.[0-9]{kMaxPrecisionDigits-1}e[+-][0-9]{1,3}
323 constexpr int PRECISE_MAX_CHARS =
324 lengthof("1.") + DTSC::kMaxPrecisionDigits - 1 + lengthof("e+999");
326 constexpr int DTSC_MAX_CHARS =
327 std::max({FIXED_MAX_CHARS, EXPONENTIAL_MAX_CHARS, PRECISE_MAX_CHARS});
330 * Convert a double precision floating point number into its printable
331 * form.
333 bool mozilla::PrintfTarget::cvt_f(double d, char c, int width, int prec,
334 int flags) {
335 bool lower = islower(c);
336 const char* inf = lower ? "inf" : "INF";
337 const char* nan = lower ? "nan" : "NAN";
338 char e = lower ? 'e' : 'E';
339 DoubleToStringConverter converter(DTSC::UNIQUE_ZERO | DTSC::NO_TRAILING_ZERO |
340 DTSC::EMIT_POSITIVE_EXPONENT_SIGN,
341 inf, nan, e, 0, 0, 4, 0, 2);
342 // Longest of the above cases, plus space for a terminal nul character.
343 char buf[DTSC_MAX_CHARS + 1];
344 double_conversion::StringBuilder builder(buf, sizeof(buf));
345 bool success = false;
346 if (std::signbit(d)) {
347 d = std::abs(d);
348 flags |= FLAG_NEG;
350 if (!std::isfinite(d)) {
351 flags &= ~FLAG_ZEROS;
353 // "If the precision is missing, it shall be taken as 6."
354 if (prec < 0) {
355 prec = 6;
357 switch (c) {
358 case 'e':
359 case 'E':
360 success = converter.ToExponential(d, prec, &builder);
361 break;
362 case 'f':
363 case 'F':
364 success = converter.ToFixed(d, prec, &builder);
365 break;
366 case 'g':
367 case 'G':
368 // "If an explicit precision is zero, it shall be taken as 1."
369 success = converter.ToPrecision(d, prec ? prec : 1, &builder);
370 break;
372 if (!success) {
373 return false;
375 int len = builder.position();
376 char* cvt = builder.Finalize();
377 return fill_n(cvt, len, width, prec, TYPE_DOUBLE, flags);
381 * Convert a string into its printable form. "width" is the output
382 * width. "prec" is the maximum number of characters of "s" to output,
383 * where -1 means until NUL.
385 bool mozilla::PrintfTarget::cvt_s(const char* s, int width, int prec,
386 int flags) {
387 if (prec == 0) {
388 return true;
390 if (!s) {
391 s = "(null)";
394 // Limit string length by precision value
395 int slen = int(strlen(s));
396 if (0 < prec && prec < slen) {
397 slen = prec;
400 // and away we go
401 return fill2(s, slen, width, flags);
405 * BuildArgArray stands for Numbered Argument list Sprintf
406 * for example,
407 * fmp = "%4$i, %2$d, %3s, %1d";
408 * the number must start from 1, and no gap among them
410 static bool BuildArgArray(const char* fmt, va_list ap, NumArgStateVector& nas) {
411 size_t number = 0, cn = 0, i;
412 const char* p;
413 char c;
415 // First pass:
416 // Detemine how many legal % I have got, then allocate space.
418 p = fmt;
419 i = 0;
420 while ((c = *p++) != 0) {
421 if (c != '%') {
422 continue;
424 if ((c = *p++) == '%') { // skip %% case
425 continue;
428 while (c != 0) {
429 if (c > '9' || c < '0') {
430 if (c == '$') { // numbered argument case
431 if (i > 0) {
432 MOZ_CRASH("Bad format string");
434 number++;
435 } else { // non-numbered argument case
436 if (number > 0) {
437 MOZ_CRASH("Bad format string");
439 i = 1;
441 break;
444 c = *p++;
448 if (number == 0) {
449 return true;
452 // Only allow a limited number of arguments.
453 MOZ_RELEASE_ASSERT(number <= 20);
455 if (!nas.growByUninitialized(number)) {
456 return false;
459 for (i = 0; i < number; i++) {
460 nas[i].type = TYPE_UNKNOWN;
463 // Second pass:
464 // Set nas[].type.
466 p = fmt;
467 while ((c = *p++) != 0) {
468 if (c != '%') {
469 continue;
471 c = *p++;
472 if (c == '%') {
473 continue;
476 cn = 0;
477 while (c && c != '$') { // should improve error check later
478 cn = cn * 10 + c - '0';
479 c = *p++;
482 if (!c || cn < 1 || cn > number) {
483 MOZ_CRASH("Bad format string");
486 // nas[cn] starts from 0, and make sure nas[cn].type is not assigned.
487 cn--;
488 if (nas[cn].type != TYPE_UNKNOWN) {
489 continue;
492 c = *p++;
494 // flags
495 while ((c == '-') || (c == '+') || (c == ' ') || (c == '0')) {
496 c = *p++;
499 // width
500 if (c == '*') {
501 // not supported feature, for the argument is not numbered
502 MOZ_CRASH("Bad format string");
505 while ((c >= '0') && (c <= '9')) {
506 c = *p++;
509 // precision
510 if (c == '.') {
511 c = *p++;
512 if (c == '*') {
513 // not supported feature, for the argument is not numbered
514 MOZ_CRASH("Bad format string");
517 while ((c >= '0') && (c <= '9')) {
518 c = *p++;
522 // size
523 nas[cn].type = TYPE_INTN;
524 if (c == 'h') {
525 nas[cn].type = TYPE_SHORT;
526 c = *p++;
527 if (c == 'h') {
528 nas[cn].type = TYPE_SCHAR;
529 c = *p++;
531 } else if (c == 'L') {
532 nas[cn].type = TYPE_LONGLONG;
533 c = *p++;
534 } else if (c == 'l') {
535 nas[cn].type = TYPE_LONG;
536 c = *p++;
537 if (c == 'l') {
538 nas[cn].type = TYPE_LONGLONG;
539 c = *p++;
541 } else if (c == 'z' || c == 'I') {
542 static_assert(sizeof(size_t) == sizeof(int) ||
543 sizeof(size_t) == sizeof(long) ||
544 sizeof(size_t) == sizeof(long long),
545 "size_t is not one of the expected sizes");
546 nas[cn].type = sizeof(size_t) == sizeof(int) ? TYPE_INTN
547 : sizeof(size_t) == sizeof(long) ? TYPE_LONG
548 : TYPE_LONGLONG;
549 c = *p++;
550 } else if (c == 't') {
551 static_assert(sizeof(ptrdiff_t) == sizeof(int) ||
552 sizeof(ptrdiff_t) == sizeof(long) ||
553 sizeof(ptrdiff_t) == sizeof(long long),
554 "ptrdiff_t is not one of the expected sizes");
555 nas[cn].type = sizeof(ptrdiff_t) == sizeof(int) ? TYPE_INTN
556 : sizeof(ptrdiff_t) == sizeof(long) ? TYPE_LONG
557 : TYPE_LONGLONG;
558 c = *p++;
559 } else if (c == 'j') {
560 static_assert(sizeof(intmax_t) == sizeof(int) ||
561 sizeof(intmax_t) == sizeof(long) ||
562 sizeof(intmax_t) == sizeof(long long),
563 "intmax_t is not one of the expected sizes");
564 nas[cn].type = sizeof(intmax_t) == sizeof(int) ? TYPE_INTN
565 : sizeof(intmax_t) == sizeof(long) ? TYPE_LONG
566 : TYPE_LONGLONG;
567 c = *p++;
570 // format
571 switch (c) {
572 case 'd':
573 case 'c':
574 case 'i':
575 break;
577 case 'o':
578 case 'u':
579 case 'x':
580 case 'X':
581 // Mark as unsigned type.
582 nas[cn].type |= 1;
583 break;
585 case 'e':
586 case 'E':
587 case 'f':
588 case 'F':
589 case 'g':
590 case 'G':
591 nas[cn].type = TYPE_DOUBLE;
592 break;
594 case 'p':
595 nas[cn].type = TYPE_POINTER;
596 break;
598 case 'S':
599 #if defined(XP_WIN)
600 nas[cn].type = TYPE_WSTRING;
601 #else
602 MOZ_ASSERT(0);
603 nas[cn].type = TYPE_UNKNOWN;
604 #endif
605 break;
607 case 's':
608 #if defined(XP_WIN)
609 if (nas[cn].type == TYPE_LONG) {
610 nas[cn].type = TYPE_WSTRING;
611 break;
613 #endif
614 // Other type sizes are not supported here.
615 MOZ_ASSERT(nas[cn].type == TYPE_INTN);
616 nas[cn].type = TYPE_STRING;
617 break;
619 case 'n':
620 nas[cn].type = TYPE_INTSTR;
621 break;
623 default:
624 MOZ_ASSERT(0);
625 nas[cn].type = TYPE_UNKNOWN;
626 break;
629 // get a legal para.
630 if (nas[cn].type == TYPE_UNKNOWN) {
631 MOZ_CRASH("Bad format string");
635 // Third pass:
636 // Fill nas[].ap.
638 cn = 0;
639 while (cn < number) {
640 // A TYPE_UNKNOWN here means that the format asked for a
641 // positional argument without specifying the meaning of some
642 // earlier argument.
643 MOZ_ASSERT(nas[cn].type != TYPE_UNKNOWN);
645 va_copy(nas[cn].ap, ap);
647 switch (nas[cn].type) {
648 case TYPE_SCHAR:
649 case TYPE_UCHAR:
650 case TYPE_SHORT:
651 case TYPE_USHORT:
652 case TYPE_INTN:
653 case TYPE_UINTN:
654 (void)va_arg(ap, int);
655 break;
656 case TYPE_LONG:
657 (void)va_arg(ap, long);
658 break;
659 case TYPE_ULONG:
660 (void)va_arg(ap, unsigned long);
661 break;
662 case TYPE_LONGLONG:
663 (void)va_arg(ap, long long);
664 break;
665 case TYPE_ULONGLONG:
666 (void)va_arg(ap, unsigned long long);
667 break;
668 case TYPE_STRING:
669 (void)va_arg(ap, char*);
670 break;
671 case TYPE_INTSTR:
672 (void)va_arg(ap, int*);
673 break;
674 case TYPE_DOUBLE:
675 (void)va_arg(ap, double);
676 break;
677 case TYPE_POINTER:
678 (void)va_arg(ap, void*);
679 break;
680 #if defined(XP_WIN)
681 case TYPE_WSTRING:
682 (void)va_arg(ap, wchar_t*);
683 break;
684 #endif
686 default:
687 MOZ_CRASH();
690 cn++;
693 return true;
696 mozilla::PrintfTarget::PrintfTarget() : mEmitted(0) {}
698 bool mozilla::PrintfTarget::vprint(const char* fmt, va_list ap) {
699 char c;
700 int flags, width, prec, radix, type;
701 union {
702 char ch;
703 int i;
704 long l;
705 long long ll;
706 double d;
707 const char* s;
708 int* ip;
709 void* p;
710 #if defined(XP_WIN)
711 const wchar_t* ws;
712 #endif
713 } u{};
714 const char* hexp;
715 int i;
717 // Build an argument array, IF the fmt is numbered argument
718 // list style, to contain the Numbered Argument list pointers.
720 NumArgStateVector nas;
721 if (!BuildArgArray(fmt, ap, nas)) {
722 // the fmt contains error Numbered Argument format, jliu@netscape.com
723 MOZ_CRASH("Bad format string");
726 while ((c = *fmt++) != 0) {
727 if (c != '%') {
728 if (!emit(fmt - 1, 1)) {
729 return false;
732 continue;
735 // Gobble up the % format string. Hopefully we have handled all
736 // of the strange cases!
737 flags = 0;
738 c = *fmt++;
739 if (c == '%') {
740 // quoting a % with %%
741 if (!emit(fmt - 1, 1)) {
742 return false;
745 continue;
748 if (!nas.empty()) {
749 // the fmt contains the Numbered Arguments feature
750 i = 0;
751 while (c && c != '$') { // should improve error check later
752 i = (i * 10) + (c - '0');
753 c = *fmt++;
756 if (nas[i - 1].type == TYPE_UNKNOWN) {
757 MOZ_CRASH("Bad format string");
760 ap = nas[i - 1].ap;
761 c = *fmt++;
764 // Examine optional flags. Note that we do not implement the
765 // '#' flag of sprintf(). The ANSI C spec. of the '#' flag is
766 // somewhat ambiguous and not ideal, which is perhaps why
767 // the various sprintf() implementations are inconsistent
768 // on this feature.
769 while ((c == '-') || (c == '+') || (c == ' ') || (c == '0')) {
770 if (c == '-') {
771 flags |= FLAG_LEFT;
773 if (c == '+') {
774 flags |= FLAG_SIGNED;
776 if (c == ' ') {
777 flags |= FLAG_SPACED;
779 if (c == '0') {
780 flags |= FLAG_ZEROS;
782 c = *fmt++;
784 if (flags & FLAG_SIGNED) {
785 flags &= ~FLAG_SPACED;
787 if (flags & FLAG_LEFT) {
788 flags &= ~FLAG_ZEROS;
791 // width
792 if (c == '*') {
793 c = *fmt++;
794 width = va_arg(ap, int);
795 if (width < 0) {
796 width = -width;
797 flags |= FLAG_LEFT;
798 flags &= ~FLAG_ZEROS;
800 } else {
801 width = 0;
802 while ((c >= '0') && (c <= '9')) {
803 width = (width * 10) + (c - '0');
804 c = *fmt++;
808 // precision
809 prec = -1;
810 if (c == '.') {
811 c = *fmt++;
812 if (c == '*') {
813 c = *fmt++;
814 prec = va_arg(ap, int);
815 } else {
816 prec = 0;
817 while ((c >= '0') && (c <= '9')) {
818 prec = (prec * 10) + (c - '0');
819 c = *fmt++;
824 // size
825 type = TYPE_INTN;
826 if (c == 'h') {
827 type = TYPE_SHORT;
828 c = *fmt++;
829 if (c == 'h') {
830 type = TYPE_SCHAR;
831 c = *fmt++;
833 } else if (c == 'L') {
834 type = TYPE_LONGLONG;
835 c = *fmt++;
836 } else if (c == 'l') {
837 type = TYPE_LONG;
838 c = *fmt++;
839 if (c == 'l') {
840 type = TYPE_LONGLONG;
841 c = *fmt++;
843 } else if (c == 'z' || c == 'I') {
844 static_assert(sizeof(size_t) == sizeof(int) ||
845 sizeof(size_t) == sizeof(long) ||
846 sizeof(size_t) == sizeof(long long),
847 "size_t is not one of the expected sizes");
848 type = sizeof(size_t) == sizeof(int) ? TYPE_INTN
849 : sizeof(size_t) == sizeof(long) ? TYPE_LONG
850 : TYPE_LONGLONG;
851 c = *fmt++;
852 } else if (c == 't') {
853 static_assert(sizeof(ptrdiff_t) == sizeof(int) ||
854 sizeof(ptrdiff_t) == sizeof(long) ||
855 sizeof(ptrdiff_t) == sizeof(long long),
856 "ptrdiff_t is not one of the expected sizes");
857 type = sizeof(ptrdiff_t) == sizeof(int) ? TYPE_INTN
858 : sizeof(ptrdiff_t) == sizeof(long) ? TYPE_LONG
859 : TYPE_LONGLONG;
860 c = *fmt++;
861 } else if (c == 'j') {
862 static_assert(sizeof(intmax_t) == sizeof(int) ||
863 sizeof(intmax_t) == sizeof(long) ||
864 sizeof(intmax_t) == sizeof(long long),
865 "intmax_t is not one of the expected sizes");
866 type = sizeof(intmax_t) == sizeof(int) ? TYPE_INTN
867 : sizeof(intmax_t) == sizeof(long) ? TYPE_LONG
868 : TYPE_LONGLONG;
869 c = *fmt++;
872 // format
873 hexp = hex;
874 switch (c) {
875 case 'd':
876 case 'i': // decimal/integer
877 radix = 10;
878 goto fetch_and_convert;
880 case 'o': // octal
881 radix = 8;
882 type |= 1;
883 goto fetch_and_convert;
885 case 'u': // unsigned decimal
886 radix = 10;
887 type |= 1;
888 goto fetch_and_convert;
890 case 'x': // unsigned hex
891 radix = 16;
892 type |= 1;
893 goto fetch_and_convert;
895 case 'X': // unsigned HEX
896 radix = 16;
897 hexp = HEX;
898 type |= 1;
899 goto fetch_and_convert;
901 fetch_and_convert:
902 switch (type) {
903 case TYPE_SCHAR:
904 u.l = (signed char)va_arg(ap, int);
905 if (u.l < 0) {
906 u.l = -u.l;
907 flags |= FLAG_NEG;
909 goto do_long;
910 case TYPE_UCHAR:
911 u.l = (unsigned char)va_arg(ap, unsigned int);
912 goto do_long;
913 case TYPE_SHORT:
914 u.l = (short)va_arg(ap, int);
915 if (u.l < 0) {
916 u.l = -u.l;
917 flags |= FLAG_NEG;
919 goto do_long;
920 case TYPE_USHORT:
921 u.l = (unsigned short)va_arg(ap, unsigned int);
922 goto do_long;
923 case TYPE_INTN:
924 u.l = va_arg(ap, int);
925 if (u.l < 0) {
926 u.l = -u.l;
927 flags |= FLAG_NEG;
929 goto do_long;
930 case TYPE_UINTN:
931 u.l = (long)va_arg(ap, unsigned int);
932 goto do_long;
934 case TYPE_LONG:
935 u.l = va_arg(ap, long);
936 if (u.l < 0) {
937 u.l = -u.l;
938 flags |= FLAG_NEG;
940 goto do_long;
941 case TYPE_ULONG:
942 u.l = (long)va_arg(ap, unsigned long);
943 do_long:
944 if (!cvt_l(u.l, width, prec, radix, type, flags, hexp)) {
945 return false;
948 break;
950 case TYPE_LONGLONG:
951 u.ll = va_arg(ap, long long);
952 if (u.ll < 0) {
953 u.ll = -u.ll;
954 flags |= FLAG_NEG;
956 goto do_longlong;
957 case TYPE_POINTER:
958 u.ll = (uintptr_t)va_arg(ap, void*);
959 goto do_longlong;
960 case TYPE_ULONGLONG:
961 u.ll = va_arg(ap, unsigned long long);
962 do_longlong:
963 if (!cvt_ll(u.ll, width, prec, radix, type, flags, hexp)) {
964 return false;
967 break;
969 break;
971 case 'e':
972 case 'E':
973 case 'f':
974 case 'F':
975 case 'g':
976 case 'G':
977 u.d = va_arg(ap, double);
978 if (!cvt_f(u.d, c, width, prec, flags)) {
979 return false;
982 break;
984 case 'c':
985 if ((flags & FLAG_LEFT) == 0) {
986 while (width-- > 1) {
987 if (!emit(" ", 1)) {
988 return false;
992 switch (type) {
993 case TYPE_SHORT:
994 case TYPE_INTN:
995 u.ch = va_arg(ap, int);
996 if (!emit(&u.ch, 1)) {
997 return false;
999 break;
1001 if (flags & FLAG_LEFT) {
1002 while (width-- > 1) {
1003 if (!emit(" ", 1)) {
1004 return false;
1008 break;
1010 case 'p':
1011 type = TYPE_POINTER;
1012 radix = 16;
1013 goto fetch_and_convert;
1015 case 's':
1016 if (type == TYPE_INTN) {
1017 u.s = va_arg(ap, const char*);
1018 if (!cvt_s(u.s, width, prec, flags)) {
1019 return false;
1021 break;
1023 MOZ_ASSERT(type == TYPE_LONG);
1024 [[fallthrough]];
1025 case 'S':
1026 #if defined(XP_WIN)
1028 u.ws = va_arg(ap, const wchar_t*);
1030 int rv = WideCharToMultiByte(CP_ACP, 0, u.ws, -1, NULL, 0, NULL, NULL);
1031 if (rv == 0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
1032 if (!cvt_s("<unicode errors in string>", width, prec, flags)) {
1033 return false;
1035 } else {
1036 if (rv == 0) {
1037 rv = 1;
1039 UniqueFreePtr<char[]> buf((char*)malloc(rv));
1040 WideCharToMultiByte(CP_ACP, 0, u.ws, -1, buf.get(), rv, NULL, NULL);
1041 buf[rv - 1] = '\0';
1043 if (!cvt_s(buf.get(), width, prec, flags)) {
1044 return false;
1048 #else
1049 // Not supported here.
1050 MOZ_ASSERT(0);
1051 #endif
1052 break;
1054 case 'n':
1055 u.ip = va_arg(ap, int*);
1056 if (u.ip) {
1057 *u.ip = mEmitted;
1059 break;
1061 default:
1062 // Not a % token after all... skip it
1063 if (!emit("%", 1)) {
1064 return false;
1066 if (!emit(fmt - 1, 1)) {
1067 return false;
1072 return true;
1075 /************************************************************************/
1077 bool mozilla::PrintfTarget::print(const char* format, ...) {
1078 va_list ap;
1080 va_start(ap, format);
1081 bool result = vprint(format, ap);
1082 va_end(ap);
1083 return result;
1086 #undef TYPE_SHORT
1087 #undef TYPE_USHORT
1088 #undef TYPE_INTN
1089 #undef TYPE_UINTN
1090 #undef TYPE_LONG
1091 #undef TYPE_ULONG
1092 #undef TYPE_LONGLONG
1093 #undef TYPE_ULONGLONG
1094 #undef TYPE_STRING
1095 #undef TYPE_DOUBLE
1096 #undef TYPE_INTSTR
1097 #undef TYPE_POINTER
1098 #undef TYPE_WSTRING
1099 #undef TYPE_UNKNOWN
1100 #undef TYPE_SCHAR
1101 #undef TYPE_UCHAR
1103 #undef FLAG_LEFT
1104 #undef FLAG_SIGNED
1105 #undef FLAG_SPACED
1106 #undef FLAG_ZEROS
1107 #undef FLAG_NEG