AK: Print NaN and infinite numbers in PrintfImplementation

This commit is contained in:
Peter Ross 2022-03-01 19:50:19 +11:00 committed by Andreas Kling
parent feb19646df
commit 34108547b6
Notes: sideshowbarker 2024-07-17 18:04:05 +09:00
2 changed files with 41 additions and 1 deletions

View file

@ -9,6 +9,7 @@
#include <AK/Format.h>
#include <AK/StdLibExtras.h>
#include <AK/Types.h>
#include <math.h>
#include <stdarg.h>
#ifdef __serenity__
@ -165,7 +166,30 @@ ALWAYS_INLINE int print_double(PutChFunc putch, CharType*& bufptr, double number
u32 whole_width = (field_width >= precision + 1) ? field_width - precision - 1 : 0;
bool sign = number < 0;
bool sign = signbit(number);
bool nan = isnan(number);
bool inf = isinf(number);
if (nan || inf) {
for (unsigned i = 0; i < field_width - 3 - sign; i++) {
putch(bufptr, ' ');
length++;
}
if (sign) {
putch(bufptr, '-');
length++;
}
if (nan) {
putch(bufptr, 'n');
putch(bufptr, 'a');
putch(bufptr, 'n');
} else {
putch(bufptr, 'i');
putch(bufptr, 'n');
putch(bufptr, 'f');
}
return length + 3;
}
if (sign)
number = -number;

View file

@ -273,3 +273,19 @@ TEST_CASE(inttypes_macros)
EXPECT(test_single<uint16_t>({ LITERAL("xxxxxxx"), "|%" PRIx16 "|", 0xC0DE, 6, LITERAL("|c0de|\0") }));
EXPECT(test_single<uint16_t>({ LITERAL("xxxxxxx"), "|%" PRIX16 "|", 0xC0DE, 6, LITERAL("|C0DE|\0") }));
}
TEST_CASE(float_values)
{
union {
float f;
int i;
} v;
v.i = 0x7fc00000;
EXPECT(test_single<double>({ LITERAL("xxxxxxx"), "|%4f|", v.f, 6, LITERAL("| nan|\0") }));
EXPECT(test_single<double>({ LITERAL("xxxxxxx"), "|%4f|", -v.f, 6, LITERAL("|-nan|\0") }));
v.i = 0x7f800000;
EXPECT(test_single<double>({ LITERAL("xxxxxxx"), "|%4f|", v.f, 6, LITERAL("| inf|\0") }));
EXPECT(test_single<double>({ LITERAL("xxxxxxx"), "|%4f|", -v.f, 6, LITERAL("|-inf|\0") }));
}