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