Fix a bunch of places where \arg was used instead of \param. Using \arg
[asterisk-bristuff.git] / include / asterisk / strings.h
blob13d68d3fcdd645b27732c151e78ec10dd9beb5a2
1 /*
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.
19 /*! \file
20 * \brief String manipulation functions
23 #ifndef _ASTERISK_STRINGS_H
24 #define _ASTERISK_STRINGS_H
26 #include "asterisk/inline_api.h"
27 #include "asterisk/utils.h"
28 #include "asterisk/threadstorage.h"
30 /* You may see casts in this header that may seem useless but they ensure this file is C++ clean */
32 #ifdef AST_DEVMODE
33 #define ast_strlen_zero(foo) _ast_strlen_zero(foo, __FILE__, __PRETTY_FUNCTION__, __LINE__)
34 static force_inline int _ast_strlen_zero(const char *s, const char *file, const char *function, int line)
36 if (!s || (*s == '\0')) {
37 return 1;
39 if (!strcmp(s, "(null)")) {
40 ast_log(__LOG_WARNING, file, line, function, "Possible programming error: \"(null)\" is not NULL!\n");
42 return 0;
45 #else
46 static force_inline int ast_strlen_zero(const char *s)
48 return (!s || (*s == '\0'));
50 #endif
52 /*! \brief returns the equivalent of logic or for strings:
53 * first one if not empty, otherwise second one.
55 #define S_OR(a, b) (!ast_strlen_zero(a) ? (a) : (b))
57 /*! \brief returns the equivalent of logic or for strings, with an additional boolean check:
58 * second one if not empty and first one is true, otherwise third one.
59 * example: S_COR(usewidget, widget, "<no widget>")
61 #define S_COR(a, b, c) ((a && !ast_strlen_zero(b)) ? (b) : (c))
63 /*!
64 \brief Gets a pointer to the first non-whitespace character in a string.
65 \param str the input string
66 \return a pointer to the first non-whitespace character
68 AST_INLINE_API(
69 char *ast_skip_blanks(const char *str),
71 while (*str && ((unsigned char) *str) < 33)
72 str++;
73 return (char *)str;
77 /*!
78 \brief Trims trailing whitespace characters from a string.
79 \param str the input string
80 \return a pointer to the modified string
82 AST_INLINE_API(
83 char *ast_trim_blanks(char *str),
85 char *work = str;
87 if (work) {
88 work += strlen(work) - 1;
89 /* It's tempting to only want to erase after we exit this loop,
90 but since ast_trim_blanks *could* receive a constant string
91 (which we presumably wouldn't have to touch), we shouldn't
92 actually set anything unless we must, and it's easier just
93 to set each position to \0 than to keep track of a variable
94 for it */
95 while ((work >= str) && ((unsigned char) *work) < 33)
96 *(work--) = '\0';
98 return str;
103 \brief Gets a pointer to first whitespace character in a string.
104 \param str the input string
105 \return a pointer to the first whitespace character
107 AST_INLINE_API(
108 char *ast_skip_nonblanks(char *str),
110 while (*str && ((unsigned char) *str) > 32)
111 str++;
112 return str;
117 \brief Strip leading/trailing whitespace from a string.
118 \param s The string to be stripped (will be modified).
119 \return The stripped string.
121 This functions strips all leading and trailing whitespace
122 characters from the input string, and returns a pointer to
123 the resulting string. The string is modified in place.
125 AST_INLINE_API(
126 char *ast_strip(char *s),
128 s = ast_skip_blanks(s);
129 if (s)
130 ast_trim_blanks(s);
131 return s;
136 \brief Strip leading/trailing whitespace and quotes from a string.
137 \param s The string to be stripped (will be modified).
138 \param beg_quotes The list of possible beginning quote characters.
139 \param end_quotes The list of matching ending quote characters.
140 \return The stripped string.
142 This functions strips all leading and trailing whitespace
143 characters from the input string, and returns a pointer to
144 the resulting string. The string is modified in place.
146 It can also remove beginning and ending quote (or quote-like)
147 characters, in matching pairs. If the first character of the
148 string matches any character in beg_quotes, and the last
149 character of the string is the matching character in
150 end_quotes, then they are removed from the string.
152 Examples:
153 \code
154 ast_strip_quoted(buf, "\"", "\"");
155 ast_strip_quoted(buf, "'", "'");
156 ast_strip_quoted(buf, "[{(", "]})");
157 \endcode
159 char *ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes);
162 \brief Strip backslash for "escaped" semicolons,
163 the string to be stripped (will be modified).
164 \return The stripped string.
166 char *ast_unescape_semicolon(char *s);
169 \brief Convert some C escape sequences \verbatim (\b\f\n\r\t) \endverbatim into the
170 equivalent characters. The string to be converted (will be modified).
171 \return The converted string.
173 char *ast_unescape_c(char *s);
176 \brief Size-limited null-terminating string copy.
177 \param dst The destination buffer.
178 \param src The source string
179 \param size The size of the destination buffer
180 \return Nothing.
182 This is similar to \a strncpy, with two important differences:
183 - the destination buffer will \b always be null-terminated
184 - the destination buffer is not filled with zeros past the copied string length
185 These differences make it slightly more efficient, and safer to use since it will
186 not leave the destination buffer unterminated. There is no need to pass an artificially
187 reduced buffer size to this function (unlike \a strncpy), and the buffer does not need
188 to be initialized to zeroes prior to calling this function.
190 AST_INLINE_API(
191 void ast_copy_string(char *dst, const char *src, size_t size),
193 while (*src && size) {
194 *dst++ = *src++;
195 size--;
197 if (__builtin_expect(!size, 0))
198 dst--;
199 *dst = '\0';
205 \brief Build a string in a buffer, designed to be called repeatedly
207 \note This method is not recommended. New code should use ast_str_*() instead.
209 This is a wrapper for snprintf, that properly handles the buffer pointer
210 and buffer space available.
212 \param buffer current position in buffer to place string into (will be updated on return)
213 \param space remaining space in buffer (will be updated on return)
214 \param fmt printf-style format string
215 \retval 0 on success
216 \retval non-zero on failure.
218 int ast_build_string(char **buffer, size_t *space, const char *fmt, ...) __attribute__ ((format (printf, 3, 4)));
221 \brief Build a string in a buffer, designed to be called repeatedly
223 This is a wrapper for snprintf, that properly handles the buffer pointer
224 and buffer space available.
226 \return 0 on success, non-zero on failure.
227 \param buffer current position in buffer to place string into (will be updated on return)
228 \param space remaining space in buffer (will be updated on return)
229 \param fmt printf-style format string
230 \param ap varargs list of arguments for format
232 int ast_build_string_va(char **buffer, size_t *space, const char *fmt, va_list ap) __attribute__((format (printf, 3, 0)));
234 /*!
235 * \brief Make sure something is true.
236 * Determine if a string containing a boolean value is "true".
237 * This function checks to see whether a string passed to it is an indication of an "true" value.
238 * It checks to see if the string is "yes", "true", "y", "t", "on" or "1".
240 * \retval 0 if val is a NULL pointer.
241 * \retval -1 if "true".
242 * \retval 0 otherwise.
244 int ast_true(const char *val);
246 /*!
247 * \brief Make sure something is false.
248 * Determine if a string containing a boolean value is "false".
249 * This function checks to see whether a string passed to it is an indication of an "false" value.
250 * It checks to see if the string is "no", "false", "n", "f", "off" or "0".
252 * \retval 0 if val is a NULL pointer.
253 * \retval -1 if "true".
254 * \retval 0 otherwise.
256 int ast_false(const char *val);
259 * \brief Join an array of strings into a single string.
260 * \param s the resulting string buffer
261 * \param len the length of the result buffer, s
262 * \param w an array of strings to join.
264 * This function will join all of the strings in the array 'w' into a single
265 * string. It will also place a space in the result buffer in between each
266 * string from 'w'.
268 void ast_join(char *s, size_t len, char * const w[]);
271 \brief Parse a time (integer) string.
272 \param src String to parse
273 \param dst Destination
274 \param _default Value to use if the string does not contain a valid time
275 \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
276 \retval 0 on success
277 \retval non-zero on failure.
279 int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed);
282 \brief Parse a time (float) string.
283 \param src String to parse
284 \param dst Destination
285 \param _default Value to use if the string does not contain a valid time
286 \param consumed The number of characters 'consumed' in the string by the parse (see 'man sscanf' for details)
287 \return zero on success, non-zero on failure
289 int ast_get_timeval(const char *src, struct timeval *tv, struct timeval _default, int *consumed);
292 * Support for dynamic strings.
294 * A dynamic string is just a C string prefixed by a few control fields
295 * that help setting/appending/extending it using a printf-like syntax.
297 * One should never declare a variable with this type, but only a pointer
298 * to it, e.g.
300 * struct ast_str *ds;
302 * The pointer can be initialized with the following:
304 * ds = ast_str_create(init_len);
305 * creates a malloc()'ed dynamic string;
307 * ds = ast_str_alloca(init_len);
308 * creates a string on the stack (not very dynamic!).
310 * ds = ast_str_thread_get(ts, init_len)
311 * creates a malloc()'ed dynamic string associated to
312 * the thread-local storage key ts
314 * Finally, the string can be manipulated with the following:
316 * ast_str_set(&buf, max_len, fmt, ...)
317 * ast_str_append(&buf, max_len, fmt, ...)
319 * and their varargs variant
321 * ast_str_set_va(&buf, max_len, ap)
322 * ast_str_append_va(&buf, max_len, ap)
324 * \param max_len The maximum allowed length, reallocating if needed.
325 * 0 means unlimited, -1 means "at most the available space"
327 * \return All the functions return <0 in case of error, or the
328 * length of the string added to the buffer otherwise.
331 /*! \brief The descriptor of a dynamic string
332 * XXX storage will be optimized later if needed
333 * We use the ts field to indicate the type of storage.
334 * Three special constants indicate malloc, alloca() or static
335 * variables, all other values indicate a
336 * struct ast_threadstorage pointer.
338 struct ast_str {
339 size_t len; /*!< The current maximum length of the string */
340 size_t used; /*!< Amount of space used */
341 struct ast_threadstorage *ts; /*!< What kind of storage is this ? */
342 #define DS_MALLOC ((struct ast_threadstorage *)1)
343 #define DS_ALLOCA ((struct ast_threadstorage *)2)
344 #define DS_STATIC ((struct ast_threadstorage *)3) /* not supported yet */
345 char str[0]; /*!< The string buffer */
349 * \brief Create a malloc'ed dynamic length string
351 * \param init_len This is the initial length of the string buffer
353 * \return This function returns a pointer to the dynamic string length. The
354 * result will be NULL in the case of a memory allocation error.
356 * \note The result of this function is dynamically allocated memory, and must
357 * be free()'d after it is no longer needed.
359 AST_INLINE_API(
360 struct ast_str * attribute_malloc ast_str_create(size_t init_len),
362 struct ast_str *buf;
364 buf = (struct ast_str *)ast_calloc(1, sizeof(*buf) + init_len);
365 if (buf == NULL)
366 return NULL;
368 buf->len = init_len;
369 buf->used = 0;
370 buf->ts = DS_MALLOC;
372 return buf;
376 /*! \brief Reset the content of a dynamic string.
377 * Useful before a series of ast_str_append.
379 AST_INLINE_API(
380 void ast_str_reset(struct ast_str *buf),
382 if (buf) {
383 buf->used = 0;
384 if (buf->len)
385 buf->str[0] = '\0';
391 * AST_INLINE_API() is a macro that takes a block of code as an argument.
392 * Using preprocessor #directives in the argument is not supported by all
393 * compilers, and it is a bit of an obfuscation anyways, so avoid it.
394 * As a workaround, define a macro that produces either its argument
395 * or nothing, and use that instead of #ifdef/#endif within the
396 * argument to AST_INLINE_API().
398 #if defined(DEBUG_THREADLOCALS)
399 #define _DB1(x) x
400 #else
401 #define _DB1(x)
402 #endif
405 * Make space in a new string (e.g. to read in data from a file)
407 AST_INLINE_API(
408 int ast_str_make_space(struct ast_str **buf, size_t new_len),
410 _DB1(struct ast_str *old_buf = *buf;)
412 if (new_len <= (*buf)->len)
413 return 0; /* success */
414 if ((*buf)->ts == DS_ALLOCA || (*buf)->ts == DS_STATIC)
415 return -1; /* cannot extend */
416 *buf = (struct ast_str *)ast_realloc(*buf, new_len + sizeof(struct ast_str));
417 if (*buf == NULL) /* XXX watch out, we leak memory here */
418 return -1;
419 if ((*buf)->ts != DS_MALLOC) {
420 pthread_setspecific((*buf)->ts->key, *buf);
421 _DB1(__ast_threadstorage_object_replace(old_buf, *buf, new_len + sizeof(struct ast_str));)
424 (*buf)->len = new_len;
425 return 0;
429 #define ast_str_alloca(init_len) \
430 ({ \
431 struct ast_str *buf; \
432 buf = alloca(sizeof(*buf) + init_len); \
433 buf->len = init_len; \
434 buf->used = 0; \
435 buf->ts = DS_ALLOCA; \
436 buf->str[0] = '\0'; \
437 (buf); \
441 * \brief Retrieve a thread locally stored dynamic string
443 * \param ts This is a pointer to the thread storage structure declared by using
444 * the AST_THREADSTORAGE macro. If declared with
445 * AST_THREADSTORAGE(my_buf, my_buf_init), then this argument would be
446 * (&my_buf).
447 * \param init_len This is the initial length of the thread's dynamic string. The
448 * current length may be bigger if previous operations in this thread have
449 * caused it to increase.
451 * \return This function will return the thread locally stored dynamic string
452 * associated with the thread storage management variable passed as the
453 * first argument.
454 * The result will be NULL in the case of a memory allocation error.
456 * Example usage:
457 * \code
458 * AST_THREADSTORAGE(my_str, my_str_init);
459 * #define MY_STR_INIT_SIZE 128
460 * ...
461 * void my_func(const char *fmt, ...)
463 * struct ast_str *buf;
465 * if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
466 * return;
467 * ...
469 * \endcode
471 #if !defined(DEBUG_THREADLOCALS)
472 AST_INLINE_API(
473 struct ast_str *ast_str_thread_get(struct ast_threadstorage *ts,
474 size_t init_len),
476 struct ast_str *buf;
478 buf = (struct ast_str *)ast_threadstorage_get(ts, sizeof(*buf) + init_len);
479 if (buf == NULL)
480 return NULL;
482 if (!buf->len) {
483 buf->len = init_len;
484 buf->used = 0;
485 buf->ts = ts;
488 return buf;
491 #else /* defined(DEBUG_THREADLOCALS) */
492 AST_INLINE_API(
493 struct ast_str *__ast_str_thread_get(struct ast_threadstorage *ts,
494 size_t init_len, const char *file, const char *function, unsigned int line),
496 struct ast_str *buf;
498 buf = (struct ast_str *)__ast_threadstorage_get(ts, sizeof(*buf) + init_len, file, function, line);
499 if (buf == NULL)
500 return NULL;
502 if (!buf->len) {
503 buf->len = init_len;
504 buf->used = 0;
505 buf->ts = ts;
508 return buf;
512 #define ast_str_thread_get(ts, init_len) __ast_str_thread_get(ts, init_len, __FILE__, __PRETTY_FUNCTION__, __LINE__)
513 #endif /* defined(DEBUG_THREADLOCALS) */
516 * \brief Error codes from __ast_str_helper()
517 * The undelying processing to manipulate dynamic string is done
518 * by __ast_str_helper(), which can return a success, a
519 * permanent failure (e.g. no memory), or a temporary one (when
520 * the string needs to be reallocated, and we must run va_start()
521 * again; XXX this convoluted interface is only here because
522 * FreeBSD 4 lacks va_copy, but this will be fixed and the
523 * interface simplified).
525 enum {
526 /*! An error has occured and the contents of the dynamic string
527 * are undefined */
528 AST_DYNSTR_BUILD_FAILED = -1,
529 /*! The buffer size for the dynamic string had to be increased, and
530 * __ast_str_helper() needs to be called again after
531 * a va_end() and va_start().
533 AST_DYNSTR_BUILD_RETRY = -2
537 * \brief Set a dynamic string from a va_list
539 * \param buf This is the address of a pointer to a struct ast_str.
540 * If it is retrieved using ast_str_thread_get, the
541 struct ast_threadstorage pointer will need to
542 * be updated in the case that the buffer has to be reallocated to
543 * accommodate a longer string than what it currently has space for.
544 * \param max_len This is the maximum length to allow the string buffer to grow
545 * to. If this is set to 0, then there is no maximum length.
546 * \param fmt This is the format string (printf style)
547 * \param ap This is the va_list
549 * \return The return value of this function is the same as that of the printf
550 * family of functions.
552 * Example usage (the first part is only for thread-local storage)
553 * \code
554 * AST_THREADSTORAGE(my_str, my_str_init);
555 * #define MY_STR_INIT_SIZE 128
556 * ...
557 * void my_func(const char *fmt, ...)
559 * struct ast_str *buf;
560 * va_list ap;
562 * if (!(buf = ast_str_thread_get(&my_str, MY_STR_INIT_SIZE)))
563 * return;
564 * ...
565 * va_start(fmt, ap);
566 * ast_str_set_va(&buf, 0, fmt, ap);
567 * va_end(ap);
569 * printf("This is the string we just built: %s\n", buf->str);
570 * ...
572 * \endcode
574 * \note: the following two functions must be implemented as macros
575 * because we must do va_end()/va_start() on the original arguments.
577 #define ast_str_set_va(buf, max_len, fmt, ap) \
578 ({ \
579 int __res; \
580 while ((__res = __ast_str_helper(buf, max_len, \
581 0, fmt, ap)) == AST_DYNSTR_BUILD_RETRY) { \
582 va_end(ap); \
583 va_start(ap, fmt); \
585 (__res); \
589 * \brief Append to a dynamic string using a va_list
591 * Same as ast_str_set_va(), but append to the current content.
593 #define ast_str_append_va(buf, max_len, fmt, ap) \
594 ({ \
595 int __res; \
596 while ((__res = __ast_str_helper(buf, max_len, \
597 1, fmt, ap)) == AST_DYNSTR_BUILD_RETRY) { \
598 va_end(ap); \
599 va_start(ap, fmt); \
601 (__res); \
605 * \brief Core functionality of ast_str_(set|append)_va
607 * The arguments to this function are the same as those described for
608 * ast_str_set_va except for an addition argument, append.
609 * If append is non-zero, this will append to the current string instead of
610 * writing over it.
612 * In the case that this function is called and the buffer was not large enough
613 * to hold the result, the partial write will be truncated, and the result
614 * AST_DYNSTR_BUILD_RETRY will be returned to indicate that the buffer size
615 * was increased, and the function should be called a second time.
617 * A return of AST_DYNSTR_BUILD_FAILED indicates a memory allocation error.
619 * A return value greater than or equal to zero indicates the number of
620 * characters that have been written, not including the terminating '\0'.
621 * In the append case, this only includes the number of characters appended.
623 * \note This function should never need to be called directly. It should
624 * through calling one of the other functions or macros defined in this
625 * file.
627 int __ast_str_helper(struct ast_str **buf, size_t max_len,
628 int append, const char *fmt, va_list ap);
631 * \brief Set a dynamic string using variable arguments
633 * \param buf This is the address of a pointer to a struct ast_str which should
634 * have been retrieved using ast_str_thread_get. It will need to
635 * be updated in the case that the buffer has to be reallocated to
636 * accomodate a longer string than what it currently has space for.
637 * \param max_len This is the maximum length to allow the string buffer to grow
638 * to. If this is set to 0, then there is no maximum length.
639 * If set to -1, we are bound to the current maximum length.
640 * \param fmt This is the format string (printf style)
642 * \return The return value of this function is the same as that of the printf
643 * family of functions.
645 * All the rest is the same as ast_str_set_va()
647 AST_INLINE_API(
648 int __attribute__ ((format (printf, 3, 4))) ast_str_set(
649 struct ast_str **buf, size_t max_len, const char *fmt, ...),
651 int res;
652 va_list ap;
654 va_start(ap, fmt);
655 res = ast_str_set_va(buf, max_len, fmt, ap);
656 va_end(ap);
658 return res;
663 * \brief Append to a thread local dynamic string
665 * The arguments, return values, and usage of this function are the same as
666 * ast_str_set(), but the new data is appended to the current value.
668 AST_INLINE_API(
669 int __attribute__ ((format (printf, 3, 4))) ast_str_append(
670 struct ast_str **buf, size_t max_len, const char *fmt, ...),
672 int res;
673 va_list ap;
675 va_start(ap, fmt);
676 res = ast_str_append_va(buf, max_len, fmt, ap);
677 va_end(ap);
679 return res;
684 * \brief Compute a hash value on a string
686 * This famous hash algorithm was written by Dan Bernstein and is
687 * commonly used.
689 * http://www.cse.yorku.ca/~oz/hash.html
691 static force_inline int ast_str_hash(const char *str)
693 int hash = 5381;
695 while (*str)
696 hash = hash * 33 ^ *str++;
698 return abs(hash);
701 #endif /* _ASTERISK_STRINGS_H */