2 #include <msp/core/maputils.h>
3 #include <msp/strings/format.h>
4 #include "binaryparser.h"
12 class bad_definition: public runtime_error
15 bad_definition(const std::string &w):
19 virtual ~bad_definition() throw() { }
23 BinaryParser::BinaryParser(Input &i, const string &s):
27 dict[1] = DictEntry("__kwd", "iss");
28 dict[2] = DictEntry("__str", "is");
31 Statement BinaryParser::parse()
35 Statement st = parse_statement();
36 if(st.keyword=="__kwd")
39 throw bad_definition("__kwd");
41 const unsigned id = st.args[0].get<unsigned>();
42 const string &kw = st.args[1].get<const string &>();
43 const string &args = st.args[2].get<const string &>();
44 dict[id] = DictEntry(kw, args);
46 else if(st.keyword=="__str")
49 throw bad_definition("__str");
51 const unsigned id = st.args[0].get<unsigned>();
52 strings[id] = st.args[1].get<const string &>();
59 Statement BinaryParser::parse_statement()
61 while(first && in.peek()=='\n')
65 unsigned id = parse_int();
69 const DictEntry &de = get_item(dict, id);
72 result.keyword = de.keyword;
75 for(unsigned j = 0; j<de.args.size(); ++j)
79 case IntType::signature:
80 result.args.push_back(parse_int());
82 case FloatType::signature:
83 result.args.push_back(parse_float());
85 case StringType::signature:
86 result.args.push_back(parse_string());
88 case BoolType::signature:
89 result.args.push_back(parse_bool());
91 case SymbolType::signature:
92 result.args.push_back(parse_symbol());
97 unsigned nsub = parse_int();
98 for(unsigned j = 0; j<nsub; ++j)
99 result.sub.push_back(parse());
106 long long BinaryParser::parse_int()
108 long long result = 0;
115 result = (result<<7) | (c&0x7F);
122 const long long mask = 1LL<<(bits-1);
123 result = (result^mask)-mask;
128 float BinaryParser::parse_float()
133 char d[sizeof(float)];
136 #if BYTE_ORDER == LITTLE_ENDIAN
137 for(unsigned i = sizeof(float); i--;)
140 for(unsigned i = 0; i<sizeof(float); ++i)
147 bool BinaryParser::parse_bool()
152 string BinaryParser::parse_string()
154 int len = parse_int();
159 for(int i = 0; i<len; ++i)
164 return get_item(strings, -len);
167 Symbol BinaryParser::parse_symbol()
169 return get_item(strings, parse_int());
172 } // namespace DataFile