Add g_set_string for simplified and correct property setters
This is a humble request that we add a g_set_string()
API for GNOME 44 so that we significantly reduce the number of broken string setter implementations out there.
Just to get the discussion started, proposed API and implementation.
static inline gboolean
g_set_string (char **dest, const char *src)
{
char *copy;
if (*dest == str || g_strcmp0 (*dest, src) == 0)
return FALSE;
copy = g_strdup (src);
g_free (*dest);
*dest = copy;
return TRUE;
}
Why?
Because I see so much broken string setters in code across our platform, including a ton by myself. Generally, people do something like the following (if you're lucky enough to even find that).
if (g_strcmp0 (self->value, value) != 0)
{
g_free (self->value);
self->value = g_strdup (value);
g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_VALUE]);
}
That looks good and all, but still fails upon re-entrant code like:
const char *value = object_get_value (obj);
object_set_value (obj, &value[1]);
as you'll now free value before copying.
We can make those code both safer and smaller by just doing:
if (g_set_string (&self->value, value))
g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_VALUE]);
Think of this as a stop-gap until we get better property abstractions in GObject.