You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/11/17 20:30:32 UTC

[GitHub] [arrow] westonpace commented on a diff in pull request #14666: ARROW-18350: [C++] Use std::to_chars instead of std::to_string

westonpace commented on code in PR #14666:
URL: https://github.com/apache/arrow/pull/14666#discussion_r1025684123


##########
cpp/src/arrow/util/string.h:
##########
@@ -97,5 +100,31 @@ std::optional<std::string> Replace(std::string_view s, std::string_view token,
 ARROW_EXPORT
 arrow::Result<bool> ParseBoolean(std::string_view value);
 
+/// \brief An ergonomic wrapper around std::to_chars, returning a std::string
+///
+/// For most inputs, the std::string result will not incur any heap allocation
+/// thanks to small string optimization.
+///
+/// Compared to std::to_string, this function gives locale-agnostic results
+/// and might also be faster.
+template <typename T, typename... Args>
+std::string ToChars(T value, Args&&... args) {
+  // According to various sources, the GNU libstdc++ and Microsoft's C++ STL
+  // allow up to 15 bytes of small string optimization, while clang's libc++
+  // goes up to 22 bytes. Choose the pessimistic value.
+  std::string out(15, 0);
+  auto res = std::to_chars(&out.front(), &out.back(), value, args...);
+  while (res.ec != std::errc{}) {
+    assert(res.ec == std::errc::value_too_large);
+    out.resize(out.capacity() * 2);
+    res = std::to_chars(&out.front(), &out.back(), value, args...);
+  }
+  const auto length = res.ptr - out.data();
+  assert(length <= static_cast<int64_t>(out.length()));
+  out[length] = 0;

Review Comment:
   I believe this is redundant: https://godbolt.org/z/6vcW1jEfh
   
   The call to resize *should* set `out[length]` to 0 so that `std::string` can fulfill its requirements for `c_str`.
   
   That being said, it should be harmless and I imagine would optimize out.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org