2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
20 * \brief String manipulation functions
23 #ifndef _ASTERISK_STRINGS_H
24 #define _ASTERISK_STRINGS_H
28 #include "asterisk/inline_api.h"
29 #include "asterisk/utils.h"
30 #include "asterisk/threadstorage.h"
32 /* You may see casts in this header that may seem useless but they ensure this file is C++ clean */
35 #define ast_strlen_zero(foo) _ast_strlen_zero(foo, __FILE__, __PRETTY_FUNCTION__, __LINE__)
36 static force_inline int _ast_strlen_zero(const char *s, const char *file, const char *function, int line)
38 if (!s || (*s == '\0')) {
41 if (!strcmp(s, "(null)")) {
42 ast_log(__LOG_WARNING, file, line, function, "Possible programming error: \"(null)\" is not NULL!\n");
48 static force_inline int ast_strlen_zero(const char *s)
50 return (!s || (*s == '\0'));
54 /*! \brief returns the equivalent of logic or for strings:
55 * first one if not empty, otherwise second one.
57 #define S_OR(a, b) ({typeof(&((a)[0])) __x = (a); ast_strlen_zero(__x) ? (b) : __x;})
59 /*! \brief returns the equivalent of logic or for strings, with an additional boolean check:
60 * second one if not empty and first one is true, otherwise third one.
61 * example: S_COR(usewidget, widget, "<no widget>")
63 #define S_COR(a, b, c) ({typeof(&((b)[0])) __x = (b); (a) && !ast_strlen_zero(__x) ? (__x) : (c);})
66 \brief Gets a pointer to the first non-whitespace character in a string.
67 \param str the input string
68 \return a pointer to the first non-whitespace character
71 char *ast_skip_blanks(const char *str),
73 while (*str && ((unsigned char) *str) < 33)
80 \brief Trims trailing whitespace characters from a string.
81 \param str the input string
82 \return a pointer to the modified string
85 char *ast_trim_blanks(char *str),
90 work += strlen(work) - 1;
91 /* It's tempting to only want to erase after we exit this loop,
92 but since ast_trim_blanks *could* receive a constant string
93 (which we presumably wouldn't have to touch), we shouldn't
94 actually set anything unless we must, and it's easier just
95 to set each position to \0 than to keep track of a variable
97 while ((work >= str) && ((unsigned char) *work) < 33)
105 \brief Gets a pointer to first whitespace character in a string.
106 \param str the input string
107 \return a pointer to the first whitespace character
110 char *ast_skip_nonblanks(char *str),
112 while (*str && ((unsigned char) *str) > 32)
119 \brief Strip leading/trailing whitespace from a string.
120 \param s The string to be stripped (will be modified).
121 \return The stripped string.
123 This functions strips all leading and trailing whitespace
124 characters from the input string, and returns a pointer to
125 the resulting string. The string is modified in place.
128 char *ast_strip(char *s),
130 s = ast_skip_blanks(s);
138 \brief Strip leading/trailing whitespace and quotes from a string.
139 \param s The string to be stripped (will be modified).
140 \param beg_quotes The list of possible beginning quote characters.
141 \param end_quotes The list of matching ending quote characters.
142 \return The stripped string.
144 This functions strips all leading and trailing whitespace
145 characters from the input string, and returns a pointer to
146 the resulting string. The string is modified in place.
148 It can also remove beginning and ending quote (or quote-like)
149 characters, in matching pairs. If the first character of the
150 string matches any character in beg_quotes, and the last
151 character of the string is the matching character in
152 end_quotes, then they are removed from the string.
156 ast_strip_quoted(buf, "\"", "\"");
157 ast_strip_quoted(buf, "'", "'");
158 ast_strip_quoted(buf, "[{(", "]})");
161 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes);
164 \brief Strip backslash for "escaped" semicolons,
165 the string to be stripped (will be modified).
166 \return The stripped string.
168 char *ast_unescape_semicolon(char *s);
171 \brief Convert some C escape sequences \verbatim (\b\f\n\r\t) \endverbatim into the
172 equivalent characters. The string to be converted (will be modified).
173 \return The converted string.
175 char *ast_unescape_c(char *s);
178 \brief Size-limited null-terminating string copy.
179 \param dst The destination buffer.
180 \param src The source string
181 \param size The size of the destination buffer
184 This is similar to \a strncpy, with two important differences:
185 - the destination buffer will \b always be null-terminated
186 - the destination buffer is not filled with zeros past the copied string length
187 These differences make it slightly more efficient, and safer to use since it will
188 not leave the destination buffer unterminated. There is no need to pass an artificially
189 reduced buffer size to this function (unlike \a strncpy), and the buffer does not need
190 to be initialized to zeroes prior to calling this function.
193 void ast_copy_string(char *dst, const char *src, size_t size),
195 while (*src && size) {
199 if (__builtin_expect(!size, 0))
207 \brief Build a string in a buffer, designed to be called repeatedly
209 \note This method is not recommended. New code should use ast_str_*() instead.
211 This is a wrapper for snprintf, that properly handles the buffer pointer
212 and buffer space available.
214 \param buffer current position in buffer to place string into (will be updated on return)
215 \param space remaining space in buffer (will be updated on return)
216 \param fmt printf-style format string
218 \retval non-zero on failure.
220 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...) __attribute__ ((format (printf, 3, 4)));
223 \brief Build a string in a buffer, designed to be called repeatedly
225 This is a wrapper for snprintf, that properly handles the buffer pointer
226 and buffer space available.
228 \return 0 on success, non-zero on failure.
229 \param buffer current position in buffer to place string into (will be updated on return)
230 \param space remaining space in buffer (will be updated on return)
231 \param fmt printf-style format string
232 \param ap varargs list of arguments for format
234 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap) __attribute__((format (printf, 3, 0)));
237 * \brief Make sure something is true.
238 * Determine if a string containing a boolean value is "true".
239 * This function checks to see whether a string passed to it is an indication of an "true" value.
240 * It checks to see if the string is "yes", "true", "y", "t", "on" or "1".
242 * \retval 0 if val is a NULL pointer.
243 * \retval -1 if "true".
244 * \retval 0 otherwise.
246 int ast_true(const char *val);
249 * \brief Make sure something is false.
250 * Determine if a string containing a boolean value is "false".
251 * This function checks to see whether a string passed to it is an indication of an "false" value.
252 * It checks to see if the string is "no", "false", "n", "f", "off" or "0".
254 * \retval 0 if val is a NULL pointer.
255 * \retval -1 if "true".
256 * \retval 0 otherwise.
258 int ast_false(const char *val);
261 * \brief Join an array of strings into a single string.
262 * \param s the resulting string buffer
263 * \param len the length of the result buffer, s
264 * \param w an array of strings to join.
266 * This function will join all of the strings in the array 'w' into a single
267 * string. It will also place a space in the result buffer in between each
270 void ast_join(char *s, size_t len, char * const w[]);
273 \brief Parse a time (integer) string.
274 \param src String to parse
275 \param dst Destination
276 \param _default Value to use if the string does not contain a valid time
277 \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
279 \retval non-zero on failure.
281 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed);
284 \brief Parse a time (float) string.
285 \param src String to parse
286 \param dst Destination
287 \param _default Value to use if the string does not contain a valid time
288 \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
289 \return zero on success, non-zero on failure
291 int ast_get_timeval(const char *src, struct timeval *tv, struct timeval _default, int *consumed);
294 * Support for dynamic strings.
296 * A dynamic string is just a C string prefixed by a few control fields
297 * that help setting/appending/extending it using a printf-like syntax.
299 * One should never declare a variable with this type, but only a pointer
302 * struct ast_str *ds;
304 * The pointer can be initialized with the following:
306 * ds = ast_str_create(init_len);
307 * creates a malloc()'ed dynamic string;
309 * ds = ast_str_alloca(init_len);
310 * creates a string on the stack (not very dynamic!).
312 * ds = ast_str_thread_get(ts, init_len)
313 * creates a malloc()'ed dynamic string associated to
314 * the thread-local storage key ts
316 * Finally, the string can be manipulated with the following:
318 * ast_str_set(&buf, max_len, fmt, ...)
319 * ast_str_append(&buf, max_len, fmt, ...)
321 * and their varargs variant
323 * ast_str_set_va(&buf, max_len, ap)
324 * ast_str_append_va(&buf, max_len, ap)
326 * \param max_len The maximum allowed length, reallocating if needed.
327 * 0 means unlimited, -1 means "at most the available space"
329 * \return All the functions return <0 in case of error, or the
330 * length of the string added to the buffer otherwise.
333 /*! \brief The descriptor of a dynamic string
334 * XXX storage will be optimized later if needed
335 * We use the ts field to indicate the type of storage.
336 * Three special constants indicate malloc, alloca() or static
337 * variables, all other values indicate a
338 * struct ast_threadstorage pointer.
341 size_t len; /*!< The current maximum length of the string */
342 size_t used; /*!< Amount of space used */
343 struct ast_threadstorage *ts; /*!< What kind of storage is this ? */
344 #define DS_MALLOC ((struct ast_threadstorage *)1)
345 #define DS_ALLOCA ((struct ast_threadstorage *)2)
346 #define DS_STATIC ((struct ast_threadstorage *)3) /* not supported yet */
347 char str[0]; /*!< The string buffer */
351 * \brief Create a malloc'ed dynamic length string
353 * \param init_len This is the initial length of the string buffer
355 * \return This function returns a pointer to the dynamic string length. The
356 * result will be NULL in the case of a memory allocation error.
358 * \note The result of this function is dynamically allocated memory, and must
359 * be free()'d after it is no longer needed.
362 struct ast_str * attribute_malloc ast_str_create(size_t init_len),
366 buf = (struct ast_str *)ast_calloc(1, sizeof(*buf) + init_len);
378 /*! \brief Reset the content of a dynamic string.
379 * Useful before a series of ast_str_append.
382 void ast_str_reset(struct ast_str *buf),
392 /*! \brief Trims trailing whitespace characters from an ast_str string.
393 * \param buf A pointer to the ast_str string.
396 void ast_str_trim_blanks(struct ast_str *buf),
401 while (buf->used && buf->str[buf->used - 1] < 33) {
402 buf->str[--(buf->used)] = '\0';
408 * AST_INLINE_API() is a macro that takes a block of code as an argument.
409 * Using preprocessor #directives in the argument is not supported by all
410 * compilers, and it is a bit of an obfuscation anyways, so avoid it.
411 * As a workaround, define a macro that produces either its argument
412 * or nothing, and use that instead of #ifdef/#endif within the
413 * argument to AST_INLINE_API().
415 #if defined(DEBUG_THREADLOCALS)
422 * Make space in a new string (e.g. to read in data from a file)
424 #if (defined(MALLOC_DEBUG) && !defined(STANDALONE))
426 int _ast_str_make_space(struct ast_str **buf, size_t new_len, const char *file, int lineno, const char *function),
428 struct ast_str *old_buf = *buf;
430 if (new_len <= (*buf)->len)
431 return 0; /* success */
432 if ((*buf)->ts == DS_ALLOCA || (*buf)->ts == DS_STATIC)
433 return -1; /* cannot extend */
434 *buf = (struct ast_str *)__ast_realloc(*buf, new_len + sizeof(struct ast_str), file, lineno, function);
439 if ((*buf)->ts != DS_MALLOC) {
440 pthread_setspecific((*buf)->ts->key, *buf);
441 _DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
444 (*buf)->len = new_len;
448 #define ast_str_make_space(a,b) _ast_str_make_space(a,b,__FILE__,__LINE__,__PRETTY_FUNCTION__)
451 int ast_str_make_space(struct ast_str **buf, size_t new_len),
453 struct ast_str *old_buf = *buf;
455 if (new_len <= (*buf)->len)
456 return 0; /* success */
457 if ((*buf)->ts == DS_ALLOCA || (*buf)->ts == DS_STATIC)
458 return -1; /* cannot extend */
459 *buf = (struct ast_str *)ast_realloc(*buf, new_len + sizeof(struct ast_str));
464 if ((*buf)->ts != DS_MALLOC) {
465 pthread_setspecific((*buf)->ts->key, *buf);
466 _DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
469 (*buf)->len = new_len;
475 #define ast_str_alloca(init_len) \
477 struct ast_str *__ast_str_buf; \
478 __ast_str_buf = alloca(sizeof(*__ast_str_buf) + init_len); \
479 __ast_str_buf->len = init_len; \
480 __ast_str_buf->used = 0; \
481 __ast_str_buf->ts = DS_ALLOCA; \
482 __ast_str_buf->str[0] = '\0'; \
487 * \brief Retrieve a thread locally stored dynamic string
489 * \param ts This is a pointer to the thread storage structure declared by using
490 * the AST_THREADSTORAGE macro. If declared with
491 * AST_THREADSTORAGE(my_buf, my_buf_init), then this argument would be
493 * \param init_len This is the initial length of the thread's dynamic string. The
494 * current length may be bigger if previous operations in this thread have
495 * caused it to increase.
497 * \return This function will return the thread locally stored dynamic string
498 * associated with the thread storage management variable passed as the
500 * The result will be NULL in the case of a memory allocation error.
504 * AST_THREADSTORAGE(my_str, my_str_init);
505 * #define MY_STR_INIT_SIZE 128
507 * void my_func(const char *fmt, ...)
509 * struct ast_str *buf;
511 * if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
517 #if !defined(DEBUG_THREADLOCALS)
519 struct ast_str *ast_str_thread_get(struct ast_threadstorage *ts,
524 buf = (struct ast_str *)ast_threadstorage_get(ts, sizeof(*buf) + init_len);
537 #else /* defined(DEBUG_THREADLOCALS) */
539 struct ast_str *__ast_str_thread_get(struct ast_threadstorage *ts,
540 size_t init_len, const char *file, const char *function, unsigned int line),
544 buf = (struct ast_str *)__ast_threadstorage_get(ts, sizeof(*buf) + init_len, file, function, line);
558 #define ast_str_thread_get(ts, init_len) __ast_str_thread_get(ts, init_len, __FILE__, __PRETTY_FUNCTION__, __LINE__)
559 #endif /* defined(DEBUG_THREADLOCALS) */
562 * \brief Error codes from __ast_str_helper()
563 * The undelying processing to manipulate dynamic string is done
564 * by __ast_str_helper(), which can return a success or a
565 * permanent failure (e.g. no memory).
568 /*! An error has occurred and the contents of the dynamic string
570 AST_DYNSTR_BUILD_FAILED = -1,
571 /*! The buffer size for the dynamic string had to be increased, and
572 * __ast_str_helper() needs to be called again after
573 * a va_end() and va_start(). This return value is legacy and will
576 AST_DYNSTR_BUILD_RETRY = -2
580 * \brief Core functionality of ast_str_(set|append)_va
582 * The arguments to this function are the same as those described for
583 * ast_str_set_va except for an addition argument, append.
584 * If append is non-zero, this will append to the current string instead of
587 * AST_DYNSTR_BUILD_RETRY is a legacy define. It should probably never
590 * A return of AST_DYNSTR_BUILD_FAILED indicates a memory allocation error.
592 * A return value greater than or equal to zero indicates the number of
593 * characters that have been written, not including the terminating '\0'.
594 * In the append case, this only includes the number of characters appended.
596 * \note This function should never need to be called directly. It should
597 * through calling one of the other functions or macros defined in this
600 int __ast_str_helper(struct ast_str **buf, size_t max_len,
601 int append, const char *fmt, va_list ap);
604 * \brief Set a dynamic string from a va_list
606 * \param buf This is the address of a pointer to a struct ast_str.
607 * If it is retrieved using ast_str_thread_get, the
608 struct ast_threadstorage pointer will need to
609 * be updated in the case that the buffer has to be reallocated to
610 * accommodate a longer string than what it currently has space for.
611 * \param max_len This is the maximum length to allow the string buffer to grow
612 * to. If this is set to 0, then there is no maximum length.
613 * \param fmt This is the format string (printf style)
614 * \param ap This is the va_list
616 * \return The return value of this function is the same as that of the printf
617 * family of functions.
619 * Example usage (the first part is only for thread-local storage)
621 * AST_THREADSTORAGE(my_str, my_str_init);
622 * #define MY_STR_INIT_SIZE 128
624 * void my_func(const char *fmt, ...)
626 * struct ast_str *buf;
629 * if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
633 * ast_str_set_va(&buf, 0, fmt, ap);
636 * printf("This is the string we just built: %s\n", buf->str);
641 AST_INLINE_API(int ast_str_set_va(struct ast_str **buf, size_t max_len, const char *fmt, va_list ap),
643 return __ast_str_helper(buf, max_len, 0, fmt, ap);
648 * \brief Append to a dynamic string using a va_list
650 * Same as ast_str_set_va(), but append to the current content.
652 AST_INLINE_API(int ast_str_append_va(struct ast_str **buf, size_t max_len, const char *fmt, va_list ap),
654 return __ast_str_helper(buf, max_len, 1, fmt, ap);
659 * \brief Set a dynamic string using variable arguments
661 * \param buf This is the address of a pointer to a struct ast_str which should
662 * have been retrieved using ast_str_thread_get. It will need to
663 * be updated in the case that the buffer has to be reallocated to
664 * accomodate a longer string than what it currently has space for.
665 * \param max_len This is the maximum length to allow the string buffer to grow
666 * to. If this is set to 0, then there is no maximum length.
667 * If set to -1, we are bound to the current maximum length.
668 * \param fmt This is the format string (printf style)
670 * \return The return value of this function is the same as that of the printf
671 * family of functions.
673 * All the rest is the same as ast_str_set_va()
676 int __attribute__ ((format (printf, 3, 4))) ast_str_set(
677 struct ast_str **buf, size_t max_len, const char *fmt, ...),
683 res = ast_str_set_va(buf, max_len, fmt, ap);
691 * \brief Append to a thread local dynamic string
693 * The arguments, return values, and usage of this function are the same as
694 * ast_str_set(), but the new data is appended to the current value.
697 int __attribute__ ((format (printf, 3, 4))) ast_str_append(
698 struct ast_str **buf, size_t max_len, const char *fmt, ...),
704 res = ast_str_append_va(buf, max_len, fmt, ap);
712 * \brief Compute a hash value on a string
714 * This famous hash algorithm was written by Dan Bernstein and is
717 * http://www.cse.yorku.ca/~oz/hash.html
719 static force_inline int ast_str_hash(const char *str)
724 hash = hash * 33 ^ *str++;
730 * \brief Compute a hash value on a case-insensitive string
732 * Uses the same hash algorithm as ast_str_hash, but converts
733 * all characters to lowercase prior to computing a hash. This
734 * allows for easy case-insensitive lookups in a hash table.
736 static force_inline int ast_str_case_hash(const char *str)
741 hash = hash * 33 ^ tolower(*str++);
746 #endif /* _ASTERISK_STRINGS_H */