From 406562ac6d3863dfdaedbf40f9d4a23ca37c9ec5 Mon Sep 17 00:00:00 2001 From: ZyX Date: Sun, 21 Feb 2016 21:33:58 +0300 Subject: encode: Fail to dump NaN and infinity Thanks to vim/vim#654 --- src/nvim/eval/encode.c | 21 ++++++++++++++++++--- test/functional/eval/json_functions_spec.lua | 9 +++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/nvim/eval/encode.c b/src/nvim/eval/encode.c index a131f5c3c1..d21347cca6 100644 --- a/src/nvim/eval/encode.c +++ b/src/nvim/eval/encode.c @@ -7,6 +7,7 @@ #include #include #include +#include #include "nvim/eval/encode.h" #include "nvim/buffer_defs.h" // vimconv_T @@ -827,9 +828,23 @@ DEFINE_VIML_CONV_FUNCTIONS(, echo, garray_T *const, gap) #undef CONV_FLOAT #define CONV_FLOAT(flt) \ do { \ - char numbuf[NUMBUFLEN]; \ - vim_snprintf(numbuf, NUMBUFLEN - 1, "%g", (flt)); \ - ga_concat(gap, numbuf); \ + const float_T flt_ = (flt); \ + switch (fpclassify(flt_)) { \ + case FP_NAN: { \ + EMSG(_("E474: Unable to represent NaN value in JSON")); \ + return FAIL; \ + } \ + case FP_INFINITE: { \ + EMSG(_("E474: Unable to represent infinity in JSON")); \ + return FAIL; \ + } \ + default: { \ + char numbuf[NUMBUFLEN]; \ + vim_snprintf(numbuf, NUMBUFLEN - 1, "%g", flt_); \ + ga_concat(gap, (char_u *) numbuf); \ + break; \ + } \ + } \ } while (0) /// Last used p_enc value diff --git a/test/functional/eval/json_functions_spec.lua b/test/functional/eval/json_functions_spec.lua index 0b0403ce8e..33d177a2b6 100644 --- a/test/functional/eval/json_functions_spec.lua +++ b/test/functional/eval/json_functions_spec.lua @@ -472,6 +472,15 @@ describe('json_encode() function', function() eq('1.0e50', eval('json_encode(1.0e50)')) end) + it('fails to dump NaN and infinite values', function() + eq('Vim(call):E474: Unable to represent NaN value in JSON', + exc_exec('call json_encode(str2float("nan"))')) + eq('Vim(call):E474: Unable to represent infinity in JSON', + exc_exec('call json_encode(str2float("inf"))')) + eq('Vim(call):E474: Unable to represent infinity in JSON', + exc_exec('call json_encode(-str2float("inf"))')) + end) + it('dumps lists', function() eq('[]', funcs.json_encode({})) eq('[[]]', funcs.json_encode({{}})) -- cgit