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