diff --git a/doc/src/Developer_utils.rst b/doc/src/Developer_utils.rst index f6e7d64c3e..2945420b5a 100644 --- a/doc/src/Developer_utils.rst +++ b/doc/src/Developer_utils.rst @@ -71,6 +71,9 @@ and parsing files or arguments. ---------- +.. doxygenfunction:: strdup + :project: progguide + .. doxygenfunction:: trim :project: progguide diff --git a/src/utils.cpp b/src/utils.cpp index 44dcc16f0c..ee2533e725 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -546,6 +546,18 @@ int utils::expand_args(const char *file, int line, int narg, char **arg, return newarg; } +/* ---------------------------------------------------------------------- + Make copy of string in new storage. Works like the (non-portable) + C-style strdup() but also accepts a C++ string as argument. +------------------------------------------------------------------------- */ + +char *utils::strdup(const std::string &text) +{ + char *tmp = new char[text.size()+1]; + strcpy(tmp,text.c_str()); + return tmp; +} + /* ---------------------------------------------------------------------- Return string without leading or trailing whitespace ------------------------------------------------------------------------- */ diff --git a/src/utils.h b/src/utils.h index a403217cfe..eece00f306 100644 --- a/src/utils.h +++ b/src/utils.h @@ -195,6 +195,17 @@ namespace LAMMPS_NS { int expand_args(const char *file, int line, int narg, char **arg, int mode, char **&earg, LAMMPS *lmp); + /** Make C-style copy of string in new storage + * + * This allocates a storage buffer and copies the C-style or + * C++ style string into it. The buffer is allocated with "new" + * and thus needs to be deallocated with "delete[]". + * + * \param text string that should be copied + * \return new buffer with copy of string */ + + char *strdup(const std::string &text); + /** Trim leading and trailing whitespace. Like TRIM() in Fortran. * * \param line string that should be trimmed diff --git a/unittest/utils/test_utils.cpp b/unittest/utils/test_utils.cpp index 80042be9b0..73a9449f6e 100644 --- a/unittest/utils/test_utils.cpp +++ b/unittest/utils/test_utils.cpp @@ -30,6 +30,21 @@ using ::testing::StrEq; #define FLERR __FILE__, __LINE__ #endif +TEST(Utils, strdup) +{ + std::string original("some_text"); + const char *copy = utils::strdup(original); + ASSERT_THAT(original, StrEq(copy)); + ASSERT_NE(copy,original.c_str()); + + const char *copy2 = utils::strdup(copy); + ASSERT_THAT(original, StrEq(copy2)); + ASSERT_NE(copy,copy2); + + delete[] copy; + delete[] copy2; +} + TEST(Utils, trim) { auto trimmed = utils::trim("\t some text");