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