bus: Assign a serial number for messages from the driver
[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_STATIC_ASSERT (sizeof (DBusString) == sizeof (DBusRealString));
138
139   _dbus_assert (str != NULL);
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   dbus_bool_t ret = FALSE;
1077   int len;
1078   va_list args_copy;
1079
1080   DBUS_STRING_PREAMBLE (str);
1081
1082   DBUS_VA_COPY (args_copy, args);
1083
1084   /* Measure the message length without terminating nul */
1085   len = _dbus_printf_string_upper_bound (format, args);
1086
1087   if (len < 0)
1088     goto out;
1089
1090   if (!_dbus_string_lengthen (str, len))
1091     {
1092       goto out;
1093     }
1094   
1095   vsprintf ((char*) (real->str + (real->len - len)),
1096             format, args_copy);
1097   ret = TRUE;
1098
1099 out:
1100   va_end (args_copy);
1101
1102   return ret;
1103 }
1104
1105 /**
1106  * Appends a printf-style formatted string
1107  * to the #DBusString.
1108  *
1109  * @param str the string
1110  * @param format printf format
1111  * @returns #FALSE if no memory
1112  */
1113 dbus_bool_t
1114 _dbus_string_append_printf (DBusString        *str,
1115                             const char        *format,
1116                             ...)
1117 {
1118   va_list args;
1119   dbus_bool_t retval;
1120   
1121   va_start (args, format);
1122   retval = _dbus_string_append_printf_valist (str, format, args);
1123   va_end (args);
1124
1125   return retval;
1126 }
1127
1128 /**
1129  * Appends block of bytes with the given length to a DBusString.
1130  *
1131  * @param str the DBusString
1132  * @param buffer the bytes to append
1133  * @param len the number of bytes to append
1134  * @returns #FALSE if not enough memory.
1135  */
1136 dbus_bool_t
1137 _dbus_string_append_len (DBusString *str,
1138                          const char *buffer,
1139                          int         len)
1140 {
1141   DBUS_STRING_PREAMBLE (str);
1142   _dbus_assert (buffer != NULL);
1143   _dbus_assert (len >= 0);
1144
1145   return append (real, buffer, len);
1146 }
1147
1148 /**
1149  * Appends a single byte to the string, returning #FALSE
1150  * if not enough memory.
1151  *
1152  * @param str the string
1153  * @param byte the byte to append
1154  * @returns #TRUE on success
1155  */
1156 dbus_bool_t
1157 _dbus_string_append_byte (DBusString    *str,
1158                           unsigned char  byte)
1159 {
1160   DBUS_STRING_PREAMBLE (str);
1161
1162   if (!set_length (real, real->len + 1))
1163     return FALSE;
1164
1165   real->str[real->len-1] = byte;
1166
1167   return TRUE;
1168 }
1169
1170 static void
1171 delete (DBusRealString *real,
1172         int             start,
1173         int             len)
1174 {
1175   if (len == 0)
1176     return;
1177   
1178   memmove (real->str + start, real->str + start + len, real->len - (start + len));
1179   real->len -= len;
1180   real->str[real->len] = '\0';
1181 }
1182
1183 /**
1184  * Deletes a segment of a DBusString with length len starting at
1185  * start. (Hint: to clear an entire string, setting length to 0
1186  * with _dbus_string_set_length() is easier.)
1187  *
1188  * @param str the DBusString
1189  * @param start where to start deleting
1190  * @param len the number of bytes to delete
1191  */
1192 void
1193 _dbus_string_delete (DBusString       *str,
1194                      int               start,
1195                      int               len)
1196 {
1197   DBUS_STRING_PREAMBLE (str);
1198   _dbus_assert (start >= 0);
1199   _dbus_assert (len >= 0);
1200   _dbus_assert (start <= real->len);
1201   _dbus_assert (len <= real->len - start);
1202   
1203   delete (real, start, len);
1204 }
1205
1206 static dbus_bool_t
1207 copy (DBusRealString *source,
1208       int             start,
1209       int             len,
1210       DBusRealString *dest,
1211       int             insert_at)
1212 {
1213   if (len == 0)
1214     return TRUE;
1215
1216   if (!open_gap (len, dest, insert_at))
1217     return FALSE;
1218   
1219   memmove (dest->str + insert_at,
1220            source->str + start,
1221            len);
1222
1223   return TRUE;
1224 }
1225
1226 /**
1227  * Checks assertions for two strings we're copying a segment between,
1228  * and declares real_source/real_dest variables.
1229  *
1230  * @param source the source string
1231  * @param start the starting offset
1232  * @param dest the dest string
1233  * @param insert_at where the copied segment is inserted
1234  */
1235 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at)       \
1236   DBusRealString *real_source = (DBusRealString*) source;               \
1237   DBusRealString *real_dest = (DBusRealString*) dest;                   \
1238   _dbus_assert ((source) != (dest));                                    \
1239   DBUS_GENERIC_STRING_PREAMBLE (real_source);                           \
1240   DBUS_GENERIC_STRING_PREAMBLE (real_dest);                             \
1241   _dbus_assert (!real_dest->constant);                                  \
1242   _dbus_assert (!real_dest->locked);                                    \
1243   _dbus_assert ((start) >= 0);                                          \
1244   _dbus_assert ((start) <= real_source->len);                           \
1245   _dbus_assert ((insert_at) >= 0);                                      \
1246   _dbus_assert ((insert_at) <= real_dest->len)
1247
1248 /**
1249  * Moves the end of one string into another string. Both strings
1250  * must be initialized, valid strings.
1251  *
1252  * @param source the source string
1253  * @param start where to chop off the source string
1254  * @param dest the destination string
1255  * @param insert_at where to move the chopped-off part of source string
1256  * @returns #FALSE if not enough memory
1257  */
1258 dbus_bool_t
1259 _dbus_string_move (DBusString       *source,
1260                    int               start,
1261                    DBusString       *dest,
1262                    int               insert_at)
1263 {
1264   DBusRealString *real_source = (DBusRealString*) source;
1265   _dbus_assert (start <= real_source->len);
1266   
1267   return _dbus_string_move_len (source, start,
1268                                 real_source->len - start,
1269                                 dest, insert_at);
1270 }
1271
1272 /**
1273  * Like _dbus_string_move(), but does not delete the section
1274  * of the source string that's copied to the dest string.
1275  *
1276  * @param source the source string
1277  * @param start where to start copying the source string
1278  * @param dest the destination string
1279  * @param insert_at where to place the copied part of source string
1280  * @returns #FALSE if not enough memory
1281  */
1282 dbus_bool_t
1283 _dbus_string_copy (const DBusString *source,
1284                    int               start,
1285                    DBusString       *dest,
1286                    int               insert_at)
1287 {
1288   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1289
1290   return copy (real_source, start,
1291                real_source->len - start,
1292                real_dest,
1293                insert_at);
1294 }
1295
1296 /**
1297  * Like _dbus_string_move(), but can move a segment from
1298  * the middle of the source string.
1299  *
1300  * @param source the source string
1301  * @param start first byte of source string to move
1302  * @param len length of segment to move
1303  * @param dest the destination string
1304  * @param insert_at where to move the bytes from the source string
1305  * @returns #FALSE if not enough memory
1306  */
1307 dbus_bool_t
1308 _dbus_string_move_len (DBusString       *source,
1309                        int               start,
1310                        int               len,
1311                        DBusString       *dest,
1312                        int               insert_at)
1313
1314 {
1315   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1316   _dbus_assert (len >= 0);
1317   _dbus_assert ((start + len) <= real_source->len);
1318
1319
1320   if (len == 0)
1321     {
1322       return TRUE;
1323     }
1324   else if (start == 0 &&
1325            len == real_source->len &&
1326            real_dest->len == 0)
1327     {
1328       /* Short-circuit moving an entire existing string to an empty string
1329        * by just swapping the buffers.
1330        */
1331       /* we assume ->constant doesn't matter as you can't have
1332        * a constant string involved in a move.
1333        */
1334 #define ASSIGN_DATA(a, b) do {                  \
1335         (a)->str = (b)->str;                    \
1336         (a)->len = (b)->len;                    \
1337         (a)->allocated = (b)->allocated;        \
1338         (a)->align_offset = (b)->align_offset;  \
1339       } while (0)
1340       
1341       DBusRealString tmp;
1342
1343       ASSIGN_DATA (&tmp, real_source);
1344       ASSIGN_DATA (real_source, real_dest);
1345       ASSIGN_DATA (real_dest, &tmp);
1346
1347       return TRUE;
1348     }
1349   else
1350     {
1351       if (!copy (real_source, start, len,
1352                  real_dest,
1353                  insert_at))
1354         return FALSE;
1355       
1356       delete (real_source, start,
1357               len);
1358       
1359       return TRUE;
1360     }
1361 }
1362
1363 /**
1364  * Like _dbus_string_copy(), but can copy a segment from the middle of
1365  * the source string.
1366  *
1367  * @param source the source string
1368  * @param start where to start copying the source string
1369  * @param len length of segment to copy
1370  * @param dest the destination string
1371  * @param insert_at where to place the copied segment of source string
1372  * @returns #FALSE if not enough memory
1373  */
1374 dbus_bool_t
1375 _dbus_string_copy_len (const DBusString *source,
1376                        int               start,
1377                        int               len,
1378                        DBusString       *dest,
1379                        int               insert_at)
1380 {
1381   DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1382   _dbus_assert (len >= 0);
1383   _dbus_assert (start <= real_source->len);
1384   _dbus_assert (len <= real_source->len - start);
1385   
1386   return copy (real_source, start, len,
1387                real_dest,
1388                insert_at);
1389 }
1390
1391 /**
1392  * Replaces a segment of dest string with a segment of source string.
1393  *
1394  * @param source the source string
1395  * @param start where to start copying the source string
1396  * @param len length of segment to copy
1397  * @param dest the destination string
1398  * @param replace_at start of segment of dest string to replace
1399  * @param replace_len length of segment of dest string to replace
1400  * @returns #FALSE if not enough memory
1401  *
1402  */
1403 dbus_bool_t
1404 _dbus_string_replace_len (const DBusString *source,
1405                           int               start,
1406                           int               len,
1407                           DBusString       *dest,
1408                           int               replace_at,
1409                           int               replace_len)
1410 {
1411   DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1412   _dbus_assert (len >= 0);
1413   _dbus_assert (start <= real_source->len);
1414   _dbus_assert (len <= real_source->len - start);
1415   _dbus_assert (replace_at >= 0);
1416   _dbus_assert (replace_at <= real_dest->len);
1417   _dbus_assert (replace_len <= real_dest->len - replace_at);
1418
1419   if (len == replace_len)
1420     {
1421       memmove (real_dest->str + replace_at,
1422                real_source->str + start, len);
1423     }
1424   else if (len < replace_len)
1425     {
1426       memmove (real_dest->str + replace_at,
1427                real_source->str + start, len);
1428       delete (real_dest, replace_at + len,
1429               replace_len - len);
1430     }
1431   else
1432     {
1433       int diff;
1434
1435       _dbus_assert (len > replace_len);
1436
1437       diff = len - replace_len;
1438
1439       /* First of all we check if destination string can be enlarged as
1440        * required, then we overwrite previous bytes
1441        */
1442
1443       if (!copy (real_source, start + replace_len, diff,
1444                  real_dest, replace_at + replace_len))
1445         return FALSE;
1446
1447       memmove (real_dest->str + replace_at,
1448                real_source->str + start, replace_len);
1449     }
1450
1451   return TRUE;
1452 }
1453
1454 /**
1455  * Looks for the first occurance of a byte, deletes that byte,
1456  * and moves everything after the byte to the beginning of a
1457  * separate string.  Both strings must be initialized, valid
1458  * strings.
1459  *
1460  * @param source the source string
1461  * @param byte the byte to remove and split the string at
1462  * @param tail the split off string
1463  * @returns #FALSE if not enough memory or if byte could not be found
1464  *
1465  */
1466 dbus_bool_t
1467 _dbus_string_split_on_byte (DBusString        *source,
1468                             unsigned char      byte,
1469                             DBusString        *tail)
1470 {
1471   int byte_position;
1472   char byte_string[2] = "";
1473   int head_length;
1474   int tail_length;
1475
1476   byte_string[0] = (char) byte;
1477
1478   if (!_dbus_string_find (source, 0, byte_string, &byte_position))
1479     return FALSE;
1480
1481   head_length = byte_position;
1482   tail_length = _dbus_string_get_length (source) - head_length - 1;
1483
1484   if (!_dbus_string_move_len (source, byte_position + 1, tail_length,
1485                               tail, 0))
1486     return FALSE;
1487
1488   /* remove the trailing delimiter byte from the head now.
1489    */
1490   if (!_dbus_string_set_length (source, head_length))
1491     return FALSE;
1492
1493   return TRUE;
1494 }
1495
1496 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1497  * Pennington, and Tom Tromey are the authors and authorized relicense.
1498  */
1499
1500 /** computes length and mask of a unicode character
1501  * @param Char the char
1502  * @param Mask the mask variable to assign to
1503  * @param Len the length variable to assign to
1504  */
1505 #define UTF8_COMPUTE(Char, Mask, Len)                                         \
1506   if (Char < 128)                                                             \
1507     {                                                                         \
1508       Len = 1;                                                                \
1509       Mask = 0x7f;                                                            \
1510     }                                                                         \
1511   else if ((Char & 0xe0) == 0xc0)                                             \
1512     {                                                                         \
1513       Len = 2;                                                                \
1514       Mask = 0x1f;                                                            \
1515     }                                                                         \
1516   else if ((Char & 0xf0) == 0xe0)                                             \
1517     {                                                                         \
1518       Len = 3;                                                                \
1519       Mask = 0x0f;                                                            \
1520     }                                                                         \
1521   else if ((Char & 0xf8) == 0xf0)                                             \
1522     {                                                                         \
1523       Len = 4;                                                                \
1524       Mask = 0x07;                                                            \
1525     }                                                                         \
1526   else if ((Char & 0xfc) == 0xf8)                                             \
1527     {                                                                         \
1528       Len = 5;                                                                \
1529       Mask = 0x03;                                                            \
1530     }                                                                         \
1531   else if ((Char & 0xfe) == 0xfc)                                             \
1532     {                                                                         \
1533       Len = 6;                                                                \
1534       Mask = 0x01;                                                            \
1535     }                                                                         \
1536   else                                                                        \
1537     {                                                                         \
1538       Len = 0;                                                               \
1539       Mask = 0;                                                               \
1540     }
1541
1542 /**
1543  * computes length of a unicode character in UTF-8
1544  * @param Char the char
1545  */
1546 #define UTF8_LENGTH(Char)              \
1547   ((Char) < 0x80 ? 1 :                 \
1548    ((Char) < 0x800 ? 2 :               \
1549     ((Char) < 0x10000 ? 3 :            \
1550      ((Char) < 0x200000 ? 4 :          \
1551       ((Char) < 0x4000000 ? 5 : 6)))))
1552    
1553 /**
1554  * Gets a UTF-8 value.
1555  *
1556  * @param Result variable for extracted unicode char.
1557  * @param Chars the bytes to decode
1558  * @param Count counter variable
1559  * @param Mask mask for this char
1560  * @param Len length for this char in bytes
1561  */
1562 #define UTF8_GET(Result, Chars, Count, Mask, Len)                             \
1563   (Result) = (Chars)[0] & (Mask);                                             \
1564   for ((Count) = 1; (Count) < (Len); ++(Count))                               \
1565     {                                                                         \
1566       if (((Chars)[(Count)] & 0xc0) != 0x80)                                  \
1567         {                                                                     \
1568           (Result) = -1;                                                      \
1569           break;                                                              \
1570         }                                                                     \
1571       (Result) <<= 6;                                                         \
1572       (Result) |= ((Chars)[(Count)] & 0x3f);                                  \
1573     }
1574
1575 /**
1576  * Check whether a Unicode (5.2) char is in a valid range.
1577  *
1578  * The first check comes from the Unicode guarantee to never encode
1579  * a point above 0x0010ffff, since UTF-16 couldn't represent it.
1580  *
1581  * The second check covers surrogate pairs (category Cs).
1582  *
1583  * @param Char the character
1584  */
1585 #define UNICODE_VALID(Char)                   \
1586     ((Char) < 0x110000 &&                     \
1587      (((Char) & 0xFFFFF800) != 0xD800))
1588
1589 /**
1590  * Finds the given substring in the string,
1591  * returning #TRUE and filling in the byte index
1592  * where the substring was found, if it was found.
1593  * Returns #FALSE if the substring wasn't found.
1594  * Sets *start to the length of the string if the substring
1595  * is not found.
1596  *
1597  * @param str the string
1598  * @param start where to start looking
1599  * @param substr the substring
1600  * @param found return location for where it was found, or #NULL
1601  * @returns #TRUE if found
1602  */
1603 dbus_bool_t
1604 _dbus_string_find (const DBusString *str,
1605                    int               start,
1606                    const char       *substr,
1607                    int              *found)
1608 {
1609   return _dbus_string_find_to (str, start,
1610                                ((const DBusRealString*)str)->len,
1611                                substr, found);
1612 }
1613
1614 /**
1615  * Finds end of line ("\r\n" or "\n") in the string,
1616  * returning #TRUE and filling in the byte index
1617  * where the eol string was found, if it was found.
1618  * Returns #FALSE if eol wasn't found.
1619  *
1620  * @param str the string
1621  * @param start where to start looking
1622  * @param found return location for where eol was found or string length otherwise
1623  * @param found_len return length of found eol string or zero otherwise
1624  * @returns #TRUE if found
1625  */
1626 dbus_bool_t
1627 _dbus_string_find_eol (const DBusString *str,
1628                        int               start,
1629                        int              *found,
1630                        int              *found_len)
1631 {
1632   int i;
1633
1634   DBUS_CONST_STRING_PREAMBLE (str);
1635   _dbus_assert (start <= real->len);
1636   _dbus_assert (start >= 0);
1637   
1638   i = start;
1639   while (i < real->len)
1640     {
1641       if (real->str[i] == '\r') 
1642         {
1643           if ((i+1) < real->len && real->str[i+1] == '\n') /* "\r\n" */
1644             {
1645               if (found) 
1646                 *found = i;
1647               if (found_len)
1648                 *found_len = 2;
1649               return TRUE;
1650             } 
1651           else /* only "\r" */
1652             {
1653               if (found) 
1654                 *found = i;
1655               if (found_len)
1656                 *found_len = 1;
1657               return TRUE;
1658             }
1659         } 
1660       else if (real->str[i] == '\n')  /* only "\n" */
1661         {
1662           if (found) 
1663             *found = i;
1664           if (found_len)
1665             *found_len = 1;
1666           return TRUE;
1667         }
1668       ++i;
1669     }
1670
1671   if (found)
1672     *found = real->len;
1673
1674   if (found_len)
1675     *found_len = 0;
1676   
1677   return FALSE;
1678 }
1679
1680 /**
1681  * Finds the given substring in the string,
1682  * up to a certain position,
1683  * returning #TRUE and filling in the byte index
1684  * where the substring was found, if it was found.
1685  * Returns #FALSE if the substring wasn't found.
1686  * Sets *start to the length of the string if the substring
1687  * is not found.
1688  *
1689  * @param str the string
1690  * @param start where to start looking
1691  * @param end where to stop looking
1692  * @param substr the substring
1693  * @param found return location for where it was found, or #NULL
1694  * @returns #TRUE if found
1695  */
1696 dbus_bool_t
1697 _dbus_string_find_to (const DBusString *str,
1698                       int               start,
1699                       int               end,
1700                       const char       *substr,
1701                       int              *found)
1702 {
1703   int i;
1704   DBUS_CONST_STRING_PREAMBLE (str);
1705   _dbus_assert (substr != NULL);
1706   _dbus_assert (start <= real->len);
1707   _dbus_assert (start >= 0);
1708   _dbus_assert (substr != NULL);
1709   _dbus_assert (end <= real->len);
1710   _dbus_assert (start <= end);
1711
1712   /* we always "find" an empty string */
1713   if (*substr == '\0')
1714     {
1715       if (found)
1716         *found = start;
1717       return TRUE;
1718     }
1719
1720   i = start;
1721   while (i < end)
1722     {
1723       if (real->str[i] == substr[0])
1724         {
1725           int j = i + 1;
1726           
1727           while (j < end)
1728             {
1729               if (substr[j - i] == '\0')
1730                 break;
1731               else if (real->str[j] != substr[j - i])
1732                 break;
1733               
1734               ++j;
1735             }
1736
1737           if (substr[j - i] == '\0')
1738             {
1739               if (found)
1740                 *found = i;
1741               return TRUE;
1742             }
1743         }
1744       
1745       ++i;
1746     }
1747
1748   if (found)
1749     *found = end;
1750   
1751   return FALSE;  
1752 }
1753
1754 /**
1755  * Finds a blank (space or tab) in the string. Returns #TRUE
1756  * if found, #FALSE otherwise. If a blank is not found sets
1757  * *found to the length of the string.
1758  *
1759  * @param str the string
1760  * @param start byte index to start looking
1761  * @param found place to store the location of the first blank
1762  * @returns #TRUE if a blank was found
1763  */
1764 dbus_bool_t
1765 _dbus_string_find_blank (const DBusString *str,
1766                          int               start,
1767                          int              *found)
1768 {
1769   int i;
1770   DBUS_CONST_STRING_PREAMBLE (str);
1771   _dbus_assert (start <= real->len);
1772   _dbus_assert (start >= 0);
1773   
1774   i = start;
1775   while (i < real->len)
1776     {
1777       if (real->str[i] == ' ' ||
1778           real->str[i] == '\t')
1779         {
1780           if (found)
1781             *found = i;
1782           return TRUE;
1783         }
1784       
1785       ++i;
1786     }
1787
1788   if (found)
1789     *found = real->len;
1790   
1791   return FALSE;
1792 }
1793
1794 /**
1795  * Skips blanks from start, storing the first non-blank in *end
1796  * (blank is space or tab).
1797  *
1798  * @param str the string
1799  * @param start where to start
1800  * @param end where to store the first non-blank byte index
1801  */
1802 void
1803 _dbus_string_skip_blank (const DBusString *str,
1804                          int               start,
1805                          int              *end)
1806 {
1807   int i;
1808   DBUS_CONST_STRING_PREAMBLE (str);
1809   _dbus_assert (start <= real->len);
1810   _dbus_assert (start >= 0);
1811   
1812   i = start;
1813   while (i < real->len)
1814     {
1815       if (!DBUS_IS_ASCII_BLANK (real->str[i]))
1816         break;
1817       
1818       ++i;
1819     }
1820
1821   _dbus_assert (i == real->len || !DBUS_IS_ASCII_WHITE (real->str[i]));
1822   
1823   if (end)
1824     *end = i;
1825 }
1826
1827
1828 /**
1829  * Skips whitespace from start, storing the first non-whitespace in *end.
1830  * (whitespace is space, tab, newline, CR).
1831  *
1832  * @param str the string
1833  * @param start where to start
1834  * @param end where to store the first non-whitespace byte index
1835  */
1836 void
1837 _dbus_string_skip_white (const DBusString *str,
1838                          int               start,
1839                          int              *end)
1840 {
1841   int i;
1842   DBUS_CONST_STRING_PREAMBLE (str);
1843   _dbus_assert (start <= real->len);
1844   _dbus_assert (start >= 0);
1845   
1846   i = start;
1847   while (i < real->len)
1848     {
1849       if (!DBUS_IS_ASCII_WHITE (real->str[i]))
1850         break;
1851       
1852       ++i;
1853     }
1854
1855   _dbus_assert (i == real->len || !(DBUS_IS_ASCII_WHITE (real->str[i])));
1856   
1857   if (end)
1858     *end = i;
1859 }
1860
1861 /**
1862  * Skips whitespace from end, storing the start index of the trailing
1863  * whitespace in *start. (whitespace is space, tab, newline, CR).
1864  *
1865  * @param str the string
1866  * @param end where to start scanning backward
1867  * @param start where to store the start of whitespace chars
1868  */
1869 void
1870 _dbus_string_skip_white_reverse (const DBusString *str,
1871                                  int               end,
1872                                  int              *start)
1873 {
1874   int i;
1875   DBUS_CONST_STRING_PREAMBLE (str);
1876   _dbus_assert (end <= real->len);
1877   _dbus_assert (end >= 0);
1878   
1879   i = end;
1880   while (i > 0)
1881     {
1882       if (!DBUS_IS_ASCII_WHITE (real->str[i-1]))
1883         break;
1884       --i;
1885     }
1886
1887   _dbus_assert (i >= 0 && (i == 0 || !(DBUS_IS_ASCII_WHITE (real->str[i-1]))));
1888   
1889   if (start)
1890     *start = i;
1891 }
1892
1893 /**
1894  * Assigns a newline-terminated or \\r\\n-terminated line from the front
1895  * of the string to the given dest string. The dest string's previous
1896  * contents are deleted. If the source string contains no newline,
1897  * moves the entire source string to the dest string.
1898  *
1899  * @todo owen correctly notes that this is a stupid function (it was
1900  * written purely for test code,
1901  * e.g. dbus-message-builder.c). Probably should be enforced as test
1902  * code only with ifdef DBUS_ENABLE_EMBEDDED_TESTS
1903  * 
1904  * @param source the source string
1905  * @param dest the destination string (contents are replaced)
1906  * @returns #FALSE if no memory, or source has length 0
1907  */
1908 dbus_bool_t
1909 _dbus_string_pop_line (DBusString *source,
1910                        DBusString *dest)
1911 {
1912   int eol, eol_len;
1913   
1914   _dbus_string_set_length (dest, 0);
1915   
1916   eol = 0;
1917   eol_len = 0;
1918   if (!_dbus_string_find_eol (source, 0, &eol, &eol_len))
1919     {
1920       _dbus_assert (eol == _dbus_string_get_length (source));
1921       if (eol == 0)
1922         {
1923           /* If there's no newline and source has zero length, we're done */
1924           return FALSE;
1925         }
1926       /* otherwise, the last line of the file has no eol characters */
1927     }
1928
1929   /* remember eol can be 0 if it's an empty line, but eol_len should not be zero also
1930    * since find_eol returned TRUE
1931    */
1932   
1933   if (!_dbus_string_move_len (source, 0, eol + eol_len, dest, 0))
1934     return FALSE;
1935   
1936   /* remove line ending */
1937   if (!_dbus_string_set_length (dest, eol))
1938     {
1939       _dbus_assert_not_reached ("out of memory when shortening a string");
1940       return FALSE;
1941     }
1942
1943   return TRUE;
1944 }
1945
1946 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1947 /**
1948  * Deletes up to and including the first blank space
1949  * in the string.
1950  *
1951  * @param str the string
1952  */
1953 void
1954 _dbus_string_delete_first_word (DBusString *str)
1955 {
1956   int i;
1957   
1958   if (_dbus_string_find_blank (str, 0, &i))
1959     _dbus_string_skip_blank (str, i, &i);
1960
1961   _dbus_string_delete (str, 0, i);
1962 }
1963 #endif
1964
1965 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1966 /**
1967  * Deletes any leading blanks in the string
1968  *
1969  * @param str the string
1970  */
1971 void
1972 _dbus_string_delete_leading_blanks (DBusString *str)
1973 {
1974   int i;
1975   
1976   _dbus_string_skip_blank (str, 0, &i);
1977
1978   if (i > 0)
1979     _dbus_string_delete (str, 0, i);
1980 }
1981 #endif
1982
1983 /**
1984  * Deletes leading and trailing whitespace
1985  * 
1986  * @param str the string
1987  */
1988 void
1989 _dbus_string_chop_white(DBusString *str)
1990 {
1991   int i;
1992   
1993   _dbus_string_skip_white (str, 0, &i);
1994
1995   if (i > 0)
1996     _dbus_string_delete (str, 0, i);
1997   
1998   _dbus_string_skip_white_reverse (str, _dbus_string_get_length (str), &i);
1999
2000   _dbus_string_set_length (str, i);
2001 }
2002
2003 /**
2004  * Tests two DBusString for equality.
2005  *
2006  * @todo memcmp is probably faster
2007  *
2008  * @param a first string
2009  * @param b second string
2010  * @returns #TRUE if equal
2011  */
2012 dbus_bool_t
2013 _dbus_string_equal (const DBusString *a,
2014                     const DBusString *b)
2015 {
2016   const unsigned char *ap;
2017   const unsigned char *bp;
2018   const unsigned char *a_end;
2019   const DBusRealString *real_a = (const DBusRealString*) a;
2020   const DBusRealString *real_b = (const DBusRealString*) b;
2021   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2022   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2023
2024   if (real_a->len != real_b->len)
2025     return FALSE;
2026
2027   ap = real_a->str;
2028   bp = real_b->str;
2029   a_end = real_a->str + real_a->len;
2030   while (ap != a_end)
2031     {
2032       if (*ap != *bp)
2033         return FALSE;
2034       
2035       ++ap;
2036       ++bp;
2037     }
2038
2039   return TRUE;
2040 }
2041
2042 /**
2043  * Tests two DBusString for equality up to the given length.
2044  * The strings may be shorter than the given length.
2045  *
2046  * @todo write a unit test
2047  *
2048  * @todo memcmp is probably faster
2049  *
2050  * @param a first string
2051  * @param b second string
2052  * @param len the maximum length to look at
2053  * @returns #TRUE if equal for the given number of bytes
2054  */
2055 dbus_bool_t
2056 _dbus_string_equal_len (const DBusString *a,
2057                         const DBusString *b,
2058                         int               len)
2059 {
2060   const unsigned char *ap;
2061   const unsigned char *bp;
2062   const unsigned char *a_end;
2063   const DBusRealString *real_a = (const DBusRealString*) a;
2064   const DBusRealString *real_b = (const DBusRealString*) b;
2065   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2066   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2067
2068   if (real_a->len != real_b->len &&
2069       (real_a->len < len || real_b->len < len))
2070     return FALSE;
2071
2072   ap = real_a->str;
2073   bp = real_b->str;
2074   a_end = real_a->str + MIN (real_a->len, len);
2075   while (ap != a_end)
2076     {
2077       if (*ap != *bp)
2078         return FALSE;
2079       
2080       ++ap;
2081       ++bp;
2082     }
2083
2084   return TRUE;
2085 }
2086
2087 /**
2088  * Tests two sub-parts of two DBusString for equality.  The specified
2089  * range of the first string must exist; the specified start position
2090  * of the second string must exist.
2091  *
2092  * @todo write a unit test
2093  *
2094  * @todo memcmp is probably faster
2095  *
2096  * @param a first string
2097  * @param a_start where to start substring in first string
2098  * @param a_len length of substring in first string
2099  * @param b second string
2100  * @param b_start where to start substring in second string
2101  * @returns #TRUE if the two substrings are equal
2102  */
2103 dbus_bool_t
2104 _dbus_string_equal_substring (const DBusString  *a,
2105                               int                a_start,
2106                               int                a_len,
2107                               const DBusString  *b,
2108                               int                b_start)
2109 {
2110   const unsigned char *ap;
2111   const unsigned char *bp;
2112   const unsigned char *a_end;
2113   const DBusRealString *real_a = (const DBusRealString*) a;
2114   const DBusRealString *real_b = (const DBusRealString*) b;
2115   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2116   DBUS_GENERIC_STRING_PREAMBLE (real_b);
2117   _dbus_assert (a_start >= 0);
2118   _dbus_assert (a_len >= 0);
2119   _dbus_assert (a_start <= real_a->len);
2120   _dbus_assert (a_len <= real_a->len - a_start);
2121   _dbus_assert (b_start >= 0);
2122   _dbus_assert (b_start <= real_b->len);
2123   
2124   if (a_len > real_b->len - b_start)
2125     return FALSE;
2126
2127   ap = real_a->str + a_start;
2128   bp = real_b->str + b_start;
2129   a_end = ap + a_len;
2130   while (ap != a_end)
2131     {
2132       if (*ap != *bp)
2133         return FALSE;
2134       
2135       ++ap;
2136       ++bp;
2137     }
2138
2139   _dbus_assert (bp <= (real_b->str + real_b->len));
2140   
2141   return TRUE;
2142 }
2143
2144 /**
2145  * Checks whether a string is equal to a C string.
2146  *
2147  * @param a the string
2148  * @param c_str the C string
2149  * @returns #TRUE if equal
2150  */
2151 dbus_bool_t
2152 _dbus_string_equal_c_str (const DBusString *a,
2153                           const char       *c_str)
2154 {
2155   const unsigned char *ap;
2156   const unsigned char *bp;
2157   const unsigned char *a_end;
2158   const DBusRealString *real_a = (const DBusRealString*) a;
2159   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2160   _dbus_assert (c_str != NULL);
2161   
2162   ap = real_a->str;
2163   bp = (const unsigned char*) c_str;
2164   a_end = real_a->str + real_a->len;
2165   while (ap != a_end && *bp)
2166     {
2167       if (*ap != *bp)
2168         return FALSE;
2169       
2170       ++ap;
2171       ++bp;
2172     }
2173
2174   if (ap != a_end || *bp)
2175     return FALSE;
2176   
2177   return TRUE;
2178 }
2179
2180 /**
2181  * Checks whether a string starts with the given C string.
2182  *
2183  * @param a the string
2184  * @param c_str the C string
2185  * @returns #TRUE if string starts with it
2186  */
2187 dbus_bool_t
2188 _dbus_string_starts_with_c_str (const DBusString *a,
2189                                 const char       *c_str)
2190 {
2191   const unsigned char *ap;
2192   const unsigned char *bp;
2193   const unsigned char *a_end;
2194   const DBusRealString *real_a = (const DBusRealString*) a;
2195   DBUS_GENERIC_STRING_PREAMBLE (real_a);
2196   _dbus_assert (c_str != NULL);
2197   
2198   ap = real_a->str;
2199   bp = (const unsigned char*) c_str;
2200   a_end = real_a->str + real_a->len;
2201   while (ap != a_end && *bp)
2202     {
2203       if (*ap != *bp)
2204         return FALSE;
2205       
2206       ++ap;
2207       ++bp;
2208     }
2209
2210   if (*bp == '\0')
2211     return TRUE;
2212   else
2213     return FALSE;
2214 }
2215
2216 /**
2217  * Checks whether a string starts with the given C string, after which it ends or is separated from
2218  * the rest by a given separator character.
2219  *
2220  * @param a the string
2221  * @param c_str the C string
2222  * @param word_separator the separator
2223  * @returns #TRUE if string starts with it
2224  */
2225 dbus_bool_t
2226 _dbus_string_starts_with_words_c_str (const DBusString  *a,
2227                                       const char        *c_str,
2228                                       char               word_separator)
2229 {
2230   char next_char;
2231   const char *data;
2232   _dbus_assert (c_str != NULL);
2233
2234   if (!_dbus_string_starts_with_c_str (a, c_str))
2235     return FALSE;
2236
2237   data = _dbus_string_get_const_data (a);
2238   next_char = data[strlen (c_str)];
2239   return next_char == '\0' || next_char == word_separator;
2240 }
2241
2242 /**
2243  * Appends a two-character hex digit to a string, where the hex digit
2244  * has the value of the given byte.
2245  *
2246  * @param str the string
2247  * @param byte the byte
2248  * @returns #FALSE if no memory
2249  */
2250 dbus_bool_t
2251 _dbus_string_append_byte_as_hex (DBusString *str,
2252                                  unsigned char byte)
2253 {
2254   const char hexdigits[16] = {
2255     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2256     'a', 'b', 'c', 'd', 'e', 'f'
2257   };
2258
2259   if (!_dbus_string_append_byte (str,
2260                                  hexdigits[(byte >> 4)]))
2261     return FALSE;
2262   
2263   if (!_dbus_string_append_byte (str,
2264                                  hexdigits[(byte & 0x0f)]))
2265     {
2266       _dbus_string_set_length (str,
2267                                _dbus_string_get_length (str) - 1);
2268       return FALSE;
2269     }
2270
2271   return TRUE;
2272 }
2273
2274 /**
2275  * Encodes a string in hex, the way MD5 and SHA-1 are usually
2276  * encoded. (Each byte is two hex digits.)
2277  *
2278  * @param source the string to encode
2279  * @param start byte index to start encoding
2280  * @param dest string where encoded data should be placed
2281  * @param insert_at where to place encoded data
2282  * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2283  */
2284 dbus_bool_t
2285 _dbus_string_hex_encode (const DBusString *source,
2286                          int               start,
2287                          DBusString       *dest,
2288                          int               insert_at)
2289 {
2290   DBusString result;
2291   const unsigned char *p;
2292   const unsigned char *end;
2293   dbus_bool_t retval;
2294   
2295   _dbus_assert (start <= _dbus_string_get_length (source));
2296
2297   if (!_dbus_string_init (&result))
2298     return FALSE;
2299
2300   retval = FALSE;
2301   
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       if (!_dbus_string_append_byte_as_hex (&result, *p))
2309         goto out;
2310       
2311       ++p;
2312     }
2313
2314   if (!_dbus_string_move (&result, 0, dest, insert_at))
2315     goto out;
2316
2317   retval = TRUE;
2318
2319  out:
2320   _dbus_string_free (&result);
2321   return retval;
2322 }
2323
2324 /**
2325  * Decodes a string from hex encoding.
2326  *
2327  * @param source the string to decode
2328  * @param start byte index to start decode
2329  * @param end_return return location of the end of the hex data, or #NULL
2330  * @param dest string where decoded data should be placed
2331  * @param insert_at where to place decoded data
2332  * @returns #TRUE if decoding was successful, #FALSE if no memory.
2333  */
2334 dbus_bool_t
2335 _dbus_string_hex_decode (const DBusString *source,
2336                          int               start,
2337                          int              *end_return,
2338                          DBusString       *dest,
2339                          int               insert_at)
2340 {
2341   DBusString result;
2342   const unsigned char *p;
2343   const unsigned char *end;
2344   dbus_bool_t retval;
2345   dbus_bool_t high_bits;
2346   
2347   _dbus_assert (start <= _dbus_string_get_length (source));
2348
2349   if (!_dbus_string_init (&result))
2350     return FALSE;
2351
2352   retval = FALSE;
2353
2354   high_bits = TRUE;
2355   p = (const unsigned char*) _dbus_string_get_const_data (source);
2356   end = p + _dbus_string_get_length (source);
2357   p += start;
2358   
2359   while (p != end)
2360     {
2361       unsigned int val;
2362
2363       switch (*p)
2364         {
2365         case '0':
2366           val = 0;
2367           break;
2368         case '1':
2369           val = 1;
2370           break;
2371         case '2':
2372           val = 2;
2373           break;
2374         case '3':
2375           val = 3;
2376           break;
2377         case '4':
2378           val = 4;
2379           break;
2380         case '5':
2381           val = 5;
2382           break;
2383         case '6':
2384           val = 6;
2385           break;
2386         case '7':
2387           val = 7;
2388           break;
2389         case '8':
2390           val = 8;
2391           break;
2392         case '9':
2393           val = 9;
2394           break;
2395         case 'a':
2396         case 'A':
2397           val = 10;
2398           break;
2399         case 'b':
2400         case 'B':
2401           val = 11;
2402           break;
2403         case 'c':
2404         case 'C':
2405           val = 12;
2406           break;
2407         case 'd':
2408         case 'D':
2409           val = 13;
2410           break;
2411         case 'e':
2412         case 'E':
2413           val = 14;
2414           break;
2415         case 'f':
2416         case 'F':
2417           val = 15;
2418           break;
2419         default:
2420           goto done;
2421         }
2422
2423       if (high_bits)
2424         {
2425           if (!_dbus_string_append_byte (&result,
2426                                          val << 4))
2427             goto out;
2428         }
2429       else
2430         {
2431           int len;
2432           unsigned char b;
2433
2434           len = _dbus_string_get_length (&result);
2435           
2436           b = _dbus_string_get_byte (&result, len - 1);
2437
2438           b |= val;
2439
2440           _dbus_string_set_byte (&result, len - 1, b);
2441         }
2442
2443       high_bits = !high_bits;
2444
2445       ++p;
2446     }
2447
2448  done:
2449   if (!_dbus_string_move (&result, 0, dest, insert_at))
2450     goto out;
2451
2452   if (end_return)
2453     *end_return = p - (const unsigned char*) _dbus_string_get_const_data (source);
2454
2455   retval = TRUE;
2456   
2457  out:
2458   _dbus_string_free (&result);  
2459   return retval;
2460 }
2461
2462 /**
2463  * Checks that the given range of the string is valid ASCII with no
2464  * nul bytes. If the given range is not entirely contained in the
2465  * string, returns #FALSE.
2466  *
2467  * @todo this is inconsistent with most of DBusString in that
2468  * it allows a start,len range that extends past the string end.
2469  * 
2470  * @param str the string
2471  * @param start first byte index to check
2472  * @param len number of bytes to check
2473  * @returns #TRUE if the byte range exists and is all valid ASCII
2474  */
2475 dbus_bool_t
2476 _dbus_string_validate_ascii (const DBusString *str,
2477                              int               start,
2478                              int               len)
2479 {
2480   const unsigned char *s;
2481   const unsigned char *end;
2482   DBUS_CONST_STRING_PREAMBLE (str);
2483   _dbus_assert (start >= 0);
2484   _dbus_assert (start <= real->len);
2485   _dbus_assert (len >= 0);
2486   
2487   if (len > real->len - start)
2488     return FALSE;
2489   
2490   s = real->str + start;
2491   end = s + len;
2492   while (s != end)
2493     {
2494       if (_DBUS_UNLIKELY (!_DBUS_ISASCII (*s)))
2495         return FALSE;
2496         
2497       ++s;
2498     }
2499   
2500   return TRUE;
2501 }
2502
2503 /**
2504  * Converts the given range of the string to lower case.
2505  *
2506  * @param str the string
2507  * @param start first byte index to convert
2508  * @param len number of bytes to convert
2509  */
2510 void
2511 _dbus_string_tolower_ascii (const DBusString *str,
2512                             int               start,
2513                             int               len)
2514 {
2515   unsigned char *s;
2516   unsigned char *end;
2517   DBUS_STRING_PREAMBLE (str);
2518   _dbus_assert (start >= 0);
2519   _dbus_assert (start <= real->len);
2520   _dbus_assert (len >= 0);
2521   _dbus_assert (len <= real->len - start);
2522
2523   s = real->str + start;
2524   end = s + len;
2525
2526   while (s != end)
2527     {
2528       if (*s >= 'A' && *s <= 'Z')
2529           *s += 'a' - 'A';
2530       ++s;
2531     }
2532 }
2533
2534 /**
2535  * Converts the given range of the string to upper case.
2536  *
2537  * @param str the string
2538  * @param start first byte index to convert
2539  * @param len number of bytes to convert
2540  */
2541 void
2542 _dbus_string_toupper_ascii (const DBusString *str,
2543                             int               start,
2544                             int               len)
2545 {
2546   unsigned char *s;
2547   unsigned char *end;
2548   DBUS_STRING_PREAMBLE (str);
2549   _dbus_assert (start >= 0);
2550   _dbus_assert (start <= real->len);
2551   _dbus_assert (len >= 0);
2552   _dbus_assert (len <= real->len - start);
2553
2554   s = real->str + start;
2555   end = s + len;
2556
2557   while (s != end)
2558     {
2559       if (*s >= 'a' && *s <= 'z')
2560           *s += 'A' - 'a';
2561       ++s;
2562     }
2563 }
2564
2565 /**
2566  * Checks that the given range of the string is valid UTF-8. If the
2567  * given range is not entirely contained in the string, returns
2568  * #FALSE. If the string contains any nul bytes in the given range,
2569  * returns #FALSE. If the start and start+len are not on character
2570  * boundaries, returns #FALSE.
2571  *
2572  * @todo this is inconsistent with most of DBusString in that
2573  * it allows a start,len range that extends past the string end.
2574  * 
2575  * @param str the string
2576  * @param start first byte index to check
2577  * @param len number of bytes to check
2578  * @returns #TRUE if the byte range exists and is all valid UTF-8
2579  */
2580 dbus_bool_t
2581 _dbus_string_validate_utf8  (const DBusString *str,
2582                              int               start,
2583                              int               len)
2584 {
2585   const unsigned char *p;
2586   const unsigned char *end;
2587   DBUS_CONST_STRING_PREAMBLE (str);
2588   _dbus_assert (start >= 0);
2589   _dbus_assert (start <= real->len);
2590   _dbus_assert (len >= 0);
2591
2592   /* we are doing _DBUS_UNLIKELY() here which might be
2593    * dubious in a generic library like GLib, but in D-Bus
2594    * we know we're validating messages and that it would
2595    * only be evil/broken apps that would have invalid
2596    * UTF-8. Also, this function seems to be a performance
2597    * bottleneck in profiles.
2598    */
2599   
2600   if (_DBUS_UNLIKELY (len > real->len - start))
2601     return FALSE;
2602   
2603   p = real->str + start;
2604   end = p + len;
2605   
2606   while (p < end)
2607     {
2608       int i, mask, char_len;
2609       dbus_unichar_t result;
2610
2611       /* nul bytes considered invalid */
2612       if (*p == '\0')
2613         break;
2614       
2615       /* Special-case ASCII; this makes us go a lot faster in
2616        * D-Bus profiles where we are typically validating
2617        * function names and such. We have to know that
2618        * all following checks will pass for ASCII though,
2619        * comments follow ...
2620        */      
2621       if (*p < 128)
2622         {
2623           ++p;
2624           continue;
2625         }
2626       
2627       UTF8_COMPUTE (*p, mask, char_len);
2628
2629       if (_DBUS_UNLIKELY (char_len == 0))  /* ASCII: char_len == 1 */
2630         break;
2631
2632       /* check that the expected number of bytes exists in the remaining length */
2633       if (_DBUS_UNLIKELY ((end - p) < char_len)) /* ASCII: p < end and char_len == 1 */
2634         break;
2635         
2636       UTF8_GET (result, p, i, mask, char_len);
2637
2638       /* Check for overlong UTF-8 */
2639       if (_DBUS_UNLIKELY (UTF8_LENGTH (result) != char_len)) /* ASCII: UTF8_LENGTH == 1 */
2640         break;
2641 #if 0
2642       /* The UNICODE_VALID check below will catch this */
2643       if (_DBUS_UNLIKELY (result == (dbus_unichar_t)-1)) /* ASCII: result = ascii value */
2644         break;
2645 #endif
2646
2647       if (_DBUS_UNLIKELY (!UNICODE_VALID (result))) /* ASCII: always valid */
2648         break;
2649
2650       /* UNICODE_VALID should have caught it */
2651       _dbus_assert (result != (dbus_unichar_t)-1);
2652       
2653       p += char_len;
2654     }
2655
2656   /* See that we covered the entire length if a length was
2657    * passed in
2658    */
2659   if (_DBUS_UNLIKELY (p != end))
2660     return FALSE;
2661   else
2662     return TRUE;
2663 }
2664
2665 /**
2666  * Checks that the given range of the string is all nul bytes. If the
2667  * given range is not entirely contained in the string, returns
2668  * #FALSE.
2669  *
2670  * @todo this is inconsistent with most of DBusString in that
2671  * it allows a start,len range that extends past the string end.
2672  * 
2673  * @param str the string
2674  * @param start first byte index to check
2675  * @param len number of bytes to check
2676  * @returns #TRUE if the byte range exists and is all nul bytes
2677  */
2678 dbus_bool_t
2679 _dbus_string_validate_nul (const DBusString *str,
2680                            int               start,
2681                            int               len)
2682 {
2683   const unsigned char *s;
2684   const unsigned char *end;
2685   DBUS_CONST_STRING_PREAMBLE (str);
2686   _dbus_assert (start >= 0);
2687   _dbus_assert (len >= 0);
2688   _dbus_assert (start <= real->len);
2689   
2690   if (len > real->len - start)
2691     return FALSE;
2692   
2693   s = real->str + start;
2694   end = s + len;
2695   while (s != end)
2696     {
2697       if (_DBUS_UNLIKELY (*s != '\0'))
2698         return FALSE;
2699       ++s;
2700     }
2701   
2702   return TRUE;
2703 }
2704
2705 /**
2706  * Clears all allocated bytes in the string to zero.
2707  *
2708  * @param str the string
2709  */
2710 void
2711 _dbus_string_zero (DBusString *str)
2712 {
2713   DBUS_STRING_PREAMBLE (str);
2714
2715   memset (real->str - real->align_offset, '\0', real->allocated);
2716 }
2717 /** @} */
2718
2719 /* tests are in dbus-string-util.c */