1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-string.c String utility class (internal to D-BUS implementation)
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
6 * Licensed under the Academic Free License version 1.2
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus-internals.h"
25 #include "dbus-string.h"
26 /* we allow a system header here, for speed/convenience */
28 #include "dbus-marshal.h"
29 #define DBUS_CAN_USE_DBUS_STRING_PRIVATE 1
30 #include "dbus-string-private.h"
33 * @defgroup DBusString string class
34 * @ingroup DBusInternals
35 * @brief DBusString data structure
37 * Types and functions related to DBusString. DBusString is intended
38 * to be a string class that makes it hard to mess up security issues
39 * (and just in general harder to write buggy code). It should be
40 * used (or extended and then used) rather than the libc stuff in
41 * string.h. The string class is a bit inconvenient at spots because
42 * it handles out-of-memory failures and tries to be extra-robust.
44 * A DBusString has a maximum length set at initialization time; this
45 * can be used to ensure that a buffer doesn't get too big. The
46 * _dbus_string_lengthen() method checks for overflow, and for max
47 * length being exceeded.
49 * Try to avoid conversion to a plain C string, i.e. add methods on
50 * the string object instead, only convert to C string when passing
51 * things out to the public API. In particular, no sprintf, strcpy,
52 * strcat, any of that should be used. The GString feature of
53 * accepting negative numbers for "length of string" is also absent,
54 * because it could keep us from detecting bogus huge lengths. i.e. if
55 * we passed in some bogus huge length it would be taken to mean
56 * "current length of string" instead of "broken crack"
60 * @defgroup DBusStringInternals DBusString implementation details
61 * @ingroup DBusInternals
62 * @brief DBusString implementation details
64 * The guts of DBusString.
70 * We allocate 1 byte for nul termination, plus 7 bytes for possible
71 * align_offset, so we always need 8 bytes on top of the string's
72 * length to be in the allocated block.
74 #define ALLOCATION_PADDING 8
77 * This is the maximum max length (and thus also the maximum length)
80 #define MAX_MAX_LENGTH (_DBUS_INT_MAX - ALLOCATION_PADDING)
83 * Checks a bunch of assertions about a string object
85 * @param real the DBusRealString
87 #define DBUS_GENERIC_STRING_PREAMBLE(real) _dbus_assert ((real) != NULL); _dbus_assert (!(real)->invalid); _dbus_assert ((real)->len >= 0); _dbus_assert ((real)->allocated >= 0); _dbus_assert ((real)->max_length >= 0); _dbus_assert ((real)->len <= ((real)->allocated - ALLOCATION_PADDING)); _dbus_assert ((real)->len <= (real)->max_length)
90 * Checks assertions about a string object that needs to be
91 * modifiable - may not be locked or const. Also declares
92 * the "real" variable pointing to DBusRealString.
93 * @param str the string
95 #define DBUS_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
96 DBUS_GENERIC_STRING_PREAMBLE (real); \
97 _dbus_assert (!(real)->constant); \
98 _dbus_assert (!(real)->locked)
101 * Checks assertions about a string object that may be locked but
102 * can't be const. i.e. a string object that we can free. Also
103 * declares the "real" variable pointing to DBusRealString.
105 * @param str the string
107 #define DBUS_LOCKED_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
108 DBUS_GENERIC_STRING_PREAMBLE (real); \
109 _dbus_assert (!(real)->constant)
112 * Checks assertions about a string that may be const or locked. Also
113 * declares the "real" variable pointing to DBusRealString.
114 * @param str the string.
116 #define DBUS_CONST_STRING_PREAMBLE(str) const DBusRealString *real = (DBusRealString*) str; \
117 DBUS_GENERIC_STRING_PREAMBLE (real)
122 * @addtogroup DBusString
127 fixup_alignment (DBusRealString *real)
131 unsigned int old_align_offset;
133 /* we have to have extra space in real->allocated for the align offset and nul byte */
134 _dbus_assert (real->len <= real->allocated - ALLOCATION_PADDING);
136 old_align_offset = real->align_offset;
137 real_block = real->str - old_align_offset;
139 aligned = _DBUS_ALIGN_ADDRESS (real_block, 8);
141 real->align_offset = aligned - real_block;
144 if (old_align_offset != real->align_offset)
146 /* Here comes the suck */
147 memmove (real_block + real->align_offset,
148 real_block + old_align_offset,
152 _dbus_assert (real->align_offset < 8);
153 _dbus_assert (_DBUS_ALIGN_ADDRESS (real->str, 8) == real->str);
157 undo_alignment (DBusRealString *real)
159 if (real->align_offset != 0)
161 memmove (real->str - real->align_offset,
165 real->str = real->str - real->align_offset;
166 real->align_offset = 0;
171 * Initializes a string. The maximum length may be _DBUS_INT_MAX for
172 * no maximum. The string starts life with zero length.
173 * The string must eventually be freed with _dbus_string_free().
175 * @todo the max length feature is useless, because it looks to the
176 * app like out of memory, and the app might try to "recover" - but
177 * recovery in this case is impossible, as we can't ever "get more
178 * memory" - so should delete the max length feature I think. Well, at
179 * least there's a strong caveat that it can only be used when
180 * out-of-memory is a permanent fatal error.
182 * @todo we could make this init routine not alloc any memory and
183 * return void, would simplify a lot of code, however it might
184 * complexify things elsewhere because _dbus_string_get_data()
185 * etc. could suddenly fail as they'd need to alloc new memory.
187 * @param str memory to hold the string
188 * @param max_length the maximum size of the string
189 * @returns #TRUE on success */
191 _dbus_string_init (DBusString *str,
194 DBusRealString *real;
196 _dbus_assert (str != NULL);
197 _dbus_assert (max_length >= 0);
199 _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
201 real = (DBusRealString*) str;
203 /* It's very important not to touch anything
204 * other than real->str if we're going to fail,
205 * since we also use this function to reset
206 * an existing string, e.g. in _dbus_string_steal_data()
209 real->str = dbus_malloc (ALLOCATION_PADDING);
210 if (real->str == NULL)
213 real->allocated = ALLOCATION_PADDING;
215 real->str[real->len] = '\0';
217 real->max_length = max_length;
218 if (real->max_length > MAX_MAX_LENGTH)
219 real->max_length = MAX_MAX_LENGTH;
220 real->constant = FALSE;
221 real->locked = FALSE;
222 real->invalid = FALSE;
223 real->align_offset = 0;
225 fixup_alignment (real);
231 * Initializes a constant string. The value parameter is not copied
232 * (should be static), and the string may never be modified.
233 * It is safe but not necessary to call _dbus_string_free()
234 * on a const string. The string has a length limit of MAXINT - 8.
236 * @param str memory to use for the string
237 * @param value a string to be stored in str (not copied!!!)
240 _dbus_string_init_const (DBusString *str,
243 _dbus_assert (value != NULL);
245 _dbus_string_init_const_len (str, value,
250 * Initializes a constant string with a length. The value parameter is
251 * not copied (should be static), and the string may never be
252 * modified. It is safe but not necessary to call _dbus_string_free()
255 * @param str memory to use for the string
256 * @param value a string to be stored in str (not copied!!!)
257 * @param len the length to use
260 _dbus_string_init_const_len (DBusString *str,
264 DBusRealString *real;
266 _dbus_assert (str != NULL);
267 _dbus_assert (value != NULL);
268 _dbus_assert (len <= MAX_MAX_LENGTH);
269 _dbus_assert (len >= 0);
271 real = (DBusRealString*) str;
273 real->str = (char*) value;
275 real->allocated = real->len + ALLOCATION_PADDING; /* a lie, just to avoid special-case assertions... */
276 real->max_length = real->len + 1;
277 real->constant = TRUE;
278 real->invalid = FALSE;
280 /* We don't require const strings to be 8-byte aligned as the
281 * memory is coming from elsewhere.
286 * Frees a string created by _dbus_string_init().
288 * @param str memory where the string is stored.
291 _dbus_string_free (DBusString *str)
293 DBusRealString *real = (DBusRealString*) str;
294 DBUS_GENERIC_STRING_PREAMBLE (real);
298 dbus_free (real->str - real->align_offset);
300 real->invalid = TRUE;
304 * Locks a string such that any attempts to change the string will
305 * result in aborting the program. Also, if the string is wasting a
306 * lot of memory (allocation is sufficiently larger than what the
307 * string is really using), _dbus_string_lock() will realloc the
308 * string's data to "compact" it.
310 * @param str the string to lock.
313 _dbus_string_lock (DBusString *str)
315 DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
319 /* Try to realloc to avoid excess memory usage, since
320 * we know we won't change the string further
323 if (real->allocated - MAX_WASTE > real->len)
328 new_allocated = real->len + ALLOCATION_PADDING;
330 new_str = dbus_realloc (real->str - real->align_offset,
334 real->str = new_str + real->align_offset;
335 real->allocated = new_allocated;
336 fixup_alignment (real);
342 set_length (DBusRealString *real,
345 /* Note, we are setting the length without nul termination */
347 /* exceeding max length is the same as failure to allocate memory */
348 if (new_length > real->max_length)
351 if (new_length > (real->allocated - ALLOCATION_PADDING))
356 /* at least double our old allocation to avoid O(n), avoiding
359 if (real->allocated > (MAX_MAX_LENGTH + ALLOCATION_PADDING) / 2)
360 new_allocated = MAX_MAX_LENGTH + ALLOCATION_PADDING;
362 new_allocated = real->allocated * 2;
364 /* But be sure we always alloc at least space for the new length */
365 new_allocated = MAX (real->allocated, new_length + ALLOCATION_PADDING);
367 new_str = dbus_realloc (real->str - real->align_offset, new_allocated);
371 real->str = new_str + real->align_offset;
372 real->allocated = new_allocated;
373 fixup_alignment (real);
376 real->len = new_length;
377 real->str[real->len] = '\0';
384 DBusRealString *dest,
390 if (len > dest->max_length - dest->len)
391 return FALSE; /* detected overflow of dest->len + len below */
393 if (!set_length (dest, dest->len + len))
396 memmove (dest->str + insert_at + len,
397 dest->str + insert_at,
398 dest->len - len - insert_at);
404 * Gets the raw character buffer from the string. The returned buffer
405 * will be nul-terminated, but note that strings may contain binary
406 * data so there may be extra nul characters prior to the termination.
407 * This function should be little-used, extend DBusString or add
408 * stuff to dbus-sysdeps.c instead. It's an error to use this
409 * function on a const string.
411 * @param str the string
412 * @param data_return place to store the returned data
415 _dbus_string_get_data (DBusString *str,
418 DBUS_STRING_PREAMBLE (str);
419 _dbus_assert (data_return != NULL);
421 *data_return = real->str;
425 * Gets the raw character buffer from a const string.
427 * @todo should return the const char* instead of using an out param;
428 * the temporary variable encourages a bug where you use const data
429 * after modifying the string and possibly causing a realloc.
431 * @param str the string
432 * @param data_return location to store returned data
435 _dbus_string_get_const_data (const DBusString *str,
436 const char **data_return)
438 DBUS_CONST_STRING_PREAMBLE (str);
439 _dbus_assert (data_return != NULL);
441 *data_return = real->str;
445 * Gets a sub-portion of the raw character buffer from the
446 * string. The "len" field is required simply for error
447 * checking, to be sure you don't try to use more
448 * string than exists. The nul termination of the
449 * returned buffer remains at the end of the entire
450 * string, not at start + len.
452 * @param str the string
453 * @param data_return location to return the buffer
454 * @param start byte offset to return
455 * @param len length of segment to return
458 _dbus_string_get_data_len (DBusString *str,
463 DBUS_STRING_PREAMBLE (str);
464 _dbus_assert (data_return != NULL);
465 _dbus_assert (start >= 0);
466 _dbus_assert (len >= 0);
467 _dbus_assert (start <= real->len);
468 _dbus_assert (len <= real->len - start);
470 *data_return = real->str + start;
474 * const version of _dbus_string_get_data_len().
476 * @todo should return the const char* instead of using an out param;
477 * the temporary variable encourages a bug where you use const data
478 * after modifying the string and possibly causing a realloc.
480 * @param str the string
481 * @param data_return location to return the buffer
482 * @param start byte offset to return
483 * @param len length of segment to return
486 _dbus_string_get_const_data_len (const DBusString *str,
487 const char **data_return,
491 DBUS_CONST_STRING_PREAMBLE (str);
492 _dbus_assert (data_return != NULL);
493 _dbus_assert (start >= 0);
494 _dbus_assert (len >= 0);
495 _dbus_assert (start <= real->len);
496 _dbus_assert (len <= real->len - start);
498 *data_return = real->str + start;
502 * Sets the value of the byte at the given position.
504 * @param str the string
505 * @param i the position
506 * @param byte the new value
509 _dbus_string_set_byte (DBusString *str,
513 DBUS_STRING_PREAMBLE (str);
514 _dbus_assert (i < real->len);
515 _dbus_assert (i >= 0);
521 * Gets the byte at the given position.
523 * @param str the string
524 * @param start the position
525 * @returns the byte at that position
528 _dbus_string_get_byte (const DBusString *str,
531 DBUS_CONST_STRING_PREAMBLE (str);
532 _dbus_assert (start < real->len);
533 _dbus_assert (start >= 0);
535 return real->str[start];
539 * Inserts the given byte at the given position.
541 * @param str the string
542 * @param i the position
543 * @param byte the value to insert
544 * @returns #TRUE on success
547 _dbus_string_insert_byte (DBusString *str,
551 DBUS_STRING_PREAMBLE (str);
552 _dbus_assert (i <= real->len);
553 _dbus_assert (i >= 0);
555 if (!open_gap (1, real, i))
564 * Like _dbus_string_get_data(), but removes the
565 * gotten data from the original string. The caller
566 * must free the data returned. This function may
567 * fail due to lack of memory, and return #FALSE.
569 * @param str the string
570 * @param data_return location to return the buffer
571 * @returns #TRUE on success
574 _dbus_string_steal_data (DBusString *str,
577 DBUS_STRING_PREAMBLE (str);
578 _dbus_assert (data_return != NULL);
580 undo_alignment (real);
582 *data_return = real->str;
584 /* reset the string */
585 if (!_dbus_string_init (str, real->max_length))
587 /* hrm, put it back then */
588 real->str = *data_return;
590 fixup_alignment (real);
598 * Like _dbus_string_get_data_len(), but removes the gotten data from
599 * the original string. The caller must free the data returned. This
600 * function may fail due to lack of memory, and return #FALSE.
601 * The returned string is nul-terminated and has length len.
603 * @todo this function is broken because on failure it
604 * may corrupt the source string.
606 * @param str the string
607 * @param data_return location to return the buffer
608 * @param start the start of segment to steal
609 * @param len the length of segment to steal
610 * @returns #TRUE on success
613 _dbus_string_steal_data_len (DBusString *str,
620 DBUS_STRING_PREAMBLE (str);
621 _dbus_assert (data_return != NULL);
622 _dbus_assert (start >= 0);
623 _dbus_assert (len >= 0);
624 _dbus_assert (start <= real->len);
625 _dbus_assert (len <= real->len - start);
627 if (!_dbus_string_init (&dest, real->max_length))
630 if (!_dbus_string_move_len (str, start, len, &dest, 0))
632 _dbus_string_free (&dest);
636 _dbus_warn ("Broken code in _dbus_string_steal_data_len(), FIXME\n");
637 if (!_dbus_string_steal_data (&dest, data_return))
639 _dbus_string_free (&dest);
643 _dbus_string_free (&dest);
648 * Gets the length of a string (not including nul termination).
650 * @returns the length.
653 _dbus_string_get_length (const DBusString *str)
655 DBUS_CONST_STRING_PREAMBLE (str);
661 * Makes a string longer by the given number of bytes. Checks whether
662 * adding additional_length to the current length would overflow an
663 * integer, and checks for exceeding a string's max length.
664 * The new bytes are not initialized, other than nul-terminating
665 * the end of the string. The uninitialized bytes may contain
666 * nul bytes or other junk.
668 * @param str a string
669 * @param additional_length length to add to the string.
670 * @returns #TRUE on success.
673 _dbus_string_lengthen (DBusString *str,
674 int additional_length)
676 DBUS_STRING_PREAMBLE (str);
677 _dbus_assert (additional_length >= 0);
679 if (additional_length > real->max_length - real->len)
680 return FALSE; /* would overflow */
682 return set_length (real,
683 real->len + additional_length);
687 * Makes a string shorter by the given number of bytes.
689 * @param str a string
690 * @param length_to_remove length to remove from the string.
693 _dbus_string_shorten (DBusString *str,
694 int length_to_remove)
696 DBUS_STRING_PREAMBLE (str);
697 _dbus_assert (length_to_remove >= 0);
698 _dbus_assert (length_to_remove <= real->len);
701 real->len - length_to_remove);
705 * Sets the length of a string. Can be used to truncate or lengthen
706 * the string. If the string is lengthened, the function may fail and
707 * return #FALSE. Newly-added bytes are not initialized, as with
708 * _dbus_string_lengthen().
710 * @param str a string
711 * @param length new length of the string.
712 * @returns #FALSE on failure.
715 _dbus_string_set_length (DBusString *str,
718 DBUS_STRING_PREAMBLE (str);
719 _dbus_assert (length >= 0);
721 return set_length (real, length);
725 * Align the length of a string to a specific alignment (typically 4 or 8)
726 * by appending nul bytes to the string.
728 * @param str a string
729 * @param alignment the alignment
730 * @returns #FALSE if no memory
733 _dbus_string_align_length (DBusString *str,
736 unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
738 DBUS_STRING_PREAMBLE (str);
739 _dbus_assert (alignment >= 1);
740 _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
742 new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
743 if (new_len > (unsigned long) real->max_length)
746 delta = new_len - real->len;
747 _dbus_assert (delta >= 0);
752 if (!set_length (real, new_len))
755 memset (real->str + (new_len - delta),
762 append (DBusRealString *real,
769 if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
772 memcpy (real->str + (real->len - buffer_len),
780 * Appends a nul-terminated C-style string to a DBusString.
782 * @param str the DBusString
783 * @param buffer the nul-terminated characters to append
784 * @returns #FALSE if not enough memory.
787 _dbus_string_append (DBusString *str,
790 unsigned long buffer_len;
792 DBUS_STRING_PREAMBLE (str);
793 _dbus_assert (buffer != NULL);
795 buffer_len = strlen (buffer);
796 if (buffer_len > (unsigned long) real->max_length)
799 return append (real, buffer, buffer_len);
803 * Appends block of bytes with the given length to a DBusString.
805 * @param str the DBusString
806 * @param buffer the bytes to append
807 * @param len the number of bytes to append
808 * @returns #FALSE if not enough memory.
811 _dbus_string_append_len (DBusString *str,
815 DBUS_STRING_PREAMBLE (str);
816 _dbus_assert (buffer != NULL);
817 _dbus_assert (len >= 0);
819 return append (real, buffer, len);
823 * Appends a single byte to the string, returning #FALSE
824 * if not enough memory.
826 * @param str the string
827 * @param byte the byte to append
828 * @returns #TRUE on success
831 _dbus_string_append_byte (DBusString *str,
834 DBUS_STRING_PREAMBLE (str);
836 if (!set_length (real, real->len + 1))
839 real->str[real->len-1] = byte;
845 * Appends a single Unicode character, encoding the character
848 * @param str the string
849 * @param ch the Unicode character
852 _dbus_string_append_unichar (DBusString *str,
860 DBUS_STRING_PREAMBLE (str);
862 /* this code is from GLib but is pretty standard I think */
876 else if (ch < 0x10000)
881 else if (ch < 0x200000)
886 else if (ch < 0x4000000)
897 if (len > (real->max_length - real->len))
898 return FALSE; /* real->len + len would overflow */
900 if (!set_length (real, real->len + len))
903 out = real->str + (real->len - len);
905 for (i = len - 1; i > 0; --i)
907 out[i] = (ch & 0x3f) | 0x80;
916 delete (DBusRealString *real,
923 memmove (real->str + start, real->str + start + len, real->len - (start + len));
925 real->str[real->len] = '\0';
929 * Deletes a segment of a DBusString with length len starting at
930 * start. (Hint: to clear an entire string, setting length to 0
931 * with _dbus_string_set_length() is easier.)
933 * @param str the DBusString
934 * @param start where to start deleting
935 * @param len the number of bytes to delete
938 _dbus_string_delete (DBusString *str,
942 DBUS_STRING_PREAMBLE (str);
943 _dbus_assert (start >= 0);
944 _dbus_assert (len >= 0);
945 _dbus_assert (start <= real->len);
946 _dbus_assert (len <= real->len - start);
948 delete (real, start, len);
952 copy (DBusRealString *source,
955 DBusRealString *dest,
961 if (!open_gap (len, dest, insert_at))
964 memcpy (dest->str + insert_at,
972 * Checks assertions for two strings we're copying a segment between,
973 * and declares real_source/real_dest variables.
975 * @param source the source string
976 * @param start the starting offset
977 * @param dest the dest string
978 * @param insert_at where the copied segment is inserted
980 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at) \
981 DBusRealString *real_source = (DBusRealString*) source; \
982 DBusRealString *real_dest = (DBusRealString*) dest; \
983 _dbus_assert ((source) != (dest)); \
984 DBUS_GENERIC_STRING_PREAMBLE (real_source); \
985 DBUS_GENERIC_STRING_PREAMBLE (real_dest); \
986 _dbus_assert (!real_dest->constant); \
987 _dbus_assert (!real_dest->locked); \
988 _dbus_assert ((start) >= 0); \
989 _dbus_assert ((start) <= real_source->len); \
990 _dbus_assert ((insert_at) >= 0); \
991 _dbus_assert ((insert_at) <= real_dest->len)
994 * Moves the end of one string into another string. Both strings
995 * must be initialized, valid strings.
997 * @param source the source string
998 * @param start where to chop off the source string
999 * @param dest the destination string
1000 * @param insert_at where to move the chopped-off part of source string
1001 * @returns #FALSE if not enough memory
1004 _dbus_string_move (DBusString *source,
1009 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1011 if (!copy (real_source, start,
1012 real_source->len - start,
1017 delete (real_source, start,
1018 real_source->len - start);
1024 * Like _dbus_string_move(), but does not delete the section
1025 * of the source string that's copied to the dest string.
1027 * @param source the source string
1028 * @param start where to start copying the source string
1029 * @param dest the destination string
1030 * @param insert_at where to place the copied part of source string
1031 * @returns #FALSE if not enough memory
1034 _dbus_string_copy (const DBusString *source,
1039 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1041 return copy (real_source, start,
1042 real_source->len - start,
1048 * Like _dbus_string_move(), but can move a segment from
1049 * the middle of the source string.
1051 * @param source the source string
1052 * @param start first byte of source string to move
1053 * @param len length of segment to move
1054 * @param dest the destination string
1055 * @param insert_at where to move the bytes from the source string
1056 * @returns #FALSE if not enough memory
1059 _dbus_string_move_len (DBusString *source,
1066 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1067 _dbus_assert (len >= 0);
1068 _dbus_assert ((start + len) <= real_source->len);
1070 if (!copy (real_source, start, len,
1075 delete (real_source, start,
1082 * Like _dbus_string_copy(), but can copy a segment from the middle of
1083 * the source string.
1085 * @param source the source string
1086 * @param start where to start copying the source string
1087 * @param len length of segment to copy
1088 * @param dest the destination string
1089 * @param insert_at where to place the copied segment of source string
1090 * @returns #FALSE if not enough memory
1093 _dbus_string_copy_len (const DBusString *source,
1099 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1100 _dbus_assert (len >= 0);
1101 _dbus_assert (start <= real_source->len);
1102 _dbus_assert (len <= real_source->len - start);
1104 return copy (real_source, start, len,
1110 * Replaces a segment of dest string with a segment of source string.
1112 * @todo optimize the case where the two lengths are the same, and
1113 * avoid memmoving the data in the trailing part of the string twice.
1115 * @todo avoid inserting the source into dest, then deleting
1116 * the replaced chunk of dest (which creates a potentially large
1117 * intermediate string). Instead, extend the replaced chunk
1118 * of dest with padding to the same size as the source chunk,
1119 * then copy in the source bytes.
1121 * @param source the source string
1122 * @param start where to start copying the source string
1123 * @param len length of segment to copy
1124 * @param dest the destination string
1125 * @param replace_at start of segment of dest string to replace
1126 * @param replace_len length of segment of dest string to replace
1127 * @returns #FALSE if not enough memory
1131 _dbus_string_replace_len (const DBusString *source,
1138 DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1139 _dbus_assert (len >= 0);
1140 _dbus_assert (start <= real_source->len);
1141 _dbus_assert (len <= real_source->len - start);
1142 _dbus_assert (replace_at >= 0);
1143 _dbus_assert (replace_at <= real_dest->len);
1144 _dbus_assert (replace_len <= real_dest->len - replace_at);
1146 if (!copy (real_source, start, len,
1147 real_dest, replace_at))
1150 delete (real_dest, replace_at + len, replace_len);
1155 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1156 * Pennington, and Tom Tromey are the authors and authorized relicense.
1159 /** computes length and mask of a unicode character
1160 * @param Char the char
1161 * @param Mask the mask variable to assign to
1162 * @param Len the length variable to assign to
1164 #define UTF8_COMPUTE(Char, Mask, Len) \
1170 else if ((Char & 0xe0) == 0xc0) \
1175 else if ((Char & 0xf0) == 0xe0) \
1180 else if ((Char & 0xf8) == 0xf0) \
1185 else if ((Char & 0xfc) == 0xf8) \
1190 else if ((Char & 0xfe) == 0xfc) \
1199 * computes length of a unicode character in UTF-8
1200 * @param Char the char
1202 #define UTF8_LENGTH(Char) \
1203 ((Char) < 0x80 ? 1 : \
1204 ((Char) < 0x800 ? 2 : \
1205 ((Char) < 0x10000 ? 3 : \
1206 ((Char) < 0x200000 ? 4 : \
1207 ((Char) < 0x4000000 ? 5 : 6)))))
1210 * Gets a UTF-8 value.
1212 * @param Result variable for extracted unicode char.
1213 * @param Chars the bytes to decode
1214 * @param Count counter variable
1215 * @param Mask mask for this char
1216 * @param Len length for this char in bytes
1218 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
1219 (Result) = (Chars)[0] & (Mask); \
1220 for ((Count) = 1; (Count) < (Len); ++(Count)) \
1222 if (((Chars)[(Count)] & 0xc0) != 0x80) \
1228 (Result) |= ((Chars)[(Count)] & 0x3f); \
1232 * Check whether a unicode char is in a valid range.
1234 * @param Char the character
1236 #define UNICODE_VALID(Char) \
1237 ((Char) < 0x110000 && \
1238 ((Char) < 0xD800 || (Char) >= 0xE000) && \
1239 (Char) != 0xFFFE && (Char) != 0xFFFF)
1242 * Gets a unicode character from a UTF-8 string. Does no validation;
1243 * you must verify that the string is valid UTF-8 in advance and must
1244 * pass in the start of a character.
1246 * @param str the string
1247 * @param start the start of the UTF-8 character.
1248 * @param ch_return location to return the character
1249 * @param end_return location to return the byte index of next character
1252 _dbus_string_get_unichar (const DBusString *str,
1254 dbus_unichar_t *ch_return,
1258 dbus_unichar_t result;
1261 DBUS_CONST_STRING_PREAMBLE (str);
1262 _dbus_assert (start >= 0);
1263 _dbus_assert (start <= real->len);
1268 *end_return = real->len;
1271 p = real->str + start;
1274 UTF8_COMPUTE (c, mask, len);
1277 UTF8_GET (result, p, i, mask, len);
1279 if (result == (dbus_unichar_t)-1)
1283 *ch_return = result;
1285 *end_return = start + len;
1289 * Finds the given substring in the string,
1290 * returning #TRUE and filling in the byte index
1291 * where the substring was found, if it was found.
1292 * Returns #FALSE if the substring wasn't found.
1293 * Sets *start to the length of the string if the substring
1296 * @param str the string
1297 * @param start where to start looking
1298 * @param substr the substring
1299 * @param found return location for where it was found, or #NULL
1300 * @returns #TRUE if found
1303 _dbus_string_find (const DBusString *str,
1308 return _dbus_string_find_to (str, start,
1309 ((const DBusRealString*)str)->len,
1314 * Finds the given substring in the string,
1315 * up to a certain position,
1316 * returning #TRUE and filling in the byte index
1317 * where the substring was found, if it was found.
1318 * Returns #FALSE if the substring wasn't found.
1319 * Sets *start to the length of the string if the substring
1322 * @param str the string
1323 * @param start where to start looking
1324 * @param end where to stop looking
1325 * @param substr the substring
1326 * @param found return location for where it was found, or #NULL
1327 * @returns #TRUE if found
1330 _dbus_string_find_to (const DBusString *str,
1337 DBUS_CONST_STRING_PREAMBLE (str);
1338 _dbus_assert (substr != NULL);
1339 _dbus_assert (start <= real->len);
1340 _dbus_assert (start >= 0);
1341 _dbus_assert (substr != NULL);
1342 _dbus_assert (end <= real->len);
1343 _dbus_assert (start <= end);
1345 /* we always "find" an empty string */
1346 if (*substr == '\0')
1356 if (real->str[i] == substr[0])
1362 if (substr[j - i] == '\0')
1364 else if (real->str[j] != substr[j - i])
1370 if (substr[j - i] == '\0')
1388 * Finds a blank (space or tab) in the string. Returns #TRUE
1389 * if found, #FALSE otherwise. If a blank is not found sets
1390 * *found to the length of the string.
1392 * @param str the string
1393 * @param start byte index to start looking
1394 * @param found place to store the location of the first blank
1395 * @returns #TRUE if a blank was found
1398 _dbus_string_find_blank (const DBusString *str,
1403 DBUS_CONST_STRING_PREAMBLE (str);
1404 _dbus_assert (start <= real->len);
1405 _dbus_assert (start >= 0);
1408 while (i < real->len)
1410 if (real->str[i] == ' ' ||
1411 real->str[i] == '\t')
1428 * Skips blanks from start, storing the first non-blank in *end
1430 * @param str the string
1431 * @param start where to start
1432 * @param end where to store the first non-blank byte index
1435 _dbus_string_skip_blank (const DBusString *str,
1440 DBUS_CONST_STRING_PREAMBLE (str);
1441 _dbus_assert (start <= real->len);
1442 _dbus_assert (start >= 0);
1445 while (i < real->len)
1447 if (!(real->str[i] == ' ' ||
1448 real->str[i] == '\t'))
1454 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1455 real->str[i] == '\t'));
1462 * Assigns a newline-terminated or \r\n-terminated line from the front
1463 * of the string to the given dest string. The dest string's previous
1464 * contents are deleted. If the source string contains no newline,
1465 * moves the entire source string to the dest string.
1467 * @todo owen correctly notes that this is a stupid function (it was
1468 * written purely for test code,
1469 * e.g. dbus-message-builder.c). Probably should be enforced as test
1470 * code only with #ifdef DBUS_BUILD_TESTS
1472 * @param source the source string
1473 * @param dest the destination string (contents are replaced)
1474 * @returns #FALSE if no memory, or source has length 0
1477 _dbus_string_pop_line (DBusString *source,
1481 dbus_bool_t have_newline;
1483 _dbus_string_set_length (dest, 0);
1486 if (_dbus_string_find (source, 0, "\n", &eol))
1488 have_newline = TRUE;
1489 eol += 1; /* include newline */
1493 eol = _dbus_string_get_length (source);
1494 have_newline = FALSE;
1498 return FALSE; /* eof */
1500 if (!_dbus_string_move_len (source, 0, eol,
1506 /* dump the newline and the \r if we have one */
1509 dbus_bool_t have_cr;
1511 _dbus_assert (_dbus_string_get_length (dest) > 0);
1513 if (_dbus_string_get_length (dest) > 1 &&
1514 _dbus_string_get_byte (dest,
1515 _dbus_string_get_length (dest) - 2) == '\r')
1520 _dbus_string_set_length (dest,
1521 _dbus_string_get_length (dest) -
1529 * Deletes up to and including the first blank space
1532 * @param str the string
1535 _dbus_string_delete_first_word (DBusString *str)
1539 if (_dbus_string_find_blank (str, 0, &i))
1540 _dbus_string_skip_blank (str, i, &i);
1542 _dbus_string_delete (str, 0, i);
1546 * Deletes any leading blanks in the string
1548 * @param str the string
1551 _dbus_string_delete_leading_blanks (DBusString *str)
1555 _dbus_string_skip_blank (str, 0, &i);
1558 _dbus_string_delete (str, 0, i);
1562 * Tests two DBusString for equality.
1564 * @todo memcmp is probably faster
1566 * @param a first string
1567 * @param b second string
1568 * @returns #TRUE if equal
1571 _dbus_string_equal (const DBusString *a,
1572 const DBusString *b)
1574 const unsigned char *ap;
1575 const unsigned char *bp;
1576 const unsigned char *a_end;
1577 const DBusRealString *real_a = (const DBusRealString*) a;
1578 const DBusRealString *real_b = (const DBusRealString*) b;
1579 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1580 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1582 if (real_a->len != real_b->len)
1587 a_end = real_a->str + real_a->len;
1601 * Tests two DBusString for equality up to the given length.
1603 * @todo write a unit test
1605 * @todo memcmp is probably faster
1607 * @param a first string
1608 * @param b second string
1609 * @param len the lengh
1610 * @returns #TRUE if equal for the given number of bytes
1613 _dbus_string_equal_len (const DBusString *a,
1614 const DBusString *b,
1617 const unsigned char *ap;
1618 const unsigned char *bp;
1619 const unsigned char *a_end;
1620 const DBusRealString *real_a = (const DBusRealString*) a;
1621 const DBusRealString *real_b = (const DBusRealString*) b;
1622 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1623 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1625 if (real_a->len != real_b->len &&
1626 (real_a->len < len || real_b->len < len))
1631 a_end = real_a->str + MIN (real_a->len, len);
1645 * Checks whether a string is equal to a C string.
1647 * @param a the string
1648 * @param c_str the C string
1649 * @returns #TRUE if equal
1652 _dbus_string_equal_c_str (const DBusString *a,
1655 const unsigned char *ap;
1656 const unsigned char *bp;
1657 const unsigned char *a_end;
1658 const DBusRealString *real_a = (const DBusRealString*) a;
1659 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1660 _dbus_assert (c_str != NULL);
1663 bp = (const unsigned char*) c_str;
1664 a_end = real_a->str + real_a->len;
1665 while (ap != a_end && *bp)
1674 if (ap != a_end || *bp)
1681 * Checks whether a string starts with the given C string.
1683 * @param a the string
1684 * @param c_str the C string
1685 * @returns #TRUE if string starts with it
1688 _dbus_string_starts_with_c_str (const DBusString *a,
1691 const unsigned char *ap;
1692 const unsigned char *bp;
1693 const unsigned char *a_end;
1694 const DBusRealString *real_a = (const DBusRealString*) a;
1695 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1696 _dbus_assert (c_str != NULL);
1699 bp = (const unsigned char*) c_str;
1700 a_end = real_a->str + real_a->len;
1701 while (ap != a_end && *bp)
1717 * Returns whether a string ends with the given suffix
1719 * @todo memcmp might make this faster.
1721 * @param a the string
1722 * @param c_str the C-style string
1723 * @returns #TRUE if the string ends with the suffix
1726 _dbus_string_ends_with_c_str (const DBusString *a,
1729 const unsigned char *ap;
1730 const unsigned char *bp;
1731 const unsigned char *a_end;
1732 unsigned long c_str_len;
1733 const DBusRealString *real_a = (const DBusRealString*) a;
1734 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1735 _dbus_assert (c_str != NULL);
1737 c_str_len = strlen (c_str);
1738 if (((unsigned long)real_a->len) < c_str_len)
1741 ap = real_a->str + (real_a->len - c_str_len);
1742 bp = (const unsigned char*) c_str;
1743 a_end = real_a->str + real_a->len;
1753 _dbus_assert (*ap == '\0');
1754 _dbus_assert (*bp == '\0');
1759 static const signed char base64_table[] = {
1826 /** The minimum char that's a valid char in Base64-encoded text */
1827 #define UNBASE64_MIN_CHAR (43)
1828 /** The maximum char that's a valid char in Base64-encoded text */
1829 #define UNBASE64_MAX_CHAR (122)
1830 /** Must subtract this from a char's integer value before offsetting
1831 * into unbase64_table
1833 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1834 static const signed char unbase64_table[] = {
1918 * Encodes a string using Base64, as documented in RFC 2045.
1920 * @param source the string to encode
1921 * @param start byte index to start encoding
1922 * @param dest string where encoded data should be placed
1923 * @param insert_at where to place encoded data
1924 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
1927 _dbus_string_base64_encode (const DBusString *source,
1933 unsigned int dest_len; /* unsigned for overflow checks below */
1934 const unsigned char *s;
1936 const unsigned char *triplet_end;
1937 const unsigned char *final_end;
1938 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1939 _dbus_assert (source != dest);
1941 /* For each 24 bits (3 bytes) of input, we have 4 bytes of
1944 source_len = real_source->len - start;
1945 dest_len = (source_len / 3) * 4;
1946 if (source_len % 3 != 0)
1949 if (dest_len > (unsigned int) real_dest->max_length)
1952 if (source_len == 0)
1955 if (!open_gap (dest_len, real_dest, insert_at))
1958 d = real_dest->str + insert_at;
1959 s = real_source->str + start;
1960 final_end = real_source->str + (start + source_len);
1961 triplet_end = final_end - (source_len % 3);
1962 _dbus_assert (triplet_end <= final_end);
1963 _dbus_assert ((final_end - triplet_end) < 3);
1965 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
1966 #define SIX_BITS_MASK (0x3f)
1967 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
1969 while (s != triplet_end)
1971 unsigned int triplet;
1973 triplet = s[2] | (s[1] << 8) | (s[0] << 16);
1975 /* Encode each 6 bits. */
1977 *d++ = ENCODE_64 (triplet >> 18);
1978 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
1979 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
1980 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
1985 switch (final_end - triplet_end)
1989 unsigned int doublet;
1991 doublet = s[1] | (s[0] << 8);
1993 *d++ = ENCODE_64 (doublet >> 12);
1994 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
1995 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
2001 unsigned int singlet;
2005 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2006 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2015 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2021 * Decodes a string from Base64, as documented in RFC 2045.
2023 * @todo sort out the AUDIT comment in here. The case it mentions
2024 * ("====" or "x===") is not allowed in correct base64, so need to
2025 * decide what to do with that kind of input. Probably ignore it
2026 * since we ignore any other junk seen.
2028 * @param source the string to decode
2029 * @param start byte index to start decode
2030 * @param dest string where decoded data should be placed
2031 * @param insert_at where to place decoded data
2032 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2035 _dbus_string_base64_decode (const DBusString *source,
2044 unsigned int triplet = 0;
2047 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2048 _dbus_assert (source != dest);
2050 source_len = real_source->len - start;
2051 s = real_source->str + start;
2052 end = real_source->str + source_len;
2054 if (source_len == 0)
2057 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2064 /* The idea is to just skip anything that isn't
2065 * a base64 char - it's allowed to have whitespace,
2066 * newlines, etc. in here. We also ignore trailing
2067 * base64 chars, though that's suspicious.
2070 if (*s >= UNBASE64_MIN_CHAR &&
2071 *s <= UNBASE64_MAX_CHAR)
2075 /* '=' is padding, doesn't represent additional data
2076 * but does increment our count.
2085 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2090 triplet |= (unsigned int) val;
2095 if (sextet_count == 4)
2097 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2100 /* AUDIT: Comment doesn't mention 4 pad => 0,
2101 * 3 pad => 1 byte, though the code should
2102 * work fine if those are the required outputs.
2104 * I assume that the spec requires dropping
2105 * the top two bits of, say, ///= which is > 2
2106 * bytes worth of bits. (Or otherwise, you couldn't
2107 * actually represent 2 byte sequences.
2111 _dbus_string_append_byte (&result,
2115 _dbus_string_append_byte (&result,
2116 (triplet >> 8) & 0xff);
2118 _dbus_string_append_byte (&result,
2130 if (!_dbus_string_move (&result, 0, dest, insert_at))
2132 _dbus_string_free (&result);
2136 _dbus_string_free (&result);
2142 * Encodes a string in hex, the way MD5 and SHA-1 are usually
2143 * encoded. (Each byte is two hex digits.)
2145 * @param source the string to encode
2146 * @param start byte index to start encoding
2147 * @param dest string where encoded data should be placed
2148 * @param insert_at where to place encoded data
2149 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2152 _dbus_string_hex_encode (const DBusString *source,
2158 const char hexdigits[16] = {
2159 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2160 'a', 'b', 'c', 'd', 'e', 'f'
2162 const unsigned char *p;
2163 const unsigned char *end;
2166 _dbus_assert (start <= _dbus_string_get_length (source));
2168 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2173 _dbus_string_get_const_data (source, (const char**) &p);
2174 end = p + _dbus_string_get_length (source);
2179 if (!_dbus_string_append_byte (&result,
2180 hexdigits[(*p >> 4)]))
2183 if (!_dbus_string_append_byte (&result,
2184 hexdigits[(*p & 0x0f)]))
2190 if (!_dbus_string_move (&result, 0, dest, insert_at))
2196 _dbus_string_free (&result);
2201 * Decodes a string from hex encoding.
2203 * @param source the string to decode
2204 * @param start byte index to start decode
2205 * @param dest string where decoded data should be placed
2206 * @param insert_at where to place decoded data
2207 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2210 _dbus_string_hex_decode (const DBusString *source,
2216 const unsigned char *p;
2217 const unsigned char *end;
2219 dbus_bool_t high_bits;
2221 _dbus_assert (start <= _dbus_string_get_length (source));
2223 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2229 _dbus_string_get_const_data (source, (const char**) &p);
2230 end = p + _dbus_string_get_length (source);
2295 _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2302 if (!_dbus_string_append_byte (&result,
2311 len = _dbus_string_get_length (&result);
2313 b = _dbus_string_get_byte (&result, len - 1);
2317 _dbus_string_set_byte (&result, len - 1, b);
2320 high_bits = !high_bits;
2325 if (!_dbus_string_move (&result, 0, dest, insert_at))
2331 _dbus_string_free (&result);
2336 * Checks that the given range of the string is valid ASCII with no
2337 * nul bytes. If the given range is not entirely contained in the
2338 * string, returns #FALSE.
2340 * @todo this is inconsistent with most of DBusString in that
2341 * it allows a start,len range that isn't in the string.
2343 * @param str the string
2344 * @param start first byte index to check
2345 * @param len number of bytes to check
2346 * @returns #TRUE if the byte range exists and is all valid ASCII
2349 _dbus_string_validate_ascii (const DBusString *str,
2353 const unsigned char *s;
2354 const unsigned char *end;
2355 DBUS_CONST_STRING_PREAMBLE (str);
2356 _dbus_assert (start >= 0);
2357 _dbus_assert (start <= real->len);
2358 _dbus_assert (len >= 0);
2360 if (len > real->len - start)
2363 s = real->str + start;
2368 ((*s & ~0x7f) != 0))
2378 * Checks that the given range of the string is valid UTF-8. If the
2379 * given range is not entirely contained in the string, returns
2380 * #FALSE. If the string contains any nul bytes in the given range,
2381 * returns #FALSE. If the start and start+len are not on character
2382 * boundaries, returns #FALSE.
2384 * @todo this is inconsistent with most of DBusString in that
2385 * it allows a start,len range that isn't in the string.
2387 * @param str the string
2388 * @param start first byte index to check
2389 * @param len number of bytes to check
2390 * @returns #TRUE if the byte range exists and is all valid UTF-8
2393 _dbus_string_validate_utf8 (const DBusString *str,
2397 const unsigned char *p;
2398 const unsigned char *end;
2399 DBUS_CONST_STRING_PREAMBLE (str);
2400 _dbus_assert (start >= 0);
2401 _dbus_assert (start <= real->len);
2402 _dbus_assert (len >= 0);
2404 if (len > real->len - start)
2407 p = real->str + start;
2412 int i, mask = 0, char_len;
2413 dbus_unichar_t result;
2414 unsigned char c = (unsigned char) *p;
2416 UTF8_COMPUTE (c, mask, char_len);
2421 /* check that the expected number of bytes exists in the remaining length */
2422 if ((end - p) < char_len)
2425 UTF8_GET (result, p, i, mask, char_len);
2427 if (UTF8_LENGTH (result) != char_len) /* Check for overlong UTF-8 */
2430 if (result == (dbus_unichar_t)-1)
2433 if (!UNICODE_VALID (result))
2439 /* See that we covered the entire length if a length was
2449 * Checks that the given range of the string is all nul bytes. If the
2450 * given range is not entirely contained in the string, returns
2453 * @todo this is inconsistent with most of DBusString in that
2454 * it allows a start,len range that isn't in the string.
2456 * @param str the string
2457 * @param start first byte index to check
2458 * @param len number of bytes to check
2459 * @returns #TRUE if the byte range exists and is all nul bytes
2462 _dbus_string_validate_nul (const DBusString *str,
2466 const unsigned char *s;
2467 const unsigned char *end;
2468 DBUS_CONST_STRING_PREAMBLE (str);
2469 _dbus_assert (start >= 0);
2470 _dbus_assert (len >= 0);
2471 _dbus_assert (start <= real->len);
2473 if (len > real->len - start)
2476 s = real->str + start;
2489 * Clears all allocated bytes in the string to zero.
2491 * @param str the string
2494 _dbus_string_zero (DBusString *str)
2496 DBUS_STRING_PREAMBLE (str);
2498 memset (real->str, '\0', real->allocated);
2502 #ifdef DBUS_BUILD_TESTS
2503 #include "dbus-test.h"
2507 test_max_len (DBusString *str,
2512 if (!_dbus_string_set_length (str, max_len - 1))
2513 _dbus_assert_not_reached ("setting len to one less than max should have worked");
2516 if (!_dbus_string_set_length (str, max_len))
2517 _dbus_assert_not_reached ("setting len to max len should have worked");
2519 if (_dbus_string_set_length (str, max_len + 1))
2520 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2522 if (!_dbus_string_set_length (str, 0))
2523 _dbus_assert_not_reached ("setting len to zero should have worked");
2527 test_base64_roundtrip (const unsigned char *data,
2535 len = strlen (data);
2537 if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2538 _dbus_assert_not_reached ("could not init string");
2540 if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2541 _dbus_assert_not_reached ("could not init string");
2543 if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2544 _dbus_assert_not_reached ("could not init string");
2546 if (!_dbus_string_append_len (&orig, data, len))
2547 _dbus_assert_not_reached ("couldn't append orig data");
2549 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2550 _dbus_assert_not_reached ("could not encode");
2552 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2553 _dbus_assert_not_reached ("could not decode");
2555 if (!_dbus_string_equal (&orig, &decoded))
2559 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2560 _dbus_string_get_length (&orig),
2561 _dbus_string_get_length (&encoded),
2562 _dbus_string_get_length (&decoded));
2563 printf ("Original: %s\n", data);
2564 _dbus_string_get_const_data (&decoded, &s);
2565 printf ("Decoded: %s\n", s);
2566 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2569 _dbus_string_free (&orig);
2570 _dbus_string_free (&encoded);
2571 _dbus_string_free (&decoded);
2575 test_hex_roundtrip (const unsigned char *data,
2583 len = strlen (data);
2585 if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2586 _dbus_assert_not_reached ("could not init string");
2588 if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2589 _dbus_assert_not_reached ("could not init string");
2591 if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2592 _dbus_assert_not_reached ("could not init string");
2594 if (!_dbus_string_append_len (&orig, data, len))
2595 _dbus_assert_not_reached ("couldn't append orig data");
2597 if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2598 _dbus_assert_not_reached ("could not encode");
2600 if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2601 _dbus_assert_not_reached ("could not decode");
2603 if (!_dbus_string_equal (&orig, &decoded))
2607 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2608 _dbus_string_get_length (&orig),
2609 _dbus_string_get_length (&encoded),
2610 _dbus_string_get_length (&decoded));
2611 printf ("Original: %s\n", data);
2612 _dbus_string_get_const_data (&decoded, &s);
2613 printf ("Decoded: %s\n", s);
2614 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2617 _dbus_string_free (&orig);
2618 _dbus_string_free (&encoded);
2619 _dbus_string_free (&decoded);
2622 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2625 test_roundtrips (TestRoundtripFunc func)
2627 (* func) ("Hello this is a string\n", -1);
2628 (* func) ("Hello this is a string\n1", -1);
2629 (* func) ("Hello this is a string\n12", -1);
2630 (* func) ("Hello this is a string\n123", -1);
2631 (* func) ("Hello this is a string\n1234", -1);
2632 (* func) ("Hello this is a string\n12345", -1);
2636 (* func) ("123", 3);
2637 (* func) ("1234", 4);
2638 (* func) ("12345", 5);
2642 (* func) ("123", 4);
2643 (* func) ("1234", 5);
2644 (* func) ("12345", 6);
2646 unsigned char buf[512];
2650 while (i < _DBUS_N_ELEMENTS (buf))
2656 while (i < _DBUS_N_ELEMENTS (buf))
2666 * @ingroup DBusStringInternals
2667 * Unit test for DBusString.
2669 * @todo Need to write tests for _dbus_string_copy() and
2670 * _dbus_string_move() moving to/from each of start/middle/end of a
2671 * string. Also need tests for _dbus_string_move_len ()
2673 * @returns #TRUE on success.
2676 _dbus_string_test (void)
2683 int lens[] = { 0, 1, 2, 3, 4, 5, 10, 16, 17, 18, 25, 31, 32, 33, 34, 35, 63, 64, 65, 66, 67, 68, 69, 70, 71, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136 };
2688 while (i < _DBUS_N_ELEMENTS (lens))
2690 if (!_dbus_string_init (&str, lens[i]))
2691 _dbus_assert_not_reached ("failed to init string");
2693 test_max_len (&str, lens[i]);
2694 _dbus_string_free (&str);
2699 /* Test shortening and setting length */
2701 while (i < _DBUS_N_ELEMENTS (lens))
2705 if (!_dbus_string_init (&str, lens[i]))
2706 _dbus_assert_not_reached ("failed to init string");
2708 if (!_dbus_string_set_length (&str, lens[i]))
2709 _dbus_assert_not_reached ("failed to set string length");
2714 _dbus_assert (_dbus_string_get_length (&str) == j);
2717 _dbus_string_shorten (&str, 1);
2718 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2723 _dbus_string_free (&str);
2728 /* Test appending data */
2729 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2730 _dbus_assert_not_reached ("failed to init string");
2735 if (!_dbus_string_append (&str, "a"))
2736 _dbus_assert_not_reached ("failed to append string to string\n");
2738 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2740 if (!_dbus_string_append_byte (&str, 'b'))
2741 _dbus_assert_not_reached ("failed to append byte to string\n");
2743 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2748 _dbus_string_free (&str);
2750 /* Check steal_data */
2752 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2753 _dbus_assert_not_reached ("failed to init string");
2755 if (!_dbus_string_append (&str, "Hello World"))
2756 _dbus_assert_not_reached ("could not append to string");
2758 i = _dbus_string_get_length (&str);
2760 if (!_dbus_string_steal_data (&str, &s))
2761 _dbus_assert_not_reached ("failed to steal data");
2763 _dbus_assert (_dbus_string_get_length (&str) == 0);
2764 _dbus_assert (((int)strlen (s)) == i);
2770 if (!_dbus_string_append (&str, "Hello World"))
2771 _dbus_assert_not_reached ("could not append to string");
2773 i = _dbus_string_get_length (&str);
2775 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2776 _dbus_assert_not_reached ("could not init string");
2778 if (!_dbus_string_move (&str, 0, &other, 0))
2779 _dbus_assert_not_reached ("could not move");
2781 _dbus_assert (_dbus_string_get_length (&str) == 0);
2782 _dbus_assert (_dbus_string_get_length (&other) == i);
2784 if (!_dbus_string_append (&str, "Hello World"))
2785 _dbus_assert_not_reached ("could not append to string");
2787 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2788 _dbus_assert_not_reached ("could not move");
2790 _dbus_assert (_dbus_string_get_length (&str) == 0);
2791 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2793 if (!_dbus_string_append (&str, "Hello World"))
2794 _dbus_assert_not_reached ("could not append to string");
2796 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2797 _dbus_assert_not_reached ("could not move");
2799 _dbus_assert (_dbus_string_get_length (&str) == 0);
2800 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2802 _dbus_string_free (&other);
2806 if (!_dbus_string_append (&str, "Hello World"))
2807 _dbus_assert_not_reached ("could not append to string");
2809 i = _dbus_string_get_length (&str);
2811 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2812 _dbus_assert_not_reached ("could not init string");
2814 if (!_dbus_string_copy (&str, 0, &other, 0))
2815 _dbus_assert_not_reached ("could not copy");
2817 _dbus_assert (_dbus_string_get_length (&str) == i);
2818 _dbus_assert (_dbus_string_get_length (&other) == i);
2820 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2821 _dbus_assert_not_reached ("could not copy");
2823 _dbus_assert (_dbus_string_get_length (&str) == i);
2824 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2825 _dbus_assert (_dbus_string_equal_c_str (&other,
2826 "Hello WorldHello World"));
2828 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2829 _dbus_assert_not_reached ("could not copy");
2831 _dbus_assert (_dbus_string_get_length (&str) == i);
2832 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2833 _dbus_assert (_dbus_string_equal_c_str (&other,
2834 "Hello WorldHello WorldHello World"));
2836 _dbus_string_free (&str);
2837 _dbus_string_free (&other);
2841 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2842 _dbus_assert_not_reached ("failed to init string");
2844 if (!_dbus_string_append (&str, "Hello World"))
2845 _dbus_assert_not_reached ("could not append to string");
2847 i = _dbus_string_get_length (&str);
2849 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2850 _dbus_assert_not_reached ("could not init string");
2852 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2853 &other, 0, _dbus_string_get_length (&other)))
2854 _dbus_assert_not_reached ("could not replace");
2856 _dbus_assert (_dbus_string_get_length (&str) == i);
2857 _dbus_assert (_dbus_string_get_length (&other) == i);
2858 _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
2860 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2862 _dbus_assert_not_reached ("could not replace center space");
2864 _dbus_assert (_dbus_string_get_length (&str) == i);
2865 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2866 _dbus_assert (_dbus_string_equal_c_str (&other,
2867 "HelloHello WorldWorld"));
2870 if (!_dbus_string_replace_len (&str, 1, 1,
2872 _dbus_string_get_length (&other) - 1,
2874 _dbus_assert_not_reached ("could not replace end character");
2876 _dbus_assert (_dbus_string_get_length (&str) == i);
2877 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2878 _dbus_assert (_dbus_string_equal_c_str (&other,
2879 "HelloHello WorldWorle"));
2881 _dbus_string_free (&str);
2882 _dbus_string_free (&other);
2884 /* Check append/get unichar */
2886 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2887 _dbus_assert_not_reached ("failed to init string");
2890 if (!_dbus_string_append_unichar (&str, 0xfffc))
2891 _dbus_assert_not_reached ("failed to append unichar");
2893 _dbus_string_get_unichar (&str, 0, &ch, &i);
2895 _dbus_assert (ch == 0xfffc);
2896 _dbus_assert (i == _dbus_string_get_length (&str));
2898 _dbus_string_free (&str);
2900 /* Check insert/set/get byte */
2902 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2903 _dbus_assert_not_reached ("failed to init string");
2905 if (!_dbus_string_append (&str, "Hello"))
2906 _dbus_assert_not_reached ("failed to append Hello");
2908 _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
2909 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
2910 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
2911 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
2912 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
2914 _dbus_string_set_byte (&str, 1, 'q');
2915 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
2917 if (!_dbus_string_insert_byte (&str, 0, 255))
2918 _dbus_assert_not_reached ("can't insert byte");
2920 if (!_dbus_string_insert_byte (&str, 2, 'Z'))
2921 _dbus_assert_not_reached ("can't insert byte");
2923 if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
2924 _dbus_assert_not_reached ("can't insert byte");
2926 _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
2927 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
2928 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
2929 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
2930 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
2931 _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
2932 _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
2933 _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
2935 _dbus_string_free (&str);
2937 /* Check append/parse int/double */
2939 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2940 _dbus_assert_not_reached ("failed to init string");
2942 if (!_dbus_string_append_int (&str, 27))
2943 _dbus_assert_not_reached ("failed to append int");
2945 i = _dbus_string_get_length (&str);
2947 if (!_dbus_string_parse_int (&str, 0, &v, &end))
2948 _dbus_assert_not_reached ("failed to parse int");
2950 _dbus_assert (v == 27);
2951 _dbus_assert (end == i);
2953 _dbus_string_free (&str);
2955 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2956 _dbus_assert_not_reached ("failed to init string");
2958 if (!_dbus_string_append_double (&str, 50.3))
2959 _dbus_assert_not_reached ("failed to append float");
2961 i = _dbus_string_get_length (&str);
2963 if (!_dbus_string_parse_double (&str, 0, &d, &end))
2964 _dbus_assert_not_reached ("failed to parse float");
2966 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
2967 _dbus_assert (end == i);
2969 _dbus_string_free (&str);
2972 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2973 _dbus_assert_not_reached ("failed to init string");
2975 if (!_dbus_string_append (&str, "Hello"))
2976 _dbus_assert_not_reached ("couldn't append to string");
2978 if (!_dbus_string_find (&str, 0, "He", &i))
2979 _dbus_assert_not_reached ("didn't find 'He'");
2980 _dbus_assert (i == 0);
2982 if (!_dbus_string_find (&str, 0, "Hello", &i))
2983 _dbus_assert_not_reached ("didn't find 'Hello'");
2984 _dbus_assert (i == 0);
2986 if (!_dbus_string_find (&str, 0, "ello", &i))
2987 _dbus_assert_not_reached ("didn't find 'ello'");
2988 _dbus_assert (i == 1);
2990 if (!_dbus_string_find (&str, 0, "lo", &i))
2991 _dbus_assert_not_reached ("didn't find 'lo'");
2992 _dbus_assert (i == 3);
2994 if (!_dbus_string_find (&str, 2, "lo", &i))
2995 _dbus_assert_not_reached ("didn't find 'lo'");
2996 _dbus_assert (i == 3);
2998 if (_dbus_string_find (&str, 4, "lo", &i))
2999 _dbus_assert_not_reached ("did find 'lo'");
3001 if (!_dbus_string_find (&str, 0, "l", &i))
3002 _dbus_assert_not_reached ("didn't find 'l'");
3003 _dbus_assert (i == 2);
3005 if (!_dbus_string_find (&str, 0, "H", &i))
3006 _dbus_assert_not_reached ("didn't find 'H'");
3007 _dbus_assert (i == 0);
3009 if (!_dbus_string_find (&str, 0, "", &i))
3010 _dbus_assert_not_reached ("didn't find ''");
3011 _dbus_assert (i == 0);
3013 if (_dbus_string_find (&str, 0, "Hello!", NULL))
3014 _dbus_assert_not_reached ("Did find 'Hello!'");
3016 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
3017 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
3019 if (_dbus_string_find (&str, 0, "ill", NULL))
3020 _dbus_assert_not_reached ("Did find 'ill'");
3022 if (_dbus_string_find (&str, 0, "q", NULL))
3023 _dbus_assert_not_reached ("Did find 'q'");
3025 if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
3026 _dbus_assert_not_reached ("Didn't find 'He'");
3028 if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
3029 _dbus_assert_not_reached ("Did find 'Hello'");
3031 _dbus_string_free (&str);
3033 /* Base 64 and Hex encoding */
3034 test_roundtrips (test_base64_roundtrip);
3035 test_roundtrips (test_hex_roundtrip);
3040 #endif /* DBUS_BUILD_TESTS */