[glib/gvariant-utils: 2/2] Finish implementations in gvariant.c



commit dee0b3e0af92a4c65067a17cb276a45db50d18d5
Author: Ryan Lortie <desrt desrt ca>
Date:   Thu Feb 11 16:52:47 2010 -0500

    Finish implementations in gvariant.c
    
    Also, add printer and hashtable functions, lots of comments.

 glib/gvariant.c |  842 +++++++++++++++++++++++++++++++++++++++++++++++++++----
 glib/gvariant.h |   11 +
 2 files changed, 791 insertions(+), 62 deletions(-)
---
diff --git a/glib/gvariant.c b/glib/gvariant.c
index 529218c..7211d1a 100644
--- a/glib/gvariant.c
+++ b/glib/gvariant.c
@@ -26,6 +26,7 @@
 #include <glib/gvariant-core.h>
 #include <glib/gtestutils.h>
 #include <glib/gstrfuncs.h>
+#include <glib/ghash.h>
 #include <glib/gmem.h>
 
 #include <string.h>
@@ -73,15 +74,214 @@
  * There is a Python-inspired text language for describing #GVariant
  * values.  #GVariant includes a printer for this language and a parser
  * with type inferencing.
+ *
+ * <refsect2>
+ *  <title>Memory Use</title>
+ *  <para>
+ *   #GVariant 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.
+ *  </para>
+ *  <para>
+ *   The memory allocated by #GVariant can be grouped into 4 broad
+ *   purposes: memory for serialised data, memory for the type
+ *   information cache, buffer management memory and memory for the
+ *   #GVariant structure itself.
+ *  </para>
+ *  <refsect3>
+ *   <title>Serialised Data Memory</title>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *  </refect3>
+ *  <refect3>
+ *   <title>Type Information Cache</title>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    Continuing with the above example, if a #GVariant 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
+ *    #GVariant.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *   <para>
+ *    Array type info structures are 6 * sizeof (void *), plus the
+ *    memory required to store the type string itself.  This means that
+ *    on 32bit systems, the cache entry for "a{sv}" would require 30
+ *    bytes of memory (plus malloc overhead).
+ *   </para>
+ *   <para>
+ *    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 32bit systems, the cache entry for
+ *    "{sv}" would require 61 bytes of memory (plus malloc overhead).
+ *   </para>
+ *   <para>
+ *    This means that in total, for our "a{sv}" example, 91 bytes of
+ *    type information would be allocated.
+ *   </para>
+ *   <para>
+ *    The type information cache, additionally, uses a #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.
+ *   </para>
+ *   <para>
+ *    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.
+ *   </para>
+ *  </refect3>
+ *  <refsect3>
+ *   <title>Buffer Management Memory</title>
+ *   <para>
+ *    #GVariant 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
+ *    #GVariant.  This may involve a g_free() or a g_slice_free() or
+ *    even g_mapped_file_unref().
+ *   </para>
+ *   <para>
+ *    One buffer management structure is used for each chunk of
+ *    serialised data.  The size of the buffer management structure is 4
+ *    * (void *).  On 32bit systems, that's 16 bytes.
+ *   </para>
+ *  </refect3>
+ *  <refsect3>
+ *   <title>GVariant structure</title>
+ *   <para>
+ *    The size of a #GVariant structure is 6 * (void *).  On 32 bit
+ *    systems, that's 24 bytes.
+ *   </para>
+ *   <para>
+ *    #GVariant structures only exist if they are explicitly created
+ *    with API calls.  For example, if a #GVariant 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 #GVariant instance exists -- the one refering to the
+ *    dictionary.
+ *   </para>
+ *   <para>
+ *    If calls are made to start accessing the other values then
+ *    #GVariant 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.
+ *   </para>
+ *  </refect3>
+ *  <refsect3>
+ *   <title>Summary</title>
+ *   <para>
+ *    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 byes of memory
+ *    for the serialised data, 16 bytes for buffer management and 24
+ *    bytes for the #GVariant instance, or a total of 160 bytes, plus
+ *    malloc overhead.  If we were to use 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.
+ *   </para>
+ *  </refsect3>
+ * </refsect2>
  */
 
 /* definition of GVariant structure is in gvariant-core.c */
 
+/* this is a g_return_val_if_fail() for making
+ * sure a (GVariant *) has the required type.
+ */
 #define TYPE_CHECK(value, TYPE, val) \
   if G_UNLIKELY (!g_variant_is_of_type (value, TYPE)) {           \
     g_return_if_fail_warning (G_LOG_DOMAIN, __PRETTY_FUNCTION__,  \
                               "g_variant_is_of_type (" #value     \
-                              ", G_VARIANT_TYPE_" #TYPE ")");     \
+                              ", " #TYPE ")");                    \
     return val;                                                   \
   }
 
@@ -147,57 +347,17 @@ g_variant_get_boolean (GVariant *value)
   return data != NULL ? *data != 0 : FALSE;
 }
 
-/**
- * g_variant_new_handle:
- * @handle: a #gint32 value
- * @returns: a new handle #GVariant instance
- *
- * Creates a new handle #GVariant instance.
- *
- * By convention, handles are indexes into an array of file descriptors
- * that are sent alongside a DBus message.  If you're not interacting
- * with DBus, you probably don't need them.
- **/
-GVariant *
-g_variant_new_handle (gint32 value)
-{
-  return g_variant_new_from_trusted (G_VARIANT_TYPE_HANDLE,
-                                     &value, sizeof value);
-}
-
-/**
- * g_variant_get_handle:
- * @value: a handle #GVariant instance
- * @returns: a #gint32
- *
- * Returns the 32-bit signed integer value of @value.
- *
- * It is an error to call this function with a @value of any type other
- * than %G_VARIANT_TYPE_HANDLE.
- *
- * By convention, handles are indexes into an array of file descriptors
- * that are sent alongside a DBus message.  If you're not interacting
- * with DBus, you probably don't need them.
- **/
-gint32
-g_variant_get_handle (GVariant *value)
-{
-  const gint32 *data;
-
-  TYPE_CHECK (value, G_VARIANT_TYPE_HANDLE, -1);
-
-  data = g_variant_get_data (value);
-
-  return data != NULL ? *data : 0;
-}
-
-#define NUMERIC_TYPE(TYPE, type) \
-  GVariant *g_variant_new_##type (g##type value) {              \
+/* the constructors and accessors for byte, int{16,32,64}, handles and
+ * doubles all look pretty much exactly the same, so we reduce
+ * copy/pasting here.
+ */
+#define NUMERIC_TYPE(TYPE, type, ctype) \
+  GVariant *g_variant_new_##type (ctype value) {                \
     return g_variant_new_from_trusted (G_VARIANT_TYPE_##TYPE,   \
                                        &value, sizeof value);   \
   }                                                             \
-  g##type g_variant_get_##type (GVariant *value) {              \
-    const g##type *data;                                        \
+  ctype g_variant_get_##type (GVariant *value) {                \
+    const ctype *data;                                          \
     TYPE_CHECK (value, G_VARIANT_TYPE_ ## TYPE, 0);             \
     data = g_variant_get_data (value);                          \
     return data != NULL ? *data : 0;                            \
@@ -221,8 +381,7 @@ g_variant_get_handle (GVariant *value)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_BYTE.
  **/
-#define gbyte guchar
-NUMERIC_TYPE (BYTE, byte)
+NUMERIC_TYPE (BYTE, byte, guchar)
 
 /**
  * g_variant_new_int16:
@@ -241,7 +400,7 @@ NUMERIC_TYPE (BYTE, byte)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_INT16.
  **/
-NUMERIC_TYPE (INT16, int16)
+NUMERIC_TYPE (INT16, int16, gint16)
 
 /**
  * g_variant_new_uint16:
@@ -260,7 +419,7 @@ NUMERIC_TYPE (INT16, int16)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_UINT16.
  **/
-NUMERIC_TYPE (UINT16, uint16)
+NUMERIC_TYPE (UINT16, uint16, guint16)
 
 /**
  * g_variant_new_int32:
@@ -279,7 +438,7 @@ NUMERIC_TYPE (UINT16, uint16)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_INT32.
  **/
-NUMERIC_TYPE (INT32, int32)
+NUMERIC_TYPE (INT32, int32, gint32)
 
 /**
  * g_variant_new_uint32:
@@ -298,7 +457,7 @@ NUMERIC_TYPE (INT32, int32)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_UINT32.
  **/
-NUMERIC_TYPE (UINT32, uint32)
+NUMERIC_TYPE (UINT32, uint32, guint32)
 
 /**
  * g_variant_new_int64:
@@ -317,7 +476,7 @@ NUMERIC_TYPE (UINT32, uint32)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_INT64.
  **/
-NUMERIC_TYPE (INT64, int64)
+NUMERIC_TYPE (INT64, int64, gint64)
 
 /**
  * g_variant_new_uint64:
@@ -336,7 +495,34 @@ NUMERIC_TYPE (INT64, int64)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_UINT64.
  **/
-NUMERIC_TYPE (UINT64, uint64)
+NUMERIC_TYPE (UINT64, uint64, guint64)
+
+/**
+ * g_variant_new_handle:
+ * @handle: a #gint32 value
+ * @returns: a new handle #GVariant instance
+ *
+ * Creates a new handle #GVariant instance.
+ *
+ * By convention, handles are indexes into an array of file descriptors
+ * that are sent alongside a DBus message.  If you're not interacting
+ * with DBus, you probably don't need them.
+ **/
+/**
+ * g_variant_get_handle:
+ * @value: a handle #GVariant instance
+ * @returns: a #gint32
+ *
+ * Returns the 32-bit signed integer value of @value.
+ *
+ * It is an error to call this function with a @value of any type other
+ * than %G_VARIANT_TYPE_HANDLE.
+ *
+ * By convention, handles are indexes into an array of file descriptors
+ * that are sent alongside a DBus message.  If you're not interacting
+ * with DBus, you probably don't need them.
+ **/
+NUMERIC_TYPE (HANDLE, handle, gint32)
 
 /**
  * g_variant_new_double:
@@ -355,7 +541,7 @@ NUMERIC_TYPE (UINT64, uint64)
  * It is an error to call this function with a @value of any type
  * other than %G_VARIANT_TYPE_DOUBLE.
  **/
-NUMERIC_TYPE (DOUBLE, double)
+NUMERIC_TYPE (DOUBLE, double, gdouble)
 
 /**
  * g_variant_get_type:
@@ -822,21 +1008,91 @@ g_variant_new_array (const GVariantType *child_type,
                      GVariant * const   *children,
                      gsize               n_children)
 {
-  g_assert_not_reached ();
+  GVariantType *array_type;
+  GVariant **my_children;
+  gboolean trusted;
+  GVariant *value;
+  gsize i;
+
+  g_return_val_if_fail (n_children > 0 || child_type != NULL, NULL);
+  g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
+
+  my_children = g_new (GVariant *, n_children);
+  trusted = TRUE;
+
+  if (child_type == NULL)
+    child_type = g_variant_get_type (children[0]);
+  array_type = g_variant_type_new_array (child_type);
+
+  for (i = 0; i < n_children; i++)
+    {
+      TYPE_CHECK (children[i], child_type, NULL);
+      my_children[i] = g_variant_ref_sink (children[i]);
+      trusted &= g_variant_is_trusted (children[i]);
+    }
+
+  value = g_variant_new_from_children (array_type, my_children,
+                                       n_children, trusted);
+  g_variant_type_free (array_type);
+
+  return value;
 }
 
 GVariant *
 g_variant_new_tuple (GVariant * const *children,
                      gsize             n_children)
 {
-  g_assert_not_reached ();
+  const GVariantType **types;
+  GVariantType *tuple_type;
+  GVariant **my_children;
+  gboolean trusted;
+  GVariant *value;
+  gsize i;
+
+  g_return_val_if_fail (n_children == 0 || children != NULL, NULL);
+
+  types = g_new (const GVariantType *, n_children);
+  my_children = g_new (GVariant *, n_children);
+  trusted = TRUE;
+
+  for (i = 0; i < n_children; i++)
+    {
+      types[i] = g_variant_get_type (children[i]);
+      my_children[i] = g_variant_ref_sink (children[i]);
+      trusted &= g_variant_is_trusted (children[i]);
+    }
+
+  tuple_type = g_variant_type_new_tuple (types, n_children);
+  value = g_variant_new_from_children (tuple_type, my_children,
+                                       n_children, trusted);
+  g_variant_type_free (tuple_type);
+  g_free (types);
+
+  return value;
 }
 
 GVariant *
 g_variant_new_dict_entry (GVariant *key,
                           GVariant *value)
 {
-  g_assert_not_reached ();
+  GVariantType *dict_type;
+  GVariant **children;
+  gboolean trusted;
+
+  g_return_val_if_fail (key != NULL && value != NULL, NULL);
+  g_return_val_if_fail (!g_variant_is_container (key), NULL);
+
+  children = g_new (GVariant *, 2);
+  children[0] = g_variant_ref_sink (key);
+  children[1] = g_variant_ref_sink (value);
+  trusted = g_variant_is_trusted (key) && g_variant_is_trusted (value);
+
+  dict_type = g_variant_type_new_dict_entry (g_variant_get_type (key),
+                                             g_variant_get_type (value));
+  value = g_variant_new_from_children (dict_type, children, 2, trusted);
+  g_variant_type_free (dict_type);
+
+  return value;
 }
 
 gconstpointer
@@ -908,6 +1164,468 @@ g_variant_classify (GVariant *value)
   return *g_variant_get_type_string (value);
 }
 
+/**
+ * g_variant_print_string:
+ * @value: a #GVariant
+ * @string: a #GString, or %NULL
+ * @type_annotate: %TRUE if type information should be included in
+ *                 the output
+ * @returns: a #GString containing the string
+ *
+ * Behaves as g_variant_print(), but operates on a #GString.
+ *
+ * If @string is non-%NULL then it is appended to and returned.  Else,
+ * a new empty #GString is allocated and it is returned.
+ **/
+GString *
+g_variant_print_string (GVariant *value,
+                        GString  *string,
+                        gboolean  type_annotate)
+{
+  if G_UNLIKELY (string == NULL)
+    string = g_string_new (NULL);
+
+  switch (g_variant_classify (value))
+    {
+    case G_VARIANT_CLASS_MAYBE:
+      if (type_annotate)
+        g_string_append_printf (string, "@%s ",
+                                g_variant_get_type_string (value));
+
+      if (g_variant_n_children (value))
+        {
+          gchar *printed_child;
+          GVariant *element;
+
+          /* Nested maybes:
+           *
+           * Consider the case of the type "mmi".  In this case we could
+           * write "Just Just 4", but "4" alone is totally unambiguous,
+           * so we try to drop "Just" where possible.
+           *
+           * We have to be careful not to always drop "Just", though,
+           * since "Nothing" needs to be distinguishable from "Just
+           * Nothing".  The case where we need to ensure we keep the
+           * "Just" is actually exactly the case where we have a nested
+           * Nothing.
+           *
+           * Instead of searching for that nested Nothing, we just print
+           * the contained value into a separate string and see if we
+           * end up with "Nothing" at the end of it.  If so, we need to
+           * add "Just" at our level.
+           */
+          element = g_variant_get_child_value (value, 0);
+          printed_child = g_variant_print (element, FALSE);
+          g_variant_unref (element);
+
+          if (g_str_has_suffix (printed_child, "Nothing"))
+            g_string_append (string, "Just ");
+          g_string_append (string, printed_child);
+          g_free (printed_child);
+        }
+      else
+        g_string_append (string, "Nothing");
+
+      break;
+
+    case G_VARIANT_CLASS_ARRAY:
+      /* it's an array so the first character of the type string is 'a'
+       *
+       * if the first two characters are 'a{' then it's an array of
+       * dictionary entries (ie: a dictionary) so we print that
+       * differently.
+       */
+      if (g_variant_get_type_string (value)[1] == '{')
+        /* dictionary */
+        {
+          const gchar *comma = "";
+          gsize n, i;
+
+          if ((n = g_variant_n_children (value)) == 0)
+            {
+              if (type_annotate)
+                g_string_append_printf (string, "@%s ",
+                                        g_variant_get_type_string (value));
+              g_string_append (string, "{}");
+              break;
+            }
+
+          g_string_append_c (string, '{');
+          for (i = 0; i < n; i++)
+            {
+              GVariant *entry, *key, *val;
+
+              g_string_append (string, comma);
+              comma = ", ";
+
+              entry = g_variant_get_child_value (value, i);
+              key = g_variant_get_child_value (entry, 0);
+              val = g_variant_get_child_value (entry, 1);
+              g_variant_unref (entry);
+
+              g_variant_print_string (key, string, type_annotate);
+              g_variant_unref (key);
+              g_string_append (string, ": ");
+              g_variant_print_string (val, string, type_annotate);
+              g_variant_unref (val);
+              type_annotate = FALSE;
+            }
+          g_string_append_c (string, '}');
+        }
+      else
+        /* normal (non-dictionary) array */
+        {
+          const gchar *comma = "";
+          gsize n, i;
+
+          if ((n = g_variant_n_children (value)) == 0)
+            {
+              if (type_annotate)
+                g_string_append_printf (string, "@%s ",
+                                        g_variant_get_type_string (value));
+              g_string_append (string, "[]");
+              break;
+            }
+
+          g_string_append_c (string, '[');
+          for (i = 0; i < n; i++)
+            {
+              GVariant *element;
+
+              g_string_append (string, comma);
+              comma = ", ";
+
+              element = g_variant_get_child_value (value, i);
+
+              g_variant_print_string (element, string, type_annotate);
+              g_variant_unref (element);
+              type_annotate = FALSE;
+            }
+          g_string_append_c (string, ']');
+        }
+
+      break;
+
+    case G_VARIANT_CLASS_TUPLE:
+      {
+        gsize n, i;
+
+        n = g_variant_n_children (value);
+
+        g_string_append_c (string, '(');
+        for (i = 0; i < n; i++)
+          {
+            GVariant *element;
+
+            element = g_variant_get_child_value (value, i);
+            g_variant_print_string (element, string, type_annotate);
+            g_string_append (string, ", ");
+          }
+
+        /* for >1 item:  remove final ", "
+         * for 1 item:   remove final " ", but leave the ","
+         * for 0 items:  there is only "(", so remove nothing
+         */
+        g_string_truncate (string, string->len - (n > 0) - (n > 1));
+        g_string_append_c (string, ')');
+      }
+      break;
+
+    case G_VARIANT_CLASS_DICT_ENTRY:
+      {
+        GVariant *element;
+
+        g_string_append_c (string, '{');
+
+        element = g_variant_get_child_value (value, 0);
+        g_variant_print_string (element, string, type_annotate);
+        g_variant_unref (element);
+
+        g_string_append (string, ", ");
+
+        element = g_variant_get_child_value (value, 1);
+        g_variant_print_string (element, string, type_annotate);
+        g_variant_unref (element);
+
+        g_string_append_c (string, '}');
+      }
+      break;
+
+    case G_VARIANT_CLASS_VARIANT:
+      {
+        GVariant *child = g_variant_get_variant (value);
+
+        /* Always annotate types in nested variants, because they are
+         * (by nature) of variable type.
+         */
+        g_string_append_c (string, '<');
+        g_variant_print_string (child, string, TRUE);
+        g_string_append_c (string, '>');
+
+        g_variant_unref (child);
+      }
+      break;
+
+    case G_VARIANT_CLASS_BOOLEAN:
+      if (g_variant_get_boolean (value))
+        g_string_append (string, "true");
+      else
+        g_string_append (string, "false");
+      break;
+
+    case G_VARIANT_CLASS_STRING:
+      {
+        const gchar *str = g_variant_get_string (value, NULL);
+        gchar *escaped = g_strescape (str, NULL);
+
+        g_string_append_printf (string, "\"%s\"", escaped);
+
+        g_free (escaped);
+      }
+      break;
+
+    case G_VARIANT_CLASS_BYTE:
+      if (type_annotate)
+        g_string_append (string, "byte ");
+      g_string_append_printf (string, "0x%02x",
+                              g_variant_get_byte (value));
+      break;
+
+    case G_VARIANT_CLASS_INT16:
+      if (type_annotate)
+        g_string_append (string, "int16 ");
+      g_string_append_printf (string, "%"G_GINT16_FORMAT,
+                              g_variant_get_int16 (value));
+      break;
+
+    case G_VARIANT_CLASS_UINT16:
+      if (type_annotate)
+        g_string_append (string, "uint16 ");
+      g_string_append_printf (string, "%"G_GUINT16_FORMAT,
+                              g_variant_get_uint16 (value));
+      break;
+
+    case G_VARIANT_CLASS_INT32:
+      /* Never annotate this type because it is the default for numbers
+       * (and this is a *pretty* printer)
+       */
+      g_string_append_printf (string, "%"G_GINT32_FORMAT,
+                              g_variant_get_int32 (value));
+      break;
+
+    case G_VARIANT_CLASS_HANDLE:
+      if (type_annotate)
+        g_string_append (string, "handle ");
+      g_string_append_printf (string, "%"G_GINT32_FORMAT,
+                              g_variant_get_handle (value));
+      break;
+
+    case G_VARIANT_CLASS_UINT32:
+      if (type_annotate)
+        g_string_append (string, "uint32 ");
+      g_string_append_printf (string, "%"G_GUINT32_FORMAT,
+                              g_variant_get_uint32 (value));
+      break;
+
+    case G_VARIANT_CLASS_INT64:
+      if (type_annotate)
+        g_string_append (string, "int64 ");
+      g_string_append_printf (string, "%"G_GINT64_FORMAT,
+                              g_variant_get_int64 (value));
+      break;
+
+    case G_VARIANT_CLASS_UINT64:
+      if (type_annotate)
+        g_string_append (string, "uint64 ");
+      g_string_append_printf (string, "%"G_GUINT64_FORMAT,
+                              g_variant_get_uint64 (value));
+      break;
+
+    case G_VARIANT_CLASS_DOUBLE:
+      {
+        gchar buffer[100];
+        gint i;
+
+        g_ascii_dtostr (buffer, sizeof buffer, g_variant_get_double (value));
+
+        for (i = 0; buffer[i]; i++)
+          if (buffer[i] == '.' || buffer[i] == 'e' ||
+              buffer[i] == 'n' || buffer[i] == 'N')
+            break;
+
+        /* if there is no '.' or 'e' in the float then add one */
+        if (buffer[i] == '\0')
+          {
+            buffer[i++] = '.';
+            buffer[i++] = '0';
+            buffer[i++] = '\0';
+          }
+
+        g_string_append (string, buffer);
+      }
+      break;
+
+    case G_VARIANT_CLASS_OBJECT_PATH:
+      if (type_annotate)
+        g_string_append (string, "objectpath ");
+      g_string_append_printf (string, "\"%s\"",
+                              g_variant_get_string (value, NULL));
+      break;
+
+    case G_VARIANT_CLASS_SIGNATURE:
+      if (type_annotate)
+        g_string_append (string, "signature");
+      g_string_append_printf (string, "\"%s\"",
+                              g_variant_get_string (value, NULL));
+      break;
+
+    default:
+      g_assert_not_reached ();
+  }
+
+  return string;
+}
+
+/**
+ * g_variant_print:
+ * @value: a #GVariant
+ * @type_annotate: %TRUE if type information should be included in
+ *                 the output
+ * @returns: a newly-allocated string holding the result.
+ *
+ * Pretty-prints @value in the format understood by g_variant_parse().
+ *
+ * If @type_annotate is %TRUE, then type information is included in
+ * the output.
+ */
+gchar *
+g_variant_print (GVariant *value,
+                 gboolean  type_annotate)
+{
+  return g_string_free (g_variant_print_string (value, NULL, type_annotate),
+                        FALSE);
+};
+
+guint
+g_variant_hash (gconstpointer value_)
+{
+  GVariant *value = (GVariant *) value_;
+
+  switch (g_variant_classify (value))
+    {
+    case G_VARIANT_CLASS_STRING:
+    case G_VARIANT_CLASS_OBJECT_PATH:
+    case G_VARIANT_CLASS_SIGNATURE:
+      return g_str_hash (g_variant_get_string (value, NULL));
+
+    case G_VARIANT_CLASS_BOOLEAN:
+      /* this is a very odd thing to hash... */
+      return 0;
+
+    case G_VARIANT_CLASS_BYTE:
+      return g_variant_get_byte (value);
+
+    case G_VARIANT_CLASS_INT16:
+    case G_VARIANT_CLASS_UINT16:
+      {
+        const guint16 *ptr;
+
+        ptr = g_variant_get_data (value);
+
+        if (ptr)
+          return *ptr;
+        else
+          return 0;
+      }
+
+    case G_VARIANT_CLASS_INT32:
+    case G_VARIANT_CLASS_UINT32:
+    case G_VARIANT_CLASS_HANDLE:
+      {
+        const guint *ptr;
+
+        ptr = g_variant_get_data (value);
+
+        if (ptr)
+          return *ptr;
+        else
+          return 0;
+      }
+
+    case G_VARIANT_CLASS_INT64:
+    case G_VARIANT_CLASS_UINT64:
+    case G_VARIANT_CLASS_DOUBLE:
+      /* need a separate case for these guys because otherwise
+       * performance could be quite bad on big endian systems
+       */
+      {
+        const guint *ptr;
+
+        ptr = g_variant_get_data (value);
+
+        if (ptr)
+          return ptr[0] + ptr[1];
+        else
+          return 0;
+      }
+
+    default:
+      g_return_val_if_fail (!g_variant_is_container (value), 0);
+      g_assert_not_reached ();
+    }
+}
+
+gboolean
+g_variant_equal (gconstpointer one,
+                 gconstpointer two)
+{
+  gboolean equal;
+
+  g_return_val_if_fail (one != NULL && two != NULL, FALSE);
+
+  if (g_variant_get_type_info ((GVariant *) one) !=
+      g_variant_get_type_info ((GVariant *) two))
+    return FALSE;
+
+  /* if both values are trusted to be in their canonical serialised form
+   * then a simple memcmp() of their serialised data will answer the
+   * question.
+   *
+   * if not, then this might generate a false negative (since it is
+   * possible for two different byte sequences to represent the same
+   * value).  for now we solve this by pretty-printing both values and
+   * comparing the result.
+   */
+  if (g_variant_is_trusted ((GVariant *) one) &&
+      g_variant_is_trusted ((GVariant *) two))
+    {
+      gconstpointer data_one, data_two;
+      gsize size_one, size_two;
+
+      size_one = g_variant_get_size ((GVariant *) one);
+      size_two = g_variant_get_size ((GVariant *) two);
+
+      if (size_one != size_two)
+        return FALSE;
+
+      data_one = g_variant_get_data ((GVariant *) one);
+      data_two = g_variant_get_data ((GVariant *) two);
+
+      equal = memcmp (data_one, data_two, size_one) == 0;
+    }
+  else
+    {
+      gchar *strone, *strtwo;
+
+      strone = g_variant_print ((GVariant *) one, FALSE);
+      strtwo = g_variant_print ((GVariant *) two, FALSE);
+      equal = strcmp (strone, strtwo);
+      g_free (strone);
+      g_free (strtwo);
+    }
+
+  return equal;
+}
+
 #define __G_VARIANT_C__
 #include "galiasdef.c"
-
diff --git a/glib/gvariant.h b/glib/gvariant.h
index 9a2f326..19da9cb 100644
--- a/glib/gvariant.h
+++ b/glib/gvariant.h
@@ -24,6 +24,7 @@
 #define __G_VARIANT_H__
 
 #include <glib/gvarianttype.h>
+#include <glib/gstring.h>
 
 G_BEGIN_DECLS
 
@@ -124,6 +125,16 @@ gconstpointer                   g_variant_get_data                      (GVarian
 void                            g_variant_store                         (GVariant             *value,
                                                                          gpointer              data);
 
+gchar *                         g_variant_print                         (GVariant             *value,
+                                                                         gboolean              type_annotate);
+GString *                       g_variant_print_string                  (GVariant             *value,
+                                                                         GString              *string,
+                                                                         gboolean              type_annotate);
+
+guint                           g_variant_hash                          (gconstpointer         value);
+gboolean                        g_variant_equal                         (gconstpointer         one,
+                                                                         gconstpointer         two);
+
 G_END_DECLS
 
 #endif /* __G_VARIANT_H__ */



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