From 4b53e44d92fc04d9ca822333413838c941878cee Mon Sep 17 00:00:00 2001 From: Yuri D'Elia Date: Sun, 21 Dec 2014 22:05:16 +0100 Subject: [PATCH] Avoid allocations by performing stripping in-place Introduce a helper function (string_strip_delimited). --- notification.c | 13 +------------ utils.c | 15 +++++++++++++++ utils.h | 3 +++ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/notification.c b/notification.c index 5be57fd..f96931f 100644 --- a/notification.c +++ b/notification.c @@ -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(""", "\"", str); diff --git a/utils.c b/utils.c index 0ab4b3a..c162024 100644 --- a/utils.c +++ b/utils.c @@ -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); diff --git a/utils.h b/utils.h index 9617301..1009f96 100644 --- a/utils.h +++ b/utils.h @@ -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);