From 083f5e73e2b6817ae423cf04d153e4c4bc1b1786 Mon Sep 17 00:00:00 2001 From: bkaradzic Date: Sun, 9 Jun 2013 15:24:18 -0700 Subject: [PATCH] Added strlcpy and strlcat. --- include/bx/string.h | 93 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/include/bx/string.h b/include/bx/string.h index 2d044cb..fcafc95 100644 --- a/include/bx/string.h +++ b/include/bx/string.h @@ -239,6 +239,99 @@ namespace bx va_end(argList); } + /* + * Copyright (c) 1998 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + + /// Copy src to string dst of size siz. At most siz-1 characters + /// will be copied. Always NUL terminates (unless siz == 0). + /// Returns strlen(src); if retval >= siz, truncation occurred. + inline size_t strlcpy(char* _dst, const char* _src, size_t _siz) + { + char* dd = _dst; + const char* ss = _src; + size_t nn = _siz; + + /* Copy as many bytes as will fit */ + if (nn != 0) + { + while (--nn != 0) + { + if ( (*dd++ = *ss++) == '\0') + { + break; + } + } + } + + /* Not enough room in dst, add NUL and traverse rest of src */ + if (nn == 0) + { + if (_siz != 0) + { + *dd = '\0'; /* NUL-terminate dst */ + } + + while (*ss++) + { + } + } + + return(ss - _src - 1); /* count does not include NUL */ + } + + /// Appends src to string dst of size siz (unlike strncat, siz is the + /// full size of dst, not space left). At most siz-1 characters + /// will be copied. Always NUL terminates (unless siz <= strlen(dst)). + /// Returns strlen(src) + MIN(siz, strlen(initial dst)). + /// If retval >= siz, truncation occurred. + inline size_t strlcat(char* _dst, const char* _src, size_t _siz) + { + char* dd = _dst; + const char *s = _src; + size_t nn = _siz; + size_t dlen; + + /* Find the end of dst and adjust bytes left but don't go past end */ + while (nn-- != 0 && *dd != '\0') + { + dd++; + } + + dlen = dd - _dst; + nn = _siz - dlen; + + if (nn == 0) + { + return(dlen + strlen(s)); + } + + while (*s != '\0') + { + if (nn != 1) + { + *dd++ = *s; + nn--; + } + s++; + } + *dd = '\0'; + + return(dlen + (s - _src)); /* count does not include NUL */ + } + } // namespace bx #endif // __BX_PRINTF_H__