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