encode_decode.c 42 KB

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