diff --git a/contrib/10.roundtrip/emyg_dtoa.c b/contrib/10.roundtrip/emyg_dtoa.c index 9fbc5e19..ec76a1c2 100644 --- a/contrib/10.roundtrip/emyg_dtoa.c +++ b/contrib/10.roundtrip/emyg_dtoa.c @@ -421,11 +421,12 @@ static inline void Prettify(char* buffer, int length, int k) { } void emyg_dtoa (double value, char* buffer) { - // Not handling NaN and inf - assert(!isnan(value)); - assert(!isinf(value)); - if (value == 0) { + if (isinf(value)) + strcpy(buffer, signbit(value) ? "-inf.0" : "+inf.0"); + else if (isnan(value)) + strcpy(buffer, signbit(value) ? "-nan.0" : "+nan.0"); + else if (value == 0) { buffer[0] = '0'; buffer[1] = '.'; buffer[2] = '0'; diff --git a/contrib/10.roundtrip/nitro.mk b/contrib/10.roundtrip/nitro.mk index e28f3ffb..8238a1ff 100644 --- a/contrib/10.roundtrip/nitro.mk +++ b/contrib/10.roundtrip/nitro.mk @@ -2,3 +2,8 @@ CONTRIB_DEFS += -DPIC_CSTRING_TO_DOUBLE=emyg_atod -DPIC_DOUBLE_TO_CSTRING=emyg_d CONTRIB_SRCS += contrib/10.roundtrip/emyg_dtoa.c \ contrib/10.roundtrip/emyg_atod.c + +CONTRIB_TESTS += test-roundtrip + +test-roundtrip: bin/picrin + $(TEST_RUNNER) contrib/10.roundtrip/t/roundtrip.scm diff --git a/contrib/10.roundtrip/t/roundtrip.scm b/contrib/10.roundtrip/t/roundtrip.scm new file mode 100644 index 00000000..ecbde357 --- /dev/null +++ b/contrib/10.roundtrip/t/roundtrip.scm @@ -0,0 +1,48 @@ +(import (scheme base) + (srfi 27) + (scheme inexact) + (picrin test)) + +(test-begin) + +(define (rountrip-ok number) + (let ((radix 10)) + (eqv? number (string->number (number->string number radix) radix)))) + +(test #t (rountrip-ok -nan.0)) + +(test #t (rountrip-ok +nan.0)) + +(test #t (rountrip-ok -inf.0)) + +(test #t (rountrip-ok +inf.0)) + +(test -inf.0 (string->number "-inf.0")) + +(test +inf.0 (string->number "+inf.0")) + +(test #t (nan? (string->number "-nan.0"))) + +(test #t (nan? (string->number "+nan.0"))) + +(define (random-roundtrip) + (let ((r (random-real))) + (if (rountrip-ok r) + #t + r))) + +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) +(test #t (random-roundtrip)) + +(test-end)