|
Boost Users : |
Subject: [Boost-users] [Spirit] Karma generator for JSON
From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2012-03-09 13:47:36
Hello Hartmut,
as discussed @irc channel I am posting the example of my problem (I use
boost 1.47):
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/karma_char_class.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <iterator>
#include <cassert>
#include <utility>
#include <string>
namespace karma = boost::spirit::karma;
typedef std::pair<unsigned char, unsigned char> utf16_t;
template<class OutIter>
struct json_char_encoder2
: boost::spirit::karma::grammar<OutIter, std::string()>
{
json_char_encoder2()
: json_char_encoder2::base_type(encoded_)
{
json_sym_.add
('"', "\\\"")
('/', "\\/")
('\\', "\\\\")
('\b', "\\b")
('\f', "\\f")
('\n', "\\n")
('\r', "\\r")
('\t', "\\t")
;
using boost::spirit::iso8859_1::print;
encoded_=*(json_sym_ | print | uchar_);
uchar_ = karma::lit("\\u") << karma::hex << karma::hex; //also tried
to use unicode_gen_;
}
karma::rule<OutIter, std::string()> encoded_;
karma::symbols<char, char const*> json_sym_;
karma::rule<OutIter, utf16_t()> uchar_;
karma::uint_generator<unsigned short, 16> unicode_gen_;
};
int main()
{
assert(2==sizeof(short));
typedef std::back_insert_iterator<std::string> iter_t;
json_char_encoder2<iter_t> encoder2;
std::string generated;
iter_t sink(generated);
std::string sinput="abc";
sinput.push_back(char(0xAA));
sinput.push_back(char(0xBB));
bool result = karma::generate(sink, encoder2, sinput);
return 0;
}
The problem here is that I would like the generator in case of uchar_ to
retrieve 2 subsequent string bytes and write them out as \uXXXX as
specified at JSON.org. What I get is:
a. IF: replacing utf16_t with unsigned short => and removing 1 of the
karma::hex terminals => 2 calls where each byte is converted to unsigned
short
b. IF: having the source as it is => fails the generation, where the
generated string is empty.
One strange behavior as well: result is true for case b. Why?
Regards,
Ovanes
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net