diff options
Diffstat (limited to 'src/strutil.h')
| -rw-r--r-- | src/strutil.h | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/src/strutil.h b/src/strutil.h new file mode 100644 index 0000000..f4dea54 --- /dev/null +++ b/src/strutil.h @@ -0,0 +1,81 @@ +/** + * \file strutil.h + * A collection of string utilities. + */ + +#ifndef STRUTIL_H +#define STRUTIL_H + +#include "dynstr.h" + +#include <string.h> + +/** + * Allocate a string initialized with the len first bytes of src. + * Similar to strndup but it doesn't check for '\0' in src. + * Returns NULL in case of allocation errors. + * @param src string to copy len bytes from, may not be NULL + * @param len bytes to copy from src + * @return newly allocate null-terminated string + */ +MALLOC NONULL char* strdup_len(const char* src, size_t len); + +/** + * Unescape (remove backslashes from) a null-terminated string inline. + * Does not have any special handling for sequences like \\n, \\t or \\0. + * @param str null-terminated string to remove backslashes from, may not be NULL + */ +NONULL void unescape(char* str); + +/** + * Escape all listed characters if they appear in string with backslash. + * Also escapes backslash. + * Returns NULL in case of allocation errors. + * @param str null-terminated string to escape characters in if needed, + * may not be NULL + * @param chars null-terminated string containing all characters that need to + * be escaped, may not be NULL + * @return newly allocated null-terminated copy of string with + * characters escaped + */ +MALLOC NONULL char* escape(const char* str, const char* chars); + +/** + * Escape all listed characters if they appear in the dynamic string with + * backslash inline. Also escapes backslash. + * @param str dynamic string to escape characters in if needed, + * may not be NULL + * @param chars null-terminated string containing all characters that need to + * be escaped, may not be NULL + * @return false in case of allocation errors + */ +NONULL bool dynstr_escape(dynstr_t* str, const char* chars); + +/** + * Split string by delimiter. + * Returned list will always contain at least one item and will be + * null-terminated. + * Returns NULL in case of allocation errors. + * @param start start of string to split by delimiter + * @param end end of string to split by delimiter + * @param delim delimiter to use + * @return null-terminated list of strings or NULL + */ +NONULL char** split_len(const char* start, const char* end, char delim); + +/** + * Split string by delimiter. + * Returned list will always contain at least one item and will be + * null-terminated. + * Returns NULL in case of allocation errors. + * @param str string to split by delimiter + * @param delim delimiter to use + * @return null-terminated list of strings or NULL + */ +NONULL static inline char** split(const char* str, char delim) +{ + assert(str); + return split_len(str, str + strlen(str), delim); +} + +#endif /* STRUTIL_H */ |
