Avoid allocations by performing stripping in-place

Introduce a helper function (string_strip_delimited).
This commit is contained in:
Yuri D'Elia 2014-12-21 22:05:16 +01:00 committed by Eizen
parent bed4877d7b
commit 4b53e44d92
3 changed files with 19 additions and 12 deletions

View File

@ -185,23 +185,12 @@ void notification_free(notification * n)
*/
char *notification_strip_markup(char *str)
{
char *replace_buf, *start, *end;
if (str == NULL) {
return NULL;
}
/* strip all tags */
while ((start = strstr(str, "<")) != NULL) {
end = strstr(start, ">");
if (end != NULL) {
replace_buf = strndup(start, end - start + 1);
str = string_replace(replace_buf, "", str);
free(replace_buf);
} else {
break;
}
}
string_strip_delimited(str, '<', '>');
/* unquote the remainder */
str = string_replace_all("&quot;", "\"", str);

15
utils.c
View File

@ -105,6 +105,21 @@ char **string_to_argv(const char *s)
return argv;
}
void string_strip_delimited(char *str, char a, char b)
{
int iread=-1, iwrite=0, copen=0;
while (str[++iread] != 0) {
if (str[iread] == a) {
++copen;
} else if (str[iread] == b && copen > 0) {
--copen;
} else if (copen == 0) {
str[iwrite++] = str[iread];
}
}
str[iwrite] = 0;
}
int digit_count(int i)
{
i = ABS(i);

View File

@ -17,6 +17,9 @@ char *string_append(char *a, const char *b, const char *sep);
char **string_to_argv(const char *s);
/* strip content between two delimiter characters (inplace) */
void string_strip_delimited(char *str, char a, char b);
/* exit with an error message */
void die(char *msg, int exit_value);