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 from GLib */
1157 /** computes length and mask of a unicode character
1158 * @param Char the char
1159 * @param Mask the mask variable to assign to
1160 * @param Len the length variable to assign to
1162 #define UTF8_COMPUTE(Char, Mask, Len) \
1168 else if ((Char & 0xe0) == 0xc0) \
1173 else if ((Char & 0xf0) == 0xe0) \
1178 else if ((Char & 0xf8) == 0xf0) \
1183 else if ((Char & 0xfc) == 0xf8) \
1188 else if ((Char & 0xfe) == 0xfc) \
1197 * computes length of a unicode character in UTF-8
1198 * @param Char the char
1200 #define UTF8_LENGTH(Char) \
1201 ((Char) < 0x80 ? 1 : \
1202 ((Char) < 0x800 ? 2 : \
1203 ((Char) < 0x10000 ? 3 : \
1204 ((Char) < 0x200000 ? 4 : \
1205 ((Char) < 0x4000000 ? 5 : 6)))))
1208 * Gets a UTF-8 value.
1210 * @param Result variable for extracted unicode char.
1211 * @param Chars the bytes to decode
1212 * @param Count counter variable
1213 * @param Mask mask for this char
1214 * @param Len length for this char in bytes
1216 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
1217 (Result) = (Chars)[0] & (Mask); \
1218 for ((Count) = 1; (Count) < (Len); ++(Count)) \
1220 if (((Chars)[(Count)] & 0xc0) != 0x80) \
1226 (Result) |= ((Chars)[(Count)] & 0x3f); \
1230 * Check whether a unicode char is in a valid range.
1232 * @param Char the character
1234 #define UNICODE_VALID(Char) \
1235 ((Char) < 0x110000 && \
1236 ((Char) < 0xD800 || (Char) >= 0xE000) && \
1237 (Char) != 0xFFFE && (Char) != 0xFFFF)
1240 * Gets a unicode character from a UTF-8 string. Does no validation;
1241 * you must verify that the string is valid UTF-8 in advance and must
1242 * pass in the start of a character.
1244 * @param str the string
1245 * @param start the start of the UTF-8 character.
1246 * @param ch_return location to return the character
1247 * @param end_return location to return the byte index of next character
1250 _dbus_string_get_unichar (const DBusString *str,
1252 dbus_unichar_t *ch_return,
1256 dbus_unichar_t result;
1259 DBUS_CONST_STRING_PREAMBLE (str);
1260 _dbus_assert (start >= 0);
1261 _dbus_assert (start <= real->len);
1266 *end_return = real->len;
1269 p = real->str + start;
1272 UTF8_COMPUTE (c, mask, len);
1275 UTF8_GET (result, p, i, mask, len);
1277 if (result == (dbus_unichar_t)-1)
1281 *ch_return = result;
1283 *end_return = start + len;
1287 * Finds the given substring in the string,
1288 * returning #TRUE and filling in the byte index
1289 * where the substring was found, if it was found.
1290 * Returns #FALSE if the substring wasn't found.
1291 * Sets *start to the length of the string if the substring
1294 * @param str the string
1295 * @param start where to start looking
1296 * @param substr the substring
1297 * @param found return location for where it was found, or #NULL
1298 * @returns #TRUE if found
1301 _dbus_string_find (const DBusString *str,
1306 return _dbus_string_find_to (str, start,
1307 ((const DBusRealString*)str)->len,
1312 * Finds the given substring in the string,
1313 * up to a certain position,
1314 * returning #TRUE and filling in the byte index
1315 * where the substring was found, if it was found.
1316 * Returns #FALSE if the substring wasn't found.
1317 * Sets *start to the length of the string if the substring
1320 * @param str the string
1321 * @param start where to start looking
1322 * @param end where to stop looking
1323 * @param substr the substring
1324 * @param found return location for where it was found, or #NULL
1325 * @returns #TRUE if found
1328 _dbus_string_find_to (const DBusString *str,
1335 DBUS_CONST_STRING_PREAMBLE (str);
1336 _dbus_assert (substr != NULL);
1337 _dbus_assert (start <= real->len);
1338 _dbus_assert (start >= 0);
1339 _dbus_assert (substr != NULL);
1340 _dbus_assert (end <= real->len);
1341 _dbus_assert (start <= end);
1343 /* we always "find" an empty string */
1344 if (*substr == '\0')
1354 if (real->str[i] == substr[0])
1360 if (substr[j - i] == '\0')
1362 else if (real->str[j] != substr[j - i])
1368 if (substr[j - i] == '\0')
1386 * Finds a blank (space or tab) in the string. Returns #TRUE
1387 * if found, #FALSE otherwise. If a blank is not found sets
1388 * *found to the length of the string.
1390 * @param str the string
1391 * @param start byte index to start looking
1392 * @param found place to store the location of the first blank
1393 * @returns #TRUE if a blank was found
1396 _dbus_string_find_blank (const DBusString *str,
1401 DBUS_CONST_STRING_PREAMBLE (str);
1402 _dbus_assert (start <= real->len);
1403 _dbus_assert (start >= 0);
1406 while (i < real->len)
1408 if (real->str[i] == ' ' ||
1409 real->str[i] == '\t')
1426 * Skips blanks from start, storing the first non-blank in *end
1428 * @param str the string
1429 * @param start where to start
1430 * @param end where to store the first non-blank byte index
1433 _dbus_string_skip_blank (const DBusString *str,
1438 DBUS_CONST_STRING_PREAMBLE (str);
1439 _dbus_assert (start <= real->len);
1440 _dbus_assert (start >= 0);
1443 while (i < real->len)
1445 if (!(real->str[i] == ' ' ||
1446 real->str[i] == '\t'))
1452 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1453 real->str[i] == '\t'));
1460 * Assigns a newline-terminated or \r\n-terminated line from the front
1461 * of the string to the given dest string. The dest string's previous
1462 * contents are deleted. If the source string contains no newline,
1463 * moves the entire source string to the dest string.
1465 * @todo owen correctly notes that this is a stupid function (it was
1466 * written purely for test code,
1467 * e.g. dbus-message-builder.c). Probably should be enforced as test
1468 * code only with #ifdef DBUS_BUILD_TESTS
1470 * @param source the source string
1471 * @param dest the destination string (contents are replaced)
1472 * @returns #FALSE if no memory, or source has length 0
1475 _dbus_string_pop_line (DBusString *source,
1479 dbus_bool_t have_newline;
1481 _dbus_string_set_length (dest, 0);
1484 if (_dbus_string_find (source, 0, "\n", &eol))
1486 have_newline = TRUE;
1487 eol += 1; /* include newline */
1491 eol = _dbus_string_get_length (source);
1492 have_newline = FALSE;
1496 return FALSE; /* eof */
1498 if (!_dbus_string_move_len (source, 0, eol,
1504 /* dump the newline and the \r if we have one */
1507 dbus_bool_t have_cr;
1509 _dbus_assert (_dbus_string_get_length (dest) > 0);
1511 if (_dbus_string_get_length (dest) > 1 &&
1512 _dbus_string_get_byte (dest,
1513 _dbus_string_get_length (dest) - 2) == '\r')
1518 _dbus_string_set_length (dest,
1519 _dbus_string_get_length (dest) -
1527 * Deletes up to and including the first blank space
1530 * @param str the string
1533 _dbus_string_delete_first_word (DBusString *str)
1537 if (_dbus_string_find_blank (str, 0, &i))
1538 _dbus_string_skip_blank (str, i, &i);
1540 _dbus_string_delete (str, 0, i);
1544 * Deletes any leading blanks in the string
1546 * @param str the string
1549 _dbus_string_delete_leading_blanks (DBusString *str)
1553 _dbus_string_skip_blank (str, 0, &i);
1556 _dbus_string_delete (str, 0, i);
1560 * Tests two DBusString for equality.
1562 * @todo memcmp is probably faster
1564 * @param a first string
1565 * @param b second string
1566 * @returns #TRUE if equal
1569 _dbus_string_equal (const DBusString *a,
1570 const DBusString *b)
1572 const unsigned char *ap;
1573 const unsigned char *bp;
1574 const unsigned char *a_end;
1575 const DBusRealString *real_a = (const DBusRealString*) a;
1576 const DBusRealString *real_b = (const DBusRealString*) b;
1577 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1578 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1580 if (real_a->len != real_b->len)
1585 a_end = real_a->str + real_a->len;
1599 * Tests two DBusString for equality up to the given length.
1601 * @todo write a unit test
1603 * @todo memcmp is probably faster
1605 * @param a first string
1606 * @param b second string
1607 * @param len the lengh
1608 * @returns #TRUE if equal for the given number of bytes
1611 _dbus_string_equal_len (const DBusString *a,
1612 const DBusString *b,
1615 const unsigned char *ap;
1616 const unsigned char *bp;
1617 const unsigned char *a_end;
1618 const DBusRealString *real_a = (const DBusRealString*) a;
1619 const DBusRealString *real_b = (const DBusRealString*) b;
1620 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1621 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1623 if (real_a->len != real_b->len &&
1624 (real_a->len < len || real_b->len < len))
1629 a_end = real_a->str + MIN (real_a->len, len);
1643 * Checks whether a string is equal to a C string.
1645 * @param a the string
1646 * @param c_str the C string
1647 * @returns #TRUE if equal
1650 _dbus_string_equal_c_str (const DBusString *a,
1653 const unsigned char *ap;
1654 const unsigned char *bp;
1655 const unsigned char *a_end;
1656 const DBusRealString *real_a = (const DBusRealString*) a;
1657 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1658 _dbus_assert (c_str != NULL);
1661 bp = (const unsigned char*) c_str;
1662 a_end = real_a->str + real_a->len;
1663 while (ap != a_end && *bp)
1672 if (ap != a_end || *bp)
1679 * Checks whether a string starts with the given C string.
1681 * @param a the string
1682 * @param c_str the C string
1683 * @returns #TRUE if string starts with it
1686 _dbus_string_starts_with_c_str (const DBusString *a,
1689 const unsigned char *ap;
1690 const unsigned char *bp;
1691 const unsigned char *a_end;
1692 const DBusRealString *real_a = (const DBusRealString*) a;
1693 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1694 _dbus_assert (c_str != NULL);
1697 bp = (const unsigned char*) c_str;
1698 a_end = real_a->str + real_a->len;
1699 while (ap != a_end && *bp)
1715 * Returns whether a string ends with the given suffix
1717 * @todo memcmp might make this faster.
1719 * @param a the string
1720 * @param c_str the C-style string
1721 * @returns #TRUE if the string ends with the suffix
1724 _dbus_string_ends_with_c_str (const DBusString *a,
1727 const unsigned char *ap;
1728 const unsigned char *bp;
1729 const unsigned char *a_end;
1730 unsigned long c_str_len;
1731 const DBusRealString *real_a = (const DBusRealString*) a;
1732 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1733 _dbus_assert (c_str != NULL);
1735 c_str_len = strlen (c_str);
1736 if (((unsigned long)real_a->len) < c_str_len)
1739 ap = real_a->str + (real_a->len - c_str_len);
1740 bp = (const unsigned char*) c_str;
1741 a_end = real_a->str + real_a->len;
1751 _dbus_assert (*ap == '\0');
1752 _dbus_assert (*bp == '\0');
1757 static const signed char base64_table[] = {
1824 /** The minimum char that's a valid char in Base64-encoded text */
1825 #define UNBASE64_MIN_CHAR (43)
1826 /** The maximum char that's a valid char in Base64-encoded text */
1827 #define UNBASE64_MAX_CHAR (122)
1828 /** Must subtract this from a char's integer value before offsetting
1829 * into unbase64_table
1831 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1832 static const signed char unbase64_table[] = {
1916 * Encodes a string using Base64, as documented in RFC 2045.
1918 * @param source the string to encode
1919 * @param start byte index to start encoding
1920 * @param dest string where encoded data should be placed
1921 * @param insert_at where to place encoded data
1922 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
1925 _dbus_string_base64_encode (const DBusString *source,
1931 unsigned int dest_len; /* unsigned for overflow checks below */
1932 const unsigned char *s;
1934 const unsigned char *triplet_end;
1935 const unsigned char *final_end;
1936 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1937 _dbus_assert (source != dest);
1939 /* For each 24 bits (3 bytes) of input, we have 4 bytes of
1942 source_len = real_source->len - start;
1943 dest_len = (source_len / 3) * 4;
1944 if (source_len % 3 != 0)
1947 if (dest_len > (unsigned int) real_dest->max_length)
1950 if (source_len == 0)
1953 if (!open_gap (dest_len, real_dest, insert_at))
1956 d = real_dest->str + insert_at;
1957 s = real_source->str + start;
1958 final_end = real_source->str + (start + source_len);
1959 triplet_end = final_end - (source_len % 3);
1960 _dbus_assert (triplet_end <= final_end);
1961 _dbus_assert ((final_end - triplet_end) < 3);
1963 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
1964 #define SIX_BITS_MASK (0x3f)
1965 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
1967 while (s != triplet_end)
1969 unsigned int triplet;
1971 triplet = s[2] | (s[1] << 8) | (s[0] << 16);
1973 /* Encode each 6 bits. */
1975 *d++ = ENCODE_64 (triplet >> 18);
1976 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
1977 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
1978 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
1983 switch (final_end - triplet_end)
1987 unsigned int doublet;
1989 doublet = s[1] | (s[0] << 8);
1991 *d++ = ENCODE_64 (doublet >> 12);
1992 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
1993 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
1999 unsigned int singlet;
2003 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2004 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2013 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2019 * Decodes a string from Base64, as documented in RFC 2045.
2021 * @todo sort out the AUDIT comment in here. The case it mentions
2022 * ("====" or "x===") is not allowed in correct base64, so need to
2023 * decide what to do with that kind of input. Probably ignore it
2024 * since we ignore any other junk seen.
2026 * @param source the string to decode
2027 * @param start byte index to start decode
2028 * @param dest string where decoded data should be placed
2029 * @param insert_at where to place decoded data
2030 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2033 _dbus_string_base64_decode (const DBusString *source,
2042 unsigned int triplet = 0;
2045 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2046 _dbus_assert (source != dest);
2048 source_len = real_source->len - start;
2049 s = real_source->str + start;
2050 end = real_source->str + source_len;
2052 if (source_len == 0)
2055 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2062 /* The idea is to just skip anything that isn't
2063 * a base64 char - it's allowed to have whitespace,
2064 * newlines, etc. in here. We also ignore trailing
2065 * base64 chars, though that's suspicious.
2068 if (*s >= UNBASE64_MIN_CHAR &&
2069 *s <= UNBASE64_MAX_CHAR)
2073 /* '=' is padding, doesn't represent additional data
2074 * but does increment our count.
2083 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2088 triplet |= (unsigned int) val;
2093 if (sextet_count == 4)
2095 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2098 /* AUDIT: Comment doesn't mention 4 pad => 0,
2099 * 3 pad => 1 byte, though the code should
2100 * work fine if those are the required outputs.
2102 * I assume that the spec requires dropping
2103 * the top two bits of, say, ///= which is > 2
2104 * bytes worth of bits. (Or otherwise, you couldn't
2105 * actually represent 2 byte sequences.
2109 _dbus_string_append_byte (&result,
2113 _dbus_string_append_byte (&result,
2114 (triplet >> 8) & 0xff);
2116 _dbus_string_append_byte (&result,
2128 if (!_dbus_string_move (&result, 0, dest, insert_at))
2130 _dbus_string_free (&result);
2134 _dbus_string_free (&result);
2140 * Encodes a string in hex, the way MD5 and SHA-1 are usually
2141 * encoded. (Each byte is two hex digits.)
2143 * @param source the string to encode
2144 * @param start byte index to start encoding
2145 * @param dest string where encoded data should be placed
2146 * @param insert_at where to place encoded data
2147 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2150 _dbus_string_hex_encode (const DBusString *source,
2156 const char hexdigits[16] = {
2157 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2158 'a', 'b', 'c', 'd', 'e', 'f'
2160 const unsigned char *p;
2161 const unsigned char *end;
2164 _dbus_assert (start <= _dbus_string_get_length (source));
2166 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2171 _dbus_string_get_const_data (source, (const char**) &p);
2172 end = p + _dbus_string_get_length (source);
2177 if (!_dbus_string_append_byte (&result,
2178 hexdigits[(*p >> 4)]))
2181 if (!_dbus_string_append_byte (&result,
2182 hexdigits[(*p & 0x0f)]))
2188 if (!_dbus_string_move (&result, 0, dest, insert_at))
2194 _dbus_string_free (&result);
2199 * Decodes a string from hex encoding.
2201 * @param source the string to decode
2202 * @param start byte index to start decode
2203 * @param dest string where decoded data should be placed
2204 * @param insert_at where to place decoded data
2205 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2208 _dbus_string_hex_decode (const DBusString *source,
2214 const unsigned char *p;
2215 const unsigned char *end;
2217 dbus_bool_t high_bits;
2219 _dbus_assert (start <= _dbus_string_get_length (source));
2221 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2227 _dbus_string_get_const_data (source, (const char**) &p);
2228 end = p + _dbus_string_get_length (source);
2293 _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2300 if (!_dbus_string_append_byte (&result,
2309 len = _dbus_string_get_length (&result);
2311 b = _dbus_string_get_byte (&result, len - 1);
2315 _dbus_string_set_byte (&result, len - 1, b);
2318 high_bits = !high_bits;
2323 if (!_dbus_string_move (&result, 0, dest, insert_at))
2329 _dbus_string_free (&result);
2334 * Checks that the given range of the string is valid ASCII with no
2335 * nul bytes. If the given range is not entirely contained in the
2336 * string, returns #FALSE.
2338 * @todo this is inconsistent with most of DBusString in that
2339 * it allows a start,len range that isn't in the string.
2341 * @param str the string
2342 * @param start first byte index to check
2343 * @param len number of bytes to check
2344 * @returns #TRUE if the byte range exists and is all valid ASCII
2347 _dbus_string_validate_ascii (const DBusString *str,
2351 const unsigned char *s;
2352 const unsigned char *end;
2353 DBUS_CONST_STRING_PREAMBLE (str);
2354 _dbus_assert (start >= 0);
2355 _dbus_assert (start <= real->len);
2356 _dbus_assert (len >= 0);
2358 if (len > real->len - start)
2361 s = real->str + start;
2366 ((*s & ~0x7f) != 0))
2376 * Checks that the given range of the string is valid UTF-8. If the
2377 * given range is not entirely contained in the string, returns
2378 * #FALSE. If the string contains any nul bytes in the given range,
2381 * @todo right now just calls _dbus_string_validate_ascii()
2383 * @todo this is inconsistent with most of DBusString in that
2384 * it allows a start,len range that isn't in the string.
2386 * @param str the string
2387 * @param start first byte index to check
2388 * @param len number of bytes to check
2389 * @returns #TRUE if the byte range exists and is all valid UTF-8
2392 _dbus_string_validate_utf8 (const DBusString *str,
2396 /* FIXME actually validate UTF-8 */
2399 /*return _dbus_string_validate_ascii (str, start, len);*/
2403 * Checks that the given range of the string is all nul bytes. If the
2404 * given range is not entirely contained in the string, returns
2407 * @todo this is inconsistent with most of DBusString in that
2408 * it allows a start,len range that isn't in the string.
2410 * @param str the string
2411 * @param start first byte index to check
2412 * @param len number of bytes to check
2413 * @returns #TRUE if the byte range exists and is all nul bytes
2416 _dbus_string_validate_nul (const DBusString *str,
2420 const unsigned char *s;
2421 const unsigned char *end;
2422 DBUS_CONST_STRING_PREAMBLE (str);
2423 _dbus_assert (start >= 0);
2424 _dbus_assert (len >= 0);
2425 _dbus_assert (start <= real->len);
2427 if (len > real->len - start)
2430 s = real->str + start;
2443 * Clears all allocated bytes in the string to zero.
2445 * @param str the string
2448 _dbus_string_zero (DBusString *str)
2450 DBUS_STRING_PREAMBLE (str);
2452 memset (real->str, '\0', real->allocated);
2456 #ifdef DBUS_BUILD_TESTS
2457 #include "dbus-test.h"
2461 test_max_len (DBusString *str,
2466 if (!_dbus_string_set_length (str, max_len - 1))
2467 _dbus_assert_not_reached ("setting len to one less than max should have worked");
2470 if (!_dbus_string_set_length (str, max_len))
2471 _dbus_assert_not_reached ("setting len to max len should have worked");
2473 if (_dbus_string_set_length (str, max_len + 1))
2474 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2476 if (!_dbus_string_set_length (str, 0))
2477 _dbus_assert_not_reached ("setting len to zero should have worked");
2481 test_base64_roundtrip (const unsigned char *data,
2489 len = strlen (data);
2491 if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2492 _dbus_assert_not_reached ("could not init string");
2494 if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2495 _dbus_assert_not_reached ("could not init string");
2497 if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2498 _dbus_assert_not_reached ("could not init string");
2500 if (!_dbus_string_append_len (&orig, data, len))
2501 _dbus_assert_not_reached ("couldn't append orig data");
2503 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2504 _dbus_assert_not_reached ("could not encode");
2506 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2507 _dbus_assert_not_reached ("could not decode");
2509 if (!_dbus_string_equal (&orig, &decoded))
2513 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2514 _dbus_string_get_length (&orig),
2515 _dbus_string_get_length (&encoded),
2516 _dbus_string_get_length (&decoded));
2517 printf ("Original: %s\n", data);
2518 _dbus_string_get_const_data (&decoded, &s);
2519 printf ("Decoded: %s\n", s);
2520 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2523 _dbus_string_free (&orig);
2524 _dbus_string_free (&encoded);
2525 _dbus_string_free (&decoded);
2529 test_hex_roundtrip (const unsigned char *data,
2537 len = strlen (data);
2539 if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2540 _dbus_assert_not_reached ("could not init string");
2542 if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2543 _dbus_assert_not_reached ("could not init string");
2545 if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2546 _dbus_assert_not_reached ("could not init string");
2548 if (!_dbus_string_append_len (&orig, data, len))
2549 _dbus_assert_not_reached ("couldn't append orig data");
2551 if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2552 _dbus_assert_not_reached ("could not encode");
2554 if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2555 _dbus_assert_not_reached ("could not decode");
2557 if (!_dbus_string_equal (&orig, &decoded))
2561 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2562 _dbus_string_get_length (&orig),
2563 _dbus_string_get_length (&encoded),
2564 _dbus_string_get_length (&decoded));
2565 printf ("Original: %s\n", data);
2566 _dbus_string_get_const_data (&decoded, &s);
2567 printf ("Decoded: %s\n", s);
2568 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2571 _dbus_string_free (&orig);
2572 _dbus_string_free (&encoded);
2573 _dbus_string_free (&decoded);
2576 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2579 test_roundtrips (TestRoundtripFunc func)
2581 (* func) ("Hello this is a string\n", -1);
2582 (* func) ("Hello this is a string\n1", -1);
2583 (* func) ("Hello this is a string\n12", -1);
2584 (* func) ("Hello this is a string\n123", -1);
2585 (* func) ("Hello this is a string\n1234", -1);
2586 (* func) ("Hello this is a string\n12345", -1);
2590 (* func) ("123", 3);
2591 (* func) ("1234", 4);
2592 (* func) ("12345", 5);
2596 (* func) ("123", 4);
2597 (* func) ("1234", 5);
2598 (* func) ("12345", 6);
2600 unsigned char buf[512];
2604 while (i < _DBUS_N_ELEMENTS (buf))
2610 while (i < _DBUS_N_ELEMENTS (buf))
2620 * @ingroup DBusStringInternals
2621 * Unit test for DBusString.
2623 * @todo Need to write tests for _dbus_string_copy() and
2624 * _dbus_string_move() moving to/from each of start/middle/end of a
2625 * string. Also need tests for _dbus_string_move_len ()
2627 * @returns #TRUE on success.
2630 _dbus_string_test (void)
2637 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 };
2642 while (i < _DBUS_N_ELEMENTS (lens))
2644 if (!_dbus_string_init (&str, lens[i]))
2645 _dbus_assert_not_reached ("failed to init string");
2647 test_max_len (&str, lens[i]);
2648 _dbus_string_free (&str);
2653 /* Test shortening and setting length */
2655 while (i < _DBUS_N_ELEMENTS (lens))
2659 if (!_dbus_string_init (&str, lens[i]))
2660 _dbus_assert_not_reached ("failed to init string");
2662 if (!_dbus_string_set_length (&str, lens[i]))
2663 _dbus_assert_not_reached ("failed to set string length");
2668 _dbus_assert (_dbus_string_get_length (&str) == j);
2671 _dbus_string_shorten (&str, 1);
2672 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2677 _dbus_string_free (&str);
2682 /* Test appending data */
2683 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2684 _dbus_assert_not_reached ("failed to init string");
2689 if (!_dbus_string_append (&str, "a"))
2690 _dbus_assert_not_reached ("failed to append string to string\n");
2692 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2694 if (!_dbus_string_append_byte (&str, 'b'))
2695 _dbus_assert_not_reached ("failed to append byte to string\n");
2697 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2702 _dbus_string_free (&str);
2704 /* Check steal_data */
2706 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2707 _dbus_assert_not_reached ("failed to init string");
2709 if (!_dbus_string_append (&str, "Hello World"))
2710 _dbus_assert_not_reached ("could not append to string");
2712 i = _dbus_string_get_length (&str);
2714 if (!_dbus_string_steal_data (&str, &s))
2715 _dbus_assert_not_reached ("failed to steal data");
2717 _dbus_assert (_dbus_string_get_length (&str) == 0);
2718 _dbus_assert (((int)strlen (s)) == i);
2724 if (!_dbus_string_append (&str, "Hello World"))
2725 _dbus_assert_not_reached ("could not append to string");
2727 i = _dbus_string_get_length (&str);
2729 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2730 _dbus_assert_not_reached ("could not init string");
2732 if (!_dbus_string_move (&str, 0, &other, 0))
2733 _dbus_assert_not_reached ("could not move");
2735 _dbus_assert (_dbus_string_get_length (&str) == 0);
2736 _dbus_assert (_dbus_string_get_length (&other) == i);
2738 if (!_dbus_string_append (&str, "Hello World"))
2739 _dbus_assert_not_reached ("could not append to string");
2741 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2742 _dbus_assert_not_reached ("could not move");
2744 _dbus_assert (_dbus_string_get_length (&str) == 0);
2745 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2747 if (!_dbus_string_append (&str, "Hello World"))
2748 _dbus_assert_not_reached ("could not append to string");
2750 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2751 _dbus_assert_not_reached ("could not move");
2753 _dbus_assert (_dbus_string_get_length (&str) == 0);
2754 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2756 _dbus_string_free (&other);
2760 if (!_dbus_string_append (&str, "Hello World"))
2761 _dbus_assert_not_reached ("could not append to string");
2763 i = _dbus_string_get_length (&str);
2765 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2766 _dbus_assert_not_reached ("could not init string");
2768 if (!_dbus_string_copy (&str, 0, &other, 0))
2769 _dbus_assert_not_reached ("could not copy");
2771 _dbus_assert (_dbus_string_get_length (&str) == i);
2772 _dbus_assert (_dbus_string_get_length (&other) == i);
2774 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2775 _dbus_assert_not_reached ("could not copy");
2777 _dbus_assert (_dbus_string_get_length (&str) == i);
2778 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2779 _dbus_assert (_dbus_string_equal_c_str (&other,
2780 "Hello WorldHello World"));
2782 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2783 _dbus_assert_not_reached ("could not copy");
2785 _dbus_assert (_dbus_string_get_length (&str) == i);
2786 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2787 _dbus_assert (_dbus_string_equal_c_str (&other,
2788 "Hello WorldHello WorldHello World"));
2790 _dbus_string_free (&str);
2791 _dbus_string_free (&other);
2795 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2796 _dbus_assert_not_reached ("failed to init string");
2798 if (!_dbus_string_append (&str, "Hello World"))
2799 _dbus_assert_not_reached ("could not append to string");
2801 i = _dbus_string_get_length (&str);
2803 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2804 _dbus_assert_not_reached ("could not init string");
2806 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2807 &other, 0, _dbus_string_get_length (&other)))
2808 _dbus_assert_not_reached ("could not replace");
2810 _dbus_assert (_dbus_string_get_length (&str) == i);
2811 _dbus_assert (_dbus_string_get_length (&other) == i);
2812 _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
2814 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2816 _dbus_assert_not_reached ("could not replace center space");
2818 _dbus_assert (_dbus_string_get_length (&str) == i);
2819 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2820 _dbus_assert (_dbus_string_equal_c_str (&other,
2821 "HelloHello WorldWorld"));
2824 if (!_dbus_string_replace_len (&str, 1, 1,
2826 _dbus_string_get_length (&other) - 1,
2828 _dbus_assert_not_reached ("could not replace end character");
2830 _dbus_assert (_dbus_string_get_length (&str) == i);
2831 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2832 _dbus_assert (_dbus_string_equal_c_str (&other,
2833 "HelloHello WorldWorle"));
2835 _dbus_string_free (&str);
2836 _dbus_string_free (&other);
2838 /* Check append/get unichar */
2840 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2841 _dbus_assert_not_reached ("failed to init string");
2844 if (!_dbus_string_append_unichar (&str, 0xfffc))
2845 _dbus_assert_not_reached ("failed to append unichar");
2847 _dbus_string_get_unichar (&str, 0, &ch, &i);
2849 _dbus_assert (ch == 0xfffc);
2850 _dbus_assert (i == _dbus_string_get_length (&str));
2852 _dbus_string_free (&str);
2854 /* Check insert/set/get byte */
2856 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2857 _dbus_assert_not_reached ("failed to init string");
2859 if (!_dbus_string_append (&str, "Hello"))
2860 _dbus_assert_not_reached ("failed to append Hello");
2862 _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
2863 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
2864 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
2865 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
2866 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
2868 _dbus_string_set_byte (&str, 1, 'q');
2869 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
2871 if (!_dbus_string_insert_byte (&str, 0, 255))
2872 _dbus_assert_not_reached ("can't insert byte");
2874 if (!_dbus_string_insert_byte (&str, 2, 'Z'))
2875 _dbus_assert_not_reached ("can't insert byte");
2877 if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
2878 _dbus_assert_not_reached ("can't insert byte");
2880 _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
2881 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
2882 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
2883 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
2884 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
2885 _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
2886 _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
2887 _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
2889 _dbus_string_free (&str);
2891 /* Check append/parse int/double */
2893 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2894 _dbus_assert_not_reached ("failed to init string");
2896 if (!_dbus_string_append_int (&str, 27))
2897 _dbus_assert_not_reached ("failed to append int");
2899 i = _dbus_string_get_length (&str);
2901 if (!_dbus_string_parse_int (&str, 0, &v, &end))
2902 _dbus_assert_not_reached ("failed to parse int");
2904 _dbus_assert (v == 27);
2905 _dbus_assert (end == i);
2907 _dbus_string_free (&str);
2909 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2910 _dbus_assert_not_reached ("failed to init string");
2912 if (!_dbus_string_append_double (&str, 50.3))
2913 _dbus_assert_not_reached ("failed to append float");
2915 i = _dbus_string_get_length (&str);
2917 if (!_dbus_string_parse_double (&str, 0, &d, &end))
2918 _dbus_assert_not_reached ("failed to parse float");
2920 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
2921 _dbus_assert (end == i);
2923 _dbus_string_free (&str);
2926 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2927 _dbus_assert_not_reached ("failed to init string");
2929 if (!_dbus_string_append (&str, "Hello"))
2930 _dbus_assert_not_reached ("couldn't append to string");
2932 if (!_dbus_string_find (&str, 0, "He", &i))
2933 _dbus_assert_not_reached ("didn't find 'He'");
2934 _dbus_assert (i == 0);
2936 if (!_dbus_string_find (&str, 0, "Hello", &i))
2937 _dbus_assert_not_reached ("didn't find 'Hello'");
2938 _dbus_assert (i == 0);
2940 if (!_dbus_string_find (&str, 0, "ello", &i))
2941 _dbus_assert_not_reached ("didn't find 'ello'");
2942 _dbus_assert (i == 1);
2944 if (!_dbus_string_find (&str, 0, "lo", &i))
2945 _dbus_assert_not_reached ("didn't find 'lo'");
2946 _dbus_assert (i == 3);
2948 if (!_dbus_string_find (&str, 2, "lo", &i))
2949 _dbus_assert_not_reached ("didn't find 'lo'");
2950 _dbus_assert (i == 3);
2952 if (_dbus_string_find (&str, 4, "lo", &i))
2953 _dbus_assert_not_reached ("did find 'lo'");
2955 if (!_dbus_string_find (&str, 0, "l", &i))
2956 _dbus_assert_not_reached ("didn't find 'l'");
2957 _dbus_assert (i == 2);
2959 if (!_dbus_string_find (&str, 0, "H", &i))
2960 _dbus_assert_not_reached ("didn't find 'H'");
2961 _dbus_assert (i == 0);
2963 if (!_dbus_string_find (&str, 0, "", &i))
2964 _dbus_assert_not_reached ("didn't find ''");
2965 _dbus_assert (i == 0);
2967 if (_dbus_string_find (&str, 0, "Hello!", NULL))
2968 _dbus_assert_not_reached ("Did find 'Hello!'");
2970 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
2971 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
2973 if (_dbus_string_find (&str, 0, "ill", NULL))
2974 _dbus_assert_not_reached ("Did find 'ill'");
2976 if (_dbus_string_find (&str, 0, "q", NULL))
2977 _dbus_assert_not_reached ("Did find 'q'");
2979 if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
2980 _dbus_assert_not_reached ("Didn't find 'He'");
2982 if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
2983 _dbus_assert_not_reached ("Did find 'Hello'");
2985 _dbus_string_free (&str);
2987 /* Base 64 and Hex encoding */
2988 test_roundtrips (test_base64_roundtrip);
2989 test_roundtrips (test_hex_roundtrip);
2994 #endif /* DBUS_BUILD_TESTS */