encode_decode.c 40 KB

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