printer.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. /*
  2. ** This currently uses snprintf() to format primitives, and could be optimized
  3. ** further.
  4. */
  5. #include "upb/json/printer.h"
  6. #include <ctype.h>
  7. #include <inttypes.h>
  8. #include <stdint.h>
  9. #include <string.h>
  10. #include <time.h>
  11. #include "upb/port_def.inc"
  12. struct upb_json_printer {
  13. upb_sink input_;
  14. /* BytesSink closure. */
  15. void *subc_;
  16. upb_bytessink output_;
  17. /* We track the depth so that we know when to emit startstr/endstr on the
  18. * output. */
  19. int depth_;
  20. /* Have we emitted the first element? This state is necessary to emit commas
  21. * without leaving a trailing comma in arrays/maps. We keep this state per
  22. * frame depth.
  23. *
  24. * Why max_depth * 2? UPB_MAX_HANDLER_DEPTH counts depth as nested messages.
  25. * We count frames (contexts in which we separate elements by commas) as both
  26. * repeated fields and messages (maps), and the worst case is a
  27. * message->repeated field->submessage->repeated field->... nesting. */
  28. bool first_elem_[UPB_MAX_HANDLER_DEPTH * 2];
  29. /* To print timestamp, printer needs to cache its seconds and nanos values
  30. * and convert them when ending timestamp message. See comments of
  31. * printer_sethandlers_timestamp for more detail. */
  32. int64_t seconds;
  33. int32_t nanos;
  34. };
  35. /* StringPiece; a pointer plus a length. */
  36. typedef struct {
  37. char *ptr;
  38. size_t len;
  39. } strpc;
  40. void freestrpc(void *ptr) {
  41. strpc *pc = ptr;
  42. upb_gfree(pc->ptr);
  43. upb_gfree(pc);
  44. }
  45. typedef struct {
  46. bool preserve_fieldnames;
  47. } upb_json_printercache;
  48. /* Convert fielddef name to JSON name and return as a string piece. */
  49. strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
  50. bool preserve_fieldnames) {
  51. /* TODO(haberman): handle malloc failure. */
  52. strpc *ret = upb_gmalloc(sizeof(*ret));
  53. if (preserve_fieldnames) {
  54. ret->ptr = upb_gstrdup(upb_fielddef_name(f));
  55. ret->len = strlen(ret->ptr);
  56. } else {
  57. size_t len;
  58. ret->len = upb_fielddef_getjsonname(f, NULL, 0);
  59. ret->ptr = upb_gmalloc(ret->len);
  60. len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
  61. UPB_ASSERT(len == ret->len);
  62. ret->len--; /* NULL */
  63. }
  64. upb_handlers_addcleanup(h, ret, freestrpc);
  65. return ret;
  66. }
  67. /* Convert a null-terminated const char* to a string piece. */
  68. strpc *newstrpc_str(upb_handlers *h, const char * str) {
  69. strpc * ret = upb_gmalloc(sizeof(*ret));
  70. ret->ptr = upb_gstrdup(str);
  71. ret->len = strlen(str);
  72. upb_handlers_addcleanup(h, ret, freestrpc);
  73. return ret;
  74. }
  75. /* ------------ JSON string printing: values, maps, arrays ------------------ */
  76. static void print_data(
  77. upb_json_printer *p, const char *buf, unsigned int len) {
  78. /* TODO: Will need to change if we support pushback from the sink. */
  79. size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
  80. UPB_ASSERT(n == len);
  81. }
  82. static void print_comma(upb_json_printer *p) {
  83. if (!p->first_elem_[p->depth_]) {
  84. print_data(p, ",", 1);
  85. }
  86. p->first_elem_[p->depth_] = false;
  87. }
  88. /* Helpers that print properly formatted elements to the JSON output stream. */
  89. /* Used for escaping control chars in strings. */
  90. static const char kControlCharLimit = 0x20;
  91. UPB_INLINE bool is_json_escaped(char c) {
  92. /* See RFC 4627. */
  93. unsigned char uc = (unsigned char)c;
  94. return uc < kControlCharLimit || uc == '"' || uc == '\\';
  95. }
  96. UPB_INLINE const char* json_nice_escape(char c) {
  97. switch (c) {
  98. case '"': return "\\\"";
  99. case '\\': return "\\\\";
  100. case '\b': return "\\b";
  101. case '\f': return "\\f";
  102. case '\n': return "\\n";
  103. case '\r': return "\\r";
  104. case '\t': return "\\t";
  105. default: return NULL;
  106. }
  107. }
  108. /* Write a properly escaped string chunk. The surrounding quotes are *not*
  109. * printed; this is so that the caller has the option of emitting the string
  110. * content in chunks. */
  111. static void putstring(upb_json_printer *p, const char *buf, unsigned int len) {
  112. const char* unescaped_run = NULL;
  113. unsigned int i;
  114. for (i = 0; i < len; i++) {
  115. char c = buf[i];
  116. /* Handle escaping. */
  117. if (is_json_escaped(c)) {
  118. /* Use a "nice" escape, like \n, if one exists for this character. */
  119. const char* escape = json_nice_escape(c);
  120. /* If we don't have a specific 'nice' escape code, use a \uXXXX-style
  121. * escape. */
  122. char escape_buf[8];
  123. if (!escape) {
  124. unsigned char byte = (unsigned char)c;
  125. _upb_snprintf(escape_buf, sizeof(escape_buf), "\\u%04x", (int)byte);
  126. escape = escape_buf;
  127. }
  128. /* N.B. that we assume that the input encoding is equal to the output
  129. * encoding (both UTF-8 for now), so for chars >= 0x20 and != \, ", we
  130. * can simply pass the bytes through. */
  131. /* If there's a current run of unescaped chars, print that run first. */
  132. if (unescaped_run) {
  133. print_data(p, unescaped_run, &buf[i] - unescaped_run);
  134. unescaped_run = NULL;
  135. }
  136. /* Then print the escape code. */
  137. print_data(p, escape, strlen(escape));
  138. } else {
  139. /* Add to the current unescaped run of characters. */
  140. if (unescaped_run == NULL) {
  141. unescaped_run = &buf[i];
  142. }
  143. }
  144. }
  145. /* If the string ended in a run of unescaped characters, print that last run. */
  146. if (unescaped_run) {
  147. print_data(p, unescaped_run, &buf[len] - unescaped_run);
  148. }
  149. }
  150. #define CHKLENGTH(x) if (!(x)) return -1;
  151. /* Helpers that format floating point values according to our custom formats.
  152. * Right now we use %.8g and %.17g for float/double, respectively, to match
  153. * proto2::util::JsonFormat's defaults. May want to change this later. */
  154. const char neginf[] = "\"-Infinity\"";
  155. const char inf[] = "\"Infinity\"";
  156. static size_t fmt_double(double val, char* buf, size_t length) {
  157. if (val == UPB_INFINITY) {
  158. CHKLENGTH(length >= strlen(inf));
  159. strcpy(buf, inf);
  160. return strlen(inf);
  161. } else if (val == -UPB_INFINITY) {
  162. CHKLENGTH(length >= strlen(neginf));
  163. strcpy(buf, neginf);
  164. return strlen(neginf);
  165. } else {
  166. size_t n = _upb_snprintf(buf, length, "%.17g", val);
  167. CHKLENGTH(n > 0 && n < length);
  168. return n;
  169. }
  170. }
  171. static size_t fmt_float(float val, char* buf, size_t length) {
  172. size_t n = _upb_snprintf(buf, length, "%.8g", val);
  173. CHKLENGTH(n > 0 && n < length);
  174. return n;
  175. }
  176. static size_t fmt_bool(bool val, char* buf, size_t length) {
  177. size_t n = _upb_snprintf(buf, length, "%s", (val ? "true" : "false"));
  178. CHKLENGTH(n > 0 && n < length);
  179. return n;
  180. }
  181. static size_t fmt_int64_as_number(int64_t val, char* buf, size_t length) {
  182. size_t n = _upb_snprintf(buf, length, "%" PRId64, val);
  183. CHKLENGTH(n > 0 && n < length);
  184. return n;
  185. }
  186. static size_t fmt_uint64_as_number(uint64_t val, char* buf, size_t length) {
  187. size_t n = _upb_snprintf(buf, length, "%" PRIu64, val);
  188. CHKLENGTH(n > 0 && n < length);
  189. return n;
  190. }
  191. static size_t fmt_int64_as_string(int64_t val, char* buf, size_t length) {
  192. size_t n = _upb_snprintf(buf, length, "\"%" PRId64 "\"", val);
  193. CHKLENGTH(n > 0 && n < length);
  194. return n;
  195. }
  196. static size_t fmt_uint64_as_string(uint64_t val, char* buf, size_t length) {
  197. size_t n = _upb_snprintf(buf, length, "\"%" PRIu64 "\"", val);
  198. CHKLENGTH(n > 0 && n < length);
  199. return n;
  200. }
  201. /* Print a map key given a field name. Called by scalar field handlers and by
  202. * startseq for repeated fields. */
  203. static bool putkey(void *closure, const void *handler_data) {
  204. upb_json_printer *p = closure;
  205. const strpc *key = handler_data;
  206. print_comma(p);
  207. print_data(p, "\"", 1);
  208. putstring(p, key->ptr, key->len);
  209. print_data(p, "\":", 2);
  210. return true;
  211. }
  212. #define CHKFMT(val) if ((val) == (size_t)-1) return false;
  213. #define CHK(val) if (!(val)) return false;
  214. #define TYPE_HANDLERS(type, fmt_func) \
  215. static bool put##type(void *closure, const void *handler_data, type val) { \
  216. upb_json_printer *p = closure; \
  217. char data[64]; \
  218. size_t length = fmt_func(val, data, sizeof(data)); \
  219. UPB_UNUSED(handler_data); \
  220. CHKFMT(length); \
  221. print_data(p, data, length); \
  222. return true; \
  223. } \
  224. static bool scalar_##type(void *closure, const void *handler_data, \
  225. type val) { \
  226. CHK(putkey(closure, handler_data)); \
  227. CHK(put##type(closure, handler_data, val)); \
  228. return true; \
  229. } \
  230. static bool repeated_##type(void *closure, const void *handler_data, \
  231. type val) { \
  232. upb_json_printer *p = closure; \
  233. print_comma(p); \
  234. CHK(put##type(closure, handler_data, val)); \
  235. return true; \
  236. }
  237. #define TYPE_HANDLERS_MAPKEY(type, fmt_func) \
  238. static bool putmapkey_##type(void *closure, const void *handler_data, \
  239. type val) { \
  240. upb_json_printer *p = closure; \
  241. char data[64]; \
  242. size_t length = fmt_func(val, data, sizeof(data)); \
  243. UPB_UNUSED(handler_data); \
  244. print_data(p, "\"", 1); \
  245. print_data(p, data, length); \
  246. print_data(p, "\":", 2); \
  247. return true; \
  248. }
  249. TYPE_HANDLERS(double, fmt_double)
  250. TYPE_HANDLERS(float, fmt_float)
  251. TYPE_HANDLERS(bool, fmt_bool)
  252. TYPE_HANDLERS(int32_t, fmt_int64_as_number)
  253. TYPE_HANDLERS(uint32_t, fmt_int64_as_number)
  254. TYPE_HANDLERS(int64_t, fmt_int64_as_string)
  255. TYPE_HANDLERS(uint64_t, fmt_uint64_as_string)
  256. /* double and float are not allowed to be map keys. */
  257. TYPE_HANDLERS_MAPKEY(bool, fmt_bool)
  258. TYPE_HANDLERS_MAPKEY(int32_t, fmt_int64_as_number)
  259. TYPE_HANDLERS_MAPKEY(uint32_t, fmt_int64_as_number)
  260. TYPE_HANDLERS_MAPKEY(int64_t, fmt_int64_as_number)
  261. TYPE_HANDLERS_MAPKEY(uint64_t, fmt_uint64_as_number)
  262. #undef TYPE_HANDLERS
  263. #undef TYPE_HANDLERS_MAPKEY
  264. typedef struct {
  265. void *keyname;
  266. const upb_enumdef *enumdef;
  267. } EnumHandlerData;
  268. static bool scalar_enum(void *closure, const void *handler_data,
  269. int32_t val) {
  270. const EnumHandlerData *hd = handler_data;
  271. upb_json_printer *p = closure;
  272. const char *symbolic_name;
  273. CHK(putkey(closure, hd->keyname));
  274. symbolic_name = upb_enumdef_iton(hd->enumdef, val);
  275. if (symbolic_name) {
  276. print_data(p, "\"", 1);
  277. putstring(p, symbolic_name, strlen(symbolic_name));
  278. print_data(p, "\"", 1);
  279. } else {
  280. putint32_t(closure, NULL, val);
  281. }
  282. return true;
  283. }
  284. static void print_enum_symbolic_name(upb_json_printer *p,
  285. const upb_enumdef *def,
  286. int32_t val) {
  287. const char *symbolic_name = upb_enumdef_iton(def, val);
  288. if (symbolic_name) {
  289. print_data(p, "\"", 1);
  290. putstring(p, symbolic_name, strlen(symbolic_name));
  291. print_data(p, "\"", 1);
  292. } else {
  293. putint32_t(p, NULL, val);
  294. }
  295. }
  296. static bool repeated_enum(void *closure, const void *handler_data,
  297. int32_t val) {
  298. const EnumHandlerData *hd = handler_data;
  299. upb_json_printer *p = closure;
  300. print_comma(p);
  301. print_enum_symbolic_name(p, hd->enumdef, val);
  302. return true;
  303. }
  304. static bool mapvalue_enum(void *closure, const void *handler_data,
  305. int32_t val) {
  306. const EnumHandlerData *hd = handler_data;
  307. upb_json_printer *p = closure;
  308. print_enum_symbolic_name(p, hd->enumdef, val);
  309. return true;
  310. }
  311. static void *scalar_startsubmsg(void *closure, const void *handler_data) {
  312. return putkey(closure, handler_data) ? closure : UPB_BREAK;
  313. }
  314. static void *repeated_startsubmsg(void *closure, const void *handler_data) {
  315. upb_json_printer *p = closure;
  316. UPB_UNUSED(handler_data);
  317. print_comma(p);
  318. return closure;
  319. }
  320. static void start_frame(upb_json_printer *p) {
  321. p->depth_++;
  322. p->first_elem_[p->depth_] = true;
  323. print_data(p, "{", 1);
  324. }
  325. static void end_frame(upb_json_printer *p) {
  326. print_data(p, "}", 1);
  327. p->depth_--;
  328. }
  329. static bool printer_startmsg(void *closure, const void *handler_data) {
  330. upb_json_printer *p = closure;
  331. UPB_UNUSED(handler_data);
  332. if (p->depth_ == 0) {
  333. upb_bytessink_start(p->output_, 0, &p->subc_);
  334. }
  335. start_frame(p);
  336. return true;
  337. }
  338. static bool printer_endmsg(void *closure, const void *handler_data, upb_status *s) {
  339. upb_json_printer *p = closure;
  340. UPB_UNUSED(handler_data);
  341. UPB_UNUSED(s);
  342. end_frame(p);
  343. if (p->depth_ == 0) {
  344. upb_bytessink_end(p->output_);
  345. }
  346. return true;
  347. }
  348. static void *startseq(void *closure, const void *handler_data) {
  349. upb_json_printer *p = closure;
  350. CHK(putkey(closure, handler_data));
  351. p->depth_++;
  352. p->first_elem_[p->depth_] = true;
  353. print_data(p, "[", 1);
  354. return closure;
  355. }
  356. static bool endseq(void *closure, const void *handler_data) {
  357. upb_json_printer *p = closure;
  358. UPB_UNUSED(handler_data);
  359. print_data(p, "]", 1);
  360. p->depth_--;
  361. return true;
  362. }
  363. static void *startmap(void *closure, const void *handler_data) {
  364. upb_json_printer *p = closure;
  365. CHK(putkey(closure, handler_data));
  366. p->depth_++;
  367. p->first_elem_[p->depth_] = true;
  368. print_data(p, "{", 1);
  369. return closure;
  370. }
  371. static bool endmap(void *closure, const void *handler_data) {
  372. upb_json_printer *p = closure;
  373. UPB_UNUSED(handler_data);
  374. print_data(p, "}", 1);
  375. p->depth_--;
  376. return true;
  377. }
  378. static size_t putstr(void *closure, const void *handler_data, const char *str,
  379. size_t len, const upb_bufhandle *handle) {
  380. upb_json_printer *p = closure;
  381. UPB_UNUSED(handler_data);
  382. UPB_UNUSED(handle);
  383. putstring(p, str, len);
  384. return len;
  385. }
  386. /* This has to Base64 encode the bytes, because JSON has no "bytes" type. */
  387. static size_t putbytes(void *closure, const void *handler_data, const char *str,
  388. size_t len, const upb_bufhandle *handle) {
  389. upb_json_printer *p = closure;
  390. /* This is the regular base64, not the "web-safe" version. */
  391. static const char base64[] =
  392. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  393. /* Base64-encode. */
  394. char data[16000];
  395. const char *limit = data + sizeof(data);
  396. const unsigned char *from = (const unsigned char*)str;
  397. char *to = data;
  398. size_t remaining = len;
  399. size_t bytes;
  400. UPB_UNUSED(handler_data);
  401. UPB_UNUSED(handle);
  402. print_data(p, "\"", 1);
  403. while (remaining > 2) {
  404. if (limit - to < 4) {
  405. bytes = to - data;
  406. putstring(p, data, bytes);
  407. to = data;
  408. }
  409. to[0] = base64[from[0] >> 2];
  410. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  411. to[2] = base64[((from[1] & 0xf) << 2) | (from[2] >> 6)];
  412. to[3] = base64[from[2] & 0x3f];
  413. remaining -= 3;
  414. to += 4;
  415. from += 3;
  416. }
  417. switch (remaining) {
  418. case 2:
  419. to[0] = base64[from[0] >> 2];
  420. to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
  421. to[2] = base64[(from[1] & 0xf) << 2];
  422. to[3] = '=';
  423. to += 4;
  424. from += 2;
  425. break;
  426. case 1:
  427. to[0] = base64[from[0] >> 2];
  428. to[1] = base64[((from[0] & 0x3) << 4)];
  429. to[2] = '=';
  430. to[3] = '=';
  431. to += 4;
  432. from += 1;
  433. break;
  434. }
  435. bytes = to - data;
  436. putstring(p, data, bytes);
  437. print_data(p, "\"", 1);
  438. return len;
  439. }
  440. static void *scalar_startstr(void *closure, const void *handler_data,
  441. size_t size_hint) {
  442. upb_json_printer *p = closure;
  443. UPB_UNUSED(handler_data);
  444. UPB_UNUSED(size_hint);
  445. CHK(putkey(closure, handler_data));
  446. print_data(p, "\"", 1);
  447. return p;
  448. }
  449. static size_t scalar_str(void *closure, const void *handler_data,
  450. const char *str, size_t len,
  451. const upb_bufhandle *handle) {
  452. CHK(putstr(closure, handler_data, str, len, handle));
  453. return len;
  454. }
  455. static bool scalar_endstr(void *closure, const void *handler_data) {
  456. upb_json_printer *p = closure;
  457. UPB_UNUSED(handler_data);
  458. print_data(p, "\"", 1);
  459. return true;
  460. }
  461. static void *repeated_startstr(void *closure, const void *handler_data,
  462. size_t size_hint) {
  463. upb_json_printer *p = closure;
  464. UPB_UNUSED(handler_data);
  465. UPB_UNUSED(size_hint);
  466. print_comma(p);
  467. print_data(p, "\"", 1);
  468. return p;
  469. }
  470. static size_t repeated_str(void *closure, const void *handler_data,
  471. const char *str, size_t len,
  472. const upb_bufhandle *handle) {
  473. CHK(putstr(closure, handler_data, str, len, handle));
  474. return len;
  475. }
  476. static bool repeated_endstr(void *closure, const void *handler_data) {
  477. upb_json_printer *p = closure;
  478. UPB_UNUSED(handler_data);
  479. print_data(p, "\"", 1);
  480. return true;
  481. }
  482. static void *mapkeyval_startstr(void *closure, const void *handler_data,
  483. size_t size_hint) {
  484. upb_json_printer *p = closure;
  485. UPB_UNUSED(handler_data);
  486. UPB_UNUSED(size_hint);
  487. print_data(p, "\"", 1);
  488. return p;
  489. }
  490. static size_t mapkey_str(void *closure, const void *handler_data,
  491. const char *str, size_t len,
  492. const upb_bufhandle *handle) {
  493. CHK(putstr(closure, handler_data, str, len, handle));
  494. return len;
  495. }
  496. static bool mapkey_endstr(void *closure, const void *handler_data) {
  497. upb_json_printer *p = closure;
  498. UPB_UNUSED(handler_data);
  499. print_data(p, "\":", 2);
  500. return true;
  501. }
  502. static bool mapvalue_endstr(void *closure, const void *handler_data) {
  503. upb_json_printer *p = closure;
  504. UPB_UNUSED(handler_data);
  505. print_data(p, "\"", 1);
  506. return true;
  507. }
  508. static size_t scalar_bytes(void *closure, const void *handler_data,
  509. const char *str, size_t len,
  510. const upb_bufhandle *handle) {
  511. CHK(putkey(closure, handler_data));
  512. CHK(putbytes(closure, handler_data, str, len, handle));
  513. return len;
  514. }
  515. static size_t repeated_bytes(void *closure, const void *handler_data,
  516. const char *str, size_t len,
  517. const upb_bufhandle *handle) {
  518. upb_json_printer *p = closure;
  519. print_comma(p);
  520. CHK(putbytes(closure, handler_data, str, len, handle));
  521. return len;
  522. }
  523. static size_t mapkey_bytes(void *closure, const void *handler_data,
  524. const char *str, size_t len,
  525. const upb_bufhandle *handle) {
  526. upb_json_printer *p = closure;
  527. CHK(putbytes(closure, handler_data, str, len, handle));
  528. print_data(p, ":", 1);
  529. return len;
  530. }
  531. static void set_enum_hd(upb_handlers *h,
  532. const upb_fielddef *f,
  533. bool preserve_fieldnames,
  534. upb_handlerattr *attr) {
  535. EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
  536. hd->enumdef = upb_fielddef_enumsubdef(f);
  537. hd->keyname = newstrpc(h, f, preserve_fieldnames);
  538. upb_handlers_addcleanup(h, hd, upb_gfree);
  539. attr->handler_data = hd;
  540. }
  541. /* Set up handlers for a mapentry submessage (i.e., an individual key/value pair
  542. * in a map).
  543. *
  544. * TODO: Handle missing key, missing value, out-of-order key/value, or repeated
  545. * key or value cases properly. The right way to do this is to allocate a
  546. * temporary structure at the start of a mapentry submessage, store key and
  547. * value data in it as key and value handlers are called, and then print the
  548. * key/value pair once at the end of the submessage. If we don't do this, we
  549. * should at least detect the case and throw an error. However, so far all of
  550. * our sources that emit mapentry messages do so canonically (with one key
  551. * field, and then one value field), so this is not a pressing concern at the
  552. * moment. */
  553. void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
  554. upb_handlers *h) {
  555. const upb_msgdef *md = upb_handlers_msgdef(h);
  556. /* A mapentry message is printed simply as '"key": value'. Rather than
  557. * special-case key and value for every type below, we just handle both
  558. * fields explicitly here. */
  559. const upb_fielddef* key_field = upb_msgdef_itof(md, UPB_MAPENTRY_KEY);
  560. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_MAPENTRY_VALUE);
  561. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  562. UPB_UNUSED(closure);
  563. switch (upb_fielddef_type(key_field)) {
  564. case UPB_TYPE_INT32:
  565. upb_handlers_setint32(h, key_field, putmapkey_int32_t, &empty_attr);
  566. break;
  567. case UPB_TYPE_INT64:
  568. upb_handlers_setint64(h, key_field, putmapkey_int64_t, &empty_attr);
  569. break;
  570. case UPB_TYPE_UINT32:
  571. upb_handlers_setuint32(h, key_field, putmapkey_uint32_t, &empty_attr);
  572. break;
  573. case UPB_TYPE_UINT64:
  574. upb_handlers_setuint64(h, key_field, putmapkey_uint64_t, &empty_attr);
  575. break;
  576. case UPB_TYPE_BOOL:
  577. upb_handlers_setbool(h, key_field, putmapkey_bool, &empty_attr);
  578. break;
  579. case UPB_TYPE_STRING:
  580. upb_handlers_setstartstr(h, key_field, mapkeyval_startstr, &empty_attr);
  581. upb_handlers_setstring(h, key_field, mapkey_str, &empty_attr);
  582. upb_handlers_setendstr(h, key_field, mapkey_endstr, &empty_attr);
  583. break;
  584. case UPB_TYPE_BYTES:
  585. upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
  586. break;
  587. default:
  588. UPB_ASSERT(false);
  589. break;
  590. }
  591. switch (upb_fielddef_type(value_field)) {
  592. case UPB_TYPE_INT32:
  593. upb_handlers_setint32(h, value_field, putint32_t, &empty_attr);
  594. break;
  595. case UPB_TYPE_INT64:
  596. upb_handlers_setint64(h, value_field, putint64_t, &empty_attr);
  597. break;
  598. case UPB_TYPE_UINT32:
  599. upb_handlers_setuint32(h, value_field, putuint32_t, &empty_attr);
  600. break;
  601. case UPB_TYPE_UINT64:
  602. upb_handlers_setuint64(h, value_field, putuint64_t, &empty_attr);
  603. break;
  604. case UPB_TYPE_BOOL:
  605. upb_handlers_setbool(h, value_field, putbool, &empty_attr);
  606. break;
  607. case UPB_TYPE_FLOAT:
  608. upb_handlers_setfloat(h, value_field, putfloat, &empty_attr);
  609. break;
  610. case UPB_TYPE_DOUBLE:
  611. upb_handlers_setdouble(h, value_field, putdouble, &empty_attr);
  612. break;
  613. case UPB_TYPE_STRING:
  614. upb_handlers_setstartstr(h, value_field, mapkeyval_startstr, &empty_attr);
  615. upb_handlers_setstring(h, value_field, putstr, &empty_attr);
  616. upb_handlers_setendstr(h, value_field, mapvalue_endstr, &empty_attr);
  617. break;
  618. case UPB_TYPE_BYTES:
  619. upb_handlers_setstring(h, value_field, putbytes, &empty_attr);
  620. break;
  621. case UPB_TYPE_ENUM: {
  622. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  623. set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
  624. upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
  625. break;
  626. }
  627. case UPB_TYPE_MESSAGE:
  628. /* No handler necessary -- the submsg handlers will print the message
  629. * as appropriate. */
  630. break;
  631. }
  632. }
  633. static bool putseconds(void *closure, const void *handler_data,
  634. int64_t seconds) {
  635. upb_json_printer *p = closure;
  636. p->seconds = seconds;
  637. UPB_UNUSED(handler_data);
  638. return true;
  639. }
  640. static bool putnanos(void *closure, const void *handler_data,
  641. int32_t nanos) {
  642. upb_json_printer *p = closure;
  643. p->nanos = nanos;
  644. UPB_UNUSED(handler_data);
  645. return true;
  646. }
  647. static void *scalar_startstr_nokey(void *closure, const void *handler_data,
  648. size_t size_hint) {
  649. upb_json_printer *p = closure;
  650. UPB_UNUSED(handler_data);
  651. UPB_UNUSED(size_hint);
  652. print_data(p, "\"", 1);
  653. return p;
  654. }
  655. static size_t putstr_nokey(void *closure, const void *handler_data,
  656. const char *str, size_t len,
  657. const upb_bufhandle *handle) {
  658. upb_json_printer *p = closure;
  659. UPB_UNUSED(handler_data);
  660. UPB_UNUSED(handle);
  661. print_data(p, "\"", 1);
  662. putstring(p, str, len);
  663. print_data(p, "\"", 1);
  664. return len + 2;
  665. }
  666. static void *startseq_nokey(void *closure, const void *handler_data) {
  667. upb_json_printer *p = closure;
  668. UPB_UNUSED(handler_data);
  669. p->depth_++;
  670. p->first_elem_[p->depth_] = true;
  671. print_data(p, "[", 1);
  672. return closure;
  673. }
  674. static void *startseq_fieldmask(void *closure, const void *handler_data) {
  675. upb_json_printer *p = closure;
  676. UPB_UNUSED(handler_data);
  677. p->depth_++;
  678. p->first_elem_[p->depth_] = true;
  679. return closure;
  680. }
  681. static bool endseq_fieldmask(void *closure, const void *handler_data) {
  682. upb_json_printer *p = closure;
  683. UPB_UNUSED(handler_data);
  684. p->depth_--;
  685. return true;
  686. }
  687. static void *repeated_startstr_fieldmask(
  688. void *closure, const void *handler_data,
  689. size_t size_hint) {
  690. upb_json_printer *p = closure;
  691. UPB_UNUSED(handler_data);
  692. UPB_UNUSED(size_hint);
  693. print_comma(p);
  694. return p;
  695. }
  696. static size_t repeated_str_fieldmask(
  697. void *closure, const void *handler_data,
  698. const char *str, size_t len,
  699. const upb_bufhandle *handle) {
  700. const char* limit = str + len;
  701. bool upper = false;
  702. size_t result_len = 0;
  703. for (; str < limit; str++) {
  704. if (*str == '_') {
  705. upper = true;
  706. continue;
  707. }
  708. if (upper && *str >= 'a' && *str <= 'z') {
  709. char upper_char = toupper(*str);
  710. CHK(putstr(closure, handler_data, &upper_char, 1, handle));
  711. } else {
  712. CHK(putstr(closure, handler_data, str, 1, handle));
  713. }
  714. upper = false;
  715. result_len++;
  716. }
  717. return result_len;
  718. }
  719. static void *startmap_nokey(void *closure, const void *handler_data) {
  720. upb_json_printer *p = closure;
  721. UPB_UNUSED(handler_data);
  722. p->depth_++;
  723. p->first_elem_[p->depth_] = true;
  724. print_data(p, "{", 1);
  725. return closure;
  726. }
  727. static bool putnull(void *closure, const void *handler_data,
  728. int32_t null) {
  729. upb_json_printer *p = closure;
  730. print_data(p, "null", 4);
  731. UPB_UNUSED(handler_data);
  732. UPB_UNUSED(null);
  733. return true;
  734. }
  735. static bool printer_startdurationmsg(void *closure, const void *handler_data) {
  736. upb_json_printer *p = closure;
  737. UPB_UNUSED(handler_data);
  738. if (p->depth_ == 0) {
  739. upb_bytessink_start(p->output_, 0, &p->subc_);
  740. }
  741. return true;
  742. }
  743. #define UPB_DURATION_MAX_JSON_LEN 23
  744. #define UPB_DURATION_MAX_NANO_LEN 9
  745. static bool printer_enddurationmsg(void *closure, const void *handler_data,
  746. upb_status *s) {
  747. upb_json_printer *p = closure;
  748. char buffer[UPB_DURATION_MAX_JSON_LEN];
  749. size_t base_len;
  750. size_t curr;
  751. size_t i;
  752. memset(buffer, 0, UPB_DURATION_MAX_JSON_LEN);
  753. if (p->seconds < -315576000000) {
  754. upb_status_seterrf(s, "error parsing duration: "
  755. "minimum acceptable value is "
  756. "-315576000000");
  757. return false;
  758. }
  759. if (p->seconds > 315576000000) {
  760. upb_status_seterrf(s, "error serializing duration: "
  761. "maximum acceptable value is "
  762. "315576000000");
  763. return false;
  764. }
  765. _upb_snprintf(buffer, sizeof(buffer), "%ld", (long)p->seconds);
  766. base_len = strlen(buffer);
  767. if (p->nanos != 0) {
  768. char nanos_buffer[UPB_DURATION_MAX_NANO_LEN + 3];
  769. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  770. p->nanos / 1000000000.0);
  771. /* Remove trailing 0. */
  772. for (i = UPB_DURATION_MAX_NANO_LEN + 2;
  773. nanos_buffer[i] == '0'; i--) {
  774. nanos_buffer[i] = 0;
  775. }
  776. strcpy(buffer + base_len, nanos_buffer + 1);
  777. }
  778. curr = strlen(buffer);
  779. strcpy(buffer + curr, "s");
  780. p->seconds = 0;
  781. p->nanos = 0;
  782. print_data(p, "\"", 1);
  783. print_data(p, buffer, strlen(buffer));
  784. print_data(p, "\"", 1);
  785. if (p->depth_ == 0) {
  786. upb_bytessink_end(p->output_);
  787. }
  788. UPB_UNUSED(handler_data);
  789. return true;
  790. }
  791. static bool printer_starttimestampmsg(void *closure, const void *handler_data) {
  792. upb_json_printer *p = closure;
  793. UPB_UNUSED(handler_data);
  794. if (p->depth_ == 0) {
  795. upb_bytessink_start(p->output_, 0, &p->subc_);
  796. }
  797. return true;
  798. }
  799. #define UPB_TIMESTAMP_MAX_JSON_LEN 31
  800. #define UPB_TIMESTAMP_BEFORE_NANO_LEN 19
  801. #define UPB_TIMESTAMP_MAX_NANO_LEN 9
  802. static bool printer_endtimestampmsg(void *closure, const void *handler_data,
  803. upb_status *s) {
  804. upb_json_printer *p = closure;
  805. char buffer[UPB_TIMESTAMP_MAX_JSON_LEN];
  806. time_t time = p->seconds;
  807. size_t curr;
  808. size_t i;
  809. size_t year_length =
  810. strftime(buffer, UPB_TIMESTAMP_MAX_JSON_LEN, "%Y", gmtime(&time));
  811. if (p->seconds < -62135596800) {
  812. upb_status_seterrf(s, "error parsing timestamp: "
  813. "minimum acceptable value is "
  814. "0001-01-01T00:00:00Z");
  815. return false;
  816. }
  817. if (p->seconds > 253402300799) {
  818. upb_status_seterrf(s, "error parsing timestamp: "
  819. "maximum acceptable value is "
  820. "9999-12-31T23:59:59Z");
  821. return false;
  822. }
  823. /* strftime doesn't guarantee 4 digits for year. Prepend 0 by ourselves. */
  824. for (i = 0; i < 4 - year_length; i++) {
  825. buffer[i] = '0';
  826. }
  827. strftime(buffer + (4 - year_length), UPB_TIMESTAMP_MAX_JSON_LEN,
  828. "%Y-%m-%dT%H:%M:%S", gmtime(&time));
  829. if (p->nanos != 0) {
  830. char nanos_buffer[UPB_TIMESTAMP_MAX_NANO_LEN + 3];
  831. _upb_snprintf(nanos_buffer, sizeof(nanos_buffer), "%.9f",
  832. p->nanos / 1000000000.0);
  833. /* Remove trailing 0. */
  834. for (i = UPB_TIMESTAMP_MAX_NANO_LEN + 2;
  835. nanos_buffer[i] == '0'; i--) {
  836. nanos_buffer[i] = 0;
  837. }
  838. strcpy(buffer + UPB_TIMESTAMP_BEFORE_NANO_LEN, nanos_buffer + 1);
  839. }
  840. curr = strlen(buffer);
  841. strcpy(buffer + curr, "Z");
  842. p->seconds = 0;
  843. p->nanos = 0;
  844. print_data(p, "\"", 1);
  845. print_data(p, buffer, strlen(buffer));
  846. print_data(p, "\"", 1);
  847. if (p->depth_ == 0) {
  848. upb_bytessink_end(p->output_);
  849. }
  850. UPB_UNUSED(handler_data);
  851. UPB_UNUSED(s);
  852. return true;
  853. }
  854. static bool printer_startmsg_noframe(void *closure, const void *handler_data) {
  855. upb_json_printer *p = closure;
  856. UPB_UNUSED(handler_data);
  857. if (p->depth_ == 0) {
  858. upb_bytessink_start(p->output_, 0, &p->subc_);
  859. }
  860. return true;
  861. }
  862. static bool printer_endmsg_noframe(
  863. void *closure, const void *handler_data, upb_status *s) {
  864. upb_json_printer *p = closure;
  865. UPB_UNUSED(handler_data);
  866. UPB_UNUSED(s);
  867. if (p->depth_ == 0) {
  868. upb_bytessink_end(p->output_);
  869. }
  870. return true;
  871. }
  872. static bool printer_startmsg_fieldmask(
  873. void *closure, const void *handler_data) {
  874. upb_json_printer *p = closure;
  875. UPB_UNUSED(handler_data);
  876. if (p->depth_ == 0) {
  877. upb_bytessink_start(p->output_, 0, &p->subc_);
  878. }
  879. print_data(p, "\"", 1);
  880. return true;
  881. }
  882. static bool printer_endmsg_fieldmask(
  883. void *closure, const void *handler_data, upb_status *s) {
  884. upb_json_printer *p = closure;
  885. UPB_UNUSED(handler_data);
  886. UPB_UNUSED(s);
  887. print_data(p, "\"", 1);
  888. if (p->depth_ == 0) {
  889. upb_bytessink_end(p->output_);
  890. }
  891. return true;
  892. }
  893. static void *scalar_startstr_onlykey(
  894. void *closure, const void *handler_data, size_t size_hint) {
  895. upb_json_printer *p = closure;
  896. UPB_UNUSED(size_hint);
  897. CHK(putkey(closure, handler_data));
  898. return p;
  899. }
  900. /* Set up handlers for an Any submessage. */
  901. void printer_sethandlers_any(const void *closure, upb_handlers *h) {
  902. const upb_msgdef *md = upb_handlers_msgdef(h);
  903. const upb_fielddef* type_field = upb_msgdef_itof(md, UPB_ANY_TYPE);
  904. const upb_fielddef* value_field = upb_msgdef_itof(md, UPB_ANY_VALUE);
  905. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  906. /* type_url's json name is "@type" */
  907. upb_handlerattr type_name_attr = UPB_HANDLERATTR_INIT;
  908. upb_handlerattr value_name_attr = UPB_HANDLERATTR_INIT;
  909. strpc *type_url_json_name = newstrpc_str(h, "@type");
  910. strpc *value_json_name = newstrpc_str(h, "value");
  911. type_name_attr.handler_data = type_url_json_name;
  912. value_name_attr.handler_data = value_json_name;
  913. /* Set up handlers. */
  914. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  915. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  916. upb_handlers_setstartstr(h, type_field, scalar_startstr, &type_name_attr);
  917. upb_handlers_setstring(h, type_field, scalar_str, &empty_attr);
  918. upb_handlers_setendstr(h, type_field, scalar_endstr, &empty_attr);
  919. /* This is not the full and correct JSON encoding for the Any value field. It
  920. * requires further processing by the wrapper code based on the type URL.
  921. */
  922. upb_handlers_setstartstr(h, value_field, scalar_startstr_onlykey,
  923. &value_name_attr);
  924. UPB_UNUSED(closure);
  925. }
  926. /* Set up handlers for a fieldmask submessage. */
  927. void printer_sethandlers_fieldmask(const void *closure, upb_handlers *h) {
  928. const upb_msgdef *md = upb_handlers_msgdef(h);
  929. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  930. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  931. upb_handlers_setstartseq(h, f, startseq_fieldmask, &empty_attr);
  932. upb_handlers_setendseq(h, f, endseq_fieldmask, &empty_attr);
  933. upb_handlers_setstartmsg(h, printer_startmsg_fieldmask, &empty_attr);
  934. upb_handlers_setendmsg(h, printer_endmsg_fieldmask, &empty_attr);
  935. upb_handlers_setstartstr(h, f, repeated_startstr_fieldmask, &empty_attr);
  936. upb_handlers_setstring(h, f, repeated_str_fieldmask, &empty_attr);
  937. UPB_UNUSED(closure);
  938. }
  939. /* Set up handlers for a duration submessage. */
  940. void printer_sethandlers_duration(const void *closure, upb_handlers *h) {
  941. const upb_msgdef *md = upb_handlers_msgdef(h);
  942. const upb_fielddef* seconds_field =
  943. upb_msgdef_itof(md, UPB_DURATION_SECONDS);
  944. const upb_fielddef* nanos_field =
  945. upb_msgdef_itof(md, UPB_DURATION_NANOS);
  946. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  947. upb_handlers_setstartmsg(h, printer_startdurationmsg, &empty_attr);
  948. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  949. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  950. upb_handlers_setendmsg(h, printer_enddurationmsg, &empty_attr);
  951. UPB_UNUSED(closure);
  952. }
  953. /* Set up handlers for a timestamp submessage. Instead of printing fields
  954. * separately, the json representation of timestamp follows RFC 3339 */
  955. void printer_sethandlers_timestamp(const void *closure, upb_handlers *h) {
  956. const upb_msgdef *md = upb_handlers_msgdef(h);
  957. const upb_fielddef* seconds_field =
  958. upb_msgdef_itof(md, UPB_TIMESTAMP_SECONDS);
  959. const upb_fielddef* nanos_field =
  960. upb_msgdef_itof(md, UPB_TIMESTAMP_NANOS);
  961. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  962. upb_handlers_setstartmsg(h, printer_starttimestampmsg, &empty_attr);
  963. upb_handlers_setint64(h, seconds_field, putseconds, &empty_attr);
  964. upb_handlers_setint32(h, nanos_field, putnanos, &empty_attr);
  965. upb_handlers_setendmsg(h, printer_endtimestampmsg, &empty_attr);
  966. UPB_UNUSED(closure);
  967. }
  968. void printer_sethandlers_value(const void *closure, upb_handlers *h) {
  969. const upb_msgdef *md = upb_handlers_msgdef(h);
  970. upb_msg_field_iter i;
  971. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  972. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  973. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  974. upb_msg_field_begin(&i, md);
  975. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  976. const upb_fielddef *f = upb_msg_iter_field(&i);
  977. switch (upb_fielddef_type(f)) {
  978. case UPB_TYPE_ENUM:
  979. upb_handlers_setint32(h, f, putnull, &empty_attr);
  980. break;
  981. case UPB_TYPE_DOUBLE:
  982. upb_handlers_setdouble(h, f, putdouble, &empty_attr);
  983. break;
  984. case UPB_TYPE_STRING:
  985. upb_handlers_setstartstr(h, f, scalar_startstr_nokey, &empty_attr);
  986. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  987. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  988. break;
  989. case UPB_TYPE_BOOL:
  990. upb_handlers_setbool(h, f, putbool, &empty_attr);
  991. break;
  992. case UPB_TYPE_MESSAGE:
  993. break;
  994. default:
  995. UPB_ASSERT(false);
  996. break;
  997. }
  998. }
  999. UPB_UNUSED(closure);
  1000. }
  1001. #define WRAPPER_SETHANDLERS(wrapper, type, putmethod) \
  1002. void printer_sethandlers_##wrapper(const void *closure, upb_handlers *h) { \
  1003. const upb_msgdef *md = upb_handlers_msgdef(h); \
  1004. const upb_fielddef* f = upb_msgdef_itof(md, 1); \
  1005. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT; \
  1006. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr); \
  1007. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr); \
  1008. upb_handlers_set##type(h, f, putmethod, &empty_attr); \
  1009. UPB_UNUSED(closure); \
  1010. }
  1011. WRAPPER_SETHANDLERS(doublevalue, double, putdouble)
  1012. WRAPPER_SETHANDLERS(floatvalue, float, putfloat)
  1013. WRAPPER_SETHANDLERS(int64value, int64, putint64_t)
  1014. WRAPPER_SETHANDLERS(uint64value, uint64, putuint64_t)
  1015. WRAPPER_SETHANDLERS(int32value, int32, putint32_t)
  1016. WRAPPER_SETHANDLERS(uint32value, uint32, putuint32_t)
  1017. WRAPPER_SETHANDLERS(boolvalue, bool, putbool)
  1018. WRAPPER_SETHANDLERS(stringvalue, string, putstr_nokey)
  1019. WRAPPER_SETHANDLERS(bytesvalue, string, putbytes)
  1020. #undef WRAPPER_SETHANDLERS
  1021. void printer_sethandlers_listvalue(const void *closure, upb_handlers *h) {
  1022. const upb_msgdef *md = upb_handlers_msgdef(h);
  1023. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  1024. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  1025. upb_handlers_setstartseq(h, f, startseq_nokey, &empty_attr);
  1026. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  1027. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  1028. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  1029. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  1030. UPB_UNUSED(closure);
  1031. }
  1032. void printer_sethandlers_structvalue(const void *closure, upb_handlers *h) {
  1033. const upb_msgdef *md = upb_handlers_msgdef(h);
  1034. const upb_fielddef* f = upb_msgdef_itof(md, 1);
  1035. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  1036. upb_handlers_setstartseq(h, f, startmap_nokey, &empty_attr);
  1037. upb_handlers_setendseq(h, f, endmap, &empty_attr);
  1038. upb_handlers_setstartmsg(h, printer_startmsg_noframe, &empty_attr);
  1039. upb_handlers_setendmsg(h, printer_endmsg_noframe, &empty_attr);
  1040. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &empty_attr);
  1041. UPB_UNUSED(closure);
  1042. }
  1043. void printer_sethandlers(const void *closure, upb_handlers *h) {
  1044. const upb_msgdef *md = upb_handlers_msgdef(h);
  1045. bool is_mapentry = upb_msgdef_mapentry(md);
  1046. upb_handlerattr empty_attr = UPB_HANDLERATTR_INIT;
  1047. upb_msg_field_iter i;
  1048. const upb_json_printercache *cache = closure;
  1049. const bool preserve_fieldnames = cache->preserve_fieldnames;
  1050. if (is_mapentry) {
  1051. /* mapentry messages are sufficiently different that we handle them
  1052. * separately. */
  1053. printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
  1054. return;
  1055. }
  1056. switch (upb_msgdef_wellknowntype(md)) {
  1057. case UPB_WELLKNOWN_UNSPECIFIED:
  1058. break;
  1059. case UPB_WELLKNOWN_ANY:
  1060. printer_sethandlers_any(closure, h);
  1061. return;
  1062. case UPB_WELLKNOWN_FIELDMASK:
  1063. printer_sethandlers_fieldmask(closure, h);
  1064. return;
  1065. case UPB_WELLKNOWN_DURATION:
  1066. printer_sethandlers_duration(closure, h);
  1067. return;
  1068. case UPB_WELLKNOWN_TIMESTAMP:
  1069. printer_sethandlers_timestamp(closure, h);
  1070. return;
  1071. case UPB_WELLKNOWN_VALUE:
  1072. printer_sethandlers_value(closure, h);
  1073. return;
  1074. case UPB_WELLKNOWN_LISTVALUE:
  1075. printer_sethandlers_listvalue(closure, h);
  1076. return;
  1077. case UPB_WELLKNOWN_STRUCT:
  1078. printer_sethandlers_structvalue(closure, h);
  1079. return;
  1080. #define WRAPPER(wellknowntype, name) \
  1081. case wellknowntype: \
  1082. printer_sethandlers_##name(closure, h); \
  1083. return; \
  1084. WRAPPER(UPB_WELLKNOWN_DOUBLEVALUE, doublevalue);
  1085. WRAPPER(UPB_WELLKNOWN_FLOATVALUE, floatvalue);
  1086. WRAPPER(UPB_WELLKNOWN_INT64VALUE, int64value);
  1087. WRAPPER(UPB_WELLKNOWN_UINT64VALUE, uint64value);
  1088. WRAPPER(UPB_WELLKNOWN_INT32VALUE, int32value);
  1089. WRAPPER(UPB_WELLKNOWN_UINT32VALUE, uint32value);
  1090. WRAPPER(UPB_WELLKNOWN_BOOLVALUE, boolvalue);
  1091. WRAPPER(UPB_WELLKNOWN_STRINGVALUE, stringvalue);
  1092. WRAPPER(UPB_WELLKNOWN_BYTESVALUE, bytesvalue);
  1093. #undef WRAPPER
  1094. }
  1095. upb_handlers_setstartmsg(h, printer_startmsg, &empty_attr);
  1096. upb_handlers_setendmsg(h, printer_endmsg, &empty_attr);
  1097. #define TYPE(type, name, ctype) \
  1098. case type: \
  1099. if (upb_fielddef_isseq(f)) { \
  1100. upb_handlers_set##name(h, f, repeated_##ctype, &empty_attr); \
  1101. } else { \
  1102. upb_handlers_set##name(h, f, scalar_##ctype, &name_attr); \
  1103. } \
  1104. break;
  1105. upb_msg_field_begin(&i, md);
  1106. for(; !upb_msg_field_done(&i); upb_msg_field_next(&i)) {
  1107. const upb_fielddef *f = upb_msg_iter_field(&i);
  1108. upb_handlerattr name_attr = UPB_HANDLERATTR_INIT;
  1109. name_attr.handler_data = newstrpc(h, f, preserve_fieldnames);
  1110. if (upb_fielddef_ismap(f)) {
  1111. upb_handlers_setstartseq(h, f, startmap, &name_attr);
  1112. upb_handlers_setendseq(h, f, endmap, &name_attr);
  1113. } else if (upb_fielddef_isseq(f)) {
  1114. upb_handlers_setstartseq(h, f, startseq, &name_attr);
  1115. upb_handlers_setendseq(h, f, endseq, &empty_attr);
  1116. }
  1117. switch (upb_fielddef_type(f)) {
  1118. TYPE(UPB_TYPE_FLOAT, float, float);
  1119. TYPE(UPB_TYPE_DOUBLE, double, double);
  1120. TYPE(UPB_TYPE_BOOL, bool, bool);
  1121. TYPE(UPB_TYPE_INT32, int32, int32_t);
  1122. TYPE(UPB_TYPE_UINT32, uint32, uint32_t);
  1123. TYPE(UPB_TYPE_INT64, int64, int64_t);
  1124. TYPE(UPB_TYPE_UINT64, uint64, uint64_t);
  1125. case UPB_TYPE_ENUM: {
  1126. /* For now, we always emit symbolic names for enums. We may want an
  1127. * option later to control this behavior, but we will wait for a real
  1128. * need first. */
  1129. upb_handlerattr enum_attr = UPB_HANDLERATTR_INIT;
  1130. set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
  1131. if (upb_fielddef_isseq(f)) {
  1132. upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
  1133. } else {
  1134. upb_handlers_setint32(h, f, scalar_enum, &enum_attr);
  1135. }
  1136. break;
  1137. }
  1138. case UPB_TYPE_STRING:
  1139. if (upb_fielddef_isseq(f)) {
  1140. upb_handlers_setstartstr(h, f, repeated_startstr, &empty_attr);
  1141. upb_handlers_setstring(h, f, repeated_str, &empty_attr);
  1142. upb_handlers_setendstr(h, f, repeated_endstr, &empty_attr);
  1143. } else {
  1144. upb_handlers_setstartstr(h, f, scalar_startstr, &name_attr);
  1145. upb_handlers_setstring(h, f, scalar_str, &empty_attr);
  1146. upb_handlers_setendstr(h, f, scalar_endstr, &empty_attr);
  1147. }
  1148. break;
  1149. case UPB_TYPE_BYTES:
  1150. /* XXX: this doesn't support strings that span buffers yet. The base64
  1151. * encoder will need to be made resumable for this to work properly. */
  1152. if (upb_fielddef_isseq(f)) {
  1153. upb_handlers_setstring(h, f, repeated_bytes, &empty_attr);
  1154. } else {
  1155. upb_handlers_setstring(h, f, scalar_bytes, &name_attr);
  1156. }
  1157. break;
  1158. case UPB_TYPE_MESSAGE:
  1159. if (upb_fielddef_isseq(f)) {
  1160. upb_handlers_setstartsubmsg(h, f, repeated_startsubmsg, &name_attr);
  1161. } else {
  1162. upb_handlers_setstartsubmsg(h, f, scalar_startsubmsg, &name_attr);
  1163. }
  1164. break;
  1165. }
  1166. }
  1167. #undef TYPE
  1168. }
  1169. static void json_printer_reset(upb_json_printer *p) {
  1170. p->depth_ = 0;
  1171. }
  1172. /* Public API *****************************************************************/
  1173. upb_json_printer *upb_json_printer_create(upb_arena *a, const upb_handlers *h,
  1174. upb_bytessink output) {
  1175. #ifndef NDEBUG
  1176. size_t size_before = upb_arena_bytesallocated(a);
  1177. #endif
  1178. upb_json_printer *p = upb_arena_malloc(a, sizeof(upb_json_printer));
  1179. if (!p) return NULL;
  1180. p->output_ = output;
  1181. json_printer_reset(p);
  1182. upb_sink_reset(&p->input_, h, p);
  1183. p->seconds = 0;
  1184. p->nanos = 0;
  1185. /* If this fails, increase the value in printer.h. */
  1186. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(a) - size_before <=
  1187. UPB_JSON_PRINTER_SIZE);
  1188. return p;
  1189. }
  1190. upb_sink upb_json_printer_input(upb_json_printer *p) {
  1191. return p->input_;
  1192. }
  1193. upb_handlercache *upb_json_printer_newcache(bool preserve_proto_fieldnames) {
  1194. upb_json_printercache *cache = upb_gmalloc(sizeof(*cache));
  1195. upb_handlercache *ret = upb_handlercache_new(printer_sethandlers, cache);
  1196. cache->preserve_fieldnames = preserve_proto_fieldnames;
  1197. upb_handlercache_addcleanup(ret, cache, upb_gfree);
  1198. return ret;
  1199. }