Skip to content

Commit

Permalink
fmt: add pl trim functions
Browse files Browse the repository at this point in the history
  • Loading branch information
cspiel1 committed Oct 3, 2022
1 parent fb061a9 commit ec80cd2
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
3 changes: 3 additions & 0 deletions include/re_fmt.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
63 changes: 63 additions & 0 deletions src/fmt/pl.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit ec80cd2

Please sign in to comment.