add utils::strdup() convenience function

This commit is contained in:
Axel Kohlmeyer 2021-02-04 15:35:43 -05:00
parent f5bf10e00f
commit 0f07215a2b
No known key found for this signature in database
GPG Key ID: D9B44E93BF0C375A
4 changed files with 41 additions and 0 deletions

View File

@ -71,6 +71,9 @@ and parsing files or arguments.
----------
.. doxygenfunction:: strdup
:project: progguide
.. doxygenfunction:: trim
:project: progguide

View File

@ -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
------------------------------------------------------------------------- */

View File

@ -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

View File

@ -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");