Path: blob/main/crypto/krb5/src/util/support/strlcpy.c
34889 views
/* -*- mode: c; c-file-style: "bsd"; indent-tabs-mode: t -*- */1/*2* Copyright (c) 1998 Todd C. Miller <[email protected]>3*4* Permission to use, copy, modify, and distribute this software for any5* purpose with or without fee is hereby granted, provided that the above6* copyright notice and this permission notice appear in all copies.7*8* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES9* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF10* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR11* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES12* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN13* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF14* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.15*/1617/* Provide strlcpy and strlcat for platforms that don't have them. */1819#include "k5-platform.h"20#include <sys/types.h>21#include <string.h>2223/*24* Copy src to string dst of size siz. At most siz-1 characters25* will be copied. Always NUL terminates (unless siz == 0).26* Returns strlen(src); if retval >= siz, truncation occurred.27*/28size_t29krb5int_strlcpy(char *dst, const char *src, size_t siz)30{31char *d = dst;32const char *s = src;33size_t n = siz;3435/* Copy as many bytes as will fit */36if (n != 0) {37while (--n != 0) {38if ((*d++ = *s++) == '\0')39break;40}41}4243/* Not enough room in dst, add NUL and traverse rest of src */44if (n == 0) {45if (siz != 0)46*d = '\0'; /* NUL-terminate dst */47while (*s++)48;49}5051return(s - src - 1); /* count does not include NUL */52}5354/*55* Appends src to string dst of size siz (unlike strncat, siz is the56* full size of dst, not space left). At most siz-1 characters57* will be copied. Always NUL terminates (unless siz <= strlen(dst)).58* Returns strlen(src) + MIN(siz, strlen(initial dst)).59* If retval >= siz, truncation occurred.60*/61size_t62krb5int_strlcat(char *dst, const char *src, size_t siz)63{64char *d = dst;65const char *s = src;66size_t n = siz;67size_t dlen;6869/* Find the end of dst and adjust bytes left but don't go past end */70while (n-- != 0 && *d != '\0')71d++;72dlen = d - dst;73n = siz - dlen;7475if (n == 0)76return(dlen + strlen(s));77while (*s != '\0') {78if (n != 1) {79*d++ = *s;80n--;81}82s++;83}84*d = '\0';8586return(dlen + (s - src)); /* count does not include NUL */87}888990