encode_decode.c 40 KB

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