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