encode_decode.c 40 KB

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