Skip to content

array: add support for g_ptr_array_null_terminated()

Thomas Haller requested to merge th/g-ptr-array-set-null-terminated into main

How about this?

GArray supports a "zero_terminated" flag, but GPtrArray doesn't.
This is odd, because especially for a pointer array it makes sense
to have a NULL sentinel. This would be for example useful to track a
strv array with a GPtrArray.

As workaround for this missing features you could use a GArray instead
(ugly) or to explicitly add the NULL sentinel. However the latter increases
the "len" of the array, which can be problematic if you want to still use
the GPtrArray for other purposes.

Add g_ptr_array_null_terminated(). The null-terminated flag cannot be
reverted. Once the GPtrArray is flagged to be %NULL terminated, it sticks.
The purpose is that once a user checks whether a GPtrArray instance
is safe to be treated as a %NULL terminated array, the decision does
not be re-evaluated.

The API g_ptr_array_null_terminated() with the "make_null_terminated"
argument seems odd at first. It is this way because we need both a
set-null-terminated and a get-null-terminated function. The getter
is very useful, because if somebody provides you an GPtrArray of strings
that you'd like to use as a strv array, you need to be able to confirm
whether it is safe to do. Instead of adding two new symbols for a
getter and setter, only function to both enable and retrieve the flag.

The new flag is tracked as a guint8 in GRealPtrArray. On common 64 bit
architectures this does not increase the size of the struct as it fits
in an existing hole. Note that this is not a bitfield because it's
probably more efficient to access the entire guint8. However, there is
still a 3 bytes hole (on common 32 and 64 architectures), so if we need
to add more flags in the future, we still have space for 24 bits,
although we don't make the new flag a bitfield.

The biggest downside of the patch is the runtime overhead that most
operations now need to check whether %NULL termination is requested.

https://gitlab.gnome.org/GNOME/glib/-/issues/353

Example1:

char **
_create (void)
{
    GPtrArray *array;
    int i;

    array = g_ptr_array_new ();
    for (i = 0; i < 1000; i++)
        g_ptr_array_add (array, g_strdup_printf ("%d", i));
    g_ptr_array_null_terminated(array, TRUE);
    return g_ptr_array_free (array, FALSE);
}

Example2:

void
_set_strv_gvalue (GPtrArray *str_array, GValue *out_value)
{
    const char **t;
    const char *dummy = NULL;

    if (g_ptr_array_null_terminated (str_array, FALSE)) {
        g_value_set_boxed (out_value, ((const char *const*) str_array->pdata) ?: &dummy);
        return;
    }
    t = g_new (const char *, str_array->len + 1u);
    memcpy (t, str_array->pdata, (str_array->len + 1u) * sizeof (const char *));
    t[l] = NULL;
    g_value_set_boxed (out_value, t);
    g_free (t);
}
Edited by Philip Withnall

Merge request reports