Skip to content

Commit 92a4e49

Browse files
authored
Merge pull request zerebubuth#390 from mmd-osm/patch/jsonentryint
json writer: fmt for formatting integer values
2 parents da21807 + bb945e2 commit 92a4e49

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

include/cgimap/json_writer.hpp

+25-1
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,16 @@
1010
#ifndef JSON_WRITER_HPP
1111
#define JSON_WRITER_HPP
1212

13+
#include <array>
1314
#include <memory>
1415
#include <string>
1516
#include <string_view>
1617
#include <stdexcept>
18+
19+
#include <fmt/core.h>
20+
#include <fmt/compile.h>
1721
#include <yajl/yajl_gen.h>
22+
1823
#include "cgimap/output_buffer.hpp"
1924
#include "cgimap/output_writer.hpp"
2025

@@ -46,7 +51,26 @@ class json_writer : public output_writer {
4651

4752
template<typename TInteger, std::enable_if_t<std::is_integral_v<TInteger>, bool> = true>
4853
void entry(TInteger i) {
49-
yajl_gen_integer(gen, i);
54+
55+
const char* str = nullptr;
56+
size_t len = 0;
57+
58+
#if FMT_VERSION >= 90000
59+
std::array<char, 64> buf;
60+
constexpr size_t max_chars = buf.size() - 1;
61+
auto [end, n_written] = fmt::format_to_n(buf.begin(), max_chars, FMT_COMPILE("{:d}"), i);
62+
if (n_written > max_chars)
63+
throw write_error("cannot convert int attribute to string.");
64+
*end = '\0'; // Null terminate string
65+
str = buf.data();
66+
len = n_written;
67+
#else
68+
auto s = fmt::format("{:d}", i);
69+
str = s.c_str();
70+
len = s.length();
71+
#endif
72+
73+
yajl_gen_number(gen, str, len);
5074
}
5175

5276
void entry(const char* s);

0 commit comments

Comments
 (0)