| 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 |
*/ |
| 4 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 5 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 6 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 7 |
|
| 8 |
#include "mozilla/IntegerPrintfMacros.h" |
| 9 |
|
| 10 |
#include <cfloat> |
| 11 |
#include <stdarg.h> |
| 12 |
|
| 13 |
#include "js/Printf.h" |
| 14 |
|
| 15 |
#include "jsapi-tests/tests.h" |
| 16 |
|
| 17 |
static bool MOZ_FORMAT_PRINTF(2, 3) |
| 18 |
print_one(const char* expect, const char* fmt, ...) { |
| 19 |
va_list ap; |
| 20 |
|
| 21 |
va_start(ap, fmt); |
| 22 |
JS::UniqueChars output = JS_vsmprintf(fmt, ap); |
| 23 |
va_end(ap); |
| 24 |
|
| 25 |
return output && !strcmp(output.get(), expect); |
| 26 |
} |
| 27 |
|
| 28 |
static const char* zero() { |
| 29 |
// gcc 9 is altogether too clever about detecting that this will always |
| 30 |
// return nullptr. Do not replace 0x10 with 0x1; it will no longer work. |
| 31 |
return uintptr_t(&zero) == 0x10 ? "never happens" : nullptr; |
| 32 |
} |
| 33 |
|
| 34 |
BEGIN_TEST(testPrintf) { |
| 35 |
CHECK(print_one("23", "%d", 23)); |
| 36 |
CHECK(print_one("-1", "%d", -1)); |
| 37 |
CHECK(print_one("23", "%u", 23u)); |
| 38 |
CHECK(print_one("0x17", "0x%x", 23u)); |
| 39 |
CHECK(print_one("0xFF", "0x%X", 255u)); |
| 40 |
CHECK(print_one("027", "0%o", 23u)); |
| 41 |
CHECK(print_one("-1", "%hd", (short)-1)); |
| 42 |
// This could be expanded if need be, it's just convenient to do |
| 43 |
// it this way. |
| 44 |
if (sizeof(short) == 2) { |
| 45 |
CHECK(print_one("8000", "%hx", (unsigned short)0x8000)); |
| 46 |
} |
| 47 |
CHECK(print_one("0xf0f0", "0x%lx", 0xf0f0ul)); |
| 48 |
CHECK(print_one("0xF0F0", "0x%llX", 0xf0f0ull)); |
| 49 |
CHECK(print_one("27270", "%zu", (size_t)27270)); |
| 50 |
CHECK(print_one("27270", "%zu", (size_t)27270)); |
| 51 |
CHECK(print_one("hello", "he%so", "ll")); |
| 52 |
CHECK(print_one("(null)", "%s", ::zero())); |
| 53 |
CHECK(print_one("0", "%p", (char*)0)); |
| 54 |
CHECK(print_one("h", "%c", 'h')); |
| 55 |
CHECK(print_one("1.500000", "%f", 1.5f)); |
| 56 |
CHECK(print_one("1.5", "%g", 1.5)); |
| 57 |
|
| 58 |
// Regression test for bug#1350097. The bug was an assertion |
| 59 |
// failure caused by printing a very long floating point value. |
| 60 |
print_one("ignore", "%lf", DBL_MAX); |
| 61 |
|
| 62 |
CHECK(print_one("2727", "%" PRIu32, (uint32_t)2727)); |
| 63 |
CHECK(print_one("aa7", "%" PRIx32, (uint32_t)2727)); |
| 64 |
CHECK(print_one("2727", "%" PRIu64, (uint64_t)2727)); |
| 65 |
CHECK(print_one("aa7", "%" PRIx64, (uint64_t)2727)); |
| 66 |
|
| 67 |
return true; |
| 68 |
} |
| 69 |
END_TEST(testPrintf) |