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