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