Variant

glib.Variant is a variant datatype; it can contain one or more values along with information about the type of the values.

A glib.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 glib.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 DBus, or when saving settings using GSettings.

When creating a new glib.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 glib.Variant holding an integer value you can use:

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

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

More advanced examples of glib.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 glib.Variant is glib.VariantType

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

glib.Variant is reference counted using Variant.ref and Variant.unref. glib.Variant also has floating reference counts -- see Variant.refSink.

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

glib.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 glib.Variant data can also be sent over the network.

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

For space-efficiency, the glib.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 glib.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 glib.MappedFile, and call Variant.newFromData on it.

For convenience to C programmers, glib.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 glib.Variant values. glib.Variant includes a printer for this language and a parser with type inferencing.

Memory Use

glib.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 glib.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 glib.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 glib.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 glib.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 glib.HashTable 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

glib.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 glib.Variant This may involve a g_free() or a g_slice_free() or even MappedFile.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 glib.Variant structure is 6 * (void *). On 32-bit systems, that's 24 bytes.

glib.Variant structures only exist if they are explicitly created with API calls. For example, if a glib.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 glib.Variant instance exists -- the one referring to the dictionary.

If calls are made to start accessing the other values then glib.Variant instances will exist for those values only for as long as they are in use (ie: until you call 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 glib.Variant instance, or a total of 160 bytes, plus malloc overhead. If we were to use Variant.getChildValue 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.

class Variant {
protected
bool ownedRef;
}

Constructors

this
this(GVariant* gVariant, bool ownedRef)

Sets our main struct and passes it to the parent class.

this
this(VariantType childType, Variant[] children)

Creates a new glib.Variant array from children.

this
this(bool value)

Creates a new boolean glib.Variant instance -- either TRUE or FALSE.

this
this(ubyte value)

Creates a new byte glib.Variant instance.

this
this(Variant key, Variant value)

Creates a new dictionary entry glib.Variant key and value must be non-NULL. key must be a value of a basic type (ie: not a container).

this
this(double value)

Creates a new double glib.Variant instance.

this
this(VariantType elementType, void* elements, size_t nElements, size_t elementSize)

Constructs a new array glib.Variant instance, where the elements are of element_type type.

this
this(VariantType type, Bytes bytes, bool trusted)

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

this
this(VariantType type, ubyte[] data, bool trusted, GDestroyNotify notify, void* userData)

Creates a new glib.Variant instance from serialised data.

this
this(short value)

Creates a new int16 glib.Variant instance.

this
this(int value)

Creates a new int32 glib.Variant instance.

this
this(long value)

Creates a new int64 glib.Variant instance.

this
this(VariantType childType, Variant child)

Depending on if child is NULL, either wraps child inside of a maybe container or creates a Nothing instance for the given type.

this
this(string format, void** app)

Parses format and returns the result.

this
this(string string_)

Creates a string glib.Variant with the contents of string.

this
this(string[] strv)

Constructs an array of strings glib.Variant from the given array of strings.

this
this(Variant[] children)

Creates a new tuple glib.Variant out of the items in children. The type is determined from the types of children. No entry in the children array may be NULL.

this
this(ushort value)

Creates a new uint16 glib.Variant instance.

this
this(uint value)

Creates a new uint32 glib.Variant instance.

this
this(ulong value)

Creates a new uint64 glib.Variant instance.

this
this(string formatString, string[] endptr, void** app)

This function is intended to be used by libraries based on glib.Variant that want to provide Variant.new-like functionality to their users.

this
this(Variant value)

Boxes value. The result is a glib.Variant instance representing a variant containing the original value.

Destructor

A destructor is present on this object, but not explicitly documented in the source.

Members

Functions

byteswap
Variant byteswap()

Performs a byteswapping operation on the contents of value. The result is that all multi-byte numeric data contained in value is byteswapped. That includes 16, 32, and 64bit signed and unsigned integers as well as file handles and double precision floating point values.

checkFormatString
bool checkFormatString(string formatString, bool copyOnly)

Checks if calling Variant.get with format_string on value would be valid from a type-compatibility standpoint. format_string is assumed to be a valid format string (from a syntactic standpoint).

classify
GVariantClass classify()

Classifies value according to its top-level type.

compare
int compare(Variant two)

Compares one and two.

dupBytestring
string dupBytestring()

Similar to Variant.getBytestring except that instead of returning a constant string, the string is duplicated.

dupBytestringArray
string[] dupBytestringArray()

Gets the contents of an array of array of bytes glib.Variant This call makes a deep copy; the return result should be released with g_strfreev().

dupObjv
string[] dupObjv()

Gets the contents of an array of object paths glib.Variant This call makes a deep copy; the return result should be released with g_strfreev().

dupString
string dupString(size_t length)

Similar to Variant.getString except that instead of returning a constant string, the string is duplicated.

dupStrv
string[] dupStrv()

Gets the contents of an array of strings glib.Variant This call makes a deep copy; the return result should be released with g_strfreev().

equal
bool equal(Variant two)

Checks if one and two have the same type and value.

getBoolean
bool getBoolean()

Returns the boolean value of value.

getByte
ubyte getByte()

Returns the byte value of value.

getBytestring
string getBytestring()

Returns the string value of a glib.Variant instance with an array-of-bytes type. The string has no particular encoding.

getBytestringArray
string[] getBytestringArray()

Gets the contents of an array of array of bytes glib.Variant This call makes a shallow copy; the return result should be released with g_free(), but the individual strings must not be modified.

getChildValue
Variant getChildValue(size_t index)

Reads a child item out of a container glib.Variant instance. This includes variants, maybes, arrays, tuples and dictionary entries. It is an error to call this function on any other type of glib.Variant

getData
void* getData()

Returns a pointer to the serialised form of a glib.Variant instance. The returned data may not be in fully-normalised form if read from an untrusted source. The returned data must not be freed; it remains valid for as long as value exists.

getDataAsBytes
Bytes getDataAsBytes()

Returns a pointer to the serialised form of a glib.Variant instance. The semantics of this function are exactly the same as Variant.getData, except that the returned glib.Bytes holds a reference to the variant data.

getDouble
double getDouble()

Returns the double precision floating point value of value.

getFixedArray
void[] getFixedArray(size_t elementSize)

Provides access to the serialised data for an array of fixed-sized items.

getHandle
int getHandle()

Returns the 32-bit signed integer value of value.

getInt16
short getInt16()

Returns the 16-bit signed integer value of value.

getInt32
int getInt32()

Returns the 32-bit signed integer value of value.

getInt64
long getInt64()

Returns the 64-bit signed integer value of value.

getMaybe
Variant getMaybe()

Given a maybe-typed glib.Variant instance, extract its value. If the value is Nothing, then this function returns NULL.

getNormalForm
Variant getNormalForm()

Gets a glib.Variant instance that has the same value as value and is trusted to be in normal form.

getObjv
string[] getObjv()

Gets the contents of an array of object paths glib.Variant This call makes a shallow copy; the return result should be released with g_free(), but the individual strings must not be modified.

getSize
size_t getSize()

Determines the number of bytes that would be required to store value with Variant.store.

getString
string getString(size_t length)

Returns the string value of a glib.Variant instance with a string type. This includes the types G_VARIANT_TYPE_STRING, G_VARIANT_TYPE_OBJECT_PATH and G_VARIANT_TYPE_SIGNATURE.

getStruct
void* getStruct()

the main Gtk struct as a void*

getStrv
string[] getStrv()

Gets the contents of an array of strings glib.Variant This call makes a shallow copy; the return result should be released with g_free(), but the individual strings must not be modified.

getType
VariantType getType()

Determines the type of value.

getTypeString
string getTypeString()

Returns the type string of value. Unlike the result of calling Variant.typePeekString, this string is nul-terminated. This string belongs to glib.Variant and must not be freed.

getUint16
ushort getUint16()

Returns the 16-bit unsigned integer value of value.

getUint32
uint getUint32()

Returns the 32-bit unsigned integer value of value.

getUint64
ulong getUint64()

Returns the 64-bit unsigned integer value of value.

getVa
void getVa(string formatString, string[] endptr, void** app)

This function is intended to be used by libraries based on glib.Variant that want to provide Variant.get-like functionality to their users.

getVariant
Variant getVariant()

Unboxes value. The result is the glib.Variant instance that was contained in value.

getVariantStruct
GVariant* getVariantStruct(bool transferOwnership)

Get the main Gtk struct

hash
uint hash()

Generates a hash value for a glib.Variant instance.

isContainer
bool isContainer()

Checks if value is a container.

isFloating
bool isFloating()

Checks whether value has a floating reference count.

isNormalForm
bool isNormalForm()

Checks if value is in normal form.

isOfType
bool isOfType(VariantType type)

Checks if a value has a type matching the provided type.

iterNew
VariantIter iterNew()

Creates a heap-allocated glib.VariantIter for iterating over the items in value.

lookupValue
Variant lookupValue(string key, VariantType expectedType)

Looks up a value in a dictionary glib.Variant

nChildren
size_t nChildren()

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

print
string print(bool typeAnnotate)

Pretty-prints value in the format understood by Variant.parse.

printString
StringG printString(StringG string_, bool typeAnnotate)

Behaves as Variant.print, but operates on a GString

refSink
Variant refSink()

glib.Variant uses a floating reference count system. All functions with names starting with g_variant_new_ return floating references.

ref_
Variant ref_()

Increases the reference count of value.

store
void store(void* data)

Stores the serialised form of value at data. data should be large enough. See Variant.getSize.

takeRef
Variant takeRef()

If value is floating, sink it. Otherwise, do nothing.

unref
void unref()

Decreases the reference count of value. When its reference count drops to 0, the memory used by the variant is freed.

Static functions

fromByteString
Variant fromByteString(string byteString)

Creates an array-of-bytes GVariant with the contents of string. This function is just like new Variant(string) except that the string need not be valid utf8.

fromByteStringArray
Variant fromByteStringArray(string[] strv)

Constructs an array of bytestring GVariant from the given array of strings. If length is -1 then strv is null-terminated.

fromObjectPath
Variant fromObjectPath(string path)

Creates a DBus object path GVariant with the contents of string. string must be a valid DBus object path. Use Variant.isObjectPath() if you're not sure.

fromObjv
Variant fromObjv(string[] strv)

Constructs an array of object paths Variant from the given array of strings.

fromSignature
Variant fromSignature(string signature)

Creates a DBus type signature GVariant with the contents of string. string must be a valid DBus type signature. Use Variant.isSignature() if you're not sure.

isObjectPath
bool isObjectPath(string string_)

Determines if a given string is a valid D-Bus object path. You should ensure that a string is a valid D-Bus object path before passing it to Variant.newObjectPath.

isSignature
bool isSignature(string string_)

Determines if a given string is a valid D-Bus type signature. You should ensure that a string is a valid D-Bus type signature before passing it to Variant.newSignature.

parse
Variant parse(VariantType type, string text, string limit, string[] endptr)

Parses a glib.Variant from a text representation.

parseErrorPrintContext
string parseErrorPrintContext(ErrorG error, string sourceStr)

Pretty-prints a message showing the context of a glib.Variant parse error within the string for which parsing was attempted.

parseErrorQuark
GQuark parseErrorQuark()
parserGetErrorQuark
GQuark parserGetErrorQuark()

Same as Variant.errorQuark.

Variables

gVariant
GVariant* gVariant;

the main Gtk struct

Meta

Since

2.24