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