Merge branch 'master' of drop.maemo.org:/git/monky
[monky] / src / dbus / dbus-string.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-string.c String utility class (internal to D-Bus implementation)
3  * 
4  * Copyright (C) 2002, 2003, 2004, 2005 Red Hat, Inc.
5  * Copyright (C) 2006 Ralf Habacker <ralf.habacker@freenet.de>
6  *
7  * Licensed under the Academic Free License version 2.1
8  * 
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #include "dbus-internals.h"
26 #include "dbus-string.h"
27 /* we allow a system header here, for speed/convenience */
28 #include <string.h>
29 /* for vsnprintf */
30 #include <stdio.h>
31 #define DBUS_CAN_USE_DBUS_STRING_PRIVATE 1
32 #include "dbus-string-private.h"
33 #include "dbus-marshal-basic.h" /* probably should be removed by moving the usage of DBUS_TYPE
34                                  * into the marshaling-related files
35                                  */
36 /* for DBUS_VA_COPY */
37 #include "dbus-sysdeps.h"
38
39 /**
40  * @defgroup DBusString DBusString class
41  * @ingroup  DBusInternals
42  * @brief DBusString data structure for safer string handling
43  *
44  * Types and functions related to DBusString. DBusString is intended
45  * to be a string class that makes it hard to mess up security issues
46  * (and just in general harder to write buggy code).  It should be
47  * used (or extended and then used) rather than the libc stuff in
48  * string.h.  The string class is a bit inconvenient at spots because
49  * it handles out-of-memory failures and tries to be extra-robust.
50  * 
51  * A DBusString has a maximum length set at initialization time; this
52  * can be used to ensure that a buffer doesn't get too big.  The
53  * _dbus_string_lengthen() method checks for overflow, and for max
54  * length being exceeded.
55  * 
56  * Try to avoid conversion to a plain C string, i.e. add methods on
57  * the string object instead, only convert to C string when passing
58  * things out to the public API. In particular, no sprintf, strcpy,
59  * strcat, any of that should be used. The GString feature of
60  * accepting negative numbers for "length of string" is also absent,
61  * because it could keep us from detecting bogus huge lengths. i.e. if
62  * we passed in some bogus huge length it would be taken to mean
63  * "current length of string" instead of "broken crack"
64  *
65  * @todo #DBusString needs a lot of cleaning up; some of the
66  * API is no longer used, and the API is pretty inconsistent.
67  * In particular all the "append" APIs, especially those involving
68  * alignment but probably lots of them, are no longer used by the
69  * marshaling code which always does "inserts" now.
70  */
71
72 /**
73  * @addtogroup DBusString
74  * @{
75  */
76
77 static void
78 fixup_alignment (DBusRealString *real)
79 {
80   unsigned char *aligned;
81   unsigned char *real_block;
82   unsigned int old_align_offset;
83
84   /* we have to have extra space in real->allocated for the align offset and nul byte */
85   _dbus_assert (real->len <= real->allocated - _DBUS_STRING_ALLOCATION_PADDING);
86   
87   old_align_offset = real->align_offset;
88   real_block = real->str - old_align_offset;
89   
90   aligned = _DBUS_ALIGN_ADDRESS (real_block, 8);
91
92   real->align_offset = aligned - real_block;
93   real->str = aligned;
94   
95   if (old_align_offset != real->align_offset)
96     {
97       /* Here comes the suck */
98       memmove (real_block + real->align_offset,
99                real_block + old_align_offset,
100                real->len + 1);
101     }
102
103   _dbus_assert (real->align_offset < 8);
104   _dbus_assert (_DBUS_ALIGN_ADDRESS (real->str, 8) == real->str);
105 }
106
107 static void
108 undo_alignment (DBusRealString *real)
109 {
110   if (real->align_offset != 0)
111     {
112       memmove (real->str - real->align_offset,
113                real->str,
114                real->len + 1);
115
116       real->str = real->str - real->align_offset;
117       real->align_offset = 0;
118     }
119 }
120
121 /**
122  * Initializes a string that can be up to the given allocation size
123  * before it has to realloc. The string starts life with zero length.
124  * The string must eventually be freed with _dbus_string_free().
125  * 
126  * @param str memory to hold the string
127  * @param allocate_size amount to preallocate
128  * @returns #TRUE on success, #FALSE if no memory
129  */
130 dbus_bool_t
131 _dbus_string_init_preallocated (DBusString *str,
132                                 int         allocate_size)
133 {
134   DBusRealString *real;
135   
136   _dbus_assert (str != NULL);
137
138   _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
139   
140   real = (DBusRealString*) str;
141
142   /* It's very important not to touch anything
143    * other than real->str if we're going to fail,
144    * since we also use this function to reset
145    * an existing string, e.g. in _dbus_string_steal_data()
146    */
147   
148   real->str = dbus_malloc (_DBUS_STRING_ALLOCATION_PADDING + allocate_size);
149   if (real->str == NULL)
150     return FALSE;  
151   
152   real->allocated = _DBUS_STRING_ALLOCATION_PADDING + allocate_size;
153   real->len = 0;
154   real->str[real->len] = '\0';
155   
156   real->max_length = _DBUS_STRING_MAX_MAX_LENGTH;
157   real->constant = FALSE;
158   real->locked = FALSE;
159   real->invalid = FALSE;
160   real->align_offset = 0;
161   
162   fixup_alignment (real);
163   
164   return TRUE;
165 }
166
167 /**
168  * Initializes a string. The string starts life with zero length.  The
169  * string must eventually be freed with _dbus_string_free().
170  * 
171  * @param str memory to hold the string
172  * @returns #TRUE on success, #FALSE if no memory
173  */
174 dbus_bool_t
175 _dbus_string_init (DBusString *str)
176 {
177   return _dbus_string_init_preallocated (str, 0);
178 }
179
180 #ifdef DBUS_BUILD_TESTS
181 /* The max length thing is sort of a historical artifact
182  * from a feature that turned out to be dumb; perhaps
183  * we should purge it entirely. The problem with
184  * the feature is that it looks like memory allocation
185  * failure, but is not a transient or resolvable failure.
186  */
187 static void
188 set_max_length (DBusString *str,
189                 int         max_length)
190 {
191   DBusRealString *real;
192   
193   real = (DBusRealString*) str;
194
195   real->max_length = max_length;
196 }
197 #endif /* DBUS_BUILD_TESTS */
198
199 /**
200  * Initializes a constant string. The value parameter is not copied
201  * (should be static), and the string may never be modified.
202  * It is safe but not necessary to call _dbus_string_free()
203  * on a const string. The string has a length limit of MAXINT - 8.
204  * 
205  * @param str memory to use for the string
206  * @param value a string to be stored in str (not copied!!!)
207  */
208 void
209 _dbus_string_init_const (DBusString *str,
210                          const char *value)
211 {
212   _dbus_assert (value != NULL);
213   
214   _dbus_string_init_const_len (str, value,
215                                strlen (value));
216 }
217
218 /**
219  * Initializes a constant string with a length. The value parameter is
220  * not copied (should be static), and the string may never be
221  * modified.  It is safe but not necessary to call _dbus_string_free()
222  * on a const string.
223  * 
224  * @param str memory to use for the string
225  * @param value a string to be stored in str (not copied!!!)
226  * @param len the length to use
227  */
228 void
229 _dbus_string_init_const_len (DBusString *str,
230                              const char *value,
231                              int         len)
232 {
233   DBusRealString *real;
234   
235   _dbus_assert (str != NULL);
236   _dbus_assert (len == 0 || value != NULL);
237   _dbus_assert (len <= _DBUS_STRING_MAX_MAX_LENGTH);
238   _dbus_assert (len >= 0);
239   
240   real = (DBusRealString*) str;
241   
242   real->str = (unsigned char*) value;
243   real->len = len;
244   real->allocated = real->len + _DBUS_STRING_ALLOCATION_PADDING; /* a lie, just to avoid special-case assertions... */
245   real->max_length = real->len + 1;
246   real->constant = TRUE;
247   real->locked = TRUE;
248   real->invalid = FALSE;
249   real->align_offset = 0;
250
251   /* We don't require const strings to be 8-byte aligned as the
252    * memory is coming from elsewhere.
253    */
254 }
255
256 /**
257  * Frees a string created by _dbus_string_init().
258  *
259  * @param str memory where the string is stored.
260  */
261 void
262 _dbus_string_free (DBusString *str)
263 {
264   DBusRealString *real = (DBusRealString*) str;
265   DBUS_GENERIC_STRING_PREAMBLE (real);
266   
267   if (real->constant)
268     return;
269   dbus_free (real->str - real->align_offset);
270
271   real->invalid = TRUE;
272 }
273
274 static dbus_bool_t
275 compact (DBusRealString *real,
276          int             max_waste)
277 {
278   unsigned char *new_str;
279   int new_allocated;
280   int waste;
281
282   waste = real->allocated - (real->len + _DBUS_STRING_ALLOCATION_PADDING);
283
284   if (waste <= max_waste)
285     return TRUE;
286
287   new_allocated = real->len + _DBUS_STRING_ALLOCATION_PADDING;
288
289   new_str = dbus_realloc (real->str - real->align_offset, new_allocated);
290   if (_DBUS_UNLIKELY (new_str == NULL))
291     return FALSE;
292
293   real->str = new_str + real->align_offset;
294   real->allocated = new_allocated;
295   fixup_alignment (real);
296
297   return TRUE;
298 }
299
300 #ifdef DBUS_BUILD_TESTS
301 /* Not using this feature at the moment,
302  * so marked DBUS_BUILD_TESTS-only
303  */
304 /**
305  * Locks a string such that any attempts to change the string will
306  * result in aborting the program. Also, if the string is wasting a
307  * lot of memory (allocation is sufficiently larger than what the
308  * string is really using), _dbus_string_lock() will realloc the
309  * string's data to "compact" it.
310  *
311  * @param str the string to lock.
312  */
313 void
314 _dbus_string_lock (DBusString *str)
315 {  
316   DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
317
318   real->locked = TRUE;
319
320   /* Try to realloc to avoid excess memory usage, since
321    * we know we won't change the string further
322    */
323 #define MAX_WASTE 48
324   compact (real, MAX_WASTE);
325 }
326 #endif /* DBUS_BUILD_TESTS */
327
328 static dbus_bool_t
329 reallocate_for_length (DBusRealString *real,
330                        int             new_length)
331 {
332   int new_allocated;
333   unsigned char *new_str;
334
335   /* at least double our old allocation to avoid O(n), avoiding
336    * overflow
337    */
338   if (real->allocated > (_DBUS_STRING_MAX_MAX_LENGTH + _DBUS_STRING_ALLOCATION_PADDING) / 2)
339     new_allocated = _DBUS_STRING_MAX_MAX_LENGTH + _DBUS_STRING_ALLOCATION_PADDING;
340   else
341     new_allocated = real->allocated * 2;
342
343   /* if you change the code just above here, run the tests without
344    * the following assert-only hack before you commit
345    */
346   /* This is keyed off asserts in addition to tests so when you
347    * disable asserts to profile, you don't get this destroyer
348    * of profiles.
349    */
350 #ifdef DBUS_DISABLE_ASSERT
351 #else
352 #ifdef DBUS_BUILD_TESTS
353   new_allocated = 0; /* ensure a realloc every time so that we go
354                       * through all malloc failure codepaths
355                       */
356 #endif /* DBUS_BUILD_TESTS */
357 #endif /* !DBUS_DISABLE_ASSERT */
358
359   /* But be sure we always alloc at least space for the new length */
360   new_allocated = MAX (new_allocated,
361                        new_length + _DBUS_STRING_ALLOCATION_PADDING);
362
363   _dbus_assert (new_allocated >= real->allocated); /* code relies on this */
364   new_str = dbus_realloc (real->str - real->align_offset, new_allocated);
365   if (_DBUS_UNLIKELY (new_str == NULL))
366     return FALSE;
367
368   real->str = new_str + real->align_offset;
369   real->allocated = new_allocated;
370   fixup_alignment (real);
371
372   return TRUE;
373 }
374
375 /**
376  * Compacts the string to avoid wasted memory.  Wasted memory is
377  * memory that is allocated but not actually required to store the
378  * current length of the string.  The compact is only done if more
379  * than the given amount of memory is being wasted (otherwise the
380  * waste is ignored and the call does nothing).
381  *
382  * @param str the string
383  * @param max_waste the maximum amount of waste to ignore
384  * @returns #FALSE if the compact failed due to realloc failure
385  */
386 dbus_bool_t
387 _dbus_string_compact (DBusString *str,
388                       int         max_waste)
389 {
390   DBUS_STRING_PREAMBLE (str);
391
392   return compact (real, max_waste);
393 }
394
395 static dbus_bool_t
396 set_length (DBusRealString *real,
397             int             new_length)
398 {
399   /* Note, we are setting the length not including nul termination */
400
401   /* exceeding max length is the same as failure to allocate memory */
402   if (_DBUS_UNLIKELY (new_length > real->max_length))
403     return FALSE;
404   else if (new_length > (real->allocated - _DBUS_STRING_ALLOCATION_PADDING) &&
405            _DBUS_UNLIKELY (!reallocate_for_length (real, new_length)))
406     return FALSE;
407   else
408     {
409       real->len = new_length;
410       real->str[new_length] = '\0';
411       return TRUE;
412     }
413 }
414
415 static dbus_bool_t
416 open_gap (int             len,
417           DBusRealString *dest,
418           int             insert_at)
419 {
420   if (len == 0)
421     return TRUE;
422
423   if (len > dest->max_length - dest->len)
424     return FALSE; /* detected overflow of dest->len + len below */
425   
426   if (!set_length (dest, dest->len + len))
427     return FALSE;
428
429   memmove (dest->str + insert_at + len, 
430            dest->str + insert_at,
431            dest->len - len - insert_at);
432
433   return TRUE;
434 }
435
436 #ifndef _dbus_string_get_data
437 /**
438  * Gets the raw character buffer from the string.  The returned buffer
439  * will be nul-terminated, but note that strings may contain binary
440  * data so there may be extra nul characters prior to the termination.
441  * This function should be little-used, extend DBusString or add
442  * stuff to dbus-sysdeps.c instead. It's an error to use this
443  * function on a const string.
444  *
445  * @param str the string
446  * @returns the data
447  */
448 char*
449 _dbus_string_get_data (DBusString *str)
450 {
451   DBUS_STRING_PREAMBLE (str);
452   
453   return (char*) real->str;
454 }
455 #endif /* _dbus_string_get_data */
456
457 /* only do the function if we don't have the macro */
458 #ifndef _dbus_string_get_const_data
459 /**
460  * Gets the raw character buffer from a const string.
461  *
462  * @param str the string
463  * @returns the string data
464  */
465 const char*
466 _dbus_string_get_const_data (const DBusString  *str)
467 {
468   DBUS_CONST_STRING_PREAMBLE (str);
469   
470   return (const char*) real->str;
471 }
472 #endif /* _dbus_string_get_const_data */
473
474 /**
475  * Gets a sub-portion of the raw character buffer from the
476  * string. The "len" field is required simply for error
477  * checking, to be sure you don't try to use more
478  * string than exists. The nul termination of the
479  * returned buffer remains at the end of the entire
480  * string, not at start + len.
481  *
482  * @param str the string
483  * @param start byte offset to return
484  * @param len length of segment to return
485  * @returns the string data
486  */
487 char*
488 _dbus_string_get_data_len (DBusString *str,
489                            int         start,
490                            int         len)
491 {
492   DBUS_STRING_PREAMBLE (str);
493   _dbus_assert (start >= 0);
494   _dbus_assert (len >= 0);
495   _dbus_assert (start <= real->len);
496   _dbus_assert (len <= real->len - start);
497   
498   return (char*) real->str + start;
499 }
500
501 /* only do the function if we don't have the macro */
502 #ifndef _dbus_string_get_const_data_len
503 /**
504  * const version of _dbus_string_get_data_len().
505  *
506  * @param str the string
507  * @param start byte offset to return
508  * @param len length of segment to return
509  * @returns the string data
510  */
511 const char*
512 _dbus_string_get_const_data_len (const DBusString  *str,
513                                  int                start,
514                                  int                len)
515 {
516   DBUS_CONST_STRING_PREAMBLE (str);
517   _dbus_assert (start >= 0);
518   _dbus_assert (len >= 0);
519   _dbus_assert (start <= real->len);
520   _dbus_assert (len <= real->len - start);
521   
522   return (const char*) real->str + start;
523 }
524 #endif /* _dbus_string_get_const_data_len */
525
526 /* only do the function if we don't have the macro */
527 #ifndef _dbus_string_set_byte
528 /**
529  * Sets the value of the byte at the given position.
530  *
531  * @param str the string
532  * @param i the position
533  * @param byte the new value
534  */
535 void
536 _dbus_string_set_byte (DBusString    *str,
537                        int            i,
538                        unsigned char  byte)
539 {
540   DBUS_STRING_PREAMBLE (str);
541   _dbus_assert (i < real->len);
542   _dbus_assert (i >= 0);
543   
544   real->str[i] = byte;
545 }
546 #endif /* _dbus_string_set_byte */
547
548 /* only have the function if we didn't create a macro */
549 #ifndef _dbus_string_get_byte
550 /**
551  * Gets the byte at the given position. It is
552  * allowed to ask for the nul byte at the end of
553  * the string.
554  *
555  * @param str the string
556  * @param start the position
557  * @returns the byte at that position
558  */
559 unsigned char
560 _dbus_string_get_byte (const DBusString  *str,
561                        int                start)
562 {
563   DBUS_CONST_STRING_PREAMBLE (str);
564   _dbus_assert (start <= real->len);
565   _dbus_assert (start >= 0);
566   
567   return real->str[start];
568 }
569 #endif /* _dbus_string_get_byte */
570
571 /**
572  * Inserts a number of bytes of a given value at the
573  * given position.
574  *
575  * @param str the string
576  * @param i the position
577  * @param n_bytes number of bytes
578  * @param byte the value to insert
579  * @returns #TRUE on success
580  */
581 dbus_bool_t
582 _dbus_string_insert_bytes (DBusString   *str,
583                            int           i,
584                            int           n_bytes,
585                            unsigned char byte)
586 {
587   DBUS_STRING_PREAMBLE (str);
588   _dbus_assert (i <= real->len);
589   _dbus_assert (i >= 0);
590   _dbus_assert (n_bytes >= 0);
591
592   if (n_bytes == 0)
593     return TRUE;
594   
595   if (!open_gap (n_bytes, real, i))
596     return FALSE;
597   
598   memset (real->str + i, byte, n_bytes);
599
600   return TRUE;
601 }
602
603 /**
604  * Inserts a single byte at the given position.
605  *
606  * @param str the string
607  * @param i the position
608  * @param byte the value to insert
609  * @returns #TRUE on success
610  */
611 dbus_bool_t
612 _dbus_string_insert_byte (DBusString   *str,
613                            int           i,
614                            unsigned char byte)
615 {
616   DBUS_STRING_PREAMBLE (str);
617   _dbus_assert (i <= real->len);
618   _dbus_assert (i >= 0);
619   
620   if (!open_gap (1, real, i))
621     return FALSE;
622
623   real->str[i] = byte;
624
625   return TRUE;
626 }
627
628 /**
629  * Like _dbus_string_get_data(), but removes the
630  * gotten data from the original string. The caller
631  * must free the data returned. This function may
632  * fail due to lack of memory, and return #FALSE.
633  *
634  * @param str the string
635  * @param data_return location to return the buffer
636  * @returns #TRUE on success
637  */
638 dbus_bool_t
639 _dbus_string_steal_data (DBusString        *str,
640                          char             **data_return)
641 {
642   int old_max_length;
643   DBUS_STRING_PREAMBLE (str);
644   _dbus_assert (data_return != NULL);
645
646   undo_alignment (real);
647   
648   *data_return = (char*) real->str;
649
650   old_max_length = real->max_length;
651   
652   /* reset the string */
653   if (!_dbus_string_init (str))
654     {
655       /* hrm, put it back then */
656       real->str = (unsigned char*) *data_return;
657       *data_return = NULL;
658       fixup_alignment (real);
659       return FALSE;
660     }
661
662   real->max_length = old_max_length;
663
664   return TRUE;
665 }
666
667 #ifdef DBUS_BUILD_TESTS
668 /**
669  * Like _dbus_string_get_data_len(), but removes the gotten data from
670  * the original string. The caller must free the data returned. This
671  * function may fail due to lack of memory, and return #FALSE.
672  * The returned string is nul-terminated and has length len.
673  *
674  * @todo this function is broken because on failure it
675  * may corrupt the source string.
676  * 
677  * @param str the string
678  * @param data_return location to return the buffer
679  * @param start the start of segment to steal
680  * @param len the length of segment to steal
681  * @returns #TRUE on success
682  */
683 dbus_bool_t
684 _dbus_string_steal_data_len (DBusString        *str,
685                              char             **data_return,
686                              int                start,
687                              int                len)
688 {
689   DBusString dest;
690   DBUS_STRING_PREAMBLE (str);
691   _dbus_assert (data_return != NULL);
692   _dbus_assert (start >= 0);
693   _dbus_assert (len >= 0);
694   _dbus_assert (start <= real->len);
695   _dbus_assert (len <= real->len - start);
696
697   if (!_dbus_string_init (&dest))
698     return FALSE;
699
700   set_max_length (&dest, real->max_length);
701   
702   if (!_dbus_string_move_len (str, start, len, &dest, 0))
703     {
704       _dbus_string_free (&dest);
705       return FALSE;
706     }
707
708   _dbus_warn ("Broken code in _dbus_string_steal_data_len(), see @todo, FIXME\n");
709   if (!_dbus_string_steal_data (&dest, data_return))
710     {
711       _dbus_string_free (&dest);
712       return FALSE;
713     }
714
715   _dbus_string_free (&dest);
716   return TRUE;
717 }
718 #endif /* DBUS_BUILD_TESTS */
719
720 /**
721  * Copies the data from the string into a char*
722  *
723  * @param str the string
724  * @param data_return place to return the data
725  * @returns #TRUE on success, #FALSE on no memory
726  */
727 dbus_bool_t
728 _dbus_string_copy_data (const DBusString  *str,
729                         char             **data_return)
730 {
731   DBUS_CONST_STRING_PREAMBLE (str);
732   _dbus_assert (data_return != NULL);
733   
734   *data_return = dbus_malloc (real->len + 1);
735   if (*data_return == NULL)
736     return FALSE;
737
738   memcpy (*data_return, real->str, real->len + 1);
739
740   return TRUE;
741 }
742
743 /**
744  * Copies the contents of a DBusString into a different buffer. It is
745  * a bug if avail_len is too short to hold the string contents. nul
746  * termination is not copied, just the supplied bytes.
747  * 
748  * @param str a string
749  * @param buffer a C buffer to copy data to
750  * @param avail_len maximum length of C buffer
751  */
752 void
753 _dbus_string_copy_to_buffer (const DBusString  *str,
754                              char              *buffer,
755                              int                avail_len)
756 {
757   DBUS_CONST_STRING_PREAMBLE (str);
758
759   _dbus_assert (avail_len >= 0);
760   _dbus_assert (avail_len >= real->len);
761   
762   memcpy (buffer, real->str, real->len);
763 }
764
765 /**
766  * Copies the contents of a DBusString into a different buffer. It is
767  * a bug if avail_len is too short to hold the string contents plus a
768  * nul byte. 
769  * 
770  * @param str a string
771  * @param buffer a C buffer to copy data to
772  * @param avail_len maximum length of C buffer
773  */
774 void
775 _dbus_string_copy_to_buffer_with_nul (const DBusString  *str,
776                                       char              *buffer,
777                                       int                avail_len)
778 {
779   DBUS_CONST_STRING_PREAMBLE (str);
780
781   _dbus_assert (avail_len >= 0);
782   _dbus_assert (avail_len > real->len);
783   
784   memcpy (buffer, real->str, real->len+1);
785 }
786
787 #ifdef DBUS_BUILD_TESTS
788 /**
789  * Copies a segment of the string into a char*
790  *
791  * @param str the string
792  * @param data_return place to return the data
793  * @param start start index
794  * @param len length to copy
795  * @returns #FALSE if no memory
796  */
797 dbus_bool_t
798 _dbus_string_copy_data_len (const DBusString  *str,
799                             char             **data_return,
800                             int                start,
801                             int                len)
802 {
803   DBusString dest;
804
805   DBUS_CONST_STRING_PREAMBLE (str);
806   _dbus_assert (data_return != NULL);
807   _dbus_assert (start >= 0);
808   _dbus_assert (len >= 0);
809   _dbus_assert (start <= real->len);
810   _dbus_assert (len <= real->len - start);
811
812   if (!_dbus_string_init (&dest))
813     return FALSE;
814
815   set_max_length (&dest, real->max_length);
816
817   if (!_dbus_string_copy_len (str, start, len, &dest, 0))
818     {
819       _dbus_string_free (&dest);
820       return FALSE;
821     }
822
823   if (!_dbus_string_steal_data (&dest, data_return))
824     {
825       _dbus_string_free (&dest);
826       return FALSE;
827     }
828
829   _dbus_string_free (&dest);
830   return TRUE;
831 }
832 #endif /* DBUS_BUILD_TESTS */
833
834 /* Only have the function if we don't have the macro */
835 #ifndef _dbus_string_get_length
836 /**
837  * Gets the length of a string (not including nul termination).
838  *
839  * @returns the length.
840  */
841 int
842 _dbus_string_get_length (const DBusString  *str)
843 {
844   DBUS_CONST_STRING_PREAMBLE (str);
845   
846   return real->len;
847 }
848 #endif /* !_dbus_string_get_length */
849
850 /**
851  * Makes a string longer by the given number of bytes.  Checks whether
852  * adding additional_length to the current length would overflow an
853  * integer, and checks for exceeding a string's max length.
854  * The new bytes are not initialized, other than nul-terminating
855  * the end of the string. The uninitialized bytes may contain
856  * nul bytes or other junk.
857  *
858  * @param str a string
859  * @param additional_length length to add to the string.
860  * @returns #TRUE on success.
861  */
862 dbus_bool_t
863 _dbus_string_lengthen (DBusString *str,
864                        int         additional_length)
865 {
866   DBUS_STRING_PREAMBLE (str);  
867   _dbus_assert (additional_length >= 0);
868
869   if (_DBUS_UNLIKELY (additional_length > real->max_length - real->len))
870     return FALSE; /* would overflow */
871   
872   return set_length (real,
873                      real->len + additional_length);
874 }
875
876 /**
877  * Makes a string shorter by the given number of bytes.
878  *
879  * @param str a string
880  * @param length_to_remove length to remove from the string.
881  */
882 void
883 _dbus_string_shorten (DBusString *str,
884                       int         length_to_remove)
885 {
886   DBUS_STRING_PREAMBLE (str);
887   _dbus_assert (length_to_remove >= 0);
888   _dbus_assert (length_to_remove <= real->len);
889
890   set_length (real,
891               real->len - length_to_remove);
892 }
893
894 /**
895  * Sets the length of a string. Can be used to truncate or lengthen
896  * the string. If the string is lengthened, the function may fail and
897  * return #FALSE. Newly-added bytes are not initialized, as with
898  * _dbus_string_lengthen().
899  *
900  * @param str a string
901  * @param length new length of the string.
902  * @returns #FALSE on failure.
903  */
904 dbus_bool_t
905 _dbus_string_set_length (DBusString *str,
906                          int         length)
907 {
908   DBUS_STRING_PREAMBLE (str);
909   _dbus_assert (length >= 0);
910
911   return set_length (real, length);
912 }
913
914 static dbus_bool_t
915 align_insert_point_then_open_gap (DBusString *str,
916                                   int        *insert_at_p,
917                                   int         alignment,
918                                   int         gap_size)
919 {
920   unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
921   unsigned long gap_pos;
922   int insert_at;
923   int delta;
924   DBUS_STRING_PREAMBLE (str);
925   _dbus_assert (alignment >= 1);
926   _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
927
928   insert_at = *insert_at_p;
929
930   _dbus_assert (insert_at <= real->len);
931   
932   gap_pos = _DBUS_ALIGN_VALUE (insert_at, alignment);
933   new_len = real->len + (gap_pos - insert_at) + gap_size;
934   
935   if (_DBUS_UNLIKELY (new_len > (unsigned long) real->max_length))
936     return FALSE;
937   
938   delta = new_len - real->len;
939   _dbus_assert (delta >= 0);
940
941   if (delta == 0) /* only happens if gap_size == 0 and insert_at is aligned already */
942     {
943       _dbus_assert (((unsigned long) *insert_at_p) == gap_pos);
944       return TRUE;
945     }
946
947   if (_DBUS_UNLIKELY (!open_gap (new_len - real->len,
948                                  real, insert_at)))
949     return FALSE;
950
951   /* nul the padding if we had to add any padding */
952   if (gap_size < delta)
953     {
954       memset (&real->str[insert_at], '\0',
955               gap_pos - insert_at);
956     }
957
958   *insert_at_p = gap_pos;
959   
960   return TRUE;
961 }
962
963 static dbus_bool_t
964 align_length_then_lengthen (DBusString *str,
965                             int         alignment,
966                             int         then_lengthen_by)
967 {
968   int insert_at;
969
970   insert_at = _dbus_string_get_length (str);
971   
972   return align_insert_point_then_open_gap (str,
973                                            &insert_at,
974                                            alignment, then_lengthen_by);
975 }
976
977 /**
978  * Align the length of a string to a specific alignment (typically 4 or 8)
979  * by appending nul bytes to the string.
980  *
981  * @param str a string
982  * @param alignment the alignment
983  * @returns #FALSE if no memory
984  */
985 dbus_bool_t
986 _dbus_string_align_length (DBusString *str,
987                            int         alignment)
988 {
989   return align_length_then_lengthen (str, alignment, 0);
990 }
991
992 /**
993  * Preallocate extra_bytes such that a future lengthening of the
994  * string by extra_bytes is guaranteed to succeed without an out of
995  * memory error.
996  *
997  * @param str a string
998  * @param extra_bytes bytes to alloc
999  * @returns #FALSE if no memory
1000  */
1001 dbus_bool_t
1002 _dbus_string_alloc_space (DBusString        *str,
1003                           int                extra_bytes)
1004 {
1005   if (!_dbus_string_lengthen (str, extra_bytes))
1006     return FALSE;
1007   _dbus_string_shorten (str, extra_bytes);
1008
1009   return TRUE;
1010 }
1011
1012 static dbus_bool_t
1013 append (DBusRealString *real,
1014         const char     *buffer,
1015         int             buffer_len)
1016 {
1017   if (buffer_len == 0)
1018     return TRUE;
1019
1020   if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
1021     return FALSE;
1022
1023   memcpy (real->str + (real->len - buffer_len),
1024           buffer,
1025           buffer_len);
1026
1027   return TRUE;
1028 }
1029
1030 /**
1031  * Appends a nul-terminated C-style string to a DBusString.
1032  *
1033  * @param str the DBusString
1034  * @param buffer the nul-terminated characters to append
1035  * @returns #FALSE if not enough memory.
1036  */
1037 dbus_bool_t
1038 _dbus_string_append (DBusString *str,
1039                      const char *buffer)
1040 {
1041   unsigned long buffer_len;
1042   
1043   DBUS_STRING_PREAMBLE (str);
1044   _dbus_assert (buffer != NULL);
1045   
1046   buffer_len = strlen (buffer);
1047   if (buffer_len > (unsigned long) real->max_length)
1048     return FALSE;
1049   
1050   return append (real, buffer, buffer_len);
1051 }
1052
1053 /** assign 2 bytes from one string to another */
1054 #define ASSIGN_2_OCTETS(p, octets) \
1055   *((dbus_uint16_t*)(p)) = *((dbus_uint16_t*)(octets));
1056
1057 /** assign 4 bytes from one string to another */
1058 #define ASSIGN_4_OCTETS(p, octets) \
1059   *((dbus_uint32_t*)(p)) = *((dbus_uint32_t*)(octets));
1060
1061 #ifdef DBUS_HAVE_INT64
1062 /** assign 8 bytes from one string to another */
1063 #define ASSIGN_8_OCTETS(p, octets) \
1064   *((dbus_uint64_t*)(p)) = *((dbus_uint64_t*)(octets));
1065 #else
1066 /** assign 8 bytes from one string to another */
1067 #define ASSIGN_8_OCTETS(p, octets)              \
1068 do {                                            \
1069   unsigned char *b;                             \
1070                                                 \
1071   b = p;                                        \
1072                                                 \
1073   *b++ = octets[0];                             \
1074   *b++ = octets[1];                             \
1075   *b++ = octets[2];                             \
1076   *b++ = octets[3];                             \
1077   *b++ = octets[4];                             \
1078   *b++ = octets[5];                             \
1079   *b++ = octets[6];                             \
1080   *b++ = octets[7];                             \
1081   _dbus_assert (b == p + 8);                    \
1082 } while (0)
1083 #endif /* DBUS_HAVE_INT64 */
1084
1085 #ifdef DBUS_BUILD_TESTS
1086 /**
1087  * Appends 4 bytes aligned on a 4 byte boundary
1088  * with any alignment padding initialized to 0.
1089  *
1090  * @param str the DBusString
1091  * @param octets 4 bytes to append
1092  * @returns #FALSE if not enough memory.
1093  */
1094 dbus_bool_t
1095 _dbus_string_append_4_aligned (DBusString         *str,
1096                                const unsigned char octets[4])
1097 {
1098   DBUS_STRING_PREAMBLE (str);
1099   
1100   if (!align_length_then_lengthen (str, 4, 4))
1101     return FALSE;
1102
1103   ASSIGN_4_OCTETS (real->str + (real->len - 4), octets);
1104
1105   return TRUE;
1106 }
1107 #endif /* DBUS_BUILD_TESTS */
1108
1109 #ifdef DBUS_BUILD_TESTS
1110 /**
1111  * Appends 8 bytes aligned on an 8 byte boundary
1112  * with any alignment padding initialized to 0.
1113  *
1114  * @param str the DBusString
1115  * @param octets 8 bytes to append
1116  * @returns #FALSE if not enough memory.
1117  */
1118 dbus_bool_t
1119 _dbus_string_append_8_aligned (DBusString         *str,
1120                                const unsigned char octets[8])
1121 {
1122   DBUS_STRING_PREAMBLE (str);
1123   
1124   if (!align_length_then_lengthen (str, 8, 8))
1125     return FALSE;
1126
1127   ASSIGN_8_OCTETS (real->str + (real->len - 8), octets);
1128
1129   return TRUE;
1130 }
1131 #endif /* DBUS_BUILD_TESTS */
1132
1133 /**
1134  * Inserts 2 bytes aligned on a 2 byte boundary
1135  * with any alignment padding initialized to 0.
1136  *
1137  * @param str the DBusString
1138  * @param insert_at where to insert
1139  * @param octets 2 bytes to insert
1140  * @returns #FALSE if not enough memory.
1141  */
1142 dbus_bool_t
1143 _dbus_string_insert_2_aligned (DBusString         *str,
1144                                int                 insert_at,
1145                                const unsigned char octets[4])
1146 {
1147   DBUS_STRING_PREAMBLE (str);
1148   
1149   if (!align_insert_point_then_open_gap (str, &insert_at, 2, 2))
1150     return FALSE;
1151
1152   ASSIGN_2_OCTETS (real->str + insert_at, octets);
1153
1154   return TRUE;
1155 }
1156
1157 /**
1158  * Inserts 4 bytes aligned on a 4 byte boundary
1159  * with any alignment padding initialized to 0.
1160  *
1161  * @param str the DBusString
1162  * @param insert_at where to insert
1163  * @param octets 4 bytes to insert
1164  * @returns #FALSE if not enough memory.
1165  */
1166 dbus_bool_t
1167 _dbus_string_insert_4_aligned (DBusString         *str,
1168                                int                 insert_at,
1169                                const unsigned char octets[4])
1170 {
1171   DBUS_STRING_PREAMBLE (str);
1172   
1173   if (!align_insert_point_then_open_gap (str, &insert_at, 4, 4))
1174     return FALSE;
1175
1176   ASSIGN_4_OCTETS (real->str + insert_at, octets);
1177
1178   return TRUE;
1179 }
1180
1181 /**
1182  * Inserts 8 bytes aligned on an 8 byte boundary
1183  * with any alignment padding initialized to 0.
1184  *
1185  * @param str the DBusString
1186  * @param insert_at where to insert
1187  * @param octets 8 bytes to insert
1188  * @returns #FALSE if not enough memory.
1189  */
1190 dbus_bool_t
1191 _dbus_string_insert_8_aligned (DBusString         *str,
1192                                int                 insert_at,
1193                                const unsigned char octets[8])
1194 {
1195   DBUS_STRING_PREAMBLE (str);
1196   
1197   if (!align_insert_point_then_open_gap (str, &insert_at, 8, 8))
1198     return FALSE;
1199
1200   _dbus_assert (_DBUS_ALIGN_VALUE (insert_at, 8) == (unsigned) insert_at);
1201   
1202   ASSIGN_8_OCTETS (real->str + insert_at, octets);
1203
1204   return TRUE;
1205 }
1206
1207
1208 /**
1209  * Inserts padding at *insert_at such to align it to the given
1210  * boundary. Initializes the padding to nul bytes. Sets *insert_at
1211  * to the aligned position.
1212  *
1213  * @param str the DBusString
1214  * @param insert_at location to be aligned
1215  * @param alignment alignment boundary (1, 2, 4, or 8)
1216  * @returns #FALSE if not enough memory.
1217  */
1218 dbus_bool_t
1219 _dbus_string_insert_alignment (DBusString        *str,
1220                                int               *insert_at,
1221                                int                alignment)
1222 {
1223   DBUS_STRING_PREAMBLE (str);
1224   
1225   if (!align_insert_point_then_open_gap (str, insert_at, alignment, 0))
1226     return FALSE;
1227
1228   _dbus_assert (_DBUS_ALIGN_VALUE (*insert_at, alignment) == (unsigned) *insert_at);
1229
1230   return TRUE;
1231 }
1232
1233 /**
1234  * Appends a printf-style formatted string
1235  * to the #DBusString.
1236  *
1237  * @param str the string
1238  * @param format printf format
1239  * @param args variable argument list
1240  * @returns #FALSE if no memory
1241  */
1242 dbus_bool_t
1243 _dbus_string_append_printf_valist  (DBusString        *str,
1244                                     const char        *format,
1245                                     va_list            args)
1246 {
1247   int len;
1248   va_list args_copy;
1249
1250   DBUS_STRING_PREAMBLE (str);
1251
1252   DBUS_VA_COPY (args_copy, args);
1253
1254   /* Measure the message length without terminating nul */
1255   len = _dbus_printf_string_upper_bound (format, args);
1256
1257   if (!_dbus_string_lengthen (str, len))
1258     {
1259       /* don't leak the copy */
1260       va_end (args_copy);
1261       return FALSE;
1262     }
1263   
1264   vsprintf ((char*) (real->str + (real->len - len)),
1265             format, args_copy);
1266
1267   va_end (args_copy);
1268
1269   return TRUE;
1270 }
1271
1272 /**
1273  * Appends a printf-style formatted string
1274  * to the #DBusString.
1275  *
1276  * @param str the string
1277  * @param format printf format
1278  * @returns #FALSE if no memory
1279  */
1280 dbus_bool_t
1281 _dbus_string_append_printf (DBusString        *str,
1282                             const char        *format,
1283                             ...)
1284 {
1285   va_list args;
1286   dbus_bool_t retval;
1287   
1288   va_start (args, format);
1289   retval = _dbus_string_append_printf_valist (str, format, args);
1290   va_end (args);
1291
1292   return retval;
1293 }
1294
1295 /**
1296  * Appends block of bytes with the given length to a DBusString.
1297  *
1298  * @param str the DBusString
1299  * @param buffer the bytes to append
1300  * @param len the number of bytes to append
1301  * @returns #FALSE if not enough memory.
1302  */
1303 dbus_bool_t
1304 _dbus_string_append_len (DBusString *str,
1305                          const char *buffer,
1306                          int         len)
1307 {
1308   DBUS_STRING_PREAMBLE (str);
1309   _dbus_assert (buffer != NULL);
1310   _dbus_assert (len >= 0);
1311
1312   return append (real, buffer, len);
1313 }
1314
1315 /**
1316  * Appends a single byte to the string, returning #FALSE
1317  * if not enough memory.
1318  *
1319  * @param str the string
1320  * @param byte the byte to append
1321  * @returns #TRUE on success
1322  */
1323 dbus_bool_t
1324 _dbus_string_append_byte (DBusString    *str,
1325                           unsigned char  byte)
1326 {
1327   DBUS_STRING_PREAMBLE (str);
1328
1329   if (!set_length (real, real->len + 1))
1330     return FALSE;
1331
1332   real->str[real->len-1] = byte;
1333
1334   return TRUE;
1335 }
1336
1337 #ifdef DBUS_BUILD_TESTS
1338 /**
1339  * Appends a single Unicode character, encoding the character
1340  * in UTF-8 format.
1341  *
1342  * @param str the string
1343  * @param ch the Unicode character
1344  */
1345 dbus_bool_t
1346 _dbus_string_append_unichar (DBusString    *str,
1347                              dbus_unichar_t ch)
1348 {
1349   int len;
1350   int first;
1351   int i;
1352   unsigned char *out;
1353   
1354   DBUS_STRING_PREAMBLE (str);
1355
1356   /* this code is from GLib but is pretty standard I think */
1357   
1358   len = 0;
1359   
1360   if (ch < 0x80)
1361     {
1362       first = 0;
1363       len = 1;
1364     }
1365   else if (ch < 0x800)
1366     {
1367       first = 0xc0;
1368       len = 2;
1369     }
1370   else if (ch < 0x10000)
1371     {
1372       first = 0xe0;
1373       len = 3;
1374     }
1375    else if (ch < 0x200000)
1376     {
1377       first = 0xf0;
1378       len = 4;
1379     }
1380   else if (ch < 0x4000000)
1381     {
1382       first = 0xf8;
1383       len = 5;
1384     }
1385   else
1386     {
1387       first = 0xfc;
1388       len = 6;
1389     }
1390
1391   if (len > (real->max_length - real->len))
1392     return FALSE; /* real->len + len would overflow */
1393   
1394   if (!set_length (real, real->len + len))
1395     return FALSE;
1396
1397   out = real->str + (real->len - len);
1398   
1399   for (i = len - 1; i > 0; --i)
1400     {
1401       out[i] = (ch & 0x3f) | 0x80;
1402       ch >>= 6;
1403     }
1404   out[0] = ch | first;
1405
1406   return TRUE;
1407 }
1408 #endif /* DBUS_BUILD_TESTS */
1409
1410 static void
1411 delete (DBusRealString *real,
1412         int             start,
1413         int             len)
1414 {
1415   if (len == 0)
1416     return;
1417   
1418   memmove (real->str + start, real->str + start + len, real->len - (start + len));
1419   real->len -= len;
1420   real->str[real->len] = '\0';
1421 }
1422
1423 /**
1424  * Deletes a segment of a DBusString with length len starting at
1425  * start. (Hint: to clear an entire string, setting length to 0
1426  * with _dbus_string_set_length() is easier.)
1427  *
1428  * @param str the DBusString
1429  * @param start where to start deleting
1430  * @param len the number of bytes to delete
1431  */
1432 void
1433 _dbus_string_delete (DBusString       *str,
1434                      int               start,
1435                      int               len)
1436 {
1437   DBUS_STRING_PREAMBLE (str);
1438   _dbus_assert (start >= 0);
1439   _dbus_assert (len >= 0);
1440   _dbus_assert (start <= real->len);
1441   _dbus_assert (len <= real->len - start);
1442   
1443   delete (real, start, len);
1444 }
1445
1446 static dbus_bool_t
1447 copy (DBusRealString *source,
1448       int             start,
1449       int             len,
1450       DBusRealString *dest,
1451       int             insert_at)
1452 {
1453   if (len == 0)
1454     return TRUE;
1455
1456   if (!open_gap (len, dest, insert_at))
1457     return FALSE;
1458   
1459   memmove (dest->str + insert_at,
1460            source->str + start,
1461            len);
1462
1463   return TRUE;
1464 }
1465
1466 /**
1467  * Checks assertions for two strings we're copying a segment between,
1468  * and declares real_source/real_dest variables.
1469  *
1470  * @param source the source string
1471  * @param start the starting offset
1472  * @param dest the dest string
1473  * @param insert_at where the copied segment is inserted
1474  */
1475 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at)       \
1476   DBusRealString *real_source = (DBusRealString*) source;               \
1477   DBusRealString *real_dest = (DBusRealString*) dest;                   \
1478   _dbus_assert ((source) != (dest));                                    \
1479   DBUS_GENERIC_STRING_PREAMBLE (real_source);                           \
1480   DBUS_GENERIC_STRING_PREAMBLE (real_dest);                             \
1481   _dbus_assert (!real_dest->constant);                                  \
1482   _dbus_assert (!real_dest->locked);                                    \
1483   _dbus_assert ((start) >= 0);                                          \
1484   _dbus_assert ((start) <= real_source->len);                           \
1485   _dbus_assert ((insert_at) >= 0);                                      \
1486   _dbus_assert ((insert_at) <= real_dest->len)
1487
1488 /**
1489  * Moves the end of one string into another string. Both strings
1490  * must be initialized, valid strings.
1491  *
1492  * @param source the source string
1493  * @param start where to chop off the source string
1494  * @param dest the destination string
1495  * @param insert_at where to move the chopped-off part of source string
1496  * @returns #FALSE if not enough memory
1497  */
1498 dbus_bool_t
1499 _dbus_string_move (DBusString       *source,
1500                    int               start,
1501                    DBusString       *dest,
1502                    int               insert_at)
1503 {
1504   DBusRealString *real_source = (DBusRealString*) source;
1505   _dbus_assert (start <= real_source->len);
1506   
1507   return _dbus_string_move_len (source, start,
1508                                 real_source->len - start,
1509                                 dest, insert_at);
1510 }
1511
1512 /**
1513  * Like _dbus_string_move(), but does not delete the section
1514  * of the source string that's copied to the dest string.
1515  *
1516  * @param source the source string
1517  * @param start where to start copying the source string
1518  * @param dest the destination string
1519  * @param insert_at where to place the copied part of source string
1520  * @returns #FALSE if not enough memory
1521  */
1522 dbus_bool_t
1523 _dbus_string_copy (const DBusString *source,
1524                    int               start,
1525                    DBusString       *dest,
1526                    int               insert_at)
1527 {
1528   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1529
1530   return copy (real_source, start,
1531                real_source->len - start,
1532                real_dest,
1533                insert_at);
1534 }
1535
1536 /**
1537  * Like _dbus_string_move(), but can move a segment from
1538  * the middle of the source string.
1539  *
1540  * @todo this doesn't do anything with max_length field.
1541  * we should probably just kill the max_length field though.
1542  * 
1543  * @param source the source string
1544  * @param start first byte of source string to move
1545  * @param len length of segment to move
1546  * @param dest the destination string
1547  * @param insert_at where to move the bytes from the source string
1548  * @returns #FALSE if not enough memory
1549  */
1550 dbus_bool_t
1551 _dbus_string_move_len (DBusString       *source,
1552                        int               start,
1553                        int               len,
1554                        DBusString       *dest,
1555                        int               insert_at)
1556
1557 {
1558   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1559   _dbus_assert (len >= 0);
1560   _dbus_assert ((start + len) <= real_source->len);
1561
1562
1563   if (len == 0)
1564     {
1565       return TRUE;
1566     }
1567   else if (start == 0 &&
1568            len == real_source->len &&
1569            real_dest->len == 0)
1570     {
1571       /* Short-circuit moving an entire existing string to an empty string
1572        * by just swapping the buffers.
1573        */
1574       /* we assume ->constant doesn't matter as you can't have
1575        * a constant string involved in a move.
1576        */
1577 #define ASSIGN_DATA(a, b) do {                  \
1578         (a)->str = (b)->str;                    \
1579         (a)->len = (b)->len;                    \
1580         (a)->allocated = (b)->allocated;        \
1581         (a)->align_offset = (b)->align_offset;  \
1582       } while (0)
1583       
1584       DBusRealString tmp;
1585
1586       ASSIGN_DATA (&tmp, real_source);
1587       ASSIGN_DATA (real_source, real_dest);
1588       ASSIGN_DATA (real_dest, &tmp);
1589
1590       return TRUE;
1591     }
1592   else
1593     {
1594       if (!copy (real_source, start, len,
1595                  real_dest,
1596                  insert_at))
1597         return FALSE;
1598       
1599       delete (real_source, start,
1600               len);
1601       
1602       return TRUE;
1603     }
1604 }
1605
1606 /**
1607  * Like _dbus_string_copy(), but can copy a segment from the middle of
1608  * the source string.
1609  *
1610  * @param source the source string
1611  * @param start where to start copying the source string
1612  * @param len length of segment to copy
1613  * @param dest the destination string
1614  * @param insert_at where to place the copied segment of source string
1615  * @returns #FALSE if not enough memory
1616  */
1617 dbus_bool_t
1618 _dbus_string_copy_len (const DBusString *source,
1619                        int               start,
1620                        int               len,
1621                        DBusString       *dest,
1622                        int               insert_at)
1623 {
1624   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1625   _dbus_assert (len >= 0);
1626   _dbus_assert (start <= real_source->len);
1627   _dbus_assert (len <= real_source->len - start);
1628   
1629   return copy (real_source, start, len,
1630                real_dest,
1631                insert_at);
1632 }
1633
1634 /**
1635  * Replaces a segment of dest string with a segment of source string.
1636  *
1637  * @todo optimize the case where the two lengths are the same, and
1638  * avoid memmoving the data in the trailing part of the string twice.
1639  *
1640  * @todo avoid inserting the source into dest, then deleting
1641  * the replaced chunk of dest (which creates a potentially large
1642  * intermediate string). Instead, extend the replaced chunk
1643  * of dest with padding to the same size as the source chunk,
1644  * then copy in the source bytes.
1645  * 
1646  * @param source the source string
1647  * @param start where to start copying the source string
1648  * @param len length of segment to copy
1649  * @param dest the destination string
1650  * @param replace_at start of segment of dest string to replace
1651  * @param replace_len length of segment of dest string to replace
1652  * @returns #FALSE if not enough memory
1653  *
1654  */
1655 dbus_bool_t
1656 _dbus_string_replace_len (const DBusString *source,
1657                           int               start,
1658                           int               len,
1659                           DBusString       *dest,
1660                           int               replace_at,
1661                           int               replace_len)
1662 {
1663   DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1664   _dbus_assert (len >= 0);
1665   _dbus_assert (start <= real_source->len);
1666   _dbus_assert (len <= real_source->len - start);
1667   _dbus_assert (replace_at >= 0);
1668   _dbus_assert (replace_at <= real_dest->len);
1669   _dbus_assert (replace_len <= real_dest->len - replace_at);
1670
1671   if (!copy (real_source, start, len,
1672              real_dest, replace_at))
1673     return FALSE;
1674
1675   delete (real_dest, replace_at + len, replace_len);
1676
1677   return TRUE;
1678 }
1679
1680 /**
1681  * Looks for the first occurance of a byte, deletes that byte,
1682  * and moves everything after the byte to the beginning of a
1683  * separate string.  Both strings must be initialized, valid
1684  * strings.
1685  *
1686  * @param source the source string
1687  * @param byte the byte to remove and split the string at
1688  * @param tail the split off string
1689  * @returns #FALSE if not enough memory or if byte could not be found
1690  *
1691  */
1692 dbus_bool_t
1693 _dbus_string_split_on_byte (DBusString        *source,
1694                             unsigned char      byte,
1695                             DBusString        *tail)
1696 {
1697   int byte_position;
1698   char byte_string[2] = "";
1699   int head_length;
1700   int tail_length;
1701
1702   byte_string[0] = (char) byte;
1703
1704   if (!_dbus_string_find (source, 0, byte_string, &byte_position))
1705     return FALSE;
1706
1707   head_length = byte_position;
1708   tail_length = _dbus_string_get_length (source) - head_length - 1;
1709
1710   if (!_dbus_string_move_len (source, byte_position + 1, tail_length,
1711                               tail, 0))
1712     return FALSE;
1713
1714   /* remove the trailing delimiter byte from the head now.
1715    */
1716   if (!_dbus_string_set_length (source, head_length))
1717     return FALSE;
1718
1719   return TRUE;
1720 }
1721
1722 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1723  * Pennington, and Tom Tromey are the authors and authorized relicense.
1724  */
1725
1726 /** computes length and mask of a unicode character
1727  * @param Char the char
1728  * @param Mask the mask variable to assign to
1729  * @param Len the length variable to assign to
1730  */
1731 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
1732   if (Char < 128)                                                             \
1733     {                                                                         \
1734       Len = 1;                                                                \
1735       Mask = 0x7f;                                                            \
1736     }                                                                         \
1737   else if ((Char & 0xe0) == 0xc0)                                             \
1738     {                                                                         \
1739       Len = 2;                                                                \
1740       Mask = 0x1f;                                                            \
1741     }                                                                         \
1742   else if ((Char & 0xf0) == 0xe0)                                             \
1743     {                                                                         \
1744       Len = 3;                                                                \
1745       Mask = 0x0f;                                                            \
1746     }                                                                         \
1747   else if ((Char & 0xf8) == 0xf0)                                             \
1748     {                                                                         \
1749       Len = 4;                                                                \
1750       Mask = 0x07;                                                            \
1751     }                                                                         \
1752   else if ((Char & 0xfc) == 0xf8)                                             \
1753     {                                                                         \
1754       Len = 5;                                                                \
1755       Mask = 0x03;                                                            \
1756     }                                                                         \
1757   else if ((Char & 0xfe) == 0xfc)                                             \
1758     {                                                                         \
1759       Len = 6;                                                                \
1760       Mask = 0x01;                                                            \
1761     }                                                                         \
1762   else                                                                        \
1763     {                                                                         \
1764       Len = 0;                                                               \
1765       Mask = 0;                                                               \
1766     }
1767
1768 /**
1769  * computes length of a unicode character in UTF-8
1770  * @param Char the char
1771  */
1772 #define UTF8_LENGTH(Char)              \
1773   ((Char) < 0x80 ? 1 :                 \
1774    ((Char) < 0x800 ? 2 :               \
1775     ((Char) < 0x10000 ? 3 :            \
1776      ((Char) < 0x200000 ? 4 :          \
1777       ((Char) < 0x4000000 ? 5 : 6)))))
1778    
1779 /**
1780  * Gets a UTF-8 value.
1781  *
1782  * @param Result variable for extracted unicode char.
1783  * @param Chars the bytes to decode
1784  * @param Count counter variable
1785  * @param Mask mask for this char
1786  * @param Len length for this char in bytes
1787  */
1788 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
1789   (Result) = (Chars)[0] & (Mask);                                             \
1790   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
1791     {                                                                         \
1792       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
1793         {                                                                     \
1794           (Result) = -1;                                                      \
1795           break;                                                              \
1796         }                                                                     \
1797       (Result) <<= 6;                                                         \
1798       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
1799     }
1800
1801 /**
1802  * Check whether a unicode char is in a valid range.
1803  *
1804  * @param Char the character
1805  */
1806 #define UNICODE_VALID(Char)                   \
1807     ((Char) < 0x110000 &&                     \
1808      (((Char) & 0xFFFFF800) != 0xD800) &&     \
1809      ((Char) < 0xFDD0 || (Char) > 0xFDEF) &&  \
1810      ((Char) & 0xFFFF) != 0xFFFF)
1811
1812 #ifdef DBUS_BUILD_TESTS
1813 /**
1814  * Gets a unicode character from a UTF-8 string. Does no validation;
1815  * you must verify that the string is valid UTF-8 in advance and must
1816  * pass in the start of a character.
1817  *
1818  * @param str the string
1819  * @param start the start of the UTF-8 character.
1820  * @param ch_return location to return the character
1821  * @param end_return location to return the byte index of next character
1822  */
1823 void
1824 _dbus_string_get_unichar (const DBusString *str,
1825                           int               start,
1826                           dbus_unichar_t   *ch_return,
1827                           int              *end_return)
1828 {
1829   int i, mask, len;
1830   dbus_unichar_t result;
1831   unsigned char c;
1832   unsigned char *p;
1833   DBUS_CONST_STRING_PREAMBLE (str);
1834   _dbus_assert (start >= 0);
1835   _dbus_assert (start <= real->len);
1836   
1837   if (ch_return)
1838     *ch_return = 0;
1839   if (end_return)
1840     *end_return = real->len;
1841   
1842   mask = 0;
1843   p = real->str + start;
1844   c = *p;
1845   
1846   UTF8_COMPUTE (c, mask, len);
1847   if (len == 0)
1848     return;
1849   UTF8_GET (result, p, i, mask, len);
1850
1851   if (result == (dbus_unichar_t)-1)
1852     return;
1853
1854   if (ch_return)
1855     *ch_return = result;
1856   if (end_return)
1857     *end_return = start + len;
1858 }
1859 #endif /* DBUS_BUILD_TESTS */
1860
1861 /**
1862  * Finds the given substring in the string,
1863  * returning #TRUE and filling in the byte index
1864  * where the substring was found, if it was found.
1865  * Returns #FALSE if the substring wasn't found.
1866  * Sets *start to the length of the string if the substring
1867  * is not found.
1868  *
1869  * @param str the string
1870  * @param start where to start looking
1871  * @param substr the substring
1872  * @param found return location for where it was found, or #NULL
1873  * @returns #TRUE if found
1874  */
1875 dbus_bool_t
1876 _dbus_string_find (const DBusString *str,
1877                    int               start,
1878                    const char       *substr,
1879                    int              *found)
1880 {
1881   return _dbus_string_find_to (str, start,
1882                                ((const DBusRealString*)str)->len,
1883                                substr, found);
1884 }
1885
1886 /**
1887  * Finds end of line ("\r\n" or "\n") in the string,
1888  * returning #TRUE and filling in the byte index
1889  * where the eol string was found, if it was found.
1890  * Returns #FALSE if eol wasn't found.
1891  *
1892  * @param str the string
1893  * @param start where to start looking
1894  * @param found return location for where eol was found or string length otherwise
1895  * @param found_len return length of found eol string or zero otherwise
1896  * @returns #TRUE if found
1897  */
1898 dbus_bool_t
1899 _dbus_string_find_eol (const DBusString *str,
1900                        int               start,
1901                        int              *found,
1902                        int              *found_len)
1903 {
1904   int i;
1905
1906   DBUS_CONST_STRING_PREAMBLE (str);
1907   _dbus_assert (start <= real->len);
1908   _dbus_assert (start >= 0);
1909   
1910   i = start;
1911   while (i < real->len)
1912     {
1913       if (real->str[i] == '\r') 
1914         {
1915           if ((i+1) < real->len && real->str[i+1] == '\n') /* "\r\n" */
1916             {
1917               if (found) 
1918                 *found = i;
1919               if (found_len)
1920                 *found_len = 2;
1921               return TRUE;
1922             } 
1923           else /* only "\r" */
1924             {
1925               if (found) 
1926                 *found = i;
1927               if (found_len)
1928                 *found_len = 1;
1929               return TRUE;
1930             }
1931         } 
1932       else if (real->str[i] == '\n')  /* only "\n" */
1933         {
1934           if (found) 
1935             *found = i;
1936           if (found_len)
1937             *found_len = 1;
1938           return TRUE;
1939         }
1940       ++i;
1941     }
1942
1943   if (found)
1944     *found = real->len;
1945
1946   if (found_len)
1947     *found_len = 0;
1948   
1949   return FALSE;
1950 }
1951
1952 /**
1953  * Finds the given substring in the string,
1954  * up to a certain position,
1955  * returning #TRUE and filling in the byte index
1956  * where the substring was found, if it was found.
1957  * Returns #FALSE if the substring wasn't found.
1958  * Sets *start to the length of the string if the substring
1959  * is not found.
1960  *
1961  * @param str the string
1962  * @param start where to start looking
1963  * @param end where to stop looking
1964  * @param substr the substring
1965  * @param found return location for where it was found, or #NULL
1966  * @returns #TRUE if found
1967  */
1968 dbus_bool_t
1969 _dbus_string_find_to (const DBusString *str,
1970                       int               start,
1971                       int               end,
1972                       const char       *substr,
1973                       int              *found)
1974 {
1975   int i;
1976   DBUS_CONST_STRING_PREAMBLE (str);
1977   _dbus_assert (substr != NULL);
1978   _dbus_assert (start <= real->len);
1979   _dbus_assert (start >= 0);
1980   _dbus_assert (substr != NULL);
1981   _dbus_assert (end <= real->len);
1982   _dbus_assert (start <= end);
1983
1984   /* we always "find" an empty string */
1985   if (*substr == '\0')
1986     {
1987       if (found)
1988         *found = start;
1989       return TRUE;
1990     }
1991
1992   i = start;
1993   while (i < end)
1994     {
1995       if (real->str[i] == substr[0])
1996         {
1997           int j = i + 1;
1998           
1999           while (j < end)
2000             {
2001               if (substr[j - i] == '\0')
2002                 break;
2003               else if (real->str[j] != substr[j - i])
2004                 break;
2005               
2006               ++j;
2007             }
2008
2009           if (substr[j - i] == '\0')
2010             {
2011               if (found)
2012                 *found = i;
2013               return TRUE;
2014             }
2015         }
2016       
2017       ++i;
2018     }
2019
2020   if (found)
2021     *found = end;
2022   
2023   return FALSE;  
2024 }
2025
2026 /**
2027  * Finds a blank (space or tab) in the string. Returns #TRUE
2028  * if found, #FALSE otherwise. If a blank is not found sets
2029  * *found to the length of the string.
2030  *
2031  * @param str the string
2032  * @param start byte index to start looking
2033  * @param found place to store the location of the first blank
2034  * @returns #TRUE if a blank was found
2035  */
2036 dbus_bool_t
2037 _dbus_string_find_blank (const DBusString *str,
2038                          int               start,
2039                          int              *found)
2040 {
2041   int i;
2042   DBUS_CONST_STRING_PREAMBLE (str);
2043   _dbus_assert (start <= real->len);
2044   _dbus_assert (start >= 0);
2045   
2046   i = start;
2047   while (i < real->len)
2048     {
2049       if (real->str[i] == ' ' ||
2050           real->str[i] == '\t')
2051         {
2052           if (found)
2053             *found = i;
2054           return TRUE;
2055         }
2056       
2057       ++i;
2058     }
2059
2060   if (found)
2061     *found = real->len;
2062   
2063   return FALSE;
2064 }
2065
2066 /**
2067  * Skips blanks from start, storing the first non-blank in *end
2068  * (blank is space or tab).
2069  *
2070  * @param str the string
2071  * @param start where to start
2072  * @param end where to store the first non-blank byte index
2073  */
2074 void
2075 _dbus_string_skip_blank (const DBusString *str,
2076                          int               start,
2077                          int              *end)
2078 {
2079   int i;
2080   DBUS_CONST_STRING_PREAMBLE (str);
2081   _dbus_assert (start <= real->len);
2082   _dbus_assert (start >= 0);
2083   
2084   i = start;
2085   while (i < real->len)
2086     {
2087       if (!DBUS_IS_ASCII_BLANK (real->str[i]))
2088         break;
2089       
2090       ++i;
2091     }
2092
2093   _dbus_assert (i == real->len || !DBUS_IS_ASCII_WHITE (real->str[i]));
2094   
2095   if (end)
2096     *end = i;
2097 }
2098
2099
2100 /**
2101  * Skips whitespace from start, storing the first non-whitespace in *end.
2102  * (whitespace is space, tab, newline, CR).
2103  *
2104  * @param str the string
2105  * @param start where to start
2106  * @param end where to store the first non-whitespace byte index
2107  */
2108 void
2109 _dbus_string_skip_white (const DBusString *str,
2110                          int               start,
2111                          int              *end)
2112 {
2113   int i;
2114   DBUS_CONST_STRING_PREAMBLE (str);
2115   _dbus_assert (start <= real->len);
2116   _dbus_assert (start >= 0);
2117   
2118   i = start;
2119   while (i < real->len)
2120     {
2121       if (!DBUS_IS_ASCII_WHITE (real->str[i]))
2122         break;
2123       
2124       ++i;
2125     }
2126
2127   _dbus_assert (i == real->len || !(DBUS_IS_ASCII_WHITE (real->str[i])));
2128   
2129   if (end)
2130     *end = i;
2131 }
2132
2133 /**
2134  * Skips whitespace from end, storing the start index of the trailing
2135  * whitespace in *start. (whitespace is space, tab, newline, CR).
2136  *
2137  * @param str the string
2138  * @param end where to start scanning backward
2139  * @param start where to store the start of whitespace chars
2140  */
2141 void
2142 _dbus_string_skip_white_reverse (const DBusString *str,
2143                                  int               end,
2144                                  int              *start)
2145 {
2146   int i;
2147   DBUS_CONST_STRING_PREAMBLE (str);
2148   _dbus_assert (end <= real->len);
2149   _dbus_assert (end >= 0);
2150   
2151   i = end;
2152   while (i > 0)
2153     {
2154       if (!DBUS_IS_ASCII_WHITE (real->str[i-1]))
2155         break;
2156       --i;
2157     }
2158
2159   _dbus_assert (i >= 0 && (i == 0 || !(DBUS_IS_ASCII_WHITE (real->str[i-1]))));
2160   
2161   if (start)
2162     *start = i;
2163 }
2164
2165 /**
2166  * Assigns a newline-terminated or \\r\\n-terminated line from the front
2167  * of the string to the given dest string. The dest string's previous
2168  * contents are deleted. If the source string contains no newline,
2169  * moves the entire source string to the dest string.
2170  *
2171  * @todo owen correctly notes that this is a stupid function (it was
2172  * written purely for test code,
2173  * e.g. dbus-message-builder.c). Probably should be enforced as test
2174  * code only with ifdef DBUS_BUILD_TESTS
2175  * 
2176  * @param source the source string
2177  * @param dest the destination string (contents are replaced)
2178  * @returns #FALSE if no memory, or source has length 0
2179  */
2180 dbus_bool_t
2181 _dbus_string_pop_line (DBusString *source,
2182                        DBusString *dest)
2183 {
2184   int eol, eol_len;
2185   
2186   _dbus_string_set_length (dest, 0);
2187   
2188   eol = 0;
2189   eol_len = 0;
2190   if (!_dbus_string_find_eol (source, 0, &eol, &eol_len))
2191     {
2192       _dbus_assert (eol == _dbus_string_get_length (source));
2193       if (eol == 0)
2194         {
2195           /* If there's no newline and source has zero length, we're done */
2196           return FALSE;
2197         }
2198       /* otherwise, the last line of the file has no eol characters */
2199     }
2200
2201   /* remember eol can be 0 if it's an empty line, but eol_len should not be zero also
2202    * since find_eol returned TRUE
2203    */
2204   
2205   if (!_dbus_string_move_len (source, 0, eol + eol_len, dest, 0))
2206     return FALSE;
2207   
2208   /* remove line ending */
2209   if (!_dbus_string_set_length (dest, eol))
2210     {
2211       _dbus_assert_not_reached ("out of memory when shortening a string");
2212       return FALSE;
2213     }
2214
2215   return TRUE;
2216 }
2217
2218 #ifdef DBUS_BUILD_TESTS
2219 /**
2220  * Deletes up to and including the first blank space
2221  * in the string.
2222  *
2223  * @param str the string
2224  */
2225 void
2226 _dbus_string_delete_first_word (DBusString *str)
2227 {
2228   int i;
2229   
2230   if (_dbus_string_find_blank (str, 0, &i))
2231     _dbus_string_skip_blank (str, i, &i);
2232
2233   _dbus_string_delete (str, 0, i);
2234 }
2235 #endif
2236
2237 #ifdef DBUS_BUILD_TESTS
2238 /**
2239  * Deletes any leading blanks in the string
2240  *
2241  * @param str the string
2242  */
2243 void
2244 _dbus_string_delete_leading_blanks (DBusString *str)
2245 {
2246   int i;
2247   
2248   _dbus_string_skip_blank (str, 0, &i);
2249
2250   if (i > 0)
2251     _dbus_string_delete (str, 0, i);
2252 }
2253 #endif
2254
2255 /**
2256  * Deletes leading and trailing whitespace
2257  * 
2258  * @param str the string
2259  */
2260 void
2261 _dbus_string_chop_white(DBusString *str)
2262 {
2263   int i;
2264   
2265   _dbus_string_skip_white (str, 0, &i);
2266
2267   if (i > 0)
2268     _dbus_string_delete (str, 0, i);
2269   
2270   _dbus_string_skip_white_reverse (str, _dbus_string_get_length (str), &i);
2271
2272   _dbus_string_set_length (str, i);
2273 }
2274
2275 /**
2276  * Tests two DBusString for equality.
2277  *
2278  * @todo memcmp is probably faster
2279  *
2280  * @param a first string
2281  * @param b second string
2282  * @returns #TRUE if equal
2283  */
2284 dbus_bool_t
2285 _dbus_string_equal (const DBusString *a,
2286                     const DBusString *b)
2287 {
2288   const unsigned char *ap;
2289   const unsigned char *bp;
2290   const unsigned char *a_end;
2291   const DBusRealString *real_a = (const DBusRealString*) a;
2292   const DBusRealString *real_b = (const DBusRealString*) b;
2293   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2294   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2295
2296   if (real_a->len != real_b->len)
2297     return FALSE;
2298
2299   ap = real_a->str;
2300   bp = real_b->str;
2301   a_end = real_a->str + real_a->len;
2302   while (ap != a_end)
2303     {
2304       if (*ap != *bp)
2305         return FALSE;
2306       
2307       ++ap;
2308       ++bp;
2309     }
2310
2311   return TRUE;
2312 }
2313
2314 #ifdef DBUS_BUILD_TESTS
2315 /**
2316  * Tests two DBusString for equality up to the given length.
2317  * The strings may be shorter than the given length.
2318  *
2319  * @todo write a unit test
2320  *
2321  * @todo memcmp is probably faster
2322  *
2323  * @param a first string
2324  * @param b second string
2325  * @param len the maximum length to look at
2326  * @returns #TRUE if equal for the given number of bytes
2327  */
2328 dbus_bool_t
2329 _dbus_string_equal_len (const DBusString *a,
2330                         const DBusString *b,
2331                         int               len)
2332 {
2333   const unsigned char *ap;
2334   const unsigned char *bp;
2335   const unsigned char *a_end;
2336   const DBusRealString *real_a = (const DBusRealString*) a;
2337   const DBusRealString *real_b = (const DBusRealString*) b;
2338   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2339   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2340
2341   if (real_a->len != real_b->len &&
2342       (real_a->len < len || real_b->len < len))
2343     return FALSE;
2344
2345   ap = real_a->str;
2346   bp = real_b->str;
2347   a_end = real_a->str + MIN (real_a->len, len);
2348   while (ap != a_end)
2349     {
2350       if (*ap != *bp)
2351         return FALSE;
2352       
2353       ++ap;
2354       ++bp;
2355     }
2356
2357   return TRUE;
2358 }
2359 #endif /* DBUS_BUILD_TESTS */
2360
2361 /**
2362  * Tests two sub-parts of two DBusString for equality.  The specified
2363  * range of the first string must exist; the specified start position
2364  * of the second string must exist.
2365  *
2366  * @todo write a unit test
2367  *
2368  * @todo memcmp is probably faster
2369  *
2370  * @param a first string
2371  * @param a_start where to start substring in first string
2372  * @param a_len length of substring in first string
2373  * @param b second string
2374  * @param b_start where to start substring in second string
2375  * @returns #TRUE if the two substrings are equal
2376  */
2377 dbus_bool_t
2378 _dbus_string_equal_substring (const DBusString  *a,
2379                               int                a_start,
2380                               int                a_len,
2381                               const DBusString  *b,
2382                               int                b_start)
2383 {
2384   const unsigned char *ap;
2385   const unsigned char *bp;
2386   const unsigned char *a_end;
2387   const DBusRealString *real_a = (const DBusRealString*) a;
2388   const DBusRealString *real_b = (const DBusRealString*) b;
2389   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2390   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2391   _dbus_assert (a_start >= 0);
2392   _dbus_assert (a_len >= 0);
2393   _dbus_assert (a_start <= real_a->len);
2394   _dbus_assert (a_len <= real_a->len - a_start);
2395   _dbus_assert (b_start >= 0);
2396   _dbus_assert (b_start <= real_b->len);
2397   
2398   if (a_len > real_b->len - b_start)
2399     return FALSE;
2400
2401   ap = real_a->str + a_start;
2402   bp = real_b->str + b_start;
2403   a_end = ap + a_len;
2404   while (ap != a_end)
2405     {
2406       if (*ap != *bp)
2407         return FALSE;
2408       
2409       ++ap;
2410       ++bp;
2411     }
2412
2413   _dbus_assert (bp <= (real_b->str + real_b->len));
2414   
2415   return TRUE;
2416 }
2417
2418 /**
2419  * Checks whether a string is equal to a C string.
2420  *
2421  * @param a the string
2422  * @param c_str the C string
2423  * @returns #TRUE if equal
2424  */
2425 dbus_bool_t
2426 _dbus_string_equal_c_str (const DBusString *a,
2427                           const char       *c_str)
2428 {
2429   const unsigned char *ap;
2430   const unsigned char *bp;
2431   const unsigned char *a_end;
2432   const DBusRealString *real_a = (const DBusRealString*) a;
2433   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2434   _dbus_assert (c_str != NULL);
2435   
2436   ap = real_a->str;
2437   bp = (const unsigned char*) c_str;
2438   a_end = real_a->str + real_a->len;
2439   while (ap != a_end && *bp)
2440     {
2441       if (*ap != *bp)
2442         return FALSE;
2443       
2444       ++ap;
2445       ++bp;
2446     }
2447
2448   if (ap != a_end || *bp)
2449     return FALSE;
2450   
2451   return TRUE;
2452 }
2453
2454 #ifdef DBUS_BUILD_TESTS
2455 /**
2456  * Checks whether a string starts with the given C string.
2457  *
2458  * @param a the string
2459  * @param c_str the C string
2460  * @returns #TRUE if string starts with it
2461  */
2462 dbus_bool_t
2463 _dbus_string_starts_with_c_str (const DBusString *a,
2464                                 const char       *c_str)
2465 {
2466   const unsigned char *ap;
2467   const unsigned char *bp;
2468   const unsigned char *a_end;
2469   const DBusRealString *real_a = (const DBusRealString*) a;
2470   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2471   _dbus_assert (c_str != NULL);
2472   
2473   ap = real_a->str;
2474   bp = (const unsigned char*) c_str;
2475   a_end = real_a->str + real_a->len;
2476   while (ap != a_end && *bp)
2477     {
2478       if (*ap != *bp)
2479         return FALSE;
2480       
2481       ++ap;
2482       ++bp;
2483     }
2484
2485   if (*bp == '\0')
2486     return TRUE;
2487   else
2488     return FALSE;
2489 }
2490 #endif /* DBUS_BUILD_TESTS */
2491
2492 /**
2493  * Appends a two-character hex digit to a string, where the hex digit
2494  * has the value of the given byte.
2495  *
2496  * @param str the string
2497  * @param byte the byte
2498  * @returns #FALSE if no memory
2499  */
2500 dbus_bool_t
2501 _dbus_string_append_byte_as_hex (DBusString *str,
2502                                  int         byte)
2503 {
2504   const char hexdigits[16] = {
2505     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2506     'a', 'b', 'c', 'd', 'e', 'f'
2507   };
2508
2509   if (!_dbus_string_append_byte (str,
2510                                  hexdigits[(byte >> 4)]))
2511     return FALSE;
2512   
2513   if (!_dbus_string_append_byte (str,
2514                                  hexdigits[(byte & 0x0f)]))
2515     {
2516       _dbus_string_set_length (str,
2517                                _dbus_string_get_length (str) - 1);
2518       return FALSE;
2519     }
2520
2521   return TRUE;
2522 }
2523
2524 /**
2525  * Encodes a string in hex, the way MD5 and SHA-1 are usually
2526  * encoded. (Each byte is two hex digits.)
2527  *
2528  * @param source the string to encode
2529  * @param start byte index to start encoding
2530  * @param dest string where encoded data should be placed
2531  * @param insert_at where to place encoded data
2532  * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2533  */
2534 dbus_bool_t
2535 _dbus_string_hex_encode (const DBusString *source,
2536                          int               start,
2537                          DBusString       *dest,
2538                          int               insert_at)
2539 {
2540   DBusString result;
2541   const unsigned char *p;
2542   const unsigned char *end;
2543   dbus_bool_t retval;
2544   
2545   _dbus_assert (start <= _dbus_string_get_length (source));
2546
2547   if (!_dbus_string_init (&result))
2548     return FALSE;
2549
2550   retval = FALSE;
2551   
2552   p = (const unsigned char*) _dbus_string_get_const_data (source);
2553   end = p + _dbus_string_get_length (source);
2554   p += start;
2555   
2556   while (p != end)
2557     {
2558       if (!_dbus_string_append_byte_as_hex (&result, *p))
2559         goto out;
2560       
2561       ++p;
2562     }
2563
2564   if (!_dbus_string_move (&result, 0, dest, insert_at))
2565     goto out;
2566
2567   retval = TRUE;
2568
2569  out:
2570   _dbus_string_free (&result);
2571   return retval;
2572 }
2573
2574 /**
2575  * Decodes a string from hex encoding.
2576  *
2577  * @param source the string to decode
2578  * @param start byte index to start decode
2579  * @param end_return return location of the end of the hex data, or #NULL
2580  * @param dest string where decoded data should be placed
2581  * @param insert_at where to place decoded data
2582  * @returns #TRUE if decoding was successful, #FALSE if no memory.
2583  */
2584 dbus_bool_t
2585 _dbus_string_hex_decode (const DBusString *source,
2586                          int               start,
2587                          int              *end_return,
2588                          DBusString       *dest,
2589                          int               insert_at)
2590 {
2591   DBusString result;
2592   const unsigned char *p;
2593   const unsigned char *end;
2594   dbus_bool_t retval;
2595   dbus_bool_t high_bits;
2596   
2597   _dbus_assert (start <= _dbus_string_get_length (source));
2598
2599   if (!_dbus_string_init (&result))
2600     return FALSE;
2601
2602   retval = FALSE;
2603
2604   high_bits = TRUE;
2605   p = (const unsigned char*) _dbus_string_get_const_data (source);
2606   end = p + _dbus_string_get_length (source);
2607   p += start;
2608   
2609   while (p != end)
2610     {
2611       unsigned int val;
2612
2613       switch (*p)
2614         {
2615         case '0':
2616           val = 0;
2617           break;
2618         case '1':
2619           val = 1;
2620           break;
2621         case '2':
2622           val = 2;
2623           break;
2624         case '3':
2625           val = 3;
2626           break;
2627         case '4':
2628           val = 4;
2629           break;
2630         case '5':
2631           val = 5;
2632           break;
2633         case '6':
2634           val = 6;
2635           break;
2636         case '7':
2637           val = 7;
2638           break;
2639         case '8':
2640           val = 8;
2641           break;
2642         case '9':
2643           val = 9;
2644           break;
2645         case 'a':
2646         case 'A':
2647           val = 10;
2648           break;
2649         case 'b':
2650         case 'B':
2651           val = 11;
2652           break;
2653         case 'c':
2654         case 'C':
2655           val = 12;
2656           break;
2657         case 'd':
2658         case 'D':
2659           val = 13;
2660           break;
2661         case 'e':
2662         case 'E':
2663           val = 14;
2664           break;
2665         case 'f':
2666         case 'F':
2667           val = 15;
2668           break;
2669         default:
2670           goto done;
2671         }
2672
2673       if (high_bits)
2674         {
2675           if (!_dbus_string_append_byte (&result,
2676                                          val << 4))
2677             goto out;
2678         }
2679       else
2680         {
2681           int len;
2682           unsigned char b;
2683
2684           len = _dbus_string_get_length (&result);
2685           
2686           b = _dbus_string_get_byte (&result, len - 1);
2687
2688           b |= val;
2689
2690           _dbus_string_set_byte (&result, len - 1, b);
2691         }
2692
2693       high_bits = !high_bits;
2694
2695       ++p;
2696     }
2697
2698  done:
2699   if (!_dbus_string_move (&result, 0, dest, insert_at))
2700     goto out;
2701
2702   if (end_return)
2703     *end_return = p - (const unsigned char*) _dbus_string_get_const_data (source);
2704
2705   retval = TRUE;
2706   
2707  out:
2708   _dbus_string_free (&result);  
2709   return retval;
2710 }
2711
2712 /**
2713  * Checks that the given range of the string is valid ASCII with no
2714  * nul bytes. If the given range is not entirely contained in the
2715  * string, returns #FALSE.
2716  *
2717  * @todo this is inconsistent with most of DBusString in that
2718  * it allows a start,len range that extends past the string end.
2719  * 
2720  * @param str the string
2721  * @param start first byte index to check
2722  * @param len number of bytes to check
2723  * @returns #TRUE if the byte range exists and is all valid ASCII
2724  */
2725 dbus_bool_t
2726 _dbus_string_validate_ascii (const DBusString *str,
2727                              int               start,
2728                              int               len)
2729 {
2730   const unsigned char *s;
2731   const unsigned char *end;
2732   DBUS_CONST_STRING_PREAMBLE (str);
2733   _dbus_assert (start >= 0);
2734   _dbus_assert (start <= real->len);
2735   _dbus_assert (len >= 0);
2736   
2737   if (len > real->len - start)
2738     return FALSE;
2739   
2740   s = real->str + start;
2741   end = s + len;
2742   while (s != end)
2743     {
2744       if (_DBUS_UNLIKELY (!_DBUS_ISASCII (*s)))
2745         return FALSE;
2746         
2747       ++s;
2748     }
2749   
2750   return TRUE;
2751 }
2752
2753 /**
2754  * Checks that the given range of the string is valid UTF-8. If the
2755  * given range is not entirely contained in the string, returns
2756  * #FALSE. If the string contains any nul bytes in the given range,
2757  * returns #FALSE. If the start and start+len are not on character
2758  * boundaries, returns #FALSE.
2759  *
2760  * @todo this is inconsistent with most of DBusString in that
2761  * it allows a start,len range that extends past the string end.
2762  * 
2763  * @param str the string
2764  * @param start first byte index to check
2765  * @param len number of bytes to check
2766  * @returns #TRUE if the byte range exists and is all valid UTF-8
2767  */
2768 dbus_bool_t
2769 _dbus_string_validate_utf8  (const DBusString *str,
2770                              int               start,
2771                              int               len)
2772 {
2773   const unsigned char *p;
2774   const unsigned char *end;
2775   DBUS_CONST_STRING_PREAMBLE (str);
2776   _dbus_assert (start >= 0);
2777   _dbus_assert (start <= real->len);
2778   _dbus_assert (len >= 0);
2779
2780   /* we are doing _DBUS_UNLIKELY() here which might be
2781    * dubious in a generic library like GLib, but in D-Bus
2782    * we know we're validating messages and that it would
2783    * only be evil/broken apps that would have invalid
2784    * UTF-8. Also, this function seems to be a performance
2785    * bottleneck in profiles.
2786    */
2787   
2788   if (_DBUS_UNLIKELY (len > real->len - start))
2789     return FALSE;
2790   
2791   p = real->str + start;
2792   end = p + len;
2793   
2794   while (p < end)
2795     {
2796       int i, mask, char_len;
2797       dbus_unichar_t result;
2798
2799       /* nul bytes considered invalid */
2800       if (*p == '\0')
2801         break;
2802       
2803       /* Special-case ASCII; this makes us go a lot faster in
2804        * D-Bus profiles where we are typically validating
2805        * function names and such. We have to know that
2806        * all following checks will pass for ASCII though,
2807        * comments follow ...
2808        */      
2809       if (*p < 128)
2810         {
2811           ++p;
2812           continue;
2813         }
2814       
2815       UTF8_COMPUTE (*p, mask, char_len);
2816
2817       if (_DBUS_UNLIKELY (char_len == 0))  /* ASCII: char_len == 1 */
2818         break;
2819
2820       /* check that the expected number of bytes exists in the remaining length */
2821       if (_DBUS_UNLIKELY ((end - p) < char_len)) /* ASCII: p < end and char_len == 1 */
2822         break;
2823         
2824       UTF8_GET (result, p, i, mask, char_len);
2825
2826       /* Check for overlong UTF-8 */
2827       if (_DBUS_UNLIKELY (UTF8_LENGTH (result) != char_len)) /* ASCII: UTF8_LENGTH == 1 */
2828         break;
2829 #if 0
2830       /* The UNICODE_VALID check below will catch this */
2831       if (_DBUS_UNLIKELY (result == (dbus_unichar_t)-1)) /* ASCII: result = ascii value */
2832         break;
2833 #endif
2834
2835       if (_DBUS_UNLIKELY (!UNICODE_VALID (result))) /* ASCII: always valid */
2836         break;
2837
2838       /* UNICODE_VALID should have caught it */
2839       _dbus_assert (result != (dbus_unichar_t)-1);
2840       
2841       p += char_len;
2842     }
2843
2844   /* See that we covered the entire length if a length was
2845    * passed in
2846    */
2847   if (_DBUS_UNLIKELY (p != end))
2848     return FALSE;
2849   else
2850     return TRUE;
2851 }
2852
2853 /**
2854  * Checks that the given range of the string is all nul bytes. If the
2855  * given range is not entirely contained in the string, returns
2856  * #FALSE.
2857  *
2858  * @todo this is inconsistent with most of DBusString in that
2859  * it allows a start,len range that extends past the string end.
2860  * 
2861  * @param str the string
2862  * @param start first byte index to check
2863  * @param len number of bytes to check
2864  * @returns #TRUE if the byte range exists and is all nul bytes
2865  */
2866 dbus_bool_t
2867 _dbus_string_validate_nul (const DBusString *str,
2868                            int               start,
2869                            int               len)
2870 {
2871   const unsigned char *s;
2872   const unsigned char *end;
2873   DBUS_CONST_STRING_PREAMBLE (str);
2874   _dbus_assert (start >= 0);
2875   _dbus_assert (len >= 0);
2876   _dbus_assert (start <= real->len);
2877   
2878   if (len > real->len - start)
2879     return FALSE;
2880   
2881   s = real->str + start;
2882   end = s + len;
2883   while (s != end)
2884     {
2885       if (_DBUS_UNLIKELY (*s != '\0'))
2886         return FALSE;
2887       ++s;
2888     }
2889   
2890   return TRUE;
2891 }
2892
2893 /**
2894  * Clears all allocated bytes in the string to zero.
2895  *
2896  * @param str the string
2897  */
2898 void
2899 _dbus_string_zero (DBusString *str)
2900 {
2901   DBUS_STRING_PREAMBLE (str);
2902
2903   memset (real->str - real->align_offset, '\0', real->allocated);
2904 }
2905 /** @} */
2906
2907 /* tests are in dbus-string-util.c */