From ff112e924cf648f9147c674360c9993dec53136e Mon Sep 17 00:00:00 2001 From: Mark Nauwelaerts Date: Thu, 26 Jan 2023 11:23:32 +0100 Subject: generator: ensure valid output double exponential notation Fixes #67 --- json-glib/json-generator.c | 7 ++++++- json-glib/tests/generator.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/json-glib/json-generator.c b/json-glib/json-generator.c index 40e9b02..eef41a7 100644 --- a/json-glib/json-generator.c +++ b/json-glib/json-generator.c @@ -360,7 +360,12 @@ dump_value (GString *buffer, g_ascii_dtostr (buf, sizeof (buf), json_value_get_double (value))); /* ensure doubles don't become ints */ - if (g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, ".") == NULL) + /* also make sure not to append .0 that results in invalid exponential notation + * since the numbers should be decimal, a hex 'e' or "E" can not be mistaken + */ + if (g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, ".") == NULL && + g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, "e") == NULL && + g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, "E") == NULL) { g_string_append (buffer, ".0"); } diff --git a/json-glib/tests/generator.c b/json-glib/tests/generator.c index 034de5a..db27b1a 100644 --- a/json-glib/tests/generator.c +++ b/json-glib/tests/generator.c @@ -350,6 +350,33 @@ test_double_stays_double (void) json_node_free (node); } +static void +test_double_valid (void) +{ + gchar *str; + JsonNode *node = json_node_new (JSON_NODE_VALUE); + JsonGenerator *generator = json_generator_new (); + + json_node_set_double (node, 1e-8); + json_generator_set_root (generator, node); + + str = json_generator_to_data (generator, NULL); + g_test_message ("%s: value: '%.2f' - string: '%s'", + G_STRFUNC, + json_node_get_double (node), + str); + + /* should be valid double + * in particular; no trailing .0 for exponential notation */ + gchar *end = NULL; + g_ascii_strtod(str, &end); + g_assert_cmpint (0, ==, *end); + + g_free (str); + g_object_unref (generator); + json_node_free (node); +} + static void test_pretty (void) @@ -439,6 +466,7 @@ main (int argc, g_test_add_func ("/generator/nested-object", test_nested_object); g_test_add_func ("/generator/decimal-separator", test_decimal_separator); g_test_add_func ("/generator/double-stays-double", test_double_stays_double); + g_test_add_func ("/generator/double-valid", test_double_valid); g_test_add_func ("/generator/pretty", test_pretty); for (guint i = 0; i < G_N_ELEMENTS (string_fixtures); i++) -- cgit v1.2.1