encode_decode.c 40 KB

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