Trivial typo fix
[platform/upstream/glib.git] / glib / gvariant-serialiser.c
1 /*
2  * Copyright © 2007, 2008 Ryan Lortie
3  * Copyright © 2010 Codethink Limited
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Ryan Lortie <desrt@desrt.ca>
21  */
22
23 /* Prologue {{{1 */
24 #include "config.h"
25
26 #include "gvariant-serialiser.h"
27
28 #include <glib/gtestutils.h>
29 #include <glib/gstrfuncs.h>
30 #include <glib/gtypes.h>
31
32 #include <string.h>
33
34
35 /* GVariantSerialiser
36  *
37  * After this prologue section, this file has roughly 2 parts.
38  *
39  * The first part is split up into sections according to various
40  * container types.  Maybe, Array, Tuple, Variant.  The Maybe and Array
41  * sections are subdivided for element types being fixed or
42  * variable-sized types.
43  *
44  * Each section documents the format of that particular type of
45  * container and implements 5 functions for dealing with it:
46  *
47  *  n_children:
48  *    - determines (according to serialised data) how many child values
49  *      are inside a particular container value.
50  *
51  *  get_child:
52  *    - gets the type of and the serialised data corresponding to a
53  *      given child value within the container value.
54  *
55  *  needed_size:
56  *    - determines how much space would be required to serialise a
57  *      container of this type, containing the given children so that
58  *      buffers can be preallocated before serialising.
59  *
60  *  serialise:
61  *    - write the serialised data for a container of this type,
62  *      containing the given children, to a buffer.
63  *
64  *  is_normal:
65  *    - check the given data to ensure that it is in normal form.  For a
66  *      given set of child values, there is exactly one normal form for
67  *      the serialised data of a container.  Other forms are possible
68  *      while maintaining the same children (for example, by inserting
69  *      something other than zero bytes as padding) but only one form is
70  *      the normal form.
71  *
72  * The second part contains the main entry point for each of the above 5
73  * functions and logic to dispatch it to the handler for the appropriate
74  * container type code.
75  *
76  * The second part also contains a routine to byteswap serialised
77  * values.  This code makes use of the n_children() and get_child()
78  * functions above to do its work so no extra support is needed on a
79  * per-container-type basis.
80  *
81  * There is also additional code for checking for normal form.  All
82  * numeric types are always in normal form since the full range of
83  * values is permitted (eg: 0 to 255 is a valid byte).  Special checks
84  * need to be performed for booleans (only 0 or 1 allowed), strings
85  * (properly nul-terminated) and object paths and signature strings
86  * (meeting the D-Bus specification requirements).
87  */
88
89 /* < private >
90  * GVariantSerialised:
91  * @type_info: the #GVariantTypeInfo of this value
92  * @data: (allow-none): the serialised data of this value, or %NULL
93  * @size: the size of this value
94  *
95  * A structure representing a GVariant in serialised form.  This
96  * structure is used with #GVariantSerialisedFiller functions and as the
97  * primary interface to the serialiser.  See #GVariantSerialisedFiller
98  * for a description of its use there.
99  *
100  * When used with the serialiser API functions, the following invariants
101  * apply to all #GVariantTypeSerialised structures passed to and
102  * returned from the serialiser.
103  *
104  * @type_info must be non-%NULL.
105  *
106  * @data must be properly aligned for the type described by @type_info.
107  *
108  * If @type_info describes a fixed-sized type then @size must always be
109  * equal to the fixed size of that type.
110  *
111  * For fixed-sized types (and only fixed-sized types), @data may be
112  * %NULL even if @size is non-zero.  This happens when a framing error
113  * occurs while attempting to extract a fixed-sized value out of a
114  * variable-sized container.  There is no data to return for the
115  * fixed-sized type, yet @size must be non-zero.  The effect of this
116  * combination should be as if @data were a pointer to an
117  * appropriately-sized zero-filled region.
118  */
119
120 /* < private >
121  * g_variant_serialised_check:
122  * @serialised: a #GVariantSerialised struct
123  *
124  * Checks @serialised for validity according to the invariants described
125  * above.
126  */
127 static void
128 g_variant_serialised_check (GVariantSerialised serialised)
129 {
130   gsize fixed_size;
131   guint alignment;
132
133   g_assert (serialised.type_info != NULL);
134   g_variant_type_info_query (serialised.type_info, &alignment, &fixed_size);
135
136   if (fixed_size)
137     g_assert_cmpint (serialised.size, ==, fixed_size);
138   else
139     g_assert (serialised.size == 0 || serialised.data != NULL);
140
141   /* Depending on the native alignment requirements of the machine, the
142    * compiler will insert either 3 or 7 padding bytes after the char.
143    * This will result in the sizeof() the struct being 12 or 16.
144    * Subtract 9 to get 3 or 7 which is a nice bitmask to apply to get
145    * the alignment bits that we "care about" being zero: in the
146    * 4-aligned case, we care about 2 bits, and in the 8-aligned case, we
147    * care about 3 bits.
148    */
149   alignment &= sizeof (struct {
150                          char a;
151                          union {
152                            guint64 x;
153                            void *y;
154                            gdouble z;
155                          } b;
156                        }
157                       ) - 9;
158
159   /* Some OSes (FreeBSD is a known example) have a malloc() that returns
160    * unaligned memory if you request small sizes.  'malloc (1);', for
161    * example, has been seen to return pointers aligned to 6 mod 16.
162    *
163    * Check if this is a small allocation and return without enforcing
164    * the alignment assertion if this is the case.
165    */
166   if (serialised.size <= alignment)
167     return;
168
169   g_assert_cmpint (alignment & (gsize) serialised.data, ==, 0);
170 }
171
172 /* < private >
173  * GVariantSerialisedFiller:
174  * @serialised: a #GVariantSerialised instance to fill
175  * @data: data from the children array
176  *
177  * This function is called back from g_variant_serialiser_needed_size()
178  * and g_variant_serialiser_serialise().  It fills in missing details
179  * from a partially-complete #GVariantSerialised.
180  *
181  * The @data parameter passed back to the function is one of the items
182  * that was passed to the serialiser in the @children array.  It
183  * represents a single child item of the container that is being
184  * serialised.  The information filled in to @serialised is the
185  * information for this child.
186  *
187  * If the @type_info field of @serialised is %NULL then the callback
188  * function must set it to the type information corresponding to the
189  * type of the child.  No reference should be added.  If it is non-%NULL
190  * then the callback should assert that it is equal to the actual type
191  * of the child.
192  *
193  * If the @size field is zero then the callback must fill it in with the
194  * required amount of space to store the serialised form of the child.
195  * If it is non-zero then the callback should assert that it is equal to
196  * the needed size of the child.
197  *
198  * If @data is non-%NULL then it points to a space that is properly
199  * aligned for and large enough to store the serialised data of the
200  * child.  The callback must store the serialised form of the child at
201  * @data.
202  *
203  * If the child value is another container then the callback will likely
204  * recurse back into the serialiser by calling
205  * g_variant_serialiser_needed_size() to determine @size and
206  * g_variant_serialiser_serialise() to write to @data.
207  */
208
209 /* PART 1: Container types {{{1
210  *
211  * This section contains the serialiser implementation functions for
212  * each container type.
213  */
214
215 /* Maybe {{{2
216  *
217  * Maybe types are handled depending on if the element type of the maybe
218  * type is a fixed-sized or variable-sized type.  Although all maybe
219  * types themselves are variable-sized types, herein, a maybe value with
220  * a fixed-sized element type is called a "fixed-sized maybe" for
221  * convenience and a maybe value with a variable-sized element type is
222  * called a "variable-sized maybe".
223  */
224
225 /* Fixed-sized Maybe {{{3
226  *
227  * The size of a maybe value with a fixed-sized element type is either 0
228  * or equal to the fixed size of its element type.  The case where the
229  * size of the maybe value is zero corresponds to the "Nothing" case and
230  * the case where the size of the maybe value is equal to the fixed size
231  * of the element type corresponds to the "Just" case; in that case, the
232  * serialised data of the child value forms the entire serialised data
233  * of the maybe value.
234  *
235  * In the event that a fixed-sized maybe value is presented with a size
236  * that is not equal to the fixed size of the element type then the
237  * value must be taken to be "Nothing".
238  */
239
240 static gsize
241 gvs_fixed_sized_maybe_n_children (GVariantSerialised value)
242 {
243   gsize element_fixed_size;
244
245   g_variant_type_info_query_element (value.type_info, NULL,
246                                      &element_fixed_size);
247
248   return (element_fixed_size == value.size) ? 1 : 0;
249 }
250
251 static GVariantSerialised
252 gvs_fixed_sized_maybe_get_child (GVariantSerialised value,
253                                  gsize              index_)
254 {
255   /* the child has the same bounds as the
256    * container, so just update the type.
257    */
258   value.type_info = g_variant_type_info_element (value.type_info);
259   g_variant_type_info_ref (value.type_info);
260
261   return value;
262 }
263
264 static gsize
265 gvs_fixed_sized_maybe_needed_size (GVariantTypeInfo         *type_info,
266                                    GVariantSerialisedFiller  gvs_filler,
267                                    const gpointer           *children,
268                                    gsize                     n_children)
269 {
270   if (n_children)
271     {
272       gsize element_fixed_size;
273
274       g_variant_type_info_query_element (type_info, NULL,
275                                          &element_fixed_size);
276
277       return element_fixed_size;
278     }
279   else
280     return 0;
281 }
282
283 static void
284 gvs_fixed_sized_maybe_serialise (GVariantSerialised        value,
285                                  GVariantSerialisedFiller  gvs_filler,
286                                  const gpointer           *children,
287                                  gsize                     n_children)
288 {
289   if (n_children)
290     {
291       GVariantSerialised child = { NULL, value.data, value.size };
292
293       gvs_filler (&child, children[0]);
294     }
295 }
296
297 static gboolean
298 gvs_fixed_sized_maybe_is_normal (GVariantSerialised value)
299 {
300   if (value.size > 0)
301     {
302       gsize element_fixed_size;
303
304       g_variant_type_info_query_element (value.type_info,
305                                          NULL, &element_fixed_size);
306
307       if (value.size != element_fixed_size)
308         return FALSE;
309
310       /* proper element size: "Just".  recurse to the child. */
311       value.type_info = g_variant_type_info_element (value.type_info);
312
313       return g_variant_serialised_is_normal (value);
314     }
315
316   /* size of 0: "Nothing" */
317   return TRUE;
318 }
319
320 /* Variable-sized Maybe
321  *
322  * The size of a maybe value with a variable-sized element type is
323  * either 0 or strictly greater than 0.  The case where the size of the
324  * maybe value is zero corresponds to the "Nothing" case and the case
325  * where the size of the maybe value is greater than zero corresponds to
326  * the "Just" case; in that case, the serialised data of the child value
327  * forms the first part of the serialised data of the maybe value and is
328  * followed by a single zero byte.  This zero byte is always appended,
329  * regardless of any zero bytes that may already be at the end of the
330  * serialised ata of the child value.
331  */
332
333 static gsize
334 gvs_variable_sized_maybe_n_children (GVariantSerialised value)
335 {
336   return (value.size > 0) ? 1 : 0;
337 }
338
339 static GVariantSerialised
340 gvs_variable_sized_maybe_get_child (GVariantSerialised value,
341                                     gsize              index_)
342 {
343   /* remove the padding byte and update the type. */
344   value.type_info = g_variant_type_info_element (value.type_info);
345   g_variant_type_info_ref (value.type_info);
346   value.size--;
347
348   /* if it's zero-sized then it may as well be NULL */
349   if (value.size == 0)
350     value.data = NULL;
351
352   return value;
353 }
354
355 static gsize
356 gvs_variable_sized_maybe_needed_size (GVariantTypeInfo         *type_info,
357                                       GVariantSerialisedFiller  gvs_filler,
358                                       const gpointer           *children,
359                                       gsize                     n_children)
360 {
361   if (n_children)
362     {
363       GVariantSerialised child = { 0, };
364
365       gvs_filler (&child, children[0]);
366
367       return child.size + 1;
368     }
369   else
370     return 0;
371 }
372
373 static void
374 gvs_variable_sized_maybe_serialise (GVariantSerialised        value,
375                                     GVariantSerialisedFiller  gvs_filler,
376                                     const gpointer           *children,
377                                     gsize                     n_children)
378 {
379   if (n_children)
380     {
381       GVariantSerialised child = { NULL, value.data, value.size - 1 };
382
383       /* write the data for the child.  */
384       gvs_filler (&child, children[0]);
385       value.data[child.size] = '\0';
386     }
387 }
388
389 static gboolean
390 gvs_variable_sized_maybe_is_normal (GVariantSerialised value)
391 {
392   if (value.size == 0)
393     return TRUE;
394
395   if (value.data[value.size - 1] != '\0')
396     return FALSE;
397
398   value.type_info = g_variant_type_info_element (value.type_info);
399   value.size--;
400
401   return g_variant_serialised_is_normal (value);
402 }
403
404 /* Arrays {{{2
405  *
406  * Just as with maybe types, array types are handled depending on if the
407  * element type of the array type is a fixed-sized or variable-sized
408  * type.  Similar to maybe types, for convenience, an array value with a
409  * fixed-sized element type is called a "fixed-sized array" and an array
410  * value with a variable-sized element type is called a "variable sized
411  * array".
412  */
413
414 /* Fixed-sized Array {{{3
415  *
416  * For fixed sized arrays, the serialised data is simply a concatenation
417  * of the serialised data of each element, in order.  Since fixed-sized
418  * values always have a fixed size that is a multiple of their alignment
419  * requirement no extra padding is required.
420  *
421  * In the event that a fixed-sized array is presented with a size that
422  * is not an integer multiple of the element size then the value of the
423  * array must be taken as being empty.
424  */
425
426 static gsize
427 gvs_fixed_sized_array_n_children (GVariantSerialised value)
428 {
429   gsize element_fixed_size;
430
431   g_variant_type_info_query_element (value.type_info, NULL,
432                                      &element_fixed_size);
433
434   if (value.size % element_fixed_size == 0)
435     return value.size / element_fixed_size;
436
437   return 0;
438 }
439
440 static GVariantSerialised
441 gvs_fixed_sized_array_get_child (GVariantSerialised value,
442                                  gsize              index_)
443 {
444   GVariantSerialised child = { 0, };
445
446   child.type_info = g_variant_type_info_element (value.type_info);
447   g_variant_type_info_query (child.type_info, NULL, &child.size);
448   child.data = value.data + (child.size * index_);
449   g_variant_type_info_ref (child.type_info);
450
451   return child;
452 }
453
454 static gsize
455 gvs_fixed_sized_array_needed_size (GVariantTypeInfo         *type_info,
456                                    GVariantSerialisedFiller  gvs_filler,
457                                    const gpointer           *children,
458                                    gsize                     n_children)
459 {
460   gsize element_fixed_size;
461
462   g_variant_type_info_query_element (type_info, NULL, &element_fixed_size);
463
464   return element_fixed_size * n_children;
465 }
466
467 static void
468 gvs_fixed_sized_array_serialise (GVariantSerialised        value,
469                                  GVariantSerialisedFiller  gvs_filler,
470                                  const gpointer           *children,
471                                  gsize                     n_children)
472 {
473   GVariantSerialised child = { 0, };
474   gsize i;
475
476   child.type_info = g_variant_type_info_element (value.type_info);
477   g_variant_type_info_query (child.type_info, NULL, &child.size);
478   child.data = value.data;
479
480   for (i = 0; i < n_children; i++)
481     {
482       gvs_filler (&child, children[i]);
483       child.data += child.size;
484     }
485 }
486
487 static gboolean
488 gvs_fixed_sized_array_is_normal (GVariantSerialised value)
489 {
490   GVariantSerialised child = { 0, };
491
492   child.type_info = g_variant_type_info_element (value.type_info);
493   g_variant_type_info_query (child.type_info, NULL, &child.size);
494
495   if (value.size % child.size != 0)
496     return FALSE;
497
498   for (child.data = value.data;
499        child.data < value.data + value.size;
500        child.data += child.size)
501     {
502       if (!g_variant_serialised_is_normal (child))
503         return FALSE;
504     }
505
506   return TRUE;
507 }
508
509 /* Variable-sized Array {{{3
510  *
511  * Variable sized arrays, containing variable-sized elements, must be
512  * able to determine the boundaries between the elements.  The items
513  * cannot simply be concatenated.  Additionally, we are faced with the
514  * fact that non-fixed-sized values do not necessarily have a size that
515  * is a multiple of their alignment requirement, so we may need to
516  * insert zero-filled padding.
517  *
518  * While it is possible to find the start of an item by starting from
519  * the end of the item before it and padding for alignment, it is not
520  * generally possible to do the reverse operation.  For this reason, we
521  * record the end point of each element in the array.
522  *
523  * GVariant works in terms of "offsets".  An offset is a pointer to a
524  * boundary between two bytes.  In 4 bytes of serialised data, there
525  * would be 5 possible offsets: one at the start ('0'), one between each
526  * pair of adjacent bytes ('1', '2', '3') and one at the end ('4').
527  *
528  * The numeric value of an offset is an unsigned integer given relative
529  * to the start of the serialised data of the array.  Offsets are always
530  * stored in little endian byte order and are always only as big as they
531  * need to be.  For example, in 255 bytes of serialised data, there are
532  * 256 offsets.  All possibilities can be stored in an 8 bit unsigned
533  * integer.  In 256 bytes of serialised data, however, there are 257
534  * possible offsets so 16 bit integers must be used.  The size of an
535  * offset is always a power of 2.
536  *
537  * The offsets are stored at the end of the serialised data of the
538  * array.  They are simply concatenated on without any particular
539  * alignment.  The size of the offsets is included in the size of the
540  * serialised data for purposes of determining the size of the offsets.
541  * This presents a possibly ambiguity; in certain cases, a particular
542  * value of array could have two different serialised forms.
543  *
544  * Imagine an array containing a single string of 253 bytes in length
545  * (so, 254 bytes including the nul terminator).  Now the offset must be
546  * written.  If an 8 bit offset is written, it will bring the size of
547  * the array's serialised data to 255 -- which means that the use of an
548  * 8 bit offset was valid.  If a 16 bit offset is used then the total
549  * size of the array will be 256 -- which means that the use of a 16 bit
550  * offset was valid.  Although both of these will be accepted by the
551  * deserialiser, only the smaller of the two is considered to be in
552  * normal form and that is the one that the serialiser must produce.
553  */
554
555 /* bytes may be NULL if (size == 0). */
556 static inline gsize
557 gvs_read_unaligned_le (guchar *bytes,
558                        guint   size)
559 {
560   union
561   {
562     guchar bytes[GLIB_SIZEOF_SIZE_T];
563     gsize integer;
564   } tmpvalue;
565
566   tmpvalue.integer = 0;
567   if (bytes != NULL)
568     memcpy (&tmpvalue.bytes, bytes, size);
569
570   return GSIZE_FROM_LE (tmpvalue.integer);
571 }
572
573 static inline void
574 gvs_write_unaligned_le (guchar *bytes,
575                         gsize   value,
576                         guint   size)
577 {
578   union
579   {
580     guchar bytes[GLIB_SIZEOF_SIZE_T];
581     gsize integer;
582   } tmpvalue;
583
584   tmpvalue.integer = GSIZE_TO_LE (value);
585   memcpy (bytes, &tmpvalue.bytes, size);
586 }
587
588 static guint
589 gvs_get_offset_size (gsize size)
590 {
591   if (size > G_MAXUINT32)
592     return 8;
593
594   else if (size > G_MAXUINT16)
595     return 4;
596
597   else if (size > G_MAXUINT8)
598     return 2;
599
600   else if (size > 0)
601     return 1;
602
603   return 0;
604 }
605
606 static gsize
607 gvs_calculate_total_size (gsize body_size,
608                           gsize offsets)
609 {
610   if (body_size + 1 * offsets <= G_MAXUINT8)
611     return body_size + 1 * offsets;
612
613   if (body_size + 2 * offsets <= G_MAXUINT16)
614     return body_size + 2 * offsets;
615
616   if (body_size + 4 * offsets <= G_MAXUINT32)
617     return body_size + 4 * offsets;
618
619   return body_size + 8 * offsets;
620 }
621
622 static gsize
623 gvs_variable_sized_array_n_children (GVariantSerialised value)
624 {
625   gsize offsets_array_size;
626   gsize offset_size;
627   gsize last_end;
628
629   if (value.size == 0)
630     return 0;
631
632   offset_size = gvs_get_offset_size (value.size);
633
634   last_end = gvs_read_unaligned_le (value.data + value.size -
635                                     offset_size, offset_size);
636
637   if (last_end > value.size)
638     return 0;
639
640   offsets_array_size = value.size - last_end;
641
642   if (offsets_array_size % offset_size)
643     return 0;
644
645   return offsets_array_size / offset_size;
646 }
647
648 static GVariantSerialised
649 gvs_variable_sized_array_get_child (GVariantSerialised value,
650                                     gsize              index_)
651 {
652   GVariantSerialised child = { 0, };
653   gsize offset_size;
654   gsize last_end;
655   gsize start;
656   gsize end;
657
658   child.type_info = g_variant_type_info_element (value.type_info);
659   g_variant_type_info_ref (child.type_info);
660
661   offset_size = gvs_get_offset_size (value.size);
662
663   last_end = gvs_read_unaligned_le (value.data + value.size -
664                                     offset_size, offset_size);
665
666   if (index_ > 0)
667     {
668       guint alignment;
669
670       start = gvs_read_unaligned_le (value.data + last_end +
671                                      (offset_size * (index_ - 1)),
672                                      offset_size);
673
674       g_variant_type_info_query (child.type_info, &alignment, NULL);
675       start += (-start) & alignment;
676     }
677   else
678     start = 0;
679
680   end = gvs_read_unaligned_le (value.data + last_end +
681                                (offset_size * index_),
682                                offset_size);
683
684   if (start < end && end <= value.size)
685     {
686       child.data = value.data + start;
687       child.size = end - start;
688     }
689
690   return child;
691 }
692
693 static gsize
694 gvs_variable_sized_array_needed_size (GVariantTypeInfo         *type_info,
695                                       GVariantSerialisedFiller  gvs_filler,
696                                       const gpointer           *children,
697                                       gsize                     n_children)
698 {
699   guint alignment;
700   gsize offset;
701   gsize i;
702
703   g_variant_type_info_query (type_info, &alignment, NULL);
704   offset = 0;
705
706   for (i = 0; i < n_children; i++)
707     {
708       GVariantSerialised child = { 0, };
709
710       offset += (-offset) & alignment;
711       gvs_filler (&child, children[i]);
712       offset += child.size;
713     }
714
715   return gvs_calculate_total_size (offset, n_children);
716 }
717
718 static void
719 gvs_variable_sized_array_serialise (GVariantSerialised        value,
720                                     GVariantSerialisedFiller  gvs_filler,
721                                     const gpointer           *children,
722                                     gsize                     n_children)
723 {
724   guchar *offset_ptr;
725   gsize offset_size;
726   guint alignment;
727   gsize offset;
728   gsize i;
729
730   g_variant_type_info_query (value.type_info, &alignment, NULL);
731   offset_size = gvs_get_offset_size (value.size);
732   offset = 0;
733
734   offset_ptr = value.data + value.size - offset_size * n_children;
735
736   for (i = 0; i < n_children; i++)
737     {
738       GVariantSerialised child = { 0, };
739
740       while (offset & alignment)
741         value.data[offset++] = '\0';
742
743       child.data = value.data + offset;
744       gvs_filler (&child, children[i]);
745       offset += child.size;
746
747       gvs_write_unaligned_le (offset_ptr, offset, offset_size);
748       offset_ptr += offset_size;
749     }
750 }
751
752 static gboolean
753 gvs_variable_sized_array_is_normal (GVariantSerialised value)
754 {
755   GVariantSerialised child = { 0, };
756   gsize offsets_array_size;
757   guchar *offsets_array;
758   guint offset_size;
759   guint alignment;
760   gsize last_end;
761   gsize length;
762   gsize offset;
763   gsize i;
764
765   if (value.size == 0)
766     return TRUE;
767
768   offset_size = gvs_get_offset_size (value.size);
769   last_end = gvs_read_unaligned_le (value.data + value.size -
770                                     offset_size, offset_size);
771
772   if (last_end > value.size)
773     return FALSE;
774
775   offsets_array_size = value.size - last_end;
776
777   if (offsets_array_size % offset_size)
778     return FALSE;
779
780   offsets_array = value.data + value.size - offsets_array_size;
781   length = offsets_array_size / offset_size;
782
783   if (length == 0)
784     return FALSE;
785
786   child.type_info = g_variant_type_info_element (value.type_info);
787   g_variant_type_info_query (child.type_info, &alignment, NULL);
788   offset = 0;
789
790   for (i = 0; i < length; i++)
791     {
792       gsize this_end;
793
794       this_end = gvs_read_unaligned_le (offsets_array + offset_size * i,
795                                         offset_size);
796
797       if (this_end < offset || this_end > last_end)
798         return FALSE;
799
800       while (offset & alignment)
801         {
802           if (!(offset < this_end && value.data[offset] == '\0'))
803             return FALSE;
804           offset++;
805         }
806
807       child.data = value.data + offset;
808       child.size = this_end - offset;
809
810       if (child.size == 0)
811         child.data = NULL;
812
813       if (!g_variant_serialised_is_normal (child))
814         return FALSE;
815
816       offset = this_end;
817     }
818
819   g_assert (offset == last_end);
820
821   return TRUE;
822 }
823
824 /* Tuples {{{2
825  *
826  * Since tuples can contain a mix of variable- and fixed-sized items,
827  * they are, in terms of serialisation, a hybrid of variable-sized and
828  * fixed-sized arrays.
829  *
830  * Offsets are only stored for variable-sized items.  Also, since the
831  * number of items in a tuple is known from its type, we are able to
832  * know exactly how many offsets to expect in the serialised data (and
833  * therefore how much space is taken up by the offset array).  This
834  * means that we know where the end of the serialised data for the last
835  * item is -- we can just subtract the size of the offset array from the
836  * total size of the tuple.  For this reason, the last item in the tuple
837  * doesn't need an offset stored.
838  *
839  * Tuple offsets are stored in reverse.  This design choice allows
840  * iterator-based deserialisers to be more efficient.
841  *
842  * Most of the "heavy lifting" here is handled by the GVariantTypeInfo
843  * for the tuple.  See the notes in gvarianttypeinfo.h.
844  */
845
846 static gsize
847 gvs_tuple_n_children (GVariantSerialised value)
848 {
849   return g_variant_type_info_n_members (value.type_info);
850 }
851
852 static GVariantSerialised
853 gvs_tuple_get_child (GVariantSerialised value,
854                      gsize              index_)
855 {
856   const GVariantMemberInfo *member_info;
857   GVariantSerialised child = { 0, };
858   gsize offset_size;
859   gsize start, end;
860
861   member_info = g_variant_type_info_member_info (value.type_info, index_);
862   child.type_info = g_variant_type_info_ref (member_info->type_info);
863   offset_size = gvs_get_offset_size (value.size);
864
865   /* tuples are the only (potentially) fixed-sized containers, so the
866    * only ones that have to deal with the possibility of having %NULL
867    * data with a non-zero %size if errors occurred elsewhere.
868    */
869   if G_UNLIKELY (value.data == NULL && value.size != 0)
870     {
871       g_variant_type_info_query (child.type_info, NULL, &child.size);
872
873       /* this can only happen in fixed-sized tuples,
874        * so the child must also be fixed sized.
875        */
876       g_assert (child.size != 0);
877       child.data = NULL;
878
879       return child;
880     }
881
882   if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_OFFSET)
883     {
884       if (offset_size * (member_info->i + 2) > value.size)
885         return child;
886     }
887   else
888     {
889       if (offset_size * (member_info->i + 1) > value.size)
890         {
891           /* if the child is fixed size, return its size.
892            * if child is not fixed-sized, return size = 0.
893            */
894           g_variant_type_info_query (child.type_info, NULL, &child.size);
895
896           return child;
897         }
898     }
899
900   if (member_info->i + 1)
901     start = gvs_read_unaligned_le (value.data + value.size -
902                                    offset_size * (member_info->i + 1),
903                                    offset_size);
904   else
905     start = 0;
906
907   start += member_info->a;
908   start &= member_info->b;
909   start |= member_info->c;
910
911   if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_LAST)
912     end = value.size - offset_size * (member_info->i + 1);
913
914   else if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_FIXED)
915     {
916       gsize fixed_size;
917
918       g_variant_type_info_query (child.type_info, NULL, &fixed_size);
919       end = start + fixed_size;
920       child.size = fixed_size;
921     }
922
923   else /* G_VARIANT_MEMBER_ENDING_OFFSET */
924     end = gvs_read_unaligned_le (value.data + value.size -
925                                  offset_size * (member_info->i + 2),
926                                  offset_size);
927
928   if (start < end && end <= value.size)
929     {
930       child.data = value.data + start;
931       child.size = end - start;
932     }
933
934   return child;
935 }
936
937 static gsize
938 gvs_tuple_needed_size (GVariantTypeInfo         *type_info,
939                        GVariantSerialisedFiller  gvs_filler,
940                        const gpointer           *children,
941                        gsize                     n_children)
942 {
943   const GVariantMemberInfo *member_info = NULL;
944   gsize fixed_size;
945   gsize offset;
946   gsize i;
947
948   g_variant_type_info_query (type_info, NULL, &fixed_size);
949
950   if (fixed_size)
951     return fixed_size;
952
953   offset = 0;
954
955   for (i = 0; i < n_children; i++)
956     {
957       guint alignment;
958
959       member_info = g_variant_type_info_member_info (type_info, i);
960       g_variant_type_info_query (member_info->type_info,
961                                  &alignment, &fixed_size);
962       offset += (-offset) & alignment;
963
964       if (fixed_size)
965         offset += fixed_size;
966       else
967         {
968           GVariantSerialised child = { 0, };
969
970           gvs_filler (&child, children[i]);
971           offset += child.size;
972         }
973     }
974
975   return gvs_calculate_total_size (offset, member_info->i + 1);
976 }
977
978 static void
979 gvs_tuple_serialise (GVariantSerialised        value,
980                      GVariantSerialisedFiller  gvs_filler,
981                      const gpointer           *children,
982                      gsize                     n_children)
983 {
984   gsize offset_size;
985   gsize offset;
986   gsize i;
987
988   offset_size = gvs_get_offset_size (value.size);
989   offset = 0;
990
991   for (i = 0; i < n_children; i++)
992     {
993       const GVariantMemberInfo *member_info;
994       GVariantSerialised child = { 0, };
995       guint alignment;
996
997       member_info = g_variant_type_info_member_info (value.type_info, i);
998       g_variant_type_info_query (member_info->type_info, &alignment, NULL);
999
1000       while (offset & alignment)
1001         value.data[offset++] = '\0';
1002
1003       child.data = value.data + offset;
1004       gvs_filler (&child, children[i]);
1005       offset += child.size;
1006
1007       if (member_info->ending_type == G_VARIANT_MEMBER_ENDING_OFFSET)
1008         {
1009           value.size -= offset_size;
1010           gvs_write_unaligned_le (value.data + value.size,
1011                                   offset, offset_size);
1012         }
1013     }
1014
1015   while (offset < value.size)
1016     value.data[offset++] = '\0';
1017 }
1018
1019 static gboolean
1020 gvs_tuple_is_normal (GVariantSerialised value)
1021 {
1022   guint offset_size;
1023   gsize offset_ptr;
1024   gsize length;
1025   gsize offset;
1026   gsize i;
1027
1028   /* as per the comment in gvs_tuple_get_child() */
1029   if G_UNLIKELY (value.data == NULL && value.size != 0)
1030     return FALSE;
1031
1032   offset_size = gvs_get_offset_size (value.size);
1033   length = g_variant_type_info_n_members (value.type_info);
1034   offset_ptr = value.size;
1035   offset = 0;
1036
1037   for (i = 0; i < length; i++)
1038     {
1039       const GVariantMemberInfo *member_info;
1040       GVariantSerialised child;
1041       gsize fixed_size;
1042       guint alignment;
1043       gsize end;
1044
1045       member_info = g_variant_type_info_member_info (value.type_info, i);
1046       child.type_info = member_info->type_info;
1047
1048       g_variant_type_info_query (child.type_info, &alignment, &fixed_size);
1049
1050       while (offset & alignment)
1051         {
1052           if (offset > value.size || value.data[offset] != '\0')
1053             return FALSE;
1054           offset++;
1055         }
1056
1057       child.data = value.data + offset;
1058
1059       switch (member_info->ending_type)
1060         {
1061         case G_VARIANT_MEMBER_ENDING_FIXED:
1062           end = offset + fixed_size;
1063           break;
1064
1065         case G_VARIANT_MEMBER_ENDING_LAST:
1066           end = offset_ptr;
1067           break;
1068
1069         case G_VARIANT_MEMBER_ENDING_OFFSET:
1070           offset_ptr -= offset_size;
1071
1072           if (offset_ptr < offset)
1073             return FALSE;
1074
1075           end = gvs_read_unaligned_le (value.data + offset_ptr, offset_size);
1076           break;
1077
1078         default:
1079           g_assert_not_reached ();
1080         }
1081
1082       if (end < offset || end > offset_ptr)
1083         return FALSE;
1084
1085       child.size = end - offset;
1086
1087       if (child.size == 0)
1088         child.data = NULL;
1089
1090       if (!g_variant_serialised_is_normal (child))
1091         return FALSE;
1092
1093       offset = end;
1094     }
1095
1096   {
1097     gsize fixed_size;
1098     guint alignment;
1099
1100     g_variant_type_info_query (value.type_info, &alignment, &fixed_size);
1101
1102     if (fixed_size)
1103       {
1104         g_assert (fixed_size == value.size);
1105         g_assert (offset_ptr == value.size);
1106
1107         if (i == 0)
1108           {
1109             if (value.data[offset++] != '\0')
1110               return FALSE;
1111           }
1112         else
1113           {
1114             while (offset & alignment)
1115               if (value.data[offset++] != '\0')
1116                 return FALSE;
1117           }
1118
1119         g_assert (offset == value.size);
1120       }
1121   }
1122
1123   return offset_ptr == offset;
1124 }
1125
1126 /* Variants {{{2
1127  *
1128  * Variants are stored by storing the serialised data of the child,
1129  * followed by a '\0' character, followed by the type string of the
1130  * child.
1131  *
1132  * In the case that a value is presented that contains no '\0'
1133  * character, or doesn't have a single well-formed definite type string
1134  * following that character, the variant must be taken as containing the
1135  * unit tuple: ().
1136  */
1137
1138 static inline gsize
1139 gvs_variant_n_children (GVariantSerialised value)
1140 {
1141   return 1;
1142 }
1143
1144 static inline GVariantSerialised
1145 gvs_variant_get_child (GVariantSerialised value,
1146                        gsize              index_)
1147 {
1148   GVariantSerialised child = { 0, };
1149
1150   /* NOTE: not O(1) and impossible for it to be... */
1151   if (value.size)
1152     {
1153       /* find '\0' character */
1154       for (child.size = value.size - 1; child.size; child.size--)
1155         if (value.data[child.size] == '\0')
1156           break;
1157
1158       /* ensure we didn't just hit the start of the string */
1159       if (value.data[child.size] == '\0')
1160         {
1161           const gchar *type_string = (gchar *) &value.data[child.size + 1];
1162           const gchar *limit = (gchar *) &value.data[value.size];
1163           const gchar *end;
1164
1165           if (g_variant_type_string_scan (type_string, limit, &end) &&
1166               end == limit)
1167             {
1168               const GVariantType *type = (GVariantType *) type_string;
1169
1170               if (g_variant_type_is_definite (type))
1171                 {
1172                   gsize fixed_size;
1173
1174                   child.type_info = g_variant_type_info_get (type);
1175
1176                   if (child.size != 0)
1177                     /* only set to non-%NULL if size > 0 */
1178                     child.data = value.data;
1179
1180                   g_variant_type_info_query (child.type_info,
1181                                              NULL, &fixed_size);
1182
1183                   if (!fixed_size || fixed_size == child.size)
1184                     return child;
1185
1186                   g_variant_type_info_unref (child.type_info);
1187                 }
1188             }
1189         }
1190     }
1191
1192   child.type_info = g_variant_type_info_get (G_VARIANT_TYPE_UNIT);
1193   child.data = NULL;
1194   child.size = 1;
1195
1196   return child;
1197 }
1198
1199 static inline gsize
1200 gvs_variant_needed_size (GVariantTypeInfo         *type_info,
1201                          GVariantSerialisedFiller  gvs_filler,
1202                          const gpointer           *children,
1203                          gsize                     n_children)
1204 {
1205   GVariantSerialised child = { 0, };
1206   const gchar *type_string;
1207
1208   gvs_filler (&child, children[0]);
1209   type_string = g_variant_type_info_get_type_string (child.type_info);
1210
1211   return child.size + 1 + strlen (type_string);
1212 }
1213
1214 static inline void
1215 gvs_variant_serialise (GVariantSerialised        value,
1216                        GVariantSerialisedFiller  gvs_filler,
1217                        const gpointer           *children,
1218                        gsize                     n_children)
1219 {
1220   GVariantSerialised child = { 0, };
1221   const gchar *type_string;
1222
1223   child.data = value.data;
1224
1225   gvs_filler (&child, children[0]);
1226   type_string = g_variant_type_info_get_type_string (child.type_info);
1227   value.data[child.size] = '\0';
1228   memcpy (value.data + child.size + 1, type_string, strlen (type_string));
1229 }
1230
1231 static inline gboolean
1232 gvs_variant_is_normal (GVariantSerialised value)
1233 {
1234   GVariantSerialised child;
1235   gboolean normal;
1236
1237   child = gvs_variant_get_child (value, 0);
1238
1239   normal = (child.data != NULL || child.size == 0) &&
1240            g_variant_serialised_is_normal (child);
1241
1242   g_variant_type_info_unref (child.type_info);
1243
1244   return normal;
1245 }
1246
1247
1248
1249 /* PART 2: Serialiser API {{{1
1250  *
1251  * This is the implementation of the API of the serialiser as advertised
1252  * in gvariant-serialiser.h.
1253  */
1254
1255 /* Dispatch Utilities {{{2
1256  *
1257  * These macros allow a given function (for example,
1258  * g_variant_serialiser_serialise) to be dispatched to the appropriate
1259  * type-specific function above (fixed/variable-sized maybe,
1260  * fixed/variable-sized array, tuple or variant).
1261  */
1262 #define DISPATCH_FIXED(type_info, before, after) \
1263   {                                                     \
1264     gsize fixed_size;                                   \
1265                                                         \
1266     g_variant_type_info_query_element (type_info, NULL, \
1267                                        &fixed_size);    \
1268                                                         \
1269     if (fixed_size)                                     \
1270       {                                                 \
1271         before ## fixed_sized ## after                  \
1272       }                                                 \
1273     else                                                \
1274       {                                                 \
1275         before ## variable_sized ## after               \
1276       }                                                 \
1277   }
1278
1279 #define DISPATCH_CASES(type_info, before, after) \
1280   switch (g_variant_type_info_get_type_char (type_info))        \
1281     {                                                           \
1282       case G_VARIANT_TYPE_INFO_CHAR_MAYBE:                      \
1283         DISPATCH_FIXED (type_info, before, _maybe ## after)     \
1284                                                                 \
1285       case G_VARIANT_TYPE_INFO_CHAR_ARRAY:                      \
1286         DISPATCH_FIXED (type_info, before, _array ## after)     \
1287                                                                 \
1288       case G_VARIANT_TYPE_INFO_CHAR_DICT_ENTRY:                 \
1289       case G_VARIANT_TYPE_INFO_CHAR_TUPLE:                      \
1290         {                                                       \
1291           before ## tuple ## after                              \
1292         }                                                       \
1293                                                                 \
1294       case G_VARIANT_TYPE_INFO_CHAR_VARIANT:                    \
1295         {                                                       \
1296           before ## variant ## after                            \
1297         }                                                       \
1298     }
1299
1300 /* Serialiser entry points {{{2
1301  *
1302  * These are the functions that are called in order for the serialiser
1303  * to do its thing.
1304  */
1305
1306 /* < private >
1307  * g_variant_serialised_n_children:
1308  * @serialised: a #GVariantSerialised
1309  *
1310  * For serialised data that represents a container value (maybes,
1311  * tuples, arrays, variants), determine how many child items are inside
1312  * that container.
1313  *
1314  * Returns: the number of children
1315  */
1316 gsize
1317 g_variant_serialised_n_children (GVariantSerialised serialised)
1318 {
1319   g_variant_serialised_check (serialised);
1320
1321   DISPATCH_CASES (serialised.type_info,
1322
1323                   return gvs_/**/,/**/_n_children (serialised);
1324
1325                  )
1326   g_assert_not_reached ();
1327 }
1328
1329 /* < private >
1330  * g_variant_serialised_get_child:
1331  * @serialised: a #GVariantSerialised
1332  * @index_: the index of the child to fetch
1333  *
1334  * Extracts a child from a serialised data representing a container
1335  * value.
1336  *
1337  * It is an error to call this function with an index out of bounds.
1338  *
1339  * If the result .data == %NULL and .size > 0 then there has been an
1340  * error extracting the requested fixed-sized value.  This number of
1341  * zero bytes needs to be allocated instead.
1342  *
1343  * In the case that .data == %NULL and .size == 0 then a zero-sized
1344  * item of a variable-sized type is being returned.
1345  *
1346  * .data is never non-%NULL if size is 0.
1347  *
1348  * Returns: a #GVariantSerialised for the child
1349  */
1350 GVariantSerialised
1351 g_variant_serialised_get_child (GVariantSerialised serialised,
1352                                 gsize              index_)
1353 {
1354   GVariantSerialised child;
1355
1356   g_variant_serialised_check (serialised);
1357
1358   if G_LIKELY (index_ < g_variant_serialised_n_children (serialised))
1359     {
1360       DISPATCH_CASES (serialised.type_info,
1361
1362                       child = gvs_/**/,/**/_get_child (serialised, index_);
1363                       g_assert (child.size || child.data == NULL);
1364                       g_variant_serialised_check (child);
1365                       return child;
1366
1367                      )
1368       g_assert_not_reached ();
1369     }
1370
1371   g_error ("Attempt to access item %"G_GSIZE_FORMAT
1372            " in a container with only %"G_GSIZE_FORMAT" items",
1373            index_, g_variant_serialised_n_children (serialised));
1374 }
1375
1376 /* < private >
1377  * g_variant_serialiser_serialise:
1378  * @serialised: a #GVariantSerialised, properly set up
1379  * @gvs_filler: the filler function
1380  * @children: an array of child items
1381  * @n_children: the size of @children
1382  *
1383  * Writes data in serialised form.
1384  *
1385  * The type_info field of @serialised must be filled in to type info for
1386  * the type that we are serialising.
1387  *
1388  * The size field of @serialised must be filled in with the value
1389  * returned by a previous call to g_variant_serialiser_needed_size().
1390  *
1391  * The data field of @serialised must be a pointer to a properly-aligned
1392  * memory region large enough to serialise into (ie: at least as big as
1393  * the size field).
1394  *
1395  * This function is only resonsible for serialising the top-level
1396  * container.  @gvs_filler is called on each child of the container in
1397  * order for all of the data of that child to be filled in.
1398  */
1399 void
1400 g_variant_serialiser_serialise (GVariantSerialised        serialised,
1401                                 GVariantSerialisedFiller  gvs_filler,
1402                                 const gpointer           *children,
1403                                 gsize                     n_children)
1404 {
1405   g_variant_serialised_check (serialised);
1406
1407   DISPATCH_CASES (serialised.type_info,
1408
1409                   gvs_/**/,/**/_serialise (serialised, gvs_filler,
1410                                            children, n_children);
1411                   return;
1412
1413                  )
1414   g_assert_not_reached ();
1415 }
1416
1417 /* < private >
1418  * g_variant_serialiser_needed_size:
1419  * @type_info: the type to serialise for
1420  * @gvs_filler: the filler function
1421  * @children: an array of child items
1422  * @n_children: the size of @children
1423  *
1424  * Determines how much memory would be needed to serialise this value.
1425  *
1426  * This function is only resonsible for performing calculations for the
1427  * top-level container.  @gvs_filler is called on each child of the
1428  * container in order to determine its size.
1429  */
1430 gsize
1431 g_variant_serialiser_needed_size (GVariantTypeInfo         *type_info,
1432                                   GVariantSerialisedFiller  gvs_filler,
1433                                   const gpointer           *children,
1434                                   gsize                     n_children)
1435 {
1436   DISPATCH_CASES (type_info,
1437
1438                   return gvs_/**/,/**/_needed_size (type_info, gvs_filler,
1439                                                     children, n_children);
1440
1441                  )
1442   g_assert_not_reached ();
1443 }
1444
1445 /* Byteswapping {{{2 */
1446
1447 /* < private >
1448  * g_variant_serialised_byteswap:
1449  * @value: a #GVariantSerialised
1450  *
1451  * Byte-swap serialised data.  The result of this function is only
1452  * well-defined if the data is in normal form.
1453  */
1454 void
1455 g_variant_serialised_byteswap (GVariantSerialised serialised)
1456 {
1457   gsize fixed_size;
1458   guint alignment;
1459
1460   g_variant_serialised_check (serialised);
1461
1462   if (!serialised.data)
1463     return;
1464
1465   /* the types we potentially need to byteswap are
1466    * exactly those with alignment requirements.
1467    */
1468   g_variant_type_info_query (serialised.type_info, &alignment, &fixed_size);
1469   if (!alignment)
1470     return;
1471
1472   /* if fixed size and alignment are equal then we are down
1473    * to the base integer type and we should swap it.  the
1474    * only exception to this is if we have a tuple with a
1475    * single item, and then swapping it will be OK anyway.
1476    */
1477   if (alignment + 1 == fixed_size)
1478     {
1479       switch (fixed_size)
1480       {
1481         case 2:
1482           {
1483             guint16 *ptr = (guint16 *) serialised.data;
1484
1485             g_assert_cmpint (serialised.size, ==, 2);
1486             *ptr = GUINT16_SWAP_LE_BE (*ptr);
1487           }
1488           return;
1489
1490         case 4:
1491           {
1492             guint32 *ptr = (guint32 *) serialised.data;
1493
1494             g_assert_cmpint (serialised.size, ==, 4);
1495             *ptr = GUINT32_SWAP_LE_BE (*ptr);
1496           }
1497           return;
1498
1499         case 8:
1500           {
1501             guint64 *ptr = (guint64 *) serialised.data;
1502
1503             g_assert_cmpint (serialised.size, ==, 8);
1504             *ptr = GUINT64_SWAP_LE_BE (*ptr);
1505           }
1506           return;
1507
1508         default:
1509           g_assert_not_reached ();
1510       }
1511     }
1512
1513   /* else, we have a container that potentially contains
1514    * some children that need to be byteswapped.
1515    */
1516   else
1517     {
1518       gsize children, i;
1519
1520       children = g_variant_serialised_n_children (serialised);
1521       for (i = 0; i < children; i++)
1522         {
1523           GVariantSerialised child;
1524
1525           child = g_variant_serialised_get_child (serialised, i);
1526           g_variant_serialised_byteswap (child);
1527           g_variant_type_info_unref (child.type_info);
1528         }
1529     }
1530 }
1531
1532 /* Normal form checking {{{2 */
1533
1534 /* < private >
1535  * g_variant_serialised_is_normal:
1536  * @serialised: a #GVariantSerialised
1537  *
1538  * Determines, recursively if @serialised is in normal form.  There is
1539  * precisely one normal form of serialised data for each possible value.
1540  *
1541  * It is possible that multiple byte sequences form the serialised data
1542  * for a given value if, for example, the padding bytes are filled in
1543  * with something other than zeros, but only one form is the normal
1544  * form.
1545  */
1546 gboolean
1547 g_variant_serialised_is_normal (GVariantSerialised serialised)
1548 {
1549   DISPATCH_CASES (serialised.type_info,
1550
1551                   return gvs_/**/,/**/_is_normal (serialised);
1552
1553                  )
1554
1555   if (serialised.data == NULL)
1556     return FALSE;
1557
1558   /* some hard-coded terminal cases */
1559   switch (g_variant_type_info_get_type_char (serialised.type_info))
1560     {
1561     case 'b': /* boolean */
1562       return serialised.data[0] < 2;
1563
1564     case 's': /* string */
1565       return g_variant_serialiser_is_string (serialised.data,
1566                                              serialised.size);
1567
1568     case 'o':
1569       return g_variant_serialiser_is_object_path (serialised.data,
1570                                                   serialised.size);
1571
1572     case 'g':
1573       return g_variant_serialiser_is_signature (serialised.data,
1574                                                 serialised.size);
1575
1576     default:
1577       /* all of the other types are fixed-sized numerical types for
1578        * which all possible values are valid (including various NaN
1579        * representations for floating point values).
1580        */
1581       return TRUE;
1582     }
1583 }
1584
1585 /* Validity-checking functions {{{2
1586  *
1587  * Checks if strings, object paths and signature strings are valid.
1588  */
1589
1590 /* < private >
1591  * g_variant_serialiser_is_string:
1592  * @data: a possible string
1593  * @size: the size of @data
1594  *
1595  * Ensures that @data is a valid string with a nul terminator at the end
1596  * and no nul bytes embedded.
1597  */
1598 gboolean
1599 g_variant_serialiser_is_string (gconstpointer data,
1600                                 gsize         size)
1601 {
1602   const gchar *expected_end;
1603   const gchar *end;
1604
1605   if (size == 0)
1606     return FALSE;
1607
1608   expected_end = ((gchar *) data) + size - 1;
1609
1610   if (*expected_end != '\0')
1611     return FALSE;
1612
1613   g_utf8_validate (data, size, &end);
1614
1615   return end == expected_end;
1616 }
1617
1618 /* < private >
1619  * g_variant_serialiser_is_object_path:
1620  * @data: a possible D-Bus object path
1621  * @size: the size of @data
1622  *
1623  * Performs the checks for being a valid string.
1624  *
1625  * Also, ensures that @data is a valid DBus object path, as per the D-Bus
1626  * specification.
1627  */
1628 gboolean
1629 g_variant_serialiser_is_object_path (gconstpointer data,
1630                                      gsize         size)
1631 {
1632   const gchar *string = data;
1633   gsize i;
1634
1635   if (!g_variant_serialiser_is_string (data, size))
1636     return FALSE;
1637
1638   /* The path must begin with an ASCII '/' (integer 47) character */
1639   if (string[0] != '/')
1640     return FALSE;
1641
1642   for (i = 1; string[i]; i++)
1643     /* Each element must only contain the ASCII characters
1644      * "[A-Z][a-z][0-9]_"
1645      */
1646     if (g_ascii_isalnum (string[i]) || string[i] == '_')
1647       ;
1648
1649     /* must consist of elements separated by slash characters. */
1650     else if (string[i] == '/')
1651       {
1652         /* No element may be the empty string. */
1653         /* Multiple '/' characters cannot occur in sequence. */
1654         if (string[i - 1] == '/')
1655           return FALSE;
1656       }
1657
1658     else
1659       return FALSE;
1660
1661   /* A trailing '/' character is not allowed unless the path is the
1662    * root path (a single '/' character).
1663    */
1664   if (i > 1 && string[i - 1] == '/')
1665     return FALSE;
1666
1667   return TRUE;
1668 }
1669
1670 /* < private >
1671  * g_variant_serialiser_is_signature:
1672  * @data: a possible D-Bus signature
1673  * @size: the size of @data
1674  *
1675  * Performs the checks for being a valid string.
1676  *
1677  * Also, ensures that @data is a valid D-Bus type signature, as per the
1678  * D-Bus specification.
1679  */
1680 gboolean
1681 g_variant_serialiser_is_signature (gconstpointer data,
1682                                    gsize         size)
1683 {
1684   const gchar *string = data;
1685   gsize first_invalid;
1686
1687   if (!g_variant_serialiser_is_string (data, size))
1688     return FALSE;
1689
1690   /* make sure no non-definite characters appear */
1691   first_invalid = strspn (string, "ybnqiuxthdvasog(){}");
1692   if (string[first_invalid])
1693     return FALSE;
1694
1695   /* make sure each type string is well-formed */
1696   while (*string)
1697     if (!g_variant_type_string_scan (string, NULL, &string))
1698       return FALSE;
1699
1700   return TRUE;
1701 }
1702
1703 /* Epilogue {{{1 */
1704 /* vim:set foldmethod=marker: */