GKeyFile: allow loading from empty strings
authorRyan Lortie <desrt@desrt.ca>
Thu, 26 Jan 2012 16:27:47 +0000 (11:27 -0500)
committerRyan Lortie <desrt@desrt.ca>
Thu, 26 Jan 2012 19:40:34 +0000 (14:40 -0500)
GKeyFile supports empty files and also supports loading from the string
"", but will fail with a critical if you try:

  - explicit length == 0
  - data == NULL

length == 0 should always be valid, and data == NULL should be valid in
the case that length == 0, so add some testcases for those and fix the
code up to allow them.

https://bugzilla.gnome.org/show_bug.cgi?id=668756

glib/gkeyfile.c
glib/tests/keyfile.c

index 33b3c36..7b1f595 100644 (file)
@@ -885,8 +885,7 @@ g_key_file_load_from_data (GKeyFile       *key_file,
   gchar list_separator;
 
   g_return_val_if_fail (key_file != NULL, FALSE);
-  g_return_val_if_fail (data != NULL, FALSE);
-  g_return_val_if_fail (length != 0, FALSE);
+  g_return_val_if_fail (data != NULL || length == 0, FALSE);
 
   if (length == (gsize)-1)
     length = strlen (data);
@@ -1354,7 +1353,7 @@ g_key_file_parse_data (GKeyFile     *key_file,
   gsize i;
 
   g_return_if_fail (key_file != NULL);
-  g_return_if_fail (data != NULL);
+  g_return_if_fail (data != NULL || length == 0);
 
   parse_error = NULL;
 
index 9f40236..b06a1c0 100644 (file)
@@ -1455,6 +1455,31 @@ test_list_separator (void)
   g_key_file_unref (keyfile);
 }
 
+static void
+test_empty_string (void)
+{
+  GError *error = NULL;
+  GKeyFile *kf;
+
+  kf = g_key_file_new ();
+
+  g_key_file_load_from_data (kf, "", 0, 0, &error);
+  g_assert_no_error (error);
+
+  g_key_file_load_from_data (kf, "", -1, 0, &error);
+  g_assert_no_error (error);
+
+  /* NULL is a fine pointer to use if length is zero */
+  g_key_file_load_from_data (kf, NULL, 0, 0, &error);
+  g_assert_no_error (error);
+
+  /* should not attempt to access non-NULL pointer if length is zero */
+  g_key_file_load_from_data (kf, GINT_TO_POINTER (1), 0, 0, &error);
+  g_assert_no_error (error);
+
+  g_key_file_unref (kf);
+}
+
 int
 main (int argc, char *argv[])
 {
@@ -1489,7 +1514,7 @@ main (int argc, char *argv[])
   g_test_add_func ("/keyfile/ref", test_ref);
   g_test_add_func ("/keyfile/replace-value", test_replace_value);
   g_test_add_func ("/keyfile/list-separator", test_list_separator);
-
+  g_test_add_func ("/keyfile/empty-string", test_empty_string);
 
   return g_test_run ();
 }