Header And Logo

PostgreSQL
| The world's most advanced open source database.

strlcpy.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * strlcpy.c
00004  *    strncpy done right
00005  *
00006  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00007  *
00008  *
00009  * IDENTIFICATION
00010  *    src/port/strlcpy.c
00011  *
00012  * This file was taken from OpenBSD and is used on platforms that don't
00013  * provide strlcpy().  The OpenBSD copyright terms follow.
00014  *-------------------------------------------------------------------------
00015  */
00016 
00017 /*  $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $    */
00018 
00019 /*
00020  * Copyright (c) 1998 Todd C. Miller <[email protected]>
00021  *
00022  * Permission to use, copy, modify, and distribute this software for any
00023  * purpose with or without fee is hereby granted, provided that the above
00024  * copyright notice and this permission notice appear in all copies.
00025  *
00026  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
00027  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
00028  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
00029  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
00030  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
00031  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
00032  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
00033  */
00034 
00035 #include "c.h"
00036 
00037 
00038 /*
00039  * Copy src to string dst of size siz.  At most siz-1 characters
00040  * will be copied.  Always NUL terminates (unless siz == 0).
00041  * Returns strlen(src); if retval >= siz, truncation occurred.
00042  * Function creation history:  http://www.gratisoft.us/todd/papers/strlcpy.html
00043  */
00044 size_t
00045 strlcpy(char *dst, const char *src, size_t siz)
00046 {
00047     char       *d = dst;
00048     const char *s = src;
00049     size_t      n = siz;
00050 
00051     /* Copy as many bytes as will fit */
00052     if (n != 0)
00053     {
00054         while (--n != 0)
00055         {
00056             if ((*d++ = *s++) == '\0')
00057                 break;
00058         }
00059     }
00060 
00061     /* Not enough room in dst, add NUL and traverse rest of src */
00062     if (n == 0)
00063     {
00064         if (siz != 0)
00065             *d = '\0';          /* NUL-terminate dst */
00066         while (*s++)
00067             ;
00068     }
00069 
00070     return (s - src - 1);       /* count does not include NUL */
00071 }