charconv.hpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (c) 2022 Dvir Yitzchaki.
  2. // Use, modification and distribution are subject to the Boost Software License,
  3. // Version 1.0. See http://www.boost.org/LICENSE_1_0.txt.
  4. #ifndef BOOST_CONVERT_CHARCONV_BASED_CONVERTER_HPP
  5. #define BOOST_CONVERT_CHARCONV_BASED_CONVERTER_HPP
  6. #ifdef BOOST_NO_CXX17_HDR_CHARCONV
  7. #error "This header requires <charconv> which is unavailable"
  8. #endif // BOOST_NO_CXX17_HDR_CHARCONV
  9. #ifdef BOOST_NO_CXX17_STRUCTURED_BINDINGS
  10. #error "This header requires structured bindings which is unavailable"
  11. #endif // BOOST_NO_CXX17_STRUCTURED_BINDINGS
  12. #ifdef BOOST_NO_CXX17_IF_CONSTEXPR
  13. #error "This header requires constexpr if which is unavailable"
  14. #endif // BOOST_NO_CXX17_IF_CONSTEXPR
  15. #include <boost/convert/base.hpp>
  16. #include <boost/make_default.hpp>
  17. #include <charconv>
  18. #include <type_traits>
  19. namespace boost::cnv { struct charconv; }
  20. /// @brief std::to/from_chars-based extended converter
  21. /// @details Good overall performance and moderate formatting facilities.
  22. struct boost::cnv::charconv : public boost::cnv::cnvbase<boost::cnv::charconv>
  23. {
  24. using this_type = boost::cnv::charconv;
  25. using base_type = boost::cnv::cnvbase<this_type>;
  26. template<typename in_type>
  27. cnv::range<char*>
  28. to_str(in_type value_in, char* buf) const
  29. {
  30. auto [ptr, err] = [&]
  31. {
  32. if constexpr (std::is_integral_v<in_type>)
  33. return std::to_chars(buf, buf + bufsize_, value_in, int(base_));
  34. else
  35. return std::to_chars(buf, buf + bufsize_, value_in, chars_format(), precision_);
  36. }();
  37. return cnv::range<char*>(buf, err == std::errc{} ? ptr : buf);
  38. }
  39. template<typename string_type, typename out_type>
  40. void
  41. str_to(cnv::range<string_type> range, optional<out_type>& result_out) const
  42. {
  43. out_type result = boost::make_default<out_type>();
  44. auto [ptr, err] = [&]
  45. {
  46. char_cptr beg = &*range.begin();
  47. char_cptr end = beg + range.size();
  48. if constexpr (std::is_integral_v<out_type>)
  49. return std::from_chars(beg, end, result, int(base_));
  50. else
  51. return std::from_chars(beg, end, result, chars_format());
  52. }();
  53. if (err == std::errc{})
  54. result_out = result;
  55. }
  56. std::chars_format chars_format() const
  57. {
  58. static constexpr std::chars_format format[] =
  59. {
  60. std::chars_format::fixed,
  61. std::chars_format::scientific,
  62. std::chars_format::hex
  63. };
  64. return format[int(notation_)];
  65. }
  66. };
  67. #endif // BOOST_CONVERT_CHARCONV_BASED_CONVERTER_HPP