String stuff that should be in stdlib but isn't.
Dependents: X10Svr SSDP_Server
Diff: SW_String.cpp
- Revision:
- 1:65bc379d8cd0
- Parent:
- 0:6d899ce93ea0
- Child:
- 2:c7a3039893cb
--- a/SW_String.cpp Mon Apr 11 02:25:34 2016 +0000 +++ b/SW_String.cpp Tue Apr 11 18:42:07 2017 +0000 @@ -2,6 +2,84 @@ #include "SW_String.h" +/// A more secure version of strcat +/// +/// This function is like a wrapper on strcat, to first validate the concatination +/// and then if all parameters appear good, it will call strcat. It will not +/// permit overlapping source and destination. +/// +/// If there is an error, no concatination is performed. +/// +/// @note This has a different return value than the normal strcat. +/// +/// @param[out] dst is a pointer to the start of the destination buffer (not necessarily +/// where the next string will appear). +/// @param[in] dstSize defines the size of the destination buffer. +/// @param[in] src is a pointer to the source. +/// +/// @returns +/// - 0 = no error +/// - -1 = destination pointer invalid +/// - -2 = source is too big to append into the destination +/// - -3 = overlap between src and dst +/// +int strcat_s(char * dst, size_t dstSize, const char * src) { + if (dst == NULL) + return -1; + if (src == NULL || *src == '\0') + return 0; // done, that was easy. + if (src >= dst && src <= dst + dstSize) + return -3; + int dstLen = strlen(dst); + int srcLen = strlen(src); + if (src + srcLen >= dst && src + srcLen <= dst + dstSize) + return -3; + if (dstLen + srcLen > dstSize) + return -2; + strcat(dst, src); + return 0; +} + + +/// A more secure version of strcpy +/// +/// This function is like a wrapper on strcpy, to first validate the concatination +/// and then if all parameters appear good, it will call strcpy. It will not +/// permit overlapping source and destination. +/// +/// If there is an error, no copy is performed. +/// +/// @note This has a different return value than the normal strcpy. +/// +/// @param[out] dst is a pointer to the start of the destination buffer. +/// @param[in] dstSize defines the size of the destination buffer. +/// @param[in] src is a pointer to the source. +/// +/// @returns +/// - 0 = no error +/// - -1 = destination pointer invalid +/// - -2 = source is too big to append into the destination +/// - -3 = overlap between src and dst +/// +int strcpy_s(char * dst, size_t dstSize, const char * src) { + if (dst == NULL) + return -1; + if (src == NULL || *src == '\0') { + *dst = '\0'; + return 0; // done, that was easy. + } + if (src >= dst && src <= dst + dstSize) + return -3; + int srcLen = strlen(src); + if (src + srcLen >= dst && src + srcLen <= dst + dstSize) + return -3; + if (srcLen > dstSize) + return -2; + strcpy(dst, src); + return 0; +} + + /// sw_tolower exists because not all compiler libraries have this function /// /// This takes a character and if it is upper-case, it converts it to