summaryrefslogtreecommitdiff
path: root/lib/str.c
diff options
context:
space:
mode:
authorQuentin Young <qlyoung@cumulusnetworks.com>2016-09-21 22:11:53 +0000
committerQuentin Young <qlyoung@cumulusnetworks.com>2016-09-21 22:11:53 +0000
commit844ec28cee41395cdd1cc0cdf8cf0168f9dc1adf (patch)
treef2fe0a9a71bb075a5f6f43cd992b89f46b95574f /lib/str.c
parentd0bfb22c223d645e554290ca82581eb06f94ac3b (diff)
parent039dc61292de5f3ed5f46316b1940ab6bb184c3f (diff)
Merge branch 'cmaster-next' into vtysh-grammar
Signed-off-by: Quentin Young <qlyoung@cumulusnetworks.com> Conflicts: lib/.gitignore lib/command.c lib/command.h
Diffstat (limited to 'lib/str.c')
-rw-r--r--lib/str.c42
1 files changed, 25 insertions, 17 deletions
diff --git a/lib/str.c b/lib/str.c
index d8f039a094..16f759c074 100644
--- a/lib/str.c
+++ b/lib/str.c
@@ -54,26 +54,34 @@ snprintf(char *str, size_t size, const char *format, ...)
#endif
#ifndef HAVE_STRLCPY
-/**
- * Like strncpy but does not 0 fill the buffer and always null
- * terminates.
- *
- * @param bufsize is the size of the destination buffer.
- *
- * @return index of the terminating byte.
- **/
+/*
+ * Copy string src to buffer dst of size dsize. At most dsize-1
+ * chars will be copied. Always NUL terminates (unless dsize == 0).
+ * Returns strlen(src); if retval >= dsize, truncation occurred.
+ */
size_t
-strlcpy(char *d, const char *s, size_t bufsize)
+strlcpy(char *dst, const char *src, size_t dsize)
{
- size_t len = strlen(s);
- size_t ret = len;
- if (bufsize > 0) {
- if (len >= bufsize)
- len = bufsize-1;
- memcpy(d, s, len);
- d[len] = 0;
+ const char *osrc = src;
+ size_t nleft = dsize;
+
+ /* Copy as many bytes as will fit. */
+ if (nleft != 0) {
+ while (--nleft != 0) {
+ if ((*dst++ = *src++) == '\0')
+ break;
+ }
}
- return ret;
+
+ /* Not enough room in dst, add NUL and traverse rest of src. */
+ if (nleft == 0) {
+ if (dsize != 0)
+ *dst = '\0'; /* NUL-terminate dst */
+ while (*src++)
+ ;
+ }
+
+ return(src - osrc - 1); /* count does not include NUL */
}
#endif