0e904ac593ebe266de45bdbcd70c1d7add8a589a
[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 Gets a pointer to the first non-whitespace character in a string.
87   \param str the input string
88   \return a pointer to the first non-whitespace character
89  */
90 AST_INLINE_API(
91 char * attribute_pure ast_skip_blanks(const char *str),
92 {
93         while (*str && ((unsigned char) *str) < 33)
94                 str++;
95         return (char *) str;
96 }
97 )
98
99 /*!
100   \brief Trims trailing whitespace characters from a string.
101   \param str the input string
102   \return a pointer to the modified string
103  */
104 AST_INLINE_API(
105 char *ast_trim_blanks(char *str),
106 {
107         char *work = str;
108
109         if (work) {
110                 work += strlen(work) - 1;
111                 /* It's tempting to only want to erase after we exit this loop, 
112                    but since ast_trim_blanks *could* receive a constant string
113                    (which we presumably wouldn't have to touch), we shouldn't
114                    actually set anything unless we must, and it's easier just
115                    to set each position to \0 than to keep track of a variable
116                    for it */
117                 while ((work >= str) && ((unsigned char) *work) < 33)
118                         *(work--) = '\0';
119         }
120         return str;
121 }
122 )
123
124 /*!
125   \brief Gets a pointer to first whitespace character in a string.
126   \param str the input string
127   \return a pointer to the first whitespace character
128  */
129 AST_INLINE_API(
130 char * attribute_pure ast_skip_nonblanks(const char *str),
131 {
132         while (*str && ((unsigned char) *str) > 32)
133                 str++;
134         return (char *) str;
135 }
136 )
137   
138 /*!
139   \brief Strip leading/trailing whitespace from a string.
140   \param s The string to be stripped (will be modified).
141   \return The stripped string.
142
143   This functions strips all leading and trailing whitespace
144   characters from the input string, and returns a pointer to
145   the resulting string. The string is modified in place.
146 */
147 AST_INLINE_API(
148 char *ast_strip(char *s),
149 {
150         if ((s = ast_skip_blanks(s))) {
151                 ast_trim_blanks(s);
152         }
153         return s;
154
155 )
156
157 /*!
158   \brief Strip leading/trailing whitespace and quotes from a string.
159   \param s The string to be stripped (will be modified).
160   \param beg_quotes The list of possible beginning quote characters.
161   \param end_quotes The list of matching ending quote characters.
162   \return The stripped string.
163
164   This functions strips all leading and trailing whitespace
165   characters from the input string, and returns a pointer to
166   the resulting string. The string is modified in place.
167
168   It can also remove beginning and ending quote (or quote-like)
169   characters, in matching pairs. If the first character of the
170   string matches any character in beg_quotes, and the last
171   character of the string is the matching character in
172   end_quotes, then they are removed from the string.
173
174   Examples:
175   \code
176   ast_strip_quoted(buf, "\"", "\"");
177   ast_strip_quoted(buf, "'", "'");
178   ast_strip_quoted(buf, "[{(", "]})");
179   \endcode
180  */
181 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes);
182
183 /*!
184   \brief Strip backslash for "escaped" semicolons, 
185         the string to be stripped (will be modified).
186   \return The stripped string.
187  */
188 char *ast_unescape_semicolon(char *s);
189
190 /*!
191   \brief Convert some C escape sequences  \verbatim (\b\f\n\r\t) \endverbatim into the
192         equivalent characters. The string to be converted (will be modified).
193   \return The converted string.
194  */
195 char *ast_unescape_c(char *s);
196
197 /*!
198   \brief Size-limited null-terminating string copy.
199   \param dst The destination buffer.
200   \param src The source string
201   \param size The size of the destination buffer
202   \return Nothing.
203
204   This is similar to \a strncpy, with two important differences:
205     - the destination buffer will \b always be null-terminated
206     - the destination buffer is not filled with zeros past the copied string length
207   These differences make it slightly more efficient, and safer to use since it will
208   not leave the destination buffer unterminated. There is no need to pass an artificially
209   reduced buffer size to this function (unlike \a strncpy), and the buffer does not need
210   to be initialized to zeroes prior to calling this function.
211 */
212 AST_INLINE_API(
213 void ast_copy_string(char *dst, const char *src, size_t size),
214 {
215         while (*src && size) {
216                 *dst++ = *src++;
217                 size--;
218         }
219         if (__builtin_expect(!size, 0))
220                 dst--;
221         *dst = '\0';
222 }
223 )
224
225 /*!
226   \brief Build a string in a buffer, designed to be called repeatedly
227   
228   \note This method is not recommended. New code should use ast_str_*() instead.
229
230   This is a wrapper for snprintf, that properly handles the buffer pointer
231   and buffer space available.
232
233   \param buffer current position in buffer to place string into (will be updated on return)
234   \param space remaining space in buffer (will be updated on return)
235   \param fmt printf-style format string
236   \retval 0 on success
237   \retval non-zero on failure.
238 */
239 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
240
241 /*!
242   \brief Build a string in a buffer, designed to be called repeatedly
243   
244   This is a wrapper for snprintf, that properly handles the buffer pointer
245   and buffer space available.
246
247   \return 0 on success, non-zero on failure.
248   \param buffer current position in buffer to place string into (will be updated on return)
249   \param space remaining space in buffer (will be updated on return)
250   \param fmt printf-style format string
251   \param ap varargs list of arguments for format
252 */
253 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap) __attribute__((format(printf, 3, 0)));
254
255 /*! 
256  * \brief Make sure something is true.
257  * Determine if a string containing a boolean value is "true".
258  * This function checks to see whether a string passed to it is an indication of an "true" value.  
259  * It checks to see if the string is "yes", "true", "y", "t", "on" or "1".  
260  *
261  * \retval 0 if val is a NULL pointer.
262  * \retval -1 if "true".
263  * \retval 0 otherwise.
264  */
265 int attribute_pure ast_true(const char *val);
266
267 /*! 
268  * \brief Make sure something is false.
269  * Determine if a string containing a boolean value is "false".
270  * This function checks to see whether a string passed to it is an indication of an "false" value.  
271  * It checks to see if the string is "no", "false", "n", "f", "off" or "0".  
272  *
273  * \retval 0 if val is a NULL pointer.
274  * \retval -1 if "true".
275  * \retval 0 otherwise.
276  */
277 int attribute_pure ast_false(const char *val);
278
279 /*
280  *  \brief Join an array of strings into a single string.
281  * \param s the resulting string buffer
282  * \param len the length of the result buffer, s
283  * \param w an array of strings to join.
284  *
285  * This function will join all of the strings in the array 'w' into a single
286  * string.  It will also place a space in the result buffer in between each
287  * string from 'w'.
288 */
289 void ast_join(char *s, size_t len, const char * const w[]);
290
291 /*
292   \brief Parse a time (integer) string.
293   \param src String to parse
294   \param dst Destination
295   \param _default Value to use if the string does not contain a valid time
296   \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
297   \retval 0 on success
298   \retval non-zero on failure.
299 */
300 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed);
301
302 /*
303   \brief Parse a time (float) string.
304   \param src String to parse
305   \param dst Destination
306   \param _default Value to use if the string does not contain a valid time
307   \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
308   \return zero on success, non-zero on failure
309 */
310 int ast_get_timeval(const char *src, struct timeval *tv, struct timeval _default, int *consumed);
311
312 /*!
313  * Support for dynamic strings.
314  *
315  * A dynamic string is just a C string prefixed by a few control fields
316  * that help setting/appending/extending it using a printf-like syntax.
317  *
318  * One should never declare a variable with this type, but only a pointer
319  * to it, e.g.
320  *
321  *      struct ast_str *ds;
322  *
323  * The pointer can be initialized with the following:
324  *
325  *      ds = ast_str_create(init_len);
326  *              creates a malloc()'ed dynamic string;
327  *
328  *      ds = ast_str_alloca(init_len);
329  *              creates a string on the stack (not very dynamic!).
330  *
331  *      ds = ast_str_thread_get(ts, init_len)
332  *              creates a malloc()'ed dynamic string associated to
333  *              the thread-local storage key ts
334  *
335  * Finally, the string can be manipulated with the following:
336  *
337  *      ast_str_set(&buf, max_len, fmt, ...)
338  *      ast_str_append(&buf, max_len, fmt, ...)
339  *
340  * and their varargs variant
341  *
342  *      ast_str_set_va(&buf, max_len, ap)
343  *      ast_str_append_va(&buf, max_len, ap)
344  *
345  * \param max_len The maximum allowed length, reallocating if needed.
346  *      0 means unlimited, -1 means "at most the available space"
347  *
348  * \return All the functions return <0 in case of error, or the
349  *      length of the string added to the buffer otherwise.
350  */
351
352 /*! \brief The descriptor of a dynamic string
353  *  XXX storage will be optimized later if needed
354  * We use the ts field to indicate the type of storage.
355  * Three special constants indicate malloc, alloca() or static
356  * variables, all other values indicate a
357  * struct ast_threadstorage pointer.
358  */
359 struct ast_str {
360         size_t __AST_STR_LEN;                   /*!< The current maximum length of the string */
361         size_t __AST_STR_USED;                  /*!< Amount of space used */
362         struct ast_threadstorage *__AST_STR_TS; /*!< What kind of storage is this ? */
363 #define DS_MALLOC       ((struct ast_threadstorage *)1)
364 #define DS_ALLOCA       ((struct ast_threadstorage *)2)
365 #define DS_STATIC       ((struct ast_threadstorage *)3) /* not supported yet */
366         char __AST_STR_STR[0];                  /*!< The string buffer */
367 };
368
369 /*!
370  * \brief Create a malloc'ed dynamic length string
371  *
372  * \param init_len This is the initial length of the string buffer
373  *
374  * \return This function returns a pointer to the dynamic string length.  The
375  *         result will be NULL in the case of a memory allocation error.
376  *
377  * \note The result of this function is dynamically allocated memory, and must
378  *       be free()'d after it is no longer needed.
379  */
380 #if (defined(MALLOC_DEBUG) && !defined(STANDALONE))
381 #define ast_str_create(a)       _ast_str_create(a,__FILE__,__LINE__,__PRETTY_FUNCTION__)
382 AST_INLINE_API(
383 struct ast_str * attribute_malloc _ast_str_create(size_t init_len,
384                 const char *file, int lineno, const char *func),
385 {
386         struct ast_str *buf;
387
388         buf = (struct ast_str *)__ast_calloc(1, sizeof(*buf) + init_len, file, lineno, func);
389         if (buf == NULL)
390                 return NULL;
391
392         buf->__AST_STR_LEN = init_len;
393         buf->__AST_STR_USED = 0;
394         buf->__AST_STR_TS = DS_MALLOC;
395
396         return buf;
397 }
398 )
399 #else
400 AST_INLINE_API(
401 struct ast_str * attribute_malloc ast_str_create(size_t init_len),
402 {
403         struct ast_str *buf;
404
405         buf = (struct ast_str *)ast_calloc(1, sizeof(*buf) + init_len);
406         if (buf == NULL)
407                 return NULL;
408
409         buf->__AST_STR_LEN = init_len;
410         buf->__AST_STR_USED = 0;
411         buf->__AST_STR_TS = DS_MALLOC;
412
413         return buf;
414 }
415 )
416 #endif
417
418 /*! \brief Reset the content of a dynamic string.
419  * Useful before a series of ast_str_append.
420  */
421 AST_INLINE_API(
422 void ast_str_reset(struct ast_str *buf),
423 {
424         if (buf) {
425                 buf->__AST_STR_USED = 0;
426                 if (buf->__AST_STR_LEN) {
427                         buf->__AST_STR_STR[0] = '\0';
428                 }
429         }
430 }
431 )
432
433 /*! \brief Update the length of the buffer, after using ast_str merely as a buffer.
434  *  \param buf A pointer to the ast_str string.
435  */
436 AST_INLINE_API(
437 void ast_str_update(struct ast_str *buf),
438 {
439         buf->__AST_STR_USED = strlen(buf->__AST_STR_STR);
440 }
441 )
442
443 /*! \brief Trims trailing whitespace characters from an ast_str string.
444  *  \param buf A pointer to the ast_str string.
445  */
446 AST_INLINE_API(
447 void ast_str_trim_blanks(struct ast_str *buf),
448 {
449         if (!buf) {
450                 return;
451         }
452         while (buf->__AST_STR_USED && buf->__AST_STR_STR[buf->__AST_STR_USED - 1] < 33) {
453                 buf->__AST_STR_STR[--(buf->__AST_STR_USED)] = '\0';
454         }
455 }
456 )
457
458 /*!\brief Returns the current length of the string stored within buf.
459  * \param buf A pointer to the ast_str structure.
460  */
461 AST_INLINE_API(
462 size_t attribute_pure ast_str_strlen(const struct ast_str *buf),
463 {
464         return buf->__AST_STR_USED;
465 }
466 )
467
468 /*!\brief Returns the current maximum length (without reallocation) of the current buffer.
469  * \param buf A pointer to the ast_str structure.
470  * \retval Current maximum length of the buffer.
471  */
472 AST_INLINE_API(
473 size_t attribute_pure ast_str_size(const struct ast_str *buf),
474 {
475         return buf->__AST_STR_LEN;
476 }
477 )
478
479 /*!\brief Returns the string buffer within the ast_str buf.
480  * \param buf A pointer to the ast_str structure.
481  * \retval A pointer to the enclosed string.
482  */
483 AST_INLINE_API(
484 char * attribute_pure ast_str_buffer(const struct ast_str *buf),
485 {
486         /* for now, cast away the const qualifier on the pointer
487          * being returned; eventually, it should become truly const
488          * and only be modified via accessor functions
489          */
490         return (char *) buf->__AST_STR_STR;
491 }
492 )
493
494 /*!\brief Truncates the enclosed string to the given length.
495  * \param buf A pointer to the ast_str structure.
496  * \param len Maximum length of the string.
497  * \retval A pointer to the resulting string.
498  */
499 AST_INLINE_API(
500 char *ast_str_truncate(struct ast_str *buf, ssize_t len),
501 {
502         if (len < 0) {
503                 buf->__AST_STR_USED += ((ssize_t) abs(len)) > (ssize_t) buf->__AST_STR_USED ? -buf->__AST_STR_USED : len;
504         } else {
505                 buf->__AST_STR_USED = len;
506         }
507         buf->__AST_STR_STR[buf->__AST_STR_USED] = '\0';
508         return buf->__AST_STR_STR;
509 }
510 )
511         
512 /*
513  * AST_INLINE_API() is a macro that takes a block of code as an argument.
514  * Using preprocessor #directives in the argument is not supported by all
515  * compilers, and it is a bit of an obfuscation anyways, so avoid it.
516  * As a workaround, define a macro that produces either its argument
517  * or nothing, and use that instead of #ifdef/#endif within the
518  * argument to AST_INLINE_API().
519  */
520 #if defined(DEBUG_THREADLOCALS)
521 #define _DB1(x) x
522 #else
523 #define _DB1(x)
524 #endif
525
526 /*!
527  * Make space in a new string (e.g. to read in data from a file)
528  */
529 #if (defined(MALLOC_DEBUG) && !defined(STANDALONE))
530 AST_INLINE_API(
531 int _ast_str_make_space(struct ast_str **buf, size_t new_len, const char *file, int lineno, const char *function),
532 {
533         struct ast_str *old_buf = *buf;
534
535         if (new_len <= (*buf)->__AST_STR_LEN) 
536                 return 0;       /* success */
537         if ((*buf)->__AST_STR_TS == DS_ALLOCA || (*buf)->__AST_STR_TS == DS_STATIC)
538                 return -1;      /* cannot extend */
539         *buf = (struct ast_str *)__ast_realloc(*buf, new_len + sizeof(struct ast_str), file, lineno, function);
540         if (*buf == NULL) {
541                 *buf = old_buf;
542                 return -1;
543         }
544         if ((*buf)->__AST_STR_TS != DS_MALLOC) {
545                 pthread_setspecific((*buf)->__AST_STR_TS->key, *buf);
546                 _DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
547         }
548
549         (*buf)->__AST_STR_LEN = new_len;
550         return 0;
551 }
552 )
553 #define ast_str_make_space(a,b) _ast_str_make_space(a,b,__FILE__,__LINE__,__PRETTY_FUNCTION__)
554 #else
555 AST_INLINE_API(
556 int ast_str_make_space(struct ast_str **buf, size_t new_len),
557 {
558         struct ast_str *old_buf = *buf;
559
560         if (new_len <= (*buf)->__AST_STR_LEN) 
561                 return 0;       /* success */
562         if ((*buf)->__AST_STR_TS == DS_ALLOCA || (*buf)->__AST_STR_TS == DS_STATIC)
563                 return -1;      /* cannot extend */
564         *buf = (struct ast_str *)ast_realloc(*buf, new_len + sizeof(struct ast_str));
565         if (*buf == NULL) {
566                 *buf = old_buf;
567                 return -1;
568         }
569         if ((*buf)->__AST_STR_TS != DS_MALLOC) {
570                 pthread_setspecific((*buf)->__AST_STR_TS->key, *buf);
571                 _DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
572         }
573
574         (*buf)->__AST_STR_LEN = new_len;
575         return 0;
576 }
577 )
578 #endif
579
580 #define ast_str_alloca(init_len)                        \
581         ({                                              \
582                 struct ast_str *__ast_str_buf;                  \
583                 __ast_str_buf = alloca(sizeof(*__ast_str_buf) + init_len);      \
584                 __ast_str_buf->__AST_STR_LEN = init_len;                        \
585                 __ast_str_buf->__AST_STR_USED = 0;                              \
586                 __ast_str_buf->__AST_STR_TS = DS_ALLOCA;                        \
587                 __ast_str_buf->__AST_STR_STR[0] = '\0';                 \
588                 (__ast_str_buf);                                        \
589         })
590
591 /*!
592  * \brief Retrieve a thread locally stored dynamic string
593  *
594  * \param ts This is a pointer to the thread storage structure declared by using
595  *      the AST_THREADSTORAGE macro.  If declared with 
596  *      AST_THREADSTORAGE(my_buf, my_buf_init), then this argument would be 
597  *      (&my_buf).
598  * \param init_len This is the initial length of the thread's dynamic string. The
599  *      current length may be bigger if previous operations in this thread have
600  *      caused it to increase.
601  *
602  * \return This function will return the thread locally stored dynamic string
603  *         associated with the thread storage management variable passed as the
604  *         first argument.
605  *         The result will be NULL in the case of a memory allocation error.
606  *
607  * Example usage:
608  * \code
609  * AST_THREADSTORAGE(my_str, my_str_init);
610  * #define MY_STR_INIT_SIZE   128
611  * ...
612  * void my_func(const char *fmt, ...)
613  * {
614  *      struct ast_str *buf;
615  *
616  *      if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
617  *           return;
618  *      ...
619  * }
620  * \endcode
621  */
622 #if !defined(DEBUG_THREADLOCALS)
623 AST_INLINE_API(
624 struct ast_str *ast_str_thread_get(struct ast_threadstorage *ts,
625         size_t init_len),
626 {
627         struct ast_str *buf;
628
629         buf = (struct ast_str *)ast_threadstorage_get(ts, sizeof(*buf) + init_len);
630         if (buf == NULL)
631                 return NULL;
632
633         if (!buf->__AST_STR_LEN) {
634                 buf->__AST_STR_LEN = init_len;
635                 buf->__AST_STR_USED = 0;
636                 buf->__AST_STR_TS = ts;
637         }
638
639         return buf;
640 }
641 )
642 #else /* defined(DEBUG_THREADLOCALS) */
643 AST_INLINE_API(
644 struct ast_str *__ast_str_thread_get(struct ast_threadstorage *ts,
645         size_t init_len, const char *file, const char *function, unsigned int line),
646 {
647         struct ast_str *buf;
648
649         buf = (struct ast_str *)__ast_threadstorage_get(ts, sizeof(*buf) + init_len, file, function, line);
650         if (buf == NULL)
651                 return NULL;
652
653         if (!buf->__AST_STR_LEN) {
654                 buf->__AST_STR_LEN = init_len;
655                 buf->__AST_STR_USED = 0;
656                 buf->__AST_STR_TS = ts;
657         }
658
659         return buf;
660 }
661 )
662
663 #define ast_str_thread_get(ts, init_len) __ast_str_thread_get(ts, init_len, __FILE__, __PRETTY_FUNCTION__, __LINE__)
664 #endif /* defined(DEBUG_THREADLOCALS) */
665
666 /*!
667  * \brief Error codes from __ast_str_helper()
668  * The undelying processing to manipulate dynamic string is done
669  * by __ast_str_helper(), which can return a success or a
670  * permanent failure (e.g. no memory).
671  */
672 enum {
673         /*! An error has occurred and the contents of the dynamic string
674          *  are undefined */
675         AST_DYNSTR_BUILD_FAILED = -1,
676         /*! The buffer size for the dynamic string had to be increased, and
677          *  __ast_str_helper() needs to be called again after
678          *  a va_end() and va_start().  This return value is legacy and will
679          *  no longer be used.
680          */
681         AST_DYNSTR_BUILD_RETRY = -2
682 };
683
684 /*!
685  * \brief Core functionality of ast_str_(set|append)_va
686  *
687  * The arguments to this function are the same as those described for
688  * ast_str_set_va except for an addition argument, append.
689  * If append is non-zero, this will append to the current string instead of
690  * writing over it.
691  *
692  * AST_DYNSTR_BUILD_RETRY is a legacy define.  It should probably never
693  * again be used.
694  *
695  * A return of AST_DYNSTR_BUILD_FAILED indicates a memory allocation error.
696  *
697  * A return value greater than or equal to zero indicates the number of
698  * characters that have been written, not including the terminating '\0'.
699  * In the append case, this only includes the number of characters appended.
700  *
701  * \note This function should never need to be called directly.  It should
702  *       through calling one of the other functions or macros defined in this
703  *       file.
704  */
705 #if (defined(MALLOC_DEBUG) && !defined(STANDALONE))
706 int __attribute__((format(printf, 4, 0))) __ast_debug_str_helper(struct ast_str **buf, size_t max_len,
707                                                            int append, const char *fmt, va_list ap, const char *file, int lineno, const char *func);
708 #define __ast_str_helper(a,b,c,d,e)     __ast_debug_str_helper(a,b,c,d,e,__FILE__,__LINE__,__PRETTY_FUNCTION__)
709 #else
710 int __attribute__((format(printf, 4, 0))) __ast_str_helper(struct ast_str **buf, size_t max_len,
711                                                            int append, const char *fmt, va_list ap);
712 #endif
713 char *__ast_str_helper2(struct ast_str **buf, size_t max_len,
714         const char *src, size_t maxsrc, int append, int escapecommas);
715
716 /*!
717  * \brief Set a dynamic string from a va_list
718  *
719  * \param buf This is the address of a pointer to a struct ast_str.
720  *      If it is retrieved using ast_str_thread_get, the
721         struct ast_threadstorage pointer will need to
722  *      be updated in the case that the buffer has to be reallocated to
723  *      accommodate a longer string than what it currently has space for.
724  * \param max_len This is the maximum length to allow the string buffer to grow
725  *      to.  If this is set to 0, then there is no maximum length.
726  * \param fmt This is the format string (printf style)
727  * \param ap This is the va_list
728  *
729  * \return The return value of this function is the same as that of the printf
730  *         family of functions.
731  *
732  * Example usage (the first part is only for thread-local storage)
733  * \code
734  * AST_THREADSTORAGE(my_str, my_str_init);
735  * #define MY_STR_INIT_SIZE   128
736  * ...
737  * void my_func(const char *fmt, ...)
738  * {
739  *      struct ast_str *buf;
740  *      va_list ap;
741  *
742  *      if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
743  *           return;
744  *      ...
745  *      va_start(fmt, ap);
746  *      ast_str_set_va(&buf, 0, fmt, ap);
747  *      va_end(ap);
748  * 
749  *      printf("This is the string we just built: %s\n", buf->str);
750  *      ...
751  * }
752  * \endcode
753  */
754 AST_INLINE_API(int __attribute__((format(printf, 3, 0))) ast_str_set_va(struct ast_str **buf, size_t max_len, const char *fmt, va_list ap),
755 {
756         return __ast_str_helper(buf, max_len, 0, fmt, ap);
757 }
758 )
759
760 /*!
761  * \brief Append to a dynamic string using a va_list
762  *
763  * Same as ast_str_set_va(), but append to the current content.
764  */
765 AST_INLINE_API(int __attribute__((format(printf, 3, 0))) ast_str_append_va(struct ast_str **buf, size_t max_len, const char *fmt, va_list ap),
766 {
767         return __ast_str_helper(buf, max_len, 1, fmt, ap);
768 }
769 )
770
771 /*!\brief Set a dynamic string to a non-NULL terminated substring. */
772 AST_INLINE_API(char *ast_str_set_substr(struct ast_str **buf, size_t maxlen, const char *src, size_t maxsrc),
773 {
774         return __ast_str_helper2(buf, maxlen, src, maxsrc, 0, 0);
775 }
776 )
777
778 /*!\brief Append a non-NULL terminated substring to the end of a dynamic string. */
779 AST_INLINE_API(char *ast_str_append_substr(struct ast_str **buf, size_t maxlen, const char *src, size_t maxsrc),
780 {
781         return __ast_str_helper2(buf, maxlen, src, maxsrc, 1, 0);
782 }
783 )
784
785 /*!\brief Set a dynamic string to a non-NULL terminated substring, with escaping of commas. */
786 AST_INLINE_API(char *ast_str_set_escapecommas(struct ast_str **buf, size_t maxlen, const char *src, size_t maxsrc),
787 {
788         return __ast_str_helper2(buf, maxlen, src, maxsrc, 0, 1);
789 }
790 )
791
792 /*!\brief Append a non-NULL terminated substring to the end of a dynamic string, with escaping of commas. */
793 AST_INLINE_API(char *ast_str_append_escapecommas(struct ast_str **buf, size_t maxlen, const char *src, size_t maxsrc),
794 {
795         return __ast_str_helper2(buf, maxlen, src, maxsrc, 1, 1);
796 }
797 )
798
799 /*!
800  * \brief Set a dynamic string using variable arguments
801  *
802  * \param buf This is the address of a pointer to a struct ast_str which should
803  *      have been retrieved using ast_str_thread_get.  It will need to
804  *      be updated in the case that the buffer has to be reallocated to
805  *      accomodate a longer string than what it currently has space for.
806  * \param max_len This is the maximum length to allow the string buffer to grow
807  *      to.  If this is set to 0, then there is no maximum length.
808  *      If set to -1, we are bound to the current maximum length.
809  * \param fmt This is the format string (printf style)
810  *
811  * \return The return value of this function is the same as that of the printf
812  *         family of functions.
813  *
814  * All the rest is the same as ast_str_set_va()
815  */
816 AST_INLINE_API(
817 int __attribute__((format(printf, 3, 4))) ast_str_set(
818         struct ast_str **buf, size_t max_len, const char *fmt, ...),
819 {
820         int res;
821         va_list ap;
822
823         va_start(ap, fmt);
824         res = ast_str_set_va(buf, max_len, fmt, ap);
825         va_end(ap);
826
827         return res;
828 }
829 )
830
831 /*!
832  * \brief Append to a thread local dynamic string
833  *
834  * The arguments, return values, and usage of this function are the same as
835  * ast_str_set(), but the new data is appended to the current value.
836  */
837 AST_INLINE_API(
838 int __attribute__((format(printf, 3, 4))) ast_str_append(
839         struct ast_str **buf, size_t max_len, const char *fmt, ...),
840 {
841         int res;
842         va_list ap;
843
844         va_start(ap, fmt);
845         res = ast_str_append_va(buf, max_len, fmt, ap);
846         va_end(ap);
847
848         return res;
849 }
850 )
851
852 /*!
853  * \brief Compute a hash value on a string
854  *
855  * This famous hash algorithm was written by Dan Bernstein and is
856  * commonly used.
857  *
858  * http://www.cse.yorku.ca/~oz/hash.html
859  */
860 static force_inline int attribute_pure ast_str_hash(const char *str)
861 {
862         int hash = 5381;
863
864         while (*str)
865                 hash = hash * 33 ^ *str++;
866
867         return abs(hash);
868 }
869
870 /*!
871  * \brief Compute a hash value on a string
872  *
873  * \param[in] str The string to add to the hash
874  * \param[in] hash The hash value to add to
875  * 
876  * \details
877  * This version of the function is for when you need to compute a
878  * string hash of more than one string.
879  *
880  * This famous hash algorithm was written by Dan Bernstein and is
881  * commonly used.
882  *
883  * \sa http://www.cse.yorku.ca/~oz/hash.html
884  */
885 static force_inline int ast_str_hash_add(const char *str, int hash)
886 {
887         while (*str)
888                 hash = hash * 33 ^ *str++;
889
890         return abs(hash);
891 }
892
893 /*!
894  * \brief Compute a hash value on a case-insensitive string
895  *
896  * Uses the same hash algorithm as ast_str_hash, but converts
897  * all characters to lowercase prior to computing a hash. This
898  * allows for easy case-insensitive lookups in a hash table.
899  */
900 static force_inline int attribute_pure ast_str_case_hash(const char *str)
901 {
902         int hash = 5381;
903
904         while (*str) {
905                 hash = hash * 33 ^ tolower(*str++);
906         }
907
908         return abs(hash);
909 }
910
911 #endif /* _ASTERISK_STRINGS_H */