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 string starts life with zero length. The
172 * string must eventually be freed with _dbus_string_free().
174 * @param str memory to hold the string
175 * @returns #TRUE on success, #FALSE if no memory
178 _dbus_string_init (DBusString *str)
180 DBusRealString *real;
182 _dbus_assert (str != NULL);
184 _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
186 real = (DBusRealString*) str;
188 /* It's very important not to touch anything
189 * other than real->str if we're going to fail,
190 * since we also use this function to reset
191 * an existing string, e.g. in _dbus_string_steal_data()
194 real->str = dbus_malloc (ALLOCATION_PADDING);
195 if (real->str == NULL)
198 real->allocated = ALLOCATION_PADDING;
200 real->str[real->len] = '\0';
202 real->max_length = MAX_MAX_LENGTH;
203 real->constant = FALSE;
204 real->locked = FALSE;
205 real->invalid = FALSE;
206 real->align_offset = 0;
208 fixup_alignment (real);
213 /* The max length thing is sort of a historical artifact
214 * from a feature that turned out to be dumb; perhaps
215 * we should purge it entirely. The problem with
216 * the feature is that it looks like memory allocation
217 * failure, but is not a transient or resolvable failure.
220 set_max_length (DBusString *str,
223 DBusRealString *real;
225 real = (DBusRealString*) str;
227 real->max_length = max_length;
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
415 _dbus_string_get_data (DBusString *str)
417 DBUS_STRING_PREAMBLE (str);
423 * Gets the raw character buffer from a const string.
425 * @param str the string
426 * @returns the string data
429 _dbus_string_get_const_data (const DBusString *str)
431 DBUS_CONST_STRING_PREAMBLE (str);
437 * Gets a sub-portion of the raw character buffer from the
438 * string. The "len" field is required simply for error
439 * checking, to be sure you don't try to use more
440 * string than exists. The nul termination of the
441 * returned buffer remains at the end of the entire
442 * string, not at start + len.
444 * @param str the string
445 * @param start byte offset to return
446 * @param len length of segment to return
447 * @returns the string data
450 _dbus_string_get_data_len (DBusString *str,
454 DBUS_STRING_PREAMBLE (str);
455 _dbus_assert (start >= 0);
456 _dbus_assert (len >= 0);
457 _dbus_assert (start <= real->len);
458 _dbus_assert (len <= real->len - start);
460 return real->str + start;
464 * const version of _dbus_string_get_data_len().
466 * @todo should return the const char* instead of using an out param;
467 * the temporary variable encourages a bug where you use const data
468 * after modifying the string and possibly causing a realloc.
470 * @param str the string
471 * @param start byte offset to return
472 * @param len length of segment to return
473 * @returns the string data
476 _dbus_string_get_const_data_len (const DBusString *str,
480 DBUS_CONST_STRING_PREAMBLE (str);
481 _dbus_assert (start >= 0);
482 _dbus_assert (len >= 0);
483 _dbus_assert (start <= real->len);
484 _dbus_assert (len <= real->len - start);
486 return real->str + start;
490 * Sets the value of the byte at the given position.
492 * @param str the string
493 * @param i the position
494 * @param byte the new value
497 _dbus_string_set_byte (DBusString *str,
501 DBUS_STRING_PREAMBLE (str);
502 _dbus_assert (i < real->len);
503 _dbus_assert (i >= 0);
509 * Gets the byte at the given position.
511 * @param str the string
512 * @param start the position
513 * @returns the byte at that position
516 _dbus_string_get_byte (const DBusString *str,
519 DBUS_CONST_STRING_PREAMBLE (str);
520 _dbus_assert (start < real->len);
521 _dbus_assert (start >= 0);
523 return real->str[start];
527 * Inserts the given byte at the given position.
529 * @param str the string
530 * @param i the position
531 * @param byte the value to insert
532 * @returns #TRUE on success
535 _dbus_string_insert_byte (DBusString *str,
539 DBUS_STRING_PREAMBLE (str);
540 _dbus_assert (i <= real->len);
541 _dbus_assert (i >= 0);
543 if (!open_gap (1, real, i))
552 * Like _dbus_string_get_data(), but removes the
553 * gotten data from the original string. The caller
554 * must free the data returned. This function may
555 * fail due to lack of memory, and return #FALSE.
557 * @param str the string
558 * @param data_return location to return the buffer
559 * @returns #TRUE on success
562 _dbus_string_steal_data (DBusString *str,
566 DBUS_STRING_PREAMBLE (str);
567 _dbus_assert (data_return != NULL);
569 undo_alignment (real);
571 *data_return = real->str;
573 old_max_length = real->max_length;
575 /* reset the string */
576 if (!_dbus_string_init (str))
578 /* hrm, put it back then */
579 real->str = *data_return;
581 fixup_alignment (real);
585 real->max_length = old_max_length;
591 * Like _dbus_string_get_data_len(), but removes the gotten data from
592 * the original string. The caller must free the data returned. This
593 * function may fail due to lack of memory, and return #FALSE.
594 * The returned string is nul-terminated and has length len.
596 * @todo this function is broken because on failure it
597 * may corrupt the source string.
599 * @param str the string
600 * @param data_return location to return the buffer
601 * @param start the start of segment to steal
602 * @param len the length of segment to steal
603 * @returns #TRUE on success
606 _dbus_string_steal_data_len (DBusString *str,
612 DBUS_STRING_PREAMBLE (str);
613 _dbus_assert (data_return != NULL);
614 _dbus_assert (start >= 0);
615 _dbus_assert (len >= 0);
616 _dbus_assert (start <= real->len);
617 _dbus_assert (len <= real->len - start);
619 if (!_dbus_string_init (&dest))
622 set_max_length (&dest, real->max_length);
624 if (!_dbus_string_move_len (str, start, len, &dest, 0))
626 _dbus_string_free (&dest);
630 _dbus_warn ("Broken code in _dbus_string_steal_data_len(), see @todo, FIXME\n");
631 if (!_dbus_string_steal_data (&dest, data_return))
633 _dbus_string_free (&dest);
637 _dbus_string_free (&dest);
643 * Copies the data from the string into a char*
645 * @param str the string
646 * @param data_return place to return the data
647 * @returns #TRUE on success, #FALSE on no memory
650 _dbus_string_copy_data (const DBusString *str,
653 DBUS_CONST_STRING_PREAMBLE (str);
654 _dbus_assert (data_return != NULL);
656 *data_return = dbus_malloc (real->len + 1);
657 if (*data_return == NULL)
660 memcpy (*data_return, real->str, real->len + 1);
666 * Copies a segment of the string into a char*
668 * @param str the string
669 * @param data_return place to return the data
670 * @param start start index
671 * @param len length to copy
672 * @returns #FALSE if no memory
675 _dbus_string_copy_data_len (const DBusString *str,
682 DBUS_CONST_STRING_PREAMBLE (str);
683 _dbus_assert (data_return != NULL);
684 _dbus_assert (start >= 0);
685 _dbus_assert (len >= 0);
686 _dbus_assert (start <= real->len);
687 _dbus_assert (len <= real->len - start);
689 if (!_dbus_string_init (&dest))
692 set_max_length (&dest, real->max_length);
694 if (!_dbus_string_copy_len (str, start, len, &dest, 0))
696 _dbus_string_free (&dest);
700 if (!_dbus_string_steal_data (&dest, data_return))
702 _dbus_string_free (&dest);
706 _dbus_string_free (&dest);
711 * Gets the length of a string (not including nul termination).
713 * @returns the length.
716 _dbus_string_get_length (const DBusString *str)
718 DBUS_CONST_STRING_PREAMBLE (str);
724 * Makes a string longer by the given number of bytes. Checks whether
725 * adding additional_length to the current length would overflow an
726 * integer, and checks for exceeding a string's max length.
727 * The new bytes are not initialized, other than nul-terminating
728 * the end of the string. The uninitialized bytes may contain
729 * nul bytes or other junk.
731 * @param str a string
732 * @param additional_length length to add to the string.
733 * @returns #TRUE on success.
736 _dbus_string_lengthen (DBusString *str,
737 int additional_length)
739 DBUS_STRING_PREAMBLE (str);
740 _dbus_assert (additional_length >= 0);
742 if (additional_length > real->max_length - real->len)
743 return FALSE; /* would overflow */
745 return set_length (real,
746 real->len + additional_length);
750 * Makes a string shorter by the given number of bytes.
752 * @param str a string
753 * @param length_to_remove length to remove from the string.
756 _dbus_string_shorten (DBusString *str,
757 int length_to_remove)
759 DBUS_STRING_PREAMBLE (str);
760 _dbus_assert (length_to_remove >= 0);
761 _dbus_assert (length_to_remove <= real->len);
764 real->len - length_to_remove);
768 * Sets the length of a string. Can be used to truncate or lengthen
769 * the string. If the string is lengthened, the function may fail and
770 * return #FALSE. Newly-added bytes are not initialized, as with
771 * _dbus_string_lengthen().
773 * @param str a string
774 * @param length new length of the string.
775 * @returns #FALSE on failure.
778 _dbus_string_set_length (DBusString *str,
781 DBUS_STRING_PREAMBLE (str);
782 _dbus_assert (length >= 0);
784 return set_length (real, length);
788 * Align the length of a string to a specific alignment (typically 4 or 8)
789 * by appending nul bytes to the string.
791 * @param str a string
792 * @param alignment the alignment
793 * @returns #FALSE if no memory
796 _dbus_string_align_length (DBusString *str,
799 unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
801 DBUS_STRING_PREAMBLE (str);
802 _dbus_assert (alignment >= 1);
803 _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
805 new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
806 if (new_len > (unsigned long) real->max_length)
809 delta = new_len - real->len;
810 _dbus_assert (delta >= 0);
815 if (!set_length (real, new_len))
818 memset (real->str + (new_len - delta),
825 append (DBusRealString *real,
832 if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
835 memcpy (real->str + (real->len - buffer_len),
843 * Appends a nul-terminated C-style string to a DBusString.
845 * @param str the DBusString
846 * @param buffer the nul-terminated characters to append
847 * @returns #FALSE if not enough memory.
850 _dbus_string_append (DBusString *str,
853 unsigned long buffer_len;
855 DBUS_STRING_PREAMBLE (str);
856 _dbus_assert (buffer != NULL);
858 buffer_len = strlen (buffer);
859 if (buffer_len > (unsigned long) real->max_length)
862 return append (real, buffer, buffer_len);
866 * Appends block of bytes with the given length to a DBusString.
868 * @param str the DBusString
869 * @param buffer the bytes to append
870 * @param len the number of bytes to append
871 * @returns #FALSE if not enough memory.
874 _dbus_string_append_len (DBusString *str,
878 DBUS_STRING_PREAMBLE (str);
879 _dbus_assert (buffer != NULL);
880 _dbus_assert (len >= 0);
882 return append (real, buffer, len);
886 * Appends a single byte to the string, returning #FALSE
887 * if not enough memory.
889 * @param str the string
890 * @param byte the byte to append
891 * @returns #TRUE on success
894 _dbus_string_append_byte (DBusString *str,
897 DBUS_STRING_PREAMBLE (str);
899 if (!set_length (real, real->len + 1))
902 real->str[real->len-1] = byte;
908 * Appends a single Unicode character, encoding the character
911 * @param str the string
912 * @param ch the Unicode character
915 _dbus_string_append_unichar (DBusString *str,
923 DBUS_STRING_PREAMBLE (str);
925 /* this code is from GLib but is pretty standard I think */
939 else if (ch < 0x10000)
944 else if (ch < 0x200000)
949 else if (ch < 0x4000000)
960 if (len > (real->max_length - real->len))
961 return FALSE; /* real->len + len would overflow */
963 if (!set_length (real, real->len + len))
966 out = real->str + (real->len - len);
968 for (i = len - 1; i > 0; --i)
970 out[i] = (ch & 0x3f) | 0x80;
979 delete (DBusRealString *real,
986 memmove (real->str + start, real->str + start + len, real->len - (start + len));
988 real->str[real->len] = '\0';
992 * Deletes a segment of a DBusString with length len starting at
993 * start. (Hint: to clear an entire string, setting length to 0
994 * with _dbus_string_set_length() is easier.)
996 * @param str the DBusString
997 * @param start where to start deleting
998 * @param len the number of bytes to delete
1001 _dbus_string_delete (DBusString *str,
1005 DBUS_STRING_PREAMBLE (str);
1006 _dbus_assert (start >= 0);
1007 _dbus_assert (len >= 0);
1008 _dbus_assert (start <= real->len);
1009 _dbus_assert (len <= real->len - start);
1011 delete (real, start, len);
1015 copy (DBusRealString *source,
1018 DBusRealString *dest,
1024 if (!open_gap (len, dest, insert_at))
1027 memcpy (dest->str + insert_at,
1028 source->str + start,
1035 * Checks assertions for two strings we're copying a segment between,
1036 * and declares real_source/real_dest variables.
1038 * @param source the source string
1039 * @param start the starting offset
1040 * @param dest the dest string
1041 * @param insert_at where the copied segment is inserted
1043 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at) \
1044 DBusRealString *real_source = (DBusRealString*) source; \
1045 DBusRealString *real_dest = (DBusRealString*) dest; \
1046 _dbus_assert ((source) != (dest)); \
1047 DBUS_GENERIC_STRING_PREAMBLE (real_source); \
1048 DBUS_GENERIC_STRING_PREAMBLE (real_dest); \
1049 _dbus_assert (!real_dest->constant); \
1050 _dbus_assert (!real_dest->locked); \
1051 _dbus_assert ((start) >= 0); \
1052 _dbus_assert ((start) <= real_source->len); \
1053 _dbus_assert ((insert_at) >= 0); \
1054 _dbus_assert ((insert_at) <= real_dest->len)
1057 * Moves the end of one string into another string. Both strings
1058 * must be initialized, valid strings.
1060 * @param source the source string
1061 * @param start where to chop off the source string
1062 * @param dest the destination string
1063 * @param insert_at where to move the chopped-off part of source string
1064 * @returns #FALSE if not enough memory
1067 _dbus_string_move (DBusString *source,
1072 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1074 if (!copy (real_source, start,
1075 real_source->len - start,
1080 delete (real_source, start,
1081 real_source->len - start);
1087 * Like _dbus_string_move(), but does not delete the section
1088 * of the source string that's copied to the dest string.
1090 * @param source the source string
1091 * @param start where to start copying the source string
1092 * @param dest the destination string
1093 * @param insert_at where to place the copied part of source string
1094 * @returns #FALSE if not enough memory
1097 _dbus_string_copy (const DBusString *source,
1102 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1104 return copy (real_source, start,
1105 real_source->len - start,
1111 * Like _dbus_string_move(), but can move a segment from
1112 * the middle of the source string.
1114 * @param source the source string
1115 * @param start first byte of source string to move
1116 * @param len length of segment to move
1117 * @param dest the destination string
1118 * @param insert_at where to move the bytes from the source string
1119 * @returns #FALSE if not enough memory
1122 _dbus_string_move_len (DBusString *source,
1129 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1130 _dbus_assert (len >= 0);
1131 _dbus_assert ((start + len) <= real_source->len);
1133 if (!copy (real_source, start, len,
1138 delete (real_source, start,
1145 * Like _dbus_string_copy(), but can copy a segment from the middle of
1146 * the source string.
1148 * @param source the source string
1149 * @param start where to start copying the source string
1150 * @param len length of segment to copy
1151 * @param dest the destination string
1152 * @param insert_at where to place the copied segment of source string
1153 * @returns #FALSE if not enough memory
1156 _dbus_string_copy_len (const DBusString *source,
1162 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1163 _dbus_assert (len >= 0);
1164 _dbus_assert (start <= real_source->len);
1165 _dbus_assert (len <= real_source->len - start);
1167 return copy (real_source, start, len,
1173 * Replaces a segment of dest string with a segment of source string.
1175 * @todo optimize the case where the two lengths are the same, and
1176 * avoid memmoving the data in the trailing part of the string twice.
1178 * @todo avoid inserting the source into dest, then deleting
1179 * the replaced chunk of dest (which creates a potentially large
1180 * intermediate string). Instead, extend the replaced chunk
1181 * of dest with padding to the same size as the source chunk,
1182 * then copy in the source bytes.
1184 * @param source the source string
1185 * @param start where to start copying the source string
1186 * @param len length of segment to copy
1187 * @param dest the destination string
1188 * @param replace_at start of segment of dest string to replace
1189 * @param replace_len length of segment of dest string to replace
1190 * @returns #FALSE if not enough memory
1194 _dbus_string_replace_len (const DBusString *source,
1201 DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1202 _dbus_assert (len >= 0);
1203 _dbus_assert (start <= real_source->len);
1204 _dbus_assert (len <= real_source->len - start);
1205 _dbus_assert (replace_at >= 0);
1206 _dbus_assert (replace_at <= real_dest->len);
1207 _dbus_assert (replace_len <= real_dest->len - replace_at);
1209 if (!copy (real_source, start, len,
1210 real_dest, replace_at))
1213 delete (real_dest, replace_at + len, replace_len);
1218 /* Unicode macros and utf8_validate() from GLib Owen Taylor, Havoc
1219 * Pennington, and Tom Tromey are the authors and authorized relicense.
1222 /** computes length and mask of a unicode character
1223 * @param Char the char
1224 * @param Mask the mask variable to assign to
1225 * @param Len the length variable to assign to
1227 #define UTF8_COMPUTE(Char, Mask, Len) \
1233 else if ((Char & 0xe0) == 0xc0) \
1238 else if ((Char & 0xf0) == 0xe0) \
1243 else if ((Char & 0xf8) == 0xf0) \
1248 else if ((Char & 0xfc) == 0xf8) \
1253 else if ((Char & 0xfe) == 0xfc) \
1262 * computes length of a unicode character in UTF-8
1263 * @param Char the char
1265 #define UTF8_LENGTH(Char) \
1266 ((Char) < 0x80 ? 1 : \
1267 ((Char) < 0x800 ? 2 : \
1268 ((Char) < 0x10000 ? 3 : \
1269 ((Char) < 0x200000 ? 4 : \
1270 ((Char) < 0x4000000 ? 5 : 6)))))
1273 * Gets a UTF-8 value.
1275 * @param Result variable for extracted unicode char.
1276 * @param Chars the bytes to decode
1277 * @param Count counter variable
1278 * @param Mask mask for this char
1279 * @param Len length for this char in bytes
1281 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
1282 (Result) = (Chars)[0] & (Mask); \
1283 for ((Count) = 1; (Count) < (Len); ++(Count)) \
1285 if (((Chars)[(Count)] & 0xc0) != 0x80) \
1291 (Result) |= ((Chars)[(Count)] & 0x3f); \
1295 * Check whether a unicode char is in a valid range.
1297 * @param Char the character
1299 #define UNICODE_VALID(Char) \
1300 ((Char) < 0x110000 && \
1301 (((Char) & 0xFFFFF800) != 0xD800) && \
1302 ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \
1303 ((Char) & 0xFFFF) != 0xFFFF)
1306 * Gets a unicode character from a UTF-8 string. Does no validation;
1307 * you must verify that the string is valid UTF-8 in advance and must
1308 * pass in the start of a character.
1310 * @param str the string
1311 * @param start the start of the UTF-8 character.
1312 * @param ch_return location to return the character
1313 * @param end_return location to return the byte index of next character
1316 _dbus_string_get_unichar (const DBusString *str,
1318 dbus_unichar_t *ch_return,
1322 dbus_unichar_t result;
1325 DBUS_CONST_STRING_PREAMBLE (str);
1326 _dbus_assert (start >= 0);
1327 _dbus_assert (start <= real->len);
1332 *end_return = real->len;
1335 p = real->str + start;
1338 UTF8_COMPUTE (c, mask, len);
1341 UTF8_GET (result, p, i, mask, len);
1343 if (result == (dbus_unichar_t)-1)
1347 *ch_return = result;
1349 *end_return = start + len;
1353 * Finds the given substring in the string,
1354 * returning #TRUE and filling in the byte index
1355 * where the substring was found, if it was found.
1356 * Returns #FALSE if the substring wasn't found.
1357 * Sets *start to the length of the string if the substring
1360 * @param str the string
1361 * @param start where to start looking
1362 * @param substr the substring
1363 * @param found return location for where it was found, or #NULL
1364 * @returns #TRUE if found
1367 _dbus_string_find (const DBusString *str,
1372 return _dbus_string_find_to (str, start,
1373 ((const DBusRealString*)str)->len,
1378 * Finds the given substring in the string,
1379 * up to a certain position,
1380 * returning #TRUE and filling in the byte index
1381 * where the substring was found, if it was found.
1382 * Returns #FALSE if the substring wasn't found.
1383 * Sets *start to the length of the string if the substring
1386 * @param str the string
1387 * @param start where to start looking
1388 * @param end where to stop looking
1389 * @param substr the substring
1390 * @param found return location for where it was found, or #NULL
1391 * @returns #TRUE if found
1394 _dbus_string_find_to (const DBusString *str,
1401 DBUS_CONST_STRING_PREAMBLE (str);
1402 _dbus_assert (substr != NULL);
1403 _dbus_assert (start <= real->len);
1404 _dbus_assert (start >= 0);
1405 _dbus_assert (substr != NULL);
1406 _dbus_assert (end <= real->len);
1407 _dbus_assert (start <= end);
1409 /* we always "find" an empty string */
1410 if (*substr == '\0')
1420 if (real->str[i] == substr[0])
1426 if (substr[j - i] == '\0')
1428 else if (real->str[j] != substr[j - i])
1434 if (substr[j - i] == '\0')
1452 * Finds a blank (space or tab) in the string. Returns #TRUE
1453 * if found, #FALSE otherwise. If a blank is not found sets
1454 * *found to the length of the string.
1456 * @param str the string
1457 * @param start byte index to start looking
1458 * @param found place to store the location of the first blank
1459 * @returns #TRUE if a blank was found
1462 _dbus_string_find_blank (const DBusString *str,
1467 DBUS_CONST_STRING_PREAMBLE (str);
1468 _dbus_assert (start <= real->len);
1469 _dbus_assert (start >= 0);
1472 while (i < real->len)
1474 if (real->str[i] == ' ' ||
1475 real->str[i] == '\t')
1492 * Skips blanks from start, storing the first non-blank in *end
1493 * (blank is space or tab).
1495 * @param str the string
1496 * @param start where to start
1497 * @param end where to store the first non-blank byte index
1500 _dbus_string_skip_blank (const DBusString *str,
1505 DBUS_CONST_STRING_PREAMBLE (str);
1506 _dbus_assert (start <= real->len);
1507 _dbus_assert (start >= 0);
1510 while (i < real->len)
1512 if (!(real->str[i] == ' ' ||
1513 real->str[i] == '\t'))
1519 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1520 real->str[i] == '\t'));
1527 * Skips whitespace from start, storing the first non-whitespace in *end.
1528 * (whitespace is space, tab, newline, CR).
1530 * @param str the string
1531 * @param start where to start
1532 * @param end where to store the first non-whitespace byte index
1535 _dbus_string_skip_white (const DBusString *str,
1540 DBUS_CONST_STRING_PREAMBLE (str);
1541 _dbus_assert (start <= real->len);
1542 _dbus_assert (start >= 0);
1545 while (i < real->len)
1547 if (!(real->str[i] == ' ' ||
1548 real->str[i] == '\n' ||
1549 real->str[i] == '\r' ||
1550 real->str[i] == '\t'))
1556 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1557 real->str[i] == '\t'));
1564 * Assigns a newline-terminated or \r\n-terminated line from the front
1565 * of the string to the given dest string. The dest string's previous
1566 * contents are deleted. If the source string contains no newline,
1567 * moves the entire source string to the dest string.
1569 * @todo owen correctly notes that this is a stupid function (it was
1570 * written purely for test code,
1571 * e.g. dbus-message-builder.c). Probably should be enforced as test
1572 * code only with #ifdef DBUS_BUILD_TESTS
1574 * @param source the source string
1575 * @param dest the destination string (contents are replaced)
1576 * @returns #FALSE if no memory, or source has length 0
1579 _dbus_string_pop_line (DBusString *source,
1583 dbus_bool_t have_newline;
1585 _dbus_string_set_length (dest, 0);
1588 if (_dbus_string_find (source, 0, "\n", &eol))
1590 have_newline = TRUE;
1591 eol += 1; /* include newline */
1595 eol = _dbus_string_get_length (source);
1596 have_newline = FALSE;
1600 return FALSE; /* eof */
1602 if (!_dbus_string_move_len (source, 0, eol,
1608 /* dump the newline and the \r if we have one */
1611 dbus_bool_t have_cr;
1613 _dbus_assert (_dbus_string_get_length (dest) > 0);
1615 if (_dbus_string_get_length (dest) > 1 &&
1616 _dbus_string_get_byte (dest,
1617 _dbus_string_get_length (dest) - 2) == '\r')
1622 _dbus_string_set_length (dest,
1623 _dbus_string_get_length (dest) -
1631 * Deletes up to and including the first blank space
1634 * @param str the string
1637 _dbus_string_delete_first_word (DBusString *str)
1641 if (_dbus_string_find_blank (str, 0, &i))
1642 _dbus_string_skip_blank (str, i, &i);
1644 _dbus_string_delete (str, 0, i);
1648 * Deletes any leading blanks in the string
1650 * @param str the string
1653 _dbus_string_delete_leading_blanks (DBusString *str)
1657 _dbus_string_skip_blank (str, 0, &i);
1660 _dbus_string_delete (str, 0, i);
1664 * Tests two DBusString for equality.
1666 * @todo memcmp is probably faster
1668 * @param a first string
1669 * @param b second string
1670 * @returns #TRUE if equal
1673 _dbus_string_equal (const DBusString *a,
1674 const DBusString *b)
1676 const unsigned char *ap;
1677 const unsigned char *bp;
1678 const unsigned char *a_end;
1679 const DBusRealString *real_a = (const DBusRealString*) a;
1680 const DBusRealString *real_b = (const DBusRealString*) b;
1681 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1682 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1684 if (real_a->len != real_b->len)
1689 a_end = real_a->str + real_a->len;
1703 * Tests two DBusString for equality up to the given length.
1705 * @todo write a unit test
1707 * @todo memcmp is probably faster
1709 * @param a first string
1710 * @param b second string
1711 * @param len the lengh
1712 * @returns #TRUE if equal for the given number of bytes
1715 _dbus_string_equal_len (const DBusString *a,
1716 const DBusString *b,
1719 const unsigned char *ap;
1720 const unsigned char *bp;
1721 const unsigned char *a_end;
1722 const DBusRealString *real_a = (const DBusRealString*) a;
1723 const DBusRealString *real_b = (const DBusRealString*) b;
1724 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1725 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1727 if (real_a->len != real_b->len &&
1728 (real_a->len < len || real_b->len < len))
1733 a_end = real_a->str + MIN (real_a->len, len);
1747 * Checks whether a string is equal to a C string.
1749 * @param a the string
1750 * @param c_str the C string
1751 * @returns #TRUE if equal
1754 _dbus_string_equal_c_str (const DBusString *a,
1757 const unsigned char *ap;
1758 const unsigned char *bp;
1759 const unsigned char *a_end;
1760 const DBusRealString *real_a = (const DBusRealString*) a;
1761 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1762 _dbus_assert (c_str != NULL);
1765 bp = (const unsigned char*) c_str;
1766 a_end = real_a->str + real_a->len;
1767 while (ap != a_end && *bp)
1776 if (ap != a_end || *bp)
1783 * Checks whether a string starts with the given C string.
1785 * @param a the string
1786 * @param c_str the C string
1787 * @returns #TRUE if string starts with it
1790 _dbus_string_starts_with_c_str (const DBusString *a,
1793 const unsigned char *ap;
1794 const unsigned char *bp;
1795 const unsigned char *a_end;
1796 const DBusRealString *real_a = (const DBusRealString*) a;
1797 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1798 _dbus_assert (c_str != NULL);
1801 bp = (const unsigned char*) c_str;
1802 a_end = real_a->str + real_a->len;
1803 while (ap != a_end && *bp)
1819 * Returns whether a string ends with the given suffix
1821 * @todo memcmp might make this faster.
1823 * @param a the string
1824 * @param c_str the C-style string
1825 * @returns #TRUE if the string ends with the suffix
1828 _dbus_string_ends_with_c_str (const DBusString *a,
1831 const unsigned char *ap;
1832 const unsigned char *bp;
1833 const unsigned char *a_end;
1834 unsigned long c_str_len;
1835 const DBusRealString *real_a = (const DBusRealString*) a;
1836 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1837 _dbus_assert (c_str != NULL);
1839 c_str_len = strlen (c_str);
1840 if (((unsigned long)real_a->len) < c_str_len)
1843 ap = real_a->str + (real_a->len - c_str_len);
1844 bp = (const unsigned char*) c_str;
1845 a_end = real_a->str + real_a->len;
1855 _dbus_assert (*ap == '\0');
1856 _dbus_assert (*bp == '\0');
1861 static const signed char base64_table[] = {
1928 /** The minimum char that's a valid char in Base64-encoded text */
1929 #define UNBASE64_MIN_CHAR (43)
1930 /** The maximum char that's a valid char in Base64-encoded text */
1931 #define UNBASE64_MAX_CHAR (122)
1932 /** Must subtract this from a char's integer value before offsetting
1933 * into unbase64_table
1935 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1936 static const signed char unbase64_table[] = {
2020 * Encodes a string using Base64, as documented in RFC 2045.
2022 * @param source the string to encode
2023 * @param start byte index to start encoding
2024 * @param dest string where encoded data should be placed
2025 * @param insert_at where to place encoded data
2026 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2029 _dbus_string_base64_encode (const DBusString *source,
2035 unsigned int dest_len; /* unsigned for overflow checks below */
2036 const unsigned char *s;
2038 const unsigned char *triplet_end;
2039 const unsigned char *final_end;
2040 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2041 _dbus_assert (source != dest);
2043 /* For each 24 bits (3 bytes) of input, we have 4 bytes of
2046 source_len = real_source->len - start;
2047 dest_len = (source_len / 3) * 4;
2048 if (source_len % 3 != 0)
2051 if (dest_len > (unsigned int) real_dest->max_length)
2054 if (source_len == 0)
2057 if (!open_gap (dest_len, real_dest, insert_at))
2060 d = real_dest->str + insert_at;
2061 s = real_source->str + start;
2062 final_end = real_source->str + (start + source_len);
2063 triplet_end = final_end - (source_len % 3);
2064 _dbus_assert (triplet_end <= final_end);
2065 _dbus_assert ((final_end - triplet_end) < 3);
2067 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
2068 #define SIX_BITS_MASK (0x3f)
2069 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
2071 while (s != triplet_end)
2073 unsigned int triplet;
2075 triplet = s[2] | (s[1] << 8) | (s[0] << 16);
2077 /* Encode each 6 bits. */
2079 *d++ = ENCODE_64 (triplet >> 18);
2080 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
2081 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
2082 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
2087 switch (final_end - triplet_end)
2091 unsigned int doublet;
2093 doublet = s[1] | (s[0] << 8);
2095 *d++ = ENCODE_64 (doublet >> 12);
2096 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
2097 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
2103 unsigned int singlet;
2107 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2108 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2117 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2123 * Decodes a string from Base64, as documented in RFC 2045.
2125 * @todo sort out the AUDIT comment in here. The case it mentions
2126 * ("====" or "x===") is not allowed in correct base64, so need to
2127 * decide what to do with that kind of input. Probably ignore it
2128 * since we ignore any other junk seen.
2130 * @param source the string to decode
2131 * @param start byte index to start decode
2132 * @param dest string where decoded data should be placed
2133 * @param insert_at where to place decoded data
2134 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2137 _dbus_string_base64_decode (const DBusString *source,
2146 unsigned int triplet = 0;
2149 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2150 _dbus_assert (source != dest);
2152 source_len = real_source->len - start;
2153 s = real_source->str + start;
2154 end = real_source->str + source_len;
2156 if (source_len == 0)
2159 if (!_dbus_string_init (&result))
2166 /* The idea is to just skip anything that isn't
2167 * a base64 char - it's allowed to have whitespace,
2168 * newlines, etc. in here. We also ignore trailing
2169 * base64 chars, though that's suspicious.
2172 if (*s >= UNBASE64_MIN_CHAR &&
2173 *s <= UNBASE64_MAX_CHAR)
2177 /* '=' is padding, doesn't represent additional data
2178 * but does increment our count.
2187 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2192 triplet |= (unsigned int) val;
2197 if (sextet_count == 4)
2199 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2202 /* AUDIT: Comment doesn't mention 4 pad => 0,
2203 * 3 pad => 1 byte, though the code should
2204 * work fine if those are the required outputs.
2206 * I assume that the spec requires dropping
2207 * the top two bits of, say, ///= which is > 2
2208 * bytes worth of bits. (Or otherwise, you couldn't
2209 * actually represent 2 byte sequences.
2214 if (!_dbus_string_append_byte (&result,
2221 if (!_dbus_string_append_byte (&result,
2222 (triplet >> 8) & 0xff))
2226 if (!_dbus_string_append_byte (&result,
2239 if (!_dbus_string_move (&result, 0, dest, insert_at))
2241 _dbus_string_free (&result);
2245 _dbus_string_free (&result);
2250 _dbus_string_free (&result);
2256 * Encodes a string in hex, the way MD5 and SHA-1 are usually
2257 * encoded. (Each byte is two hex digits.)
2259 * @param source the string to encode
2260 * @param start byte index to start encoding
2261 * @param dest string where encoded data should be placed
2262 * @param insert_at where to place encoded data
2263 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2266 _dbus_string_hex_encode (const DBusString *source,
2272 const char hexdigits[16] = {
2273 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2274 'a', 'b', 'c', 'd', 'e', 'f'
2276 const unsigned char *p;
2277 const unsigned char *end;
2280 _dbus_assert (start <= _dbus_string_get_length (source));
2282 if (!_dbus_string_init (&result))
2287 p = (const unsigned char*) _dbus_string_get_const_data (source);
2288 end = p + _dbus_string_get_length (source);
2293 if (!_dbus_string_append_byte (&result,
2294 hexdigits[(*p >> 4)]))
2297 if (!_dbus_string_append_byte (&result,
2298 hexdigits[(*p & 0x0f)]))
2304 if (!_dbus_string_move (&result, 0, dest, insert_at))
2310 _dbus_string_free (&result);
2315 * Decodes a string from hex encoding.
2317 * @param source the string to decode
2318 * @param start byte index to start decode
2319 * @param dest string where decoded data should be placed
2320 * @param insert_at where to place decoded data
2321 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2324 _dbus_string_hex_decode (const DBusString *source,
2330 const unsigned char *p;
2331 const unsigned char *end;
2333 dbus_bool_t high_bits;
2335 _dbus_assert (start <= _dbus_string_get_length (source));
2337 if (!_dbus_string_init (&result))
2343 p = (const unsigned char*) _dbus_string_get_const_data (source);
2344 end = p + _dbus_string_get_length (source);
2409 _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2416 if (!_dbus_string_append_byte (&result,
2425 len = _dbus_string_get_length (&result);
2427 b = _dbus_string_get_byte (&result, len - 1);
2431 _dbus_string_set_byte (&result, len - 1, b);
2434 high_bits = !high_bits;
2439 if (!_dbus_string_move (&result, 0, dest, insert_at))
2445 _dbus_string_free (&result);
2450 * Checks that the given range of the string is valid ASCII with no
2451 * nul bytes. If the given range is not entirely contained in the
2452 * string, returns #FALSE.
2454 * @todo this is inconsistent with most of DBusString in that
2455 * it allows a start,len range that isn't in the string.
2457 * @param str the string
2458 * @param start first byte index to check
2459 * @param len number of bytes to check
2460 * @returns #TRUE if the byte range exists and is all valid ASCII
2463 _dbus_string_validate_ascii (const DBusString *str,
2467 const unsigned char *s;
2468 const unsigned char *end;
2469 DBUS_CONST_STRING_PREAMBLE (str);
2470 _dbus_assert (start >= 0);
2471 _dbus_assert (start <= real->len);
2472 _dbus_assert (len >= 0);
2474 if (len > real->len - start)
2477 s = real->str + start;
2482 ((*s & ~0x7f) != 0))
2492 * Checks that the given range of the string is valid UTF-8. If the
2493 * given range is not entirely contained in the string, returns
2494 * #FALSE. If the string contains any nul bytes in the given range,
2495 * returns #FALSE. If the start and start+len are not on character
2496 * boundaries, returns #FALSE.
2498 * @todo this is inconsistent with most of DBusString in that
2499 * it allows a start,len range that isn't in the string.
2501 * @param str the string
2502 * @param start first byte index to check
2503 * @param len number of bytes to check
2504 * @returns #TRUE if the byte range exists and is all valid UTF-8
2507 _dbus_string_validate_utf8 (const DBusString *str,
2511 const unsigned char *p;
2512 const unsigned char *end;
2513 DBUS_CONST_STRING_PREAMBLE (str);
2514 _dbus_assert (start >= 0);
2515 _dbus_assert (start <= real->len);
2516 _dbus_assert (len >= 0);
2518 if (len > real->len - start)
2521 p = real->str + start;
2526 int i, mask = 0, char_len;
2527 dbus_unichar_t result;
2528 unsigned char c = (unsigned char) *p;
2530 UTF8_COMPUTE (c, mask, char_len);
2535 /* check that the expected number of bytes exists in the remaining length */
2536 if ((end - p) < char_len)
2539 UTF8_GET (result, p, i, mask, char_len);
2541 if (UTF8_LENGTH (result) != char_len) /* Check for overlong UTF-8 */
2544 if (result == (dbus_unichar_t)-1)
2547 if (!UNICODE_VALID (result))
2553 /* See that we covered the entire length if a length was
2563 * Checks that the given range of the string is all nul bytes. If the
2564 * given range is not entirely contained in the string, returns
2567 * @todo this is inconsistent with most of DBusString in that
2568 * it allows a start,len range that isn't in the string.
2570 * @param str the string
2571 * @param start first byte index to check
2572 * @param len number of bytes to check
2573 * @returns #TRUE if the byte range exists and is all nul bytes
2576 _dbus_string_validate_nul (const DBusString *str,
2580 const unsigned char *s;
2581 const unsigned char *end;
2582 DBUS_CONST_STRING_PREAMBLE (str);
2583 _dbus_assert (start >= 0);
2584 _dbus_assert (len >= 0);
2585 _dbus_assert (start <= real->len);
2587 if (len > real->len - start)
2590 s = real->str + start;
2603 * Clears all allocated bytes in the string to zero.
2605 * @param str the string
2608 _dbus_string_zero (DBusString *str)
2610 DBUS_STRING_PREAMBLE (str);
2612 memset (real->str, '\0', real->allocated);
2616 #ifdef DBUS_BUILD_TESTS
2617 #include "dbus-test.h"
2621 test_max_len (DBusString *str,
2626 if (!_dbus_string_set_length (str, max_len - 1))
2627 _dbus_assert_not_reached ("setting len to one less than max should have worked");
2630 if (!_dbus_string_set_length (str, max_len))
2631 _dbus_assert_not_reached ("setting len to max len should have worked");
2633 if (_dbus_string_set_length (str, max_len + 1))
2634 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2636 if (!_dbus_string_set_length (str, 0))
2637 _dbus_assert_not_reached ("setting len to zero should have worked");
2641 test_base64_roundtrip (const unsigned char *data,
2649 len = strlen (data);
2651 if (!_dbus_string_init (&orig))
2652 _dbus_assert_not_reached ("could not init string");
2654 if (!_dbus_string_init (&encoded))
2655 _dbus_assert_not_reached ("could not init string");
2657 if (!_dbus_string_init (&decoded))
2658 _dbus_assert_not_reached ("could not init string");
2660 if (!_dbus_string_append_len (&orig, data, len))
2661 _dbus_assert_not_reached ("couldn't append orig data");
2663 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2664 _dbus_assert_not_reached ("could not encode");
2666 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2667 _dbus_assert_not_reached ("could not decode");
2669 if (!_dbus_string_equal (&orig, &decoded))
2673 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2674 _dbus_string_get_length (&orig),
2675 _dbus_string_get_length (&encoded),
2676 _dbus_string_get_length (&decoded));
2677 printf ("Original: %s\n", data);
2678 s = _dbus_string_get_const_data (&decoded);
2679 printf ("Decoded: %s\n", s);
2680 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2683 _dbus_string_free (&orig);
2684 _dbus_string_free (&encoded);
2685 _dbus_string_free (&decoded);
2689 test_hex_roundtrip (const unsigned char *data,
2697 len = strlen (data);
2699 if (!_dbus_string_init (&orig))
2700 _dbus_assert_not_reached ("could not init string");
2702 if (!_dbus_string_init (&encoded))
2703 _dbus_assert_not_reached ("could not init string");
2705 if (!_dbus_string_init (&decoded))
2706 _dbus_assert_not_reached ("could not init string");
2708 if (!_dbus_string_append_len (&orig, data, len))
2709 _dbus_assert_not_reached ("couldn't append orig data");
2711 if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2712 _dbus_assert_not_reached ("could not encode");
2714 if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2715 _dbus_assert_not_reached ("could not decode");
2717 if (!_dbus_string_equal (&orig, &decoded))
2721 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2722 _dbus_string_get_length (&orig),
2723 _dbus_string_get_length (&encoded),
2724 _dbus_string_get_length (&decoded));
2725 printf ("Original: %s\n", data);
2726 s = _dbus_string_get_const_data (&decoded);
2727 printf ("Decoded: %s\n", s);
2728 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2731 _dbus_string_free (&orig);
2732 _dbus_string_free (&encoded);
2733 _dbus_string_free (&decoded);
2736 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2739 test_roundtrips (TestRoundtripFunc func)
2741 (* func) ("Hello this is a string\n", -1);
2742 (* func) ("Hello this is a string\n1", -1);
2743 (* func) ("Hello this is a string\n12", -1);
2744 (* func) ("Hello this is a string\n123", -1);
2745 (* func) ("Hello this is a string\n1234", -1);
2746 (* func) ("Hello this is a string\n12345", -1);
2750 (* func) ("123", 3);
2751 (* func) ("1234", 4);
2752 (* func) ("12345", 5);
2756 (* func) ("123", 4);
2757 (* func) ("1234", 5);
2758 (* func) ("12345", 6);
2760 unsigned char buf[512];
2764 while (i < _DBUS_N_ELEMENTS (buf))
2770 while (i < _DBUS_N_ELEMENTS (buf))
2780 * @ingroup DBusStringInternals
2781 * Unit test for DBusString.
2783 * @todo Need to write tests for _dbus_string_copy() and
2784 * _dbus_string_move() moving to/from each of start/middle/end of a
2785 * string. Also need tests for _dbus_string_move_len ()
2787 * @returns #TRUE on success.
2790 _dbus_string_test (void)
2797 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 };
2802 while (i < _DBUS_N_ELEMENTS (lens))
2804 if (!_dbus_string_init (&str))
2805 _dbus_assert_not_reached ("failed to init string");
2807 set_max_length (&str, lens[i]);
2809 test_max_len (&str, lens[i]);
2810 _dbus_string_free (&str);
2815 /* Test shortening and setting length */
2817 while (i < _DBUS_N_ELEMENTS (lens))
2821 if (!_dbus_string_init (&str))
2822 _dbus_assert_not_reached ("failed to init string");
2824 set_max_length (&str, lens[i]);
2826 if (!_dbus_string_set_length (&str, lens[i]))
2827 _dbus_assert_not_reached ("failed to set string length");
2832 _dbus_assert (_dbus_string_get_length (&str) == j);
2835 _dbus_string_shorten (&str, 1);
2836 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2841 _dbus_string_free (&str);
2846 /* Test appending data */
2847 if (!_dbus_string_init (&str))
2848 _dbus_assert_not_reached ("failed to init string");
2853 if (!_dbus_string_append (&str, "a"))
2854 _dbus_assert_not_reached ("failed to append string to string\n");
2856 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2858 if (!_dbus_string_append_byte (&str, 'b'))
2859 _dbus_assert_not_reached ("failed to append byte to string\n");
2861 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2866 _dbus_string_free (&str);
2868 /* Check steal_data */
2870 if (!_dbus_string_init (&str))
2871 _dbus_assert_not_reached ("failed to init string");
2873 if (!_dbus_string_append (&str, "Hello World"))
2874 _dbus_assert_not_reached ("could not append to string");
2876 i = _dbus_string_get_length (&str);
2878 if (!_dbus_string_steal_data (&str, &s))
2879 _dbus_assert_not_reached ("failed to steal data");
2881 _dbus_assert (_dbus_string_get_length (&str) == 0);
2882 _dbus_assert (((int)strlen (s)) == i);
2888 if (!_dbus_string_append (&str, "Hello World"))
2889 _dbus_assert_not_reached ("could not append to string");
2891 i = _dbus_string_get_length (&str);
2893 if (!_dbus_string_init (&other))
2894 _dbus_assert_not_reached ("could not init string");
2896 if (!_dbus_string_move (&str, 0, &other, 0))
2897 _dbus_assert_not_reached ("could not move");
2899 _dbus_assert (_dbus_string_get_length (&str) == 0);
2900 _dbus_assert (_dbus_string_get_length (&other) == i);
2902 if (!_dbus_string_append (&str, "Hello World"))
2903 _dbus_assert_not_reached ("could not append to string");
2905 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2906 _dbus_assert_not_reached ("could not move");
2908 _dbus_assert (_dbus_string_get_length (&str) == 0);
2909 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2911 if (!_dbus_string_append (&str, "Hello World"))
2912 _dbus_assert_not_reached ("could not append to string");
2914 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2915 _dbus_assert_not_reached ("could not move");
2917 _dbus_assert (_dbus_string_get_length (&str) == 0);
2918 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2920 _dbus_string_free (&other);
2924 if (!_dbus_string_append (&str, "Hello World"))
2925 _dbus_assert_not_reached ("could not append to string");
2927 i = _dbus_string_get_length (&str);
2929 if (!_dbus_string_init (&other))
2930 _dbus_assert_not_reached ("could not init string");
2932 if (!_dbus_string_copy (&str, 0, &other, 0))
2933 _dbus_assert_not_reached ("could not copy");
2935 _dbus_assert (_dbus_string_get_length (&str) == i);
2936 _dbus_assert (_dbus_string_get_length (&other) == i);
2938 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2939 _dbus_assert_not_reached ("could not copy");
2941 _dbus_assert (_dbus_string_get_length (&str) == i);
2942 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2943 _dbus_assert (_dbus_string_equal_c_str (&other,
2944 "Hello WorldHello World"));
2946 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2947 _dbus_assert_not_reached ("could not copy");
2949 _dbus_assert (_dbus_string_get_length (&str) == i);
2950 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2951 _dbus_assert (_dbus_string_equal_c_str (&other,
2952 "Hello WorldHello WorldHello World"));
2954 _dbus_string_free (&str);
2955 _dbus_string_free (&other);
2959 if (!_dbus_string_init (&str))
2960 _dbus_assert_not_reached ("failed to init string");
2962 if (!_dbus_string_append (&str, "Hello World"))
2963 _dbus_assert_not_reached ("could not append to string");
2965 i = _dbus_string_get_length (&str);
2967 if (!_dbus_string_init (&other))
2968 _dbus_assert_not_reached ("could not init string");
2970 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2971 &other, 0, _dbus_string_get_length (&other)))
2972 _dbus_assert_not_reached ("could not replace");
2974 _dbus_assert (_dbus_string_get_length (&str) == i);
2975 _dbus_assert (_dbus_string_get_length (&other) == i);
2976 _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
2978 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2980 _dbus_assert_not_reached ("could not replace center space");
2982 _dbus_assert (_dbus_string_get_length (&str) == i);
2983 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2984 _dbus_assert (_dbus_string_equal_c_str (&other,
2985 "HelloHello WorldWorld"));
2988 if (!_dbus_string_replace_len (&str, 1, 1,
2990 _dbus_string_get_length (&other) - 1,
2992 _dbus_assert_not_reached ("could not replace end character");
2994 _dbus_assert (_dbus_string_get_length (&str) == i);
2995 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2996 _dbus_assert (_dbus_string_equal_c_str (&other,
2997 "HelloHello WorldWorle"));
2999 _dbus_string_free (&str);
3000 _dbus_string_free (&other);
3002 /* Check append/get unichar */
3004 if (!_dbus_string_init (&str))
3005 _dbus_assert_not_reached ("failed to init string");
3008 if (!_dbus_string_append_unichar (&str, 0xfffc))
3009 _dbus_assert_not_reached ("failed to append unichar");
3011 _dbus_string_get_unichar (&str, 0, &ch, &i);
3013 _dbus_assert (ch == 0xfffc);
3014 _dbus_assert (i == _dbus_string_get_length (&str));
3016 _dbus_string_free (&str);
3018 /* Check insert/set/get byte */
3020 if (!_dbus_string_init (&str))
3021 _dbus_assert_not_reached ("failed to init string");
3023 if (!_dbus_string_append (&str, "Hello"))
3024 _dbus_assert_not_reached ("failed to append Hello");
3026 _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
3027 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
3028 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
3029 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
3030 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
3032 _dbus_string_set_byte (&str, 1, 'q');
3033 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
3035 if (!_dbus_string_insert_byte (&str, 0, 255))
3036 _dbus_assert_not_reached ("can't insert byte");
3038 if (!_dbus_string_insert_byte (&str, 2, 'Z'))
3039 _dbus_assert_not_reached ("can't insert byte");
3041 if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
3042 _dbus_assert_not_reached ("can't insert byte");
3044 _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
3045 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
3046 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
3047 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
3048 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
3049 _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
3050 _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
3051 _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
3053 _dbus_string_free (&str);
3055 /* Check append/parse int/double */
3057 if (!_dbus_string_init (&str))
3058 _dbus_assert_not_reached ("failed to init string");
3060 if (!_dbus_string_append_int (&str, 27))
3061 _dbus_assert_not_reached ("failed to append int");
3063 i = _dbus_string_get_length (&str);
3065 if (!_dbus_string_parse_int (&str, 0, &v, &end))
3066 _dbus_assert_not_reached ("failed to parse int");
3068 _dbus_assert (v == 27);
3069 _dbus_assert (end == i);
3071 _dbus_string_free (&str);
3073 if (!_dbus_string_init (&str))
3074 _dbus_assert_not_reached ("failed to init string");
3076 if (!_dbus_string_append_double (&str, 50.3))
3077 _dbus_assert_not_reached ("failed to append float");
3079 i = _dbus_string_get_length (&str);
3081 if (!_dbus_string_parse_double (&str, 0, &d, &end))
3082 _dbus_assert_not_reached ("failed to parse float");
3084 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
3085 _dbus_assert (end == i);
3087 _dbus_string_free (&str);
3090 if (!_dbus_string_init (&str))
3091 _dbus_assert_not_reached ("failed to init string");
3093 if (!_dbus_string_append (&str, "Hello"))
3094 _dbus_assert_not_reached ("couldn't append to string");
3096 if (!_dbus_string_find (&str, 0, "He", &i))
3097 _dbus_assert_not_reached ("didn't find 'He'");
3098 _dbus_assert (i == 0);
3100 if (!_dbus_string_find (&str, 0, "Hello", &i))
3101 _dbus_assert_not_reached ("didn't find 'Hello'");
3102 _dbus_assert (i == 0);
3104 if (!_dbus_string_find (&str, 0, "ello", &i))
3105 _dbus_assert_not_reached ("didn't find 'ello'");
3106 _dbus_assert (i == 1);
3108 if (!_dbus_string_find (&str, 0, "lo", &i))
3109 _dbus_assert_not_reached ("didn't find 'lo'");
3110 _dbus_assert (i == 3);
3112 if (!_dbus_string_find (&str, 2, "lo", &i))
3113 _dbus_assert_not_reached ("didn't find 'lo'");
3114 _dbus_assert (i == 3);
3116 if (_dbus_string_find (&str, 4, "lo", &i))
3117 _dbus_assert_not_reached ("did find 'lo'");
3119 if (!_dbus_string_find (&str, 0, "l", &i))
3120 _dbus_assert_not_reached ("didn't find 'l'");
3121 _dbus_assert (i == 2);
3123 if (!_dbus_string_find (&str, 0, "H", &i))
3124 _dbus_assert_not_reached ("didn't find 'H'");
3125 _dbus_assert (i == 0);
3127 if (!_dbus_string_find (&str, 0, "", &i))
3128 _dbus_assert_not_reached ("didn't find ''");
3129 _dbus_assert (i == 0);
3131 if (_dbus_string_find (&str, 0, "Hello!", NULL))
3132 _dbus_assert_not_reached ("Did find 'Hello!'");
3134 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
3135 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
3137 if (_dbus_string_find (&str, 0, "ill", NULL))
3138 _dbus_assert_not_reached ("Did find 'ill'");
3140 if (_dbus_string_find (&str, 0, "q", NULL))
3141 _dbus_assert_not_reached ("Did find 'q'");
3143 if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
3144 _dbus_assert_not_reached ("Didn't find 'He'");
3146 if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
3147 _dbus_assert_not_reached ("Did find 'Hello'");
3149 _dbus_string_free (&str);
3151 /* Base 64 and Hex encoding */
3152 test_roundtrips (test_base64_roundtrip);
3153 test_roundtrips (test_hex_roundtrip);
3158 #endif /* DBUS_BUILD_TESTS */