Re: Function completion for GVariant maybe types?



hi Markus,

On Tue, 2011-10-11 at 12:12 +0200, Markus Elfring wrote:
> > If you have a GVariant* variable, you should usually know what type it is already,
> > but if not, g_variant_get_type() will tell you.
> 
> Is a direct use of a function like "g_variant_type_is_maybe" recommended?

Yes.  It's there for exactly this reason.

I considered adding g_variant_is_array, g_variant_is_maybe,
g_variant_is_tuple, g_variant_is_variant, g_variant_is_int32,
g_variant_is_uint32, .... but you can see why I wanted to avoid that.

If you want to find out things about the type of a GVariant then of
course the GVariantType API is the correct and appropriate way to go
about it.

> > GVariants are immutable. Once a GVariant instance has been created, you can't
> > change its value/contents - you can only throw it away and create a new GVariant.
> 
> Thanks for your clarification.
> 
> I am still interested in an addition to the interface "g_variant_new_maybe".

What addition?

> > You can reset a (GVariant *) variable to point to a variant representing
> > "nothing" the same way you'd make it point to anything else.
> 
> I imagine that this approach can be improved a bit.
> 
> How do you think about an interface like the following?
> 
> GVariant* g_variant_set_to_nothing(GVariant const * gv);

The name is a bit misleading because in our APIs _set_*() tends to mean
that you're modifying an object in some way (which is not what happens
here).

It's also worth noting that the new and the old object have absolutely
nothing in common except for their type -- which suggests that you
should just use the GVariantType interface to get what you want:

g_variant_new_maybe (g_variant_type_element (g_variant_get_type (gv), NULL);

(ie: create a new maybe-typed GVariant with no child value with the
element type equal to the element type of another GVariant 'gv').

> If the passed instance is a maybe type already, its "container" will be removed
> while the contained type will be kept. (I would like to avoid the nesting of a
> maybe type into another one.)

This is complicated.  Your desire to avoid the nesting of maybe types is
understandable, but would introduce some inconsistency if we added it in
the API.  If you want to do that in your own code then it is very easy:

{
  GVariantType *type;
  GVariant *new_val;

  type = g_variant_get_type (gv);

  /* if the type is already a maybe type, strip off
   * the extra layer to avoid nested maybe types.
   */
  if (g_variant_type_is_maybe (type))
    type = g_variant_element (type);

  /* create a new 'nothing' value of the correct type */
  new_val = g_variant_new_maybe (type, NULL);
}

Note that you don't need to free 'type' anywhere here due to how
GVariantType works internally to avoid copies.

Cheers



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]