Skip to content

Commit e1ccbde

Browse files
committed
NLWriter: use_std::to_chars() #30
1 parent 2a6030b commit e1ccbde

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

nl-writer2/CMakeLists.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ set(NLW2_EXAMPLE_PATH ${NLW2_DIR}/examples)
2525
set(NLW2_LIB_FILES
2626
${NLW2_SRC_PATH}/nl-writer2.cc
2727
${NLW2_SRC_PATH}/nl-utils.cc
28-
${NLW2_SRC_PATH}/dtoa.cc
28+
# ${NLW2_SRC_PATH}/dtoa.cc
2929
${NLW2_SRC_PATH}/nl-solver.cc
3030
)
3131
set(NLW2_INC_FILES

nl-writer2/src/nl-writer2.cc

+20-3
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@
4343
#include <cmath>
4444
#include <cstring>
4545
#include <string>
46+
#include <charconv>
47+
#include <system_error>
4648

4749
#include "mp/nl-writer2.h"
4850
#include "mp/nl-writer2.hpp"
@@ -152,9 +154,20 @@ int TextFormatter::apr(File& f, const char *fmt, ...)
152154
while (*fmt++ != 'g');
153155
case 'g':
154156
x = va_arg(ap, double);
155-
#ifdef NL_LIB_USE_SPRINTF
156-
snprintf(s = buf,
157-
sizeof(buf), "%.*g", output_prec, x);
157+
#define NL_LIB_USE_TO_CHARS
158+
#ifdef NL_LIB_USE_TO_CHARS
159+
std::to_chars_result res;
160+
if (output_prec <= 0) // shortest representation
161+
res = std::to_chars(s = buf, buf+sizeof(buf)-1, x);
162+
else // 24 characters enough IEEE 754
163+
res = std::to_chars(s = buf, buf+sizeof(buf)-1, x,
164+
std::chars_format::general,
165+
output_prec);
166+
if (res.ec == std::errc()) // OK
167+
*res.ptr = '\0';
168+
else
169+
Utils().myexit("aprintf / to_chars bug: " +
170+
std::make_error_code(res.ec).message());
158171
#elif NL_LIB_USE_OWN_GFMT
159172
NL_LIB_GFMT::gfmt(s = buf, sizeof(buf), x, output_prec);
160173
#else
@@ -306,6 +319,8 @@ apr(File& f, const char *fmt, ...)
306319
} // namespace mp
307320

308321

322+
#ifndef NL_LIB_USE_TO_CHARS
323+
309324
extern "C" {
310325
char *
311326
dtoa_r_dmgay(double dd, int mode, int ndigits,
@@ -459,3 +474,5 @@ void gfmt(char *b, size_t sz, double x, int prec) {
459474
}
460475

461476
} // namespace NL_LIB_GFMT
477+
478+
#endif // NL_LIB_USE_TO_CHARS

0 commit comments

Comments
 (0)