Skip to content

Commit 16fd912

Browse files
committed
conditionally use from_char when available
1 parent 8c18a27 commit 16fd912

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ CMakeUserPresets.json
2020

2121
tags
2222
/clang_tidy_output.log
23+
/.worktrees/
2324
/.clang-tidy-venv/*
2425
/llvm.sh
2526
t11_groot_howto.btlog
2627
minitrace.json
28+
TODO.md

src/basic_types.cpp

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
#include <algorithm>
77
#include <array>
88
#include <charconv>
9+
#if __cpp_lib_to_chars < 201611L
910
#include <clocale>
11+
#endif
1012
#include <cstdlib>
1113
#include <cstring>
1214
#include <tuple>
@@ -197,26 +199,46 @@ uint32_t convertFromString<uint32_t>(StringView str)
197199
template <>
198200
double convertFromString<double>(StringView str)
199201
{
200-
// see issue #120
201-
// http://quick-bench.com/DWaXRWnxtxvwIMvZy2DxVPEKJnE
202-
202+
#if __cpp_lib_to_chars >= 201611L
203+
// from_chars is locale-independent and thread-safe
204+
double result = 0;
205+
const auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
206+
if(ec != std::errc())
207+
{
208+
throw RuntimeError(StrCat("Can't convert string [", str, "] to double"));
209+
}
210+
return result;
211+
#else
212+
// Fallback: stod is locale-dependent, so force "C" locale.
213+
// See issue #120. Note: setlocale is not thread-safe.
203214
const std::string old_locale = setlocale(LC_NUMERIC, nullptr);
204215
std::ignore = setlocale(LC_NUMERIC, "C");
205216
const std::string str_copy(str.data(), str.size());
206217
const double val = std::stod(str_copy);
207218
std::ignore = setlocale(LC_NUMERIC, old_locale.c_str());
208219
return val;
220+
#endif
209221
}
210222

211223
template <>
212224
float convertFromString<float>(StringView str)
213225
{
226+
#if __cpp_lib_to_chars >= 201611L
227+
float result = 0;
228+
const auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
229+
if(ec != std::errc())
230+
{
231+
throw RuntimeError(StrCat("Can't convert string [", str, "] to float"));
232+
}
233+
return result;
234+
#else
214235
const std::string old_locale = setlocale(LC_NUMERIC, nullptr);
215236
std::ignore = setlocale(LC_NUMERIC, "C");
216237
const std::string str_copy(str.data(), str.size());
217238
const double val = std::stod(str_copy);
218239
std::ignore = setlocale(LC_NUMERIC, old_locale.c_str());
219240
return static_cast<float>(val);
241+
#endif
220242
}
221243

222244
template <>

0 commit comments

Comments
 (0)