Commit 65ac160e authored by Steven Murray's avatar Steven Murray
Browse files

Copied copyString() to cta::utils

parent 1a3812e0
......@@ -631,4 +631,21 @@ TEST_F(cta_UtilsTest, testTrimStringContainingLeftAndRightWhiteSpace) {
ASSERT_EQ(std::string("VALUE"), trimmedString);
}
TEST_F(cta_UtilsTest, testCopyStringNullDst) {
using namespace cta;
char dummy[6] = "Dummy";
ASSERT_THROW(utils::copyString(NULL, 0, dummy),
cta::exception::Exception);
}
TEST_F(cta_UtilsTest, testCopyString) {
using namespace cta;
char src[12] = "Hello World";
char dst[12];
utils::copyString(dst, src);
ASSERT_EQ(0, strcmp(dst, src));
}
} // namespace unitTests
......@@ -27,6 +27,7 @@
#include <sstream>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <uuid/uuid.h>
......@@ -677,5 +678,32 @@ std::string hexDump(const void * mem, unsigned int n ){
return out.str();
}
//-----------------------------------------------------------------------------
// copyString
//-----------------------------------------------------------------------------
void copyString(char *const dst, const size_t dstSize, const std::string &src) {
if(dst == NULL) {
cta::exception::Exception ex;
ex.getMessage() << __FUNCTION__
<< ": Pointer to destination string is NULL";
throw ex;
}
if(src.length() >= dstSize) {
cta::exception::Exception ex;
ex.getMessage() << __FUNCTION__
<< ": Source string is longer than destination. Source length: "
<< src.length() << " Max destination length: " << (dstSize - 1);
throw ex;
}
strncpy(dst, src.c_str(), dstSize);
*(dst + dstSize -1) = '\0'; // Ensure destination string is null terminated
}
} // namespace utils
} // namespace cta
......@@ -279,6 +279,30 @@ namespace utils {
*/
std::string hexDump(const void *mem, unsigned int n);
/**
* Safely copies source string into destination string. The destination
* will always be null terminated if this function is successful.
*
* @param dst Destination string.
* @param dstSize The size of the destination string including the terminating
* null character.
* @param src Source string.
* destination.
*/
void copyString(char *const dst, const size_t dstSize, const std::string &src);
/**
* Safely copies source string into destination string. The destination
* will always be null terminated if this function is successful.
*
* @param dst Destination string.
* @param src Source string.
*/
template<size_t dstSize> void copyString(char (&dst)[dstSize],
const std::string &src) {
copyString(dst, dstSize, src);
}
} // namespace utils
} // namespace cta
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment