Refactor CEL channel events on top of Stasis-Core
[asterisk/asterisk.git] / include / asterisk / strings.h
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  * \brief String manipulation functions
21  */
22
23 #ifndef _ASTERISK_STRINGS_H
24 #define _ASTERISK_STRINGS_H
25
26 /* #define DEBUG_OPAQUE */
27
28 #include <ctype.h>
29
30 #include "asterisk/utils.h"
31 #include "asterisk/threadstorage.h"
32
33 #if defined(DEBUG_OPAQUE)
34 #define __AST_STR_USED used2
35 #define __AST_STR_LEN len2
36 #define __AST_STR_STR str2
37 #define __AST_STR_TS ts2
38 #else
39 #define __AST_STR_USED used
40 #define __AST_STR_LEN len
41 #define __AST_STR_STR str
42 #define __AST_STR_TS ts
43 #endif
44
45 /* You may see casts in this header that may seem useless but they ensure this file is C++ clean */
46
47 #define AS_OR(a,b)      (a && ast_str_strlen(a)) ? ast_str_buffer(a) : (b)
48
49 #ifdef AST_DEVMODE
50 #define ast_strlen_zero(foo)    _ast_strlen_zero(foo, __FILE__, __PRETTY_FUNCTION__, __LINE__)
51 static force_inline int _ast_strlen_zero(const char *s, const char *file, const char *function, int line)
52 {
53         if (!s || (*s == '\0')) {
54                 return 1;
55         }
56         if (!strcmp(s, "(null)")) {
57                 ast_log(__LOG_WARNING, file, line, function, "Possible programming error: \"(null)\" is not NULL!\n");
58         }
59         return 0;
60 }
61
62 #else
63 static force_inline int attribute_pure ast_strlen_zero(const char *s)
64 {
65         return (!s || (*s == '\0'));
66 }
67 #endif
68
69 #ifdef SENSE_OF_HUMOR
70 #define ast_strlen_real(a)      (a) ? strlen(a) : 0
71 #define ast_strlen_imaginary(a) ast_random()
72 #endif
73
74 /*! \brief returns the equivalent of logic or for strings:
75  * first one if not empty, otherwise second one.
76  */
77 #define S_OR(a, b) ({typeof(&((a)[0])) __x = (a); ast_strlen_zero(__x) ? (b) : __x;})
78
79 /*! \brief returns the equivalent of logic or for strings, with an additional boolean check:
80  * second one if not empty and first one is true, otherwise third one.
81  * example: S_COR(usewidget, widget, "<no widget>")
82  */
83 #define S_COR(a, b, c) ({typeof(&((b)[0])) __x = (b); (a) && !ast_strlen_zero(__x) ? (__x) : (c);})
84
85 /*
86   \brief Checks whether a string begins with another.
87   \since 12.0.0
88   \param str String to check.
89   \param prefix Prefix to look for.
90   \param 1 if \a str begins with \a prefix, 0 otherwise.
91  */
92 static int force_inline attribute_pure ast_begins_with(const char *str, const char *prefix)
93 {
94         ast_assert(str != NULL);
95         ast_assert(prefix != NULL);
96         while (*str == *prefix && *prefix != '\0') {
97                 ++str;
98                 ++prefix;
99         }
100         return *prefix == '\0';
101 }
102
103 /*
104   \brief Checks whether a string ends with another.
105   \since 12.0.0
106   \param str String to check.
107   \param suffix Suffix to look for.
108   \param 1 if \a str ends with \a suffix, 0 otherwise.
109  */
110 static int force_inline attribute_pure ast_ends_with(const char *str, const char *suffix)
111 {
112         size_t str_len;
113         size_t suffix_len;
114
115         ast_assert(str != NULL);
116         ast_assert(suffix != NULL);
117         str_len = strlen(str);
118         suffix_len = strlen(suffix);
119
120         if (suffix_len > str_len) {
121                 return 0;
122         }
123
124         return strcmp(str + str_len - suffix_len, suffix) == 0;
125 }
126
127 /*!
128  * \brief return Yes or No depending on the argument.
129  *
130  * Note that this macro is used my AMI, where a literal "Yes" and "No" are
131  * expected, and translations would cause problems.
132  *
133  * \param x Boolean value
134  * \return "Yes" if x is true (non-zero)
135  * \return "No" if x is false (zero)
136  */
137 #define AST_YESNO(x) ((x) ? "Yes" : "No")
138
139 /*!
140   \brief Gets a pointer to the first non-whitespace character in a string.
141   \param str the input string
142   \return a pointer to the first non-whitespace character
143  */
144 AST_INLINE_API(
145 char * attribute_pure ast_skip_blanks(const char *str),
146 {
147         while (*str && ((unsigned char) *str) < 33)
148                 str++;
149         return (char *) str;
150 }
151 )
152
153 /*!
154   \brief Trims trailing whitespace characters from a string.
155   \param str the input string
156   \return a pointer to the modified string
157  */
158 AST_INLINE_API(
159 char *ast_trim_blanks(char *str),
160 {
161         char *work = str;
162
163         if (work) {
164                 work += strlen(work) - 1;
165                 /* It's tempting to only want to erase after we exit this loop, 
166                    but since ast_trim_blanks *could* receive a constant string
167                    (which we presumably wouldn't have to touch), we shouldn't
168                    actually set anything unless we must, and it's easier just
169                    to set each position to \0 than to keep track of a variable
170                    for it */
171                 while ((work >= str) && ((unsigned char) *work) < 33)
172                         *(work--) = '\0';
173         }
174         return str;
175 }
176 )
177
178 /*!
179   \brief Gets a pointer to first whitespace character in a string.
180   \param str the input string
181   \return a pointer to the first whitespace character
182  */
183 AST_INLINE_API(
184 char * attribute_pure ast_skip_nonblanks(const char *str),
185 {
186         while (*str && ((unsigned char) *str) > 32)
187                 str++;
188         return (char *) str;
189 }
190 )
191   
192 /*!
193   \brief Strip leading/trailing whitespace from a string.
194   \param s The string to be stripped (will be modified).
195   \return The stripped string.
196
197   This functions strips all leading and trailing whitespace
198   characters from the input string, and returns a pointer to
199   the resulting string. The string is modified in place.
200 */
201 AST_INLINE_API(
202 char *ast_strip(char *s),
203 {
204         if ((s = ast_skip_blanks(s))) {
205                 ast_trim_blanks(s);
206         }
207         return s;
208
209 )
210
211 /*!
212   \brief Strip leading/trailing whitespace and quotes from a string.
213   \param s The string to be stripped (will be modified).
214   \param beg_quotes The list of possible beginning quote characters.
215   \param end_quotes The list of matching ending quote characters.
216   \return The stripped string.
217
218   This functions strips all leading and trailing whitespace
219   characters from the input string, and returns a pointer to
220   the resulting string. The string is modified in place.
221
222   It can also remove beginning and ending quote (or quote-like)
223   characters, in matching pairs. If the first character of the
224   string matches any character in beg_quotes, and the last
225   character of the string is the matching character in
226   end_quotes, then they are removed from the string.
227
228   Examples:
229   \code
230   ast_strip_quoted(buf, "\"", "\"");
231   ast_strip_quoted(buf, "'", "'");
232   ast_strip_quoted(buf, "[{(", "]})");
233   \endcode
234  */
235 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes);
236
237 /*!
238   \brief Strip backslash for "escaped" semicolons, 
239         the string to be stripped (will be modified).
240   \return The stripped string.
241  */
242 char *ast_unescape_semicolon(char *s);
243
244 /*!
245   \brief Convert some C escape sequences  \verbatim (\b\f\n\r\t) \endverbatim into the
246         equivalent characters. The string to be converted (will be modified).
247   \return The converted string.
248  */
249 char *ast_unescape_c(char *s);
250
251 /*!
252   \brief Size-limited null-terminating string copy.
253   \param dst The destination buffer.
254   \param src The source string
255   \param size The size of the destination buffer
256   \return Nothing.
257
258   This is similar to \a strncpy, with two important differences:
259     - the destination buffer will \b always be null-terminated
260     - the destination buffer is not filled with zeros past the copied string length
261   These differences make it slightly more efficient, and safer to use since it will
262   not leave the destination buffer unterminated. There is no need to pass an artificially
263   reduced buffer size to this function (unlike \a strncpy), and the buffer does not need
264   to be initialized to zeroes prior to calling this function.
265 */
266 AST_INLINE_API(
267 void ast_copy_string(char *dst, const char *src, size_t size),
268 {
269         while (*src && size) {
270                 *dst++ = *src++;
271                 size--;
272         }
273         if (__builtin_expect(!size, 0))
274                 dst--;
275         *dst = '\0';
276 }
277 )
278
279 /*!
280   \brief Build a string in a buffer, designed to be called repeatedly
281   
282   \note This method is not recommended. New code should use ast_str_*() instead.
283
284   This is a wrapper for snprintf, that properly handles the buffer pointer
285   and buffer space available.
286
287   \param buffer current position in buffer to place string into (will be updated on return)
288   \param space remaining space in buffer (will be updated on return)
289   \param fmt printf-style format string
290   \retval 0 on success
291   \retval non-zero on failure.
292 */
293 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
294
295 /*!
296   \brief Build a string in a buffer, designed to be called repeatedly
297   
298   This is a wrapper for snprintf, that properly handles the buffer pointer
299   and buffer space available.
300
301   \return 0 on success, non-zero on failure.
302   \param buffer current position in buffer to place string into (will be updated on return)
303   \param space remaining space in buffer (will be updated on return)
304   \param fmt printf-style format string
305   \param ap varargs list of arguments for format
306 */
307 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap) __attribute__((format(printf, 3, 0)));
308
309 /*!
310  * \brief Make sure something is true.
311  * Determine if a string containing a boolean value is "true".
312  * This function checks to see whether a string passed to it is an indication of an "true" value.
313  * It checks to see if the string is "yes", "true", "y", "t", "on" or "1".
314  *
315  * \retval 0 if val is a NULL pointer.
316  * \retval -1 if "true".
317  * \retval 0 otherwise.
318  */
319 int attribute_pure ast_true(const char *val);
320
321 /*! 
322  * \brief Make sure something is false.
323  * Determine if a string containing a boolean value is "false".
324  * This function checks to see whether a string passed to it is an indication of an "false" value.  
325  * It checks to see if the string is "no", "false", "n", "f", "off" or "0".  
326  *
327  * \retval 0 if val is a NULL pointer.
328  * \retval -1 if "true".
329  * \retval 0 otherwise.
330  */
331 int attribute_pure ast_false(const char *val);
332
333 /*
334  *  \brief Join an array of strings into a single string.
335  * \param s the resulting string buffer
336  * \param len the length of the result buffer, s
337  * \param w an array of strings to join.
338  *
339  * This function will join all of the strings in the array 'w' into a single
340  * string.  It will also place a space in the result buffer in between each
341  * string from 'w'.
342 */
343 void ast_join(char *s, size_t len, const char * const w[]);
344
345 /*
346   \brief Parse a time (integer) string.
347   \param src String to parse
348   \param dst Destination
349   \param _default Value to use if the string does not contain a valid time
350   \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
351   \retval 0 on success
352   \retval non-zero on failure.
353 */
354 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed);
355
356 /*
357   \brief Parse a time (float) string.
358   \param src String to parse
359   \param dst Destination
360   \param _default Value to use if the string does not contain a valid time
361   \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
362   \return zero on success, non-zero on failure
363 */
364 int ast_get_timeval(const char *src, struct timeval *tv, struct timeval _default, int *consumed);
365
366 /*!
367  * Support for dynamic strings.
368  *
369  * A dynamic string is just a C string prefixed by a few control fields
370  * that help setting/appending/extending it using a printf-like syntax.
371  *
372  * One should never declare a variable with this type, but only a pointer
373  * to it, e.g.
374  *
375  *      struct ast_str *ds;
376  *
377  * The pointer can be initialized with the following:
378  *
379  *      ds = ast_str_create(init_len);
380  *              creates a malloc()'ed dynamic string;
381  *
382  *      ds = ast_str_alloca(init_len);
383  *              creates a string on the stack (not very dynamic!).
384  *
385  *      ds = ast_str_thread_get(ts, init_len)
386  *              creates a malloc()'ed dynamic string associated to
387  *              the thread-local storage key ts
388  *
389  * Finally, the string can be manipulated with the following:
390  *
391  *      ast_str_set(&buf, max_len, fmt, ...)
392  *      ast_str_append(&buf, max_len, fmt, ...)
393  *
394  * and their varargs variant
395  *
396  *      ast_str_set_va(&buf, max_len, ap)
397  *      ast_str_append_va(&buf, max_len, ap)
398  *
399  * \param max_len The maximum allowed capacity of the ast_str. Note that
400  *  if the value of max_len is less than the current capacity of the
401  *  ast_str (as returned by ast_str_size), then the parameter is effectively
402  *  ignored.
403  *      0 means unlimited, -1 means "at most the available space"
404  *
405  * \return All the functions return <0 in case of error, or the
406  *      length of the string added to the buffer otherwise. Note that
407  *      in most cases where an error is returned, characters ARE written
408  *      to the ast_str.
409  */
410
411 /*! \brief The descriptor of a dynamic string
412  *  XXX storage will be optimized later if needed
413  * We use the ts field to indicate the type of storage.
414  * Three special constants indicate malloc, ast_alloca() or static
415  * variables, all other values indicate a
416  * struct ast_threadstorage pointer.
417  */
418 struct ast_str {
419         size_t __AST_STR_LEN;                   /*!< The current maximum length of the string */
420         size_t __AST_STR_USED;                  /*!< Amount of space used */
421         struct ast_threadstorage *__AST_STR_TS; /*!< What kind of storage is this ? */
422 #define DS_MALLOC       ((struct ast_threadstorage *)1)
423 #define DS_ALLOCA       ((struct ast_threadstorage *)2)
424 #define DS_STATIC       ((struct ast_threadstorage *)3) /* not supported yet */
425         char __AST_STR_STR[0];                  /*!< The string buffer */
426 };
427
428 /*!
429  * \brief Given a string regex_string in the form of "/regex/", convert it into the form of "regex"
430  *
431  * This function will trim one leading / and one trailing / from a given input string
432  * ast_str regex_pattern must be preallocated before calling this function
433  *
434  * \return 0 on success, non-zero on failure.
435  * \return 1 if we only stripped a leading /
436  * \return 2 if we only stripped a trailing /
437  * \return 3 if we did not strip any / characters
438  * \param regex_string  the string containing /regex/
439  * \param regex_pattern the destination ast_str which will contain "regex" after execution
440  */
441 int ast_regex_string_to_regex_pattern(const char *regex_string, struct ast_str **regex_pattern);
442
443 /*!
444  * \brief Create a malloc'ed dynamic length string
445  *
446  * \param init_len This is the initial length of the string buffer
447  *
448  * \return This function returns a pointer to the dynamic string length.  The
449  *         result will be NULL in the case of a memory allocation error.
450  *
451  * \note The result of this function is dynamically allocated memory, and must
452  *       be free()'d after it is no longer needed.
453  */
454 #if (defined(MALLOC_DEBUG) && !defined(STANDALONE))
455 #define ast_str_create(a)       _ast_str_create(a,__FILE__,__LINE__,__PRETTY_FUNCTION__)
456 AST_INLINE_API(
457 struct ast_str * attribute_malloc _ast_str_create(size_t init_len,
458                 const char *file, int lineno, const char *func),
459 {
460         struct ast_str *buf;
461
462         buf = (struct ast_str *)__ast_calloc(1, sizeof(*buf) + init_len, file, lineno, func);
463         if (buf == NULL)
464                 return NULL;
465
466         buf->__AST_STR_LEN = init_len;
467         buf->__AST_STR_USED = 0;
468         buf->__AST_STR_TS = DS_MALLOC;
469
470         return buf;
471 }
472 )
473 #else
474 AST_INLINE_API(
475 struct ast_str * attribute_malloc ast_str_create(size_t init_len),
476 {
477         struct ast_str *buf;
478
479         buf = (struct ast_str *)ast_calloc(1, sizeof(*buf) + init_len);
480         if (buf == NULL)
481                 return NULL;
482
483         buf->__AST_STR_LEN = init_len;
484         buf->__AST_STR_USED = 0;
485         buf->__AST_STR_TS = DS_MALLOC;
486
487         return buf;
488 }
489 )
490 #endif
491
492 /*! \brief Reset the content of a dynamic string.
493  * Useful before a series of ast_str_append.
494  */
495 AST_INLINE_API(
496 void ast_str_reset(struct ast_str *buf),
497 {
498         if (buf) {
499                 buf->__AST_STR_USED = 0;
500                 if (buf->__AST_STR_LEN) {
501                         buf->__AST_STR_STR[0] = '\0';
502                 }
503         }
504 }
505 )
506
507 /*! \brief Update the length of the buffer, after using ast_str merely as a buffer.
508  *  \param buf A pointer to the ast_str string.
509  */
510 AST_INLINE_API(
511 void ast_str_update(struct ast_str *buf),
512 {
513         buf->__AST_STR_USED = strlen(buf->__AST_STR_STR);
514 }
515 )
516
517 /*! \brief Trims trailing whitespace characters from an ast_str string.
518  *  \param buf A pointer to the ast_str string.
519  */
520 AST_INLINE_API(
521 void ast_str_trim_blanks(struct ast_str *buf),
522 {
523         if (!buf) {
524                 return;
525         }
526         while (buf->__AST_STR_USED && buf->__AST_STR_STR[buf->__AST_STR_USED - 1] < 33) {
527                 buf->__AST_STR_STR[--(buf->__AST_STR_USED)] = '\0';
528         }
529 }
530 )
531
532 /*!\brief Returns the current length of the string stored within buf.
533  * \param buf A pointer to the ast_str structure.
534  */
535 AST_INLINE_API(
536 size_t attribute_pure ast_str_strlen(const struct ast_str *buf),
537 {
538         return buf->__AST_STR_USED;
539 }
540 )
541
542 /*!\brief Returns the current maximum length (without reallocation) of the current buffer.
543  * \param buf A pointer to the ast_str structure.
544  * \retval Current maximum length of the buffer.
545  */
546 AST_INLINE_API(
547 size_t attribute_pure ast_str_size(const struct ast_str *buf),
548 {
549         return buf->__AST_STR_LEN;
550 }
551 )
552
553 /*!\brief Returns the string buffer within the ast_str buf.
554  * \param buf A pointer to the ast_str structure.
555  * \retval A pointer to the enclosed string.
556  */
557 AST_INLINE_API(
558 char * attribute_pure ast_str_buffer(const struct ast_str *buf),
559 {
560         /* for now, cast away the const qualifier on the pointer
561          * being returned; eventually, it should become truly const
562          * and only be modified via accessor functions
563          */
564         return (char *) buf->__AST_STR_STR;
565 }
566 )
567
568 /*!\brief Truncates the enclosed string to the given length.
569  * \param buf A pointer to the ast_str structure.
570  * \param len Maximum length of the string. If len is larger than the
571  *        current maximum length, things will explode. If it is negative
572  *        at most -len characters will be trimmed off the end.
573  * \retval A pointer to the resulting string.
574  */
575 AST_INLINE_API(
576 char *ast_str_truncate(struct ast_str *buf, ssize_t len),
577 {
578         if (len < 0) {
579                 if ((typeof(buf->__AST_STR_USED)) -len >= buf->__AST_STR_USED) {
580                         buf->__AST_STR_USED = 0;
581                 } else {
582                         buf->__AST_STR_USED += len;
583                 }
584         } else {
585                 buf->__AST_STR_USED = len;
586         }
587         buf->__AST_STR_STR[buf->__AST_STR_USED] = '\0';
588         return buf->__AST_STR_STR;
589 }
590 )
591         
592 /*
593  * AST_INLINE_API() is a macro that takes a block of code as an argument.
594  * Using preprocessor #directives in the argument is not supported by all
595  * compilers, and it is a bit of an obfuscation anyways, so avoid it.
596  * As a workaround, define a macro that produces either its argument
597  * or nothing, and use that instead of #ifdef/#endif within the
598  * argument to AST_INLINE_API().
599  */
600 #if defined(DEBUG_THREADLOCALS)
601 #define _DB1(x) x
602 #else
603 #define _DB1(x)
604 #endif
605
606 /*!
607  * Make space in a new string (e.g. to read in data from a file)
608  */
609 #if (defined(MALLOC_DEBUG) && !defined(STANDALONE))
610 AST_INLINE_API(
611 int _ast_str_make_space(struct ast_str **buf, size_t new_len, const char *file, int lineno, const char *function),
612 {
613         struct ast_str *old_buf = *buf;
614
615         if (new_len <= (*buf)->__AST_STR_LEN) 
616                 return 0;       /* success */
617         if ((*buf)->__AST_STR_TS == DS_ALLOCA || (*buf)->__AST_STR_TS == DS_STATIC)
618                 return -1;      /* cannot extend */
619         *buf = (struct ast_str *)__ast_realloc(*buf, new_len + sizeof(struct ast_str), file, lineno, function);
620         if (*buf == NULL) {
621                 *buf = old_buf;
622                 return -1;
623         }
624         if ((*buf)->__AST_STR_TS != DS_MALLOC) {
625                 pthread_setspecific((*buf)->__AST_STR_TS->key, *buf);
626                 _DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
627         }
628
629         (*buf)->__AST_STR_LEN = new_len;
630         return 0;
631 }
632 )
633 #define ast_str_make_space(a,b) _ast_str_make_space(a,b,__FILE__,__LINE__,__PRETTY_FUNCTION__)
634 #else
635 AST_INLINE_API(
636 int ast_str_make_space(struct ast_str **buf, size_t new_len),
637 {
638         struct ast_str *old_buf = *buf;
639
640         if (new_len <= (*buf)->__AST_STR_LEN) 
641                 return 0;       /* success */
642         if ((*buf)->__AST_STR_TS == DS_ALLOCA || (*buf)->__AST_STR_TS == DS_STATIC)
643                 return -1;      /* cannot extend */
644         *buf = (struct ast_str *)ast_realloc(*buf, new_len + sizeof(struct ast_str));
645         if (*buf == NULL) {
646                 *buf = old_buf;
647                 return -1;
648         }
649         if ((*buf)->__AST_STR_TS != DS_MALLOC) {
650                 pthread_setspecific((*buf)->__AST_STR_TS->key, *buf);
651                 _DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
652         }
653
654         (*buf)->__AST_STR_LEN = new_len;
655         return 0;
656 }
657 )
658 #endif
659
660 AST_INLINE_API(
661 int ast_str_copy_string(struct ast_str **dst, struct ast_str *src),
662 {
663
664         /* make sure our destination is large enough */
665         if (src->__AST_STR_USED + 1 > (*dst)->__AST_STR_LEN) {
666                 if (ast_str_make_space(dst, src->__AST_STR_USED + 1)) {
667                         return -1;
668                 }
669         }
670
671         memcpy((*dst)->__AST_STR_STR, src->__AST_STR_STR, src->__AST_STR_USED + 1);
672         (*dst)->__AST_STR_USED = src->__AST_STR_USED;
673         return 0;
674 }
675 )
676
677 #define ast_str_alloca(init_len)                        \
678         ({                                              \
679                 struct ast_str *__ast_str_buf;                  \
680                 __ast_str_buf = ast_alloca(sizeof(*__ast_str_buf) + init_len);  \
681                 __ast_str_buf->__AST_STR_LEN = init_len;                        \
682                 __ast_str_buf->__AST_STR_USED = 0;                              \
683                 __ast_str_buf->__AST_STR_TS = DS_ALLOCA;                        \
684                 __ast_str_buf->__AST_STR_STR[0] = '\0';                 \
685                 (__ast_str_buf);                                        \
686         })
687
688 /*!
689  * \brief Retrieve a thread locally stored dynamic string
690  *
691  * \param ts This is a pointer to the thread storage structure declared by using
692  *      the AST_THREADSTORAGE macro.  If declared with 
693  *      AST_THREADSTORAGE(my_buf, my_buf_init), then this argument would be 
694  *      (&my_buf).
695  * \param init_len This is the initial length of the thread's dynamic string. The
696  *      current length may be bigger if previous operations in this thread have
697  *      caused it to increase.
698  *
699  * \return This function will return the thread locally stored dynamic string
700  *         associated with the thread storage management variable passed as the
701  *         first argument.
702  *         The result will be NULL in the case of a memory allocation error.
703  *
704  * Example usage:
705  * \code
706  * AST_THREADSTORAGE(my_str, my_str_init);
707  * #define MY_STR_INIT_SIZE   128
708  * ...
709  * void my_func(const char *fmt, ...)
710  * {
711  *      struct ast_str *buf;
712  *
713  *      if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
714  *           return;
715  *      ...
716  * }
717  * \endcode
718  */
719 #if !defined(DEBUG_THREADLOCALS)
720 AST_INLINE_API(
721 struct ast_str *ast_str_thread_get(struct ast_threadstorage *ts,
722         size_t init_len),
723 {
724         struct ast_str *buf;
725
726         buf = (struct ast_str *)ast_threadstorage_get(ts, sizeof(*buf) + init_len);
727         if (buf == NULL)
728                 return NULL;
729
730         if (!buf->__AST_STR_LEN) {
731                 buf->__AST_STR_LEN = init_len;
732                 buf->__AST_STR_USED = 0;
733                 buf->__AST_STR_TS = ts;
734         }
735
736         return buf;
737 }
738 )
739 #else /* defined(DEBUG_THREADLOCALS) */
740 AST_INLINE_API(
741 struct ast_str *__ast_str_thread_get(struct ast_threadstorage *ts,
742         size_t init_len, const char *file, const char *function, unsigned int line),
743 {
744         struct ast_str *buf;
745
746         buf = (struct ast_str *)__ast_threadstorage_get(ts, sizeof(*buf) + init_len, file, function, line);
747         if (buf == NULL)
748                 return NULL;
749
750         if (!buf->__AST_STR_LEN) {
751                 buf->__AST_STR_LEN = init_len;
752                 buf->__AST_STR_USED = 0;
753                 buf->__AST_STR_TS = ts;
754         }
755
756         return buf;
757 }
758 )
759
760 #define ast_str_thread_get(ts, init_len) __ast_str_thread_get(ts, init_len, __FILE__, __PRETTY_FUNCTION__, __LINE__)
761 #endif /* defined(DEBUG_THREADLOCALS) */
762
763 /*!
764  * \brief Error codes from __ast_str_helper()
765  * The undelying processing to manipulate dynamic string is done
766  * by __ast_str_helper(), which can return a success or a
767  * permanent failure (e.g. no memory).
768  */
769 enum {
770         /*! An error has occurred and the contents of the dynamic string
771          *  are undefined */
772         AST_DYNSTR_BUILD_FAILED = -1,
773         /*! The buffer size for the dynamic string had to be increased, and
774          *  __ast_str_helper() needs to be called again after
775          *  a va_end() and va_start().  This return value is legacy and will
776          *  no longer be used.
777          */
778         AST_DYNSTR_BUILD_RETRY = -2
779 };
780
781 /*!
782  * \brief Core functionality of ast_str_(set|append)_va
783  *
784  * The arguments to this function are the same as those described for
785  * ast_str_set_va except for an addition argument, append.
786  * If append is non-zero, this will append to the current string instead of
787  * writing over it.
788  *
789  * AST_DYNSTR_BUILD_RETRY is a legacy define.  It should probably never
790  * again be used.
791  *
792  * A return of AST_DYNSTR_BUILD_FAILED indicates a memory allocation error.
793  *
794  * A return value greater than or equal to zero indicates the number of
795  * characters that have been written, not including the terminating '\0'.
796  * In the append case, this only includes the number of characters appended.
797  *
798  * \note This function should never need to be called directly.  It should
799  *       through calling one of the other functions or macros defined in this
800  *       file.
801  */
802 #if (defined(MALLOC_DEBUG) && !defined(STANDALONE))
803 int __attribute__((format(printf, 4, 0))) __ast_debug_str_helper(struct ast_str **buf, ssize_t max_len,
804                                                            int append, const char *fmt, va_list ap, const char *file, int lineno, const char *func);
805 #define __ast_str_helper(a,b,c,d,e)     __ast_debug_str_helper(a,b,c,d,e,__FILE__,__LINE__,__PRETTY_FUNCTION__)
806 #else
807 int __attribute__((format(printf, 4, 0))) __ast_str_helper(struct ast_str **buf, ssize_t max_len,
808                                                            int append, const char *fmt, va_list ap);
809 #endif
810 char *__ast_str_helper2(struct ast_str **buf, ssize_t max_len,
811         const char *src, size_t maxsrc, int append, int escapecommas);
812
813 /*!
814  * \brief Set a dynamic string from a va_list
815  *
816  * \param buf This is the address of a pointer to a struct ast_str.
817  *      If it is retrieved using ast_str_thread_get, the
818         struct ast_threadstorage pointer will need to
819  *      be updated in the case that the buffer has to be reallocated to
820  *      accommodate a longer string than what it currently has space for.
821  * \param max_len This is the maximum length to allow the string buffer to grow
822  *      to.  If this is set to 0, then there is no maximum length.
823  * \param fmt This is the format string (printf style)
824  * \param ap This is the va_list
825  *
826  * \return The return value of this function is the same as that of the printf
827  *         family of functions.
828  *
829  * Example usage (the first part is only for thread-local storage)
830  * \code
831  * AST_THREADSTORAGE(my_str, my_str_init);
832  * #define MY_STR_INIT_SIZE   128
833  * ...
834  * void my_func(const char *fmt, ...)
835  * {
836  *      struct ast_str *buf;
837  *      va_list ap;
838  *
839  *      if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
840  *           return;
841  *      ...
842  *      va_start(fmt, ap);
843  *      ast_str_set_va(&buf, 0, fmt, ap);
844  *      va_end(ap);
845  * 
846  *      printf("This is the string we just built: %s\n", buf->str);
847  *      ...
848  * }
849  * \endcode
850  *
851  * \note Care should be taken when using this function. The function can
852  * result in reallocating the ast_str. If a pointer to the ast_str is passed
853  * by value to a function that calls ast_str_set_va(), then the original ast_str
854  * pointer may be invalidated due to a reallocation.
855  *
856  */
857 AST_INLINE_API(int __attribute__((format(printf, 3, 0))) ast_str_set_va(struct ast_str **buf, ssize_t max_len, const char *fmt, va_list ap),
858 {
859         return __ast_str_helper(buf, max_len, 0, fmt, ap);
860 }
861 )
862
863 /*!
864  * \brief Append to a dynamic string using a va_list
865  *
866  * Same as ast_str_set_va(), but append to the current content.
867  *
868  * \note Care should be taken when using this function. The function can
869  * result in reallocating the ast_str. If a pointer to the ast_str is passed
870  * by value to a function that calls ast_str_append_va(), then the original ast_str
871  * pointer may be invalidated due to a reallocation.
872  *
873  * \param buf, max_len, fmt, ap
874  */
875 AST_INLINE_API(int __attribute__((format(printf, 3, 0))) ast_str_append_va(struct ast_str **buf, ssize_t max_len, const char *fmt, va_list ap),
876 {
877         return __ast_str_helper(buf, max_len, 1, fmt, ap);
878 }
879 )
880
881 /*!\brief Set a dynamic string to a non-NULL terminated substring. */
882 AST_INLINE_API(char *ast_str_set_substr(struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc),
883 {
884         return __ast_str_helper2(buf, maxlen, src, maxsrc, 0, 0);
885 }
886 )
887
888 /*!\brief Append a non-NULL terminated substring to the end of a dynamic string. */
889 AST_INLINE_API(char *ast_str_append_substr(struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc),
890 {
891         return __ast_str_helper2(buf, maxlen, src, maxsrc, 1, 0);
892 }
893 )
894
895 /*!\brief Set a dynamic string to a non-NULL terminated substring, with escaping of commas. */
896 AST_INLINE_API(char *ast_str_set_escapecommas(struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc),
897 {
898         return __ast_str_helper2(buf, maxlen, src, maxsrc, 0, 1);
899 }
900 )
901
902 /*!\brief Append a non-NULL terminated substring to the end of a dynamic string, with escaping of commas. */
903 AST_INLINE_API(char *ast_str_append_escapecommas(struct ast_str **buf, ssize_t maxlen, const char *src, size_t maxsrc),
904 {
905         return __ast_str_helper2(buf, maxlen, src, maxsrc, 1, 1);
906 }
907 )
908
909 /*!
910  * \brief Set a dynamic string using variable arguments
911  *
912  * \note Care should be taken when using this function. The function can
913  * result in reallocating the ast_str. If a pointer to the ast_str is passed
914  * by value to a function that calls ast_str_set(), then the original ast_str
915  * pointer may be invalidated due to a reallocation.
916  *
917  * \param buf This is the address of a pointer to a struct ast_str which should
918  *      have been retrieved using ast_str_thread_get.  It will need to
919  *      be updated in the case that the buffer has to be reallocated to
920  *      accomodate a longer string than what it currently has space for.
921  * \param max_len This is the maximum length to allow the string buffer to grow
922  *      to.  If this is set to 0, then there is no maximum length.
923  *      If set to -1, we are bound to the current maximum length.
924  * \param fmt This is the format string (printf style)
925  *
926  * \return The return value of this function is the same as that of the printf
927  *         family of functions.
928  *
929  * All the rest is the same as ast_str_set_va()
930  */
931 AST_INLINE_API(
932 int __attribute__((format(printf, 3, 4))) ast_str_set(
933         struct ast_str **buf, ssize_t max_len, const char *fmt, ...),
934 {
935         int res;
936         va_list ap;
937
938         va_start(ap, fmt);
939         res = ast_str_set_va(buf, max_len, fmt, ap);
940         va_end(ap);
941
942         return res;
943 }
944 )
945
946 /*!
947  * \brief Append to a thread local dynamic string
948  *
949  * \note Care should be taken when using this function. The function can
950  * result in reallocating the ast_str. If a pointer to the ast_str is passed
951  * by value to a function that calls ast_str_append(), then the original ast_str
952  * pointer may be invalidated due to a reallocation.
953  *
954  * The arguments, return values, and usage of this function are the same as
955  * ast_str_set(), but the new data is appended to the current value.
956  */
957 AST_INLINE_API(
958 int __attribute__((format(printf, 3, 4))) ast_str_append(
959         struct ast_str **buf, ssize_t max_len, const char *fmt, ...),
960 {
961         int res;
962         va_list ap;
963
964         va_start(ap, fmt);
965         res = ast_str_append_va(buf, max_len, fmt, ap);
966         va_end(ap);
967
968         return res;
969 }
970 )
971
972 /*!
973  * \brief Check if a string is only digits
974  *
975  * \retval 1 The string contains only digits
976  * \retval 0 The string contains non-digit characters
977  */
978 AST_INLINE_API(
979 int ast_check_digits(const char *arg),
980 {
981         while (*arg) {
982                 if (*arg < '0' || *arg > '9') {
983                         return 0;
984                 }
985                 arg++;
986         }
987         return 1;
988 }
989 )
990
991 /*!
992  * \brief Convert the tech portion of a device string to upper case
993  *
994  * \retval dev_str Returns the char* passed in for convenience
995  */
996 AST_INLINE_API(
997 char *ast_tech_to_upper(char *dev_str),
998 {
999         char *pos;
1000         if (!dev_str || !strchr(dev_str, '/')) {
1001                 return dev_str;
1002         }
1003
1004         for (pos = dev_str; *pos && *pos != '/'; pos++) {
1005                 *pos = toupper(*pos);
1006         }
1007         return dev_str;
1008 }
1009 )
1010
1011 /*!
1012  * \brief Compute a hash value on a string
1013  *
1014  * This famous hash algorithm was written by Dan Bernstein and is
1015  * commonly used.
1016  *
1017  * http://www.cse.yorku.ca/~oz/hash.html
1018  */
1019 static force_inline int attribute_pure ast_str_hash(const char *str)
1020 {
1021         int hash = 5381;
1022
1023         while (*str)
1024                 hash = hash * 33 ^ *str++;
1025
1026         return abs(hash);
1027 }
1028
1029 /*!
1030  * \brief Compute a hash value on a string
1031  *
1032  * \param[in] str The string to add to the hash
1033  * \param[in] hash The hash value to add to
1034  * 
1035  * \details
1036  * This version of the function is for when you need to compute a
1037  * string hash of more than one string.
1038  *
1039  * This famous hash algorithm was written by Dan Bernstein and is
1040  * commonly used.
1041  *
1042  * \sa http://www.cse.yorku.ca/~oz/hash.html
1043  */
1044 static force_inline int ast_str_hash_add(const char *str, int hash)
1045 {
1046         while (*str)
1047                 hash = hash * 33 ^ *str++;
1048
1049         return abs(hash);
1050 }
1051
1052 /*!
1053  * \brief Compute a hash value on a case-insensitive string
1054  *
1055  * Uses the same hash algorithm as ast_str_hash, but converts
1056  * all characters to lowercase prior to computing a hash. This
1057  * allows for easy case-insensitive lookups in a hash table.
1058  */
1059 static force_inline int attribute_pure ast_str_case_hash(const char *str)
1060 {
1061         int hash = 5381;
1062
1063         while (*str) {
1064                 hash = hash * 33 ^ tolower(*str++);
1065         }
1066
1067         return abs(hash);
1068 }
1069
1070 /*!
1071  * \brief Convert a string to all lower-case
1072  *
1073  * \param str The string to be converted to lower case
1074  *
1075  * \retval str for convenience
1076  */
1077 static force_inline char *attribute_pure ast_str_to_lower(char *str)
1078 {
1079         char *str_orig = str;
1080         if (!str) {
1081                 return str;
1082         }
1083
1084         for (; *str; ++str) {
1085                 *str = tolower(*str);
1086         }
1087
1088         return str_orig;
1089 }
1090
1091 /*!
1092  * \brief Convert a string to all upper-case
1093  *
1094  * \param str The string to be converted to upper case
1095  *
1096  * \retval str for convenience
1097  */
1098 static force_inline char *attribute_pure ast_str_to_upper(char *str)
1099 {
1100         char *str_orig = str;
1101         if (!str) {
1102                 return str;
1103         }
1104
1105         for (; *str; ++str) {
1106                 *str = toupper(*str);
1107         }
1108
1109         return str_orig;
1110 }
1111
1112 #endif /* _ASTERISK_STRINGS_H */