2003-02-01 Havoc Pennington <hp@pobox.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  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
29 /**
30  * @defgroup DBusString string class
31  * @ingroup  DBusInternals
32  * @brief DBusString data structure
33  *
34  * Types and functions related to DBusString. DBusString is intended
35  * to be a string class that makes it hard to mess up security issues
36  * (and just in general harder to write buggy code).  It should be
37  * used (or extended and then used) rather than the libc stuff in
38  * string.h.  The string class is a bit inconvenient at spots because
39  * it handles out-of-memory failures and tries to be extra-robust.
40  * 
41  * A DBusString has a maximum length set at initialization time; this
42  * can be used to ensure that a buffer doesn't get too big.  The
43  * _dbus_string_lengthen() method checks for overflow, and for max
44  * length being exceeded.
45  * 
46  * Try to avoid conversion to a plain C string, i.e. add methods on
47  * the string object instead, only convert to C string when passing
48  * things out to the public API. In particular, no sprintf, strcpy,
49  * strcat, any of that should be used. The GString feature of
50  * accepting negative numbers for "length of string" is also absent,
51  * because it could keep us from detecting bogus huge lengths. i.e. if
52  * we passed in some bogus huge length it would be taken to mean
53  * "current length of string" instead of "broken crack"
54  */
55
56 /**
57  * @defgroup DBusStringInternals DBusString implementation details
58  * @ingroup  DBusInternals
59  * @brief DBusString implementation details
60  *
61  * The guts of DBusString.
62  *
63  * @{
64  */
65
66 /**
67  * @brief Internals of DBusString.
68  * 
69  * DBusString internals. DBusString is an opaque objects, it must be
70  * used via accessor functions.
71  */
72 typedef struct
73 {
74   unsigned char *str;            /**< String data, plus nul termination */
75   int            len;            /**< Length without nul */
76   int            allocated;      /**< Allocated size of data */
77   int            max_length;     /**< Max length of this string. */
78   unsigned int   constant : 1;   /**< String data is not owned by DBusString */
79   unsigned int   locked : 1;     /**< DBusString has been locked and can't be changed */
80   unsigned int   invalid : 1;    /**< DBusString is invalid (e.g. already freed) */
81 } DBusRealString;
82
83 /**
84  * Checks a bunch of assertions about a string object
85  *
86  * @param real the DBusRealString
87  */
88 #define DBUS_GENERIC_STRING_PREAMBLE(real) _dbus_assert ((real) != NULL); _dbus_assert (!(real)->invalid); _dbus_assert ((real)->len >= 0); _dbus_assert ((real)->allocated >= 0); _dbus_assert ((real)->max_length >= 0); _dbus_assert ((real)->len <= (real)->allocated); _dbus_assert ((real)->len <= (real)->max_length)
89
90 /**
91  * Checks assertions about a string object that needs to be
92  * modifiable - may not be locked or const. Also declares
93  * the "real" variable pointing to DBusRealString. 
94  * @param str the string
95  */
96 #define DBUS_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
97   DBUS_GENERIC_STRING_PREAMBLE (real);                                          \
98   _dbus_assert (!(real)->constant);                                             \
99   _dbus_assert (!(real)->locked)
100
101 /**
102  * Checks assertions about a string object that may be locked but
103  * can't be const. i.e. a string object that we can free.  Also
104  * declares the "real" variable pointing to DBusRealString.
105  *
106  * @param str the string
107  */
108 #define DBUS_LOCKED_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
109   DBUS_GENERIC_STRING_PREAMBLE (real);                                                 \
110   _dbus_assert (!(real)->constant)
111
112 /**
113  * Checks assertions about a string that may be const or locked.  Also
114  * declares the "real" variable pointing to DBusRealString.
115  * @param str the string.
116  */
117 #define DBUS_CONST_STRING_PREAMBLE(str) const DBusRealString *real = (DBusRealString*) str; \
118   DBUS_GENERIC_STRING_PREAMBLE (real)
119
120 /** @} */
121
122 /**
123  * @addtogroup DBusString
124  * @{
125  */
126
127 /** Assert that the string's memory is 8-byte aligned.
128  *
129  *  @todo Currently we just hope libc returns 8-byte aligned memory
130  *  (which is true for GNU libc), but really we need to ensure it by
131  *  allocating 8 extra bytes and keeping an "align_offset : 3" field
132  *  in DBusString, or something along those lines.
133  */
134 #define ASSERT_8_BYTE_ALIGNED(s) \
135   _dbus_assert (_DBUS_ALIGN_ADDRESS (((const DBusRealString*)s)->str, 8) == ((const DBusRealString*)s)->str)
136
137 /**
138  * Initializes a string. The maximum length may be _DBUS_INT_MAX for
139  * no maximum. The string starts life with zero length.
140  * The string must eventually be freed with _dbus_string_free().
141  *
142  * @todo the max length feature is useless, because it looks
143  * to the app like out of memory, and the app might try
144  * to "recover" - but recovery in this case is impossible,
145  * as we can't ever "get more memory" - so should delete the
146  * max length feature I think.
147  *
148  * @todo we could make this init routine not alloc any memory and
149  * return void, would simplify a lot of code, however it might
150  * complexify things elsewhere because _dbus_string_get_data()
151  * etc. could suddenly fail as they'd need to alloc new memory.
152  * 
153  * @param str memory to hold the string
154  * @param max_length the maximum size of the string
155  * @returns #TRUE on success
156  */
157 dbus_bool_t
158 _dbus_string_init (DBusString *str,
159                    int         max_length)
160 {
161   DBusRealString *real;
162   
163   _dbus_assert (str != NULL);
164   _dbus_assert (max_length >= 0);
165
166   _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
167   
168   real = (DBusRealString*) str;
169
170   /* It's very important not to touch anything
171    * other than real->str if we're going to fail,
172    * since we also use this function to reset
173    * an existing string, e.g. in _dbus_string_steal_data()
174    */
175   
176 #define INITIAL_ALLOC 2
177   
178   real->str = dbus_malloc (INITIAL_ALLOC);
179   if (real->str == NULL)
180     return FALSE;  
181   
182   real->allocated = INITIAL_ALLOC;
183   real->len = 0;
184   real->str[real->len] = '\0';
185   
186   real->max_length = max_length;
187   real->constant = FALSE;
188   real->locked = FALSE;
189   real->invalid = FALSE;
190
191   ASSERT_8_BYTE_ALIGNED (str);
192   
193   return TRUE;
194 }
195
196 /**
197  * Initializes a constant string. The value parameter is not copied
198  * (should be static), and the string may never be modified.
199  * It is safe but not necessary to call _dbus_string_free()
200  * on a const string.
201  * 
202  * @param str memory to use for the string
203  * @param value a string to be stored in str (not copied!!!)
204  */
205 void
206 _dbus_string_init_const (DBusString *str,
207                          const char *value)
208 {
209   _dbus_string_init_const_len (str, value,
210                                strlen (value));
211 }
212
213 /**
214  * Initializes a constant string with a length. The value parameter is
215  * not copied (should be static), and the string may never be
216  * modified.  It is safe but not necessary to call _dbus_string_free()
217  * on a const string.
218  * 
219  * @param str memory to use for the string
220  * @param value a string to be stored in str (not copied!!!)
221  * @param len the length to use
222  */
223 void
224 _dbus_string_init_const_len (DBusString *str,
225                              const char *value,
226                              int         len)
227 {
228   DBusRealString *real;
229   
230   _dbus_assert (str != NULL);
231   _dbus_assert (value != NULL);
232
233   real = (DBusRealString*) str;
234   
235   real->str = (char*) value;
236   real->len = len;
237   real->allocated = real->len;
238   real->max_length = real->len;
239   real->constant = TRUE;
240   real->invalid = FALSE;
241
242   /* We don't require const strings to be 8-byte aligned as the
243    * memory is coming from elsewhere.
244    */
245 }
246
247 /**
248  * Frees a string created by _dbus_string_init().
249  *
250  * @param str memory where the string is stored.
251  */
252 void
253 _dbus_string_free (DBusString *str)
254 {
255   DBusRealString *real = (DBusRealString*) str;
256   DBUS_GENERIC_STRING_PREAMBLE (real);
257   
258   if (real->constant)
259     return;
260   dbus_free (real->str);
261
262   real->invalid = TRUE;
263 }
264
265 /**
266  * Locks a string such that any attempts to change the string
267  * will result in aborting the program. Also, if the string
268  * is wasting a lot of memory (allocation is larger than what
269  * the string is really using), _dbus_string_lock() will realloc
270  * the string's data to "compact" it.
271  *
272  * @param str the string to lock.
273  */
274 void
275 _dbus_string_lock (DBusString *str)
276 {  
277   DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
278
279   real->locked = TRUE;
280
281   /* Try to realloc to avoid excess memory usage, since
282    * we know we won't change the string further
283    */
284 #define MAX_WASTE 24
285   if (real->allocated > (real->len + MAX_WASTE))
286     {
287       char *new_str;
288       int new_allocated;
289
290       new_allocated = real->len + 1;
291
292       new_str = dbus_realloc (real->str, new_allocated);
293       if (new_str != NULL)
294         {
295           real->str = new_str;
296           real->allocated = new_allocated;
297           ASSERT_8_BYTE_ALIGNED (str);
298         }
299     }
300 }
301
302 static dbus_bool_t
303 set_length (DBusRealString *real,
304             int             new_length)
305 {
306   /* Note, we are setting the length without nul termination */
307
308   /* exceeding max length is the same as failure to allocate memory */
309   if (new_length > real->max_length)
310     return FALSE;
311   
312   while (new_length >= real->allocated)
313     {
314       int new_allocated;
315       char *new_str;
316       
317       new_allocated = 2 + real->allocated * 2;
318       if (new_allocated < real->allocated)
319         return FALSE; /* overflow */
320         
321       new_str = dbus_realloc (real->str, new_allocated);
322       if (new_str == NULL)
323         return FALSE;
324
325       real->str = new_str;
326       real->allocated = new_allocated;
327
328       ASSERT_8_BYTE_ALIGNED (real);
329     }
330
331   real->len = new_length;
332   real->str[real->len] = '\0';
333
334   return TRUE;
335 }
336
337 static dbus_bool_t
338 open_gap (int             len,
339           DBusRealString *dest,
340           int             insert_at)
341 {
342   if (len == 0)
343     return TRUE;
344
345   if (!set_length (dest, dest->len + len))
346     return FALSE;
347
348   memmove (dest->str + insert_at + len, 
349            dest->str + insert_at,
350            dest->len - len - insert_at);
351
352   return TRUE;
353 }
354
355 /**
356  * Gets the raw character buffer from the string.  The returned buffer
357  * will be nul-terminated, but note that strings may contain binary
358  * data so there may be extra nul characters prior to the termination.
359  * This function should be little-used, extend DBusString or add
360  * stuff to dbus-sysdeps.c instead. It's an error to use this
361  * function on a const string.
362  *
363  * @param str the string
364  * @param data_return place to store the returned data
365  */
366 void
367 _dbus_string_get_data (DBusString        *str,
368                        char             **data_return)
369 {
370   DBUS_STRING_PREAMBLE (str);
371   _dbus_assert (data_return != NULL);
372   
373   *data_return = real->str;
374 }
375
376 /**
377  * Gets the raw character buffer from a const string. 
378  *
379  * @param str the string
380  * @param data_return location to store returned data
381  */
382 void
383 _dbus_string_get_const_data (const DBusString  *str,
384                              const char       **data_return)
385 {
386   DBUS_CONST_STRING_PREAMBLE (str);
387   _dbus_assert (data_return != NULL);
388   
389   *data_return = real->str;
390 }
391
392 /**
393  * Gets a sub-portion of the raw character buffer from the
394  * string. The "len" field is required simply for error
395  * checking, to be sure you don't try to use more
396  * string than exists. The nul termination of the
397  * returned buffer remains at the end of the entire
398  * string, not at start + len.
399  *
400  * @param str the string
401  * @param data_return location to return the buffer
402  * @param start byte offset to return
403  * @param len length of segment to return
404  */
405 void
406 _dbus_string_get_data_len (DBusString *str,
407                            char      **data_return,
408                            int         start,
409                            int         len)
410 {
411   DBUS_STRING_PREAMBLE (str);
412   _dbus_assert (data_return != NULL);
413   _dbus_assert (start >= 0);
414   _dbus_assert (len >= 0);
415   _dbus_assert ((start + len) <= real->len);
416   
417   *data_return = real->str + start;
418 }
419
420 /**
421  * const version of _dbus_string_get_data_len().
422  *
423  * @param str the string
424  * @param data_return location to return the buffer
425  * @param start byte offset to return
426  * @param len length of segment to return
427  */
428 void
429 _dbus_string_get_const_data_len (const DBusString  *str,
430                                  const char       **data_return,
431                                  int                start,
432                                  int                len)
433 {
434   DBUS_CONST_STRING_PREAMBLE (str);
435   _dbus_assert (data_return != NULL);
436   _dbus_assert (start >= 0);
437   _dbus_assert (len >= 0);
438   _dbus_assert ((start + len) <= real->len);
439   
440   *data_return = real->str + start;
441 }
442
443 /**
444  * Sets the value of the byte at the given position.
445  *
446  * @param str the string
447  * @param i the position
448  * @param byte the new value
449  */
450 void
451 _dbus_string_set_byte (DBusString    *str,
452                        int            i,
453                        unsigned char  byte)
454 {
455   DBUS_STRING_PREAMBLE (str);
456   _dbus_assert (i < real->len);
457
458   real->str[i] = byte;
459 }
460
461 /**
462  * Gets the byte at the given position.
463  *
464  * @param str the string
465  * @param start the position
466  * @returns the byte at that position
467  */
468 unsigned char
469 _dbus_string_get_byte (const DBusString  *str,
470                        int                start)
471 {
472   DBUS_CONST_STRING_PREAMBLE (str);
473   _dbus_assert (start < real->len);
474
475   return real->str[start];
476 }
477
478 /**
479  * Inserts the given byte at the given position.
480  *
481  * @param str the string
482  * @param i the position
483  * @param byte the value to insert
484  * @returns #TRUE on success
485  */
486 dbus_bool_t
487 _dbus_string_insert_byte (DBusString   *str,
488                           int           i,
489                           unsigned char byte)
490 {
491   DBUS_STRING_PREAMBLE (str);
492   _dbus_assert (i <= real->len);
493
494   if (!open_gap (1, real, i))
495     return FALSE;
496   
497   real->str[i] = byte;
498
499   return TRUE;
500 }
501
502 /**
503  * Like _dbus_string_get_data(), but removes the
504  * gotten data from the original string. The caller
505  * must free the data returned. This function may
506  * fail due to lack of memory, and return #FALSE.
507  *
508  * @param str the string
509  * @param data_return location to return the buffer
510  * @returns #TRUE on success
511  */
512 dbus_bool_t
513 _dbus_string_steal_data (DBusString        *str,
514                          char             **data_return)
515 {
516   DBUS_STRING_PREAMBLE (str);
517   _dbus_assert (data_return != NULL);
518   
519   *data_return = real->str;
520
521   /* reset the string */
522   if (!_dbus_string_init (str, real->max_length))
523     {
524       /* hrm, put it back then */
525       real->str = *data_return;
526       *data_return = NULL;
527       return FALSE;
528     }
529
530   return TRUE;
531 }
532
533 /**
534  * Like _dbus_string_get_data_len(), but removes the gotten data from
535  * the original string. The caller must free the data returned. This
536  * function may fail due to lack of memory, and return #FALSE.
537  * The returned string is nul-terminated and has length len.
538  *
539  * @param str the string
540  * @param data_return location to return the buffer
541  * @param start the start of segment to steal
542  * @param len the length of segment to steal
543  * @returns #TRUE on success
544  */
545 dbus_bool_t
546 _dbus_string_steal_data_len (DBusString        *str,
547                              char             **data_return,
548                              int                start,
549                              int                len)
550 {
551   DBusString dest;
552   
553   DBUS_STRING_PREAMBLE (str);
554   _dbus_assert (data_return != NULL);
555   _dbus_assert (start >= 0);
556   _dbus_assert (len >= 0);
557   _dbus_assert ((start + len) <= real->len);
558
559   if (!_dbus_string_init (&dest, real->max_length))
560     return FALSE;
561
562   if (!_dbus_string_move_len (str, start, len, &dest, 0))
563     {
564       _dbus_string_free (&dest);
565       return FALSE;
566     }
567   
568   if (!_dbus_string_steal_data (&dest, data_return))
569     {
570       _dbus_string_free (&dest);
571       return FALSE;
572     }
573
574   _dbus_string_free (&dest);
575   return TRUE;
576 }
577
578 /**
579  * Gets the length of a string (not including nul termination).
580  *
581  * @returns the length.
582  */
583 int
584 _dbus_string_get_length (const DBusString  *str)
585 {
586   DBUS_CONST_STRING_PREAMBLE (str);
587   
588   return real->len;
589 }
590
591 /**
592  * Makes a string longer by the given number of bytes.  Checks whether
593  * adding additional_length to the current length would overflow an
594  * integer, and checks for exceeding a string's max length.
595  * The new bytes are not initialized, other than nul-terminating
596  * the end of the string. The uninitialized bytes may contain
597  * unexpected nul bytes or other junk.
598  *
599  * @param str a string
600  * @param additional_length length to add to the string.
601  * @returns #TRUE on success.
602  */
603 dbus_bool_t
604 _dbus_string_lengthen (DBusString *str,
605                        int         additional_length)
606 {
607   DBUS_STRING_PREAMBLE (str);  
608   _dbus_assert (additional_length >= 0);
609   
610   if ((real->len + additional_length) < real->len)
611     return FALSE; /* overflow */
612   
613   return set_length (real,
614                      real->len + additional_length);
615 }
616
617 /**
618  * Makes a string shorter by the given number of bytes.
619  *
620  * @param str a string
621  * @param length_to_remove length to remove from the string.
622  */
623 void
624 _dbus_string_shorten (DBusString *str,
625                       int         length_to_remove)
626 {
627   DBUS_STRING_PREAMBLE (str);
628   _dbus_assert (length_to_remove >= 0);
629   _dbus_assert (length_to_remove <= real->len);
630
631   set_length (real,
632               real->len - length_to_remove);
633 }
634
635 /**
636  * Sets the length of a string. Can be used to truncate or lengthen
637  * the string. If the string is lengthened, the function may fail and
638  * return #FALSE. Newly-added bytes are not initialized, as with
639  * _dbus_string_lengthen().
640  *
641  * @param str a string
642  * @param length new length of the string.
643  * @returns #FALSE on failure.
644  */
645 dbus_bool_t
646 _dbus_string_set_length (DBusString *str,
647                          int         length)
648 {
649   DBUS_STRING_PREAMBLE (str);
650   _dbus_assert (length >= 0);
651
652   return set_length (real, length);
653 }
654
655 /**
656  * Align the length of a string to a specific alignment (typically 4 or 8)
657  * by appending nul bytes to the string.
658  *
659  * @param str a string
660  * @param alignment the alignment
661  * @returns #FALSE if no memory
662  */
663 dbus_bool_t
664 _dbus_string_align_length (DBusString *str,
665                            int         alignment)
666 {
667   int new_len;
668   int delta;
669   DBUS_STRING_PREAMBLE (str);
670   _dbus_assert (alignment >= 1);
671   _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
672
673   new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
674
675   delta = new_len - real->len;
676   _dbus_assert (delta >= 0);
677
678   if (delta == 0)
679     return TRUE;
680
681   if (!set_length (real, new_len))
682     return FALSE;
683
684   memset (real->str + (new_len - delta),
685           '\0', delta);
686
687   return TRUE;
688 }
689
690 static dbus_bool_t
691 append (DBusRealString *real,
692         const char     *buffer,
693         int             buffer_len)
694 {
695   if (buffer_len == 0)
696     return TRUE;
697
698   if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
699     return FALSE;
700
701   memcpy (real->str + (real->len - buffer_len),
702           buffer,
703           buffer_len);
704
705   return TRUE;
706 }
707
708 /**
709  * Appends a nul-terminated C-style string to a DBusString.
710  *
711  * @param str the DBusString
712  * @param buffer the nul-terminated characters to append
713  * @returns #FALSE if not enough memory.
714  */
715 dbus_bool_t
716 _dbus_string_append (DBusString *str,
717                      const char *buffer)
718 {
719   int buffer_len;
720   
721   DBUS_STRING_PREAMBLE (str);
722   _dbus_assert (buffer != NULL);
723   
724   buffer_len = strlen (buffer);
725
726   return append (real, buffer, buffer_len);
727 }
728
729 /**
730  * Appends block of bytes with the given length to a DBusString.
731  *
732  * @param str the DBusString
733  * @param buffer the bytes to append
734  * @param len the number of bytes to append
735  * @returns #FALSE if not enough memory.
736  */
737 dbus_bool_t
738 _dbus_string_append_len (DBusString *str,
739                          const char *buffer,
740                          int         len)
741 {
742   DBUS_STRING_PREAMBLE (str);
743   _dbus_assert (buffer != NULL);
744   _dbus_assert (len >= 0);
745
746   return append (real, buffer, len);
747 }
748
749 /**
750  * Appends a single byte to the string, returning #FALSE
751  * if not enough memory.
752  *
753  * @param str the string
754  * @param byte the byte to append
755  * @returns #TRUE on success
756  */
757 dbus_bool_t
758 _dbus_string_append_byte (DBusString    *str,
759                           unsigned char  byte)
760 {
761   DBUS_STRING_PREAMBLE (str);
762
763   if (!set_length (real, real->len + 1))
764     return FALSE;
765
766   real->str[real->len-1] = byte;
767
768   return TRUE;
769 }
770
771 /**
772  * Appends a single Unicode character, encoding the character
773  * in UTF-8 format.
774  *
775  * @param str the string
776  * @param ch the Unicode character
777  */
778 dbus_bool_t
779 _dbus_string_append_unichar (DBusString    *str,
780                              dbus_unichar_t ch)
781 {
782   int len;
783   int first;
784   int i;
785   char *out;
786   
787   DBUS_STRING_PREAMBLE (str);
788
789   /* this code is from GLib but is pretty standard I think */
790   
791   len = 0;
792   
793   if (ch < 0x80)
794     {
795       first = 0;
796       len = 1;
797     }
798   else if (ch < 0x800)
799     {
800       first = 0xc0;
801       len = 2;
802     }
803   else if (ch < 0x10000)
804     {
805       first = 0xe0;
806       len = 3;
807     }
808    else if (ch < 0x200000)
809     {
810       first = 0xf0;
811       len = 4;
812     }
813   else if (ch < 0x4000000)
814     {
815       first = 0xf8;
816       len = 5;
817     }
818   else
819     {
820       first = 0xfc;
821       len = 6;
822     }
823
824   if (!set_length (real, real->len + len))
825     return FALSE;
826
827   out = real->str + (real->len - len);
828   
829   for (i = len - 1; i > 0; --i)
830     {
831       out[i] = (ch & 0x3f) | 0x80;
832       ch >>= 6;
833     }
834   out[0] = ch | first;
835
836   return TRUE;
837 }
838
839 static void
840 delete (DBusRealString *real,
841         int             start,
842         int             len)
843 {
844   if (len == 0)
845     return;
846   
847   memmove (real->str + start, real->str + start + len, real->len - (start + len));
848   real->len -= len;
849   real->str[real->len] = '\0';
850 }
851
852 /**
853  * Deletes a segment of a DBusString with length len starting at
854  * start. (Hint: to clear an entire string, setting length to 0
855  * with _dbus_string_set_length() is easier.)
856  *
857  * @param str the DBusString
858  * @param start where to start deleting
859  * @param len the number of bytes to delete
860  */
861 void
862 _dbus_string_delete (DBusString       *str,
863                      int               start,
864                      int               len)
865 {
866   DBUS_STRING_PREAMBLE (str);
867   _dbus_assert (start >= 0);
868   _dbus_assert (len >= 0);
869   _dbus_assert ((start + len) <= real->len);
870   
871   delete (real, start, len);
872 }
873
874 static dbus_bool_t
875 copy (DBusRealString *source,
876       int             start,
877       int             len,
878       DBusRealString *dest,
879       int             insert_at)
880 {
881   if (len == 0)
882     return TRUE;
883
884   if (!open_gap (len, dest, insert_at))
885     return FALSE;
886   
887   memcpy (dest->str + insert_at,
888           source->str + start,
889           len);
890
891   return TRUE;
892 }
893
894 /**
895  * Checks assertions for two strings we're copying a segment between,
896  * and declares real_source/real_dest variables.
897  *
898  * @param source the source string
899  * @param start the starting offset
900  * @param dest the dest string
901  * @param insert_at where the copied segment is inserted
902  */
903 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at)       \
904   DBusRealString *real_source = (DBusRealString*) source;               \
905   DBusRealString *real_dest = (DBusRealString*) dest;                   \
906   _dbus_assert ((source) != (dest));                                    \
907   DBUS_GENERIC_STRING_PREAMBLE (real_source);                           \
908   DBUS_GENERIC_STRING_PREAMBLE (real_dest);                             \
909   _dbus_assert (!real_dest->constant);                                  \
910   _dbus_assert (!real_dest->locked);                                    \
911   _dbus_assert ((start) >= 0);                                          \
912   _dbus_assert ((start) <= real_source->len);                           \
913   _dbus_assert ((insert_at) >= 0);                                      \
914   _dbus_assert ((insert_at) <= real_dest->len)
915
916 /**
917  * Moves the end of one string into another string. Both strings
918  * must be initialized, valid strings.
919  *
920  * @param source the source string
921  * @param start where to chop off the source string
922  * @param dest the destination string
923  * @param insert_at where to move the chopped-off part of source string
924  * @returns #FALSE if not enough memory
925  */
926 dbus_bool_t
927 _dbus_string_move (DBusString       *source,
928                    int               start,
929                    DBusString       *dest,
930                    int               insert_at)
931 {
932   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
933   
934   if (!copy (real_source, start,
935              real_source->len - start,
936              real_dest,
937              insert_at))
938     return FALSE;
939
940   delete (real_source, start,
941           real_source->len - start);
942
943   return TRUE;
944 }
945
946 /**
947  * Like _dbus_string_move(), but does not delete the section
948  * of the source string that's copied to the dest string.
949  *
950  * @param source the source string
951  * @param start where to start copying the source string
952  * @param dest the destination string
953  * @param insert_at where to place the copied part of source string
954  * @returns #FALSE if not enough memory
955  */
956 dbus_bool_t
957 _dbus_string_copy (const DBusString *source,
958                    int               start,
959                    DBusString       *dest,
960                    int               insert_at)
961 {
962   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
963
964   return copy (real_source, start,
965                real_source->len - start,
966                real_dest,
967                insert_at);
968 }
969
970 /**
971  * Like _dbus_string_move(), but can move a segment from
972  * the middle of the source string.
973  * 
974  * @param source the source string
975  * @param start first byte of source string to move
976  * @param len length of segment to move
977  * @param dest the destination string
978  * @param insert_at where to move the bytes from the source string
979  * @returns #FALSE if not enough memory
980  */
981 dbus_bool_t
982 _dbus_string_move_len (DBusString       *source,
983                        int               start,
984                        int               len,
985                        DBusString       *dest,
986                        int               insert_at)
987
988 {
989   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
990   _dbus_assert (len >= 0);
991   _dbus_assert ((start + len) <= real_source->len);
992
993   if (!copy (real_source, start, len,
994              real_dest,
995              insert_at))
996     return FALSE;
997
998   delete (real_source, start,
999           len);
1000
1001   return TRUE;
1002 }
1003
1004 /**
1005  * Like _dbus_string_copy(), but can copy a segment from the middle of
1006  * the source string.
1007  *
1008  * @param source the source string
1009  * @param start where to start copying the source string
1010  * @param len length of segment to copy
1011  * @param dest the destination string
1012  * @param insert_at where to place the copied segment of source string
1013  * @returns #FALSE if not enough memory
1014  */
1015 dbus_bool_t
1016 _dbus_string_copy_len (const DBusString *source,
1017                        int               start,
1018                        int               len,
1019                        DBusString       *dest,
1020                        int               insert_at)
1021 {
1022   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1023   _dbus_assert (len >= 0);
1024   _dbus_assert ((start + len) <= real_source->len);
1025   
1026   return copy (real_source, start, len,
1027                real_dest,
1028                insert_at);
1029 }
1030
1031 /**
1032  * Replaces a segment of dest string with a segment of source string.
1033  *
1034  * @todo optimize the case where the two lengths are the same, and
1035  * avoid memmoving the data in the trailing part of the string twice.
1036  * 
1037  * @param source the source string
1038  * @param start where to start copying the source string
1039  * @param len length of segment to copy
1040  * @param dest the destination string
1041  * @param replace_at start of segment of dest string to replace
1042  * @param replace_len length of segment of dest string to replace
1043  * @returns #FALSE if not enough memory
1044  *
1045  */
1046 dbus_bool_t
1047 _dbus_string_replace_len (const DBusString *source,
1048                           int               start,
1049                           int               len,
1050                           DBusString       *dest,
1051                           int               replace_at,
1052                           int               replace_len)
1053 {
1054   DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1055   _dbus_assert (len >= 0);
1056   _dbus_assert ((start + len) <= real_source->len);
1057   _dbus_assert (replace_at >= 0);
1058   _dbus_assert ((replace_at + replace_len) <= real_dest->len);
1059
1060   if (!copy (real_source, start, len,
1061              real_dest, replace_at))
1062     return FALSE;
1063
1064   delete (real_dest, replace_at + len, replace_len);
1065
1066   return TRUE;
1067 }
1068
1069 /* Unicode macros from GLib */
1070
1071 /** computes length and mask of a unicode character
1072  * @param Char the char
1073  * @param Mask the mask variable to assign to
1074  * @param Len the length variable to assign to
1075  */
1076 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
1077   if (Char < 128)                                                             \
1078     {                                                                         \
1079       Len = 1;                                                                \
1080       Mask = 0x7f;                                                            \
1081     }                                                                         \
1082   else if ((Char & 0xe0) == 0xc0)                                             \
1083     {                                                                         \
1084       Len = 2;                                                                \
1085       Mask = 0x1f;                                                            \
1086     }                                                                         \
1087   else if ((Char & 0xf0) == 0xe0)                                             \
1088     {                                                                         \
1089       Len = 3;                                                                \
1090       Mask = 0x0f;                                                            \
1091     }                                                                         \
1092   else if ((Char & 0xf8) == 0xf0)                                             \
1093     {                                                                         \
1094       Len = 4;                                                                \
1095       Mask = 0x07;                                                            \
1096     }                                                                         \
1097   else if ((Char & 0xfc) == 0xf8)                                             \
1098     {                                                                         \
1099       Len = 5;                                                                \
1100       Mask = 0x03;                                                            \
1101     }                                                                         \
1102   else if ((Char & 0xfe) == 0xfc)                                             \
1103     {                                                                         \
1104       Len = 6;                                                                \
1105       Mask = 0x01;                                                            \
1106     }                                                                         \
1107   else                                                                        \
1108     Len = -1;
1109
1110 /**
1111  * computes length of a unicode character in UTF-8
1112  * @param Char the char
1113  */
1114 #define UTF8_LENGTH(Char)              \
1115   ((Char) < 0x80 ? 1 :                 \
1116    ((Char) < 0x800 ? 2 :               \
1117     ((Char) < 0x10000 ? 3 :            \
1118      ((Char) < 0x200000 ? 4 :          \
1119       ((Char) < 0x4000000 ? 5 : 6)))))
1120    
1121 /**
1122  * Gets a UTF-8 value.
1123  *
1124  * @param Result variable for extracted unicode char.
1125  * @param Chars the bytes to decode
1126  * @param Count counter variable
1127  * @param Mask mask for this char
1128  * @param Len length for this char in bytes
1129  */
1130 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
1131   (Result) = (Chars)[0] & (Mask);                                             \
1132   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
1133     {                                                                         \
1134       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
1135         {                                                                     \
1136           (Result) = -1;                                                      \
1137           break;                                                              \
1138         }                                                                     \
1139       (Result) <<= 6;                                                         \
1140       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
1141     }
1142
1143 /**
1144  * Check whether a unicode char is in a valid range.
1145  *
1146  * @param Char the character
1147  */
1148 #define UNICODE_VALID(Char)                   \
1149     ((Char) < 0x110000 &&                     \
1150      ((Char) < 0xD800 || (Char) >= 0xE000) && \
1151      (Char) != 0xFFFE && (Char) != 0xFFFF)   
1152
1153 /**
1154  * Gets a unicode character from a UTF-8 string. Does no validation;
1155  * you must verify that the string is valid UTF-8 in advance and must
1156  * pass in the start of a character.
1157  *
1158  * @param str the string
1159  * @param start the start of the UTF-8 character.
1160  * @param ch_return location to return the character
1161  * @param end_return location to return the byte index of next character
1162  * @returns #TRUE on success, #FALSE otherwise.
1163  */
1164 void
1165 _dbus_string_get_unichar (const DBusString *str,
1166                           int               start,
1167                           dbus_unichar_t   *ch_return,
1168                           int              *end_return)
1169 {
1170   int i, mask, len;
1171   dbus_unichar_t result;
1172   unsigned char c;
1173   unsigned char *p;
1174   DBUS_CONST_STRING_PREAMBLE (str);
1175
1176   if (ch_return)
1177     *ch_return = 0;
1178   if (end_return)
1179     *end_return = real->len;
1180   
1181   mask = 0;
1182   p = real->str + start;
1183   c = *p;
1184   
1185   UTF8_COMPUTE (c, mask, len);
1186   if (len == -1)
1187     return;
1188   UTF8_GET (result, p, i, mask, len);
1189
1190   if (result == (dbus_unichar_t)-1)
1191     return;
1192
1193   if (ch_return)
1194     *ch_return = result;
1195   if (end_return)
1196     *end_return = start + len;
1197 }
1198
1199 /**
1200  * Finds the given substring in the string,
1201  * returning #TRUE and filling in the byte index
1202  * where the substring was found, if it was found.
1203  * Returns #FALSE if the substring wasn't found.
1204  * Sets *start to the length of the string if the substring
1205  * is not found.
1206  *
1207  * @param str the string
1208  * @param start where to start looking
1209  * @param substr the substring
1210  * @param found return location for where it was found, or #NULL
1211  * @returns #TRUE if found
1212  */
1213 dbus_bool_t
1214 _dbus_string_find (const DBusString *str,
1215                    int               start,
1216                    const char       *substr,
1217                    int              *found)
1218 {
1219   int i;
1220   DBUS_CONST_STRING_PREAMBLE (str);
1221   _dbus_assert (substr != NULL);
1222   _dbus_assert (start <= real->len);
1223   
1224   /* we always "find" an empty string */
1225   if (*substr == '\0')
1226     {
1227       if (found)
1228         *found = 0;
1229       return TRUE;
1230     }
1231   
1232   i = start;
1233   while (i < real->len)
1234     {
1235       if (real->str[i] == substr[0])
1236         {
1237           int j = i + 1;
1238           
1239           while (j < real->len)
1240             {
1241               if (substr[j - i] == '\0')
1242                 break;
1243               else if (real->str[j] != substr[j - i])
1244                 break;
1245               
1246               ++j;
1247             }
1248
1249           if (substr[j - i] == '\0')
1250             {
1251               if (found)
1252                 *found = i;
1253               return TRUE;
1254             }
1255         }
1256       
1257       ++i;
1258     }
1259
1260   if (found)
1261     *found = real->len;
1262   
1263   return FALSE;
1264 }
1265
1266 /**
1267  * Finds the given substring in the string,
1268  * up to a certain position,
1269  * returning #TRUE and filling in the byte index
1270  * where the substring was found, if it was found.
1271  * Returns #FALSE if the substring wasn't found.
1272  * Sets *start to the length of the string if the substring
1273  * is not found.
1274  *
1275  * @param str the string
1276  * @param start where to start looking
1277  * @param end where to stop looking
1278  * @param substr the substring
1279  * @param found return location for where it was found, or #NULL
1280  * @returns #TRUE if found
1281  */
1282 dbus_bool_t
1283 _dbus_string_find_to (const DBusString *str,
1284                       int               start,
1285                       int               end,
1286                       const char       *substr,
1287                       int              *found)
1288 {
1289   int i;
1290   DBUS_CONST_STRING_PREAMBLE (str);
1291   _dbus_assert (substr != NULL);
1292   _dbus_assert (start <= real->len);
1293   _dbus_assert (end <= real->len);
1294   _dbus_assert (start < end);
1295
1296   /* we always "find" an empty string */
1297   if (*substr == '\0')
1298     {
1299       if (found)
1300         *found = 0;
1301       return TRUE;
1302     }
1303
1304   i = start;
1305   while (i < real->len && i < end)
1306     {
1307       if (real->str[i] == substr[0])
1308         {
1309           int j = i + 1;
1310           
1311           while (j < real->len && j < end)
1312             {
1313               if (substr[j - i] == '\0')
1314                 break;
1315               else if (real->str[j] != substr[j - i])
1316                 break;
1317               
1318               ++j;
1319             }
1320
1321           if (substr[j - i] == '\0')
1322             {
1323               if (found)
1324                 *found = i;
1325               return TRUE;
1326             }
1327         }
1328       
1329       ++i;
1330     }
1331
1332   if (found)
1333     *found = end;
1334   
1335   return FALSE;  
1336 }
1337
1338 /**
1339  * Finds a blank (space or tab) in the string. Returns #TRUE
1340  * if found, #FALSE otherwise. If a blank is not found sets
1341  * *found to the length of the string.
1342  *
1343  * @param str the string
1344  * @param start byte index to start looking
1345  * @param found place to store the location of the first blank
1346  * @returns #TRUE if a blank was found
1347  */
1348 dbus_bool_t
1349 _dbus_string_find_blank (const DBusString *str,
1350                          int               start,
1351                          int              *found)
1352 {
1353   int i;
1354   DBUS_CONST_STRING_PREAMBLE (str);
1355   _dbus_assert (start <= real->len);
1356   
1357   i = start;
1358   while (i < real->len)
1359     {
1360       if (real->str[i] == ' ' ||
1361           real->str[i] == '\t')
1362         {
1363           if (found)
1364             *found = i;
1365           return TRUE;
1366         }
1367       
1368       ++i;
1369     }
1370
1371   if (found)
1372     *found = real->len;
1373   
1374   return FALSE;
1375 }
1376
1377 /**
1378  * Skips blanks from start, storing the first non-blank in *end
1379  *
1380  * @param str the string
1381  * @param start where to start
1382  * @param end where to store the first non-blank byte index
1383  */
1384 void
1385 _dbus_string_skip_blank (const DBusString *str,
1386                          int               start,
1387                          int              *end)
1388 {
1389   int i;
1390   DBUS_CONST_STRING_PREAMBLE (str);
1391   _dbus_assert (start <= real->len);
1392   
1393   i = start;
1394   while (i < real->len)
1395     {
1396       if (!(real->str[i] == ' ' ||
1397             real->str[i] == '\t'))
1398         break;
1399       
1400       ++i;
1401     }
1402
1403   _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1404                                     real->str[i] == '\t'));
1405   
1406   if (end)
1407     *end = i;
1408 }
1409
1410 /**
1411  * Tests two DBusString for equality.
1412  *
1413  * @param a first string
1414  * @param b second string
1415  * @returns #TRUE if equal
1416  */
1417 dbus_bool_t
1418 _dbus_string_equal (const DBusString *a,
1419                     const DBusString *b)
1420 {
1421   const unsigned char *ap;
1422   const unsigned char *bp;
1423   const unsigned char *a_end;
1424   const DBusRealString *real_a = (const DBusRealString*) a;
1425   const DBusRealString *real_b = (const DBusRealString*) b;
1426   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1427   DBUS_GENERIC_STRING_PREAMBLE (real_b);
1428
1429   if (real_a->len != real_b->len)
1430     return FALSE;
1431
1432   ap = real_a->str;
1433   bp = real_b->str;
1434   a_end = real_a->str + real_a->len;
1435   while (ap != a_end)
1436     {
1437       if (*ap != *bp)
1438         return FALSE;
1439       
1440       ++ap;
1441       ++bp;
1442     }
1443
1444   return TRUE;
1445 }
1446
1447 /**
1448  * Checks whether a string is equal to a C string.
1449  *
1450  * @param a the string
1451  * @param c_str the C string
1452  * @returns #TRUE if equal
1453  */
1454 dbus_bool_t
1455 _dbus_string_equal_c_str (const DBusString *a,
1456                           const char       *c_str)
1457 {
1458   const unsigned char *ap;
1459   const unsigned char *bp;
1460   const unsigned char *a_end;
1461   const DBusRealString *real_a = (const DBusRealString*) a;
1462   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1463
1464   ap = real_a->str;
1465   bp = (const unsigned char*) c_str;
1466   a_end = real_a->str + real_a->len;
1467   while (ap != a_end && *bp)
1468     {
1469       if (*ap != *bp)
1470         return FALSE;
1471       
1472       ++ap;
1473       ++bp;
1474     }
1475
1476   if (*ap && *bp == '\0')
1477     return FALSE;
1478   else if (ap == a_end && *bp)
1479     return FALSE;
1480   
1481   return TRUE;
1482 }
1483
1484 /**
1485  * Checks whether a string starts with the given C string.
1486  *
1487  * @param a the string
1488  * @param c_str the C string
1489  * @returns #TRUE if string starts with it
1490  */
1491 dbus_bool_t
1492 _dbus_string_starts_with_c_str (const DBusString *a,
1493                                 const char       *c_str)
1494 {
1495   const unsigned char *ap;
1496   const unsigned char *bp;
1497   const unsigned char *a_end;
1498   const DBusRealString *real_a = (const DBusRealString*) a;
1499   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1500
1501   ap = real_a->str;
1502   bp = (const unsigned char*) c_str;
1503   a_end = real_a->str + real_a->len;
1504   while (ap != a_end && *bp)
1505     {
1506       if (*ap != *bp)
1507         return FALSE;
1508       
1509       ++ap;
1510       ++bp;
1511     }
1512
1513   if (*bp == '\0')
1514     return TRUE;
1515   else
1516     return FALSE;
1517 }
1518
1519 /**
1520  * Returns whether a string ends with the given suffix
1521  *
1522  * @param a the string
1523  * @param c_str the C-style string
1524  * @returns #TRUE if the string ends with the suffix
1525  */
1526 dbus_bool_t
1527 _dbus_string_ends_with_c_str (const DBusString *a,
1528                               const char       *c_str)
1529 {
1530   const unsigned char *ap;
1531   const unsigned char *bp;
1532   const unsigned char *a_end;
1533   int c_str_len;
1534   const DBusRealString *real_a = (const DBusRealString*) a;
1535   DBUS_GENERIC_STRING_PREAMBLE (real_a);
1536
1537   c_str_len = strlen (c_str);
1538   if (real_a->len < c_str_len)
1539     return FALSE;
1540   
1541   ap = real_a->str + (real_a->len - c_str_len);
1542   bp = (const unsigned char*) c_str;
1543   a_end = real_a->str + real_a->len;
1544   while (ap != a_end)
1545     {
1546       if (*ap != *bp)
1547         return FALSE;
1548       
1549       ++ap;
1550       ++bp;
1551     }
1552
1553   _dbus_assert (*ap == '\0');
1554   _dbus_assert (*bp == '\0');
1555   
1556   return TRUE;
1557 }
1558
1559 static const signed char base64_table[] = {
1560   /* 0 */ 'A',
1561   /* 1 */ 'B',
1562   /* 2 */ 'C',
1563   /* 3 */ 'D',
1564   /* 4 */ 'E',
1565   /* 5 */ 'F',
1566   /* 6 */ 'G',
1567   /* 7 */ 'H',
1568   /* 8 */ 'I',
1569   /* 9 */ 'J',
1570   /* 10 */ 'K',
1571   /* 11 */ 'L',
1572   /* 12 */ 'M',
1573   /* 13 */ 'N',
1574   /* 14 */ 'O',
1575   /* 15 */ 'P',
1576   /* 16 */ 'Q',
1577   /* 17 */ 'R',
1578   /* 18 */ 'S',
1579   /* 19 */ 'T',
1580   /* 20 */ 'U',
1581   /* 21 */ 'V',
1582   /* 22 */ 'W',
1583   /* 23 */ 'X',
1584   /* 24 */ 'Y',
1585   /* 25 */ 'Z',
1586   /* 26 */ 'a',
1587   /* 27 */ 'b',
1588   /* 28 */ 'c',
1589   /* 29 */ 'd',
1590   /* 30 */ 'e',
1591   /* 31 */ 'f',
1592   /* 32 */ 'g',
1593   /* 33 */ 'h',
1594   /* 34 */ 'i',
1595   /* 35 */ 'j',
1596   /* 36 */ 'k',
1597   /* 37 */ 'l',
1598   /* 38 */ 'm',
1599   /* 39 */ 'n',
1600   /* 40 */ 'o',
1601   /* 41 */ 'p',
1602   /* 42 */ 'q',
1603   /* 43 */ 'r',
1604   /* 44 */ 's',
1605   /* 45 */ 't',
1606   /* 46 */ 'u',
1607   /* 47 */ 'v',
1608   /* 48 */ 'w',
1609   /* 49 */ 'x',
1610   /* 50 */ 'y',
1611   /* 51 */ 'z',
1612   /* 52 */ '0',
1613   /* 53 */ '1',
1614   /* 54 */ '2',
1615   /* 55 */ '3',
1616   /* 56 */ '4',
1617   /* 57 */ '5',
1618   /* 58 */ '6',
1619   /* 59 */ '7',
1620   /* 60 */ '8',
1621   /* 61 */ '9',
1622   /* 62 */ '+',
1623   /* 63 */ '/'
1624 };
1625
1626 /** The minimum char that's a valid char in Base64-encoded text */
1627 #define UNBASE64_MIN_CHAR (43)
1628 /** The maximum char that's a valid char in Base64-encoded text */
1629 #define UNBASE64_MAX_CHAR (122)
1630 /** Must subtract this from a char's integer value before offsetting
1631  * into unbase64_table
1632  */
1633 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1634 static const signed char unbase64_table[] = {
1635   /* 43 + */ 62,
1636   /* 44 , */ -1,
1637   /* 45 - */ -1,
1638   /* 46 . */ -1,
1639   /* 47 / */ 63,
1640   /* 48 0 */ 52,
1641   /* 49 1 */ 53,
1642   /* 50 2 */ 54,
1643   /* 51 3 */ 55,
1644   /* 52 4 */ 56,
1645   /* 53 5 */ 57,
1646   /* 54 6 */ 58,
1647   /* 55 7 */ 59,
1648   /* 56 8 */ 60,
1649   /* 57 9 */ 61,
1650   /* 58 : */ -1,
1651   /* 59 ; */ -1,
1652   /* 60 < */ -1,
1653   /* 61 = */ -1,
1654   /* 62 > */ -1,
1655   /* 63 ? */ -1,
1656   /* 64 @ */ -1,
1657   /* 65 A */ 0,
1658   /* 66 B */ 1,
1659   /* 67 C */ 2,
1660   /* 68 D */ 3,
1661   /* 69 E */ 4,
1662   /* 70 F */ 5,
1663   /* 71 G */ 6,
1664   /* 72 H */ 7,
1665   /* 73 I */ 8,
1666   /* 74 J */ 9,
1667   /* 75 K */ 10,
1668   /* 76 L */ 11,
1669   /* 77 M */ 12,
1670   /* 78 N */ 13,
1671   /* 79 O */ 14,
1672   /* 80 P */ 15,
1673   /* 81 Q */ 16,
1674   /* 82 R */ 17,
1675   /* 83 S */ 18,
1676   /* 84 T */ 19,
1677   /* 85 U */ 20,
1678   /* 86 V */ 21,
1679   /* 87 W */ 22,
1680   /* 88 X */ 23,
1681   /* 89 Y */ 24,
1682   /* 90 Z */ 25,
1683   /* 91 [ */ -1,
1684   /* 92 \ */ -1,
1685   /* 93 ] */ -1,
1686   /* 94 ^ */ -1,
1687   /* 95 _ */ -1,
1688   /* 96 ` */ -1,
1689   /* 97 a */ 26,
1690   /* 98 b */ 27,
1691   /* 99 c */ 28,
1692   /* 100 d */ 29,
1693   /* 101 e */ 30,
1694   /* 102 f */ 31,
1695   /* 103 g */ 32,
1696   /* 104 h */ 33,
1697   /* 105 i */ 34,
1698   /* 106 j */ 35,
1699   /* 107 k */ 36,
1700   /* 108 l */ 37,
1701   /* 109 m */ 38,
1702   /* 110 n */ 39,
1703   /* 111 o */ 40,
1704   /* 112 p */ 41,
1705   /* 113 q */ 42,
1706   /* 114 r */ 43,
1707   /* 115 s */ 44,
1708   /* 116 t */ 45,
1709   /* 117 u */ 46,
1710   /* 118 v */ 47,
1711   /* 119 w */ 48,
1712   /* 120 x */ 49,
1713   /* 121 y */ 50,
1714   /* 122 z */ 51
1715 };
1716
1717 /**
1718  * Encodes a string using Base64, as documented in RFC 2045.
1719  *
1720  * @param source the string to encode
1721  * @param start byte index to start encoding
1722  * @param dest string where encoded data should be placed
1723  * @param insert_at where to place encoded data
1724  * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
1725  */
1726 dbus_bool_t
1727 _dbus_string_base64_encode (const DBusString *source,
1728                             int               start,
1729                             DBusString       *dest,
1730                             int               insert_at)
1731 {
1732   int source_len;
1733   int dest_len;
1734   const unsigned char *s;
1735   unsigned char *d;
1736   const unsigned char *triplet_end;
1737   const unsigned char *final_end;
1738   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);  
1739   _dbus_assert (source != dest);
1740   
1741   /* For each 24 bits (3 bytes) of input, we have 4 chars of
1742    * output.
1743    */
1744   source_len = real_source->len - start;
1745   dest_len = (source_len / 3) * 4;
1746   if (source_len % 3 != 0)
1747     dest_len += 4;
1748
1749   if (source_len == 0)
1750     return TRUE;
1751   
1752   if (!open_gap (dest_len, real_dest, insert_at))
1753     return FALSE;
1754
1755   d = real_dest->str + insert_at;
1756   s = real_source->str + start;
1757   final_end = real_source->str + (start + source_len);
1758   triplet_end = final_end - (source_len % 3);
1759   _dbus_assert (triplet_end <= final_end);
1760   _dbus_assert ((final_end - triplet_end) < 3);
1761
1762 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
1763 #define SIX_BITS_MASK (0x3f)
1764   _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
1765   
1766   while (s != triplet_end)
1767     {
1768       unsigned int triplet;
1769
1770       triplet = s[2] | (s[1] << 8) | (s[0] << 16);
1771
1772       /* Encode each 6 bits. */
1773
1774       *d++ = ENCODE_64 (triplet >> 18);
1775       *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
1776       *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
1777       *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
1778       
1779       s += 3;
1780     }
1781
1782   switch (final_end - triplet_end)
1783     {
1784     case 2:
1785       {
1786         unsigned int doublet;
1787         
1788         doublet = s[1] | (s[0] << 8);        
1789
1790         *d++ = ENCODE_64 (doublet >> 12);
1791         *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
1792         *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
1793         *d++ = '=';
1794       }
1795       break;
1796     case 1:
1797       {
1798         unsigned int singlet;
1799         
1800         singlet = s[0];
1801
1802         *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
1803         *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
1804         *d++ = '=';
1805         *d++ = '=';
1806       }
1807       break;
1808     case 0:
1809       break;
1810     }
1811
1812   _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
1813
1814   return TRUE;
1815 }
1816
1817
1818 /**
1819  * Decodes a string from Base64, as documented in RFC 2045.
1820  *
1821  * @param source the string to decode
1822  * @param start byte index to start decode
1823  * @param dest string where decoded data should be placed
1824  * @param insert_at where to place decoded data
1825  * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
1826  */
1827 dbus_bool_t
1828 _dbus_string_base64_decode (const DBusString *source,
1829                             int               start,
1830                             DBusString       *dest,
1831                             int               insert_at)
1832 {
1833   int source_len;
1834   const char *s;
1835   const char *end;
1836   DBusString result;
1837   unsigned int triplet = 0;
1838   int sextet_count;
1839   int pad_count;
1840   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1841   _dbus_assert (source != dest);
1842   
1843   source_len = real_source->len - start;
1844   s = real_source->str + start;
1845   end = real_source->str + source_len;
1846
1847   if (source_len == 0)
1848     return TRUE;
1849
1850   if (!_dbus_string_init (&result, _DBUS_INT_MAX))
1851     return FALSE;
1852
1853   pad_count = 0;
1854   sextet_count = 0;
1855   while (s != end)
1856     {
1857       /* The idea is to just skip anything that isn't
1858        * a base64 char - it's allowed to have whitespace,
1859        * newlines, etc. in here. We also ignore trailing
1860        * base64 chars, though that's suspicious.
1861        */
1862       
1863       if (*s >= UNBASE64_MIN_CHAR &&
1864           *s <= UNBASE64_MAX_CHAR)
1865         {
1866           if (*s == '=')
1867             {
1868               /* '=' is padding, doesn't represent additional data
1869                * but does increment our count.
1870                */
1871               pad_count += 1;
1872               sextet_count += 1;
1873             }
1874           else
1875             {
1876               int val;
1877
1878               val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
1879
1880               if (val >= 0)
1881                 {
1882                   triplet <<= 6;
1883                   triplet |= (unsigned int) val;
1884                   sextet_count += 1;
1885                 }
1886             }
1887
1888           if (sextet_count == 4)
1889             {
1890               /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
1891               if (pad_count < 1)
1892                 _dbus_string_append_byte (&result,
1893                                           triplet >> 16);
1894               
1895               if (pad_count < 2)
1896                 _dbus_string_append_byte (&result,
1897                                           (triplet >> 8) & 0xff);              
1898               
1899               _dbus_string_append_byte (&result,
1900                                         triplet & 0xff);
1901               
1902               sextet_count = 0;
1903               pad_count = 0;
1904               triplet = 0;
1905             }
1906         }
1907       
1908       ++s;
1909     }
1910
1911   if (!_dbus_string_move (&result, 0, dest, insert_at))
1912     {
1913       _dbus_string_free (&result);
1914       return FALSE;
1915     }
1916
1917   _dbus_string_free (&result);
1918
1919   return TRUE;
1920 }
1921
1922 /**
1923  * Checks that the given range of the string
1924  * is valid ASCII. If the given range is not contained
1925  * in the string, returns #FALSE.
1926  *
1927  * @param str the string
1928  * @param start first byte index to check
1929  * @param len number of bytes to check
1930  * @returns #TRUE if the byte range exists and is all valid ASCII
1931  */
1932 dbus_bool_t
1933 _dbus_string_validate_ascii (const DBusString *str,
1934                              int               start,
1935                              int               len)
1936 {
1937   const unsigned char *s;
1938   const unsigned char *end;
1939   DBUS_CONST_STRING_PREAMBLE (str);
1940   _dbus_assert (start >= 0);
1941   _dbus_assert (len >= 0);
1942   
1943   if ((start + len) > real->len)
1944     return FALSE;
1945   
1946   s = real->str + start;
1947   end = s + len;
1948   while (s != end)
1949     {
1950       if (*s == '\0' ||
1951           ((*s & ~0x7f) != 0))
1952         return FALSE;
1953         
1954       ++s;
1955     }
1956   
1957   return TRUE;
1958 }
1959
1960 /**
1961  * Checks that the given range of the string
1962  * is valid UTF-8. If the given range is not contained
1963  * in the string, returns #FALSE. If the string
1964  * contains any nul bytes in the given range, returns
1965  * #FALSE.
1966  *
1967  * @todo right now just calls _dbus_string_validate_ascii()
1968  * 
1969  * @param str the string
1970  * @param start first byte index to check
1971  * @param len number of bytes to check
1972  * @returns #TRUE if the byte range exists and is all valid UTF-8
1973  */
1974 dbus_bool_t
1975 _dbus_string_validate_utf8  (const DBusString *str,
1976                              int               start,
1977                              int               len)
1978 {
1979   /* FIXME actually validate UTF-8 */
1980   return _dbus_string_validate_ascii (str, start, len);
1981 }
1982
1983 /**
1984  * Checks that the given range of the string
1985  * is all nul bytes. If the given range is
1986  * not contained in the string, returns #FALSE.
1987  * 
1988  * @param str the string
1989  * @param start first byte index to check
1990  * @param len number of bytes to check
1991  * @returns #TRUE if the byte range exists and is all nul bytes
1992  */
1993 dbus_bool_t
1994 _dbus_string_validate_nul (const DBusString *str,
1995                            int               start,
1996                            int               len)
1997 {
1998   const unsigned char *s;
1999   const unsigned char *end;
2000   DBUS_CONST_STRING_PREAMBLE (str);
2001   _dbus_assert (start >= 0);
2002   _dbus_assert (len >= 0);
2003   
2004   if ((start + len) > real->len)
2005     return FALSE;
2006   
2007   s = real->str + start;
2008   end = s + len;
2009   while (s != end)
2010     {
2011       if (*s != '\0')
2012         return FALSE;
2013       ++s;
2014     }
2015   
2016   return TRUE;
2017 }
2018
2019 /** @} */
2020
2021 #ifdef DBUS_BUILD_TESTS
2022 #include "dbus-test.h"
2023 #include <stdio.h>
2024
2025 static void
2026 test_max_len (DBusString *str,
2027               int         max_len)
2028 {
2029   if (max_len > 0)
2030     {
2031       if (!_dbus_string_set_length (str, max_len - 1))
2032         _dbus_assert_not_reached ("setting len to one less than max should have worked");
2033     }
2034
2035   if (!_dbus_string_set_length (str, max_len))
2036     _dbus_assert_not_reached ("setting len to max len should have worked");
2037
2038   if (_dbus_string_set_length (str, max_len + 1))
2039     _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2040
2041   if (!_dbus_string_set_length (str, 0))
2042     _dbus_assert_not_reached ("setting len to zero should have worked");
2043 }
2044
2045 static void
2046 test_base64_roundtrip (const unsigned char *data,
2047                        int                  len)
2048 {
2049   DBusString orig;
2050   DBusString encoded;
2051   DBusString decoded;
2052
2053   if (len < 0)
2054     len = strlen (data);
2055   
2056   if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2057     _dbus_assert_not_reached ("could not init string");
2058
2059   if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2060     _dbus_assert_not_reached ("could not init string");
2061   
2062   if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2063     _dbus_assert_not_reached ("could not init string");
2064
2065   if (!_dbus_string_append_len (&orig, data, len))
2066     _dbus_assert_not_reached ("couldn't append orig data");
2067
2068   if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2069     _dbus_assert_not_reached ("could not encode");
2070
2071   if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2072     _dbus_assert_not_reached ("could not decode");
2073
2074   if (!_dbus_string_equal (&orig, &decoded))
2075     {
2076       const char *s;
2077       
2078       printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2079               _dbus_string_get_length (&orig),
2080               _dbus_string_get_length (&encoded),
2081               _dbus_string_get_length (&decoded));
2082       printf ("Original: %s\n", data);
2083       _dbus_string_get_const_data (&decoded, &s);
2084       printf ("Decoded: %s\n", s);
2085       _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2086     }
2087   
2088   _dbus_string_free (&orig);
2089   _dbus_string_free (&encoded);
2090   _dbus_string_free (&decoded);  
2091 }
2092
2093 /**
2094  * @ingroup DBusStringInternals
2095  * Unit test for DBusString.
2096  *
2097  * @todo Need to write tests for _dbus_string_copy() and
2098  * _dbus_string_move() moving to/from each of start/middle/end of a
2099  * string. Also need tests for _dbus_string_move_len ()
2100  * 
2101  * @returns #TRUE on success.
2102  */
2103 dbus_bool_t
2104 _dbus_string_test (void)
2105 {
2106   DBusString str;
2107   DBusString other;
2108   int i, end;
2109   long v;
2110   double d;
2111   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 };
2112   char *s;
2113   dbus_unichar_t ch;
2114   
2115   i = 0;
2116   while (i < _DBUS_N_ELEMENTS (lens))
2117     {
2118       if (!_dbus_string_init (&str, lens[i]))
2119         _dbus_assert_not_reached ("failed to init string");
2120       
2121       test_max_len (&str, lens[i]);
2122       _dbus_string_free (&str);
2123
2124       ++i;
2125     }
2126
2127   /* Test shortening and setting length */
2128   i = 0;
2129   while (i < _DBUS_N_ELEMENTS (lens))
2130     {
2131       int j;
2132       
2133       if (!_dbus_string_init (&str, lens[i]))
2134         _dbus_assert_not_reached ("failed to init string");
2135       
2136       if (!_dbus_string_set_length (&str, lens[i]))
2137         _dbus_assert_not_reached ("failed to set string length");
2138
2139       j = lens[i];
2140       while (j > 0)
2141         {
2142           _dbus_assert (_dbus_string_get_length (&str) == j);
2143           if (j > 0)
2144             {
2145               _dbus_string_shorten (&str, 1);
2146               _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2147             }
2148           --j;
2149         }
2150       
2151       _dbus_string_free (&str);
2152
2153       ++i;
2154     }
2155
2156   /* Test appending data */
2157   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2158     _dbus_assert_not_reached ("failed to init string");
2159
2160   i = 0;
2161   while (i < 10)
2162     {
2163       if (!_dbus_string_append (&str, "a"))
2164         _dbus_assert_not_reached ("failed to append string to string\n");
2165
2166       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2167
2168       if (!_dbus_string_append_byte (&str, 'b'))
2169         _dbus_assert_not_reached ("failed to append byte to string\n");
2170
2171       _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2172                     
2173       ++i;
2174     }
2175
2176   _dbus_string_free (&str);
2177
2178   /* Check steal_data */
2179   
2180   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2181     _dbus_assert_not_reached ("failed to init string");
2182
2183   if (!_dbus_string_append (&str, "Hello World"))
2184     _dbus_assert_not_reached ("could not append to string");
2185
2186   i = _dbus_string_get_length (&str);
2187   
2188   if (!_dbus_string_steal_data (&str, &s))
2189     _dbus_assert_not_reached ("failed to steal data");
2190
2191   _dbus_assert (_dbus_string_get_length (&str) == 0);
2192   _dbus_assert (((int)strlen (s)) == i);
2193
2194   dbus_free (s);
2195
2196   /* Check move */
2197   
2198   if (!_dbus_string_append (&str, "Hello World"))
2199     _dbus_assert_not_reached ("could not append to string");
2200
2201   i = _dbus_string_get_length (&str);
2202
2203   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2204     _dbus_assert_not_reached ("could not init string");
2205   
2206   if (!_dbus_string_move (&str, 0, &other, 0))
2207     _dbus_assert_not_reached ("could not move");
2208
2209   _dbus_assert (_dbus_string_get_length (&str) == 0);
2210   _dbus_assert (_dbus_string_get_length (&other) == i);
2211
2212   if (!_dbus_string_append (&str, "Hello World"))
2213     _dbus_assert_not_reached ("could not append to string");
2214   
2215   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2216     _dbus_assert_not_reached ("could not move");
2217
2218   _dbus_assert (_dbus_string_get_length (&str) == 0);
2219   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2220
2221     if (!_dbus_string_append (&str, "Hello World"))
2222     _dbus_assert_not_reached ("could not append to string");
2223   
2224   if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2225     _dbus_assert_not_reached ("could not move");
2226
2227   _dbus_assert (_dbus_string_get_length (&str) == 0);
2228   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2229   
2230   _dbus_string_free (&other);
2231
2232   /* Check copy */
2233   
2234   if (!_dbus_string_append (&str, "Hello World"))
2235     _dbus_assert_not_reached ("could not append to string");
2236
2237   i = _dbus_string_get_length (&str);
2238   
2239   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2240     _dbus_assert_not_reached ("could not init string");
2241   
2242   if (!_dbus_string_copy (&str, 0, &other, 0))
2243     _dbus_assert_not_reached ("could not copy");
2244
2245   _dbus_assert (_dbus_string_get_length (&str) == i);
2246   _dbus_assert (_dbus_string_get_length (&other) == i);
2247
2248   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2249     _dbus_assert_not_reached ("could not copy");
2250
2251   _dbus_assert (_dbus_string_get_length (&str) == i);
2252   _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2253   _dbus_assert (_dbus_string_equal_c_str (&other,
2254                                           "Hello WorldHello World"));
2255
2256   if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2257     _dbus_assert_not_reached ("could not copy");
2258
2259   _dbus_assert (_dbus_string_get_length (&str) == i);
2260   _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2261   _dbus_assert (_dbus_string_equal_c_str (&other,
2262                                           "Hello WorldHello WorldHello World"));
2263   
2264   _dbus_string_free (&str);
2265   _dbus_string_free (&other);
2266
2267   /* Check replace */
2268
2269   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2270     _dbus_assert_not_reached ("failed to init string");
2271   
2272   if (!_dbus_string_append (&str, "Hello World"))
2273     _dbus_assert_not_reached ("could not append to string");
2274
2275   i = _dbus_string_get_length (&str);
2276   
2277   if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2278     _dbus_assert_not_reached ("could not init string");
2279   
2280   if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2281                                  &other, 0, _dbus_string_get_length (&other)))
2282     _dbus_assert_not_reached ("could not replace");
2283
2284   _dbus_assert (_dbus_string_get_length (&str) == i);
2285   _dbus_assert (_dbus_string_get_length (&other) == i);
2286   _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
2287   
2288   if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2289                                  &other, 5, 1))
2290     _dbus_assert_not_reached ("could not replace center space");
2291
2292   _dbus_assert (_dbus_string_get_length (&str) == i);
2293   _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2294   _dbus_assert (_dbus_string_equal_c_str (&other,
2295                                           "HelloHello WorldWorld"));
2296
2297   
2298   if (!_dbus_string_replace_len (&str, 1, 1,
2299                                  &other,
2300                                  _dbus_string_get_length (&other) - 1,
2301                                  1))
2302     _dbus_assert_not_reached ("could not replace end character");
2303   
2304   _dbus_assert (_dbus_string_get_length (&str) == i);
2305   _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2306   _dbus_assert (_dbus_string_equal_c_str (&other,
2307                                           "HelloHello WorldWorle"));
2308   
2309   _dbus_string_free (&str);
2310   _dbus_string_free (&other);
2311   
2312   /* Check append/get unichar */
2313   
2314   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2315     _dbus_assert_not_reached ("failed to init string");
2316
2317   ch = 0;
2318   if (!_dbus_string_append_unichar (&str, 0xfffc))
2319     _dbus_assert_not_reached ("failed to append unichar");
2320
2321   _dbus_string_get_unichar (&str, 0, &ch, &i);
2322
2323   _dbus_assert (ch == 0xfffc);
2324   _dbus_assert (i == _dbus_string_get_length (&str));
2325
2326   _dbus_string_free (&str);
2327
2328   /* Check insert/set/get byte */
2329   
2330   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2331     _dbus_assert_not_reached ("failed to init string");
2332
2333   if (!_dbus_string_append (&str, "Hello"))
2334     _dbus_assert_not_reached ("failed to append Hello");
2335
2336   _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
2337   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
2338   _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
2339   _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
2340   _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
2341
2342   _dbus_string_set_byte (&str, 1, 'q');
2343   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
2344
2345   if (!_dbus_string_insert_byte (&str, 0, 255))
2346     _dbus_assert_not_reached ("can't insert byte");
2347
2348   if (!_dbus_string_insert_byte (&str, 2, 'Z'))
2349     _dbus_assert_not_reached ("can't insert byte");
2350
2351   if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
2352     _dbus_assert_not_reached ("can't insert byte");
2353   
2354   _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
2355   _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
2356   _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
2357   _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
2358   _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
2359   _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
2360   _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
2361   _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
2362
2363   _dbus_string_free (&str);
2364   
2365   /* Check append/parse int/double */
2366   
2367   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2368     _dbus_assert_not_reached ("failed to init string");
2369
2370   if (!_dbus_string_append_int (&str, 27))
2371     _dbus_assert_not_reached ("failed to append int");
2372
2373   i = _dbus_string_get_length (&str);
2374
2375   if (!_dbus_string_parse_int (&str, 0, &v, &end))
2376     _dbus_assert_not_reached ("failed to parse int");
2377
2378   _dbus_assert (v == 27);
2379   _dbus_assert (end == i);
2380
2381   _dbus_string_free (&str);
2382   
2383   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2384     _dbus_assert_not_reached ("failed to init string");
2385   
2386   if (!_dbus_string_append_double (&str, 50.3))
2387     _dbus_assert_not_reached ("failed to append float");
2388
2389   i = _dbus_string_get_length (&str);
2390
2391   if (!_dbus_string_parse_double (&str, 0, &d, &end))
2392     _dbus_assert_not_reached ("failed to parse float");
2393
2394   _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
2395   _dbus_assert (end == i);
2396
2397   _dbus_string_free (&str);
2398
2399   /* Test find */
2400   if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2401     _dbus_assert_not_reached ("failed to init string");
2402
2403   if (!_dbus_string_append (&str, "Hello"))
2404     _dbus_assert_not_reached ("couldn't append to string");
2405   
2406   if (!_dbus_string_find (&str, 0, "He", &i))
2407     _dbus_assert_not_reached ("didn't find 'He'");
2408   _dbus_assert (i == 0);
2409
2410   if (!_dbus_string_find (&str, 0, "ello", &i))
2411     _dbus_assert_not_reached ("didn't find 'ello'");
2412   _dbus_assert (i == 1);
2413
2414   if (!_dbus_string_find (&str, 0, "lo", &i))
2415     _dbus_assert_not_reached ("didn't find 'lo'");
2416   _dbus_assert (i == 3);
2417
2418   if (!_dbus_string_find (&str, 2, "lo", &i))
2419     _dbus_assert_not_reached ("didn't find 'lo'");
2420   _dbus_assert (i == 3);
2421
2422   if (_dbus_string_find (&str, 4, "lo", &i))
2423     _dbus_assert_not_reached ("did find 'lo'");
2424   
2425   if (!_dbus_string_find (&str, 0, "l", &i))
2426     _dbus_assert_not_reached ("didn't find 'l'");
2427   _dbus_assert (i == 2);
2428
2429   if (!_dbus_string_find (&str, 0, "H", &i))
2430     _dbus_assert_not_reached ("didn't find 'H'");
2431   _dbus_assert (i == 0);
2432
2433   if (!_dbus_string_find (&str, 0, "", &i))
2434     _dbus_assert_not_reached ("didn't find ''");
2435   _dbus_assert (i == 0);
2436   
2437   if (_dbus_string_find (&str, 0, "Hello!", NULL))
2438     _dbus_assert_not_reached ("Did find 'Hello!'");
2439
2440   if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
2441     _dbus_assert_not_reached ("Did find 'Oh, Hello'");
2442   
2443   if (_dbus_string_find (&str, 0, "ill", NULL))
2444     _dbus_assert_not_reached ("Did find 'ill'");
2445
2446   if (_dbus_string_find (&str, 0, "q", NULL))
2447     _dbus_assert_not_reached ("Did find 'q'");
2448
2449   if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
2450     _dbus_assert_not_reached ("Didn't find 'He'");
2451
2452   if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
2453     _dbus_assert_not_reached ("Did find 'Hello'");
2454   
2455   _dbus_string_free (&str);
2456
2457   /* Base 64 */
2458   test_base64_roundtrip ("Hello this is a string\n", -1);
2459   test_base64_roundtrip ("Hello this is a string\n1", -1);
2460   test_base64_roundtrip ("Hello this is a string\n12", -1);
2461   test_base64_roundtrip ("Hello this is a string\n123", -1);
2462   test_base64_roundtrip ("Hello this is a string\n1234", -1);
2463   test_base64_roundtrip ("Hello this is a string\n12345", -1);
2464   test_base64_roundtrip ("", 0);
2465   test_base64_roundtrip ("1", 1);
2466   test_base64_roundtrip ("12", 2);
2467   test_base64_roundtrip ("123", 3);
2468   test_base64_roundtrip ("1234", 4);
2469   test_base64_roundtrip ("12345", 5);
2470   test_base64_roundtrip ("", 1);
2471   test_base64_roundtrip ("1", 2);
2472   test_base64_roundtrip ("12", 3);
2473   test_base64_roundtrip ("123", 4);
2474   test_base64_roundtrip ("1234", 5);
2475   test_base64_roundtrip ("12345", 6);
2476   {
2477     unsigned char buf[512];
2478     i = 0;
2479     while (i < _DBUS_N_ELEMENTS (buf))
2480       {
2481         buf[i] = i;
2482         ++i;
2483       }
2484     i = 0;
2485     while (i < _DBUS_N_ELEMENTS (buf))
2486       {
2487         test_base64_roundtrip (buf, i);
2488         ++i;
2489       }
2490   }
2491   
2492   return TRUE;
2493 }
2494
2495 #endif /* DBUS_BUILD_TESTS */