Skip to content

Commit

Permalink
UTIL: Add workaround for libc++ for util::strings::convert<double>()
Browse files Browse the repository at this point in the history
Behavior of parsing doubles from streams is different in LLVM's libc++
compared to GCC's libstdc++, see [1]. This causes
StringTest.StringConversionTest to fail when compiling against LLVM's
libc++:

  [ RUN      ] StringTest.StringConversionTest
  util/gtest_string.cc:48: Failure
  Expected equality of these values:
    10.1234
    util::string::convert<double>("10.1234asfd", false)
      Which is: 0

  [  FAILED  ] StringTest.StringConversionTest (0 ms)

This mainly affects macOS because it defaults to libc++.

The behavior of libstdc++ is what makes most sense here because
std::stringstream::operator>>() will call std::strtod() internally
which will extract 10.1234 from the string.

This is fixed by implementing a workaround for libc++.

[1] https://www.github.com/llvm/llvm-project/issues/18156
  • Loading branch information
andre-schulz committed Aug 23, 2024
1 parent 45b00bf commit 3eb318d
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions libs/util/string_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,26 @@ convert (std::string const& str, bool strict_conversion)
return ret;
}

#if defined(_LIBCPP_VERSION)
/* LLVM's libc++'s behavior when parsing a double from a stream is different
* than GCC's libstdc++, see the following issue:
* https://www.github.com/llvm/llvm-project/issues/18156
*
* This is why the following workaround is needed when compiling against
* libc++.
*/
template <>
inline double
convert (std::string const& str, bool strict_conversion)
{
std::size_t pos = 0;
double ret = std::stod(str, &pos);
if (strict_conversion && pos != str.length())
throw std::invalid_argument("Invalid string conversion: " + str);
return ret;
}
#endif

template <typename T>
inline char const*
for_type (void)
Expand Down

0 comments on commit 3eb318d

Please sign in to comment.