streamConsumer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /**
  2. * streamConsumer.cpp for jsonstroller
  3. *
  4. * Author: isundil <isundill@gmail.com>
  5. **/
  6. #include <iostream>
  7. #include <sstream>
  8. #include "jsonElement.hh"
  9. #include "streamConsumer.hh"
  10. StreamConsumer::StreamConsumer(std::istream &s): stream(s), root(nullptr)
  11. { }
  12. StreamConsumer::~StreamConsumer()
  13. {
  14. if (root)
  15. delete root;
  16. }
  17. StreamConsumer *StreamConsumer::withConfig(const AParams *p)
  18. {
  19. params = p;
  20. return this;
  21. }
  22. StreamConsumer *StreamConsumer::read()
  23. {
  24. if (root)
  25. return this;
  26. root = readNext(nullptr);
  27. return this;
  28. }
  29. JSonElement *StreamConsumer::readNext(JSonContainer *parent)
  30. {
  31. std::stringstream sbuf;
  32. JSonElement *root = consumeToken(parent, sbuf);
  33. const std::string buf = sbuf.str();
  34. if (root == nullptr)
  35. {
  36. if (buf == "{")
  37. {
  38. return readObject(parent);
  39. }
  40. else if (buf == "[")
  41. {
  42. return readArray(parent);
  43. }
  44. else
  45. return nullptr;
  46. }
  47. return root;
  48. }
  49. const JSonElement * StreamConsumer::getRoot() const
  50. { return root; }
  51. JSonElement * StreamConsumer::getRoot()
  52. { return root; }
  53. JSonObject *StreamConsumer::readObject(JSonContainer *parent)
  54. {
  55. JSonElement *keyObj;
  56. JSonObject *result = nullptr;
  57. std::stringstream buf;
  58. do
  59. {
  60. keyObj = consumeToken(result, buf);
  61. if (result == nullptr && keyObj == nullptr && buf.str() == "}")
  62. return new JSonObject(parent);
  63. JSonPrimitive<std::string> *key = dynamic_cast<JSonPrimitive<std::string> *>(keyObj);
  64. if (key == nullptr)
  65. throw JSonObject::NotAKeyException(stream.tellg(), history);
  66. if (consumeToken(parent, buf) != nullptr || buf.str() != ":")
  67. throw JsonUnexpectedException(':', stream.tellg(), history);
  68. if (result == nullptr)
  69. result = new JSonObject(parent);
  70. else if (result->contains(key->getValue()))
  71. {
  72. if (params->isStrict())
  73. throw JSonObject::DoubleKeyException(stream.tellg(), key->getValue(), history);
  74. else // add Warning, new key erase previous one
  75. {
  76. result->erase(key->getValue());
  77. warnings.push_back(Warning(JSonObject::DoubleKeyException(stream.tellg(), key->getValue(), history)));
  78. }
  79. }
  80. JSonElement *child = readNext(result);
  81. result->push(key->getValue(), child);
  82. delete keyObj;
  83. keyObj = consumeToken(result, buf);
  84. } while (!keyObj && buf.str() != "}");
  85. return result;
  86. }
  87. JSonArray *StreamConsumer::readArray(JSonContainer *parent)
  88. {
  89. JSonArray *result = nullptr;
  90. std::stringstream sbuf;
  91. JSonElement *child = consumeToken(parent, sbuf);
  92. std::string buf = sbuf.str();
  93. if (child == nullptr && buf == "]")
  94. return new JSonArray(parent); //Empty object
  95. do
  96. {
  97. if (child == nullptr && buf == "[")
  98. child = readArray(nullptr);
  99. if (child == nullptr && buf == "{")
  100. child = readObject(nullptr);
  101. if (child == nullptr)
  102. throw JsonNotJsonException(stream.tellg(), history);
  103. if (result == nullptr)
  104. result = new JSonArray(parent);
  105. child->setParent(result);
  106. result->push_back(child);
  107. child = consumeToken(result, sbuf);
  108. buf = sbuf.str();
  109. if (child != nullptr)
  110. throw JsonUnexpectedException(']', stream.tellg(), history);
  111. else if (buf == "]")
  112. break;
  113. else if (buf != ",")
  114. throw JsonUnexpectedException(']', stream.tellg(), history);
  115. child = consumeToken(result, sbuf);
  116. buf = sbuf.str();
  117. } while (true);
  118. return result;
  119. }
  120. JSonElement *StreamConsumer::consumeString(JSonContainer *parent, std::stringstream &buf)
  121. {
  122. bool escaped = false;
  123. buf.str("");
  124. buf.clear();
  125. while (stream.good())
  126. {
  127. char c = stream.get();
  128. history.put(c);
  129. if (!escaped)
  130. {
  131. if (c == '"')
  132. return new JSonPrimitive<std::string>(parent, buf.str());
  133. else if (c == '\\')
  134. escaped = true;
  135. else
  136. buf.write(&c, 1);
  137. }
  138. else
  139. {
  140. if (c == '\\' || c == '"')
  141. buf.write("\"", 1);
  142. else if (c == 'u')
  143. {
  144. if (params && params->isIgnoringUnicode())
  145. buf.write("\\u", 2);
  146. else
  147. {
  148. char unicodeBuf[4];
  149. stream.read(unicodeBuf, 4);
  150. std::streamsize gcount = stream.gcount();
  151. history.put(unicodeBuf, gcount);
  152. if (gcount != 4)
  153. break;
  154. try {
  155. appendUnicode(unicodeBuf, buf);
  156. }
  157. catch (std::invalid_argument &e)
  158. {
  159. throw JsonHexvalueException(e.what(), stream.tellg(), history);
  160. }
  161. }
  162. }
  163. else if (params->isStrict())
  164. throw JsonEscapedException(c, stream.tellg(), history);
  165. else
  166. {
  167. buf.write("\\", 1).write(&c, 1);
  168. warnings.push_back(Warning(JsonEscapedException(c, stream.tellg(), history)));
  169. }
  170. escaped = false;
  171. }
  172. }
  173. buf.str("");
  174. buf.clear();
  175. return nullptr;
  176. }
  177. JSonElement *StreamConsumer::consumeBool(JSonContainer *parent, std::stringstream &buf, char firstChar)
  178. {
  179. size_t read =1;
  180. buf.str("");
  181. buf.clear();
  182. buf.write(&firstChar, 1);
  183. //TODO batch-get 3 char, then do that
  184. while (stream.good())
  185. {
  186. char c = stream.get();
  187. history.put(c);
  188. if (c == 'a' || c == 'e' || c == 'l' || c == 'r' || c == 's' || c == 'u')
  189. {
  190. if ((read >= 5 && firstChar == 'f') || (read >= 4 && firstChar == 't'))
  191. throw JsonFormatException(stream.tellg(), history);
  192. buf.write(&c, 1);
  193. read++;
  194. }
  195. else if (buf.str() == "true")
  196. {
  197. history.pop_back();
  198. stream.unget();
  199. return new JSonPrimitive<bool>(parent, true);
  200. }
  201. else if (buf.str() == "false")
  202. {
  203. history.pop_back();
  204. stream.unget();
  205. return new JSonPrimitive<bool>(parent, false);
  206. }
  207. else if (ignoreChar(c))
  208. ;
  209. else
  210. throw JsonFormatException(stream.tellg(), history);
  211. }
  212. buf.str("");
  213. buf.clear();
  214. return nullptr;
  215. }
  216. JSonElement *StreamConsumer::consumeNumber(JSonContainer *parent, std::stringstream &buf, char firstChar)
  217. {
  218. bool numberIsDouble = false;
  219. buf.str("");
  220. buf.clear();
  221. buf.write(&firstChar, 1);
  222. while (stream.good())
  223. {
  224. char c = stream.get();
  225. history.put(c);
  226. if (c >= '0' && c <= '9')
  227. buf.write(&c, 1);
  228. else if (c == '.' && !numberIsDouble)
  229. {
  230. numberIsDouble = true;
  231. buf.write(&c, 1);
  232. }
  233. else
  234. {
  235. history.pop_back();
  236. stream.unget();
  237. if (numberIsDouble)
  238. {
  239. try {
  240. return new JSonPrimitive<double>(parent, atof(buf.str().c_str()));
  241. } catch (std::runtime_error &e)
  242. {
  243. throw JsonFormatException(stream.tellg(), history);
  244. }
  245. }
  246. try
  247. {
  248. return new JSonPrimitive<int>(parent, std::stoi(buf.str()));
  249. }
  250. catch(std::out_of_range e)
  251. {
  252. return new JSonPrimitive<long long>(parent, std::stol(buf.str()));
  253. }
  254. }
  255. }
  256. buf.str("");
  257. buf.clear();
  258. return nullptr;
  259. }
  260. JSonElement *StreamConsumer::consumeNull(JSonContainer *parent, std::stringstream &buf)
  261. {
  262. char _buf[5] = { 'n', '\0', '\0', '\0', '\0' };
  263. buf.str("");
  264. buf.clear();
  265. stream.read(&_buf[1], 3);
  266. buf.write(_buf, 4);
  267. history.put(&_buf[1], 3);
  268. if (!stream.good())
  269. {
  270. buf.str("");
  271. buf.clear();
  272. return nullptr;
  273. }
  274. if (std::string("null") == _buf)
  275. return new JSonPrimitive<Null>(parent, Null());
  276. throw JsonFormatException(stream.tellg(), history);
  277. }
  278. JSonElement *StreamConsumer::consumeToken(JSonContainer *parent, std::stringstream &buf)
  279. {
  280. while (stream.good())
  281. {
  282. char c = stream.get();
  283. history.put(c);
  284. //!InString, !inbool
  285. if (c == '"')
  286. return consumeString(parent, buf);
  287. else if (c == 't' || c == 'f')
  288. return consumeBool(parent, buf, c);
  289. else if (c == 'n')
  290. return consumeNull(parent, buf);
  291. else if ((c >= '0' && c <= '9') || c == '.' || c == '-')
  292. return consumeNumber(parent, buf, c);
  293. else if (c == '{' || c == '[' || c == '}' || c == ']' || c == ':' || c == ',')
  294. {
  295. buf.str("");
  296. buf.clear();
  297. buf.write(&c, 1);
  298. return nullptr;
  299. }
  300. else if (!ignoreChar(c))
  301. throw JsonFormatException(stream.tellg(), history);
  302. }
  303. buf.str("");
  304. buf.clear();
  305. return nullptr;
  306. }
  307. static unsigned char hexbyte(const char c)
  308. {
  309. if (c >= '0' && c <= '9')
  310. return c - '0';
  311. if (c >= 'A' && c <= 'F')
  312. return c - 'A' + 10;
  313. if (c >= 'a' && c <= 'f')
  314. return c - 'a' + 10;
  315. throw std::invalid_argument(JsonHexvalueException::msg(c));
  316. }
  317. template<typename T>
  318. static T hexbyte(const char str[], unsigned int len)
  319. {
  320. T result = 0;
  321. for (unsigned int i =0; i < len; ++i)
  322. result = (result << 4) + hexbyte(str[i]);
  323. return result;
  324. }
  325. void StreamConsumer::appendUnicode(const char unicode[4], std::stringstream &buf)
  326. {
  327. unsigned short uni = hexbyte<unsigned short>(unicode, 4);
  328. char test[5];
  329. bzero(test, sizeof(*test) *5);
  330. snprintf(test, 4, "%lc", uni);
  331. buf.write(test, 4);
  332. }
  333. std::string StreamConsumer::extractUnicode(const char *buf)
  334. {
  335. std::stringstream result;
  336. for (; *buf; buf++)
  337. {
  338. if (*buf == '\\' && buf[1] == 'u' && buf[2] && buf[3] && buf[4] && buf[5])
  339. {
  340. appendUnicode(buf +2, result);
  341. buf += 6;
  342. }
  343. else
  344. result.write(buf, 1);
  345. }
  346. return result.str();
  347. }
  348. std::string StreamConsumer::extractUnicode(const std::string &buf)
  349. {
  350. return extractUnicode(buf.c_str());
  351. }
  352. bool StreamConsumer::ignoreChar(char c) const noexcept
  353. {
  354. return (c <= 32 || c >= 127 || c == '\n');
  355. }
  356. const std::list<Warning> &StreamConsumer::getMessages() const
  357. { return warnings; }