glib.variant
Module for [Variant] class
Types 2
[glib.variant.Variant] is a variant datatype; it can contain one or more values along with information about the type of the values.
A [glib.variant.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.Variant] is also immutable: once it’s been created neither its type nor its content can be modified further.
[glib.variant.Variant] is useful whenever data needs to be serialized, for example when sending method parameters in D-Bus, or when saving settings using [[gio.settings.Settings]](../gio/class.Settings.html).
When creating a new [glib.variant.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.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.Variant] that the data passed to the constructor (40) is going to be an unsigned integer.
More advanced examples of [glib.variant.Variant] in use can be found in documentation for [[glib.variant.Variant] format strings](gvariant-format-strings.html#pointers).
The range of possible values is determined by the type.
The type system used by [glib.variant.Variant] is [glib.variant_type.VariantType].
[glib.variant.Variant] instances always have a type and a value (which are given at construction time). The type and value of a [glib.variant.Variant] instance can never change other than by the [glib.variant.Variant] itself being destroyed. A [glib.variant.Variant] cannot contain a pointer.
[glib.variant.Variant] is reference counted using [glib.variant.Variant.ref_] and [glib.variant.Variant.unref]. [glib.variant.Variant] also has floating reference counts — see [glib.variant.Variant.refSink].
[glib.variant.Variant] is completely threadsafe. A [glib.variant.Variant] instance can be concurrently accessed in any way from any number of threads without problems.
[glib.variant.Variant] is heavily optimised for dealing with data in serialized form. It works particularly well with data located in memory-mapped files. It can perform nearly all deserialization operations in a small constant time, usually touching only a single memory page. Serialized [glib.variant.Variant] data can also be sent over the network.
[glib.variant.Variant] is largely compatible with D-Bus. Almost all types of [glib.variant.Variant] instances can be sent over D-Bus. See [glib.variant_type.VariantType] for exceptions. (However, [glib.variant.Variant]’s serialization format is not the same as the serialization format of a D-Bus message body: use
GDBusMessage, in the GIO library, for those.)For space-efficiency, the [glib.variant.Variant] serialization 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.Variant]’s size is limited mainly by any lower level operating system constraints, such as the number of bits in [gobject.types.size_t]. For example, it is reasonable to have a 2GB file mapped into memory with [glib.mapped_file.MappedFile], and call [glib.variant.Variant.newFromData] on it.
For convenience to C programmers, [glib.variant.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.Variant] values. [glib.variant.Variant] includes a printer for this language and a parser with type inferencing.
Memory Use
[glib.variant.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.Variant] can be grouped into 4 broad purposes: memory for serialized data, memory for the type information cache, buffer management memory and memory for the [glib.variant.Variant] structure itself.
Serialized Data Memory
This is the memory that is used for storing [glib.variant.Variant] data in serialized 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 serialization.
If we add an item ‘width’ that maps to the int32 value of 500 then we will use 4 bytes 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 [glib.variant.Variant] 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 deserialization.
Continuing with the above example, if a [glib.variant.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.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 allocation 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 allocation 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.hash_table.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.Variant] uses an internal buffer management structure to deal with the various different possible sources of serialized 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.Variant]. This may involve a func@GLib.free or even [glib.mapped_file.MappedFile.unref].
One buffer management structure is used for each chunk of serialized 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.Variant] structure is 6 * (void *). On 32-bit systems, that’s 24 bytes.
[glib.variant.Variant] structures only exist if they are explicitly created with API calls. For example, if a [glib.variant.Variant] is constructed out of serialized 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.Variant] instance exists — the one referring to the dictionary.
If calls are made to start accessing the other values then [glib.variant.Variant] instances will exist for those values only for as long as they are in use (ie: until you call [glib.variant.Variant.unref]). The type information is shared. The serialized data and the buffer management structure for that serialized 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 serialized data, 16 bytes for buffer management and 24 bytes for the [glib.variant.Variant] instance, or a total of 160 bytes, plus allocation overhead. If we were to use [glib.variant.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 serialized data and buffer management for those dictionaries, but the type information would be shared.
GVariant * _cInstancePtrVariant newTuple(T...)(T vals) if (isTypeTuple!T)Template to create a new tuple Variant from one or more values. Params: T = The D types to create the tuple variant from vals = The values to assignbool opEquals(Object other)int opCmp(Object other)string toString()T get(T)()Template to get a single value from a Variant Params: T = The D type of the value to get Returns: The single value of the Variant of type `T`auto get(T...)() if (T.length > 1)Template to get multiple values from a container Variant. Params: T = The D types of the values to get Returns: A tuple containing the values from the Variant of the specified typesauto getItems(T...)()Template to get one or more values from a container Variant. Params: T = The D types of the values to get Returns: A tuple containing the values from the Variant of the specified typesglib.variant.Variant newArray(glib.variant_type.VariantType childType = null, glib.variant.Variant[] children = null)Creates a new #GVariant array from children.glib.variant.Variant newBoolean(bool value)Creates a new boolean #GVariant instance -- either true or false.glib.variant.Variant newByte(ubyte value)Creates a new byte #GVariant instance.glib.variant.Variant newBytestring(string string_)Creates an array-of-bytes #GVariant with the contents of string. This function is just like [glib.variant.Variant.newString] except that the string need not be valid UTF-8.glib.variant.Variant newBytestringArray(string[] strv)Constructs an array of bytestring #GVariant from the given array of strings.glib.variant.Variant newDictEntry(glib.variant.Variant key, glib.variant.Variant value)Creates a new dictionary entry #GVariant. key and value must be non-null. key must be a value of a basic type (ie: not a container).glib.variant.Variant newDouble(double value)Creates a new double #GVariant instance.glib.variant.Variant newFixedArray(glib.variant_type.VariantType elementType, const(void) * elements, size_t nElements, size_t elementSize)Constructs a new array #GVariant instance, where the elements are of element_type type.glib.variant.Variant newFromBytes(glib.variant_type.VariantType type, glib.bytes.Bytes bytes, bool trusted)Constructs a new serialized-mode #GVariant instance. This is the inner interface for creation of new serialized values that gets called from various functions in gvariant.c.glib.variant.Variant newHandle(int value)Creates a new handle #GVariant instance.glib.variant.Variant newInt16(short value)Creates a new int16 #GVariant instance.glib.variant.Variant newInt32(int value)Creates a new int32 #GVariant instance.glib.variant.Variant newInt64(long value)Creates a new int64 #GVariant instance.glib.variant.Variant newMaybe(glib.variant_type.VariantType childType = null, glib.variant.Variant child = null)Depending on if child is null, either wraps child inside of a maybe container or creates a Nothing instance for the given type.glib.variant.Variant newObjectPath(string objectPath)Creates a D-Bus object path #GVariant with the contents of objectpath. objectpath must be a valid D-Bus object path. Use [glib.variant.Variant.isObjectPath] if you're not sure.glib.variant.Variant newObjv(string[] strv)Constructs an array of object paths #GVariant from the given array of strings.glib.variant.Variant newSignature(string signature)Creates a D-Bus type signature #GVariant with the contents of string. string must be a valid D-Bus type signature. Use [glib.variant.Variant.isSignature] if you're not sure.glib.variant.Variant newString(string string_)Creates a string #GVariant with the contents of string.glib.variant.Variant newStrv(string[] strv)Constructs an array of strings #GVariant from the given array of strings.glib.variant.Variant newTuple(glib.variant.Variant[] children)Creates a new tuple #GVariant out of the items in children. The type is determined from the types of children. No entry in the children array may be null.glib.variant.Variant newUint16(ushort value)Creates a new uint16 #GVariant instance.glib.variant.Variant newUint32(uint value)Creates a new uint32 #GVariant instance.glib.variant.Variant newUint64(ulong value)Creates a new uint64 #GVariant instance.glib.variant.Variant newVariant(glib.variant.Variant value)Boxes value. The result is a #GVariant instance representing a variant containing the original value.glib.variant.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 i...bool checkFormatString(string formatString, bool copyOnly)Checks if calling [glib.variant.Variant.get] with formatstring on value would be valid from a type-compatibility standpoint. formatstring is assumed to be a valid format string (from a syntactic s...glib.types.VariantClass classify()Classifies value according to its top-level type. Returns: the #GVariantClass of valueint compare(glib.variant.Variant two)Compares one and two.ubyte[] dupBytestring()Similar to [glib.variant.Variant.getBytestring] except that instead of returning a constant string, the string is duplicated.string[] dupBytestringArray()Gets the contents of an array of array of bytes #GVariant. This call makes a deep copy; the return result should be released with [glib.global.strfreev].string[] dupObjv()Gets the contents of an array of object paths #GVariant. This call makes a deep copy; the return result should be released with [glib.global.strfreev].string[] dupStrv()Gets the contents of an array of strings #GVariant. This call makes a deep copy; the return result should be released with [glib.global.strfreev].bool equal(glib.variant.Variant two)Checks if one and two have the same type and value.bool getBoolean()Returns the boolean value of value.ubyte getByte()Returns the byte value of value.string getBytestring()Returns the string value of a #GVariant instance with an array-of-bytes type. The string has no particular encoding.string[] getBytestringArray()Gets the contents of an array of array of bytes #GVariant. This call makes a shallow copy; the return result should be released with [glib.global.gfree], but the individual strings must not be mod...glib.variant.Variant getChildValue(size_t index)Reads a child item out of a container #GVariant instance. This includes variants, maybes, arrays, tuples and dictionary entries. It is an error to call this function on any other type of #GVariant.const(void) * getData()Returns a pointer to the serialized form of a #GVariant 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 re...glib.bytes.Bytes getDataAsBytes()Returns a pointer to the serialized form of a #GVariant instance. The semantics of this function are exactly the same as [glib.variant.Variant.getData], except that the returned #GBytes holds a ref...double getDouble()Returns the double precision floating point value of value.int getHandle()Returns the 32-bit signed integer value of value.short getInt16()Returns the 16-bit signed integer value of value.int getInt32()Returns the 32-bit signed integer value of value.long getInt64()Returns the 64-bit signed integer value of value.glib.variant.Variant getMaybe()Given a maybe-typed #GVariant instance, extract its value. If the value is Nothing, then this function returns null. Returns: the contents of value, or nullglib.variant.Variant getNormalForm()Gets a #GVariant instance that has the same value as value and is trusted to be in normal form.string[] getObjv()Gets the contents of an array of object paths #GVariant. This call makes a shallow copy; the return result should be released with [glib.global.gfree], but the individual strings must not be modif...size_t getSize()Determines the number of bytes that would be required to store value with [glib.variant.Variant.store].string getString()Returns the string value of a #GVariant instance with a string type. This includes the types `GVARIANTTYPESTRING`, `GVARIANTTYPEOBJECTPATH` and `GVARIANTTYPESIGNATURE`.string[] getStrv()Gets the contents of an array of strings #GVariant. This call makes a shallow copy; the return result should be released with [glib.global.gfree], but the individual strings must not be modified.glib.variant_type.VariantType getType()Determines the type of value.string getTypeString()Returns the type string of value. Unlike the result of calling [glib.variant_type.VariantType.peekString], this string is nul-terminated. This string belongs to #GVariant and must not be freed. R...ushort getUint16()Returns the 16-bit unsigned integer value of value.uint getUint32()Returns the 32-bit unsigned integer value of value.ulong getUint64()Returns the 64-bit unsigned integer value of value.glib.variant.Variant getVariant()Unboxes value. The result is the #GVariant instance that was contained in value. Returns: the item contained in the variantuint hash()Generates a hash value for a #GVariant instance.bool isContainer()Checks if value is a container. Returns: true if value is a containerbool isFloating()Checks whether value has a floating reference count.bool isNormalForm()Checks if value is in normal form.bool isOfType(glib.variant_type.VariantType type)Checks if a value has a type matching the provided type.glib.variant.Variant lookupValue(string key, glib.variant_type.VariantType expectedType = null)Looks up a value in a dictionary #GVariant.size_t nChildren()Determines the number of children in a container #GVariant instance. This includes variants, maybes, arrays, tuples and dictionary entries. It is an error to call this function on any other type o...string print(bool typeAnnotate)Pretty-prints value in the format understood by [glib.variant.Variant.parse].glib.variant.Variant refSink()#GVariant uses a floating reference count system. All functions with names starting with `gvariantnew_` return floating references.void store(void * data)Stores the serialized form of value at data. data should be large enough. See [glib.variant.Variant.getSize].glib.variant.Variant takeRef()If value is floating, sink it. Otherwise, do nothing.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 [glib.variant.Variant.newObjectPath].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 [glib.variant.Variant.newSignature].string parseErrorPrintContext(glib.error.ErrorWrap error, string sourceStr)Pretty-prints a message showing the context of a #GVariant parse error within the string for which parsing was attempted.this(T val)Template to create a new Variant from a single D value. Params: T = The D type to create the variant from val = The value to assignthis(T vals)Template to create a new Variant from multiple D values. Params: T = The D types to create the variant from vals = The values to assignFunctions 6
GVariant * createVariant(T)(T val)Template to create a GVariant from a single D value. Params: T = The type of the value val = The value to assign to the new Variant. Returns: New variant C instance with floating referenceGVariant * createVariant(T...)(T vals) if (vals.length > 1)Template to create a new tuple GVariant from multiple D values. Params: T = The D types to create the variant from vals = The values to assign Returns: New variant C instance with floating referenceGVariant * createVariantTuple(T...)(T vals)Template to create a new tuple GVariant from one or more D values. Params: T = The D types to create the variant from vals = The values to assign Returns: New variant C instance with floating refer...T getVal(T)(GVariant * v)Template to get a single value from a GVariant Params: T = D type of the value to get v = GVariant struct pointer Returns: The single variant value of type `T`auto getVal(T...)(GVariant * v) if (T.length > 1)Template to get multiple values from a GVariant Params: T = D types of the values to get v = GVariant struct pointer Returns: A tuple containing the values from the Variant of the specified typesauto getValTuple(T...)(GVariant * v)Template to get one or more values from a container GVariant Params: T = D types of the values to get v = GVariant struct pointer Returns: A tuple containing the values from the container Variant o...