spirit.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright (c) 2009-2020 Vladimir Batov.
  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_SPIRIT_BASED_CONVERTER_HPP
  5. #define BOOST_CONVERT_SPIRIT_BASED_CONVERTER_HPP
  6. #include <boost/convert/base.hpp>
  7. #include <boost/convert/detail/config.hpp>
  8. #include <boost/spirit/include/qi.hpp>
  9. #include <boost/spirit/include/karma.hpp>
  10. namespace boost { namespace cnv { struct spirit; }}
  11. struct boost::cnv::spirit : boost::cnv::cnvbase<boost::cnv::spirit>
  12. {
  13. using this_type = boost::cnv::spirit;
  14. using base_type = boost::cnv::cnvbase<this_type>;
  15. using base_type::operator();
  16. template<typename string_type, typename out_type>
  17. void
  18. str_to(cnv::range<string_type> range, optional<out_type>& result_out) const
  19. {
  20. using parser = typename boost::spirit::traits::create_parser<out_type>::type;
  21. auto beg = range.begin();
  22. auto end = range.end();
  23. auto result = out_type();
  24. if (boost::spirit::qi::parse(beg, end, parser(), result))
  25. if (beg == end) // ensure the whole string has been parsed
  26. result_out = result;
  27. }
  28. template<typename in_type, typename char_type>
  29. cnv::range<char_type*>
  30. to_str(in_type value_in, char_type* beg) const
  31. {
  32. using generator = typename boost::spirit::traits::create_generator<in_type>::type;
  33. auto end = beg;
  34. bool good = boost::spirit::karma::generate(end, generator(), value_in);
  35. return cnv::range<char_type*>(beg, good ? end : beg);
  36. }
  37. };
  38. #endif // BOOST_CONVERT_SPIRIT_BASED_CONVERTER_HPP