|
| 1 | +/*------------------------------------------------------------------------- |
| 2 | + * |
| 3 | + * strlcpy.c |
| 4 | + * strncpy done right |
| 5 | + * |
| 6 | + * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group |
| 7 | + * |
| 8 | + * |
| 9 | + * IDENTIFICATION |
| 10 | + * $PostgreSQL: pgsql/src/port/strlcpy.c,v 1.1 2006/09/27 16:29:46 tgl Exp $ |
| 11 | + * |
| 12 | + * This file was taken from OpenBSD and is used on platforms that don't |
| 13 | + * provide strlcpy(). The OpenBSD copyright terms follow. |
| 14 | + *------------------------------------------------------------------------- |
| 15 | + */ |
| 16 | + |
| 17 | +/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */ |
| 18 | + |
| 19 | +/* |
| 20 | + * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> |
| 21 | + * |
| 22 | + * Permission to use, copy, modify, and distribute this software for any |
| 23 | + * purpose with or without fee is hereby granted, provided that the above |
| 24 | + * copyright notice and this permission notice appear in all copies. |
| 25 | + * |
| 26 | + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 27 | + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 28 | + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 29 | + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 30 | + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 31 | + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 32 | + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 33 | + */ |
| 34 | + |
| 35 | +#include "c.h" |
| 36 | + |
| 37 | + |
| 38 | +/* |
| 39 | + * Copy src to string dst of size siz. At most siz-1 characters |
| 40 | + * will be copied. Always NUL terminates (unless siz == 0). |
| 41 | + * Returns strlen(src); if retval >= siz, truncation occurred. |
| 42 | + */ |
| 43 | +size_t |
| 44 | +strlcpy(char *dst, const char *src, size_t siz) |
| 45 | +{ |
| 46 | + char *d = dst; |
| 47 | + const char *s = src; |
| 48 | + size_t n = siz; |
| 49 | + |
| 50 | + /* Copy as many bytes as will fit */ |
| 51 | + if (n != 0) { |
| 52 | + while (--n != 0) { |
| 53 | + if ((*d++ = *s++) == '\0') |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /* Not enough room in dst, add NUL and traverse rest of src */ |
| 59 | + if (n == 0) { |
| 60 | + if (siz != 0) |
| 61 | + *d = '\0'; /* NUL-terminate dst */ |
| 62 | + while (*s++) |
| 63 | + ; |
| 64 | + } |
| 65 | + |
| 66 | + return(s - src - 1); /* count does not include NUL */ |
| 67 | +} |
0 commit comments