]> git.stg.codes - stg.git/blob - libs/json/generator.cpp
Port to CMake, get rid of os_int.h.
[stg.git] / libs / json / generator.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
19  */
20
21 #include "stg/json_generator.h"
22
23 #include <yajl/yajl_gen.h>
24
25 using STG::JSON::NullGen;
26 using STG::JSON::BoolGen;
27 using STG::JSON::StringGen;
28 using STG::JSON::NumberGen;
29 using STG::JSON::MapGen;
30 using STG::JSON::ArrayGen;
31 using STG::JSON::Callback;
32
33 namespace
34 {
35
36 void genString(yajl_gen_t* handle, const std::string& value)
37 {
38     yajl_gen_string(handle, reinterpret_cast<const unsigned char*>(value.c_str()), value.length());
39 }
40
41 }
42
43 void NullGen::run(yajl_gen_t* handle) const { yajl_gen_null(handle); }
44 void BoolGen::run(yajl_gen_t* handle) const { yajl_gen_bool(handle, m_value); }
45 void StringGen::run(yajl_gen_t* handle) const { genString(handle, m_value); }
46 void NumberGen::run(yajl_gen_t* handle) const { yajl_gen_number(handle, m_value.c_str(), m_value.length()); }
47
48 void MapGen::run(yajl_gen_t* handle) const
49 {
50     yajl_gen_map_open(handle);
51     for (Value::const_iterator it = m_value.begin(); it != m_value.end(); ++it)
52     {
53         genString(handle, it->first);
54         it->second.first->run(handle);
55     }
56     yajl_gen_map_close(handle);
57 }
58
59 void ArrayGen::run(yajl_gen_t* handle) const
60 {
61     yajl_gen_array_open(handle);
62     for (Value::const_iterator it = m_value.begin(); it != m_value.end(); ++it)
63         it->first->run(handle);
64     yajl_gen_array_close(handle);
65 }
66
67 bool STG::JSON::generate(Gen& gen, Callback callback, void* data)
68 {
69     yajl_gen handle = yajl_gen_alloc(NULL);
70
71     gen.run(handle);
72
73     const unsigned char* buf = NULL;
74     size_t size = 0;
75     yajl_gen_get_buf(handle, &buf, &size);
76
77     bool res = callback(data, reinterpret_cast<const char*>(buf), size);
78
79     yajl_gen_free(handle);
80
81     return res;
82 }