]> git.ipfire.org Git - thirdparty/squid.git/blobdiff - compat/xstring.cc
SourceFormat Enforcement
[thirdparty/squid.git] / compat / xstring.cc
index 1e8376cace7ab35f68044c95188548329803cc8f..bba036b1d9bfac290618490dd579754ca6b90c0c 100644 (file)
@@ -1,18 +1,21 @@
-#include "config.h"
+/*
+ * Copyright (C) 1996-2017 The Squid Software Foundation and contributors
+ *
+ * Squid software is distributed under GPLv2+ license and includes
+ * contributions from numerous individuals and organizations.
+ * Please see the COPYING and CONTRIBUTORS files for details.
+ */
+
+#include "squid.h"
 #include "compat/xalloc.h"
 #include "compat/xstring.h"
 
-#if HAVE_ERRNO_H
-#include <errno.h>
-#endif
+#include <cerrno>
 
 char *
 xstrdup(const char *s)
 {
-    size_t sz;
-    char *p;
-
-    if (s == NULL) {
+    if (!s) {
         if (failure_notify) {
             (*failure_notify) ("xstrdup: tried to dup a NULL pointer!\n");
         } else {
@@ -23,8 +26,8 @@ xstrdup(const char *s)
     }
 
     /* copy string, including terminating character */
-    sz = strlen(s) + 1;
-    p = (char *)xmalloc(sz);
+    size_t sz = strlen(s) + 1;
+    char *p = static_cast<char *>(xmalloc(sz));
     memcpy(p, s, sz);
 
     return p;
@@ -39,8 +42,11 @@ xstrncpy(char *dst, const char *src, size_t n)
         return dst;
 
     if (src)
-        while (--n != 0 && *src != '\0')
-            *dst++ = *src++;
+        while (--n != 0 && *src != '\0') {
+            *dst = *src;
+            ++dst;
+            ++src;
+        }
 
     *dst = '\0';
     return r;
@@ -49,10 +55,7 @@ xstrncpy(char *dst, const char *src, size_t n)
 char *
 xstrndup(const char *s, size_t n)
 {
-    size_t sz;
-    char *p;
-
-    if (s == NULL) {
+    if (!s) {
         errno = EINVAL;
         if (failure_notify) {
             (*failure_notify) ("xstrndup: tried to dup a NULL pointer!\n");
@@ -61,20 +64,13 @@ xstrndup(const char *s, size_t n)
         }
         exit(1);
     }
-    if (n < 0) {
-        errno = EINVAL;
-        if (failure_notify) {
-            (*failure_notify) ("xstrndup: tried to dup a negative length string!\n");
-        } else {
-            perror("xstrndup: tried to dup a negative length string!");
-        }
-        exit(1);
-    }
 
-    sz = strlen(s) + 1;
+    size_t sz = strlen(s) + 1;
+    // size_t is unsigned, as mandated by c99 and c++ standards.
     if (sz > n)
         sz = n;
 
-    p = xstrncpy((char *)xmalloc(sz), s, sz);
+    char *p = xstrncpy(static_cast<char *>(xmalloc(sz)), s, sz);
     return p;
 }
+