From a33c742c87c5e267f00e561c27f96ddfb522f6bc Mon Sep 17 00:00:00 2001 From: Vito Caputo Date: Mon, 26 Jun 2023 14:53:55 -0700 Subject: til_str: introduce til_str_chomp() Helper for trimming off a trailing CRNL or NL if present Clearly I once knew perl if this is the name that came to mind --- src/til_str.c | 18 ++++++++++++++++++ src/til_str.h | 1 + 2 files changed, 19 insertions(+) (limited to 'src') diff --git a/src/til_str.c b/src/til_str.c index f3cc5e8..fa256d7 100644 --- a/src/til_str.c +++ b/src/til_str.c @@ -179,3 +179,21 @@ char * til_str_to_buf(til_str_t *str, size_t *res_len) return buf; } + + +/* truncate off trailing \n or \r\n if present + * str is passed through for convenience (til_str_to_buf(til_str_chomp(str), &len)) etc... + */ +til_str_t * til_str_chomp(til_str_t *str) +{ + assert(str); + + if (str->size.used > 1 && str->buf[str->size.used - 2] == '\n') { + if (str->size.used > 2 && str->buf[str->size.used - 3] == '\r') + str->size.used--; + str->size.used--; + str->buf[str->size.used - 1] = '\0'; + } + + return str; +} diff --git a/src/til_str.h b/src/til_str.h index e653884..544185c 100644 --- a/src/til_str.h +++ b/src/til_str.h @@ -10,5 +10,6 @@ int til_str_appendf(til_str_t *str, const char *format, ...); char * til_str_strdup(const til_str_t *str); const char * til_str_buf(const til_str_t *str, size_t *res_len); char * til_str_to_buf(til_str_t *str, size_t *res_len); +til_str_t * til_str_chomp(til_str_t *str); #endif -- cgit v1.2.3