diff --git a/slsDetectorSoftware/src/CallerSpecial.cpp b/slsDetectorSoftware/src/CallerSpecial.cpp index dc2ae8c6c..60e0df45c 100644 --- a/slsDetectorSoftware/src/CallerSpecial.cpp +++ b/slsDetectorSoftware/src/CallerSpecial.cpp @@ -1226,11 +1226,7 @@ std::string Caller::rx_dbitlist(int action) { } // 'none' option already covered as t is empty by default else if (args[0] != "none") { - unsigned int ntrim = args.size(); - t.resize(ntrim); - for (unsigned int i = 0; i < ntrim; ++i) { - t[i] = StringTo(args[i]); - } + t = StringTo>(ToString(args)); } det->setRxDbitList(t, std::vector{det_id}); os << ToString(args) << '\n'; diff --git a/slsSupportLib/include/sls/ToString.h b/slsSupportLib/include/sls/ToString.h index 7035f9c38..28347f1eb 100644 --- a/slsSupportLib/include/sls/ToString.h +++ b/slsSupportLib/include/sls/ToString.h @@ -1,7 +1,6 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #pragma once - /** * \file ToString.h * @@ -353,7 +352,9 @@ T StringTo(const std::string &f, const std::string &unit) { } } -template T StringTo(const std::string &t) { +template ::value, int> = 0> +T StringTo(const std::string &t) { std::string tmp{t}; auto unit = RemoveUnit(tmp); return StringTo(tmp, unit); @@ -398,6 +399,7 @@ ToString(const T &obj) { return obj.str(); } +/** Convert vector of strings to vector of type T */ template std::vector StringTo(const std::vector &strings) { std::vector result; @@ -407,4 +409,36 @@ std::vector StringTo(const std::vector &strings) { return result; } +/** Parse comma-separated string into vector type T (e.g., + * StringTo>()) */ +template ::value && + !std::is_same_v, + int> = 0> +T StringTo(const std::string &s) { + using ElementType = typename T::value_type; + T res; + std::istringstream ss(s); + std::string item; + while (std::getline(ss, item, ',')) { + item.erase(std::remove_if(item.begin(), item.end(), + [](char c) { + return c == '[' || c == ']' || c == '"' || + c == ' '; + }), + item.end()); + + try { + if (item.empty()) + continue; + auto val = StringTo(item); + res.push_back(val); + } catch (const std::exception &e) { + throw RuntimeError("Could not convert '" + item + + "' to the container element type. " + + std::string(e.what())); + } + } + return res; +} + } // namespace sls diff --git a/slsSupportLib/tests/test-ToString.cpp b/slsSupportLib/tests/test-ToString.cpp index 0c35bdfc0..0d7ebaf3d 100644 --- a/slsSupportLib/tests/test-ToString.cpp +++ b/slsSupportLib/tests/test-ToString.cpp @@ -415,4 +415,13 @@ TEST_CASE("string to timingInfoDecoder") { defs::timingInfoDecoder::SHINE); } + +TEST_CASE("Convert string to vector of ints") { + REQUIRE(StringTo>("1, 2, 3") == std::vector{1, 2, 3}); + REQUIRE(StringTo>(" 4 ,5,6 ") == std::vector{4, 5, 6}); + REQUIRE(StringTo>("[8]") == std::vector{8}); + REQUIRE(StringTo>("9, ") == std::vector{9}); + REQUIRE(StringTo>("") == std::vector{}); +} + } // namespace sls