From 601c64ec4f2b8a41fba59d31a987090feeb69e84 Mon Sep 17 00:00:00 2001 From: Garrett D'Amore Date: Fri, 25 Aug 2017 11:11:35 -0700 Subject: Introduce utility safe string handling functions. We have our versions of strdup, strlcat, and strlcpy. This means we can avoid using snprintf() in many cases (saving cycles), and we can get safer checks. We use the platform supplied versions of these if they exist (wrapping with nni_xxx versions.) --- src/core/strs.c | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/core/strs.c (limited to 'src/core/strs.c') diff --git a/src/core/strs.c b/src/core/strs.c new file mode 100644 index 00000000..7f236236 --- /dev/null +++ b/src/core/strs.c @@ -0,0 +1,98 @@ +// +// Copyright 2017 Garrett D'Amore +// Copyright 2017 Capitar IT Group BV +// +// This software is supplied under the terms of the MIT License, a +// copy of which should be located in the distribution where this +// file was obtained (LICENSE.txt). A copy of the license may also be +// found online at https://opensource.org/licenses/MIT. +// + +#include +#include + +#include "core/nng_impl.h" + +// This file contains implementation of utility functions that are not +// part of standard C99. (C11 has added some things here, but we cannot +// count on them.) + +char * +nni_strdup(const char *src) +{ +#ifdef NNG_HAVE_STRDUP + return (strdup(src)); +#else + char * dst; + size_t len = strlen(src); + + if ((dst = nni_alloc(len)) != NULL) { + memcpy(dst, src, len); + } + return (dst); +#endif +} + +void +nni_strfree(char *s) +{ + if (s != NULL) { +#ifdef NNG_HAVE_STRDUP + free(s); +#else + nni_free(s, strlen(s) + 1); +#endif + } +} + +size_t +nni_strlcpy(char *dst, const char *src, size_t len) +{ +#ifdef NNG_HAVE_STRLCPY + return (strlcpy(dst, src, len)); +#else + size_t n; + char c; + + n = 0; + do { + c = *src++; + n++; + if (n < len) { + *dst++ = c; + } else if (n == len) { + *dst = '\0'; + } + } while (c); + return (n - 1); +#endif +} + +size_t +nni_strlcat(char *dst, const char *src, size_t len) +{ +#ifdef NNG_HAVE_STRLCAT + return (strlcat(dst, src, len)); +#else + size_t n; + char c; + + n = 0; + while ((*dst != '\0') && (n < len)) { + n++; + dst++; + } + + do { + c = *src++; + n++; + if (n < len) { + *dst++ = c; + } else if (n == len) { + *dst = '\0'; + } + } while (c); + + return (n - 1); +#endif +} -- cgit v1.2.3-70-g09d2