2005-01-15 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 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 #define ASSIGN_4_OCTETS(p, octets) \
1050   *((dbus_uint32_t*)(p)) = *((dbus_uint32_t*)(octets));
1051
1052 #ifdef DBUS_HAVE_INT64
1053 #define ASSIGN_8_OCTETS(p, octets) \
1054   *((dbus_uint64_t*)(p)) = *((dbus_uint64_t*)(octets));
1055 #else
1056 #define ASSIGN_8_OCTETS(p, octets)              \
1057 do {                                            \
1058   unsigned char *b;                             \
1059                                                 \
1060   b = p;                                        \
1061                                                 \
1062   *b++ = octets[0];                             \
1063   *b++ = octets[1];                             \
1064   *b++ = octets[2];                             \
1065   *b++ = octets[3];                             \
1066   *b++ = octets[4];                             \
1067   *b++ = octets[5];                             \
1068   *b++ = octets[6];                             \
1069   *b++ = octets[7];                             \
1070   _dbus_assert (b == p + 8);                    \
1071 } while (0)
1072 #endif /* DBUS_HAVE_INT64 */
1073
1074 /**
1075  * Appends 4 bytes aligned on a 4 byte boundary
1076  * with any alignment padding initialized to 0.
1077  *
1078  * @param str the DBusString
1079  * @param octets 4 bytes to append
1080  * @returns #FALSE if not enough memory.
1081  */
1082 dbus_bool_t
1083 _dbus_string_append_4_aligned (DBusString         *str,
1084                                const unsigned char octets[4])
1085 {
1086   DBUS_STRING_PREAMBLE (str);
1087   
1088   if (!align_length_then_lengthen (str, 4, 4))
1089     return FALSE;
1090
1091   ASSIGN_4_OCTETS (real->str + (real->len - 4), octets);
1092
1093   return TRUE;
1094 }
1095
1096 /**
1097  * Appends 8 bytes aligned on an 8 byte boundary
1098  * with any alignment padding initialized to 0.
1099  *
1100  * @param str the DBusString
1101  * @param octets 8 bytes to append
1102  * @returns #FALSE if not enough memory.
1103  */
1104 dbus_bool_t
1105 _dbus_string_append_8_aligned (DBusString         *str,
1106                                const unsigned char octets[8])
1107 {
1108   DBUS_STRING_PREAMBLE (str);
1109   
1110   if (!align_length_then_lengthen (str, 8, 8))
1111     return FALSE;
1112
1113   ASSIGN_8_OCTETS (real->str + (real->len - 8), octets);
1114
1115   return TRUE;
1116 }
1117
1118 /**
1119  * Inserts 4 bytes aligned on a 4 byte boundary
1120  * with any alignment padding initialized to 0.
1121  *
1122  * @param str the DBusString
1123  * @param octets 4 bytes to insert
1124  * @returns #FALSE if not enough memory.
1125  */
1126 dbus_bool_t
1127 _dbus_string_insert_4_aligned (DBusString         *str,
1128                                int                 insert_at,
1129                                const unsigned char octets[4])
1130 {
1131   DBUS_STRING_PREAMBLE (str);
1132   
1133   if (!align_insert_point_then_open_gap (str, &insert_at, 4, 4))
1134     return FALSE;
1135
1136   ASSIGN_4_OCTETS (real->str + insert_at, octets);
1137
1138   return TRUE;
1139 }
1140
1141 /**
1142  * Inserts 8 bytes aligned on an 8 byte boundary
1143  * with any alignment padding initialized to 0.
1144  *
1145  * @param str the DBusString
1146  * @param octets 8 bytes to insert
1147  * @returns #FALSE if not enough memory.
1148  */
1149 dbus_bool_t
1150 _dbus_string_insert_8_aligned (DBusString         *str,
1151                                int                 insert_at,
1152                                const unsigned char octets[8])
1153 {
1154   DBUS_STRING_PREAMBLE (str);
1155   
1156   if (!align_insert_point_then_open_gap (str, &insert_at, 8, 8))
1157     return FALSE;
1158
1159   _dbus_assert (_DBUS_ALIGN_VALUE (insert_at, 8) == (unsigned) insert_at);
1160   
1161   ASSIGN_8_OCTETS (real->str + insert_at, octets);
1162
1163   return TRUE;
1164 }
1165
1166
1167 /**
1168  * Inserts padding at *insert_at such to align it to the given
1169  * boundary. Initializes the padding to nul bytes. Sets *insert_at
1170  * to the aligned position.
1171  *
1172  * @param str the DBusString
1173  * @param insert_at location to be aligned
1174  * @param alignment alignment boundary (1, 4, or 8)
1175  * @returns #FALSE if not enough memory.
1176  */
1177 dbus_bool_t
1178 _dbus_string_insert_alignment (DBusString        *str,
1179                                int               *insert_at,
1180                                int                alignment)
1181 {
1182   DBUS_STRING_PREAMBLE (str);
1183   
1184   if (!align_insert_point_then_open_gap (str, insert_at, alignment, 0))
1185     return FALSE;
1186
1187   _dbus_assert (_DBUS_ALIGN_VALUE (*insert_at, alignment) == (unsigned) *insert_at);
1188
1189   return TRUE;
1190 }
1191
1192 /**
1193  * Appends a printf-style formatted string
1194  * to the #DBusString.
1195  *
1196  * @param str the string
1197  * @param format printf format
1198  * @param args variable argument list
1199  * @returns #FALSE if no memory
1200  */
1201 dbus_bool_t
1202 _dbus_string_append_printf_valist  (DBusString        *str,
1203                                     const char        *format,
1204                                     va_list            args)
1205 {
1206   int len;
1207   char c;
1208   va_list args_copy;
1209
1210   DBUS_STRING_PREAMBLE (str);
1211
1212   DBUS_VA_COPY (args_copy, args);
1213
1214   /* Measure the message length without terminating nul */
1215   len = vsnprintf (&c, 1, format, args);
1216
1217   if (!_dbus_string_lengthen (str, len))
1218     {
1219       /* don't leak the copy */
1220       va_end (args_copy);
1221       return FALSE;
1222     }
1223   
1224   vsprintf (real->str + (real->len - len),
1225             format, args_copy);
1226
1227   va_end (args_copy);
1228
1229   return TRUE;
1230 }
1231
1232 /**
1233  * Appends a printf-style formatted string
1234  * to the #DBusString.
1235  *
1236  * @param str the string
1237  * @param format printf format
1238  * @returns #FALSE if no memory
1239  */
1240 dbus_bool_t
1241 _dbus_string_append_printf (DBusString        *str,
1242                             const char        *format,
1243                             ...)
1244 {
1245   va_list args;
1246   dbus_bool_t retval;
1247   
1248   va_start (args, format);
1249   retval = _dbus_string_append_printf_valist (str, format, args);
1250   va_end (args);
1251
1252   return retval;
1253 }
1254
1255 /**
1256  * Appends block of bytes with the given length to a DBusString.
1257  *
1258  * @param str the DBusString
1259  * @param buffer the bytes to append
1260  * @param len the number of bytes to append
1261  * @returns #FALSE if not enough memory.
1262  */
1263 dbus_bool_t
1264 _dbus_string_append_len (DBusString *str,
1265                          const char *buffer,
1266                          int         len)
1267 {
1268   DBUS_STRING_PREAMBLE (str);
1269   _dbus_assert (buffer != NULL);
1270   _dbus_assert (len >= 0);
1271
1272   return append (real, buffer, len);
1273 }
1274
1275 /**
1276  * Appends a single byte to the string, returning #FALSE
1277  * if not enough memory.
1278  *
1279  * @param str the string
1280  * @param byte the byte to append
1281  * @returns #TRUE on success
1282  */
1283 dbus_bool_t
1284 _dbus_string_append_byte (DBusString    *str,
1285                           unsigned char  byte)
1286 {
1287   DBUS_STRING_PREAMBLE (str);
1288
1289   if (!set_length (real, real->len + 1))
1290     return FALSE;
1291
1292   real->str[real->len-1] = byte;
1293
1294   return TRUE;
1295 }
1296
1297 /**
1298  * Appends a single Unicode character, encoding the character
1299  * in UTF-8 format.
1300  *
1301  * @param str the string
1302  * @param ch the Unicode character
1303  */
1304 dbus_bool_t
1305 _dbus_string_append_unichar (DBusString    *str,
1306                              dbus_unichar_t ch)
1307 {
1308   int len;
1309   int first;
1310   int i;
1311   char *out;
1312   
1313   DBUS_STRING_PREAMBLE (str);
1314
1315   /* this code is from GLib but is pretty standard I think */
1316   
1317   len = 0;
1318   
1319   if (ch < 0x80)
1320     {
1321       first = 0;
1322       len = 1;
1323     }
1324   else if (ch < 0x800)
1325     {
1326       first = 0xc0;
1327       len = 2;
1328     }
1329   else if (ch < 0x10000)
1330     {
1331       first = 0xe0;
1332       len = 3;
1333     }
1334    else if (ch < 0x200000)
1335     {
1336       first = 0xf0;
1337       len = 4;
1338     }
1339   else if (ch < 0x4000000)
1340     {
1341       first = 0xf8;
1342       len = 5;
1343     }
1344   else
1345     {
1346       first = 0xfc;
1347       len = 6;
1348     }
1349
1350   if (len > (real->max_length - real->len))
1351     return FALSE; /* real->len + len would overflow */
1352   
1353   if (!set_length (real, real->len + len))
1354     return FALSE;
1355
1356   out = real->str + (real->len - len);
1357   
1358   for (i = len - 1; i > 0; --i)
1359     {
1360       out[i] = (ch & 0x3f) | 0x80;
1361       ch >>= 6;
1362     }
1363   out[0] = ch | first;
1364
1365   return TRUE;
1366 }
1367
1368 static void
1369 delete (DBusRealString *real,
1370         int             start,
1371         int             len)
1372 {
1373   if (len == 0)
1374     return;
1375   
1376   memmove (real->str + start, real->str + start + len, real->len - (start + len));
1377   real->len -= len;
1378   real->str[real->len] = '\0';
1379 }
1380
1381 /**
1382  * Deletes a segment of a DBusString with length len starting at
1383  * start. (Hint: to clear an entire string, setting length to 0
1384  * with _dbus_string_set_length() is easier.)
1385  *
1386  * @param str the DBusString
1387  * @param start where to start deleting
1388  * @param len the number of bytes to delete
1389  */
1390 void
1391 _dbus_string_delete (DBusString       *str,
1392                      int               start,
1393                      int               len)
1394 {
1395   DBUS_STRING_PREAMBLE (str);
1396   _dbus_assert (start >= 0);
1397   _dbus_assert (len >= 0);
1398   _dbus_assert (start <= real->len);
1399   _dbus_assert (len <= real->len - start);
1400   
1401   delete (real, start, len);
1402 }
1403
1404 static dbus_bool_t
1405 copy (DBusRealString *source,
1406       int             start,
1407       int             len,
1408       DBusRealString *dest,
1409       int             insert_at)
1410 {
1411   if (len == 0)
1412     return TRUE;
1413
1414   if (!open_gap (len, dest, insert_at))
1415     return FALSE;
1416   
1417   memcpy (dest->str + insert_at,
1418           source->str + start,
1419           len);
1420
1421   return TRUE;
1422 }
1423
1424 /**
1425  * Checks assertions for two strings we're copying a segment between,
1426  * and declares real_source/real_dest variables.
1427  *
1428  * @param source the source string
1429  * @param start the starting offset
1430  * @param dest the dest string
1431  * @param insert_at where the copied segment is inserted
1432  */
1433 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at)       \
1434   DBusRealString *real_source = (DBusRealString*) source;               \
1435   DBusRealString *real_dest = (DBusRealString*) dest;                   \
1436   _dbus_assert ((source) != (dest));                                    \
1437   DBUS_GENERIC_STRING_PREAMBLE (real_source);                           \
1438   DBUS_GENERIC_STRING_PREAMBLE (real_dest);                             \
1439   _dbus_assert (!real_dest->constant);                                  \
1440   _dbus_assert (!real_dest->locked);                                    \
1441   _dbus_assert ((start) >= 0);                                          \
1442   _dbus_assert ((start) <= real_source->len);                           \
1443   _dbus_assert ((insert_at) >= 0);                                      \
1444   _dbus_assert ((insert_at) <= real_dest->len)
1445
1446 /**
1447  * Moves the end of one string into another string. Both strings
1448  * must be initialized, valid strings.
1449  *
1450  * @param source the source string
1451  * @param start where to chop off the source string
1452  * @param dest the destination string
1453  * @param insert_at where to move the chopped-off part of source string
1454  * @returns #FALSE if not enough memory
1455  */
1456 dbus_bool_t
1457 _dbus_string_move (DBusString       *source,
1458                    int               start,
1459                    DBusString       *dest,
1460                    int               insert_at)
1461 {
1462   DBusRealString *real_source = (DBusRealString*) source;
1463   _dbus_assert (start <= real_source->len);
1464   
1465   return _dbus_string_move_len (source, start,
1466                                 real_source->len - start,
1467                                 dest, insert_at);
1468 }
1469
1470 /**
1471  * Like _dbus_string_move(), but does not delete the section
1472  * of the source string that's copied to the dest string.
1473  *
1474  * @param source the source string
1475  * @param start where to start copying the source string
1476  * @param dest the destination string
1477  * @param insert_at where to place the copied part of source string
1478  * @returns #FALSE if not enough memory
1479  */
1480 dbus_bool_t
1481 _dbus_string_copy (const DBusString *source,
1482                    int               start,
1483                    DBusString       *dest,
1484                    int               insert_at)
1485 {
1486   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1487
1488   return copy (real_source, start,
1489                real_source->len - start,
1490                real_dest,
1491                insert_at);
1492 }
1493
1494 /**
1495  * Like _dbus_string_move(), but can move a segment from
1496  * the middle of the source string.
1497  *
1498  * @todo this doesn't do anything with max_length field.
1499  * we should probably just kill the max_length field though.
1500  * 
1501  * @param source the source string
1502  * @param start first byte of source string to move
1503  * @param len length of segment to move
1504  * @param dest the destination string
1505  * @param insert_at where to move the bytes from the source string
1506  * @returns #FALSE if not enough memory
1507  */
1508 dbus_bool_t
1509 _dbus_string_move_len (DBusString       *source,
1510                        int               start,
1511                        int               len,
1512                        DBusString       *dest,
1513                        int               insert_at)
1514
1515 {
1516   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1517   _dbus_assert (len >= 0);
1518   _dbus_assert ((start + len) <= real_source->len);
1519
1520
1521   if (len == 0)
1522     {
1523       return TRUE;
1524     }
1525   else if (start == 0 &&
1526            len == real_source->len &&
1527            real_dest->len == 0)
1528     {
1529       /* Short-circuit moving an entire existing string to an empty string
1530        * by just swapping the buffers.
1531        */
1532       /* we assume ->constant doesn't matter as you can't have
1533        * a constant string involved in a move.
1534        */
1535 #define ASSIGN_DATA(a, b) do {                  \
1536         (a)->str = (b)->str;                    \
1537         (a)->len = (b)->len;                    \
1538         (a)->allocated = (b)->allocated;        \
1539         (a)->align_offset = (b)->align_offset;  \
1540       } while (0)
1541       
1542       DBusRealString tmp;
1543
1544       ASSIGN_DATA (&tmp, real_source);
1545       ASSIGN_DATA (real_source, real_dest);
1546       ASSIGN_DATA (real_dest, &tmp);
1547
1548       return TRUE;
1549     }
1550   else
1551     {
1552       if (!copy (real_source, start, len,
1553                  real_dest,
1554                  insert_at))
1555         return FALSE;
1556       
1557       delete (real_source, start,
1558               len);
1559       
1560       return TRUE;
1561     }
1562 }
1563
1564 /**
1565  * Like _dbus_string_copy(), but can copy a segment from the middle of
1566  * the source string.
1567  *
1568  * @param source the source string
1569  * @param start where to start copying the source string
1570  * @param len length of segment to copy
1571  * @param dest the destination string
1572  * @param insert_at where to place the copied segment of source string
1573  * @returns #FALSE if not enough memory
1574  */
1575 dbus_bool_t
1576 _dbus_string_copy_len (const DBusString *source,
1577                        int               start,
1578                        int               len,
1579                        DBusString       *dest,
1580                        int               insert_at)
1581 {
1582   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1583   _dbus_assert (len >= 0);
1584   _dbus_assert (start <= real_source->len);
1585   _dbus_assert (len <= real_source->len - start);
1586   
1587   return copy (real_source, start, len,
1588                real_dest,
1589                insert_at);
1590 }
1591
1592 /**
1593  * Replaces a segment of dest string with a segment of source string.
1594  *
1595  * @todo optimize the case where the two lengths are the same, and
1596  * avoid memmoving the data in the trailing part of the string twice.
1597  *
1598  * @todo avoid inserting the source into dest, then deleting
1599  * the replaced chunk of dest (which creates a potentially large
1600  * intermediate string). Instead, extend the replaced chunk
1601  * of dest with padding to the same size as the source chunk,
1602  * then copy in the source bytes.
1603  * 
1604  * @param source the source string
1605  * @param start where to start copying the source string
1606  * @param len length of segment to copy
1607  * @param dest the destination string
1608  * @param replace_at start of segment of dest string to replace
1609  * @param replace_len length of segment of dest string to replace
1610  * @returns #FALSE if not enough memory
1611  *
1612  */
1613 dbus_bool_t
1614 _dbus_string_replace_len (const DBusString *source,
1615                           int               start,
1616                           int               len,
1617                           DBusString       *dest,
1618                           int               replace_at,
1619                           int               replace_len)
1620 {
1621   DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1622   _dbus_assert (len >= 0);
1623   _dbus_assert (start <= real_source->len);
1624   _dbus_assert (len <= real_source->len - start);
1625   _dbus_assert (replace_at >= 0);
1626   _dbus_assert (replace_at <= real_dest->len);
1627   _dbus_assert (replace_len <= real_dest->len - replace_at);
1628
1629   if (!copy (real_source, start, len,
1630              real_dest, replace_at))
1631     return FALSE;
1632
1633   delete (real_dest, replace_at + len, replace_len);
1634
1635   return TRUE;
1636 }
1637
1638 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1639  * Pennington, and Tom Tromey are the authors and authorized relicense.
1640  */
1641
1642 /** computes length and mask of a unicode character
1643  * @param Char the char
1644  * @param Mask the mask variable to assign to
1645  * @param Len the length variable to assign to
1646  */
1647 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
1648   if (Char < 128)                                                             \
1649     {                                                                         \
1650       Len = 1;                                                                \
1651       Mask = 0x7f;                                                            \
1652     }                                                                         \
1653   else if ((Char & 0xe0) == 0xc0)                                             \
1654     {                                                                         \
1655       Len = 2;                                                                \
1656       Mask = 0x1f;                                                            \
1657     }                                                                         \
1658   else if ((Char & 0xf0) == 0xe0)                                             \
1659     {                                                                         \
1660       Len = 3;                                                                \
1661       Mask = 0x0f;                                                            \
1662     }                                                                         \
1663   else if ((Char & 0xf8) == 0xf0)                                             \
1664     {                                                                         \
1665       Len = 4;                                                                \
1666       Mask = 0x07;                                                            \
1667     }                                                                         \
1668   else if ((Char & 0xfc) == 0xf8)                                             \
1669     {                                                                         \
1670       Len = 5;                                                                \
1671       Mask = 0x03;                                                            \
1672     }                                                                         \
1673   else if ((Char & 0xfe) == 0xfc)                                             \
1674     {                                                                         \
1675       Len = 6;                                                                \
1676       Mask = 0x01;                                                            \
1677     }                                                                         \
1678   else                                                                        \
1679     {                                                                         \
1680       Len = 0;                                                               \
1681       Mask = 0;                                                               \
1682     }
1683
1684 /**
1685  * computes length of a unicode character in UTF-8
1686  * @param Char the char
1687  */
1688 #define UTF8_LENGTH(Char)              \
1689   ((Char) < 0x80 ? 1 :                 \
1690    ((Char) < 0x800 ? 2 :               \
1691     ((Char) < 0x10000 ? 3 :            \
1692      ((Char) < 0x200000 ? 4 :          \
1693       ((Char) < 0x4000000 ? 5 : 6)))))
1694    
1695 /**
1696  * Gets a UTF-8 value.
1697  *
1698  * @param Result variable for extracted unicode char.
1699  * @param Chars the bytes to decode
1700  * @param Count counter variable
1701  * @param Mask mask for this char
1702  * @param Len length for this char in bytes
1703  */
1704 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
1705   (Result) = (Chars)[0] & (Mask);                                             \
1706   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
1707     {                                                                         \
1708       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
1709         {                                                                     \
1710           (Result) = -1;                                                      \
1711           break;                                                              \
1712         }                                                                     \
1713       (Result) <<= 6;                                                         \
1714       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
1715     }
1716
1717 /**
1718  * Check whether a unicode char is in a valid range.
1719  *
1720  * @param Char the character
1721  */
1722 #define UNICODE_VALID(Char)                   \
1723     ((Char) < 0x110000 &&                     \
1724      (((Char) & 0xFFFFF800) != 0xD800) &&     \
1725      ((Char) < 0xFDD0 || (Char) > 0xFDEF) &&  \
1726      ((Char) & 0xFFFF) != 0xFFFF)
1727
1728 /**
1729  * Gets a unicode character from a UTF-8 string. Does no validation;
1730  * you must verify that the string is valid UTF-8 in advance and must
1731  * pass in the start of a character.
1732  *
1733  * @param str the string
1734  * @param start the start of the UTF-8 character.
1735  * @param ch_return location to return the character
1736  * @param end_return location to return the byte index of next character
1737  */
1738 void
1739 _dbus_string_get_unichar (const DBusString *str,
1740                           int               start,
1741                           dbus_unichar_t   *ch_return,
1742                           int              *end_return)
1743 {
1744   int i, mask, len;
1745   dbus_unichar_t result;
1746   unsigned char c;
1747   unsigned char *p;
1748   DBUS_CONST_STRING_PREAMBLE (str);
1749   _dbus_assert (start >= 0);
1750   _dbus_assert (start <= real->len);
1751   
1752   if (ch_return)
1753     *ch_return = 0;
1754   if (end_return)
1755     *end_return = real->len;
1756   
1757   mask = 0;
1758   p = real->str + start;
1759   c = *p;
1760   
1761   UTF8_COMPUTE (c, mask, len);
1762   if (len == 0)
1763     return;
1764   UTF8_GET (result, p, i, mask, len);
1765
1766   if (result == (dbus_unichar_t)-1)
1767     return;
1768
1769   if (ch_return)
1770     *ch_return = result;
1771   if (end_return)
1772     *end_return = start + len;
1773 }
1774
1775 /**
1776  * Finds the given substring in the string,
1777  * returning #TRUE and filling in the byte index
1778  * where the substring was found, if it was found.
1779  * Returns #FALSE if the substring wasn't found.
1780  * Sets *start to the length of the string if the substring
1781  * is not found.
1782  *
1783  * @param str the string
1784  * @param start where to start looking
1785  * @param substr the substring
1786  * @param found return location for where it was found, or #NULL
1787  * @returns #TRUE if found
1788  */
1789 dbus_bool_t
1790 _dbus_string_find (const DBusString *str,
1791                    int               start,
1792                    const char       *substr,
1793                    int              *found)
1794 {
1795   return _dbus_string_find_to (str, start,
1796                                ((const DBusRealString*)str)->len,
1797                                substr, found);
1798 }
1799
1800 /**
1801  * Finds the given substring in the string,
1802  * up to a certain position,
1803  * returning #TRUE and filling in the byte index
1804  * where the substring was found, if it was found.
1805  * Returns #FALSE if the substring wasn't found.
1806  * Sets *start to the length of the string if the substring
1807  * is not found.
1808  *
1809  * @param str the string
1810  * @param start where to start looking
1811  * @param end where to stop looking
1812  * @param substr the substring
1813  * @param found return location for where it was found, or #NULL
1814  * @returns #TRUE if found
1815  */
1816 dbus_bool_t
1817 _dbus_string_find_to (const DBusString *str,
1818                       int               start,
1819                       int               end,
1820                       const char       *substr,
1821                       int              *found)
1822 {
1823   int i;
1824   DBUS_CONST_STRING_PREAMBLE (str);
1825   _dbus_assert (substr != NULL);
1826   _dbus_assert (start <= real->len);
1827   _dbus_assert (start >= 0);
1828   _dbus_assert (substr != NULL);
1829   _dbus_assert (end <= real->len);
1830   _dbus_assert (start <= end);
1831
1832   /* we always "find" an empty string */
1833   if (*substr == '\0')
1834     {
1835       if (found)
1836         *found = start;
1837       return TRUE;
1838     }
1839
1840   i = start;
1841   while (i < end)
1842     {
1843       if (real->str[i] == substr[0])
1844         {
1845           int j = i + 1;
1846           
1847           while (j < end)
1848             {
1849               if (substr[j - i] == '\0')
1850                 break;
1851               else if (real->str[j] != substr[j - i])
1852                 break;
1853               
1854               ++j;
1855             }
1856
1857           if (substr[j - i] == '\0')
1858             {
1859               if (found)
1860                 *found = i;
1861               return TRUE;
1862             }
1863         }
1864       
1865       ++i;
1866     }
1867
1868   if (found)
1869     *found = end;
1870   
1871   return FALSE;  
1872 }
1873
1874 /**
1875  * Find the given byte scanning backward from the given start.
1876  * Sets *found to -1 if the byte is not found.
1877  *
1878  * @param str the string
1879  * @param start the place to start scanning (will not find the byte at this point)
1880  * @param byte the byte to find
1881  * @param found return location for where it was found
1882  * @returns #TRUE if found
1883  */
1884 dbus_bool_t
1885 _dbus_string_find_byte_backward (const DBusString  *str,
1886                                  int                start,
1887                                  unsigned char      byte,
1888                                  int               *found)
1889 {
1890   int i;
1891   DBUS_CONST_STRING_PREAMBLE (str);
1892   _dbus_assert (start <= real->len);
1893   _dbus_assert (start >= 0);
1894   _dbus_assert (found != NULL);
1895
1896   i = start - 1;
1897   while (i >= 0)
1898     {
1899       if (real->str[i] == byte)
1900         break;
1901       
1902       --i;
1903     }
1904
1905   if (found)
1906     *found = i;
1907
1908   return i >= 0;
1909 }
1910
1911 /**
1912  * Finds a blank (space or tab) in the string. Returns #TRUE
1913  * if found, #FALSE otherwise. If a blank is not found sets
1914  * *found to the length of the string.
1915  *
1916  * @param str the string
1917  * @param start byte index to start looking
1918  * @param found place to store the location of the first blank
1919  * @returns #TRUE if a blank was found
1920  */
1921 dbus_bool_t
1922 _dbus_string_find_blank (const DBusString *str,
1923                          int               start,
1924                          int              *found)
1925 {
1926   int i;
1927   DBUS_CONST_STRING_PREAMBLE (str);
1928   _dbus_assert (start <= real->len);
1929   _dbus_assert (start >= 0);
1930   
1931   i = start;
1932   while (i < real->len)
1933     {
1934       if (real->str[i] == ' ' ||
1935           real->str[i] == '\t')
1936         {
1937           if (found)
1938             *found = i;
1939           return TRUE;
1940         }
1941       
1942       ++i;
1943     }
1944
1945   if (found)
1946     *found = real->len;
1947   
1948   return FALSE;
1949 }
1950
1951 /**
1952  * Skips blanks from start, storing the first non-blank in *end
1953  * (blank is space or tab).
1954  *
1955  * @param str the string
1956  * @param start where to start
1957  * @param end where to store the first non-blank byte index
1958  */
1959 void
1960 _dbus_string_skip_blank (const DBusString *str,
1961                          int               start,
1962                          int              *end)
1963 {
1964   int i;
1965   DBUS_CONST_STRING_PREAMBLE (str);
1966   _dbus_assert (start <= real->len);
1967   _dbus_assert (start >= 0);
1968   
1969   i = start;
1970   while (i < real->len)
1971     {
1972       if (!(real->str[i] == ' ' ||
1973             real->str[i] == '\t'))
1974         break;
1975       
1976       ++i;
1977     }
1978
1979   _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1980                                     real->str[i] == '\t'));
1981   
1982   if (end)
1983     *end = i;
1984 }
1985
1986 /**
1987  * Skips whitespace from start, storing the first non-whitespace in *end.
1988  * (whitespace is space, tab, newline, CR).
1989  *
1990  * @param str the string
1991  * @param start where to start
1992  * @param end where to store the first non-whitespace byte index
1993  */
1994 void
1995 _dbus_string_skip_white (const DBusString *str,
1996                          int               start,
1997                          int              *end)
1998 {
1999   int i;
2000   DBUS_CONST_STRING_PREAMBLE (str);
2001   _dbus_assert (start <= real->len);
2002   _dbus_assert (start >= 0);
2003   
2004   i = start;
2005   while (i < real->len)
2006     {
2007       if (!(real->str[i] == ' ' ||
2008             real->str[i] == '\n' ||
2009             real->str[i] == '\r' ||
2010             real->str[i] == '\t'))
2011         break;
2012       
2013       ++i;
2014     }
2015
2016   _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
2017                                     real->str[i] == '\t'));
2018   
2019   if (end)
2020     *end = i;
2021 }
2022
2023 /**
2024  * Assigns a newline-terminated or \\r\\n-terminated line from the front
2025  * of the string to the given dest string. The dest string's previous
2026  * contents are deleted. If the source string contains no newline,
2027  * moves the entire source string to the dest string.
2028  *
2029  * @todo owen correctly notes that this is a stupid function (it was
2030  * written purely for test code,
2031  * e.g. dbus-message-builder.c). Probably should be enforced as test
2032  * code only with #ifdef DBUS_BUILD_TESTS
2033  * 
2034  * @param source the source string
2035  * @param dest the destination string (contents are replaced)
2036  * @returns #FALSE if no memory, or source has length 0
2037  */
2038 dbus_bool_t
2039 _dbus_string_pop_line (DBusString *source,
2040                        DBusString *dest)
2041 {
2042   int eol;
2043   dbus_bool_t have_newline;
2044   
2045   _dbus_string_set_length (dest, 0);
2046   
2047   eol = 0;
2048   if (_dbus_string_find (source, 0, "\n", &eol))
2049     {
2050       have_newline = TRUE;
2051       eol += 1; /* include newline */
2052     }
2053   else
2054     {
2055       eol = _dbus_string_get_length (source);
2056       have_newline = FALSE;
2057     }
2058
2059   if (eol == 0)
2060     return FALSE; /* eof */
2061   
2062   if (!_dbus_string_move_len (source, 0, eol,
2063                               dest, 0))
2064     {
2065       return FALSE;
2066     }
2067
2068   /* dump the newline and the \r if we have one */
2069   if (have_newline)
2070     {
2071       dbus_bool_t have_cr;
2072       
2073       _dbus_assert (_dbus_string_get_length (dest) > 0);
2074
2075       if (_dbus_string_get_length (dest) > 1 &&
2076           _dbus_string_get_byte (dest,
2077                                  _dbus_string_get_length (dest) - 2) == '\r')
2078         have_cr = TRUE;
2079       else
2080         have_cr = FALSE;
2081         
2082       _dbus_string_set_length (dest,
2083                                _dbus_string_get_length (dest) -
2084                                (have_cr ? 2 : 1));
2085     }
2086   
2087   return TRUE;
2088 }
2089
2090 /**
2091  * Deletes up to and including the first blank space
2092  * in the string.
2093  *
2094  * @param str the string
2095  */
2096 void
2097 _dbus_string_delete_first_word (DBusString *str)
2098 {
2099   int i;
2100   
2101   if (_dbus_string_find_blank (str, 0, &i))
2102     _dbus_string_skip_blank (str, i, &i);
2103
2104   _dbus_string_delete (str, 0, i);
2105 }
2106
2107 /**
2108  * Deletes any leading blanks in the string
2109  *
2110  * @param str the string
2111  */
2112 void
2113 _dbus_string_delete_leading_blanks (DBusString *str)
2114 {
2115   int i;
2116   
2117   _dbus_string_skip_blank (str, 0, &i);
2118
2119   if (i > 0)
2120     _dbus_string_delete (str, 0, i);
2121 }
2122
2123 /**
2124  * Tests two DBusString for equality.
2125  *
2126  * @todo memcmp is probably faster
2127  *
2128  * @param a first string
2129  * @param b second string
2130  * @returns #TRUE if equal
2131  */
2132 dbus_bool_t
2133 _dbus_string_equal (const DBusString *a,
2134                     const DBusString *b)
2135 {
2136   const unsigned char *ap;
2137   const unsigned char *bp;
2138   const unsigned char *a_end;
2139   const DBusRealString *real_a = (const DBusRealString*) a;
2140   const DBusRealString *real_b = (const DBusRealString*) b;
2141   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2142   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2143
2144   if (real_a->len != real_b->len)
2145     return FALSE;
2146
2147   ap = real_a->str;
2148   bp = real_b->str;
2149   a_end = real_a->str + real_a->len;
2150   while (ap != a_end)
2151     {
2152       if (*ap != *bp)
2153         return FALSE;
2154       
2155       ++ap;
2156       ++bp;
2157     }
2158
2159   return TRUE;
2160 }
2161
2162 /**
2163  * Tests two DBusString for equality up to the given length.
2164  * The strings may be shorter than the given length.
2165  *
2166  * @todo write a unit test
2167  *
2168  * @todo memcmp is probably faster
2169  *
2170  * @param a first string
2171  * @param b second string
2172  * @param len the maximum length to look at
2173  * @returns #TRUE if equal for the given number of bytes
2174  */
2175 dbus_bool_t
2176 _dbus_string_equal_len (const DBusString *a,
2177                         const DBusString *b,
2178                         int               len)
2179 {
2180   const unsigned char *ap;
2181   const unsigned char *bp;
2182   const unsigned char *a_end;
2183   const DBusRealString *real_a = (const DBusRealString*) a;
2184   const DBusRealString *real_b = (const DBusRealString*) b;
2185   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2186   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2187
2188   if (real_a->len != real_b->len &&
2189       (real_a->len < len || real_b->len < len))
2190     return FALSE;
2191
2192   ap = real_a->str;
2193   bp = real_b->str;
2194   a_end = real_a->str + MIN (real_a->len, len);
2195   while (ap != a_end)
2196     {
2197       if (*ap != *bp)
2198         return FALSE;
2199       
2200       ++ap;
2201       ++bp;
2202     }
2203
2204   return TRUE;
2205 }
2206
2207 /**
2208  * Tests two sub-parts of two DBusString for equality.  The specified
2209  * range of the first string must exist; the specified start position
2210  * of the second string must exist.
2211  *
2212  * @todo write a unit test
2213  *
2214  * @todo memcmp is probably faster
2215  *
2216  * @param a first string
2217  * @param a_start where to start substring in first string
2218  * @param a_len length of substring in first string
2219  * @param b second string
2220  * @param b_start where to start substring in second string
2221  * @returns #TRUE if the two substrings are equal
2222  */
2223 dbus_bool_t
2224 _dbus_string_equal_substring (const DBusString  *a,
2225                               int                a_start,
2226                               int                a_len,
2227                               const DBusString  *b,
2228                               int                b_start)
2229 {
2230   const unsigned char *ap;
2231   const unsigned char *bp;
2232   const unsigned char *a_end;
2233   const DBusRealString *real_a = (const DBusRealString*) a;
2234   const DBusRealString *real_b = (const DBusRealString*) b;
2235   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2236   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2237   _dbus_assert (a_start >= 0);
2238   _dbus_assert (a_len >= 0);
2239   _dbus_assert (a_start <= real_a->len);
2240   _dbus_assert (a_len <= real_a->len - a_start);
2241   _dbus_assert (b_start >= 0);
2242   _dbus_assert (b_start <= real_b->len);
2243   
2244   if (a_len > real_b->len - b_start)
2245     return FALSE;
2246
2247   ap = real_a->str + a_start;
2248   bp = real_b->str + b_start;
2249   a_end = ap + a_len;
2250   while (ap != a_end)
2251     {
2252       if (*ap != *bp)
2253         return FALSE;
2254       
2255       ++ap;
2256       ++bp;
2257     }
2258
2259   _dbus_assert (bp <= (real_b->str + real_b->len));
2260   
2261   return TRUE;
2262 }
2263
2264 /**
2265  * Checks whether a string is equal to a C string.
2266  *
2267  * @param a the string
2268  * @param c_str the C string
2269  * @returns #TRUE if equal
2270  */
2271 dbus_bool_t
2272 _dbus_string_equal_c_str (const DBusString *a,
2273                           const char       *c_str)
2274 {
2275   const unsigned char *ap;
2276   const unsigned char *bp;
2277   const unsigned char *a_end;
2278   const DBusRealString *real_a = (const DBusRealString*) a;
2279   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2280   _dbus_assert (c_str != NULL);
2281   
2282   ap = real_a->str;
2283   bp = (const unsigned char*) c_str;
2284   a_end = real_a->str + real_a->len;
2285   while (ap != a_end && *bp)
2286     {
2287       if (*ap != *bp)
2288         return FALSE;
2289       
2290       ++ap;
2291       ++bp;
2292     }
2293
2294   if (ap != a_end || *bp)
2295     return FALSE;
2296   
2297   return TRUE;
2298 }
2299
2300 /**
2301  * Checks whether a string starts with the given C string.
2302  *
2303  * @param a the string
2304  * @param c_str the C string
2305  * @returns #TRUE if string starts with it
2306  */
2307 dbus_bool_t
2308 _dbus_string_starts_with_c_str (const DBusString *a,
2309                                 const char       *c_str)
2310 {
2311   const unsigned char *ap;
2312   const unsigned char *bp;
2313   const unsigned char *a_end;
2314   const DBusRealString *real_a = (const DBusRealString*) a;
2315   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2316   _dbus_assert (c_str != NULL);
2317   
2318   ap = real_a->str;
2319   bp = (const unsigned char*) c_str;
2320   a_end = real_a->str + real_a->len;
2321   while (ap != a_end && *bp)
2322     {
2323       if (*ap != *bp)
2324         return FALSE;
2325       
2326       ++ap;
2327       ++bp;
2328     }
2329
2330   if (*bp == '\0')
2331     return TRUE;
2332   else
2333     return FALSE;
2334 }
2335
2336 /**
2337  * Returns whether a string ends with the given suffix
2338  *
2339  * @todo memcmp might make this faster.
2340  * 
2341  * @param a the string
2342  * @param c_str the C-style string
2343  * @returns #TRUE if the string ends with the suffix
2344  */
2345 dbus_bool_t
2346 _dbus_string_ends_with_c_str (const DBusString *a,
2347                               const char       *c_str)
2348 {
2349   const unsigned char *ap;
2350   const unsigned char *bp;
2351   const unsigned char *a_end;
2352   unsigned long c_str_len;
2353   const DBusRealString *real_a = (const DBusRealString*) a;
2354   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2355   _dbus_assert (c_str != NULL);
2356   
2357   c_str_len = strlen (c_str);
2358   if (((unsigned long)real_a->len) < c_str_len)
2359     return FALSE;
2360   
2361   ap = real_a->str + (real_a->len - c_str_len);
2362   bp = (const unsigned char*) c_str;
2363   a_end = real_a->str + real_a->len;
2364   while (ap != a_end)
2365     {
2366       if (*ap != *bp)
2367         return FALSE;
2368       
2369       ++ap;
2370       ++bp;
2371     }
2372
2373   _dbus_assert (*ap == '\0');
2374   _dbus_assert (*bp == '\0');
2375   
2376   return TRUE;
2377 }
2378
2379 /**
2380  * Encodes a string in hex, the way MD5 and SHA-1 are usually
2381  * encoded. (Each byte is two hex digits.)
2382  *
2383  * @param source the string to encode
2384  * @param start byte index to start encoding
2385  * @param dest string where encoded data should be placed
2386  * @param insert_at where to place encoded data
2387  * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2388  */
2389 dbus_bool_t
2390 _dbus_string_hex_encode (const DBusString *source,
2391                          int               start,
2392                          DBusString       *dest,
2393                          int               insert_at)
2394 {
2395   DBusString result;
2396   const char hexdigits[16] = {
2397     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2398     'a', 'b', 'c', 'd', 'e', 'f'
2399   };
2400   const unsigned char *p;
2401   const unsigned char *end;
2402   dbus_bool_t retval;
2403   
2404   _dbus_assert (start <= _dbus_string_get_length (source));
2405
2406   if (!_dbus_string_init (&result))
2407     return FALSE;
2408
2409   retval = FALSE;
2410   
2411   p = (const unsigned char*) _dbus_string_get_const_data (source);
2412   end = p + _dbus_string_get_length (source);
2413   p += start;
2414   
2415   while (p != end)
2416     {
2417       if (!_dbus_string_append_byte (&result,
2418                                      hexdigits[(*p >> 4)]))
2419         goto out;
2420       
2421       if (!_dbus_string_append_byte (&result,
2422                                      hexdigits[(*p & 0x0f)]))
2423         goto out;
2424
2425       ++p;
2426     }
2427
2428   if (!_dbus_string_move (&result, 0, dest, insert_at))
2429     goto out;
2430
2431   retval = TRUE;
2432
2433  out:
2434   _dbus_string_free (&result);
2435   return retval;
2436 }
2437
2438 /**
2439  * Decodes a string from hex encoding.
2440  *
2441  * @param source the string to decode
2442  * @param start byte index to start decode
2443  * @param end_return return location of the end of the hex data, or #NULL
2444  * @param dest string where decoded data should be placed
2445  * @param insert_at where to place decoded data
2446  * @returns #TRUE if decoding was successful, #FALSE if no memory.
2447  */
2448 dbus_bool_t
2449 _dbus_string_hex_decode (const DBusString *source,
2450                          int               start,
2451                          int              *end_return,
2452                          DBusString       *dest,
2453                          int               insert_at)
2454 {
2455   DBusString result;
2456   const unsigned char *p;
2457   const unsigned char *end;
2458   dbus_bool_t retval;
2459   dbus_bool_t high_bits;
2460   
2461   _dbus_assert (start <= _dbus_string_get_length (source));
2462
2463   if (!_dbus_string_init (&result))
2464     return FALSE;
2465
2466   retval = FALSE;
2467
2468   high_bits = TRUE;
2469   p = (const unsigned char*) _dbus_string_get_const_data (source);
2470   end = p + _dbus_string_get_length (source);
2471   p += start;
2472   
2473   while (p != end)
2474     {
2475       unsigned int val;
2476
2477       switch (*p)
2478         {
2479         case '0':
2480           val = 0;
2481           break;
2482         case '1':
2483           val = 1;
2484           break;
2485         case '2':
2486           val = 2;
2487           break;
2488         case '3':
2489           val = 3;
2490           break;
2491         case '4':
2492           val = 4;
2493           break;
2494         case '5':
2495           val = 5;
2496           break;
2497         case '6':
2498           val = 6;
2499           break;
2500         case '7':
2501           val = 7;
2502           break;
2503         case '8':
2504           val = 8;
2505           break;
2506         case '9':
2507           val = 9;
2508           break;
2509         case 'a':
2510         case 'A':
2511           val = 10;
2512           break;
2513         case 'b':
2514         case 'B':
2515           val = 11;
2516           break;
2517         case 'c':
2518         case 'C':
2519           val = 12;
2520           break;
2521         case 'd':
2522         case 'D':
2523           val = 13;
2524           break;
2525         case 'e':
2526         case 'E':
2527           val = 14;
2528           break;
2529         case 'f':
2530         case 'F':
2531           val = 15;
2532           break;
2533         default:
2534           goto done;
2535         }
2536
2537       if (high_bits)
2538         {
2539           if (!_dbus_string_append_byte (&result,
2540                                          val << 4))
2541             goto out;
2542         }
2543       else
2544         {
2545           int len;
2546           unsigned char b;
2547
2548           len = _dbus_string_get_length (&result);
2549           
2550           b = _dbus_string_get_byte (&result, len - 1);
2551
2552           b |= val;
2553
2554           _dbus_string_set_byte (&result, len - 1, b);
2555         }
2556
2557       high_bits = !high_bits;
2558
2559       ++p;
2560     }
2561
2562  done:
2563   if (!_dbus_string_move (&result, 0, dest, insert_at))
2564     goto out;
2565
2566   if (end_return)
2567     *end_return = p - (const unsigned char*) _dbus_string_get_const_data (source);
2568
2569   retval = TRUE;
2570   
2571  out:
2572   _dbus_string_free (&result);  
2573   return retval;
2574 }
2575
2576 /**
2577  * Checks that the given range of the string is valid ASCII with no
2578  * nul bytes. If the given range is not entirely contained in the
2579  * string, returns #FALSE.
2580  *
2581  * @todo this is inconsistent with most of DBusString in that
2582  * it allows a start,len range that extends past the string end.
2583  * 
2584  * @param str the string
2585  * @param start first byte index to check
2586  * @param len number of bytes to check
2587  * @returns #TRUE if the byte range exists and is all valid ASCII
2588  */
2589 dbus_bool_t
2590 _dbus_string_validate_ascii (const DBusString *str,
2591                              int               start,
2592                              int               len)
2593 {
2594   const unsigned char *s;
2595   const unsigned char *end;
2596   DBUS_CONST_STRING_PREAMBLE (str);
2597   _dbus_assert (start >= 0);
2598   _dbus_assert (start <= real->len);
2599   _dbus_assert (len >= 0);
2600   
2601   if (len > real->len - start)
2602     return FALSE;
2603   
2604   s = real->str + start;
2605   end = s + len;
2606   while (s != end)
2607     {
2608       if (_DBUS_UNLIKELY (!_DBUS_ISASCII (*s)))
2609         return FALSE;
2610         
2611       ++s;
2612     }
2613   
2614   return TRUE;
2615 }
2616
2617 /**
2618  * Checks that the given range of the string is valid UTF-8. If the
2619  * given range is not entirely contained in the string, returns
2620  * #FALSE. If the string contains any nul bytes in the given range,
2621  * returns #FALSE. If the start and start+len are not on character
2622  * boundaries, returns #FALSE.
2623  *
2624  * @todo this is inconsistent with most of DBusString in that
2625  * it allows a start,len range that extends past the string end.
2626  * 
2627  * @param str the string
2628  * @param start first byte index to check
2629  * @param len number of bytes to check
2630  * @returns #TRUE if the byte range exists and is all valid UTF-8
2631  */
2632 dbus_bool_t
2633 _dbus_string_validate_utf8  (const DBusString *str,
2634                              int               start,
2635                              int               len)
2636 {
2637   const unsigned char *p;
2638   const unsigned char *end;
2639   DBUS_CONST_STRING_PREAMBLE (str);
2640   _dbus_assert (start >= 0);
2641   _dbus_assert (start <= real->len);
2642   _dbus_assert (len >= 0);
2643
2644   /* we are doing _DBUS_UNLIKELY() here which might be
2645    * dubious in a generic library like GLib, but in D-BUS
2646    * we know we're validating messages and that it would
2647    * only be evil/broken apps that would have invalid
2648    * UTF-8. Also, this function seems to be a performance
2649    * bottleneck in profiles.
2650    */
2651   
2652   if (_DBUS_UNLIKELY (len > real->len - start))
2653     return FALSE;
2654   
2655   p = real->str + start;
2656   end = p + len;
2657   
2658   while (p < end)
2659     {
2660       int i, mask, char_len;
2661       dbus_unichar_t result;
2662
2663       /* nul bytes considered invalid */
2664       if (*p == '\0')
2665         break;
2666       
2667       /* Special-case ASCII; this makes us go a lot faster in
2668        * D-BUS profiles where we are typically validating
2669        * function names and such. We have to know that
2670        * all following checks will pass for ASCII though,
2671        * comments follow ...
2672        */      
2673       if (*p < 128)
2674         {
2675           ++p;
2676           continue;
2677         }
2678       
2679       UTF8_COMPUTE (*p, mask, char_len);
2680
2681       if (_DBUS_UNLIKELY (char_len == 0))  /* ASCII: char_len == 1 */
2682         break;
2683
2684       /* check that the expected number of bytes exists in the remaining length */
2685       if (_DBUS_UNLIKELY ((end - p) < char_len)) /* ASCII: p < end and char_len == 1 */
2686         break;
2687         
2688       UTF8_GET (result, p, i, mask, char_len);
2689
2690       /* Check for overlong UTF-8 */
2691       if (_DBUS_UNLIKELY (UTF8_LENGTH (result) != char_len)) /* ASCII: UTF8_LENGTH == 1 */
2692         break;
2693 #if 0
2694       /* The UNICODE_VALID check below will catch this */
2695       if (_DBUS_UNLIKELY (result == (dbus_unichar_t)-1)) /* ASCII: result = ascii value */
2696         break;
2697 #endif
2698
2699       if (_DBUS_UNLIKELY (!UNICODE_VALID (result))) /* ASCII: always valid */
2700         break;
2701
2702       /* UNICODE_VALID should have caught it */
2703       _dbus_assert (result != (dbus_unichar_t)-1);
2704       
2705       p += char_len;
2706     }
2707
2708   /* See that we covered the entire length if a length was
2709    * passed in
2710    */
2711   if (_DBUS_UNLIKELY (p != end))
2712     return FALSE;
2713   else
2714     return TRUE;
2715 }
2716
2717 /**
2718  * Checks that the given range of the string is all nul bytes. If the
2719  * given range is not entirely contained in the string, returns
2720  * #FALSE.
2721  *
2722  * @todo this is inconsistent with most of DBusString in that
2723  * it allows a start,len range that extends past the string end.
2724  * 
2725  * @param str the string
2726  * @param start first byte index to check
2727  * @param len number of bytes to check
2728  * @returns #TRUE if the byte range exists and is all nul bytes
2729  */
2730 dbus_bool_t
2731 _dbus_string_validate_nul (const DBusString *str,
2732                            int               start,
2733                            int               len)
2734 {
2735   const unsigned char *s;
2736   const unsigned char *end;
2737   DBUS_CONST_STRING_PREAMBLE (str);
2738   _dbus_assert (start >= 0);
2739   _dbus_assert (len >= 0);
2740   _dbus_assert (start <= real->len);
2741   
2742   if (len > real->len - start)
2743     return FALSE;
2744   
2745   s = real->str + start;
2746   end = s + len;
2747   while (s != end)
2748     {
2749       if (_DBUS_UNLIKELY (*s != '\0'))
2750         return FALSE;
2751       ++s;
2752     }
2753   
2754   return TRUE;
2755 }
2756
2757 /**
2758  * Clears all allocated bytes in the string to zero.
2759  *
2760  * @param str the string
2761  */
2762 void
2763 _dbus_string_zero (DBusString *str)
2764 {
2765   DBUS_STRING_PREAMBLE (str);
2766
2767   memset (real->str - real->align_offset, '\0', real->allocated);
2768 }
2769 /** @} */
2770
2771 #ifdef DBUS_BUILD_TESTS
2772 #include "dbus-test.h"
2773 #include <stdio.h>
2774
2775 /**
2776  * Parses a basic type defined by type contained in a DBusString. The
2777  * end_return parameter may be #NULL if you aren't interested in it. The
2778  * type is parsed and stored in value_return. Return parameters are not
2779  * initialized if the function returns #FALSE.
2780  *
2781  * @param str the string
2782  * @param type the type of the basic type
2783  * @param start the byte index of the start of the type
2784  * @param value_return return location of the value or #NULL
2785  * @param end_return return location of the end of the type, or #NULL
2786  * @returns #TRUE on success
2787  */
2788 dbus_bool_t
2789 _dbus_string_parse_basic_type (const DBusString  *str,
2790                                char               type,
2791                                int                start,
2792                                void              *value,
2793                                int               *end_return)
2794 {
2795   int end = start;
2796
2797   switch (type)
2798     {
2799     case DBUS_TYPE_BOOLEAN:
2800       {
2801         int len = _dbus_string_get_length (str) - start;
2802         if (len >= 5 && _dbus_string_find_to (str, start, start + 5, "false", NULL))
2803           {
2804             end += 5;
2805             *(unsigned char *) value = TRUE;
2806           }
2807         else if (len >= 4 && _dbus_string_find_to (str, start, start + 4, "true", NULL))
2808           {
2809             end += 4;
2810             *(unsigned char *) value = FALSE;
2811           }
2812         else
2813           _dbus_warn ("could not parse BOOLEAN\n");
2814         break;
2815       }
2816     case DBUS_TYPE_BYTE:
2817       {
2818         long val = 0;
2819
2820         if (_dbus_string_get_byte (str, start) == '\'' &&
2821             _dbus_string_get_length (str) >= start + 4 &&
2822             _dbus_string_get_byte (str, start + 1) == '\\' &&
2823             _dbus_string_get_byte (str, start + 2) == '\'' &&
2824             _dbus_string_get_byte (str, start + 3) == '\'')
2825           {
2826             val = '\'';
2827             end += 4;
2828           }
2829         else if (_dbus_string_get_byte (str, start) == '\'' &&
2830                  _dbus_string_get_length (str) >= start + 3 &&
2831                  _dbus_string_get_byte (str, start + 2) == '\'')
2832           {
2833             val = _dbus_string_get_byte (str, start + 1);
2834             end += 3;
2835           }
2836         else
2837           {
2838             if (!_dbus_string_parse_int (str, start, &val, &end)) 
2839               _dbus_warn ("Failed to parse integer for BYTE\n");
2840           }
2841
2842         if (val > 255)
2843           _dbus_warn ("A byte must be in range 0-255 not %ld\n", val);
2844
2845         *(unsigned char *) value = val;
2846         break;
2847       }
2848     case DBUS_TYPE_INT32:
2849       {
2850         long val;
2851         if (_dbus_string_parse_int (str, start, &val, &end))
2852           *(dbus_int32_t *)value = val;
2853         break;
2854       }
2855     case DBUS_TYPE_UINT32:
2856       {
2857         unsigned long val;
2858         if (_dbus_string_parse_uint (str, start, &val, &end))
2859           *(dbus_uint32_t *)value = val;
2860         break;
2861       }
2862 #ifdef DBUS_HAVE_INT64
2863     case DBUS_TYPE_INT64:
2864     case DBUS_TYPE_UINT64: 
2865       /* use stroll oull */
2866       _dbus_assert_not_reached ("string -> [u]int64 not supported yet");
2867       break;
2868 #endif /* DBUS_HAVE_INT64 */
2869     case DBUS_TYPE_DOUBLE:
2870       _dbus_string_parse_double (str, start, value, &end);
2871       break;
2872     default:
2873       _dbus_assert_not_reached ("not a basic type");
2874       break;
2875     }
2876   if (end_return)
2877     *end_return = end;
2878
2879   return end != start;
2880 }
2881
2882 static void
2883 test_max_len (DBusString *str,
2884               int         max_len)
2885 {
2886   if (max_len > 0)
2887     {
2888       if (!_dbus_string_set_length (str, max_len - 1))
2889         _dbus_assert_not_reached ("setting len to one less than max should have worked");
2890     }
2891
2892   if (!_dbus_string_set_length (str, max_len))
2893     _dbus_assert_not_reached ("setting len to max len should have worked");
2894
2895   if (_dbus_string_set_length (str, max_len + 1))
2896     _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2897
2898   if (!_dbus_string_set_length (str, 0))
2899     _dbus_assert_not_reached ("setting len to zero should have worked");
2900 }
2901
2902 static void
2903 test_hex_roundtrip (const unsigned char *data,
2904                     int                  len)
2905 {
2906   DBusString orig;
2907   DBusString encoded;
2908   DBusString decoded;
2909   int end;
2910
2911   if (len < 0)
2912     len = strlen (data);
2913   
2914   if (!_dbus_string_init (&orig))
2915     _dbus_assert_not_reached ("could not init string");
2916
2917   if (!_dbus_string_init (&encoded))
2918     _dbus_assert_not_reached ("could not init string");
2919   
2920   if (!_dbus_string_init (&decoded))
2921     _dbus_assert_not_reached ("could not init string");
2922
2923   if (!_dbus_string_append_len (&orig, data, len))
2924     _dbus_assert_not_reached ("couldn't append orig data");
2925
2926   if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2927     _dbus_assert_not_reached ("could not encode");
2928
2929   if (!_dbus_string_hex_decode (&encoded, 0, &end, &decoded, 0))
2930     _dbus_assert_not_reached ("could not decode");
2931     
2932   _dbus_assert (_dbus_string_get_length (&encoded) == end);
2933
2934   if (!_dbus_string_equal (&orig, &decoded))
2935     {
2936       const char *s;
2937       
2938       printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2939               _dbus_string_get_length (&orig),
2940               _dbus_string_get_length (&encoded),
2941               _dbus_string_get_length (&decoded));
2942       printf ("Original: %s\n", data);
2943       s = _dbus_string_get_const_data (&decoded);
2944       printf ("Decoded: %s\n", s);
2945       _dbus_assert_not_reached ("original string not the same as string decoded from hex");
2946     }
2947   
2948   _dbus_string_free (&orig);
2949   _dbus_string_free (&encoded);
2950   _dbus_string_free (&decoded);  
2951 }
2952
2953 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2954                                     int                  len);
2955 static void
2956 test_roundtrips (TestRoundtripFunc func)
2957 {
2958   (* func) ("Hello this is a string\n", -1);
2959   (* func) ("Hello this is a string\n1", -1);
2960   (* func) ("Hello this is a string\n12", -1);
2961   (* func) ("Hello this is a string\n123", -1);
2962   (* func) ("Hello this is a string\n1234", -1);
2963   (* func) ("Hello this is a string\n12345", -1);
2964   (* func) ("", 0);
2965   (* func) ("1", 1);
2966   (* func) ("12", 2);
2967   (* func) ("123", 3);
2968   (* func) ("1234", 4);
2969   (* func) ("12345", 5);
2970   (* func) ("", 1);
2971   (* func) ("1", 2);
2972   (* func) ("12", 3);
2973   (* func) ("123", 4);
2974   (* func) ("1234", 5);
2975   (* func) ("12345", 6);
2976   {
2977     unsigned char buf[512];
2978     int i;
2979     
2980     i = 0;
2981     while (i < _DBUS_N_ELEMENTS (buf))
2982       {
2983         buf[i] = i;
2984         ++i;
2985       }
2986     i = 0;
2987     while (i < _DBUS_N_ELEMENTS (buf))
2988       {
2989         (* func) (buf, i);
2990         ++i;
2991       }
2992   }
2993 }
2994
2995
2996 /**
2997  * @ingroup DBusStringInternals
2998  * Unit test for DBusString.
2999  *
3000  * @todo Need to write tests for _dbus_string_copy() and
3001  * _dbus_string_move() moving to/from each of start/middle/end of a
3002  * string. Also need tests for _dbus_string_move_len ()
3003  * 
3004  * @returns #TRUE on success.
3005  */
3006 dbus_bool_t
3007 _dbus_string_test (void)
3008 {
3009   DBusString str;
3010   DBusString other;
3011   int i, end;
3012   long v;
3013   double d;
3014   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 };
3015   char *s;
3016   dbus_unichar_t ch;
3017   
3018   i = 0;
3019   while (i < _DBUS_N_ELEMENTS (lens))
3020     {
3021       if (!_dbus_string_init (&str))
3022         _dbus_assert_not_reached ("failed to init string");
3023
3024       set_max_length (&str, lens[i]);
3025       
3026       test_max_len (&str, lens[i]);
3027       _dbus_string_free (&str);
3028
3029       ++i;
3030     }
3031
3032   /* Test shortening and setting length */
3033   i = 0;
3034   while (i < _DBUS_N_ELEMENTS (lens))
3035     {
3036       int j;
3037       
3038       if (!_dbus_string_init (&str))
3039         _dbus_assert_not_reached ("failed to init string");
3040
3041       set_max_length (&str, lens[i]);
3042       
3043       if (!_dbus_string_set_length (&str, lens[i]))
3044         _dbus_assert_not_reached ("failed to set string length");
3045
3046       j = lens[i];
3047       while (j > 0)
3048         {
3049           _dbus_assert (_dbus_string_get_length (&str) == j);
3050           if (j > 0)
3051             {
3052               _dbus_string_shorten (&str, 1);
3053               _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
3054             }
3055           --j;
3056         }
3057       
3058       _dbus_string_free (&str);
3059
3060       ++i;
3061     }
3062
3063   /* Test appending data */
3064   if (!_dbus_string_init (&str))
3065     _dbus_assert_not_reached ("failed to init string");
3066
3067   i = 0;
3068   while (i < 10)
3069     {
3070       if (!_dbus_string_append (&str, "a"))
3071         _dbus_assert_not_reached ("failed to append string to string\n");
3072
3073       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
3074
3075       if (!_dbus_string_append_byte (&str, 'b'))
3076         _dbus_assert_not_reached ("failed to append byte to string\n");
3077
3078       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
3079                     
3080       ++i;
3081     }
3082
3083   _dbus_string_free (&str);
3084
3085   /* Check steal_data */
3086   
3087   if (!_dbus_string_init (&str))
3088     _dbus_assert_not_reached ("failed to init string");
3089
3090   if (!_dbus_string_append (&str, "Hello World"))
3091     _dbus_assert_not_reached ("could not append to string");
3092
3093   i = _dbus_string_get_length (&str);
3094   
3095   if (!_dbus_string_steal_data (&str, &s))
3096     _dbus_assert_not_reached ("failed to steal data");
3097
3098   _dbus_assert (_dbus_string_get_length (&str) == 0);
3099   _dbus_assert (((int)strlen (s)) == i);
3100
3101   dbus_free (s);
3102
3103   /* Check move */
3104   
3105   if (!_dbus_string_append (&str, "Hello World"))
3106     _dbus_assert_not_reached ("could not append to string");
3107
3108   i = _dbus_string_get_length (&str);
3109
3110   if (!_dbus_string_init (&other))
3111     _dbus_assert_not_reached ("could not init string");
3112   
3113   if (!_dbus_string_move (&str, 0, &other, 0))
3114     _dbus_assert_not_reached ("could not move");
3115
3116   _dbus_assert (_dbus_string_get_length (&str) == 0);
3117   _dbus_assert (_dbus_string_get_length (&other) == i);
3118
3119   if (!_dbus_string_append (&str, "Hello World"))
3120     _dbus_assert_not_reached ("could not append to string");
3121   
3122   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
3123     _dbus_assert_not_reached ("could not move");
3124
3125   _dbus_assert (_dbus_string_get_length (&str) == 0);
3126   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
3127
3128     if (!_dbus_string_append (&str, "Hello World"))
3129     _dbus_assert_not_reached ("could not append to string");
3130   
3131   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
3132     _dbus_assert_not_reached ("could not move");
3133
3134   _dbus_assert (_dbus_string_get_length (&str) == 0);
3135   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
3136   
3137   _dbus_string_free (&other);
3138
3139   /* Check copy */
3140   
3141   if (!_dbus_string_append (&str, "Hello World"))
3142     _dbus_assert_not_reached ("could not append to string");
3143
3144   i = _dbus_string_get_length (&str);
3145   
3146   if (!_dbus_string_init (&other))
3147     _dbus_assert_not_reached ("could not init string");
3148   
3149   if (!_dbus_string_copy (&str, 0, &other, 0))
3150     _dbus_assert_not_reached ("could not copy");
3151
3152   _dbus_assert (_dbus_string_get_length (&str) == i);
3153   _dbus_assert (_dbus_string_get_length (&other) == i);
3154
3155   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
3156     _dbus_assert_not_reached ("could not copy");
3157
3158   _dbus_assert (_dbus_string_get_length (&str) == i);
3159   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
3160   _dbus_assert (_dbus_string_equal_c_str (&other,
3161                                           "Hello WorldHello World"));
3162
3163   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
3164     _dbus_assert_not_reached ("could not copy");
3165
3166   _dbus_assert (_dbus_string_get_length (&str) == i);
3167   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
3168   _dbus_assert (_dbus_string_equal_c_str (&other,
3169                                           "Hello WorldHello WorldHello World"));
3170   
3171   _dbus_string_free (&str);
3172   _dbus_string_free (&other);
3173
3174   /* Check replace */
3175
3176   if (!_dbus_string_init (&str))
3177     _dbus_assert_not_reached ("failed to init string");
3178   
3179   if (!_dbus_string_append (&str, "Hello World"))
3180     _dbus_assert_not_reached ("could not append to string");
3181
3182   i = _dbus_string_get_length (&str);
3183   
3184   if (!_dbus_string_init (&other))
3185     _dbus_assert_not_reached ("could not init string");
3186   
3187   if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3188                                  &other, 0, _dbus_string_get_length (&other)))
3189     _dbus_assert_not_reached ("could not replace");
3190
3191   _dbus_assert (_dbus_string_get_length (&str) == i);
3192   _dbus_assert (_dbus_string_get_length (&other) == i);
3193   _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
3194   
3195   if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
3196                                  &other, 5, 1))
3197     _dbus_assert_not_reached ("could not replace center space");
3198
3199   _dbus_assert (_dbus_string_get_length (&str) == i);
3200   _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3201   _dbus_assert (_dbus_string_equal_c_str (&other,
3202                                           "HelloHello WorldWorld"));
3203
3204   
3205   if (!_dbus_string_replace_len (&str, 1, 1,
3206                                  &other,
3207                                  _dbus_string_get_length (&other) - 1,
3208                                  1))
3209     _dbus_assert_not_reached ("could not replace end character");
3210   
3211   _dbus_assert (_dbus_string_get_length (&str) == i);
3212   _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
3213   _dbus_assert (_dbus_string_equal_c_str (&other,
3214                                           "HelloHello WorldWorle"));
3215   
3216   _dbus_string_free (&str);
3217   _dbus_string_free (&other);
3218   
3219   /* Check append/get unichar */
3220   
3221   if (!_dbus_string_init (&str))
3222     _dbus_assert_not_reached ("failed to init string");
3223
3224   ch = 0;
3225   if (!_dbus_string_append_unichar (&str, 0xfffc))
3226     _dbus_assert_not_reached ("failed to append unichar");
3227
3228   _dbus_string_get_unichar (&str, 0, &ch, &i);
3229
3230   _dbus_assert (ch == 0xfffc);
3231   _dbus_assert (i == _dbus_string_get_length (&str));
3232
3233   _dbus_string_free (&str);
3234
3235   /* Check insert/set/get byte */
3236   
3237   if (!_dbus_string_init (&str))
3238     _dbus_assert_not_reached ("failed to init string");
3239
3240   if (!_dbus_string_append (&str, "Hello"))
3241     _dbus_assert_not_reached ("failed to append Hello");
3242
3243   _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
3244   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
3245   _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
3246   _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
3247   _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
3248
3249   _dbus_string_set_byte (&str, 1, 'q');
3250   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
3251
3252   if (!_dbus_string_insert_bytes (&str, 0, 1, 255))
3253     _dbus_assert_not_reached ("can't insert byte");
3254
3255   if (!_dbus_string_insert_bytes (&str, 2, 4, 'Z'))
3256     _dbus_assert_not_reached ("can't insert byte");
3257
3258   if (!_dbus_string_insert_bytes (&str, _dbus_string_get_length (&str), 1, 'W'))
3259     _dbus_assert_not_reached ("can't insert byte");
3260   
3261   _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
3262   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
3263   _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
3264   _dbus_assert (_dbus_string_get_byte (&str, 3) == 'Z');
3265   _dbus_assert (_dbus_string_get_byte (&str, 4) == 'Z');
3266   _dbus_assert (_dbus_string_get_byte (&str, 5) == 'Z');
3267   _dbus_assert (_dbus_string_get_byte (&str, 6) == 'q');
3268   _dbus_assert (_dbus_string_get_byte (&str, 7) == 'l');
3269   _dbus_assert (_dbus_string_get_byte (&str, 8) == 'l');
3270   _dbus_assert (_dbus_string_get_byte (&str, 9) == 'o');
3271   _dbus_assert (_dbus_string_get_byte (&str, 10) == 'W');
3272
3273   _dbus_string_free (&str);
3274   
3275   /* Check append/parse int/double */
3276   
3277   if (!_dbus_string_init (&str))
3278     _dbus_assert_not_reached ("failed to init string");
3279
3280   if (!_dbus_string_append_int (&str, 27))
3281     _dbus_assert_not_reached ("failed to append int");
3282
3283   i = _dbus_string_get_length (&str);
3284
3285   if (!_dbus_string_parse_int (&str, 0, &v, &end))
3286     _dbus_assert_not_reached ("failed to parse int");
3287
3288   _dbus_assert (v == 27);
3289   _dbus_assert (end == i);
3290
3291   _dbus_string_free (&str);
3292   
3293   if (!_dbus_string_init (&str))
3294     _dbus_assert_not_reached ("failed to init string");
3295   
3296   if (!_dbus_string_append_double (&str, 50.3))
3297     _dbus_assert_not_reached ("failed to append float");
3298
3299   i = _dbus_string_get_length (&str);
3300
3301   if (!_dbus_string_parse_double (&str, 0, &d, &end))
3302     _dbus_assert_not_reached ("failed to parse float");
3303
3304   _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
3305   _dbus_assert (end == i);
3306
3307   _dbus_string_free (&str);
3308
3309   /* Test find */
3310   if (!_dbus_string_init (&str))
3311     _dbus_assert_not_reached ("failed to init string");
3312
3313   if (!_dbus_string_append (&str, "Hello"))
3314     _dbus_assert_not_reached ("couldn't append to string");
3315   
3316   if (!_dbus_string_find (&str, 0, "He", &i))
3317     _dbus_assert_not_reached ("didn't find 'He'");
3318   _dbus_assert (i == 0);
3319
3320   if (!_dbus_string_find (&str, 0, "Hello", &i))
3321     _dbus_assert_not_reached ("didn't find 'Hello'");
3322   _dbus_assert (i == 0);
3323   
3324   if (!_dbus_string_find (&str, 0, "ello", &i))
3325     _dbus_assert_not_reached ("didn't find 'ello'");
3326   _dbus_assert (i == 1);
3327
3328   if (!_dbus_string_find (&str, 0, "lo", &i))
3329     _dbus_assert_not_reached ("didn't find 'lo'");
3330   _dbus_assert (i == 3);
3331
3332   if (!_dbus_string_find (&str, 2, "lo", &i))
3333     _dbus_assert_not_reached ("didn't find 'lo'");
3334   _dbus_assert (i == 3);
3335
3336   if (_dbus_string_find (&str, 4, "lo", &i))
3337     _dbus_assert_not_reached ("did find 'lo'");
3338   
3339   if (!_dbus_string_find (&str, 0, "l", &i))
3340     _dbus_assert_not_reached ("didn't find 'l'");
3341   _dbus_assert (i == 2);
3342
3343   if (!_dbus_string_find (&str, 0, "H", &i))
3344     _dbus_assert_not_reached ("didn't find 'H'");
3345   _dbus_assert (i == 0);
3346
3347   if (!_dbus_string_find (&str, 0, "", &i))
3348     _dbus_assert_not_reached ("didn't find ''");
3349   _dbus_assert (i == 0);
3350   
3351   if (_dbus_string_find (&str, 0, "Hello!", NULL))
3352     _dbus_assert_not_reached ("Did find 'Hello!'");
3353
3354   if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
3355     _dbus_assert_not_reached ("Did find 'Oh, Hello'");
3356   
3357   if (_dbus_string_find (&str, 0, "ill", NULL))
3358     _dbus_assert_not_reached ("Did find 'ill'");
3359
3360   if (_dbus_string_find (&str, 0, "q", NULL))
3361     _dbus_assert_not_reached ("Did find 'q'");
3362
3363   if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
3364     _dbus_assert_not_reached ("Didn't find 'He'");
3365
3366   if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
3367     _dbus_assert_not_reached ("Did find 'Hello'");
3368
3369   if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'H', &i))
3370     _dbus_assert_not_reached ("Did not find 'H'");
3371   _dbus_assert (i == 0);
3372
3373   if (!_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str), 'o', &i))
3374     _dbus_assert_not_reached ("Did not find 'o'");
3375   _dbus_assert (i == _dbus_string_get_length (&str) - 1);
3376
3377   if (_dbus_string_find_byte_backward (&str, _dbus_string_get_length (&str) - 1, 'o', &i))
3378     _dbus_assert_not_reached ("Did find 'o'");
3379   _dbus_assert (i == -1);
3380
3381   if (_dbus_string_find_byte_backward (&str, 1, 'e', &i))
3382     _dbus_assert_not_reached ("Did find 'e'");
3383   _dbus_assert (i == -1);
3384
3385   if (!_dbus_string_find_byte_backward (&str, 2, 'e', &i))
3386     _dbus_assert_not_reached ("Didn't find 'e'");
3387   _dbus_assert (i == 1);
3388   
3389   _dbus_string_free (&str);
3390
3391   /* Hex encoding */
3392   _dbus_string_init_const (&str, "cafebabe, this is a bogus hex string");
3393   if (!_dbus_string_init (&other))
3394     _dbus_assert_not_reached ("could not init string");
3395
3396   if (!_dbus_string_hex_decode (&str, 0, &end, &other, 0))
3397     _dbus_assert_not_reached ("deccoded bogus hex string with no error");
3398
3399   _dbus_assert (end == 8);
3400
3401   _dbus_string_free (&other);
3402
3403   test_roundtrips (test_hex_roundtrip);
3404   
3405   _dbus_string_free (&str);
3406   
3407   return TRUE;
3408 }
3409
3410 #endif /* DBUS_BUILD_TESTS */