diff --git a/src/openlcb/BroadcastTimeDefs.cxx b/src/openlcb/BroadcastTimeDefs.cxx index 2ca988351..b144bf08a 100644 --- a/src/openlcb/BroadcastTimeDefs.cxx +++ b/src/openlcb/BroadcastTimeDefs.cxx @@ -139,7 +139,15 @@ bool BroadcastTimeDefs::string_to_time( // int16_t BroadcastTimeDefs::string_to_rate_quarters(const std::string &srate) { - float rate = std::stof(srate); + const char *rate_c_str = srate.c_str(); + char *end; + float rate = strtof(rate_c_str, &end); + + if (end == rate_c_str) + { + // None of the string processed. + return 0; + } if (rate < -512) { // set to minimum valid rate diff --git a/src/openlcb/BroadcastTimeDefs.cxxtest b/src/openlcb/BroadcastTimeDefs.cxxtest new file mode 100644 index 000000000..9b49d795f --- /dev/null +++ b/src/openlcb/BroadcastTimeDefs.cxxtest @@ -0,0 +1,46 @@ +#include "utils/async_if_test_helper.hxx" + +#include "openlcb/BroadcastTimeDefs.hxx" + +#if 0 +#define PRINT_ALL_PACKETS() print_all_packets() +#else +#define PRINT_ALL_PACKETS() +#endif + +namespace openlcb +{ + +TEST(BroadcastTimeDefs, string_to_rate_quarters) +{ + int16_t rate; + + rate = BroadcastTimeDefs::string_to_rate_quarters("Freddy"); + EXPECT_EQ(0, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters("2000"); + EXPECT_EQ(2047, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters("-2000"); + EXPECT_EQ(-2048, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters(""); + EXPECT_EQ(0, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters("-"); + EXPECT_EQ(0, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters(" "); + EXPECT_EQ(0, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters("511,75"); + EXPECT_EQ(2044, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters("1.75"); + EXPECT_EQ(7, rate); + + rate = BroadcastTimeDefs::string_to_rate_quarters("-1.75"); + EXPECT_EQ(-7, rate); +} + +} // namespace openlcb diff --git a/src/openlcb/BroadcastTimeDefs.hxx b/src/openlcb/BroadcastTimeDefs.hxx index 4337b3b19..8147e7b1f 100644 --- a/src/openlcb/BroadcastTimeDefs.hxx +++ b/src/openlcb/BroadcastTimeDefs.hxx @@ -362,7 +362,9 @@ struct BroadcastTimeDefs /// Convert a string (float) to rate quarters. /// @param srate rate in the form of a string float - /// @return rate in the form of an int16_t in rate quarters + /// @return Rate in the form of an int16_t in rate quarters. If a + /// conversion error occurs, then the returned value will be 0, + /// which is at least a valid rate. static int16_t string_to_rate_quarters(const std::string &srate); };