String stuff that should be in stdlib but isn't.
Dependents: X10Svr SSDP_Server
Diff: SW_String.cpp
- Revision:
- 2:c7a3039893cb
- Parent:
- 1:65bc379d8cd0
- Child:
- 3:bc30d348f5b4
--- a/SW_String.cpp Tue Apr 11 18:42:07 2017 +0000 +++ b/SW_String.cpp Sun Nov 18 04:04:48 2018 +0000 @@ -1,7 +1,20 @@ - #include "SW_String.h" +#define DEBUG "SWst" +#include <cstdio> +#if (defined(DEBUG) && !defined(TARGET_LPC11U24)) +#define DBG(x, ...) std::printf("[DBG %s %4d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#define WARN(x, ...) std::printf("[WRN %s %4d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[ERR %s %4d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#define INFO(x, ...) std::printf("[INF %s %4d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#else +#define DBG(x, ...) +#define WARN(x, ...) +#define ERR(x, ...) +#define INFO(x, ...) +#endif + /// A more secure version of strcat /// /// This function is like a wrapper on strcat, to first validate the concatination @@ -24,18 +37,26 @@ /// - -3 = overlap between src and dst /// int strcat_s(char * dst, size_t dstSize, const char * src) { - if (dst == NULL) + if (dst == NULL) { + ERR("strcat_s FAIL destination == NULL"); return -1; + } if (src == NULL || *src == '\0') return 0; // done, that was easy. - if (src >= dst && src <= dst + dstSize) + if (src >= dst && src <= dst + dstSize) { + ERR("strcat_s FAIL source overlaps destination"); return -3; + } int dstLen = strlen(dst); int srcLen = strlen(src); - if (src + srcLen >= dst && src + srcLen <= dst + dstSize) + if (src + srcLen >= dst && src + srcLen <= dst + dstSize) { + ERR("strcat_s FAIL source + length overlaps destination"); return -3; - if (dstLen + srcLen > dstSize) + } + if (dstLen + srcLen > dstSize) { + ERR("strcat_s FAIL dstLen + srcLen > size"); return -2; + } strcat(dst, src); return 0; } @@ -62,19 +83,27 @@ /// - -3 = overlap between src and dst /// int strcpy_s(char * dst, size_t dstSize, const char * src) { - if (dst == NULL) + if (dst == NULL) { + ERR("strcpy_s FAIL destination == NULL"); return -1; + } if (src == NULL || *src == '\0') { *dst = '\0'; return 0; // done, that was easy. } - if (src >= dst && src <= dst + dstSize) + if (src >= dst && src <= dst + dstSize) { + ERR("strcpy_s FAIL source overlaps destination"); return -3; + } int srcLen = strlen(src); - if (src + srcLen >= dst && src + srcLen <= dst + dstSize) + if (src + srcLen >= dst && src + srcLen <= dst + dstSize) { + ERR("strcpy_s FAIL source + length overlaps destination"); return -3; - if (srcLen > dstSize) + } + if (srcLen > dstSize) { + ERR("strcpy_s FAIL dstLen + srcLen > size"); return -2; + } strcpy(dst, src); return 0; }