coreutils
[Top][All Lists]
Advanced

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

Re: removing coreutils' final strncpy uses


From: Jim Meyering
Subject: Re: removing coreutils' final strncpy uses
Date: Fri, 20 Jul 2012 20:06:04 +0200

Jim Meyering wrote:
> ohav chochmah wrote:
>> Why not reuse memccpy (in glibc)? as in 'memccpy(to, from, '\0', size)'.
>> Not only for sake of reusing, but memccpy is highly optimized for
>> ia64, and may be optimized for other arches in the future.
>
> Thanks for the suggestion, but that returns NULL
> when it finds no NUL byte in the first SIZE bytes of FROM.
> I could implement stzncpy in terms of that function instead
> of open-coding the loop:
>
> diff --git a/src/system.h b/src/system.h
> index 6907603..10b04b2 100644
> --- a/src/system.h
> +++ b/src/system.h
> @@ -633,11 +633,13 @@ The following directory is part of the cycle:\n  
> %s\n"), \
>  static inline char *
>  stzncpy (char *dest, char const *src, size_t len)
>  {
> -  char const *src_end = src + len;
> -  while (src < src_end && *src)
> -    *dest++ = *src++;
> -  *dest = 0;
> -  return dest;
> +  char *p = memccpy (dest, src, 0, len);
> +  if (p == NULL)
> +    {
> +      p = dest + len;
> +      *p = 0;
> +    }
> +  return p;
>  }
>
>  #ifndef ARRAY_CARDINALITY
>
> but (for portability) that would require a gnulib module for memccpy.
> Such a module would be welcome regardless, but here it seems like
> it's not worth the complication, since the few uses of stzncpy are not
> performance sensitive.

For the record, the above alternate patch is wrong,
since when memccpy returns non-NULL, that return
value points at the byte just after the NUL it copied
into DEST.

This is better:
(note I've added the "restrict" attributes, too,
which I'll do in system.h as well)

    static inline char *
    stzncpy (char *restrict dest, char const *restrict src, size_t len)
    {
      char *p = memccpy (dest, src, 0, len);
      if (p)
        --p;
      else
        {
          p = dest + len;
          *p = 0;
        }
      return p;
    }



reply via email to

[Prev in Thread] Current Thread [Next in Thread]