encode_decode.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2014 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #include "protobuf.h"
  31. // -----------------------------------------------------------------------------
  32. // Parsing.
  33. // -----------------------------------------------------------------------------
  34. #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
  35. // Creates a handlerdata that simply contains the offset for this field.
  36. static const void* newhandlerdata(upb_handlers* h, uint32_t ofs) {
  37. size_t* hd_ofs = ALLOC(size_t);
  38. *hd_ofs = ofs;
  39. upb_handlers_addcleanup(h, hd_ofs, free);
  40. return hd_ofs;
  41. }
  42. typedef struct {
  43. size_t ofs;
  44. const upb_msgdef *md;
  45. } submsg_handlerdata_t;
  46. // Creates a handlerdata that contains offset and submessage type information.
  47. static const void *newsubmsghandlerdata(upb_handlers* h, uint32_t ofs,
  48. const upb_fielddef* f) {
  49. submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
  50. hd->ofs = ofs;
  51. hd->md = upb_fielddef_msgsubdef(f);
  52. upb_handlers_addcleanup(h, hd, free);
  53. return hd;
  54. }
  55. typedef struct {
  56. size_t ofs; // union data slot
  57. size_t case_ofs; // oneof_case field
  58. uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
  59. const upb_msgdef *md; // msgdef, for oneof submessage handler
  60. } oneof_handlerdata_t;
  61. static const void *newoneofhandlerdata(upb_handlers *h,
  62. uint32_t ofs,
  63. uint32_t case_ofs,
  64. const upb_fielddef *f) {
  65. oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
  66. hd->ofs = ofs;
  67. hd->case_ofs = case_ofs;
  68. // We reuse the field tag number as a oneof union discriminant tag. Note that
  69. // we don't expose these numbers to the user, so the only requirement is that
  70. // we have some unique ID for each union case/possibility. The field tag
  71. // numbers are already present and are easy to use so there's no reason to
  72. // create a separate ID space. In addition, using the field tag number here
  73. // lets us easily look up the field in the oneof accessor.
  74. hd->oneof_case_num = upb_fielddef_number(f);
  75. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
  76. hd->md = upb_fielddef_msgsubdef(f);
  77. } else {
  78. hd->md = NULL;
  79. }
  80. upb_handlers_addcleanup(h, hd, free);
  81. return hd;
  82. }
  83. // A handler that starts a repeated field. Gets the Repeated*Field instance for
  84. // this field (such an instance always exists even in an empty message).
  85. static void *startseq_handler(void* closure, const void* hd) {
  86. MessageHeader* msg = closure;
  87. const size_t *ofs = hd;
  88. return (void*)DEREF(msg, *ofs, VALUE);
  89. }
  90. // Handlers that append primitive values to a repeated field.
  91. #define DEFINE_APPEND_HANDLER(type, ctype) \
  92. static bool append##type##_handler(void *closure, const void *hd, \
  93. ctype val) { \
  94. VALUE ary = (VALUE)closure; \
  95. RepeatedField_push_native(ary, &val); \
  96. return true; \
  97. }
  98. DEFINE_APPEND_HANDLER(bool, bool)
  99. DEFINE_APPEND_HANDLER(int32, int32_t)
  100. DEFINE_APPEND_HANDLER(uint32, uint32_t)
  101. DEFINE_APPEND_HANDLER(float, float)
  102. DEFINE_APPEND_HANDLER(int64, int64_t)
  103. DEFINE_APPEND_HANDLER(uint64, uint64_t)
  104. DEFINE_APPEND_HANDLER(double, double)
  105. // Appends a string to a repeated field.
  106. static void* appendstr_handler(void *closure,
  107. const void *hd,
  108. size_t size_hint) {
  109. VALUE ary = (VALUE)closure;
  110. VALUE str = rb_str_new2("");
  111. rb_enc_associate(str, kRubyStringUtf8Encoding);
  112. RepeatedField_push(ary, str);
  113. return (void*)str;
  114. }
  115. // Appends a 'bytes' string to a repeated field.
  116. static void* appendbytes_handler(void *closure,
  117. const void *hd,
  118. size_t size_hint) {
  119. VALUE ary = (VALUE)closure;
  120. VALUE str = rb_str_new2("");
  121. rb_enc_associate(str, kRubyString8bitEncoding);
  122. RepeatedField_push(ary, str);
  123. return (void*)str;
  124. }
  125. // Sets a non-repeated string field in a message.
  126. static void* str_handler(void *closure,
  127. const void *hd,
  128. size_t size_hint) {
  129. MessageHeader* msg = closure;
  130. const size_t *ofs = hd;
  131. VALUE str = rb_str_new2("");
  132. rb_enc_associate(str, kRubyStringUtf8Encoding);
  133. DEREF(msg, *ofs, VALUE) = str;
  134. return (void*)str;
  135. }
  136. // Sets a non-repeated 'bytes' field in a message.
  137. static void* bytes_handler(void *closure,
  138. const void *hd,
  139. size_t size_hint) {
  140. MessageHeader* msg = closure;
  141. const size_t *ofs = hd;
  142. VALUE str = rb_str_new2("");
  143. rb_enc_associate(str, kRubyString8bitEncoding);
  144. DEREF(msg, *ofs, VALUE) = str;
  145. return (void*)str;
  146. }
  147. static size_t stringdata_handler(void* closure, const void* hd,
  148. const char* str, size_t len,
  149. const upb_bufhandle* handle) {
  150. VALUE rb_str = (VALUE)closure;
  151. rb_str_cat(rb_str, str, len);
  152. return len;
  153. }
  154. // Appends a submessage to a repeated field (a regular Ruby array for now).
  155. static void *appendsubmsg_handler(void *closure, const void *hd) {
  156. VALUE ary = (VALUE)closure;
  157. const submsg_handlerdata_t *submsgdata = hd;
  158. VALUE subdesc =
  159. get_def_obj((void*)submsgdata->md);
  160. VALUE subklass = Descriptor_msgclass(subdesc);
  161. VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
  162. RepeatedField_push(ary, submsg_rb);
  163. MessageHeader* submsg;
  164. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  165. return submsg;
  166. }
  167. // Sets a non-repeated submessage field in a message.
  168. static void *submsg_handler(void *closure, const void *hd) {
  169. MessageHeader* msg = closure;
  170. const submsg_handlerdata_t* submsgdata = hd;
  171. VALUE subdesc =
  172. get_def_obj((void*)submsgdata->md);
  173. VALUE subklass = Descriptor_msgclass(subdesc);
  174. if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
  175. DEREF(msg, submsgdata->ofs, VALUE) =
  176. rb_class_new_instance(0, NULL, subklass);
  177. }
  178. VALUE submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
  179. MessageHeader* submsg;
  180. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  181. return submsg;
  182. }
  183. // Handler data for startmap/endmap handlers.
  184. typedef struct {
  185. size_t ofs;
  186. upb_fieldtype_t key_field_type;
  187. upb_fieldtype_t value_field_type;
  188. // We know that we can hold this reference because the handlerdata has the
  189. // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
  190. // a reference to the upb_msgdef, which in turn has references to its subdefs.
  191. const upb_def* value_field_subdef;
  192. } map_handlerdata_t;
  193. // Temporary frame for map parsing: at the beginning of a map entry message, a
  194. // submsg handler allocates a frame to hold (i) a reference to the Map object
  195. // into which this message will be inserted and (ii) storage slots to
  196. // temporarily hold the key and value for this map entry until the end of the
  197. // submessage. When the submessage ends, another handler is called to insert the
  198. // value into the map.
  199. typedef struct {
  200. VALUE map;
  201. char key_storage[NATIVE_SLOT_MAX_SIZE];
  202. char value_storage[NATIVE_SLOT_MAX_SIZE];
  203. } map_parse_frame_t;
  204. // Handler to begin a map entry: allocates a temporary frame. This is the
  205. // 'startsubmsg' handler on the msgdef that contains the map field.
  206. static void *startmapentry_handler(void *closure, const void *hd) {
  207. MessageHeader* msg = closure;
  208. const map_handlerdata_t* mapdata = hd;
  209. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  210. map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
  211. frame->map = map_rb;
  212. native_slot_init(mapdata->key_field_type, &frame->key_storage);
  213. native_slot_init(mapdata->value_field_type, &frame->value_storage);
  214. return frame;
  215. }
  216. // Handler to end a map entry: inserts the value defined during the message into
  217. // the map. This is the 'endmsg' handler on the map entry msgdef.
  218. static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
  219. map_parse_frame_t* frame = closure;
  220. const map_handlerdata_t* mapdata = hd;
  221. VALUE key = native_slot_get(
  222. mapdata->key_field_type, Qnil,
  223. &frame->key_storage);
  224. VALUE value_field_typeclass = Qnil;
  225. if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
  226. mapdata->value_field_type == UPB_TYPE_ENUM) {
  227. value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
  228. }
  229. VALUE value = native_slot_get(
  230. mapdata->value_field_type, value_field_typeclass,
  231. &frame->value_storage);
  232. Map_index_set(frame->map, key, value);
  233. free(frame);
  234. return true;
  235. }
  236. // Allocates a new map_handlerdata_t given the map entry message definition. If
  237. // the offset of the field within the parent message is also given, that is
  238. // added to the handler data as well. Note that this is called *twice* per map
  239. // field: once in the parent message handler setup when setting the startsubmsg
  240. // handler and once in the map entry message handler setup when setting the
  241. // key/value and endmsg handlers. The reason is that there is no easy way to
  242. // pass the handlerdata down to the sub-message handler setup.
  243. static map_handlerdata_t* new_map_handlerdata(
  244. size_t ofs,
  245. const upb_msgdef* mapentry_def,
  246. Descriptor* desc) {
  247. map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
  248. hd->ofs = ofs;
  249. const upb_fielddef* key_field = upb_msgdef_itof(mapentry_def,
  250. MAP_KEY_FIELD);
  251. assert(key_field != NULL);
  252. hd->key_field_type = upb_fielddef_type(key_field);
  253. const upb_fielddef* value_field = upb_msgdef_itof(mapentry_def,
  254. MAP_VALUE_FIELD);
  255. assert(value_field != NULL);
  256. hd->value_field_type = upb_fielddef_type(value_field);
  257. hd->value_field_subdef = upb_fielddef_subdef(value_field);
  258. return hd;
  259. }
  260. // Handlers that set primitive values in oneofs.
  261. #define DEFINE_ONEOF_HANDLER(type, ctype) \
  262. static bool oneof##type##_handler(void *closure, const void *hd, \
  263. ctype val) { \
  264. const oneof_handlerdata_t *oneofdata = hd; \
  265. DEREF(closure, oneofdata->case_ofs, uint32_t) = \
  266. oneofdata->oneof_case_num; \
  267. DEREF(closure, oneofdata->ofs, ctype) = val; \
  268. return true; \
  269. }
  270. DEFINE_ONEOF_HANDLER(bool, bool)
  271. DEFINE_ONEOF_HANDLER(int32, int32_t)
  272. DEFINE_ONEOF_HANDLER(uint32, uint32_t)
  273. DEFINE_ONEOF_HANDLER(float, float)
  274. DEFINE_ONEOF_HANDLER(int64, int64_t)
  275. DEFINE_ONEOF_HANDLER(uint64, uint64_t)
  276. DEFINE_ONEOF_HANDLER(double, double)
  277. #undef DEFINE_ONEOF_HANDLER
  278. // Handlers for strings in a oneof.
  279. static void *oneofstr_handler(void *closure,
  280. const void *hd,
  281. size_t size_hint) {
  282. MessageHeader* msg = closure;
  283. const oneof_handlerdata_t *oneofdata = hd;
  284. VALUE str = rb_str_new2("");
  285. rb_enc_associate(str, kRubyStringUtf8Encoding);
  286. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  287. oneofdata->oneof_case_num;
  288. DEREF(msg, oneofdata->ofs, VALUE) = str;
  289. return (void*)str;
  290. }
  291. static void *oneofbytes_handler(void *closure,
  292. const void *hd,
  293. size_t size_hint) {
  294. MessageHeader* msg = closure;
  295. const oneof_handlerdata_t *oneofdata = hd;
  296. VALUE str = rb_str_new2("");
  297. rb_enc_associate(str, kRubyString8bitEncoding);
  298. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  299. oneofdata->oneof_case_num;
  300. DEREF(msg, oneofdata->ofs, VALUE) = str;
  301. return (void*)str;
  302. }
  303. // Handler for a submessage field in a oneof.
  304. static void *oneofsubmsg_handler(void *closure,
  305. const void *hd) {
  306. MessageHeader* msg = closure;
  307. const oneof_handlerdata_t *oneofdata = hd;
  308. uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
  309. VALUE subdesc =
  310. get_def_obj((void*)oneofdata->md);
  311. VALUE subklass = Descriptor_msgclass(subdesc);
  312. if (oldcase != oneofdata->oneof_case_num ||
  313. DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
  314. DEREF(msg, oneofdata->ofs, VALUE) =
  315. rb_class_new_instance(0, NULL, subklass);
  316. }
  317. // Set the oneof case *after* allocating the new class instance -- otherwise,
  318. // if the Ruby GC is invoked as part of a call into the VM, it might invoke
  319. // our mark routines, and our mark routines might see the case value
  320. // indicating a VALUE is present and expect a valid VALUE. See comment in
  321. // layout_set() for more detail: basically, the change to the value and the
  322. // case must be atomic w.r.t. the Ruby VM.
  323. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  324. oneofdata->oneof_case_num;
  325. VALUE submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
  326. MessageHeader* submsg;
  327. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  328. return submsg;
  329. }
  330. // Set up handlers for a repeated field.
  331. static void add_handlers_for_repeated_field(upb_handlers *h,
  332. const upb_fielddef *f,
  333. size_t offset) {
  334. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  335. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  336. upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  337. upb_handlerattr_uninit(&attr);
  338. switch (upb_fielddef_type(f)) {
  339. #define SET_HANDLER(utype, ltype) \
  340. case utype: \
  341. upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
  342. break;
  343. SET_HANDLER(UPB_TYPE_BOOL, bool);
  344. SET_HANDLER(UPB_TYPE_INT32, int32);
  345. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  346. SET_HANDLER(UPB_TYPE_ENUM, int32);
  347. SET_HANDLER(UPB_TYPE_FLOAT, float);
  348. SET_HANDLER(UPB_TYPE_INT64, int64);
  349. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  350. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  351. #undef SET_HANDLER
  352. case UPB_TYPE_STRING:
  353. case UPB_TYPE_BYTES: {
  354. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  355. upb_handlers_setstartstr(h, f, is_bytes ?
  356. appendbytes_handler : appendstr_handler,
  357. NULL);
  358. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  359. break;
  360. }
  361. case UPB_TYPE_MESSAGE: {
  362. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  363. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
  364. upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
  365. upb_handlerattr_uninit(&attr);
  366. break;
  367. }
  368. }
  369. }
  370. // Set up handlers for a singular field.
  371. static void add_handlers_for_singular_field(upb_handlers *h,
  372. const upb_fielddef *f,
  373. size_t offset) {
  374. switch (upb_fielddef_type(f)) {
  375. case UPB_TYPE_BOOL:
  376. case UPB_TYPE_INT32:
  377. case UPB_TYPE_UINT32:
  378. case UPB_TYPE_ENUM:
  379. case UPB_TYPE_FLOAT:
  380. case UPB_TYPE_INT64:
  381. case UPB_TYPE_UINT64:
  382. case UPB_TYPE_DOUBLE:
  383. upb_shim_set(h, f, offset, -1);
  384. break;
  385. case UPB_TYPE_STRING:
  386. case UPB_TYPE_BYTES: {
  387. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  388. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  389. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  390. upb_handlers_setstartstr(h, f,
  391. is_bytes ? bytes_handler : str_handler,
  392. &attr);
  393. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  394. upb_handlerattr_uninit(&attr);
  395. break;
  396. }
  397. case UPB_TYPE_MESSAGE: {
  398. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  399. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
  400. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  401. upb_handlerattr_uninit(&attr);
  402. break;
  403. }
  404. }
  405. }
  406. // Adds handlers to a map field.
  407. static void add_handlers_for_mapfield(upb_handlers* h,
  408. const upb_fielddef* fielddef,
  409. size_t offset,
  410. Descriptor* desc) {
  411. const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
  412. map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
  413. upb_handlers_addcleanup(h, hd, free);
  414. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  415. upb_handlerattr_sethandlerdata(&attr, hd);
  416. upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
  417. upb_handlerattr_uninit(&attr);
  418. }
  419. // Adds handlers to a map-entry msgdef.
  420. static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
  421. upb_handlers* h,
  422. Descriptor* desc) {
  423. const upb_fielddef* key_field = map_entry_key(msgdef);
  424. const upb_fielddef* value_field = map_entry_value(msgdef);
  425. map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
  426. upb_handlers_addcleanup(h, hd, free);
  427. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  428. upb_handlerattr_sethandlerdata(&attr, hd);
  429. upb_handlers_setendmsg(h, endmap_handler, &attr);
  430. add_handlers_for_singular_field(
  431. h, key_field,
  432. offsetof(map_parse_frame_t, key_storage));
  433. add_handlers_for_singular_field(
  434. h, value_field,
  435. offsetof(map_parse_frame_t, value_storage));
  436. }
  437. // Set up handlers for a oneof field.
  438. static void add_handlers_for_oneof_field(upb_handlers *h,
  439. const upb_fielddef *f,
  440. size_t offset,
  441. size_t oneof_case_offset) {
  442. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  443. upb_handlerattr_sethandlerdata(
  444. &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
  445. switch (upb_fielddef_type(f)) {
  446. #define SET_HANDLER(utype, ltype) \
  447. case utype: \
  448. upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
  449. break;
  450. SET_HANDLER(UPB_TYPE_BOOL, bool);
  451. SET_HANDLER(UPB_TYPE_INT32, int32);
  452. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  453. SET_HANDLER(UPB_TYPE_ENUM, int32);
  454. SET_HANDLER(UPB_TYPE_FLOAT, float);
  455. SET_HANDLER(UPB_TYPE_INT64, int64);
  456. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  457. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  458. #undef SET_HANDLER
  459. case UPB_TYPE_STRING:
  460. case UPB_TYPE_BYTES: {
  461. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  462. upb_handlers_setstartstr(h, f, is_bytes ?
  463. oneofbytes_handler : oneofstr_handler,
  464. &attr);
  465. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  466. break;
  467. }
  468. case UPB_TYPE_MESSAGE: {
  469. upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
  470. break;
  471. }
  472. }
  473. upb_handlerattr_uninit(&attr);
  474. }
  475. static void add_handlers_for_message(const void *closure, upb_handlers *h) {
  476. const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  477. Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
  478. // If this is a mapentry message type, set up a special set of handlers and
  479. // bail out of the normal (user-defined) message type handling.
  480. if (upb_msgdef_mapentry(msgdef)) {
  481. add_handlers_for_mapentry(msgdef, h, desc);
  482. return;
  483. }
  484. // Ensure layout exists. We may be invoked to create handlers for a given
  485. // message if we are included as a submsg of another message type before our
  486. // class is actually built, so to work around this, we just create the layout
  487. // (and handlers, in the class-building function) on-demand.
  488. if (desc->layout == NULL) {
  489. desc->layout = create_layout(desc->msgdef);
  490. }
  491. upb_msg_field_iter i;
  492. for (upb_msg_field_begin(&i, desc->msgdef);
  493. !upb_msg_field_done(&i);
  494. upb_msg_field_next(&i)) {
  495. const upb_fielddef *f = upb_msg_iter_field(&i);
  496. size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
  497. sizeof(MessageHeader);
  498. if (upb_fielddef_containingoneof(f)) {
  499. size_t oneof_case_offset =
  500. desc->layout->fields[upb_fielddef_index(f)].case_offset +
  501. sizeof(MessageHeader);
  502. add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
  503. } else if (is_map_field(f)) {
  504. add_handlers_for_mapfield(h, f, offset, desc);
  505. } else if (upb_fielddef_isseq(f)) {
  506. add_handlers_for_repeated_field(h, f, offset);
  507. } else {
  508. add_handlers_for_singular_field(h, f, offset);
  509. }
  510. }
  511. }
  512. // Creates upb handlers for populating a message.
  513. static const upb_handlers *new_fill_handlers(Descriptor* desc,
  514. const void* owner) {
  515. // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
  516. // handlers, reuse subdef handlers so that e.g. if we already parse
  517. // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
  518. // parse A-with-field-of-type-B-with-field-of-type-C.
  519. return upb_handlers_newfrozen(desc->msgdef, owner,
  520. add_handlers_for_message, NULL);
  521. }
  522. // Constructs the handlers for filling a message's data into an in-memory
  523. // object.
  524. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  525. if (!desc->fill_handlers) {
  526. desc->fill_handlers =
  527. new_fill_handlers(desc, &desc->fill_handlers);
  528. }
  529. return desc->fill_handlers;
  530. }
  531. // Constructs the upb decoder method for parsing messages of this type.
  532. // This is called from the message class creation code.
  533. const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
  534. const void* owner) {
  535. const upb_handlers* handlers = get_fill_handlers(desc);
  536. upb_pbdecodermethodopts opts;
  537. upb_pbdecodermethodopts_init(&opts, handlers);
  538. const upb_pbdecodermethod *ret = upb_pbdecodermethod_new(&opts, owner);
  539. return ret;
  540. }
  541. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  542. if (desc->fill_method == NULL) {
  543. desc->fill_method = new_fillmsg_decodermethod(
  544. desc, &desc->fill_method);
  545. }
  546. return desc->fill_method;
  547. }
  548. /*
  549. * call-seq:
  550. * MessageClass.decode(data) => message
  551. *
  552. * Decodes the given data (as a string containing bytes in protocol buffers wire
  553. * format) under the interpretration given by this message class's definition
  554. * and returns a message object with the corresponding field values.
  555. */
  556. VALUE Message_decode(VALUE klass, VALUE data) {
  557. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  558. Descriptor* desc = ruby_to_Descriptor(descriptor);
  559. VALUE msgklass = Descriptor_msgclass(descriptor);
  560. if (TYPE(data) != T_STRING) {
  561. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  562. }
  563. VALUE msg_rb = rb_class_new_instance(0, NULL, msgklass);
  564. MessageHeader* msg;
  565. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  566. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  567. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  568. upb_pbdecoder decoder;
  569. upb_sink sink;
  570. upb_status status = UPB_STATUS_INIT;
  571. upb_pbdecoder_init(&decoder, method, &status);
  572. upb_sink_reset(&sink, h, msg);
  573. upb_pbdecoder_resetoutput(&decoder, &sink);
  574. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  575. upb_pbdecoder_input(&decoder));
  576. upb_pbdecoder_uninit(&decoder);
  577. if (!upb_ok(&status)) {
  578. rb_raise(rb_eRuntimeError, "Error occurred during parsing: %s.",
  579. upb_status_errmsg(&status));
  580. }
  581. return msg_rb;
  582. }
  583. /*
  584. * call-seq:
  585. * MessageClass.decode_json(data) => message
  586. *
  587. * Decodes the given data (as a string containing bytes in protocol buffers wire
  588. * format) under the interpretration given by this message class's definition
  589. * and returns a message object with the corresponding field values.
  590. */
  591. VALUE Message_decode_json(VALUE klass, VALUE data) {
  592. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  593. Descriptor* desc = ruby_to_Descriptor(descriptor);
  594. VALUE msgklass = Descriptor_msgclass(descriptor);
  595. if (TYPE(data) != T_STRING) {
  596. rb_raise(rb_eArgError, "Expected string for JSON data.");
  597. }
  598. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  599. // convert, because string handlers pass data directly to message string
  600. // fields.
  601. VALUE msg_rb = rb_class_new_instance(0, NULL, msgklass);
  602. MessageHeader* msg;
  603. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  604. upb_status status = UPB_STATUS_INIT;
  605. upb_json_parser parser;
  606. upb_json_parser_init(&parser, &status);
  607. upb_sink sink;
  608. upb_sink_reset(&sink, get_fill_handlers(desc), msg);
  609. upb_json_parser_resetoutput(&parser, &sink);
  610. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  611. upb_json_parser_input(&parser));
  612. upb_json_parser_uninit(&parser);
  613. if (!upb_ok(&status)) {
  614. rb_raise(rb_eRuntimeError, "Error occurred during parsing: %s.",
  615. upb_status_errmsg(&status));
  616. }
  617. return msg_rb;
  618. }
  619. // -----------------------------------------------------------------------------
  620. // Serializing.
  621. // -----------------------------------------------------------------------------
  622. //
  623. // The code below also comes from upb's prototype Ruby binding, developed by
  624. // haberman@.
  625. /* stringsink *****************************************************************/
  626. // This should probably be factored into a common upb component.
  627. typedef struct {
  628. upb_byteshandler handler;
  629. upb_bytessink sink;
  630. char *ptr;
  631. size_t len, size;
  632. } stringsink;
  633. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  634. stringsink *sink = _sink;
  635. sink->len = 0;
  636. return sink;
  637. }
  638. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  639. size_t len, const upb_bufhandle *handle) {
  640. UPB_UNUSED(hd);
  641. UPB_UNUSED(handle);
  642. stringsink *sink = _sink;
  643. size_t new_size = sink->size;
  644. while (sink->len + len > new_size) {
  645. new_size *= 2;
  646. }
  647. if (new_size != sink->size) {
  648. sink->ptr = realloc(sink->ptr, new_size);
  649. sink->size = new_size;
  650. }
  651. memcpy(sink->ptr + sink->len, ptr, len);
  652. sink->len += len;
  653. return len;
  654. }
  655. void stringsink_init(stringsink *sink) {
  656. upb_byteshandler_init(&sink->handler);
  657. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  658. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  659. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  660. sink->size = 32;
  661. sink->ptr = malloc(sink->size);
  662. sink->len = 0;
  663. }
  664. void stringsink_uninit(stringsink *sink) {
  665. free(sink->ptr);
  666. }
  667. /* msgvisitor *****************************************************************/
  668. // TODO: If/when we support proto2 semantics in addition to the current proto3
  669. // semantics, which means that we have true field presence, we will want to
  670. // modify msgvisitor so that it emits all present fields rather than all
  671. // non-default-value fields.
  672. //
  673. // Likewise, when implementing JSON serialization, we may need to have a
  674. // 'verbose' mode that outputs all fields and a 'concise' mode that outputs only
  675. // those with non-default values.
  676. static void putmsg(VALUE msg, const Descriptor* desc,
  677. upb_sink *sink, int depth);
  678. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  679. upb_selector_t ret;
  680. bool ok = upb_handlers_getselector(f, type, &ret);
  681. UPB_ASSERT_VAR(ok, ok);
  682. return ret;
  683. }
  684. static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
  685. if (str == Qnil) return;
  686. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  687. upb_sink subsink;
  688. // Ensure that the string has the correct encoding. We also check at field-set
  689. // time, but the user may have mutated the string object since then.
  690. native_slot_validate_string_encoding(upb_fielddef_type(f), str);
  691. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  692. &subsink);
  693. upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  694. RSTRING_LEN(str), NULL);
  695. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  696. }
  697. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
  698. int depth) {
  699. if (submsg == Qnil) return;
  700. upb_sink subsink;
  701. VALUE descriptor = rb_iv_get(submsg, kDescriptorInstanceVar);
  702. Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  703. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  704. putmsg(submsg, subdesc, &subsink, depth + 1);
  705. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  706. }
  707. static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
  708. int depth) {
  709. if (ary == Qnil) return;
  710. upb_sink subsink;
  711. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  712. upb_fieldtype_t type = upb_fielddef_type(f);
  713. upb_selector_t sel = 0;
  714. if (upb_fielddef_isprimitive(f)) {
  715. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  716. }
  717. int size = NUM2INT(RepeatedField_length(ary));
  718. for (int i = 0; i < size; i++) {
  719. void* memory = RepeatedField_index_native(ary, i);
  720. switch (type) {
  721. #define T(upbtypeconst, upbtype, ctype) \
  722. case upbtypeconst: \
  723. upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
  724. break;
  725. T(UPB_TYPE_FLOAT, float, float)
  726. T(UPB_TYPE_DOUBLE, double, double)
  727. T(UPB_TYPE_BOOL, bool, int8_t)
  728. case UPB_TYPE_ENUM:
  729. T(UPB_TYPE_INT32, int32, int32_t)
  730. T(UPB_TYPE_UINT32, uint32, uint32_t)
  731. T(UPB_TYPE_INT64, int64, int64_t)
  732. T(UPB_TYPE_UINT64, uint64, uint64_t)
  733. case UPB_TYPE_STRING:
  734. case UPB_TYPE_BYTES:
  735. putstr(*((VALUE *)memory), f, &subsink);
  736. break;
  737. case UPB_TYPE_MESSAGE:
  738. putsubmsg(*((VALUE *)memory), f, &subsink, depth);
  739. break;
  740. #undef T
  741. }
  742. }
  743. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  744. }
  745. static void put_ruby_value(VALUE value,
  746. const upb_fielddef *f,
  747. VALUE type_class,
  748. int depth,
  749. upb_sink *sink) {
  750. upb_selector_t sel = 0;
  751. if (upb_fielddef_isprimitive(f)) {
  752. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  753. }
  754. switch (upb_fielddef_type(f)) {
  755. case UPB_TYPE_INT32:
  756. upb_sink_putint32(sink, sel, NUM2INT(value));
  757. break;
  758. case UPB_TYPE_INT64:
  759. upb_sink_putint64(sink, sel, NUM2LL(value));
  760. break;
  761. case UPB_TYPE_UINT32:
  762. upb_sink_putuint32(sink, sel, NUM2UINT(value));
  763. break;
  764. case UPB_TYPE_UINT64:
  765. upb_sink_putuint64(sink, sel, NUM2ULL(value));
  766. break;
  767. case UPB_TYPE_FLOAT:
  768. upb_sink_putfloat(sink, sel, NUM2DBL(value));
  769. break;
  770. case UPB_TYPE_DOUBLE:
  771. upb_sink_putdouble(sink, sel, NUM2DBL(value));
  772. break;
  773. case UPB_TYPE_ENUM: {
  774. if (TYPE(value) == T_SYMBOL) {
  775. value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  776. }
  777. upb_sink_putint32(sink, sel, NUM2INT(value));
  778. break;
  779. }
  780. case UPB_TYPE_BOOL:
  781. upb_sink_putbool(sink, sel, value == Qtrue);
  782. break;
  783. case UPB_TYPE_STRING:
  784. case UPB_TYPE_BYTES:
  785. putstr(value, f, sink);
  786. break;
  787. case UPB_TYPE_MESSAGE:
  788. putsubmsg(value, f, sink, depth);
  789. }
  790. }
  791. static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
  792. int depth) {
  793. if (map == Qnil) return;
  794. Map* self = ruby_to_Map(map);
  795. upb_sink subsink;
  796. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  797. assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  798. const upb_fielddef* key_field = map_field_key(f);
  799. const upb_fielddef* value_field = map_field_value(f);
  800. Map_iter it;
  801. for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
  802. VALUE key = Map_iter_key(&it);
  803. VALUE value = Map_iter_value(&it);
  804. upb_sink entry_sink;
  805. upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG), &entry_sink);
  806. upb_sink_startmsg(&entry_sink);
  807. put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink);
  808. put_ruby_value(value, value_field, self->value_type_class, depth + 1,
  809. &entry_sink);
  810. upb_status status;
  811. upb_sink_endmsg(&entry_sink, &status);
  812. upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  813. }
  814. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  815. }
  816. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  817. upb_sink *sink, int depth) {
  818. upb_sink_startmsg(sink);
  819. // Protect against cycles (possible because users may freely reassign message
  820. // and repeated fields) by imposing a maximum recursion depth.
  821. if (depth > UPB_SINK_MAX_NESTING) {
  822. rb_raise(rb_eRuntimeError,
  823. "Maximum recursion depth exceeded during encoding.");
  824. }
  825. MessageHeader* msg;
  826. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  827. upb_msg_field_iter i;
  828. for (upb_msg_field_begin(&i, desc->msgdef);
  829. !upb_msg_field_done(&i);
  830. upb_msg_field_next(&i)) {
  831. upb_fielddef *f = upb_msg_iter_field(&i);
  832. uint32_t offset =
  833. desc->layout->fields[upb_fielddef_index(f)].offset +
  834. sizeof(MessageHeader);
  835. if (upb_fielddef_containingoneof(f)) {
  836. uint32_t oneof_case_offset =
  837. desc->layout->fields[upb_fielddef_index(f)].case_offset +
  838. sizeof(MessageHeader);
  839. // For a oneof, check that this field is actually present -- skip all the
  840. // below if not.
  841. if (DEREF(msg, oneof_case_offset, uint32_t) !=
  842. upb_fielddef_number(f)) {
  843. continue;
  844. }
  845. // Otherwise, fall through to the appropriate singular-field handler
  846. // below.
  847. }
  848. if (is_map_field(f)) {
  849. VALUE map = DEREF(msg, offset, VALUE);
  850. if (map != Qnil) {
  851. putmap(map, f, sink, depth);
  852. }
  853. } else if (upb_fielddef_isseq(f)) {
  854. VALUE ary = DEREF(msg, offset, VALUE);
  855. if (ary != Qnil) {
  856. putary(ary, f, sink, depth);
  857. }
  858. } else if (upb_fielddef_isstring(f)) {
  859. VALUE str = DEREF(msg, offset, VALUE);
  860. if (RSTRING_LEN(str) > 0) {
  861. putstr(str, f, sink);
  862. }
  863. } else if (upb_fielddef_issubmsg(f)) {
  864. putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth);
  865. } else {
  866. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  867. #define T(upbtypeconst, upbtype, ctype, default_value) \
  868. case upbtypeconst: { \
  869. ctype value = DEREF(msg, offset, ctype); \
  870. if (value != default_value) { \
  871. upb_sink_put##upbtype(sink, sel, value); \
  872. } \
  873. } \
  874. break;
  875. switch (upb_fielddef_type(f)) {
  876. T(UPB_TYPE_FLOAT, float, float, 0.0)
  877. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  878. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  879. case UPB_TYPE_ENUM:
  880. T(UPB_TYPE_INT32, int32, int32_t, 0)
  881. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  882. T(UPB_TYPE_INT64, int64, int64_t, 0)
  883. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  884. case UPB_TYPE_STRING:
  885. case UPB_TYPE_BYTES:
  886. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  887. }
  888. #undef T
  889. }
  890. }
  891. upb_status status;
  892. upb_sink_endmsg(sink, &status);
  893. }
  894. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  895. if (desc->pb_serialize_handlers == NULL) {
  896. desc->pb_serialize_handlers =
  897. upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
  898. }
  899. return desc->pb_serialize_handlers;
  900. }
  901. static const upb_handlers* msgdef_json_serialize_handlers(Descriptor* desc) {
  902. if (desc->json_serialize_handlers == NULL) {
  903. desc->json_serialize_handlers =
  904. upb_json_printer_newhandlers(
  905. desc->msgdef, &desc->json_serialize_handlers);
  906. }
  907. return desc->json_serialize_handlers;
  908. }
  909. /*
  910. * call-seq:
  911. * MessageClass.encode(msg) => bytes
  912. *
  913. * Encodes the given message object to its serialized form in protocol buffers
  914. * wire format.
  915. */
  916. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  917. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  918. Descriptor* desc = ruby_to_Descriptor(descriptor);
  919. stringsink sink;
  920. stringsink_init(&sink);
  921. const upb_handlers* serialize_handlers =
  922. msgdef_pb_serialize_handlers(desc);
  923. upb_pb_encoder encoder;
  924. upb_pb_encoder_init(&encoder, serialize_handlers);
  925. upb_pb_encoder_resetoutput(&encoder, &sink.sink);
  926. putmsg(msg_rb, desc, upb_pb_encoder_input(&encoder), 0);
  927. VALUE ret = rb_str_new(sink.ptr, sink.len);
  928. upb_pb_encoder_uninit(&encoder);
  929. stringsink_uninit(&sink);
  930. return ret;
  931. }
  932. /*
  933. * call-seq:
  934. * MessageClass.encode_json(msg) => json_string
  935. *
  936. * Encodes the given message object into its serialized JSON representation.
  937. */
  938. VALUE Message_encode_json(VALUE klass, VALUE msg_rb) {
  939. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  940. Descriptor* desc = ruby_to_Descriptor(descriptor);
  941. stringsink sink;
  942. stringsink_init(&sink);
  943. const upb_handlers* serialize_handlers =
  944. msgdef_json_serialize_handlers(desc);
  945. upb_json_printer printer;
  946. upb_json_printer_init(&printer, serialize_handlers);
  947. upb_json_printer_resetoutput(&printer, &sink.sink);
  948. putmsg(msg_rb, desc, upb_json_printer_input(&printer), 0);
  949. VALUE ret = rb_str_new(sink.ptr, sink.len);
  950. upb_json_printer_uninit(&printer);
  951. stringsink_uninit(&sink);
  952. return ret;
  953. }