[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: [Libguestfs] [PATCH 1/2] daemon: Add a trim utility function.



Richard W.M. Jones wrote:
> Subject: [PATCH 1/2] daemon: Add a trim utility function.
>
> This function trims the whitespace from around a string.  It
> does this in-place, so it can be called for malloc'd strings.
...
> diff --git a/daemon/guestfsd.c b/daemon/guestfsd.c
...
> +/* Skip leading and trailing whitespace, updating the original string
> + * in-place.
> + */
> +void
> +trim (char *str)
> +{
> +  size_t len = strlen (str);
> +
> +  while (len > 0 && c_isspace (str[len-1])) {
> +    str[len-1] = '\0';
> +    len--;
> +  }

You might want to avoid the writes when there are two or
more trailing whitespace bytes.  It's enough just to write
the final (leftmost) one.

> +
> +  char *p = str;

This can be "const".

> +  while (*p && c_isspace (*p)) {
> +    p++;
> +    len--;
> +  }

You might want to replace the loop with

    size_t n_leading_sp = strspn (p, " \t\n\v\f\r")
    p += n_leading_sp;
    len -= n_leading_sp;

> +  memmove (str, p, len+1);
> +}

It probably doesn't matter, since this function
is unlikely to be applied in an inner loop or to very long
strings with lots of leading and trailing blanks, but...

You could write this function so that it reads the input string
only once, rather than 2 or 3 times.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]