encode_decode.c 40 KB

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