Add g_variant_new_printf

Add a quick way to get a floating GVariant from printf formatting.
This commit is contained in:
Ryan Lortie 2013-07-11 12:16:44 -04:00
parent 542099b5ad
commit 1c586e44be
4 changed files with 63 additions and 0 deletions

View File

@ -3117,6 +3117,7 @@ g_variant_new_handle
g_variant_new_double
g_variant_new_string
g_variant_new_take_string
g_variant_new_printf
g_variant_new_object_path
g_variant_is_object_path
g_variant_new_signature

View File

@ -1309,6 +1309,44 @@ g_variant_new_take_string (gchar *string)
return value;
}
/**
* g_variant_new_printf: (skip)
* @format_string: a printf-style format string
* @...: arguments for @format_string
*
* Creates a string-type GVariant using printf formatting.
*
* This is similar to calling g_strdup_printf() and then
* g_variant_new_string() but it saves a temporary variable and an
* unnecessary copy.
*
* Returns: (transfer none): a floating reference to a new string
* #GVariant instance
*
* Since: 2.38
**/
GVariant *
g_variant_new_printf (const gchar *format_string,
...)
{
GVariant *value;
GBytes *bytes;
gchar *string;
va_list ap;
g_return_val_if_fail (format_string != NULL, NULL);
va_start (ap, format_string);
string = g_strdup_vprintf (format_string, ap);
va_end (ap);
bytes = g_bytes_new_take (string, strlen (string) + 1);
value = g_variant_new_from_bytes (G_VARIANT_TYPE_STRING, bytes, TRUE);
g_bytes_unref (bytes);
return value;
}
/**
* g_variant_new_object_path:
* @object_path: a normal C nul-terminated string

View File

@ -103,6 +103,9 @@ GLIB_AVAILABLE_IN_ALL
GVariant * g_variant_new_string (const gchar *string);
GLIB_AVAILABLE_IN_2_38
GVariant * g_variant_new_take_string (gchar *string);
GLIB_AVAILABLE_IN_2_38
GVariant * g_variant_new_printf (const gchar *format_string,
...) G_GNUC_PRINTF (1, 2);
GLIB_AVAILABLE_IN_ALL
GVariant * g_variant_new_object_path (const gchar *object_path);
GLIB_AVAILABLE_IN_ALL

View File

@ -2716,6 +2716,26 @@ test_container (void)
g_free (s1);
}
static void
test_string (void)
{
/* Test some different methods of creating strings */
GVariant *v;
v = g_variant_new_string ("foo");
g_assert_cmpstr (g_variant_get_string (v, NULL), ==, "foo");
g_variant_unref (v);
v = g_variant_new_take_string (g_strdup ("foo"));
g_assert_cmpstr (g_variant_get_string (v, NULL), ==, "foo");
g_variant_unref (v);
v = g_variant_new_printf ("%s %d", "foo", 123);
g_assert_cmpstr (g_variant_get_string (v, NULL), ==, "foo 123");
g_variant_unref (v);
}
static void
test_utf8 (void)
{
@ -4332,6 +4352,7 @@ main (int argc, char **argv)
g_free (testname);
}
g_test_add_func ("/gvariant/string", test_string);
g_test_add_func ("/gvariant/utf8", test_utf8);
g_test_add_func ("/gvariant/containers", test_containers);
g_test_add_func ("/gvariant/format-strings", test_format_strings);