encode_decode.c 40 KB

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