diff --git a/src/string_utils.cc b/src/string_utils.cc index 37ca6716..0b0c113c 100644 --- a/src/string_utils.cc +++ b/src/string_utils.cc @@ -4,6 +4,7 @@ #include "utf8_iterator.hh" #include "unit_tests.hh" +#include #include namespace Kakoune @@ -146,53 +147,57 @@ int str_to_int(StringView str) throw runtime_error{str + " is not a number"}; } +template +InplaceString to_string_impl(auto val, auto format) +{ + InplaceString res; + auto [end, errc] = std::to_chars(res.m_data, res.m_data + N, val, format); + if (errc != std::errc{}) + throw runtime_error("to_string error"); + res.m_length = end - res.m_data; + *end = '\0'; + return res; +} + +template +InplaceString to_string_impl(auto val) +{ + return to_string_impl(val, 10); +} + InplaceString<15> to_string(int val) { - InplaceString<15> res; - res.m_length = sprintf(res.m_data, "%i", val); - return res; + return to_string_impl<15>(val); } InplaceString<15> to_string(unsigned val) { - InplaceString<15> res; - res.m_length = sprintf(res.m_data, "%u", val); - return res; + return to_string_impl<15>(val); } InplaceString<23> to_string(long int val) { - InplaceString<23> res; - res.m_length = sprintf(res.m_data, "%li", val); - return res; + return to_string_impl<23>(val); } InplaceString<23> to_string(long long int val) { - InplaceString<23> res; - res.m_length = sprintf(res.m_data, "%lli", val); - return res; + return to_string_impl<23>(val); } InplaceString<23> to_string(unsigned long val) { - InplaceString<23> res; - res.m_length = sprintf(res.m_data, "%lu", val); - return res; + return to_string_impl<23>(val); } InplaceString<23> to_string(Hex val) { - InplaceString<23> res; - res.m_length = sprintf(res.m_data, "%zx", val.val); - return res; + return to_string_impl<23>(val.val, 16); } InplaceString<23> to_string(float val) { - InplaceString<23> res; - res.m_length = sprintf(res.m_data, "%f", val); - return res; + return to_string_impl<23>(val, std::chars_format::general); } InplaceString<7> to_string(Codepoint c)