### ----------------------------------------------------
### -- Gnome::Glib
### -- Licenses: Artistic-2.0
### -- Authors: Marcel Timmerman
### -- File: lib/Gnome/Glib/Variant.rakumod
### ----------------------------------------------------
### -- Chunk 1 of 4
#TL:1:Gnome::Glib::Variant:

use v6;
#-------------------------------------------------------------------------------
=begin pod

=head1 Gnome::Glib::Variant

Strongly typed value datatype

=head1 Description

B<Gnome::Glib::Variant> is a variant datatype; it can contain one or more values along with information about the type of the values.

A B<Gnome::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 B<Gnome::Glib::Variant> is also immutable: once it's been created neither its type nor its content can be modified further.

B<Gnome::Glib::Variant> is useful whenever data needs to be serialized, for example when sending method parameters in DBus, or when saving settings using B<Gnome::Glib::Settings>.

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

  my Gnome::Glib::Variant $v .= new(
    :type-string<u>, :value(42)
  );

The string "u" in the first argument tells B<Gnome::Glib::Variant> that the data passed to the constructor (40) is going to be an unsigned 32 bit integer.

As an alternative you can write

  my Gnome::Glib::Variant $v .= new(:parse('-42'));

where the default used type is a signed 32 bit integer. To use an other integer type, write the type with it.

  my Gnome::Glib::Variant $v .= new(:parse('uint64 42'));

More advanced examples of B<Gnome::Glib::Variant> in use can be found in documentation for GVariant format strings.

The range of possible values is determined by the type.

The type system used by B<Gnome::Glib::Variant> is B<Gnome::Glib::VariantType>.

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

=comment B<Gnome::Glib::Variant> is reference counted using C<g_variant_ref()> and C<g_variant_unref()>.  B<Gnome::Glib::Variant> also has floating reference counts -- see C<g_variant_ref_sink()>.

B<Gnome::Glib::Variant> is completely threadsafe.  A B<Gnome::Glib::Variant> instance can be concurrently accessed in any way from any number of threads without problems.

B<Gnome::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 B<Gnome::Glib::Variant> data can also be sent over the network.

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

For space-efficiency, the B<Gnome::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 C<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 B<Gnome::Glib::Variant>'s size is limited mainly by any lower level operating system constraints, such as the number of bits in B<gsize>.  For example, it is reasonable to have a 2GB file mapped into memory with B<GMappedFile>, and call C<g_variant_new_from_data()> on it.

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

=comment There is a Python-inspired text language for describing B<Gnome::Glib::Variant> values.  B<Gnome::Glib::Variant> includes a printer for this language and a parser with type inferencing.


=head2 Memory Use

B<Gnome::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 B<Gnome::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
B<Gnome::Glib::Variant> structure itself.

=head3 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.

=head3 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 B<Gnome::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
B<Gnome::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 B<GHashTable> to
store and lookup 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.

=head3 Buffer Management Memory

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

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

If calls are made to start accessing the other values then
B<Gnome::Glib::Variant> instances will exist for those values only for as long
as they are in use (ie: until you call C<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.

=head3 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 B<Gnome::Glib::Variant> instance, or a total of 160 bytes, plus malloc overhead.  If we were to use C<g_variant_get_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.

=head2 See Also

[Gnome::Glib::VariantType](VariantType.html), [variant format strings](https://developer.gnome.org/glib/stable/gvariant-format-strings.html), [variant text format](https://developer.gnome.org/glib/stable/gvariant-text.html).

 =item L<Variant dictionaries|VariantDict.html>
 =item L<Variant types|VariantType.html>
 =item L<Variant format strings|https://developer.gnome.org/glib/stable/gvariant-format-strings.html>
 =item L<Variant text format|https://developer.gnome.org/glib/stable/gvariant-text.html>

=head1 Synopsis
=head2 Declaration

  unit class Gnome::Glib::Variant;
  also is Gnome::N::TopLevelClassSupport;

=comment head2 Example

=end pod
#-------------------------------------------------------------------------------
use NativeCall;

use Gnome::N::X:api<1>;
use Gnome::N::NativeLib:api<1>;
use Gnome::N::TopLevelClassSupport:api<1>;
use Gnome::N::GlibToRakuTypes:api<1>;
use Gnome::N::N-GObject:api<1>;

use Gnome::Glib::Error:api<1>;
use Gnome::Glib::VariantType:api<1>;

#-------------------------------------------------------------------------------
unit class Gnome::Glib::Variant:auth<github:MARTIMM>:api<1>;
also is Gnome::N::TopLevelClassSupport;

#-------------------------------------------------------------------------------
=begin pod
=head1 Types
=end pod

#-------------------------------------------------------------------------------
=begin pod
=head2 GVariantClass

The range of possible top-level types of GVariant instances.

=item G_VARIANT_CLASS_BOOLEAN; The GVariant is a boolean.
=item G_VARIANT_CLASS_BYTE; The GVariant is a byte.
=item G_VARIANT_CLASS_INT16; The GVariant is a signed 16 bit integer.
=item G_VARIANT_CLASS_UINT16; The GVariant is an unsigned 16 bit integer.
=item G_VARIANT_CLASS_INT32; The GVariant is a signed 32 bit integer.
=item G_VARIANT_CLASS_UINT32; The GVariant is an unsigned 32 bit integer.
=item G_VARIANT_CLASS_INT64; The GVariant is a signed 64 bit integer.
=item G_VARIANT_CLASS_UINT64; The GVariant is an unsigned 64 bit integer.
=item G_VARIANT_CLASS_HANDLE; The GVariant is a file handle index.
=item G_VARIANT_CLASS_DOUBLE; The GVariant is a double precision floating point value.
=item G_VARIANT_CLASS_STRING; The GVariant is a normal string.
=item G_VARIANT_CLASS_OBJECT_PATH; The GVariant is a D-Bus object path string.
=item G_VARIANT_CLASS_SIGNATURE; The GVariant is a D-Bus signature string.
=item G_VARIANT_CLASS_VARIANT; The GVariant is a variant.
=item G_VARIANT_CLASS_MAYBE; The GVariant is a maybe-typed value.
=item G_VARIANT_CLASS_ARRAY; The GVariant is an array.
=item G_VARIANT_CLASS_TUPLE; The GVariant is a tuple.
=item G_VARIANT_CLASS_DICT_ENTRY; The GVariant is a dictionary entry.
=end pod

#TT:0:GVariantClass
enum GVariantClass is export (
  G_VARIANT_CLASS_BOOLEAN       => 'b',
  G_VARIANT_CLASS_BYTE          => 'y',
  G_VARIANT_CLASS_INT16         => 'n',
  G_VARIANT_CLASS_UINT16        => 'q',
  G_VARIANT_CLASS_INT32         => 'i',
  G_VARIANT_CLASS_UINT32        => 'u',
  G_VARIANT_CLASS_INT64         => 'x',
  G_VARIANT_CLASS_UINT64        => 't',
  G_VARIANT_CLASS_HANDLE        => 'h',
  G_VARIANT_CLASS_DOUBLE        => 'd',
  G_VARIANT_CLASS_STRING        => 's',
  G_VARIANT_CLASS_OBJECT_PATH   => 'o',
  G_VARIANT_CLASS_SIGNATURE     => 'g',
  G_VARIANT_CLASS_VARIANT       => 'v',
  G_VARIANT_CLASS_MAYBE         => 'm',
  G_VARIANT_CLASS_ARRAY         => 'a',
  G_VARIANT_CLASS_TUPLE         => '(',
  G_VARIANT_CLASS_DICT_ENTRY    => '{'
);

#-------------------------------------------------------------------------------
=begin pod
=head1 Methods
=head2 new

=head3 :array

Create a new Variant object. The type of the array elements is taken from the first element.

  multi method new ( Array :$array! )

=head4 Example

Create a Variant array type containing integers;

  my Array $array = [];
  for 40, 41, 42 -> $value {
    $array.push: Gnome::Glib::Variant.new( :type-string<i>, :$value);
  }
  my Gnome::Glib::Variant $v .= new(:$array);
  say $v.get-type-string;      # ai

=head3 :boolean

Creates a new boolean Variant -- either C<True> or C<False>. Note that the value in the variant is stored as an integer. Its type becomes 'b'.

  multi method new ( Bool :$boolean! )


=head3 :byte

Creates a new byte Variant. Its type becomes 'y'.

  multi method new ( Int :$byte! )


=head3 :byte-string

Creates a new byte-string Variant. Its type becomes 'ay' which is essentially an array of bytes. This can be an ascii type of string which does not have to be UTF complient.

  multi method new ( Str :$byte-string! )


=head3 :byte-string-array

Creates a new byte-string-array Variant. Its type becomes 'aay'. which is essentially an array of an array of bytes.

  multi method new ( Array :$byte-string-array! )


=head3 :dict

Creates a new dictionary Variant. Its type becomes '{}'.

  multi method new ( List :$dict! )

The List C<$dict> has two values, a I<key> and a I<value> and must both be valid B<Gnome::Glib::Variant> objects. I<key> must be a value of a basic type (ie: not a container). It will mostly be a string (variant type 's').

=head4 Example

  my Gnome::Glib::Variant $v .= new(
    :dict(
      Gnome::Glib::Variant.new(:parse<width>),
      Gnome::Glib::Variant.new(:parse<200>)
    )
  );

  say $v.print; #

=head3 :double

Creates a new double Variant. Its type becomes 'd'.

  multi method new ( Num :$double! )


=head3 :int16

Creates a new int16 Variant. Its type becomes 'n'.

  multi method new ( Int :$int16! )


=head3 :int32

Creates a new int32 Variant. Its type becomes 'i'.

  multi method new ( Int :$int32! )


=head3 :int64

Creates a new int64 Variant. Its type becomes 'x'.

  multi method new ( Int :$int64! )


=head3 :string

Creates a new string Variant. Its type becomes 's'.

  multi method new ( Str :$string! )


=head3 :strv

Creates a new string array Variant. Its type becomes 'as'.

  multi method new ( Array :$strv! )

=head4 Example

  my Gnome::Glib::Variant $v .= new(:string-array([<abc def ghi αβ ⓒ™⅔>]));
  say $v.get-type-string; #    as


=head3 :tuple

Creates a new tuple Variant. Its type becomes ''.

  multi method new ( Array :$tuple! )

=head4 Example

  my Array $tuple = [];
  $tuple.push: Gnome::Glib::Variant.new( :type-string<i>, :value(40));
  $tuple.push: Gnome::Glib::Variant.new( :type-string<s>, :value<fourtyone>);
  $tuple.push: Gnome::Glib::Variant.new( :type-string<x>, :value(42));
  my Gnome::Glib::Variant $v .= new(:$tuple);
  say $v.get-type-string; #    (isx)


=head3 :uint16

Creates a new uint16 Variant. Its type becomes 'q'.

  multi method new ( UInt :$uint16! )


=head3 :uint32

Creates a new uint32 Variant. Its type becomes 'u'.

  multi method new ( UInt :$uint32! )


=head3 :uint64

Creates a new uint64 Variant. Its type becomes 't'.

  multi method new ( UInt :$uint64! )


=head3 :variant

Creates a new variant Variant. Its type becomes 'v'.

  multi method new ( N-GObject :$variant! )

=head4 Example

  my Gnome::Glib::Variant $v .= new(
    :variant(Gnome::Glib::Variant.new( :type-string<i>, :value(40)))
  );
  say $v.get-type-string; #    v


=head3 :type-string, :parse

Create a new Variant object by parsing the type and data provided in strings. The format of the parse string is L<described here|https://developer.gnome.org/glib/stable/gvariant-text.html>.

  multi method new ( Str :$type-string?, Str :$parse! )

=head4 Example

Create a Variant tuple containing a string, an unsigned integer and a boolean (Note the lowercase 'true'!);

  my Gnome::Glib::Variant $v .= new(
    :type-string<(sub)>, :parse('("abc",20,true)')
  );

Because the values in the :parse string take the default types you can also leave out the type string;

  my Gnome::Glib::Variant $v .= new(:parse('("abc",20,true)'));


=head3 :type-string, :value

Create a new Variant object by parsing the type and a provided value. The type strings are simple like (unsigned) integer ('u' or 'i') but no arrays ('a') etc.

  multi method new ( Str :$type-string!, Any :$value! )


=head3 :native-object

Create a Variant object using a native object from elsewhere. See also B<Gnome::N::TopLevelClassSupport>.

  multi method new ( N-GObject :$native-object! )

=end pod

#TM:1:new(:array):
#TM:1:new(:boolean):
#TM:1:new(:byte):
#TM:1:new(:byte-string):
#TM:1:new(:byte-string-array):
#TM:1:new(:dict):
#TM:1:new(:double):
#TM:1:new(:int16):
#TM:1:new(:int32):
#TM:1:new(:int64):
#TM:1:new(:string):
#TM:1:new(:strv):
#TM:1:new(:tuple):
#TM:1:new(:uint16):
#TM:1:new(:uint32):
#TM:1:new(:uint64):
#TM:1:new(:variant):
#TM:1:new(:type-string,:values):
#TM:1:new(:type-string,:parse):
#TM:4:new(:native-object):Gnome::N::TopLevelClassSupport
submethod BUILD ( *%options ) {

  # prevent creating wrong native-objects
  if self.^name eq 'Gnome::Glib::Variant' #`{{or ?%options<GVariant>}} {

    # check if native object is set by other parent class BUILDers
    if self.is-valid { }

    elsif %options<native-object>:exists { }

    # process all other options
    else {
      my $no;

      if %options<array>:exists {
        my Gnome::Glib::VariantType $vt .= new(
          :type-string(%options<array>[0].get-type-string)
        );

        my Int $i = 0;
        my $children = CArray[N-GObject].new;
        for @(%options<array>) -> $no is copy {
          $no .= _get-native-object unless $no ~~ N-GObject;
          $children[$i++] = $no;
        }

        $no = _g_variant_new_array( $vt._get-native-object, $children, $i);
      }

      elsif %options<boolean>:exists {
        $no = _g_variant_new_boolean(%options<boolean>.Int);
      }

      elsif %options<byte>:exists {
        $no = _g_variant_new_byte(%options<byte>);
      }

      elsif %options<byte-string>:exists {
        $no = _g_variant_new_bytestring(%options<byte-string>);
      }

      elsif %options<byte-string-array>:exists {
        my Int $i = 0;
        my $ba = CArray[Str].new;
        for @(%options<byte-string-array>) -> $s {
          $ba[$i++] = $s;
        }
        $no = _g_variant_new_bytestring_array( $ba, $i);
      }

      elsif %options<dict>:exists {
        my $no1 = %options<dict>[0];
        $no1 .= _get-native-object-no-reffing unless $no1 ~~ N-GObject;
        my $no2 = %options<dict>[1];
        $no2 .= _get-native-object-no-reffing unless $no2 ~~ N-GObject;

        $no = _g_variant_new_dict_entry( $no1, $no2);
      }

      elsif %options<double>:exists {
        $no = _g_variant_new_double(%options<double>.Num);
      }

      elsif %options<int16>:exists {
        $no = _g_variant_new_int16(%options<int16>);
      }

      elsif %options<int32>:exists {
        $no = _g_variant_new_int32(%options<int32>);
      }

      elsif %options<int64>:exists {
        $no = _g_variant_new_int64(%options<int64>);
      }

      elsif %options<string>:exists {
        $no = _g_variant_new_string(%options<string>);
      }

      elsif %options<strv>:exists {
        my Int $i = 0;
        my $ba = CArray[Str].new;
        for @(%options<strv>) -> $s {
          $ba[$i++] = $s;
        }
        $no = _g_variant_new_strv( $ba, $i);
      }

      elsif %options<tuple>:exists {
        my Int $i = 0;
        my $children = CArray[N-GObject].new;
        for @(%options<tuple>) -> $no is copy {
          $no .= _get-native-object unless $no ~~ N-GObject;
          $children[$i++] = $no;
        }

        $no = _g_variant_new_tuple( $children, $i);
      }

      elsif %options<uint16>:exists {
        $no = _g_variant_new_uint16(%options<uint16>);
      }

      elsif %options<uint32>:exists {
        $no = _g_variant_new_uint32(%options<uint32>);
      }

      elsif %options<uint64>:exists {
        $no = _g_variant_new_uint64(%options<uint64>);
      }

      elsif %options<variant>:exists {
        $no = %options<variant>;
        $no .= _get-native-object unless $no ~~ N-GObject;
        $no = _g_variant_new_variant($no);
      }

#`{{
      elsif %options<>:exists {
        $no = _g_variant_new_(%options<>);
      }

}}

      elsif %options<parse>:exists {
        my Gnome::Glib::Error $e;
        ( $no, $e) = _g_variant_parse(|%options);

        die X::Gnome.new(
          :message("\nVariant parse error: $e.message()")
        ) if $e.is-valid;
      }

      elsif %options<value>:exists {
        $no = _g_variant_new( %options<type-string> // '', %options<value>);
      }


      self._set-native-object($no);
    }

    # only after creating the native-object, the gtype is known
    self._set-class-info('GVariant');
  }
}

#-------------------------------------------------------------------------------
# no pod. user does not have to know about it.
method _fallback ( $native-sub --> Callable ) {

  my Callable $s;
  try { $s = &::("g_variant_$native-sub"); };
  try { $s = &::("g_$native-sub"); } unless ?$s;
  try { $s = &::($native-sub); } if !$s and $native-sub ~~ m/^ 'g_' /;

  self._set-class-name-of-sub('GVariant');

  $s
}

#-------------------------------------------------------------------------------
method native-object-ref ( $n-native-object --> N-GObject ) {
  _g_variant_ref($n-native-object)
}

#-------------------------------------------------------------------------------
method native-object-unref ( $n-native-object ) {
  _g_variant_unref($n-native-object)
}


#`{{
#-------------------------------------------------------------------------------
# TM:0:byteswap:
=begin pod
=head2 byteswap

Performs a byteswapping operation on the contents of I<value>.  The result is that all multi-byte numeric data contained in I<value> is byteswapped.  That includes 16, 32, and 64bit signed and unsigned integers as well as file handles and double precision floating point values.  This function is an identity mapping on any value that does not contain multi-byte numeric data.  That include strings, booleans, bytes and containers containing only these things (recursively).  The returned value is always in normal form and is marked as trusted.

Returns: (transfer full): the byteswapped form of I<value>

  method byteswap ( --> N-GObject )


=end pod

method byteswap ( --> N-GObject ) {

  g_variant_byteswap(
    self._get-native-object-no-reffing,
  );
}

sub g_variant_byteswap ( N-GObject $value --> N-GObject )
  is native(&glib-lib)
  { * }
}}
#`{{
#-------------------------------------------------------------------------------
#TM:0:check-format-string:
=begin pod
=head2 check-format-string

Checks if calling C<g_variant_get()> with I<format_string> on I<value> would be valid from a type-compatibility standpoint.  I<format_string> is assumed to be a valid format string (from a syntactic standpoint).  If I<copy_only> is C<1> then this function additionally checks that it would be safe to call C<g_variant_unref()> on I<value> immediately after the call to C<g_variant_get()> without invalidating the result.  This is only possible if deep copies are made (ie: there are no pointers to the data inside of the soon-to-be-freed B<N-GObject> instance).  If this check fails then a C<g_critical()> is printed and C<0> is returned.  This function is meant to be used by functions that wish to provide varargs accessors to B<N-GObject> values of uncertain values (eg: C<g_variant_lookup()> or C<g_menu_model_get_item_attribute()>).

Returns: C<1> if I<format_string> is safe to use

  method check-format-string (  Str  $format_string, Int $copy_only --> Int )

=item  Str  $format_string; a valid B<N-GObject> format string
=item Int $copy_only; C<1> to ensure the format string makes deep copies

=end pod

method check-format-string (  Str  $format_string, Int $copy_only --> Int ) {

  g_variant_check_format_string(
    self._get-native-object-no-reffing, $format_string, $copy_only
  );
}

sub g_variant_check_format_string ( N-GObject $value, gchar-ptr $format_string, gboolean $copy_only --> gboolean )
  is native(&glib-lib)
  { * }
}}
#`{{
#-------------------------------------------------------------------------------
#TM:0:classify:
=begin pod
=head2 classify

Classifies I<value> according to its top-level type.

Returns: the B<GVariantClass> of I<value>

  method classify ( --> GVariantClass )


=end pod

method classify ( --> GVariantClass ) {

  g_variant_classify(
    self._get-native-object-no-reffing,
  );
}

sub g_variant_classify ( N-GObject $value --> GEnum )
  is native(&glib-lib)
  { * }
}}
#`{{
#-------------------------------------------------------------------------------
#TM:0:compare:
=begin pod
=head2 compare

Compares I<one> and I<two>.  The types of I<one> and I<two> are B<gconstpointer> only to allow use of this function with B<GTree>, B<GPtrArray>, etc.  They must each be a B<N-GObject>.  Comparison is only defined for basic types (ie: booleans, numbers, strings).  For booleans, C<0> is less than C<1>.  Numbers are ordered in the usual way.  Strings are in ASCII lexographical order.  It is a programmer error to attempt to compare container values or two values that have types that are not exactly equal.  For example, you cannot compare a 32-bit signed integer with a 32-bit unsigned integer.  Also note that this function is not particularly well-behaved when it comes to comparison of doubles; in particular, the handling of incomparable values (ie: NaN) is undefined.  If you only require an equality comparison, C<g_variant_equal()> is more general.

Returns: negative value if a < b; zero if a = b; positive value if a > b.

  method compare ( Pointer $one, Pointer $two --> Int )

=item Pointer $one; (type GVariant): a basic-typed B<N-GObject> instance
=item Pointer $two; (type GVariant): a B<N-GObject> instance of the same type

=end pod

method compare ( Pointer $one, Pointer $two --> Int ) {

  g_variant_compare(
    self._get-native-object-no-reffing, $one, $two
  );
}

sub g_variant_compare ( gpointer $one, gpointer $two --> gint )
  is native(&glib-lib)
  { * }
}}

#`{{
#-------------------------------------------------------------------------------
# TM:0:dup-bytestring:
=begin pod
=head2 dup-bytestring

Similar to C<g_variant_get_bytestring()> except that instead of returning a constant string, the string is duplicated.  The return value must be freed using C<g_free()>.

Returns: (transfer full) (array zero-terminated=1 length=length) (element-type guint8): a newly allocated string

  method dup-bytestring ( UInt $length -->  Str  )

=item UInt $length; (out) (optional) (default NULL): a pointer to a B<gsize>, to store the length (not including the nul terminator)

=end pod

method dup-bytestring ( UInt $length -->  Str  ) {

  g_variant_dup_bytestring(
    self._get-native-object-no-reffing, $length
  );
}

sub g_variant_dup_bytestring ( N-GObject $value, gsize $length --> gchar-ptr )
  is native(&glib-lib)
  { * }

#-------------------------------------------------------------------------------
# TM:0:dup-bytestring-array:
=begin pod
=head2 dup-bytestring-array

Gets the contents of an array of array of bytes B<N-GObject>.  This call makes a deep copy; the return result should be released with C<g_strfreev()>.  If I<length> is non-C<Any> then the number of elements in the result is stored there.  In any case, the resulting array will be C<Any>-terminated.  For an empty array, I<length> will be set to 0 and a pointer to a C<Any> pointer will be returned.

Returns: (array length=length) (transfer full): an array of