GVariant: support NULL for empty arrays in varargs

g_variant_new("as", NULL); now gives an empty array of strings, for
example.

This was documented as working already, but was never actually
implemented (due to the fact that it muddies the water when considering
maybe types).  It's being implemented now because its convenience to
programmers exceeds any damage done to the conceptual purity of the API.
This commit is contained in:
Ryan Lortie 2011-02-11 10:14:29 -05:00
parent d25dca2d74
commit b1d02f9323
3 changed files with 55 additions and 18 deletions

View File

@ -681,6 +681,11 @@ g_variant_unref (value);]]></programlisting></informalexample>
prefixed with an '<literal>m</literal>', the type of arguments that are collected does not change in any way, but
<link linkend='NULL--CAPS'><literal>NULL</literal></link> becomes a permissable value, to indicate the Nothing case.
</para>
<para>
Note that the "special exception" introduced in the array section for constructing empty arrays is ignored
here. Using a <literal>NULL</literal> pointer with the format string '<literal>mas</literal>' constructs
the Nothing value -- not an empty array.
</para>
<para>
The second way is used with all other format strings. For
<link linkend='g-variant-new'><function>g_variant_new()</function></link> an additional

View File

@ -3643,6 +3643,7 @@ g_variant_valist_new_nnp (const gchar **str,
switch (*(*str)++)
{
case 'a':
if (ptr != NULL)
{
const GVariantType *type;
GVariant *value;
@ -3667,6 +3668,21 @@ g_variant_valist_new_nnp (const gchar **str,
return value;
}
else
/* special case: NULL pointer for empty array */
{
const GVariantType *type = (GVariantType *) *str;
g_variant_type_string_scan (*str, NULL, str);
if G_UNLIKELY (!g_variant_type_is_definite (type))
g_error ("g_variant_new: NULL pointer given with indefinite "
"array type; unable to determine which type of empty "
"array to construct.");
return g_variant_new_array (type, NULL, 0);
}
case 's':
return g_variant_new_string (ptr);

View File

@ -3331,6 +3331,22 @@ test_varargs (void)
g_variant_unref (value);
}
{
GVariant *value;
gchar *str;
value = g_variant_new ("(masas)", NULL, NULL);
g_variant_ref_sink (value);
str = g_variant_print (value, TRUE);
g_assert_cmpstr (str, ==, "(@mas nothing, @as [])");
g_variant_unref (value);
g_free (str);
if (do_failed_test ("*which type of empty array*"))
g_variant_new ("(a{s*})", NULL);
}
g_variant_type_info_assert_no_infos ();
}