/*
* 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
//! \}
//! \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
--- /dev/null
+/*
+ * 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