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