GValue: Add interned string support

This adds support to be able to explicitely stored interned strings into
G_TYPE_STRING GValue.

This is useful for cases where the user:
* *knows* the string to be stored in the GValue is canonical
* Wants to know whther the string stored is canonical

This allows:
* zero-cost GValue copy (the content is guaranteed to be unique and exist
  throughout the process life)
* zero-cost string equality checks (if both string GValue are interned, you just
  need to check the pointers for equality or not, instead of doing a strcmp).

Fixes #2109
This commit is contained in:
Edward Hervey
2020-05-15 07:38:30 +02:00
committed by Edward Hervey
parent c964749de6
commit 1a95ce84ed
5 changed files with 99 additions and 0 deletions

View File

@@ -163,6 +163,50 @@ test_value_string (void)
g_assert_cmpstr (storedstr, ==, static2);
g_value_unset (&value);
/*
* Interned/Canonical strings
*/
static1 = g_intern_static_string (static1);
g_value_init (&value, G_TYPE_STRING);
g_assert_true (G_VALUE_HOLDS_STRING (&value));
g_value_set_interned_string (&value, static1);
g_assert_true (G_VALUE_IS_INTERNED_STRING (&value));
/* The contents should be the string we provided */
storedstr = g_value_get_string (&value);
g_assert_true (storedstr == static1);
/* But g_value_dup_string() should provide a copy */
str2 = g_value_dup_string (&value);
g_assert_true (storedstr != str2);
g_assert_cmpstr (str2, ==, static1);
g_free (str2);
/* Copying an interned string gvalue should *not* copy the contents
* and should still be an interned string */
g_value_init (&copy, G_TYPE_STRING);
g_value_copy (&value, &copy);
g_assert_true (G_VALUE_IS_INTERNED_STRING (&copy));
copystr = g_value_get_string (&copy);
g_assert_true (copystr == static1);
g_value_unset (&copy);
/* Setting a new interned string should change the contents */
static2 = g_intern_static_string (static2);
g_value_set_interned_string (&value, static2);
g_assert_true (G_VALUE_IS_INTERNED_STRING (&value));
/* The contents should be the interned string */
storedstr = g_value_get_string (&value);
g_assert_cmpstr (storedstr, ==, static2);
/* Setting a new regular string should change the contents */
g_value_set_string (&value, static2);
g_assert_false (G_VALUE_IS_INTERNED_STRING (&value));
/* The contents should be a copy of that *new* string */
storedstr = g_value_get_string (&value);
g_assert_true (storedstr != static2);
g_assert_cmpstr (storedstr, ==, static2);
g_value_unset (&value);
}
static gint