From ec80cd2e9cbc6594d8f0611d5e4313b0a8b315c7 Mon Sep 17 00:00:00 2001 From: Christian Spielberger Date: Mon, 3 Oct 2022 09:23:55 +0200 Subject: [PATCH] fmt: add pl trim functions --- include/re_fmt.h | 3 +++ src/fmt/pl.c | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/include/re_fmt.h b/include/re_fmt.h index 7b69db7e0..85f499170 100644 --- a/include/re_fmt.h +++ b/include/re_fmt.h @@ -46,6 +46,9 @@ int pl_cmp(const struct pl *pl1, const struct pl *pl2); int pl_casecmp(const struct pl *pl1, const struct pl *pl2); const char *pl_strchr(const struct pl *pl, char c); const char *pl_strrchr(const struct pl *pl, char c); +int pl_trim(struct pl *pl); +int pl_ltrim(struct pl *pl); +int pl_rtrim(struct pl *pl); /** Advance pl position/length by +/- N bytes */ static inline void pl_advance(struct pl *pl, ssize_t n) diff --git a/src/fmt/pl.c b/src/fmt/pl.c index 55a9d2119..94ce6d272 100644 --- a/src/fmt/pl.c +++ b/src/fmt/pl.c @@ -653,3 +653,66 @@ const char *pl_strrchr(const struct pl *pl, char c) return NULL; } + + +/** + * Trim white space characters at start of pointer-length string + * + * @param pl Pointer-length string + * + * @return int 0 if success, otherwise errorcode + */ +int pl_ltrim(struct pl *pl) +{ + if (!pl_isset(pl)) + return EINVAL; + + while (!re_regex(pl->p, 1, "[ \t\r\n]")) { + ++pl->p; + --pl->l; + if (!pl->l) + return EINVAL; + } + + return 0; +} + + +/** + * Trim white space characters at end of pointer-length string + * + * @param pl Pointer-length string + * + * @return int 0 if success, otherwise errorcode + */ +int pl_rtrim(struct pl *pl) +{ + if (!pl_isset(pl)) + return EINVAL; + + while (!re_regex(pl->p + pl->l - 1, 1, "[ \t\r\n]")) { + --pl->l; + if (!pl->l) + return EINVAL; + } + + return 0; +} + + +/** + * Trim a pointer-length string on both ends + * + * @param pl Pointer-length string + * + * @return int 0 if success, otherwise errorcode + */ +int pl_trim(struct pl *pl) +{ + int err; + + err = pl_ltrim(pl); + err |= pl_rtrim(pl); + + return err; +}