Struct glib::variant::Variant[][src]

pub struct Variant(_);
Expand description

A generic immutable value capable of carrying various types.

See the module documentation for more details. Variant is a variant datatype; it can contain one or more values along with information about the type of the values.

A Variant may contain simple types, like an integer, or a boolean value; or complex types, like an array of two strings, or a dictionary of key value pairs. A Variant is also immutable: once it’s been created neither its type nor its content can be modified further.

GVariant is useful whenever data needs to be serialized, for example when sending method parameters in D-Bus, or when saving settings using GSettings.

When creating a new Variant, you pass the data you want to store in it along with a string representing the type of data you wish to pass to it.

For instance, if you want to create a Variant holding an integer value you can use:

⚠️ The following code is in C ⚠️

  GVariant *v = g_variant_new ("u", 40);

The string “u” in the first argument tells Variant that the data passed to the constructor (40) is going to be an unsigned integer.

More advanced examples of Variant in use can be found in documentation for [GVariant format strings][gvariant-format-strings-pointers].

The range of possible values is determined by the type.

The type system used by Variant is VariantType.

Variant instances always have a type and a value (which are given at construction time). The type and value of a Variant instance can never change other than by the Variant itself being destroyed. A Variant cannot contain a pointer.

Variant is reference counted using g_variant_ref() and g_variant_unref(). Variant also has floating reference counts – see [ref_sink()][Self::ref_sink()].

Variant is completely threadsafe. A Variant instance can be concurrently accessed in any way from any number of threads without problems.

Variant is heavily optimised for dealing with data in serialised form. It works particularly well with data located in memory-mapped files. It can perform nearly all deserialisation operations in a small constant time, usually touching only a single memory page. Serialised Variant data can also be sent over the network.

Variant is largely compatible with D-Bus. Almost all types of Variant instances can be sent over D-Bus. See VariantType for exceptions. (However, Variant’s serialisation format is not the same as the serialisation format of a D-Bus message body: use GDBusMessage, in the gio library, for those.)

For space-efficiency, the Variant serialisation format does not automatically include the variant’s length, type or endianness, which must either be implied from context (such as knowledge that a particular file format always contains a little-endian G_VARIANT_TYPE_VARIANT which occupies the whole length of the file) or supplied out-of-band (for instance, a length, type and/or endianness indicator could be placed at the beginning of a file, network message or network stream).

A Variant’s size is limited mainly by any lower level operating system constraints, such as the number of bits in gsize. For example, it is reasonable to have a 2GB file mapped into memory with GMappedFile, and call [from_data()][Self::from_data()] on it.

For convenience to C programmers, Variant features powerful varargs-based value construction and destruction. This feature is designed to be embedded in other libraries.

There is a Python-inspired text language for describing Variant values. Variant includes a printer for this language and a parser with type inferencing.

Memory Use

Variant tries to be quite efficient with respect to memory use. This section gives a rough idea of how much memory is used by the current implementation. The information here is subject to change in the future.

The memory allocated by Variant can be grouped into 4 broad purposes: memory for serialised data, memory for the type information cache, buffer management memory and memory for the Variant structure itself.

Serialised Data Memory

This is the memory that is used for storing GVariant data in serialised form. This is what would be sent over the network or what would end up on disk, not counting any indicator of the endianness, or of the length or type of the top-level variant.

The amount of memory required to store a boolean is 1 byte. 16, 32 and 64 bit integers and double precision floating point numbers use their “natural” size. Strings (including object path and signature strings) are stored with a nul terminator, and as such use the length of the string plus 1 byte.

Maybe types use no space at all to represent the null value and use the same amount of space (sometimes plus one byte) as the equivalent non-maybe-typed value to represent the non-null case.

Arrays use the amount of space required to store each of their members, concatenated. Additionally, if the items stored in an array are not of a fixed-size (ie: strings, other arrays, etc) then an additional framing offset is stored for each item. The size of this offset is either 1, 2 or 4 bytes depending on the overall size of the container. Additionally, extra padding bytes are added as required for alignment of child values.

Tuples (including dictionary entries) use the amount of space required to store each of their members, concatenated, plus one framing offset (as per arrays) for each non-fixed-sized item in the tuple, except for the last one. Additionally, extra padding bytes are added as required for alignment of child values.

Variants use the same amount of space as the item inside of the variant, plus 1 byte, plus the length of the type string for the item inside the variant.

As an example, consider a dictionary mapping strings to variants. In the case that the dictionary is empty, 0 bytes are required for the serialisation.

If we add an item “width” that maps to the int32 value of 500 then we will use 4 byte to store the int32 (so 6 for the variant containing it) and 6 bytes for the string. The variant must be aligned to 8 after the 6 bytes of the string, so that’s 2 extra bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used for the dictionary entry. An additional 1 byte is added to the array as a framing offset making a total of 15 bytes.

If we add another entry, “title” that maps to a nullable string that happens to have a value of null, then we use 0 bytes for the null value (and 3 bytes for the variant to contain it along with its type string) plus 6 bytes for the string. Again, we need 2 padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes.

We now require extra padding between the two items in the array. After the 14 bytes of the first item, that’s 2 bytes required. We now require 2 framing offsets for an extra two bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item dictionary.

Type Information Cache

For each GVariant type that currently exists in the program a type information structure is kept in the type information cache. The type information structure is required for rapid deserialisation.

Continuing with the above example, if a Variant exists with the type “a{sv}” then a type information struct will exist for “a{sv}”, “{sv}”, “s”, and “v”. Multiple uses of the same type will share the same type information. Additionally, all single-digit types are stored in read-only static memory and do not contribute to the writable memory footprint of a program using Variant.

Aside from the type information structures stored in read-only memory, there are two forms of type information. One is used for container types where there is a single element type: arrays and maybe types. The other is used for container types where there are multiple element types: tuples and dictionary entries.

Array type info structures are 6 * sizeof (void *), plus the memory required to store the type string itself. This means that on 32-bit systems, the cache entry for “a{sv}” would require 30 bytes of memory (plus malloc overhead).

Tuple type info structures are 6 * sizeof (void *), plus 4 * sizeof (void *) for each item in the tuple, plus the memory required to store the type string itself. A 2-item tuple, for example, would have a type information structure that consumed writable memory in the size of 14 * sizeof (void *) (plus type string) This means that on 32-bit systems, the cache entry for “{sv}” would require 61 bytes of memory (plus malloc overhead).

This means that in total, for our “a{sv}” example, 91 bytes of type information would be allocated.

The type information cache, additionally, uses a GHashTable to store and look up the cached items and stores a pointer to this hash table in static storage. The hash table is freed when there are zero items in the type cache.

Although these sizes may seem large it is important to remember that a program will probably only have a very small number of different types of values in it and that only one type information structure is required for many different values of the same type.

Buffer Management Memory

Variant uses an internal buffer management structure to deal with the various different possible sources of serialised data that it uses. The buffer is responsible for ensuring that the correct call is made when the data is no longer in use by Variant. This may involve a g_free() or a g_slice_free() or even g_mapped_file_unref().

One buffer management structure is used for each chunk of serialised data. The size of the buffer management structure is 4 * (void *). On 32-bit systems, that’s 16 bytes.

GVariant structure

The size of a Variant structure is 6 * (void *). On 32-bit systems, that’s 24 bytes.

Variant structures only exist if they are explicitly created with API calls. For example, if a Variant is constructed out of serialised data for the example given above (with the dictionary) then although there are 9 individual values that comprise the entire dictionary (two keys, two values, two variants containing the values, two dictionary entries, plus the dictionary itself), only 1 Variant instance exists – the one referring to the dictionary.

If calls are made to start accessing the other values then Variant instances will exist for those values only for as long as they are in use (ie: until you call g_variant_unref()). The type information is shared. The serialised data and the buffer management structure for that serialised data is shared by the child.

Summary

To put the entire example together, for our dictionary mapping strings to variants (with two entries, as given above), we are using 91 bytes of memory for type information, 29 bytes of memory for the serialised data, 16 bytes for buffer management and 24 bytes for the Variant instance, or a total of 160 bytes, plus malloc overhead. If we were to use child_value() to access the two dictionary entries, we would use an additional 48 bytes. If we were to have other dictionaries of the same type, we would use more memory for the serialised data and buffer management for those dictionaries, but the type information would be shared.

Implementations

Returns the type of the value. Determines the type of self.

The return value is valid for the lifetime of self and must not be freed.

Returns

a VariantType

Returns true if the type of the value corresponds to T.

Tries to extract a value of type T.

Returns Some if T matches the variant’s type. Deconstructs a Variant instance.

Think of this function as an analogue to scanf().

The arguments that are expected by this function are entirely determined by format_string. format_string also restricts the permissible types of self. It is an error to give a value with an incompatible type. See the section on [GVariant format strings][gvariant-format-strings]. Please note that the syntax of the format string is very likely to be extended in the future.

format_string determines the C types that are used for unpacking the values and also determines if the values are copied or borrowed, see the section on [GVariant format strings][gvariant-format-strings-pointers].

format_string

a Variant format string

Boxes value.

Unboxes self.

Returns Some if self contains a Variant.

Reads a child item out of a container Variant instance.

Panics

  • if self is not a container type.
  • if given index is larger than number of children. Reads a child item out of a container Variant instance. This includes variants, maybes, arrays, tuples and dictionary entries. It is an error to call this function on any other type of Variant.

It is an error if index_ is greater than the number of child items in the container. See n_children().

The returned value is never floating. You should free it with g_variant_unref() when you’re done with it.

Note that values borrowed from the returned child are not guaranteed to still be valid after the child is freed even if you still hold a reference to self, if self has not been serialised at the time this function is called. To avoid this, you can serialize self by calling [data()][Self::data()] and optionally ignoring the return value.

There may be implementation specific restrictions on deeply nested values, which would result in the unit tuple being returned as the child value, instead of further nested children. Variant is guaranteed to handle nesting up to at least 64 levels.

This function is O(1).

index_

the index of the child to fetch

Returns

the child at the specified index

Tries to extract a &str.

Returns Some if the variant has a string type (s, o or g type strings).

Creates a new GVariant array from children.

All children must be of type T.

Creates a new GVariant tuple from children.

Creates a new maybe Variant.

Constructs a new serialised-mode GVariant instance. Constructs a new serialised-mode Variant instance. This is the inner interface for creation of new serialised values that gets called from various functions in gvariant.c.

A reference is taken on bytes.

The data in bytes must be aligned appropriately for the type_ being loaded. Otherwise this function will internally create a copy of the memory (since GLib 2.60) or (in older versions) fail and exit the process.

type_

a VariantType

bytes

a Bytes

trusted

if the contents of bytes are trusted

Returns

a new Variant with a floating reference

Constructs a new serialised-mode GVariant instance.

This is the same as from_bytes, except that checks on the passed data are skipped.

You should not use this function on data from external sources.

Safety

Since the data is not validated, this is potentially dangerous if called on bytes which are not guaranteed to have come from serialising another Variant. The caller is responsible for ensuring bad data is not passed in.

Returns the serialised form of a GVariant instance. Returns a pointer to the serialised form of a Variant instance. The semantics of this function are exactly the same as [data()][Self::data()], except that the returned Bytes holds a reference to the variant data.

Returns

A new Bytes representing the variant data

Determines the number of children in a container GVariant instance. Determines the number of children in a container Variant instance. This includes variants, maybes, arrays, tuples and dictionary entries. It is an error to call this function on any other type of Variant.

For variants, the return value is always 1. For values with maybe types, it is always zero or one. For arrays, it is the length of the array. For tuples it is the number of tuple items (which depends only on the type). For dictionary entries, it is always 2

This function is O(1).

Returns

the number of children in the container

Create an iterator over items in the variant.

Variant has a container type. Checks if self is a container.

Returns

true if self is a container

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Formats the value using the given formatter. Read more

Performs the conversion.

Tries to extract a value. Read more

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Returns the type identifier of Self.

Returns the VariantType corresponding to Self.

Returns a Variant clone of self.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

Returns a SendValue clone of self.

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.