3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "serialize.h"
23 #include "util/string.h"
24 #include "../exceptions.h"
30 // Creates a string with the length as the first two bytes
31 std::string serializeString(const std::string &plain)
33 //assert(plain.size() <= 65535);
34 if(plain.size() > 65535)
35 throw SerializationError("String too long for serializeString");
37 writeU16((u8*)&buf[0], plain.size());
44 // Creates a string with the length as the first two bytes from wide string
45 std::string serializeWideString(const std::wstring &plain)
47 //assert(plain.size() <= 65535);
48 if(plain.size() > 65535)
49 throw SerializationError("String too long for serializeString");
51 writeU16((u8*)buf, plain.size());
54 for(u32 i=0; i<plain.size(); i++)
56 writeU16((u8*)buf, plain[i]);
62 // Reads a string with the length as the first two bytes
63 std::string deSerializeString(std::istream &is)
68 throw SerializationError("deSerializeString: size not read");
69 u16 s_size = readU16((u8*)buf);
72 Buffer<char> buf2(s_size);
73 is.read(&buf2[0], s_size);
76 s.append(&buf2[0], s_size);
80 // Reads a wide string with the length as the first two bytes
81 std::wstring deSerializeWideString(std::istream &is)
86 throw SerializationError("deSerializeString: size not read");
87 u16 s_size = readU16((u8*)buf);
92 for(u32 i=0; i<s_size; i++)
95 wchar_t c16 = readU16((u8*)buf);
101 // Creates a string with the length as the first four bytes
102 std::string serializeLongString(const std::string &plain)
105 writeU32((u8*)&buf[0], plain.size());
112 // Reads a string with the length as the first four bytes
113 std::string deSerializeLongString(std::istream &is)
118 throw SerializationError("deSerializeLongString: size not read");
119 u32 s_size = readU32((u8*)buf);
122 Buffer<char> buf2(s_size);
123 is.read(&buf2[0], s_size);
126 s.append(&buf2[0], s_size);
130 // Creates a string encoded in JSON format (almost equivalent to a C string literal)
131 std::string serializeJsonString(const std::string &plain)
133 std::ostringstream os(std::ios::binary);
135 for(size_t i = 0; i < plain.size(); i++)
140 case '"': os<<"\\\""; break;
141 case '\\': os<<"\\\\"; break;
142 case '/': os<<"\\/"; break;
143 case '\b': os<<"\\b"; break;
144 case '\f': os<<"\\f"; break;
145 case '\n': os<<"\\n"; break;
146 case '\r': os<<"\\r"; break;
147 case '\t': os<<"\\t"; break;
150 if(c >= 32 && c <= 126)
156 u32 cnum = (u32) (u8) c;
157 os<<"\\u"<<std::hex<<std::setw(4)<<std::setfill('0')<<cnum;
167 // Reads a string encoded in JSON format
168 std::string deSerializeJsonString(std::istream &is)
170 std::ostringstream os(std::ios::binary);
173 // Parse initial doublequote
176 throw SerializationError("JSON string must start with doublequote");
183 throw SerializationError("JSON string ended prematurely");
192 throw SerializationError("JSON string ended prematurely");
195 default: os<<c2; break;
196 case 'b': os<<'\b'; break;
197 case 'f': os<<'\f'; break;
198 case 'n': os<<'\n'; break;
199 case 'r': os<<'\r'; break;
200 case 't': os<<'\t'; break;
204 is.read(hexdigits, 4);
206 throw SerializationError("JSON string ended prematurely");
208 std::istringstream tmp_is(hexdigits, std::ios::binary);
210 tmp_is >> std::hex >> hexnumber;
211 os<<((char)hexnumber);
225 bool deSerializeStringToStruct(std::string valstr,
226 std::string format, void *out, size_t olen)
229 std::vector<std::string *> strs_alloced;
234 char *s = &valstr[0];
235 char *buf = new char[len];
238 char *fmtpos, *fmt = &format[0];
239 while ((f = strtok_r(fmt, ",", &fmtpos)) && s) {
242 bool is_unsigned = false;
246 width = (int)strtol(f + 1, &f, 10);
247 if (width && valtype == 's')
256 bufpos += PADDING(bufpos, u16);
257 if ((bufpos - buf) + sizeof(u16) <= len) {
259 *(u16 *)bufpos = (u16)strtoul(s, &s, 10);
261 *(s16 *)bufpos = (s16)strtol(s, &s, 10);
263 bufpos += sizeof(u16);
264 } else if (width == 32) {
265 bufpos += PADDING(bufpos, u32);
266 if ((bufpos - buf) + sizeof(u32) <= len) {
268 *(u32 *)bufpos = (u32)strtoul(s, &s, 10);
270 *(s32 *)bufpos = (s32)strtol(s, &s, 10);
272 bufpos += sizeof(u32);
273 } else if (width == 64) {
274 bufpos += PADDING(bufpos, u64);
275 if ((bufpos - buf) + sizeof(u64) <= len) {
277 *(u64 *)bufpos = (u64)strtoull(s, &s, 10);
279 *(s64 *)bufpos = (s64)strtoll(s, &s, 10);
281 bufpos += sizeof(u64);
286 snext = strchr(s, ',');
290 bufpos += PADDING(bufpos, bool);
291 if ((bufpos - buf) + sizeof(bool) <= len)
292 *(bool *)bufpos = is_yes(std::string(s));
293 bufpos += sizeof(bool);
298 bufpos += PADDING(bufpos, float);
299 if ((bufpos - buf) + sizeof(float) <= len)
300 *(float *)bufpos = strtof(s, &s);
301 bufpos += sizeof(float);
306 while (*s == ' ' || *s == '\t')
308 if (*s++ != '"') //error, expected string
312 while (snext[0] && !(snext[-1] != '\\' && snext[0] == '"'))
316 bufpos += PADDING(bufpos, std::string *);
318 str = new std::string(s);
320 while ((pos = str->find("\\\"", pos)) != std::string::npos)
323 if ((bufpos - buf) + sizeof(std::string *) <= len)
324 *(std::string **)bufpos = str;
325 bufpos += sizeof(std::string *);
326 strs_alloced.push_back(str);
328 s = *snext ? snext + 1 : NULL;
331 while (*s == ' ' || *s == '\t')
333 if (*s++ != '(') //error, expected vector
337 bufpos += PADDING(bufpos, v2f);
339 if ((bufpos - buf) + sizeof(v2f) <= len) {
340 v2f *v = (v2f *)bufpos;
341 v->X = strtof(s, &s);
343 v->Y = strtof(s, &s);
346 bufpos += sizeof(v2f);
347 } else if (width == 3) {
348 bufpos += PADDING(bufpos, v3f);
349 if ((bufpos - buf) + sizeof(v3f) <= len) {
350 v3f *v = (v3f *)bufpos;
351 v->X = strtof(s, &s);
353 v->Y = strtof(s, &s);
355 v->Z = strtof(s, &s);
358 bufpos += sizeof(v3f);
362 default: //error, invalid format specifier
369 if ((size_t)(bufpos - buf) > len) //error, buffer too small
373 if (f && *f) { //error, mismatched number of fields and values
375 for (size_t i = 0; i != strs_alloced.size(); i++)
376 delete strs_alloced[i];
381 memcpy(out, buf, olen);
387 bool serializeStructToString(std::string *outstr,
388 std::string format, void *value)
391 int sbuflen = sizeof(sbuf) - 1;
398 char *bufpos = (char *)value;
399 char *fmtpos, *fmt = &format[0];
400 while ((f = strtok_r(fmt, ",", &fmtpos))) {
402 bool is_unsigned = false;
403 int width = 0, nprinted = 0;
406 width = (int)strtol(f + 1, &f, 10);
407 if (width && valtype == 's')
416 bufpos += PADDING(bufpos, u16);
417 nprinted = snprintf(sbuf + pos, sbuflen,
418 is_unsigned ? "%u, " : "%d, ",
420 bufpos += sizeof(u16);
421 } else if (width == 32) {
422 bufpos += PADDING(bufpos, u32);
423 nprinted = snprintf(sbuf + pos, sbuflen,
424 is_unsigned ? "%u, " : "%d, ",
426 bufpos += sizeof(u32);
427 } else if (width == 64) {
428 bufpos += PADDING(bufpos, u64);
429 nprinted = snprintf(sbuf + pos, sbuflen,
430 is_unsigned ? "%llu, " : "%lli, ",
431 (unsigned long long)*((u64 *)bufpos));
432 bufpos += sizeof(u64);
436 bufpos += PADDING(bufpos, bool);
437 nprinted = snprintf(sbuf + pos, sbuflen, "%s, ",
438 *((bool *)bufpos) ? "true" : "false");
439 bufpos += sizeof(bool);
442 bufpos += PADDING(bufpos, float);
443 nprinted = snprintf(sbuf + pos, sbuflen, "%f, ",
445 bufpos += sizeof(float);
448 bufpos += PADDING(bufpos, std::string *);
449 str = **((std::string **)bufpos);
452 while ((fpos = str.find('"', fpos)) != std::string::npos) {
453 str.insert(fpos, 1, '\\');
457 nprinted = snprintf(sbuf + pos, sbuflen, "\"%s\", ",
458 (*((std::string **)bufpos))->c_str());
459 bufpos += sizeof(std::string *);
463 bufpos += PADDING(bufpos, v2f);
464 v2f *v = (v2f *)bufpos;
465 nprinted = snprintf(sbuf + pos, sbuflen,
466 "(%f, %f), ", v->X, v->Y);
467 bufpos += sizeof(v2f);
469 bufpos += PADDING(bufpos, v3f);
470 v3f *v = (v3f *)bufpos;
471 nprinted = snprintf(sbuf + pos, sbuflen,
472 "(%f, %f, %f), ", v->X, v->Y, v->Z);
473 bufpos += sizeof(v3f);
479 if (nprinted < 0) //error, buffer too small
485 // this is to trim off the trailing comma