String to array conversion functions
authorChristian Blau <cblau.mail@gmail.com>
Fri, 4 Sep 2020 11:59:43 +0000 (11:59 +0000)
committerMagnus Lundborg <magnus.lundborg@scilifelab.se>
Fri, 4 Sep 2020 11:59:43 +0000 (11:59 +0000)
Introduce and test a function that allows to convert a string into
a fixed-size array of arbitrary ElementType.

src/gromacs/utility/strconvert.h
src/gromacs/utility/tests/CMakeLists.txt
src/gromacs/utility/tests/strconvert.cpp [new file with mode: 0644]

index f9eaa30accd0fdadbd52b5c62f16c7c46bc91d67..c48e25748eb9d5265ba64d8556545a2e5394b039 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * This file is part of the GROMACS molecular simulation package.
  *
- * Copyright (c) 2016,2017,2018,2019, by the GROMACS development team, led by
+ * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by
  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
  * and including many others, as listed in the AUTHORS file in the
  * top-level source directory and at http://www.gromacs.org.
 #ifndef GMX_UTILITY_STRCONVERT_H
 #define GMX_UTILITY_STRCONVERT_H
 
+#include <algorithm>
+#include <optional>
 #include <string>
 
 #include "gromacs/utility/basedefinitions.h"
+#include "gromacs/utility/exceptions.h"
 #include "gromacs/utility/stringutil.h"
 
 namespace gmx
@@ -218,6 +221,100 @@ static inline std::string toString(std::string t)
 //! \}
 //! \endcond
 
+/*! \brief Convert a string into an array of values.
+ *
+ * \tparam ValueType array element type to convert into
+ * \tparam NumExpectedValues number of values of the array
+ *
+ * \returns an array containing the converted string, optionally null if
+ *          the white-space stripped string is empty
+ *
+ * \throws InvalidInputError if splitting the string at whitespaces does not
+ *                           result in NumExpectedValues or zero substrings
+ *
+ * \throws InvalidInputError if conversion of any of the NumExpectedValues
+ *                           substrings of the splitted input string fails
+ *
+ * Converts a string into an array of type ValueType with exactly NumExpectedValues.
+ *
+ * No result is returned if the string is empty or contains only whitespace .
+ *
+ */
+template<typename ValueType, int NumExpectedValues>
+static inline std::optional<std::array<ValueType, NumExpectedValues>>
+parsedArrayFromInputString(const std::string& str)
+{
+    // return nullopt right away if the string is just whitespace or empty
+    {
+        const std::string& strippedString = stripString(str);
+        if (strippedString.empty())
+        {
+            return std::nullopt;
+        }
+    }
+
+    const std::vector<std::string>& valuesAsStrings = splitString(str);
+
+    // throw right away if we don't have the expected number of string entries
+    if (valuesAsStrings.size() != NumExpectedValues)
+    {
+        const std::string errorMessage =
+                "Expected empty string or string with " + intToString(NumExpectedValues)
+                + " elements to convert, but received " + intToString(valuesAsStrings.size())
+                + " elements instead.";
+        GMX_THROW(InvalidInputError(errorMessage));
+    }
+
+    // will throw if any conversion from string to value fails
+    std::array<ValueType, NumExpectedValues> valuesAsArray;
+    std::transform(std::begin(valuesAsStrings), std::end(valuesAsStrings), std::begin(valuesAsArray),
+                   [](const std::string& split) { return fromString<ValueType>(split); });
+
+    return { valuesAsArray };
+}
+
+/*! \brief Returns the input string, throwing an excpetion if the demanded
+ *         conversion to an array will not succeed.
+ *
+ * \tparam ValueType array element type to convert into
+ * \tparam NumExpectedValues number of values of the array
+ *
+ * \param[in] toConvert the string to convert
+ * \param[in] errorContextMessage the message to add to the thrown exceptions if
+ *                                conversion of the string is bound to fail at
+ *                                some point
+ * \returns the input string
+ *
+ * \throws InvalidInputError if splitting the string at whitespaces does not
+ *                           result in NumExpectedValues or zero substrings
+ *
+ * \throws InvalidInputError if conversion of any of the NumExpectedValues
+ *                           substrings of the splitted input string fails
+ *
+ * A typical use of this function would be in .mdp string option parsing
+ * where information in the .mdp file is transformed into the data that is
+ * stored in the .tpr file.
+ */
+template<typename ValueType, int NumExpectedValues>
+static inline std::string stringIdentityTransformWithArrayCheck(const std::string& toConvert,
+                                                                const std::string& errorContextMessage)
+{
+    // Attempt the conversion to an array so that the string parsing routine
+    // will throw an InvalidInputError if the string is not fit for conversion.
+    try
+    {
+        // The converted array is discarded.
+        gmx_unused const auto& val = parsedArrayFromInputString<ValueType, NumExpectedValues>(toConvert);
+    }
+    catch (const InvalidInputError& e)
+    {
+        InvalidInputError toThrow(errorContextMessage + std::string(e.what()));
+        GMX_THROW(toThrow);
+    }
+
+    return toConvert;
+}
+
 } // namespace gmx
 
 #endif
index e510f16075673129b876a8ddd940b22fa2b004f5..e3f60426fbf36c19b9cd503c52e36aa83758ff32 100644 (file)
@@ -52,6 +52,7 @@ gmx_add_unit_test(UtilityUnitTests utility-test
         path.cpp
         physicalnodecommunicator.cpp
         range.cpp
+        strconvert.cpp
         stringutil.cpp
         textreader.cpp
         textwriter.cpp
diff --git a/src/gromacs/utility/tests/strconvert.cpp b/src/gromacs/utility/tests/strconvert.cpp
new file mode 100644 (file)
index 0000000..cbf8f6f
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * This file is part of the GROMACS molecular simulation package.
+ *
+ * Copyright (c) 2020, by the GROMACS development team, led by
+ * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
+ * and including many others, as listed in the AUTHORS file in the
+ * top-level source directory and at http://www.gromacs.org.
+ *
+ * GROMACS is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 2.1
+ * of the License, or (at your option) any later version.
+ *
+ * GROMACS is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with GROMACS; if not, see
+ * http://www.gnu.org/licenses, or write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
+ *
+ * If you want to redistribute modifications to GROMACS, please
+ * consider that scientific software is very special. Version
+ * control is crucial - bugs must be traceable. We will be happy to
+ * consider code for inclusion in the official distribution, but
+ * derived work must not be called official GROMACS. Details are found
+ * in the README & COPYING files - if they are missing, get the
+ * official version at http://www.gromacs.org.
+ *
+ * To help us fund GROMACS development, we humbly ask that you cite
+ * the research papers on the package. Check out http://www.gromacs.org.
+ */
+/*! \internal \file
+ *
+ * \brief Tests routines in strconvert.h.
+ *
+ * \author Christian Blau <blau@kth.se>
+ *
+ * \ingroup module_utility
+ */
+
+#include "gmxpre.h"
+
+#include "gromacs/utility/strconvert.h"
+
+#include <gtest/gtest.h>
+
+namespace gmx
+{
+namespace test
+{
+namespace
+{
+
+TEST(StringConvert, NoResultFromEptyString)
+{
+    const std::optional<std::array<float, 3>> parsedArray =
+            parsedArrayFromInputString<float, 3>("");
+    EXPECT_FALSE(parsedArray);
+}
+
+TEST(StringConvert, ThreeFloatsSuccessfully)
+{
+    const std::optional<std::array<float, 3>> parsedArray =
+            parsedArrayFromInputString<float, 3>("1.2 .5 -6e5");
+    EXPECT_FLOAT_EQ((*parsedArray)[0], 1.2);
+    EXPECT_FLOAT_EQ((*parsedArray)[1], .5);
+    EXPECT_FLOAT_EQ((*parsedArray)[2], -6e5);
+}
+
+TEST(StringConvert, OneIntSucessfully)
+{
+    const std::optional<std::array<int, 1>> parsedArray =
+            parsedArrayFromInputString<int, 1>(" 1 \t  ");
+    EXPECT_FLOAT_EQ((*parsedArray)[0], 1);
+}
+
+TEST(StringConvert, FloatAsStringToIntArrayThrows)
+{
+    const auto& toTest = []() { return parsedArrayFromInputString<int, 1>(" 1.2 "); };
+    EXPECT_THROW(toTest(), InvalidInputError);
+}
+
+TEST(StringConvert, ThrowsWhenWrongSize)
+{
+    // use the lambda due to aviod Macro substitution error with template function
+    const auto& toTest = []() { return parsedArrayFromInputString<float, 2>("1.2\t\n  .5 -6e5"); };
+    EXPECT_THROW(toTest(), InvalidInputError);
+}
+
+TEST(StringConvert, StringIdentityTransformWithArrayThrows)
+{
+    // use the lambda due to aviod Macro substitution error with template function
+    const auto& toTest = []() {
+        return stringIdentityTransformWithArrayCheck<float, 3>(
+                "-10 5 4 1", "Here, I explain where the error occured: ");
+    };
+    EXPECT_THROW(toTest(), InvalidInputError);
+}
+
+TEST(StringConvert, StringIdentityTransformWithArrayOkay)
+{
+    // use the lambda due to aviod Macro substitution error with template function
+    const std::string input("1.2\t\n  .5 -6e5");
+    const std::string output = stringIdentityTransformWithArrayCheck<float, 3>(
+            input, "Here, I explain where the error occured: ");
+    EXPECT_EQ(input, output);
+}
+
+
+} // namespace
+} // namespace test
+} // namespace gmx