From 50d3819344ff132e043ba95da7915092d03baf6a Mon Sep 17 00:00:00 2001 From: Sebastian Harl Date: Wed, 20 Mar 2013 00:02:54 -0700 Subject: [PATCH] utils error, strbuf: Added sdb_error_chomp(), sdb_strbuf_chomp(). These functions may be used to remove all consecutive newline characters from the end of the respective strings. --- src/include/utils/error.h | 7 +++++++ src/include/utils/strbuf.h | 12 ++++++++++++ src/utils/error.c | 13 +++++++++++++ src/utils/strbuf.c | 18 ++++++++++++++++++ 4 files changed, 50 insertions(+) diff --git a/src/include/utils/error.h b/src/include/utils/error.h index 487b6e4..33731e1 100644 --- a/src/include/utils/error.h +++ b/src/include/utils/error.h @@ -91,6 +91,13 @@ sdb_error_set(const char *fmt, ...); int sdb_error_append(const char *fmt, ...); +/* + * sdb_error_chomp: + * Remove all consecutive newline characters at the end of the error message. + */ +int +sdb_error_chomp(void); + /* * sdb_error_log: * Log the current error message with the specified priority. See sdb_log for diff --git a/src/include/utils/strbuf.h b/src/include/utils/strbuf.h index 7b159ed..302cfdd 100644 --- a/src/include/utils/strbuf.h +++ b/src/include/utils/strbuf.h @@ -93,6 +93,18 @@ sdb_strbuf_vsprintf(sdb_strbuf_t *strbuf, const char *fmt, va_list ap); ssize_t sdb_strbuf_sprintf(sdb_strbuf_t *strbuf, const char *fmt, ...); +/* + * sdb_strbuf_chomp: + * Remove all consecutive newline characters from the end of the string buffer + * content. + * + * Returns: + * - the number of bytes removed + * - a negative value on error + */ +ssize_t +sdb_strbuf_chomp(sdb_strbuf_t *strbuf); + /* * sdb_strbuf_string: * Returns the content of the string buffer. The caller may not modify the diff --git a/src/utils/error.c b/src/utils/error.c index fc360eb..c62b20d 100644 --- a/src/utils/error.c +++ b/src/utils/error.c @@ -214,6 +214,19 @@ sdb_error_append(const char *fmt, ...) return ret; } /* sdb_error_append */ +int +sdb_error_chomp(void) +{ + sdb_error_ctx_t *ctx; + + ctx = sdb_error_get_ctx(); + if (! ctx) + return -1; + + sdb_strbuf_chomp(ctx->msg); + return 0; +} /* sdb_error_chomp */ + int sdb_error_log(int prio) { diff --git a/src/utils/strbuf.c b/src/utils/strbuf.c index a48f7bc..bc24fef 100644 --- a/src/utils/strbuf.c +++ b/src/utils/strbuf.c @@ -179,6 +179,24 @@ sdb_strbuf_sprintf(sdb_strbuf_t *strbuf, const char *fmt, ...) return status; } /* sdb_strbuf_sprintf */ +ssize_t +sdb_strbuf_chomp(sdb_strbuf_t *strbuf) +{ + ssize_t ret = 0; + + if (! strbuf) + return -1; + + while ((strbuf->pos > 0) + && (strbuf->string[strbuf->pos - 1] == '\n')) { + --strbuf->pos; + strbuf->string[strbuf->pos] = '\0'; + ++ret; + } + + return ret; +} /* sdb_strbuf_chomp */ + const char * sdb_strbuf_string(sdb_strbuf_t *strbuf) { -- 2.30.2