encode_decode.c 40 KB

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