Subject: Re: strl{cpy,cat} into libkern
To: Jonathan Stone <jonathan@DSG.Stanford.EDU>
From: Ian Piumarta <ian.piumarta@inria.fr>
List: tech-kern
Date: 05/15/2003 00:38:47
On Wed, 14 May 2003, Jonathan Stone wrote:
> 
> The code is ...  hideous.  Sure, lets do strl{cpy,cat}, but why
> not start with a clean readable, KNF-compliant implementation?

I don't know much about KNF but the following at least looks clean to me
(which I hereby place under BSD license -- including the bugs ;).

Ian


/*
 * Append the NUL-terminated string src to the end of dst.  Append at
 * most size - strlen(dst) - 1 bytes, NUL-terminating the result.
 * Answer the size of string we tried to create == strlen(src).
 */
size_t strlcpy(char *dst, const char *src, size_t size)
{
  register char *out= dst;
  register const char *in= src;

  if (0 != size)
    {
      while (*in && --size)
	*out++= *in++;
      *out= '\0';
    }

  while (*in)
    ++in;

  return in - src;
}

/*
 * Append the NUL-terminated string src to the end of dst.  Append at
 * most size - strlen(dst) - 1 bytes, NUL-terminating the result.
 * Answer the size of the string we tried to create: strlen(dst) +
 * strlen(src), where strlen(dst) == size if dst was not initially
 * NUL-terminated.
 */
size_t strlcat(char *dst, const char *src, size_t size)
{
  register char *out= dst;

  while (size && *out)
    ++out, --size;

  return out - dst + strlcpy(out, src, size);
}