Back to home page

Bitcoin sources

 
 

    


0001 /*
0002  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
0003  *
0004  * Permission to use, copy, modify, and distribute this software for any
0005  * purpose with or without fee is hereby granted, provided that the above
0006  * copyright notice and this permission notice appear in all copies.
0007  *
0008  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
0009  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
0010  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
0011  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
0012  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
0013  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
0014  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
0015  */
0016 #ifndef BITCOIN_STRLCPY_H
0017 #define BITCOIN_STRLCPY_H
0018 /*
0019  * Copy src to string dst of size siz.  At most siz-1 characters
0020  * will be copied.  Always NUL terminates (unless siz == 0).
0021  * Returns strlen(src); if retval >= siz, truncation occurred.
0022  */
0023 inline size_t strlcpy(char *dst, const char *src, size_t siz)
0024 {
0025     char *d = dst;
0026     const char *s = src;
0027     size_t n = siz;
0028 
0029     /* Copy as many bytes as will fit */
0030     if (n != 0)
0031     {
0032         while (--n != 0)
0033         {
0034             if ((*d++ = *s++) == '\0')
0035                 break;
0036         }
0037     }
0038 
0039     /* Not enough room in dst, add NUL and traverse rest of src */
0040     if (n == 0)
0041     {
0042         if (siz != 0)
0043             *d = '\0';  /* NUL-terminate dst */
0044         while (*s++)
0045             ;
0046     }
0047 
0048     return(s - src - 1); /* count does not include NUL */
0049 }
0050 
0051 /*
0052  * Appends src to string dst of size siz (unlike strncat, siz is the
0053  * full size of dst, not space left).  At most siz-1 characters
0054  * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
0055  * Returns strlen(src) + MIN(siz, strlen(initial dst)).
0056  * If retval >= siz, truncation occurred.
0057  */
0058 inline size_t strlcat(char *dst, const char *src, size_t siz)
0059 {
0060     char *d = dst;
0061     const char *s = src;
0062     size_t n = siz;
0063     size_t dlen;
0064 
0065     /* Find the end of dst and adjust bytes left but don't go past end */
0066     while (n-- != 0 && *d != '\0')
0067         d++;
0068     dlen = d - dst;
0069     n = siz - dlen;
0070 
0071     if (n == 0)
0072         return(dlen + strlen(s));
0073     while (*s != '\0')
0074     {
0075         if (n != 1)
0076         {
0077             *d++ = *s;
0078             n--;
0079         }
0080         s++;
0081     }
0082     *d = '\0';
0083 
0084     return(dlen + (s - src)); /* count does not include NUL */
0085 }
0086 #endif