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