encode_decode.c 39 KB

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