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 */
30 * @defgroup DBusString string class
31 * @ingroup DBusInternals
32 * @brief DBusString data structure
34 * Types and functions related to DBusString. DBusString is intended
35 * to be a string class that makes it hard to mess up security issues
36 * (and just in general harder to write buggy code). It should be
37 * used (or extended and then used) rather than the libc stuff in
38 * string.h. The string class is a bit inconvenient at spots because
39 * it handles out-of-memory failures and tries to be extra-robust.
41 * A DBusString has a maximum length set at initialization time; this
42 * can be used to ensure that a buffer doesn't get too big. The
43 * _dbus_string_lengthen() method checks for overflow, and for max
44 * length being exceeded.
46 * Try to avoid conversion to a plain C string, i.e. add methods on
47 * the string object instead, only convert to C string when passing
48 * things out to the public API. In particular, no sprintf, strcpy,
49 * strcat, any of that should be used. The GString feature of
50 * accepting negative numbers for "length of string" is also absent,
51 * because it could keep us from detecting bogus huge lengths. i.e. if
52 * we passed in some bogus huge length it would be taken to mean
53 * "current length of string" instead of "broken crack"
57 * @defgroup DBusStringInternals DBusString implementation details
58 * @ingroup DBusInternals
59 * @brief DBusString implementation details
61 * The guts of DBusString.
67 * @brief Internals of DBusString.
69 * DBusString internals. DBusString is an opaque objects, it must be
70 * used via accessor functions.
74 unsigned char *str; /**< String data, plus nul termination */
75 int len; /**< Length without nul */
76 int allocated; /**< Allocated size of data */
77 int max_length; /**< Max length of this string, without nul byte */
78 unsigned int constant : 1; /**< String data is not owned by DBusString */
79 unsigned int locked : 1; /**< DBusString has been locked and can't be changed */
80 unsigned int invalid : 1; /**< DBusString is invalid (e.g. already freed) */
81 unsigned int align_offset : 3; /**< str - align_offset is the actual malloc block */
85 * We allocate 1 byte for nul termination, plus 7 bytes for possible
86 * align_offset, so we always need 8 bytes on top of the string's
87 * length to be in the allocated block.
89 #define ALLOCATION_PADDING 8
92 * This is the maximum max length (and thus also the maximum length)
95 #define MAX_MAX_LENGTH (_DBUS_INT_MAX - ALLOCATION_PADDING)
98 * Checks a bunch of assertions about a string object
100 * @param real the DBusRealString
102 #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)
105 * Checks assertions about a string object that needs to be
106 * modifiable - may not be locked or const. Also declares
107 * the "real" variable pointing to DBusRealString.
108 * @param str the string
110 #define DBUS_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
111 DBUS_GENERIC_STRING_PREAMBLE (real); \
112 _dbus_assert (!(real)->constant); \
113 _dbus_assert (!(real)->locked)
116 * Checks assertions about a string object that may be locked but
117 * can't be const. i.e. a string object that we can free. Also
118 * declares the "real" variable pointing to DBusRealString.
120 * @param str the string
122 #define DBUS_LOCKED_STRING_PREAMBLE(str) DBusRealString *real = (DBusRealString*) str; \
123 DBUS_GENERIC_STRING_PREAMBLE (real); \
124 _dbus_assert (!(real)->constant)
127 * Checks assertions about a string that may be const or locked. Also
128 * declares the "real" variable pointing to DBusRealString.
129 * @param str the string.
131 #define DBUS_CONST_STRING_PREAMBLE(str) const DBusRealString *real = (DBusRealString*) str; \
132 DBUS_GENERIC_STRING_PREAMBLE (real)
137 * @addtogroup DBusString
142 fixup_alignment (DBusRealString *real)
146 unsigned int old_align_offset;
148 /* we have to have extra space in real->allocated for the align offset and nul byte */
149 _dbus_assert (real->len <= real->allocated - ALLOCATION_PADDING);
151 old_align_offset = real->align_offset;
152 real_block = real->str - old_align_offset;
154 aligned = _DBUS_ALIGN_ADDRESS (real_block, 8);
156 real->align_offset = aligned - real_block;
159 if (old_align_offset != real->align_offset)
161 /* Here comes the suck */
162 memmove (real_block + real->align_offset,
163 real_block + old_align_offset,
167 _dbus_assert (real->align_offset < 8);
168 _dbus_assert (_DBUS_ALIGN_ADDRESS (real->str, 8) == real->str);
172 * Initializes a string. The maximum length may be _DBUS_INT_MAX for
173 * no maximum. The string starts life with zero length.
174 * The string must eventually be freed with _dbus_string_free().
176 * @todo the max length feature is useless, because it looks to the
177 * app like out of memory, and the app might try to "recover" - but
178 * recovery in this case is impossible, as we can't ever "get more
179 * memory" - so should delete the max length feature I think. Well, at
180 * least there's a strong caveat that it can only be used when
181 * out-of-memory is a permanent fatal error.
183 * @todo we could make this init routine not alloc any memory and
184 * return void, would simplify a lot of code, however it might
185 * complexify things elsewhere because _dbus_string_get_data()
186 * etc. could suddenly fail as they'd need to alloc new memory.
188 * @param str memory to hold the string
189 * @param max_length the maximum size of the string
190 * @returns #TRUE on success */
192 _dbus_string_init (DBusString *str,
195 DBusRealString *real;
197 _dbus_assert (str != NULL);
198 _dbus_assert (max_length >= 0);
200 _dbus_assert (sizeof (DBusString) == sizeof (DBusRealString));
202 real = (DBusRealString*) str;
204 /* It's very important not to touch anything
205 * other than real->str if we're going to fail,
206 * since we also use this function to reset
207 * an existing string, e.g. in _dbus_string_steal_data()
210 real->str = dbus_malloc (ALLOCATION_PADDING);
211 if (real->str == NULL)
214 real->allocated = ALLOCATION_PADDING;
216 real->str[real->len] = '\0';
218 real->max_length = max_length;
219 if (real->max_length > MAX_MAX_LENGTH)
220 real->max_length = MAX_MAX_LENGTH;
221 real->constant = FALSE;
222 real->locked = FALSE;
223 real->invalid = FALSE;
224 real->align_offset = 0;
226 fixup_alignment (real);
232 * Initializes a constant string. The value parameter is not copied
233 * (should be static), and the string may never be modified.
234 * It is safe but not necessary to call _dbus_string_free()
235 * on a const string. The string has a length limit of MAXINT - 8.
237 * @param str memory to use for the string
238 * @param value a string to be stored in str (not copied!!!)
241 _dbus_string_init_const (DBusString *str,
244 _dbus_assert (value != NULL);
246 _dbus_string_init_const_len (str, value,
251 * Initializes a constant string with a length. The value parameter is
252 * not copied (should be static), and the string may never be
253 * modified. It is safe but not necessary to call _dbus_string_free()
256 * @param str memory to use for the string
257 * @param value a string to be stored in str (not copied!!!)
258 * @param len the length to use
261 _dbus_string_init_const_len (DBusString *str,
265 DBusRealString *real;
267 _dbus_assert (str != NULL);
268 _dbus_assert (value != NULL);
269 _dbus_assert (len <= MAX_MAX_LENGTH);
270 _dbus_assert (len >= 0);
272 real = (DBusRealString*) str;
274 real->str = (char*) value;
276 real->allocated = real->len + ALLOCATION_PADDING; /* a lie, just to avoid special-case assertions... */
277 real->max_length = real->len + 1;
278 real->constant = TRUE;
279 real->invalid = FALSE;
281 /* We don't require const strings to be 8-byte aligned as the
282 * memory is coming from elsewhere.
287 * Frees a string created by _dbus_string_init().
289 * @param str memory where the string is stored.
292 _dbus_string_free (DBusString *str)
294 DBusRealString *real = (DBusRealString*) str;
295 DBUS_GENERIC_STRING_PREAMBLE (real);
299 dbus_free (real->str);
301 real->invalid = TRUE;
305 * Locks a string such that any attempts to change the string will
306 * result in aborting the program. Also, if the string is wasting a
307 * lot of memory (allocation is sufficiently larger than what the
308 * string is really using), _dbus_string_lock() will realloc the
309 * string's data to "compact" it.
311 * @param str the string to lock.
314 _dbus_string_lock (DBusString *str)
316 DBUS_LOCKED_STRING_PREAMBLE (str); /* can lock multiple times */
320 /* Try to realloc to avoid excess memory usage, since
321 * we know we won't change the string further
324 if (real->allocated - MAX_WASTE > real->len)
329 new_allocated = real->len + ALLOCATION_PADDING;
331 new_str = dbus_realloc (real->str - real->align_offset,
335 real->str = new_str + real->align_offset;
336 real->allocated = new_allocated;
337 fixup_alignment (real);
343 set_length (DBusRealString *real,
346 /* Note, we are setting the length without nul termination */
348 /* exceeding max length is the same as failure to allocate memory */
349 if (new_length > real->max_length)
352 if (new_length > (real->allocated - ALLOCATION_PADDING))
357 /* at least double our old allocation to avoid O(n), avoiding
360 if (real->allocated > (MAX_MAX_LENGTH + ALLOCATION_PADDING) / 2)
361 new_allocated = MAX_MAX_LENGTH + ALLOCATION_PADDING;
363 new_allocated = real->allocated * 2;
365 /* But be sure we always alloc at least space for the new length */
366 new_allocated = MAX (real->allocated, new_length + ALLOCATION_PADDING);
368 new_str = dbus_realloc (real->str - real->align_offset, new_allocated);
372 real->str = new_str + real->align_offset;
373 real->allocated = new_allocated;
374 fixup_alignment (real);
377 real->len = new_length;
378 real->str[real->len] = '\0';
385 DBusRealString *dest,
391 if (len > dest->max_length - dest->len)
392 return FALSE; /* detected overflow of dest->len + len below */
394 if (!set_length (dest, dest->len + len))
397 memmove (dest->str + insert_at + len,
398 dest->str + insert_at,
399 dest->len - len - insert_at);
405 * Gets the raw character buffer from the string. The returned buffer
406 * will be nul-terminated, but note that strings may contain binary
407 * data so there may be extra nul characters prior to the termination.
408 * This function should be little-used, extend DBusString or add
409 * stuff to dbus-sysdeps.c instead. It's an error to use this
410 * function on a const string.
412 * @param str the string
413 * @param data_return place to store the returned data
416 _dbus_string_get_data (DBusString *str,
419 DBUS_STRING_PREAMBLE (str);
420 _dbus_assert (data_return != NULL);
422 *data_return = real->str;
426 * Gets the raw character buffer from a const string.
428 * @todo should return the const char* instead of using an out param;
429 * the temporary variable encourages a bug where you use const data
430 * after modifying the string and possibly causing a realloc.
432 * @param str the string
433 * @param data_return location to store returned data
436 _dbus_string_get_const_data (const DBusString *str,
437 const char **data_return)
439 DBUS_CONST_STRING_PREAMBLE (str);
440 _dbus_assert (data_return != NULL);
442 *data_return = real->str;
446 * Gets a sub-portion of the raw character buffer from the
447 * string. The "len" field is required simply for error
448 * checking, to be sure you don't try to use more
449 * string than exists. The nul termination of the
450 * returned buffer remains at the end of the entire
451 * string, not at start + len.
453 * @param str the string
454 * @param data_return location to return the buffer
455 * @param start byte offset to return
456 * @param len length of segment to return
459 _dbus_string_get_data_len (DBusString *str,
464 DBUS_STRING_PREAMBLE (str);
465 _dbus_assert (data_return != NULL);
466 _dbus_assert (start >= 0);
467 _dbus_assert (len >= 0);
468 _dbus_assert (start <= real->len);
469 _dbus_assert (len <= real->len - start);
471 *data_return = real->str + start;
475 * const version of _dbus_string_get_data_len().
477 * @todo should return the const char* instead of using an out param;
478 * the temporary variable encourages a bug where you use const data
479 * after modifying the string and possibly causing a realloc.
481 * @param str the string
482 * @param data_return location to return the buffer
483 * @param start byte offset to return
484 * @param len length of segment to return
487 _dbus_string_get_const_data_len (const DBusString *str,
488 const char **data_return,
492 DBUS_CONST_STRING_PREAMBLE (str);
493 _dbus_assert (data_return != NULL);
494 _dbus_assert (start >= 0);
495 _dbus_assert (len >= 0);
496 _dbus_assert (start <= real->len);
497 _dbus_assert (len <= real->len - start);
499 *data_return = real->str + start;
503 * Sets the value of the byte at the given position.
505 * @param str the string
506 * @param i the position
507 * @param byte the new value
510 _dbus_string_set_byte (DBusString *str,
514 DBUS_STRING_PREAMBLE (str);
515 _dbus_assert (i < real->len);
516 _dbus_assert (i >= 0);
522 * Gets the byte at the given position.
524 * @param str the string
525 * @param start the position
526 * @returns the byte at that position
529 _dbus_string_get_byte (const DBusString *str,
532 DBUS_CONST_STRING_PREAMBLE (str);
533 _dbus_assert (start < real->len);
534 _dbus_assert (start >= 0);
536 return real->str[start];
540 * Inserts the given byte at the given position.
542 * @param str the string
543 * @param i the position
544 * @param byte the value to insert
545 * @returns #TRUE on success
548 _dbus_string_insert_byte (DBusString *str,
552 DBUS_STRING_PREAMBLE (str);
553 _dbus_assert (i <= real->len);
554 _dbus_assert (i >= 0);
556 if (!open_gap (1, real, i))
565 * Like _dbus_string_get_data(), but removes the
566 * gotten data from the original string. The caller
567 * must free the data returned. This function may
568 * fail due to lack of memory, and return #FALSE.
570 * @param str the string
571 * @param data_return location to return the buffer
572 * @returns #TRUE on success
575 _dbus_string_steal_data (DBusString *str,
578 DBUS_STRING_PREAMBLE (str);
579 _dbus_assert (data_return != NULL);
581 *data_return = real->str;
583 /* reset the string */
584 if (!_dbus_string_init (str, real->max_length))
586 /* hrm, put it back then */
587 real->str = *data_return;
596 * Like _dbus_string_get_data_len(), but removes the gotten data from
597 * the original string. The caller must free the data returned. This
598 * function may fail due to lack of memory, and return #FALSE.
599 * The returned string is nul-terminated and has length len.
601 * @todo this function is broken because on failure it
602 * may corrupt the source string.
604 * @param str the string
605 * @param data_return location to return the buffer
606 * @param start the start of segment to steal
607 * @param len the length of segment to steal
608 * @returns #TRUE on success
611 _dbus_string_steal_data_len (DBusString *str,
618 DBUS_STRING_PREAMBLE (str);
619 _dbus_assert (data_return != NULL);
620 _dbus_assert (start >= 0);
621 _dbus_assert (len >= 0);
622 _dbus_assert (start <= real->len);
623 _dbus_assert (len <= real->len - start);
625 if (!_dbus_string_init (&dest, real->max_length))
628 if (!_dbus_string_move_len (str, start, len, &dest, 0))
630 _dbus_string_free (&dest);
634 _dbus_warn ("Broken code in _dbus_string_steal_data_len(), FIXME\n");
635 if (!_dbus_string_steal_data (&dest, data_return))
637 _dbus_string_free (&dest);
641 _dbus_string_free (&dest);
646 * Gets the length of a string (not including nul termination).
648 * @returns the length.
651 _dbus_string_get_length (const DBusString *str)
653 DBUS_CONST_STRING_PREAMBLE (str);
659 * Makes a string longer by the given number of bytes. Checks whether
660 * adding additional_length to the current length would overflow an
661 * integer, and checks for exceeding a string's max length.
662 * The new bytes are not initialized, other than nul-terminating
663 * the end of the string. The uninitialized bytes may contain
664 * nul bytes or other junk.
666 * @param str a string
667 * @param additional_length length to add to the string.
668 * @returns #TRUE on success.
671 _dbus_string_lengthen (DBusString *str,
672 int additional_length)
674 DBUS_STRING_PREAMBLE (str);
675 _dbus_assert (additional_length >= 0);
677 if (additional_length > real->max_length - real->len)
678 return FALSE; /* would overflow */
680 return set_length (real,
681 real->len + additional_length);
685 * Makes a string shorter by the given number of bytes.
687 * @param str a string
688 * @param length_to_remove length to remove from the string.
691 _dbus_string_shorten (DBusString *str,
692 int length_to_remove)
694 DBUS_STRING_PREAMBLE (str);
695 _dbus_assert (length_to_remove >= 0);
696 _dbus_assert (length_to_remove <= real->len);
699 real->len - length_to_remove);
703 * Sets the length of a string. Can be used to truncate or lengthen
704 * the string. If the string is lengthened, the function may fail and
705 * return #FALSE. Newly-added bytes are not initialized, as with
706 * _dbus_string_lengthen().
708 * @param str a string
709 * @param length new length of the string.
710 * @returns #FALSE on failure.
713 _dbus_string_set_length (DBusString *str,
716 DBUS_STRING_PREAMBLE (str);
717 _dbus_assert (length >= 0);
719 return set_length (real, length);
723 * Align the length of a string to a specific alignment (typically 4 or 8)
724 * by appending nul bytes to the string.
726 * @param str a string
727 * @param alignment the alignment
728 * @returns #FALSE if no memory
731 _dbus_string_align_length (DBusString *str,
734 unsigned long new_len; /* ulong to avoid _DBUS_ALIGN_VALUE overflow */
736 DBUS_STRING_PREAMBLE (str);
737 _dbus_assert (alignment >= 1);
738 _dbus_assert (alignment <= 8); /* it has to be a bug if > 8 */
740 new_len = _DBUS_ALIGN_VALUE (real->len, alignment);
741 if (new_len > (unsigned long) real->max_length)
744 delta = new_len - real->len;
745 _dbus_assert (delta >= 0);
750 if (!set_length (real, new_len))
753 memset (real->str + (new_len - delta),
760 append (DBusRealString *real,
767 if (!_dbus_string_lengthen ((DBusString*)real, buffer_len))
770 memcpy (real->str + (real->len - buffer_len),
778 * Appends a nul-terminated C-style string to a DBusString.
780 * @param str the DBusString
781 * @param buffer the nul-terminated characters to append
782 * @returns #FALSE if not enough memory.
785 _dbus_string_append (DBusString *str,
788 unsigned long buffer_len;
790 DBUS_STRING_PREAMBLE (str);
791 _dbus_assert (buffer != NULL);
793 buffer_len = strlen (buffer);
794 if (buffer_len > (unsigned long) real->max_length)
797 return append (real, buffer, buffer_len);
801 * Appends block of bytes with the given length to a DBusString.
803 * @param str the DBusString
804 * @param buffer the bytes to append
805 * @param len the number of bytes to append
806 * @returns #FALSE if not enough memory.
809 _dbus_string_append_len (DBusString *str,
813 DBUS_STRING_PREAMBLE (str);
814 _dbus_assert (buffer != NULL);
815 _dbus_assert (len >= 0);
817 return append (real, buffer, len);
821 * Appends a single byte to the string, returning #FALSE
822 * if not enough memory.
824 * @param str the string
825 * @param byte the byte to append
826 * @returns #TRUE on success
829 _dbus_string_append_byte (DBusString *str,
832 DBUS_STRING_PREAMBLE (str);
834 if (!set_length (real, real->len + 1))
837 real->str[real->len-1] = byte;
843 * Appends a single Unicode character, encoding the character
846 * @param str the string
847 * @param ch the Unicode character
850 _dbus_string_append_unichar (DBusString *str,
858 DBUS_STRING_PREAMBLE (str);
860 /* this code is from GLib but is pretty standard I think */
874 else if (ch < 0x10000)
879 else if (ch < 0x200000)
884 else if (ch < 0x4000000)
895 if (len > (real->max_length - real->len))
896 return FALSE; /* real->len + len would overflow */
898 if (!set_length (real, real->len + len))
901 out = real->str + (real->len - len);
903 for (i = len - 1; i > 0; --i)
905 out[i] = (ch & 0x3f) | 0x80;
914 delete (DBusRealString *real,
921 memmove (real->str + start, real->str + start + len, real->len - (start + len));
923 real->str[real->len] = '\0';
927 * Deletes a segment of a DBusString with length len starting at
928 * start. (Hint: to clear an entire string, setting length to 0
929 * with _dbus_string_set_length() is easier.)
931 * @param str the DBusString
932 * @param start where to start deleting
933 * @param len the number of bytes to delete
936 _dbus_string_delete (DBusString *str,
940 DBUS_STRING_PREAMBLE (str);
941 _dbus_assert (start >= 0);
942 _dbus_assert (len >= 0);
943 _dbus_assert (start <= real->len);
944 _dbus_assert (len <= real->len - start);
946 delete (real, start, len);
950 copy (DBusRealString *source,
953 DBusRealString *dest,
959 if (!open_gap (len, dest, insert_at))
962 memcpy (dest->str + insert_at,
970 * Checks assertions for two strings we're copying a segment between,
971 * and declares real_source/real_dest variables.
973 * @param source the source string
974 * @param start the starting offset
975 * @param dest the dest string
976 * @param insert_at where the copied segment is inserted
978 #define DBUS_STRING_COPY_PREAMBLE(source, start, dest, insert_at) \
979 DBusRealString *real_source = (DBusRealString*) source; \
980 DBusRealString *real_dest = (DBusRealString*) dest; \
981 _dbus_assert ((source) != (dest)); \
982 DBUS_GENERIC_STRING_PREAMBLE (real_source); \
983 DBUS_GENERIC_STRING_PREAMBLE (real_dest); \
984 _dbus_assert (!real_dest->constant); \
985 _dbus_assert (!real_dest->locked); \
986 _dbus_assert ((start) >= 0); \
987 _dbus_assert ((start) <= real_source->len); \
988 _dbus_assert ((insert_at) >= 0); \
989 _dbus_assert ((insert_at) <= real_dest->len)
992 * Moves the end of one string into another string. Both strings
993 * must be initialized, valid strings.
995 * @param source the source string
996 * @param start where to chop off the source string
997 * @param dest the destination string
998 * @param insert_at where to move the chopped-off part of source string
999 * @returns #FALSE if not enough memory
1002 _dbus_string_move (DBusString *source,
1007 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1009 if (!copy (real_source, start,
1010 real_source->len - start,
1015 delete (real_source, start,
1016 real_source->len - start);
1022 * Like _dbus_string_move(), but does not delete the section
1023 * of the source string that's copied to the dest string.
1025 * @param source the source string
1026 * @param start where to start copying the source string
1027 * @param dest the destination string
1028 * @param insert_at where to place the copied part of source string
1029 * @returns #FALSE if not enough memory
1032 _dbus_string_copy (const DBusString *source,
1037 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1039 return copy (real_source, start,
1040 real_source->len - start,
1046 * Like _dbus_string_move(), but can move a segment from
1047 * the middle of the source string.
1049 * @param source the source string
1050 * @param start first byte of source string to move
1051 * @param len length of segment to move
1052 * @param dest the destination string
1053 * @param insert_at where to move the bytes from the source string
1054 * @returns #FALSE if not enough memory
1057 _dbus_string_move_len (DBusString *source,
1064 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1065 _dbus_assert (len >= 0);
1066 _dbus_assert ((start + len) <= real_source->len);
1068 if (!copy (real_source, start, len,
1073 delete (real_source, start,
1080 * Like _dbus_string_copy(), but can copy a segment from the middle of
1081 * the source string.
1083 * @param source the source string
1084 * @param start where to start copying the source string
1085 * @param len length of segment to copy
1086 * @param dest the destination string
1087 * @param insert_at where to place the copied segment of source string
1088 * @returns #FALSE if not enough memory
1091 _dbus_string_copy_len (const DBusString *source,
1097 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1098 _dbus_assert (len >= 0);
1099 _dbus_assert (start <= real_source->len);
1100 _dbus_assert (len <= real_source->len - start);
1102 return copy (real_source, start, len,
1108 * Replaces a segment of dest string with a segment of source string.
1110 * @todo optimize the case where the two lengths are the same, and
1111 * avoid memmoving the data in the trailing part of the string twice.
1113 * @todo avoid inserting the source into dest, then deleting
1114 * the replaced chunk of dest (which creates a potentially large
1115 * intermediate string). Instead, extend the replaced chunk
1116 * of dest with padding to the same size as the source chunk,
1117 * then copy in the source bytes.
1119 * @param source the source string
1120 * @param start where to start copying the source string
1121 * @param len length of segment to copy
1122 * @param dest the destination string
1123 * @param replace_at start of segment of dest string to replace
1124 * @param replace_len length of segment of dest string to replace
1125 * @returns #FALSE if not enough memory
1129 _dbus_string_replace_len (const DBusString *source,
1136 DBUS_STRING_COPY_PREAMBLE (source, start, dest, replace_at);
1137 _dbus_assert (len >= 0);
1138 _dbus_assert (start <= real_source->len);
1139 _dbus_assert (len <= real_source->len - start);
1140 _dbus_assert (replace_at >= 0);
1141 _dbus_assert (replace_at <= real_dest->len);
1142 _dbus_assert (replace_len <= real_dest->len - replace_at);
1144 if (!copy (real_source, start, len,
1145 real_dest, replace_at))
1148 delete (real_dest, replace_at + len, replace_len);
1153 /* Unicode macros from GLib */
1155 /** computes length and mask of a unicode character
1156 * @param Char the char
1157 * @param Mask the mask variable to assign to
1158 * @param Len the length variable to assign to
1160 #define UTF8_COMPUTE(Char, Mask, Len) \
1166 else if ((Char & 0xe0) == 0xc0) \
1171 else if ((Char & 0xf0) == 0xe0) \
1176 else if ((Char & 0xf8) == 0xf0) \
1181 else if ((Char & 0xfc) == 0xf8) \
1186 else if ((Char & 0xfe) == 0xfc) \
1195 * computes length of a unicode character in UTF-8
1196 * @param Char the char
1198 #define UTF8_LENGTH(Char) \
1199 ((Char) < 0x80 ? 1 : \
1200 ((Char) < 0x800 ? 2 : \
1201 ((Char) < 0x10000 ? 3 : \
1202 ((Char) < 0x200000 ? 4 : \
1203 ((Char) < 0x4000000 ? 5 : 6)))))
1206 * Gets a UTF-8 value.
1208 * @param Result variable for extracted unicode char.
1209 * @param Chars the bytes to decode
1210 * @param Count counter variable
1211 * @param Mask mask for this char
1212 * @param Len length for this char in bytes
1214 #define UTF8_GET(Result, Chars, Count, Mask, Len) \
1215 (Result) = (Chars)[0] & (Mask); \
1216 for ((Count) = 1; (Count) < (Len); ++(Count)) \
1218 if (((Chars)[(Count)] & 0xc0) != 0x80) \
1224 (Result) |= ((Chars)[(Count)] & 0x3f); \
1228 * Check whether a unicode char is in a valid range.
1230 * @param Char the character
1232 #define UNICODE_VALID(Char) \
1233 ((Char) < 0x110000 && \
1234 ((Char) < 0xD800 || (Char) >= 0xE000) && \
1235 (Char) != 0xFFFE && (Char) != 0xFFFF)
1238 * Gets a unicode character from a UTF-8 string. Does no validation;
1239 * you must verify that the string is valid UTF-8 in advance and must
1240 * pass in the start of a character.
1242 * @param str the string
1243 * @param start the start of the UTF-8 character.
1244 * @param ch_return location to return the character
1245 * @param end_return location to return the byte index of next character
1248 _dbus_string_get_unichar (const DBusString *str,
1250 dbus_unichar_t *ch_return,
1254 dbus_unichar_t result;
1257 DBUS_CONST_STRING_PREAMBLE (str);
1258 _dbus_assert (start >= 0);
1259 _dbus_assert (start <= real->len);
1264 *end_return = real->len;
1267 p = real->str + start;
1270 UTF8_COMPUTE (c, mask, len);
1273 UTF8_GET (result, p, i, mask, len);
1275 if (result == (dbus_unichar_t)-1)
1279 *ch_return = result;
1281 *end_return = start + len;
1285 * Finds the given substring in the string,
1286 * returning #TRUE and filling in the byte index
1287 * where the substring was found, if it was found.
1288 * Returns #FALSE if the substring wasn't found.
1289 * Sets *start to the length of the string if the substring
1292 * @param str the string
1293 * @param start where to start looking
1294 * @param substr the substring
1295 * @param found return location for where it was found, or #NULL
1296 * @returns #TRUE if found
1299 _dbus_string_find (const DBusString *str,
1304 return _dbus_string_find_to (str, start,
1305 ((const DBusRealString*)str)->len,
1310 * Finds the given substring in the string,
1311 * up to a certain position,
1312 * returning #TRUE and filling in the byte index
1313 * where the substring was found, if it was found.
1314 * Returns #FALSE if the substring wasn't found.
1315 * Sets *start to the length of the string if the substring
1318 * @param str the string
1319 * @param start where to start looking
1320 * @param end where to stop looking
1321 * @param substr the substring
1322 * @param found return location for where it was found, or #NULL
1323 * @returns #TRUE if found
1326 _dbus_string_find_to (const DBusString *str,
1333 DBUS_CONST_STRING_PREAMBLE (str);
1334 _dbus_assert (substr != NULL);
1335 _dbus_assert (start <= real->len);
1336 _dbus_assert (start >= 0);
1337 _dbus_assert (substr != NULL);
1338 _dbus_assert (end <= real->len);
1339 _dbus_assert (start <= end);
1341 /* we always "find" an empty string */
1342 if (*substr == '\0')
1352 if (real->str[i] == substr[0])
1358 if (substr[j - i] == '\0')
1360 else if (real->str[j] != substr[j - i])
1366 if (substr[j - i] == '\0')
1384 * Finds a blank (space or tab) in the string. Returns #TRUE
1385 * if found, #FALSE otherwise. If a blank is not found sets
1386 * *found to the length of the string.
1388 * @param str the string
1389 * @param start byte index to start looking
1390 * @param found place to store the location of the first blank
1391 * @returns #TRUE if a blank was found
1394 _dbus_string_find_blank (const DBusString *str,
1399 DBUS_CONST_STRING_PREAMBLE (str);
1400 _dbus_assert (start <= real->len);
1401 _dbus_assert (start >= 0);
1404 while (i < real->len)
1406 if (real->str[i] == ' ' ||
1407 real->str[i] == '\t')
1424 * Skips blanks from start, storing the first non-blank in *end
1426 * @param str the string
1427 * @param start where to start
1428 * @param end where to store the first non-blank byte index
1431 _dbus_string_skip_blank (const DBusString *str,
1436 DBUS_CONST_STRING_PREAMBLE (str);
1437 _dbus_assert (start <= real->len);
1438 _dbus_assert (start >= 0);
1441 while (i < real->len)
1443 if (!(real->str[i] == ' ' ||
1444 real->str[i] == '\t'))
1450 _dbus_assert (i == real->len || !(real->str[i] == ' ' ||
1451 real->str[i] == '\t'));
1458 * Assigns a newline-terminated or \r\n-terminated line from the front
1459 * of the string to the given dest string. The dest string's previous
1460 * contents are deleted. If the source string contains no newline,
1461 * moves the entire source string to the dest string.
1463 * @todo owen correctly notes that this is a stupid function (it was
1464 * written purely for test code,
1465 * e.g. dbus-message-builder.c). Probably should be enforced as test
1466 * code only with #ifdef DBUS_BUILD_TESTS
1468 * @param source the source string
1469 * @param dest the destination string (contents are replaced)
1470 * @returns #FALSE if no memory, or source has length 0
1473 _dbus_string_pop_line (DBusString *source,
1477 dbus_bool_t have_newline;
1479 _dbus_string_set_length (dest, 0);
1482 if (_dbus_string_find (source, 0, "\n", &eol))
1484 have_newline = TRUE;
1485 eol += 1; /* include newline */
1489 eol = _dbus_string_get_length (source);
1490 have_newline = FALSE;
1494 return FALSE; /* eof */
1496 if (!_dbus_string_move_len (source, 0, eol,
1502 /* dump the newline and the \r if we have one */
1505 dbus_bool_t have_cr;
1507 _dbus_assert (_dbus_string_get_length (dest) > 0);
1509 if (_dbus_string_get_length (dest) > 1 &&
1510 _dbus_string_get_byte (dest,
1511 _dbus_string_get_length (dest) - 2) == '\r')
1516 _dbus_string_set_length (dest,
1517 _dbus_string_get_length (dest) -
1525 * Deletes up to and including the first blank space
1528 * @param str the string
1531 _dbus_string_delete_first_word (DBusString *str)
1535 if (_dbus_string_find_blank (str, 0, &i))
1536 _dbus_string_skip_blank (str, i, &i);
1538 _dbus_string_delete (str, 0, i);
1542 * Deletes any leading blanks in the string
1544 * @param str the string
1547 _dbus_string_delete_leading_blanks (DBusString *str)
1551 _dbus_string_skip_blank (str, 0, &i);
1554 _dbus_string_delete (str, 0, i);
1558 * Tests two DBusString for equality.
1560 * @todo memcmp is probably faster
1562 * @param a first string
1563 * @param b second string
1564 * @returns #TRUE if equal
1567 _dbus_string_equal (const DBusString *a,
1568 const DBusString *b)
1570 const unsigned char *ap;
1571 const unsigned char *bp;
1572 const unsigned char *a_end;
1573 const DBusRealString *real_a = (const DBusRealString*) a;
1574 const DBusRealString *real_b = (const DBusRealString*) b;
1575 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1576 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1578 if (real_a->len != real_b->len)
1583 a_end = real_a->str + real_a->len;
1597 * Tests two DBusString for equality up to the given length.
1599 * @todo write a unit test
1601 * @todo memcmp is probably faster
1603 * @param a first string
1604 * @param b second string
1605 * @param len the lengh
1606 * @returns #TRUE if equal for the given number of bytes
1609 _dbus_string_equal_len (const DBusString *a,
1610 const DBusString *b,
1613 const unsigned char *ap;
1614 const unsigned char *bp;
1615 const unsigned char *a_end;
1616 const DBusRealString *real_a = (const DBusRealString*) a;
1617 const DBusRealString *real_b = (const DBusRealString*) b;
1618 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1619 DBUS_GENERIC_STRING_PREAMBLE (real_b);
1621 if (real_a->len != real_b->len &&
1622 (real_a->len < len || real_b->len < len))
1627 a_end = real_a->str + MIN (real_a->len, len);
1641 * Checks whether a string is equal to a C string.
1643 * @param a the string
1644 * @param c_str the C string
1645 * @returns #TRUE if equal
1648 _dbus_string_equal_c_str (const DBusString *a,
1651 const unsigned char *ap;
1652 const unsigned char *bp;
1653 const unsigned char *a_end;
1654 const DBusRealString *real_a = (const DBusRealString*) a;
1655 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1656 _dbus_assert (c_str != NULL);
1659 bp = (const unsigned char*) c_str;
1660 a_end = real_a->str + real_a->len;
1661 while (ap != a_end && *bp)
1670 if (ap != a_end || *bp)
1677 * Checks whether a string starts with the given C string.
1679 * @param a the string
1680 * @param c_str the C string
1681 * @returns #TRUE if string starts with it
1684 _dbus_string_starts_with_c_str (const DBusString *a,
1687 const unsigned char *ap;
1688 const unsigned char *bp;
1689 const unsigned char *a_end;
1690 const DBusRealString *real_a = (const DBusRealString*) a;
1691 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1692 _dbus_assert (c_str != NULL);
1695 bp = (const unsigned char*) c_str;
1696 a_end = real_a->str + real_a->len;
1697 while (ap != a_end && *bp)
1713 * Returns whether a string ends with the given suffix
1715 * @todo memcmp might make this faster.
1717 * @param a the string
1718 * @param c_str the C-style string
1719 * @returns #TRUE if the string ends with the suffix
1722 _dbus_string_ends_with_c_str (const DBusString *a,
1725 const unsigned char *ap;
1726 const unsigned char *bp;
1727 const unsigned char *a_end;
1728 unsigned long c_str_len;
1729 const DBusRealString *real_a = (const DBusRealString*) a;
1730 DBUS_GENERIC_STRING_PREAMBLE (real_a);
1731 _dbus_assert (c_str != NULL);
1733 c_str_len = strlen (c_str);
1734 if (((unsigned long)real_a->len) < c_str_len)
1737 ap = real_a->str + (real_a->len - c_str_len);
1738 bp = (const unsigned char*) c_str;
1739 a_end = real_a->str + real_a->len;
1749 _dbus_assert (*ap == '\0');
1750 _dbus_assert (*bp == '\0');
1755 static const signed char base64_table[] = {
1822 /** The minimum char that's a valid char in Base64-encoded text */
1823 #define UNBASE64_MIN_CHAR (43)
1824 /** The maximum char that's a valid char in Base64-encoded text */
1825 #define UNBASE64_MAX_CHAR (122)
1826 /** Must subtract this from a char's integer value before offsetting
1827 * into unbase64_table
1829 #define UNBASE64_TABLE_OFFSET UNBASE64_MIN_CHAR
1830 static const signed char unbase64_table[] = {
1914 * Encodes a string using Base64, as documented in RFC 2045.
1916 * @param source the string to encode
1917 * @param start byte index to start encoding
1918 * @param dest string where encoded data should be placed
1919 * @param insert_at where to place encoded data
1920 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
1923 _dbus_string_base64_encode (const DBusString *source,
1929 unsigned int dest_len; /* unsigned for overflow checks below */
1930 const unsigned char *s;
1932 const unsigned char *triplet_end;
1933 const unsigned char *final_end;
1934 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
1935 _dbus_assert (source != dest);
1937 /* For each 24 bits (3 bytes) of input, we have 4 bytes of
1940 source_len = real_source->len - start;
1941 dest_len = (source_len / 3) * 4;
1942 if (source_len % 3 != 0)
1945 if (dest_len > (unsigned int) real_dest->max_length)
1948 if (source_len == 0)
1951 if (!open_gap (dest_len, real_dest, insert_at))
1954 d = real_dest->str + insert_at;
1955 s = real_source->str + start;
1956 final_end = real_source->str + (start + source_len);
1957 triplet_end = final_end - (source_len % 3);
1958 _dbus_assert (triplet_end <= final_end);
1959 _dbus_assert ((final_end - triplet_end) < 3);
1961 #define ENCODE_64(v) (base64_table[ (unsigned char) (v) ])
1962 #define SIX_BITS_MASK (0x3f)
1963 _dbus_assert (SIX_BITS_MASK < _DBUS_N_ELEMENTS (base64_table));
1965 while (s != triplet_end)
1967 unsigned int triplet;
1969 triplet = s[2] | (s[1] << 8) | (s[0] << 16);
1971 /* Encode each 6 bits. */
1973 *d++ = ENCODE_64 (triplet >> 18);
1974 *d++ = ENCODE_64 ((triplet >> 12) & SIX_BITS_MASK);
1975 *d++ = ENCODE_64 ((triplet >> 6) & SIX_BITS_MASK);
1976 *d++ = ENCODE_64 (triplet & SIX_BITS_MASK);
1981 switch (final_end - triplet_end)
1985 unsigned int doublet;
1987 doublet = s[1] | (s[0] << 8);
1989 *d++ = ENCODE_64 (doublet >> 12);
1990 *d++ = ENCODE_64 ((doublet >> 6) & SIX_BITS_MASK);
1991 *d++ = ENCODE_64 (doublet & SIX_BITS_MASK);
1997 unsigned int singlet;
2001 *d++ = ENCODE_64 ((singlet >> 6) & SIX_BITS_MASK);
2002 *d++ = ENCODE_64 (singlet & SIX_BITS_MASK);
2011 _dbus_assert (d == (real_dest->str + (insert_at + dest_len)));
2017 * Decodes a string from Base64, as documented in RFC 2045.
2019 * @todo sort out the AUDIT comment in here. The case it mentions
2020 * ("====" or "x===") is not allowed in correct base64, so need to
2021 * decide what to do with that kind of input. Probably ignore it
2022 * since we ignore any other junk seen.
2024 * @param source the string to decode
2025 * @param start byte index to start decode
2026 * @param dest string where decoded data should be placed
2027 * @param insert_at where to place decoded data
2028 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2031 _dbus_string_base64_decode (const DBusString *source,
2040 unsigned int triplet = 0;
2043 DBUS_STRING_COPY_PREAMBLE (source, start, dest, insert_at);
2044 _dbus_assert (source != dest);
2046 source_len = real_source->len - start;
2047 s = real_source->str + start;
2048 end = real_source->str + source_len;
2050 if (source_len == 0)
2053 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2060 /* The idea is to just skip anything that isn't
2061 * a base64 char - it's allowed to have whitespace,
2062 * newlines, etc. in here. We also ignore trailing
2063 * base64 chars, though that's suspicious.
2066 if (*s >= UNBASE64_MIN_CHAR &&
2067 *s <= UNBASE64_MAX_CHAR)
2071 /* '=' is padding, doesn't represent additional data
2072 * but does increment our count.
2081 val = unbase64_table[(*s) - UNBASE64_TABLE_OFFSET];
2086 triplet |= (unsigned int) val;
2091 if (sextet_count == 4)
2093 /* no pad = 3 bytes, 1 pad = 2 bytes, 2 pad = 1 byte */
2096 /* AUDIT: Comment doesn't mention 4 pad => 0,
2097 * 3 pad => 1 byte, though the code should
2098 * work fine if those are the required outputs.
2100 * I assume that the spec requires dropping
2101 * the top two bits of, say, ///= which is > 2
2102 * bytes worth of bits. (Or otherwise, you couldn't
2103 * actually represent 2 byte sequences.
2107 _dbus_string_append_byte (&result,
2111 _dbus_string_append_byte (&result,
2112 (triplet >> 8) & 0xff);
2114 _dbus_string_append_byte (&result,
2126 if (!_dbus_string_move (&result, 0, dest, insert_at))
2128 _dbus_string_free (&result);
2132 _dbus_string_free (&result);
2138 * Encodes a string in hex, the way MD5 and SHA-1 are usually
2139 * encoded. (Each byte is two hex digits.)
2141 * @param source the string to encode
2142 * @param start byte index to start encoding
2143 * @param dest string where encoded data should be placed
2144 * @param insert_at where to place encoded data
2145 * @returns #TRUE if encoding was successful, #FALSE if no memory etc.
2148 _dbus_string_hex_encode (const DBusString *source,
2154 const char hexdigits[16] = {
2155 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
2156 'a', 'b', 'c', 'd', 'e', 'f'
2158 const unsigned char *p;
2159 const unsigned char *end;
2162 _dbus_assert (start <= _dbus_string_get_length (source));
2164 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2169 _dbus_string_get_const_data (source, (const char**) &p);
2170 end = p + _dbus_string_get_length (source);
2175 if (!_dbus_string_append_byte (&result,
2176 hexdigits[(*p >> 4)]))
2179 if (!_dbus_string_append_byte (&result,
2180 hexdigits[(*p & 0x0f)]))
2186 if (!_dbus_string_move (&result, 0, dest, insert_at))
2192 _dbus_string_free (&result);
2197 * Decodes a string from hex encoding.
2199 * @param source the string to decode
2200 * @param start byte index to start decode
2201 * @param dest string where decoded data should be placed
2202 * @param insert_at where to place decoded data
2203 * @returns #TRUE if decoding was successful, #FALSE if no memory etc.
2206 _dbus_string_hex_decode (const DBusString *source,
2212 const unsigned char *p;
2213 const unsigned char *end;
2215 dbus_bool_t high_bits;
2217 _dbus_assert (start <= _dbus_string_get_length (source));
2219 if (!_dbus_string_init (&result, _DBUS_INT_MAX))
2225 _dbus_string_get_const_data (source, (const char**) &p);
2226 end = p + _dbus_string_get_length (source);
2291 _dbus_verbose ("invalid character '%c' in hex encoded text\n",
2298 if (!_dbus_string_append_byte (&result,
2307 len = _dbus_string_get_length (&result);
2309 b = _dbus_string_get_byte (&result, len - 1);
2313 _dbus_string_set_byte (&result, len - 1, b);
2316 high_bits = !high_bits;
2321 if (!_dbus_string_move (&result, 0, dest, insert_at))
2327 _dbus_string_free (&result);
2332 * Checks that the given range of the string is valid ASCII with no
2333 * nul bytes. If the given range is not entirely contained in the
2334 * string, returns #FALSE.
2336 * @todo this is inconsistent with most of DBusString in that
2337 * it allows a start,len range that isn't in the string.
2339 * @param str the string
2340 * @param start first byte index to check
2341 * @param len number of bytes to check
2342 * @returns #TRUE if the byte range exists and is all valid ASCII
2345 _dbus_string_validate_ascii (const DBusString *str,
2349 const unsigned char *s;
2350 const unsigned char *end;
2351 DBUS_CONST_STRING_PREAMBLE (str);
2352 _dbus_assert (start >= 0);
2353 _dbus_assert (start <= real->len);
2354 _dbus_assert (len >= 0);
2356 if (len > real->len - start)
2359 s = real->str + start;
2364 ((*s & ~0x7f) != 0))
2374 * Checks that the given range of the string is valid UTF-8. If the
2375 * given range is not entirely contained in the string, returns
2376 * #FALSE. If the string contains any nul bytes in the given range,
2379 * @todo right now just calls _dbus_string_validate_ascii()
2381 * @todo this is inconsistent with most of DBusString in that
2382 * it allows a start,len range that isn't in the string.
2384 * @param str the string
2385 * @param start first byte index to check
2386 * @param len number of bytes to check
2387 * @returns #TRUE if the byte range exists and is all valid UTF-8
2390 _dbus_string_validate_utf8 (const DBusString *str,
2394 /* FIXME actually validate UTF-8 */
2395 return _dbus_string_validate_ascii (str, start, len);
2399 * Checks that the given range of the string is all nul bytes. If the
2400 * given range is not entirely contained in the string, returns
2403 * @todo this is inconsistent with most of DBusString in that
2404 * it allows a start,len range that isn't in the string.
2406 * @param str the string
2407 * @param start first byte index to check
2408 * @param len number of bytes to check
2409 * @returns #TRUE if the byte range exists and is all nul bytes
2412 _dbus_string_validate_nul (const DBusString *str,
2416 const unsigned char *s;
2417 const unsigned char *end;
2418 DBUS_CONST_STRING_PREAMBLE (str);
2419 _dbus_assert (start >= 0);
2420 _dbus_assert (len >= 0);
2421 _dbus_assert (start <= real->len);
2423 if (len > real->len - start)
2426 s = real->str + start;
2439 * Clears all allocated bytes in the string to zero.
2441 * @param str the string
2444 _dbus_string_zero (DBusString *str)
2446 DBUS_STRING_PREAMBLE (str);
2448 memset (real->str, '\0', real->allocated);
2453 #ifdef DBUS_BUILD_TESTS
2454 #include "dbus-test.h"
2458 test_max_len (DBusString *str,
2463 if (!_dbus_string_set_length (str, max_len - 1))
2464 _dbus_assert_not_reached ("setting len to one less than max should have worked");
2467 if (!_dbus_string_set_length (str, max_len))
2468 _dbus_assert_not_reached ("setting len to max len should have worked");
2470 if (_dbus_string_set_length (str, max_len + 1))
2471 _dbus_assert_not_reached ("setting len to one more than max len should not have worked");
2473 if (!_dbus_string_set_length (str, 0))
2474 _dbus_assert_not_reached ("setting len to zero should have worked");
2478 test_base64_roundtrip (const unsigned char *data,
2486 len = strlen (data);
2488 if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2489 _dbus_assert_not_reached ("could not init string");
2491 if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2492 _dbus_assert_not_reached ("could not init string");
2494 if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2495 _dbus_assert_not_reached ("could not init string");
2497 if (!_dbus_string_append_len (&orig, data, len))
2498 _dbus_assert_not_reached ("couldn't append orig data");
2500 if (!_dbus_string_base64_encode (&orig, 0, &encoded, 0))
2501 _dbus_assert_not_reached ("could not encode");
2503 if (!_dbus_string_base64_decode (&encoded, 0, &decoded, 0))
2504 _dbus_assert_not_reached ("could not decode");
2506 if (!_dbus_string_equal (&orig, &decoded))
2510 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2511 _dbus_string_get_length (&orig),
2512 _dbus_string_get_length (&encoded),
2513 _dbus_string_get_length (&decoded));
2514 printf ("Original: %s\n", data);
2515 _dbus_string_get_const_data (&decoded, &s);
2516 printf ("Decoded: %s\n", s);
2517 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2520 _dbus_string_free (&orig);
2521 _dbus_string_free (&encoded);
2522 _dbus_string_free (&decoded);
2526 test_hex_roundtrip (const unsigned char *data,
2534 len = strlen (data);
2536 if (!_dbus_string_init (&orig, _DBUS_INT_MAX))
2537 _dbus_assert_not_reached ("could not init string");
2539 if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
2540 _dbus_assert_not_reached ("could not init string");
2542 if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
2543 _dbus_assert_not_reached ("could not init string");
2545 if (!_dbus_string_append_len (&orig, data, len))
2546 _dbus_assert_not_reached ("couldn't append orig data");
2548 if (!_dbus_string_hex_encode (&orig, 0, &encoded, 0))
2549 _dbus_assert_not_reached ("could not encode");
2551 if (!_dbus_string_hex_decode (&encoded, 0, &decoded, 0))
2552 _dbus_assert_not_reached ("could not decode");
2554 if (!_dbus_string_equal (&orig, &decoded))
2558 printf ("Original string %d bytes encoded %d bytes decoded %d bytes\n",
2559 _dbus_string_get_length (&orig),
2560 _dbus_string_get_length (&encoded),
2561 _dbus_string_get_length (&decoded));
2562 printf ("Original: %s\n", data);
2563 _dbus_string_get_const_data (&decoded, &s);
2564 printf ("Decoded: %s\n", s);
2565 _dbus_assert_not_reached ("original string not the same as string decoded from base64");
2568 _dbus_string_free (&orig);
2569 _dbus_string_free (&encoded);
2570 _dbus_string_free (&decoded);
2573 typedef void (* TestRoundtripFunc) (const unsigned char *data,
2576 test_roundtrips (TestRoundtripFunc func)
2578 (* func) ("Hello this is a string\n", -1);
2579 (* func) ("Hello this is a string\n1", -1);
2580 (* func) ("Hello this is a string\n12", -1);
2581 (* func) ("Hello this is a string\n123", -1);
2582 (* func) ("Hello this is a string\n1234", -1);
2583 (* func) ("Hello this is a string\n12345", -1);
2587 (* func) ("123", 3);
2588 (* func) ("1234", 4);
2589 (* func) ("12345", 5);
2593 (* func) ("123", 4);
2594 (* func) ("1234", 5);
2595 (* func) ("12345", 6);
2597 unsigned char buf[512];
2601 while (i < _DBUS_N_ELEMENTS (buf))
2607 while (i < _DBUS_N_ELEMENTS (buf))
2617 * @ingroup DBusStringInternals
2618 * Unit test for DBusString.
2620 * @todo Need to write tests for _dbus_string_copy() and
2621 * _dbus_string_move() moving to/from each of start/middle/end of a
2622 * string. Also need tests for _dbus_string_move_len ()
2624 * @returns #TRUE on success.
2627 _dbus_string_test (void)
2634 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 };
2639 while (i < _DBUS_N_ELEMENTS (lens))
2641 if (!_dbus_string_init (&str, lens[i]))
2642 _dbus_assert_not_reached ("failed to init string");
2644 test_max_len (&str, lens[i]);
2645 _dbus_string_free (&str);
2650 /* Test shortening and setting length */
2652 while (i < _DBUS_N_ELEMENTS (lens))
2656 if (!_dbus_string_init (&str, lens[i]))
2657 _dbus_assert_not_reached ("failed to init string");
2659 if (!_dbus_string_set_length (&str, lens[i]))
2660 _dbus_assert_not_reached ("failed to set string length");
2665 _dbus_assert (_dbus_string_get_length (&str) == j);
2668 _dbus_string_shorten (&str, 1);
2669 _dbus_assert (_dbus_string_get_length (&str) == (j - 1));
2674 _dbus_string_free (&str);
2679 /* Test appending data */
2680 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2681 _dbus_assert_not_reached ("failed to init string");
2686 if (!_dbus_string_append (&str, "a"))
2687 _dbus_assert_not_reached ("failed to append string to string\n");
2689 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 1);
2691 if (!_dbus_string_append_byte (&str, 'b'))
2692 _dbus_assert_not_reached ("failed to append byte to string\n");
2694 _dbus_assert (_dbus_string_get_length (&str) == i * 2 + 2);
2699 _dbus_string_free (&str);
2701 /* Check steal_data */
2703 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2704 _dbus_assert_not_reached ("failed to init string");
2706 if (!_dbus_string_append (&str, "Hello World"))
2707 _dbus_assert_not_reached ("could not append to string");
2709 i = _dbus_string_get_length (&str);
2711 if (!_dbus_string_steal_data (&str, &s))
2712 _dbus_assert_not_reached ("failed to steal data");
2714 _dbus_assert (_dbus_string_get_length (&str) == 0);
2715 _dbus_assert (((int)strlen (s)) == i);
2721 if (!_dbus_string_append (&str, "Hello World"))
2722 _dbus_assert_not_reached ("could not append to string");
2724 i = _dbus_string_get_length (&str);
2726 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2727 _dbus_assert_not_reached ("could not init string");
2729 if (!_dbus_string_move (&str, 0, &other, 0))
2730 _dbus_assert_not_reached ("could not move");
2732 _dbus_assert (_dbus_string_get_length (&str) == 0);
2733 _dbus_assert (_dbus_string_get_length (&other) == i);
2735 if (!_dbus_string_append (&str, "Hello World"))
2736 _dbus_assert_not_reached ("could not append to string");
2738 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other)))
2739 _dbus_assert_not_reached ("could not move");
2741 _dbus_assert (_dbus_string_get_length (&str) == 0);
2742 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2744 if (!_dbus_string_append (&str, "Hello World"))
2745 _dbus_assert_not_reached ("could not append to string");
2747 if (!_dbus_string_move (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2748 _dbus_assert_not_reached ("could not move");
2750 _dbus_assert (_dbus_string_get_length (&str) == 0);
2751 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2753 _dbus_string_free (&other);
2757 if (!_dbus_string_append (&str, "Hello World"))
2758 _dbus_assert_not_reached ("could not append to string");
2760 i = _dbus_string_get_length (&str);
2762 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2763 _dbus_assert_not_reached ("could not init string");
2765 if (!_dbus_string_copy (&str, 0, &other, 0))
2766 _dbus_assert_not_reached ("could not copy");
2768 _dbus_assert (_dbus_string_get_length (&str) == i);
2769 _dbus_assert (_dbus_string_get_length (&other) == i);
2771 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other)))
2772 _dbus_assert_not_reached ("could not copy");
2774 _dbus_assert (_dbus_string_get_length (&str) == i);
2775 _dbus_assert (_dbus_string_get_length (&other) == i * 2);
2776 _dbus_assert (_dbus_string_equal_c_str (&other,
2777 "Hello WorldHello World"));
2779 if (!_dbus_string_copy (&str, 0, &other, _dbus_string_get_length (&other) / 2))
2780 _dbus_assert_not_reached ("could not copy");
2782 _dbus_assert (_dbus_string_get_length (&str) == i);
2783 _dbus_assert (_dbus_string_get_length (&other) == i * 3);
2784 _dbus_assert (_dbus_string_equal_c_str (&other,
2785 "Hello WorldHello WorldHello World"));
2787 _dbus_string_free (&str);
2788 _dbus_string_free (&other);
2792 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2793 _dbus_assert_not_reached ("failed to init string");
2795 if (!_dbus_string_append (&str, "Hello World"))
2796 _dbus_assert_not_reached ("could not append to string");
2798 i = _dbus_string_get_length (&str);
2800 if (!_dbus_string_init (&other, _DBUS_INT_MAX))
2801 _dbus_assert_not_reached ("could not init string");
2803 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2804 &other, 0, _dbus_string_get_length (&other)))
2805 _dbus_assert_not_reached ("could not replace");
2807 _dbus_assert (_dbus_string_get_length (&str) == i);
2808 _dbus_assert (_dbus_string_get_length (&other) == i);
2809 _dbus_assert (_dbus_string_equal_c_str (&other, "Hello World"));
2811 if (!_dbus_string_replace_len (&str, 0, _dbus_string_get_length (&str),
2813 _dbus_assert_not_reached ("could not replace center space");
2815 _dbus_assert (_dbus_string_get_length (&str) == i);
2816 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2817 _dbus_assert (_dbus_string_equal_c_str (&other,
2818 "HelloHello WorldWorld"));
2821 if (!_dbus_string_replace_len (&str, 1, 1,
2823 _dbus_string_get_length (&other) - 1,
2825 _dbus_assert_not_reached ("could not replace end character");
2827 _dbus_assert (_dbus_string_get_length (&str) == i);
2828 _dbus_assert (_dbus_string_get_length (&other) == i * 2 - 1);
2829 _dbus_assert (_dbus_string_equal_c_str (&other,
2830 "HelloHello WorldWorle"));
2832 _dbus_string_free (&str);
2833 _dbus_string_free (&other);
2835 /* Check append/get unichar */
2837 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2838 _dbus_assert_not_reached ("failed to init string");
2841 if (!_dbus_string_append_unichar (&str, 0xfffc))
2842 _dbus_assert_not_reached ("failed to append unichar");
2844 _dbus_string_get_unichar (&str, 0, &ch, &i);
2846 _dbus_assert (ch == 0xfffc);
2847 _dbus_assert (i == _dbus_string_get_length (&str));
2849 _dbus_string_free (&str);
2851 /* Check insert/set/get byte */
2853 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2854 _dbus_assert_not_reached ("failed to init string");
2856 if (!_dbus_string_append (&str, "Hello"))
2857 _dbus_assert_not_reached ("failed to append Hello");
2859 _dbus_assert (_dbus_string_get_byte (&str, 0) == 'H');
2860 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'e');
2861 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'l');
2862 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'l');
2863 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'o');
2865 _dbus_string_set_byte (&str, 1, 'q');
2866 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'q');
2868 if (!_dbus_string_insert_byte (&str, 0, 255))
2869 _dbus_assert_not_reached ("can't insert byte");
2871 if (!_dbus_string_insert_byte (&str, 2, 'Z'))
2872 _dbus_assert_not_reached ("can't insert byte");
2874 if (!_dbus_string_insert_byte (&str, _dbus_string_get_length (&str), 'W'))
2875 _dbus_assert_not_reached ("can't insert byte");
2877 _dbus_assert (_dbus_string_get_byte (&str, 0) == 255);
2878 _dbus_assert (_dbus_string_get_byte (&str, 1) == 'H');
2879 _dbus_assert (_dbus_string_get_byte (&str, 2) == 'Z');
2880 _dbus_assert (_dbus_string_get_byte (&str, 3) == 'q');
2881 _dbus_assert (_dbus_string_get_byte (&str, 4) == 'l');
2882 _dbus_assert (_dbus_string_get_byte (&str, 5) == 'l');
2883 _dbus_assert (_dbus_string_get_byte (&str, 6) == 'o');
2884 _dbus_assert (_dbus_string_get_byte (&str, 7) == 'W');
2886 _dbus_string_free (&str);
2888 /* Check append/parse int/double */
2890 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2891 _dbus_assert_not_reached ("failed to init string");
2893 if (!_dbus_string_append_int (&str, 27))
2894 _dbus_assert_not_reached ("failed to append int");
2896 i = _dbus_string_get_length (&str);
2898 if (!_dbus_string_parse_int (&str, 0, &v, &end))
2899 _dbus_assert_not_reached ("failed to parse int");
2901 _dbus_assert (v == 27);
2902 _dbus_assert (end == i);
2904 _dbus_string_free (&str);
2906 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2907 _dbus_assert_not_reached ("failed to init string");
2909 if (!_dbus_string_append_double (&str, 50.3))
2910 _dbus_assert_not_reached ("failed to append float");
2912 i = _dbus_string_get_length (&str);
2914 if (!_dbus_string_parse_double (&str, 0, &d, &end))
2915 _dbus_assert_not_reached ("failed to parse float");
2917 _dbus_assert (d > (50.3 - 1e-6) && d < (50.3 + 1e-6));
2918 _dbus_assert (end == i);
2920 _dbus_string_free (&str);
2923 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
2924 _dbus_assert_not_reached ("failed to init string");
2926 if (!_dbus_string_append (&str, "Hello"))
2927 _dbus_assert_not_reached ("couldn't append to string");
2929 if (!_dbus_string_find (&str, 0, "He", &i))
2930 _dbus_assert_not_reached ("didn't find 'He'");
2931 _dbus_assert (i == 0);
2933 if (!_dbus_string_find (&str, 0, "Hello", &i))
2934 _dbus_assert_not_reached ("didn't find 'Hello'");
2935 _dbus_assert (i == 0);
2937 if (!_dbus_string_find (&str, 0, "ello", &i))
2938 _dbus_assert_not_reached ("didn't find 'ello'");
2939 _dbus_assert (i == 1);
2941 if (!_dbus_string_find (&str, 0, "lo", &i))
2942 _dbus_assert_not_reached ("didn't find 'lo'");
2943 _dbus_assert (i == 3);
2945 if (!_dbus_string_find (&str, 2, "lo", &i))
2946 _dbus_assert_not_reached ("didn't find 'lo'");
2947 _dbus_assert (i == 3);
2949 if (_dbus_string_find (&str, 4, "lo", &i))
2950 _dbus_assert_not_reached ("did find 'lo'");
2952 if (!_dbus_string_find (&str, 0, "l", &i))
2953 _dbus_assert_not_reached ("didn't find 'l'");
2954 _dbus_assert (i == 2);
2956 if (!_dbus_string_find (&str, 0, "H", &i))
2957 _dbus_assert_not_reached ("didn't find 'H'");
2958 _dbus_assert (i == 0);
2960 if (!_dbus_string_find (&str, 0, "", &i))
2961 _dbus_assert_not_reached ("didn't find ''");
2962 _dbus_assert (i == 0);
2964 if (_dbus_string_find (&str, 0, "Hello!", NULL))
2965 _dbus_assert_not_reached ("Did find 'Hello!'");
2967 if (_dbus_string_find (&str, 0, "Oh, Hello", NULL))
2968 _dbus_assert_not_reached ("Did find 'Oh, Hello'");
2970 if (_dbus_string_find (&str, 0, "ill", NULL))
2971 _dbus_assert_not_reached ("Did find 'ill'");
2973 if (_dbus_string_find (&str, 0, "q", NULL))
2974 _dbus_assert_not_reached ("Did find 'q'");
2976 if (!_dbus_string_find_to (&str, 0, 2, "He", NULL))
2977 _dbus_assert_not_reached ("Didn't find 'He'");
2979 if (_dbus_string_find_to (&str, 0, 2, "Hello", NULL))
2980 _dbus_assert_not_reached ("Did find 'Hello'");
2982 _dbus_string_free (&str);
2984 /* Base 64 and Hex encoding */
2985 test_roundtrips (test_base64_roundtrip);
2986 test_roundtrips (test_hex_roundtrip);
2991 #endif /* DBUS_BUILD_TESTS */