Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt: add pl_trim functions #557

Merged
merged 1 commit into from
Oct 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}