spirit.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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
  11. {
  12. struct spirit;
  13. }}
  14. struct boost::cnv::spirit : public boost::cnv::cnvbase<boost::cnv::spirit>
  15. {
  16. typedef boost::cnv::spirit this_type;
  17. typedef boost::cnv::cnvbase<this_type> base_type;
  18. using base_type::operator();
  19. template<typename string_type, typename out_type>
  20. void
  21. str_to(cnv::range<string_type> range, optional<out_type>& result_out) const
  22. {
  23. typedef typename cnv::range<string_type>::iterator iterator;
  24. typedef typename boost::spirit::traits::create_parser<out_type>::type parser;
  25. iterator beg = range.begin();
  26. iterator end = range.end();
  27. out_type result;
  28. if (boost::spirit::qi::parse(beg, end, parser(), result))
  29. if (beg == end) // ensure the whole string has been parsed
  30. result_out = result;
  31. }
  32. template<typename in_type, typename char_type>
  33. cnv::range<char_type*>
  34. to_str(in_type value_in, char_type* beg) const
  35. {
  36. typedef typename boost::spirit::traits::create_generator<in_type>::type generator;
  37. char_type* end = beg;
  38. bool good = boost::spirit::karma::generate(end, generator(), value_in);
  39. return cnv::range<char_type*>(beg, good ? end : beg);
  40. }
  41. };
  42. #endif // BOOST_CONVERT_SPIRIT_BASED_CONVERTER_HPP