encode_decode.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685
  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. // The code below also comes from upb's prototype Ruby binding, developed by
  45. // haberman@.
  46. /* stringsink *****************************************************************/
  47. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  48. stringsink *sink = _sink;
  49. sink->len = 0;
  50. return sink;
  51. }
  52. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  53. size_t len, const upb_bufhandle *handle) {
  54. stringsink *sink = _sink;
  55. size_t new_size = sink->size;
  56. UPB_UNUSED(hd);
  57. UPB_UNUSED(handle);
  58. while (sink->len + len > new_size) {
  59. new_size *= 2;
  60. }
  61. if (new_size != sink->size) {
  62. sink->ptr = realloc(sink->ptr, new_size);
  63. sink->size = new_size;
  64. }
  65. memcpy(sink->ptr + sink->len, ptr, len);
  66. sink->len += len;
  67. return len;
  68. }
  69. void stringsink_init(stringsink *sink) {
  70. upb_byteshandler_init(&sink->handler);
  71. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  72. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  73. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  74. sink->size = 32;
  75. sink->ptr = malloc(sink->size);
  76. sink->len = 0;
  77. }
  78. void stringsink_uninit(stringsink *sink) {
  79. free(sink->ptr);
  80. }
  81. // -----------------------------------------------------------------------------
  82. // Parsing.
  83. // -----------------------------------------------------------------------------
  84. #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
  85. typedef struct {
  86. size_t ofs;
  87. int32_t hasbit;
  88. } field_handlerdata_t;
  89. // Creates a handlerdata that contains the offset and the hasbit for the field
  90. static const void* newhandlerdata(upb_handlers* h, uint32_t ofs, int32_t hasbit) {
  91. field_handlerdata_t *hd = ALLOC(field_handlerdata_t);
  92. hd->ofs = ofs;
  93. hd->hasbit = hasbit;
  94. upb_handlers_addcleanup(h, hd, xfree);
  95. return hd;
  96. }
  97. typedef struct {
  98. size_t ofs;
  99. int32_t hasbit;
  100. VALUE subklass;
  101. } submsg_handlerdata_t;
  102. // Creates a handlerdata that contains offset and submessage type information.
  103. static const void *newsubmsghandlerdata(upb_handlers* h,
  104. uint32_t ofs,
  105. int32_t hasbit,
  106. VALUE subklass) {
  107. submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
  108. hd->ofs = ofs;
  109. hd->hasbit = hasbit;
  110. hd->subklass = subklass;
  111. upb_handlers_addcleanup(h, hd, xfree);
  112. return hd;
  113. }
  114. typedef struct {
  115. size_t ofs; // union data slot
  116. size_t case_ofs; // oneof_case field
  117. uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
  118. VALUE subklass;
  119. } oneof_handlerdata_t;
  120. static const void *newoneofhandlerdata(upb_handlers *h,
  121. uint32_t ofs,
  122. uint32_t case_ofs,
  123. const upb_fielddef *f,
  124. const Descriptor* desc) {
  125. oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
  126. hd->ofs = ofs;
  127. hd->case_ofs = case_ofs;
  128. // We reuse the field tag number as a oneof union discriminant tag. Note that
  129. // we don't expose these numbers to the user, so the only requirement is that
  130. // we have some unique ID for each union case/possibility. The field tag
  131. // numbers are already present and are easy to use so there's no reason to
  132. // create a separate ID space. In addition, using the field tag number here
  133. // lets us easily look up the field in the oneof accessor.
  134. hd->oneof_case_num = upb_fielddef_number(f);
  135. if (is_value_field(f)) {
  136. hd->oneof_case_num |= ONEOF_CASE_MASK;
  137. }
  138. hd->subklass = field_type_class(desc->layout, f);
  139. upb_handlers_addcleanup(h, hd, xfree);
  140. return hd;
  141. }
  142. // A handler that starts a repeated field. Gets the Repeated*Field instance for
  143. // this field (such an instance always exists even in an empty message).
  144. static void *startseq_handler(void* closure, const void* hd) {
  145. MessageHeader* msg = closure;
  146. const size_t *ofs = hd;
  147. return (void*)DEREF(msg, *ofs, VALUE);
  148. }
  149. // Handlers that append primitive values to a repeated field.
  150. #define DEFINE_APPEND_HANDLER(type, ctype) \
  151. static bool append##type##_handler(void *closure, const void *hd, \
  152. ctype val) { \
  153. VALUE ary = (VALUE)closure; \
  154. RepeatedField_push_native(ary, &val); \
  155. return true; \
  156. }
  157. DEFINE_APPEND_HANDLER(bool, bool)
  158. DEFINE_APPEND_HANDLER(int32, int32_t)
  159. DEFINE_APPEND_HANDLER(uint32, uint32_t)
  160. DEFINE_APPEND_HANDLER(float, float)
  161. DEFINE_APPEND_HANDLER(int64, int64_t)
  162. DEFINE_APPEND_HANDLER(uint64, uint64_t)
  163. DEFINE_APPEND_HANDLER(double, double)
  164. // Appends a string to a repeated field.
  165. static void* appendstr_handler(void *closure,
  166. const void *hd,
  167. size_t size_hint) {
  168. VALUE ary = (VALUE)closure;
  169. VALUE str = rb_str_new2("");
  170. rb_enc_associate(str, kRubyStringUtf8Encoding);
  171. RepeatedField_push_native(ary, &str);
  172. return (void*)str;
  173. }
  174. static void set_hasbit(void *closure, int32_t hasbit) {
  175. if (hasbit > 0) {
  176. uint8_t* storage = closure;
  177. storage[hasbit/8] |= 1 << (hasbit % 8);
  178. }
  179. }
  180. // Appends a 'bytes' string to a repeated field.
  181. static void* appendbytes_handler(void *closure,
  182. const void *hd,
  183. size_t size_hint) {
  184. VALUE ary = (VALUE)closure;
  185. VALUE str = rb_str_new2("");
  186. rb_enc_associate(str, kRubyString8bitEncoding);
  187. RepeatedField_push_native(ary, &str);
  188. return (void*)str;
  189. }
  190. // Sets a non-repeated string field in a message.
  191. static void* str_handler(void *closure,
  192. const void *hd,
  193. size_t size_hint) {
  194. MessageHeader* msg = closure;
  195. const field_handlerdata_t *fieldhandler = hd;
  196. VALUE str = rb_str_new2("");
  197. rb_enc_associate(str, kRubyStringUtf8Encoding);
  198. DEREF(msg, fieldhandler->ofs, VALUE) = str;
  199. set_hasbit(closure, fieldhandler->hasbit);
  200. return (void*)str;
  201. }
  202. // Sets a non-repeated 'bytes' field in a message.
  203. static void* bytes_handler(void *closure,
  204. const void *hd,
  205. size_t size_hint) {
  206. MessageHeader* msg = closure;
  207. const field_handlerdata_t *fieldhandler = hd;
  208. VALUE str = rb_str_new2("");
  209. rb_enc_associate(str, kRubyString8bitEncoding);
  210. DEREF(msg, fieldhandler->ofs, VALUE) = str;
  211. set_hasbit(closure, fieldhandler->hasbit);
  212. return (void*)str;
  213. }
  214. static size_t stringdata_handler(void* closure, const void* hd,
  215. const char* str, size_t len,
  216. const upb_bufhandle* handle) {
  217. VALUE rb_str = (VALUE)closure;
  218. noleak_rb_str_cat(rb_str, str, len);
  219. return len;
  220. }
  221. static bool stringdata_end_handler(void* closure, const void* hd) {
  222. VALUE rb_str = (VALUE)closure;
  223. rb_obj_freeze(rb_str);
  224. return true;
  225. }
  226. static bool appendstring_end_handler(void* closure, const void* hd) {
  227. VALUE rb_str = (VALUE)closure;
  228. rb_obj_freeze(rb_str);
  229. return true;
  230. }
  231. // Appends a submessage to a repeated field (a regular Ruby array for now).
  232. static void *appendsubmsg_handler(void *closure, const void *hd) {
  233. VALUE ary = (VALUE)closure;
  234. const submsg_handlerdata_t *submsgdata = hd;
  235. MessageHeader* submsg;
  236. VALUE submsg_rb = rb_class_new_instance(0, NULL, submsgdata->subklass);
  237. RepeatedField_push(ary, submsg_rb);
  238. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  239. return submsg;
  240. }
  241. // Sets a non-repeated submessage field in a message.
  242. static void *submsg_handler(void *closure, const void *hd) {
  243. MessageHeader* msg = closure;
  244. const submsg_handlerdata_t* submsgdata = hd;
  245. VALUE submsg_rb;
  246. MessageHeader* submsg;
  247. if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
  248. DEREF(msg, submsgdata->ofs, VALUE) =
  249. rb_class_new_instance(0, NULL, submsgdata->subklass);
  250. }
  251. set_hasbit(closure, submsgdata->hasbit);
  252. submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
  253. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  254. return submsg;
  255. }
  256. static void* startwrapper(void* closure, const void* hd) {
  257. char* msg = closure;
  258. const submsg_handlerdata_t* submsgdata = hd;
  259. set_hasbit(closure, submsgdata->hasbit);
  260. return msg + submsgdata->ofs;
  261. }
  262. // Handler data for startmap/endmap handlers.
  263. typedef struct {
  264. size_t ofs;
  265. upb_fieldtype_t key_field_type;
  266. upb_fieldtype_t value_field_type;
  267. VALUE subklass;
  268. } map_handlerdata_t;
  269. // Temporary frame for map parsing: at the beginning of a map entry message, a
  270. // submsg handler allocates a frame to hold (i) a reference to the Map object
  271. // into which this message will be inserted and (ii) storage slots to
  272. // temporarily hold the key and value for this map entry until the end of the
  273. // submessage. When the submessage ends, another handler is called to insert the
  274. // value into the map.
  275. typedef struct {
  276. VALUE map;
  277. const map_handlerdata_t* handlerdata;
  278. char key_storage[NATIVE_SLOT_MAX_SIZE];
  279. char value_storage[NATIVE_SLOT_MAX_SIZE];
  280. } map_parse_frame_t;
  281. static void MapParseFrame_mark(void* _self) {
  282. map_parse_frame_t* frame = _self;
  283. // This shouldn't strictly be necessary since this should be rooted by the
  284. // message itself, but it can't hurt.
  285. rb_gc_mark(frame->map);
  286. native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
  287. native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
  288. }
  289. void MapParseFrame_free(void* self) {
  290. xfree(self);
  291. }
  292. rb_data_type_t MapParseFrame_type = {
  293. "MapParseFrame",
  294. { MapParseFrame_mark, MapParseFrame_free, NULL },
  295. };
  296. // Handler to begin a map entry: allocates a temporary frame. This is the
  297. // 'startsubmsg' handler on the msgdef that contains the map field.
  298. static void *startmap_handler(void *closure, const void *hd) {
  299. MessageHeader* msg = closure;
  300. const map_handlerdata_t* mapdata = hd;
  301. map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
  302. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  303. frame->handlerdata = mapdata;
  304. frame->map = map_rb;
  305. native_slot_init(mapdata->key_field_type, &frame->key_storage);
  306. native_slot_init(mapdata->value_field_type, &frame->value_storage);
  307. Map_set_frame(map_rb,
  308. TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
  309. return frame;
  310. }
  311. static bool endmap_handler(void *closure, const void *hd) {
  312. MessageHeader* msg = closure;
  313. const map_handlerdata_t* mapdata = hd;
  314. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  315. Map_set_frame(map_rb, Qnil);
  316. return true;
  317. }
  318. // Handler to end a map entry: inserts the value defined during the message into
  319. // the map. This is the 'endmsg' handler on the map entry msgdef.
  320. static bool endmapentry_handler(void* closure, const void* hd, upb_status* s) {
  321. map_parse_frame_t* frame = closure;
  322. const map_handlerdata_t* mapdata = hd;
  323. VALUE key = native_slot_get(
  324. mapdata->key_field_type, Qnil,
  325. &frame->key_storage);
  326. VALUE value = native_slot_get(
  327. mapdata->value_field_type, mapdata->subklass,
  328. &frame->value_storage);
  329. Map_index_set(frame->map, key, value);
  330. return true;
  331. }
  332. // Allocates a new map_handlerdata_t given the map entry message definition. If
  333. // the offset of the field within the parent message is also given, that is
  334. // added to the handler data as well. Note that this is called *twice* per map
  335. // field: once in the parent message handler setup when setting the startsubmsg
  336. // handler and once in the map entry message handler setup when setting the
  337. // key/value and endmsg handlers. The reason is that there is no easy way to
  338. // pass the handlerdata down to the sub-message handler setup.
  339. static map_handlerdata_t* new_map_handlerdata(
  340. size_t ofs,
  341. const upb_msgdef* mapentry_def,
  342. const Descriptor* desc) {
  343. const upb_fielddef* key_field;
  344. const upb_fielddef* value_field;
  345. map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
  346. hd->ofs = ofs;
  347. key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
  348. assert(key_field != NULL);
  349. hd->key_field_type = upb_fielddef_type(key_field);
  350. value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
  351. assert(value_field != NULL);
  352. hd->value_field_type = upb_fielddef_type(value_field);
  353. hd->subklass = field_type_class(desc->layout, value_field);
  354. return hd;
  355. }
  356. // Handlers that set primitive values in oneofs.
  357. #define DEFINE_ONEOF_HANDLER(type, ctype) \
  358. static bool oneof##type##_handler(void *closure, const void *hd, \
  359. ctype val) { \
  360. const oneof_handlerdata_t *oneofdata = hd; \
  361. DEREF(closure, oneofdata->case_ofs, uint32_t) = \
  362. oneofdata->oneof_case_num; \
  363. DEREF(closure, oneofdata->ofs, ctype) = val; \
  364. return true; \
  365. }
  366. DEFINE_ONEOF_HANDLER(bool, bool)
  367. DEFINE_ONEOF_HANDLER(int32, int32_t)
  368. DEFINE_ONEOF_HANDLER(uint32, uint32_t)
  369. DEFINE_ONEOF_HANDLER(float, float)
  370. DEFINE_ONEOF_HANDLER(int64, int64_t)
  371. DEFINE_ONEOF_HANDLER(uint64, uint64_t)
  372. DEFINE_ONEOF_HANDLER(double, double)
  373. #undef DEFINE_ONEOF_HANDLER
  374. // Handlers for strings in a oneof.
  375. static void *oneofstr_handler(void *closure,
  376. const void *hd,
  377. size_t size_hint) {
  378. MessageHeader* msg = closure;
  379. const oneof_handlerdata_t *oneofdata = hd;
  380. VALUE str = rb_str_new2("");
  381. rb_enc_associate(str, kRubyStringUtf8Encoding);
  382. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  383. oneofdata->oneof_case_num;
  384. DEREF(msg, oneofdata->ofs, VALUE) = str;
  385. return (void*)str;
  386. }
  387. static void *oneofbytes_handler(void *closure,
  388. const void *hd,
  389. size_t size_hint) {
  390. MessageHeader* msg = closure;
  391. const oneof_handlerdata_t *oneofdata = hd;
  392. VALUE str = rb_str_new2("");
  393. rb_enc_associate(str, kRubyString8bitEncoding);
  394. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  395. oneofdata->oneof_case_num;
  396. DEREF(msg, oneofdata->ofs, VALUE) = str;
  397. return (void*)str;
  398. }
  399. static bool oneofstring_end_handler(void* closure, const void* hd) {
  400. VALUE rb_str = rb_str_new2("");
  401. rb_obj_freeze(rb_str);
  402. return true;
  403. }
  404. // Handler for a submessage field in a oneof.
  405. static void *oneofsubmsg_handler(void *closure,
  406. const void *hd) {
  407. MessageHeader* msg = closure;
  408. const oneof_handlerdata_t *oneofdata = hd;
  409. uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
  410. VALUE submsg_rb;
  411. MessageHeader* submsg;
  412. if (oldcase != oneofdata->oneof_case_num ||
  413. DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
  414. DEREF(msg, oneofdata->ofs, VALUE) =
  415. rb_class_new_instance(0, NULL, oneofdata->subklass);
  416. }
  417. // Set the oneof case *after* allocating the new class instance -- otherwise,
  418. // if the Ruby GC is invoked as part of a call into the VM, it might invoke
  419. // our mark routines, and our mark routines might see the case value
  420. // indicating a VALUE is present and expect a valid VALUE. See comment in
  421. // layout_set() for more detail: basically, the change to the value and the
  422. // case must be atomic w.r.t. the Ruby VM.
  423. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  424. oneofdata->oneof_case_num;
  425. submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
  426. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  427. return submsg;
  428. }
  429. // Set up handlers for a repeated field.
  430. static void add_handlers_for_repeated_field(upb_handlers *h,
  431. const Descriptor* desc,
  432. const upb_fielddef *f,
  433. size_t offset) {
  434. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  435. attr.handler_data = newhandlerdata(h, offset, -1);
  436. upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  437. switch (upb_fielddef_type(f)) {
  438. #define SET_HANDLER(utype, ltype) \
  439. case utype: \
  440. upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
  441. break;
  442. SET_HANDLER(UPB_TYPE_BOOL, bool);
  443. SET_HANDLER(UPB_TYPE_INT32, int32);
  444. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  445. SET_HANDLER(UPB_TYPE_ENUM, int32);
  446. SET_HANDLER(UPB_TYPE_FLOAT, float);
  447. SET_HANDLER(UPB_TYPE_INT64, int64);
  448. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  449. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  450. #undef SET_HANDLER
  451. case UPB_TYPE_STRING:
  452. case UPB_TYPE_BYTES: {
  453. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  454. upb_handlers_setstartstr(h, f, is_bytes ?
  455. appendbytes_handler : appendstr_handler,
  456. NULL);
  457. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  458. upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
  459. break;
  460. }
  461. case UPB_TYPE_MESSAGE: {
  462. VALUE subklass = field_type_class(desc->layout, f);
  463. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  464. attr.handler_data = newsubmsghandlerdata(h, 0, -1, subklass);
  465. upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
  466. break;
  467. }
  468. }
  469. }
  470. static bool doublewrapper_handler(void* closure, const void* hd, double val) {
  471. VALUE* rbval = closure;
  472. *rbval = DBL2NUM(val);
  473. return true;
  474. }
  475. static bool floatwrapper_handler(void* closure, const void* hd, float val) {
  476. VALUE* rbval = closure;
  477. *rbval = DBL2NUM(val);
  478. return true;
  479. }
  480. static bool int64wrapper_handler(void* closure, const void* hd, int64_t val) {
  481. VALUE* rbval = closure;
  482. *rbval = LL2NUM(val);
  483. return true;
  484. }
  485. static bool uint64wrapper_handler(void* closure, const void* hd, uint64_t val) {
  486. VALUE* rbval = closure;
  487. *rbval = ULL2NUM(val);
  488. return true;
  489. }
  490. static bool int32wrapper_handler(void* closure, const void* hd, int32_t val) {
  491. VALUE* rbval = closure;
  492. *rbval = INT2NUM(val);
  493. return true;
  494. }
  495. static bool uint32wrapper_handler(void* closure, const void* hd, uint32_t val) {
  496. VALUE* rbval = closure;
  497. *rbval = UINT2NUM(val);
  498. return true;
  499. }
  500. static size_t stringwrapper_handler(void* closure, const void* hd,
  501. const char* ptr, size_t len,
  502. const upb_bufhandle* handle) {
  503. VALUE* rbval = closure;
  504. *rbval = get_frozen_string(ptr, len, false);
  505. return len;
  506. }
  507. static size_t byteswrapper_handler(void* closure, const void* hd,
  508. const char* ptr, size_t len,
  509. const upb_bufhandle* handle) {
  510. VALUE* rbval = closure;
  511. *rbval = get_frozen_string(ptr, len, true);
  512. return len;
  513. }
  514. static bool boolwrapper_handler(void* closure, const void* hd, bool val) {
  515. VALUE* rbval = closure;
  516. if (val) {
  517. *rbval = Qtrue;
  518. } else {
  519. *rbval = Qfalse;
  520. }
  521. return true;
  522. }
  523. bool is_wrapper(const upb_msgdef* m) {
  524. switch (upb_msgdef_wellknowntype(m)) {
  525. case UPB_WELLKNOWN_DOUBLEVALUE:
  526. case UPB_WELLKNOWN_FLOATVALUE:
  527. case UPB_WELLKNOWN_INT64VALUE:
  528. case UPB_WELLKNOWN_UINT64VALUE:
  529. case UPB_WELLKNOWN_INT32VALUE:
  530. case UPB_WELLKNOWN_UINT32VALUE:
  531. case UPB_WELLKNOWN_STRINGVALUE:
  532. case UPB_WELLKNOWN_BYTESVALUE:
  533. case UPB_WELLKNOWN_BOOLVALUE:
  534. return true;
  535. default:
  536. return false;
  537. }
  538. }
  539. // Set up handlers for a singular field.
  540. static void add_handlers_for_singular_field(const Descriptor* desc,
  541. upb_handlers* h,
  542. const upb_fielddef* f,
  543. size_t offset, size_t hasbit_off) {
  544. // The offset we pass to UPB points to the start of the Message,
  545. // rather than the start of where our data is stored.
  546. int32_t hasbit = -1;
  547. if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
  548. hasbit = hasbit_off + sizeof(MessageHeader) * 8;
  549. }
  550. switch (upb_fielddef_type(f)) {
  551. case UPB_TYPE_BOOL:
  552. case UPB_TYPE_INT32:
  553. case UPB_TYPE_UINT32:
  554. case UPB_TYPE_ENUM:
  555. case UPB_TYPE_FLOAT:
  556. case UPB_TYPE_INT64:
  557. case UPB_TYPE_UINT64:
  558. case UPB_TYPE_DOUBLE:
  559. upb_msg_setscalarhandler(h, f, offset, hasbit);
  560. break;
  561. case UPB_TYPE_STRING:
  562. case UPB_TYPE_BYTES: {
  563. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  564. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  565. attr.handler_data = newhandlerdata(h, offset, hasbit);
  566. upb_handlers_setstartstr(h, f,
  567. is_bytes ? bytes_handler : str_handler,
  568. &attr);
  569. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  570. upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
  571. break;
  572. }
  573. case UPB_TYPE_MESSAGE: {
  574. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  575. attr.handler_data = newsubmsghandlerdata(
  576. h, offset, hasbit, field_type_class(desc->layout, f));
  577. if (is_wrapper(upb_fielddef_msgsubdef(f))) {
  578. upb_handlers_setstartsubmsg(h, f, startwrapper, &attr);
  579. } else {
  580. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  581. }
  582. }
  583. }
  584. }
  585. // Adds handlers to a map field.
  586. static void add_handlers_for_mapfield(upb_handlers* h,
  587. const upb_fielddef* fielddef,
  588. size_t offset,
  589. const Descriptor* desc) {
  590. const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
  591. map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
  592. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  593. upb_handlers_addcleanup(h, hd, xfree);
  594. attr.handler_data = hd;
  595. upb_handlers_setstartsubmsg(h, fielddef, startmap_handler, &attr);
  596. upb_handlers_setendsubmsg(h, fielddef, endmap_handler, &attr);
  597. }
  598. // Adds handlers to a map-entry msgdef.
  599. static void add_handlers_for_mapentry(const upb_msgdef* msgdef, upb_handlers* h,
  600. const Descriptor* desc) {
  601. const upb_fielddef* key_field = map_entry_key(msgdef);
  602. const upb_fielddef* value_field = map_entry_value(msgdef);
  603. map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
  604. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  605. upb_handlers_addcleanup(h, hd, xfree);
  606. attr.handler_data = hd;
  607. upb_handlers_setendmsg(h, endmapentry_handler, &attr);
  608. add_handlers_for_singular_field(
  609. desc, h, key_field,
  610. offsetof(map_parse_frame_t, key_storage),
  611. MESSAGE_FIELD_NO_HASBIT);
  612. add_handlers_for_singular_field(
  613. desc, h, value_field,
  614. offsetof(map_parse_frame_t, value_storage),
  615. MESSAGE_FIELD_NO_HASBIT);
  616. }
  617. static void add_handlers_for_wrapper(const upb_msgdef* msgdef,
  618. upb_handlers* h) {
  619. const upb_fielddef* f = upb_msgdef_itof(msgdef, 1);
  620. switch (upb_msgdef_wellknowntype(msgdef)) {
  621. case UPB_WELLKNOWN_DOUBLEVALUE:
  622. upb_handlers_setdouble(h, f, doublewrapper_handler, NULL);
  623. break;
  624. case UPB_WELLKNOWN_FLOATVALUE:
  625. upb_handlers_setfloat(h, f, floatwrapper_handler, NULL);
  626. break;
  627. case UPB_WELLKNOWN_INT64VALUE:
  628. upb_handlers_setint64(h, f, int64wrapper_handler, NULL);
  629. break;
  630. case UPB_WELLKNOWN_UINT64VALUE:
  631. upb_handlers_setuint64(h, f, uint64wrapper_handler, NULL);
  632. break;
  633. case UPB_WELLKNOWN_INT32VALUE:
  634. upb_handlers_setint32(h, f, int32wrapper_handler, NULL);
  635. break;
  636. case UPB_WELLKNOWN_UINT32VALUE:
  637. upb_handlers_setuint32(h, f, uint32wrapper_handler, NULL);
  638. break;
  639. case UPB_WELLKNOWN_STRINGVALUE:
  640. upb_handlers_setstring(h, f, stringwrapper_handler, NULL);
  641. break;
  642. case UPB_WELLKNOWN_BYTESVALUE:
  643. upb_handlers_setstring(h, f, byteswrapper_handler, NULL);
  644. break;
  645. case UPB_WELLKNOWN_BOOLVALUE:
  646. upb_handlers_setbool(h, f, boolwrapper_handler, NULL);
  647. return;
  648. default:
  649. rb_raise(rb_eRuntimeError,
  650. "Internal logic error with well-known types.");
  651. }
  652. }
  653. // Set up handlers for a oneof field.
  654. static void add_handlers_for_oneof_field(upb_handlers *h,
  655. const upb_fielddef *f,
  656. size_t offset,
  657. size_t oneof_case_offset,
  658. const Descriptor* desc) {
  659. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  660. attr.handler_data =
  661. newoneofhandlerdata(h, offset, oneof_case_offset, f, desc);
  662. switch (upb_fielddef_type(f)) {
  663. #define SET_HANDLER(utype, ltype) \
  664. case utype: \
  665. upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
  666. break;
  667. SET_HANDLER(UPB_TYPE_BOOL, bool);
  668. SET_HANDLER(UPB_TYPE_INT32, int32);
  669. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  670. SET_HANDLER(UPB_TYPE_ENUM, int32);
  671. SET_HANDLER(UPB_TYPE_FLOAT, float);
  672. SET_HANDLER(UPB_TYPE_INT64, int64);
  673. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  674. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  675. #undef SET_HANDLER
  676. case UPB_TYPE_STRING:
  677. case UPB_TYPE_BYTES: {
  678. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  679. upb_handlers_setstartstr(h, f, is_bytes ?
  680. oneofbytes_handler : oneofstr_handler,
  681. &attr);
  682. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  683. upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
  684. break;
  685. }
  686. case UPB_TYPE_MESSAGE: {
  687. upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
  688. break;
  689. }
  690. }
  691. }
  692. static bool unknown_field_handler(void* closure, const void* hd,
  693. const char* buf, size_t size) {
  694. MessageHeader* msg = (MessageHeader*)closure;
  695. UPB_UNUSED(hd);
  696. if (msg->unknown_fields == NULL) {
  697. msg->unknown_fields = malloc(sizeof(stringsink));
  698. stringsink_init(msg->unknown_fields);
  699. }
  700. stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
  701. return true;
  702. }
  703. void add_handlers_for_message(const void *closure, upb_handlers *h) {
  704. const VALUE descriptor_pool = (VALUE)closure;
  705. const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  706. Descriptor* desc =
  707. ruby_to_Descriptor(get_msgdef_obj(descriptor_pool, msgdef));
  708. upb_msg_field_iter i;
  709. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  710. // Ensure layout exists. We may be invoked to create handlers for a given
  711. // message if we are included as a submsg of another message type before our
  712. // class is actually built, so to work around this, we just create the layout
  713. // (and handlers, in the class-building function) on-demand.
  714. if (desc->layout == NULL) {
  715. create_layout(desc);
  716. }
  717. // If this is a mapentry message type, set up a special set of handlers and
  718. // bail out of the normal (user-defined) message type handling.
  719. if (upb_msgdef_mapentry(msgdef)) {
  720. add_handlers_for_mapentry(msgdef, h, desc);
  721. return;
  722. }
  723. // If this is a wrapper type, use special handlers and bail.
  724. if (is_wrapper(msgdef)) {
  725. add_handlers_for_wrapper(msgdef, h);
  726. return;
  727. }
  728. upb_handlers_setunknown(h, unknown_field_handler, &attr);
  729. for (upb_msg_field_begin(&i, desc->msgdef);
  730. !upb_msg_field_done(&i);
  731. upb_msg_field_next(&i)) {
  732. const upb_fielddef *f = upb_msg_iter_field(&i);
  733. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  734. size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
  735. sizeof(MessageHeader);
  736. if (oneof) {
  737. size_t oneof_case_offset =
  738. desc->layout->oneofs[upb_oneofdef_index(oneof)].case_offset +
  739. sizeof(MessageHeader);
  740. add_handlers_for_oneof_field(h, f, offset, oneof_case_offset, desc);
  741. } else if (is_map_field(f)) {
  742. add_handlers_for_mapfield(h, f, offset, desc);
  743. } else if (upb_fielddef_isseq(f)) {
  744. add_handlers_for_repeated_field(h, desc, f, offset);
  745. } else {
  746. add_handlers_for_singular_field(
  747. desc, h, f, offset,
  748. desc->layout->fields[upb_fielddef_index(f)].hasbit);
  749. }
  750. }
  751. }
  752. // Constructs the handlers for filling a message's data into an in-memory
  753. // object.
  754. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  755. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  756. return upb_handlercache_get(pool->fill_handler_cache, desc->msgdef);
  757. }
  758. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  759. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  760. return upb_pbcodecache_get(pool->fill_method_cache, desc->msgdef);
  761. }
  762. static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
  763. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  764. return upb_json_codecache_get(pool->json_fill_method_cache, desc->msgdef);
  765. }
  766. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  767. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  768. return upb_handlercache_get(pool->pb_serialize_handler_cache, desc->msgdef);
  769. }
  770. static const upb_handlers* msgdef_json_serialize_handlers(
  771. Descriptor* desc, bool preserve_proto_fieldnames) {
  772. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  773. if (preserve_proto_fieldnames) {
  774. return upb_handlercache_get(pool->json_serialize_handler_preserve_cache,
  775. desc->msgdef);
  776. } else {
  777. return upb_handlercache_get(pool->json_serialize_handler_cache,
  778. desc->msgdef);
  779. }
  780. }
  781. // Stack-allocated context during an encode/decode operation. Contains the upb
  782. // environment and its stack-based allocator, an initial buffer for allocations
  783. // to avoid malloc() when possible, and a template for Ruby exception messages
  784. // if any error occurs.
  785. #define STACK_ENV_STACKBYTES 4096
  786. typedef struct {
  787. upb_arena *arena;
  788. upb_status status;
  789. const char* ruby_error_template;
  790. char allocbuf[STACK_ENV_STACKBYTES];
  791. } stackenv;
  792. static void stackenv_init(stackenv* se, const char* errmsg);
  793. static void stackenv_uninit(stackenv* se);
  794. static void stackenv_init(stackenv* se, const char* errmsg) {
  795. se->ruby_error_template = errmsg;
  796. se->arena =
  797. upb_arena_init(se->allocbuf, sizeof(se->allocbuf), &upb_alloc_global);
  798. upb_status_clear(&se->status);
  799. }
  800. static void stackenv_uninit(stackenv* se) {
  801. upb_arena_free(se->arena);
  802. if (!upb_ok(&se->status)) {
  803. // TODO(haberman): have a way to verify that this is actually a parse error,
  804. // instead of just throwing "parse error" unconditionally.
  805. VALUE errmsg = rb_str_new2(upb_status_errmsg(&se->status));
  806. rb_raise(cParseError, se->ruby_error_template, errmsg);
  807. }
  808. }
  809. /*
  810. * call-seq:
  811. * MessageClass.decode(data) => message
  812. *
  813. * Decodes the given data (as a string containing bytes in protocol buffers wire
  814. * format) under the interpretration given by this message class's definition
  815. * and returns a message object with the corresponding field values.
  816. */
  817. VALUE Message_decode(VALUE klass, VALUE data) {
  818. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  819. Descriptor* desc = ruby_to_Descriptor(descriptor);
  820. VALUE msgklass = Descriptor_msgclass(descriptor);
  821. VALUE msg_rb;
  822. MessageHeader* msg;
  823. if (TYPE(data) != T_STRING) {
  824. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  825. }
  826. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  827. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  828. {
  829. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  830. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  831. stackenv se;
  832. upb_sink sink;
  833. upb_pbdecoder* decoder;
  834. stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
  835. upb_sink_reset(&sink, h, msg);
  836. decoder = upb_pbdecoder_create(se.arena, method, sink, &se.status);
  837. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  838. upb_pbdecoder_input(decoder));
  839. stackenv_uninit(&se);
  840. }
  841. return msg_rb;
  842. }
  843. /*
  844. * call-seq:
  845. * MessageClass.decode_json(data, options = {}) => message
  846. *
  847. * Decodes the given data (as a string containing bytes in protocol buffers wire
  848. * format) under the interpretration given by this message class's definition
  849. * and returns a message object with the corresponding field values.
  850. *
  851. * @param options [Hash] options for the decoder
  852. * ignore_unknown_fields: set true to ignore unknown fields (default is to
  853. * raise an error)
  854. */
  855. VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
  856. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  857. Descriptor* desc = ruby_to_Descriptor(descriptor);
  858. VALUE msgklass = Descriptor_msgclass(descriptor);
  859. VALUE msg_rb;
  860. VALUE data = argv[0];
  861. VALUE ignore_unknown_fields = Qfalse;
  862. MessageHeader* msg;
  863. if (argc < 1 || argc > 2) {
  864. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  865. }
  866. if (argc == 2) {
  867. VALUE hash_args = argv[1];
  868. if (TYPE(hash_args) != T_HASH) {
  869. rb_raise(rb_eArgError, "Expected hash arguments.");
  870. }
  871. ignore_unknown_fields = rb_hash_lookup2(
  872. hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse);
  873. }
  874. if (TYPE(data) != T_STRING) {
  875. rb_raise(rb_eArgError, "Expected string for JSON data.");
  876. }
  877. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  878. // convert, because string handlers pass data directly to message string
  879. // fields.
  880. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  881. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  882. {
  883. const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
  884. stackenv se;
  885. upb_sink sink;
  886. upb_json_parser* parser;
  887. DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
  888. stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
  889. upb_sink_reset(&sink, get_fill_handlers(desc), msg);
  890. parser = upb_json_parser_create(se.arena, method, pool->symtab, sink,
  891. &se.status, RTEST(ignore_unknown_fields));
  892. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  893. upb_json_parser_input(parser));
  894. stackenv_uninit(&se);
  895. }
  896. return msg_rb;
  897. }
  898. // -----------------------------------------------------------------------------
  899. // Serializing.
  900. // -----------------------------------------------------------------------------
  901. /* msgvisitor *****************************************************************/
  902. static void putmsg(VALUE msg, const Descriptor* desc, upb_sink sink, int depth,
  903. bool emit_defaults, bool is_json, bool open_msg);
  904. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  905. upb_selector_t ret;
  906. bool ok = upb_handlers_getselector(f, type, &ret);
  907. UPB_ASSERT(ok);
  908. return ret;
  909. }
  910. static void putstr(VALUE str, const upb_fielddef *f, upb_sink sink) {
  911. upb_sink subsink;
  912. if (str == Qnil) return;
  913. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  914. // We should be guaranteed that the string has the correct encoding because
  915. // we ensured this at assignment time and then froze the string.
  916. if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
  917. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
  918. } else {
  919. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
  920. }
  921. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  922. &subsink);
  923. upb_sink_putstring(subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  924. RSTRING_LEN(str), NULL);
  925. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  926. }
  927. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink sink,
  928. int depth, bool emit_defaults, bool is_json) {
  929. upb_sink subsink;
  930. VALUE descriptor;
  931. Descriptor* subdesc;
  932. if (submsg == Qnil) return;
  933. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  934. subdesc = ruby_to_Descriptor(descriptor);
  935. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  936. putmsg(submsg, subdesc, subsink, depth + 1, emit_defaults, is_json, true);
  937. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  938. }
  939. static void putary(VALUE ary, const upb_fielddef* f, upb_sink sink, int depth,
  940. bool emit_defaults, bool is_json) {
  941. upb_sink subsink;
  942. upb_fieldtype_t type = upb_fielddef_type(f);
  943. upb_selector_t sel = 0;
  944. int size;
  945. int i;
  946. if (ary == Qnil) return;
  947. if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
  948. size = NUM2INT(RepeatedField_length(ary));
  949. if (size == 0 && !emit_defaults) return;
  950. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  951. if (upb_fielddef_isprimitive(f)) {
  952. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  953. }
  954. for (i = 0; i < size; i++) {
  955. void* memory = RepeatedField_index_native(ary, i);
  956. switch (type) {
  957. #define T(upbtypeconst, upbtype, ctype) \
  958. case upbtypeconst: \
  959. upb_sink_put##upbtype(subsink, sel, *((ctype*)memory)); \
  960. break;
  961. T(UPB_TYPE_FLOAT, float, float)
  962. T(UPB_TYPE_DOUBLE, double, double)
  963. T(UPB_TYPE_BOOL, bool, int8_t)
  964. case UPB_TYPE_ENUM:
  965. T(UPB_TYPE_INT32, int32, int32_t)
  966. T(UPB_TYPE_UINT32, uint32, uint32_t)
  967. T(UPB_TYPE_INT64, int64, int64_t)
  968. T(UPB_TYPE_UINT64, uint64, uint64_t)
  969. case UPB_TYPE_STRING:
  970. case UPB_TYPE_BYTES:
  971. putstr(*((VALUE *)memory), f, subsink);
  972. break;
  973. case UPB_TYPE_MESSAGE:
  974. putsubmsg(*((VALUE*)memory), f, subsink, depth, emit_defaults, is_json);
  975. break;
  976. #undef T
  977. }
  978. }
  979. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  980. }
  981. static void put_ruby_value(VALUE value, const upb_fielddef* f, VALUE type_class,
  982. int depth, upb_sink sink, bool emit_defaults,
  983. bool is_json) {
  984. upb_selector_t sel = 0;
  985. if (depth > ENCODE_MAX_NESTING) {
  986. rb_raise(rb_eRuntimeError,
  987. "Maximum recursion depth exceeded during encoding.");
  988. }
  989. if (upb_fielddef_isprimitive(f)) {
  990. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  991. }
  992. switch (upb_fielddef_type(f)) {
  993. case UPB_TYPE_INT32:
  994. upb_sink_putint32(sink, sel, NUM2INT(value));
  995. break;
  996. case UPB_TYPE_INT64:
  997. upb_sink_putint64(sink, sel, NUM2LL(value));
  998. break;
  999. case UPB_TYPE_UINT32:
  1000. upb_sink_putuint32(sink, sel, NUM2UINT(value));
  1001. break;
  1002. case UPB_TYPE_UINT64:
  1003. upb_sink_putuint64(sink, sel, NUM2ULL(value));
  1004. break;
  1005. case UPB_TYPE_FLOAT:
  1006. upb_sink_putfloat(sink, sel, NUM2DBL(value));
  1007. break;
  1008. case UPB_TYPE_DOUBLE:
  1009. upb_sink_putdouble(sink, sel, NUM2DBL(value));
  1010. break;
  1011. case UPB_TYPE_ENUM: {
  1012. if (TYPE(value) == T_SYMBOL) {
  1013. value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  1014. }
  1015. upb_sink_putint32(sink, sel, NUM2INT(value));
  1016. break;
  1017. }
  1018. case UPB_TYPE_BOOL:
  1019. upb_sink_putbool(sink, sel, value == Qtrue);
  1020. break;
  1021. case UPB_TYPE_STRING:
  1022. case UPB_TYPE_BYTES:
  1023. putstr(value, f, sink);
  1024. break;
  1025. case UPB_TYPE_MESSAGE:
  1026. putsubmsg(value, f, sink, depth, emit_defaults, is_json);
  1027. }
  1028. }
  1029. static void putmap(VALUE map, const upb_fielddef* f, upb_sink sink, int depth,
  1030. bool emit_defaults, bool is_json) {
  1031. Map* self;
  1032. upb_sink subsink;
  1033. const upb_fielddef* key_field;
  1034. const upb_fielddef* value_field;
  1035. Map_iter it;
  1036. if (map == Qnil) return;
  1037. if (!emit_defaults && Map_length(map) == 0) return;
  1038. self = ruby_to_Map(map);
  1039. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1040. assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  1041. key_field = map_field_key(f);
  1042. value_field = map_field_value(f);
  1043. for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
  1044. VALUE key = Map_iter_key(&it);
  1045. VALUE value = Map_iter_value(&it);
  1046. upb_status status;
  1047. upb_sink entry_sink;
  1048. upb_sink_startsubmsg(subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
  1049. &entry_sink);
  1050. upb_sink_startmsg(entry_sink);
  1051. put_ruby_value(key, key_field, Qnil, depth + 1, entry_sink, emit_defaults,
  1052. is_json);
  1053. put_ruby_value(value, value_field, self->value_type_class, depth + 1,
  1054. entry_sink, emit_defaults, is_json);
  1055. upb_sink_endmsg(entry_sink, &status);
  1056. upb_sink_endsubmsg(subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  1057. }
  1058. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1059. }
  1060. static const upb_handlers* msgdef_json_serialize_handlers(
  1061. Descriptor* desc, bool preserve_proto_fieldnames);
  1062. static void putjsonany(VALUE msg_rb, const Descriptor* desc, upb_sink sink,
  1063. int depth, bool emit_defaults) {
  1064. upb_status status;
  1065. MessageHeader* msg = NULL;
  1066. const upb_fielddef* type_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_TYPE);
  1067. const upb_fielddef* value_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_VALUE);
  1068. size_t type_url_offset;
  1069. VALUE type_url_str_rb;
  1070. const upb_msgdef *payload_type = NULL;
  1071. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1072. upb_sink_startmsg(sink);
  1073. /* Handle type url */
  1074. type_url_offset = desc->layout->fields[upb_fielddef_index(type_field)].offset;
  1075. type_url_str_rb = DEREF(Message_data(msg), type_url_offset, VALUE);
  1076. if (RSTRING_LEN(type_url_str_rb) > 0) {
  1077. putstr(type_url_str_rb, type_field, sink);
  1078. }
  1079. {
  1080. const char* type_url_str = RSTRING_PTR(type_url_str_rb);
  1081. size_t type_url_len = RSTRING_LEN(type_url_str_rb);
  1082. DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
  1083. if (type_url_len <= 20 ||
  1084. strncmp(type_url_str, "type.googleapis.com/", 20) != 0) {
  1085. rb_raise(rb_eRuntimeError, "Invalid type url: %s", type_url_str);
  1086. return;
  1087. }
  1088. /* Resolve type url */
  1089. type_url_str += 20;
  1090. type_url_len -= 20;
  1091. payload_type = upb_symtab_lookupmsg2(
  1092. pool->symtab, type_url_str, type_url_len);
  1093. if (payload_type == NULL) {
  1094. rb_raise(rb_eRuntimeError, "Unknown type: %s", type_url_str);
  1095. return;
  1096. }
  1097. }
  1098. {
  1099. uint32_t value_offset;
  1100. VALUE value_str_rb;
  1101. size_t value_len;
  1102. value_offset = desc->layout->fields[upb_fielddef_index(value_field)].offset;
  1103. value_str_rb = DEREF(Message_data(msg), value_offset, VALUE);
  1104. value_len = RSTRING_LEN(value_str_rb);
  1105. if (value_len > 0) {
  1106. VALUE payload_desc_rb = get_msgdef_obj(generated_pool, payload_type);
  1107. Descriptor* payload_desc = ruby_to_Descriptor(payload_desc_rb);
  1108. VALUE payload_class = Descriptor_msgclass(payload_desc_rb);
  1109. upb_sink subsink;
  1110. bool is_wellknown;
  1111. VALUE payload_msg_rb = Message_decode(payload_class, value_str_rb);
  1112. is_wellknown =
  1113. upb_msgdef_wellknowntype(payload_desc->msgdef) !=
  1114. UPB_WELLKNOWN_UNSPECIFIED;
  1115. if (is_wellknown) {
  1116. upb_sink_startstr(sink, getsel(value_field, UPB_HANDLER_STARTSTR), 0,
  1117. &subsink);
  1118. }
  1119. subsink.handlers =
  1120. msgdef_json_serialize_handlers(payload_desc, true);
  1121. subsink.closure = sink.closure;
  1122. putmsg(payload_msg_rb, payload_desc, subsink, depth, emit_defaults, true,
  1123. is_wellknown);
  1124. }
  1125. }
  1126. upb_sink_endmsg(sink, &status);
  1127. }
  1128. static void putjsonlistvalue(
  1129. VALUE msg_rb, const Descriptor* desc,
  1130. upb_sink sink, int depth, bool emit_defaults) {
  1131. upb_status status;
  1132. upb_sink subsink;
  1133. MessageHeader* msg = NULL;
  1134. const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
  1135. uint32_t offset =
  1136. desc->layout->fields[upb_fielddef_index(f)].offset +
  1137. sizeof(MessageHeader);
  1138. VALUE ary;
  1139. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1140. upb_sink_startmsg(sink);
  1141. ary = DEREF(msg, offset, VALUE);
  1142. if (ary == Qnil || RepeatedField_size(ary) == 0) {
  1143. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1144. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1145. } else {
  1146. putary(ary, f, sink, depth, emit_defaults, true);
  1147. }
  1148. upb_sink_endmsg(sink, &status);
  1149. }
  1150. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  1151. upb_sink sink, int depth, bool emit_defaults,
  1152. bool is_json, bool open_msg) {
  1153. MessageHeader* msg;
  1154. upb_msg_field_iter i;
  1155. upb_status status;
  1156. if (is_json &&
  1157. upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
  1158. putjsonany(msg_rb, desc, sink, depth, emit_defaults);
  1159. return;
  1160. }
  1161. if (is_json &&
  1162. upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_LISTVALUE) {
  1163. putjsonlistvalue(msg_rb, desc, sink, depth, emit_defaults);
  1164. return;
  1165. }
  1166. if (open_msg) {
  1167. upb_sink_startmsg(sink);
  1168. }
  1169. // Protect against cycles (possible because users may freely reassign message
  1170. // and repeated fields) by imposing a maximum recursion depth.
  1171. if (depth > ENCODE_MAX_NESTING) {
  1172. rb_raise(rb_eRuntimeError,
  1173. "Maximum recursion depth exceeded during encoding.");
  1174. }
  1175. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1176. if (desc != msg->descriptor) {
  1177. rb_raise(rb_eArgError,
  1178. "The type of given msg is '%s', expect '%s'.",
  1179. upb_msgdef_fullname(msg->descriptor->msgdef),
  1180. upb_msgdef_fullname(desc->msgdef));
  1181. }
  1182. for (upb_msg_field_begin(&i, desc->msgdef);
  1183. !upb_msg_field_done(&i);
  1184. upb_msg_field_next(&i)) {
  1185. upb_fielddef *f = upb_msg_iter_field(&i);
  1186. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  1187. bool is_matching_oneof = false;
  1188. uint32_t offset =
  1189. desc->layout->fields[upb_fielddef_index(f)].offset +
  1190. sizeof(MessageHeader);
  1191. if (oneof) {
  1192. uint32_t oneof_case =
  1193. slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
  1194. // For a oneof, check that this field is actually present -- skip all the
  1195. // below if not.
  1196. if (oneof_case != upb_fielddef_number(f)) {
  1197. continue;
  1198. }
  1199. // Otherwise, fall through to the appropriate singular-field handler
  1200. // below.
  1201. is_matching_oneof = true;
  1202. }
  1203. if (is_map_field(f)) {
  1204. VALUE map = DEREF(msg, offset, VALUE);
  1205. if (map != Qnil || emit_defaults) {
  1206. putmap(map, f, sink, depth, emit_defaults, is_json);
  1207. }
  1208. } else if (upb_fielddef_isseq(f)) {
  1209. VALUE ary = DEREF(msg, offset, VALUE);
  1210. if (ary != Qnil) {
  1211. putary(ary, f, sink, depth, emit_defaults, is_json);
  1212. }
  1213. } else if (upb_fielddef_isstring(f)) {
  1214. VALUE str = DEREF(msg, offset, VALUE);
  1215. bool is_default = false;
  1216. if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
  1217. is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
  1218. } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
  1219. is_default = RSTRING_LEN(str) == 0;
  1220. }
  1221. if (is_matching_oneof || emit_defaults || !is_default) {
  1222. putstr(str, f, sink);
  1223. }
  1224. } else if (upb_fielddef_issubmsg(f)) {
  1225. putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth,
  1226. emit_defaults, is_json);
  1227. } else {
  1228. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  1229. #define T(upbtypeconst, upbtype, ctype, default_value) \
  1230. case upbtypeconst: { \
  1231. ctype value = DEREF(msg, offset, ctype); \
  1232. bool is_default = false; \
  1233. if (upb_fielddef_haspresence(f)) { \
  1234. is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse; \
  1235. } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) { \
  1236. is_default = default_value == value; \
  1237. } \
  1238. if (is_matching_oneof || emit_defaults || !is_default) { \
  1239. upb_sink_put##upbtype(sink, sel, value); \
  1240. } \
  1241. } break;
  1242. switch (upb_fielddef_type(f)) {
  1243. T(UPB_TYPE_FLOAT, float, float, 0.0)
  1244. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  1245. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  1246. case UPB_TYPE_ENUM:
  1247. T(UPB_TYPE_INT32, int32, int32_t, 0)
  1248. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  1249. T(UPB_TYPE_INT64, int64, int64_t, 0)
  1250. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  1251. case UPB_TYPE_STRING:
  1252. case UPB_TYPE_BYTES:
  1253. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  1254. }
  1255. #undef T
  1256. }
  1257. }
  1258. {
  1259. stringsink* unknown = msg->unknown_fields;
  1260. if (unknown != NULL) {
  1261. upb_sink_putunknown(sink, unknown->ptr, unknown->len);
  1262. }
  1263. }
  1264. if (open_msg) {
  1265. upb_sink_endmsg(sink, &status);
  1266. }
  1267. }
  1268. /*
  1269. * call-seq:
  1270. * MessageClass.encode(msg) => bytes
  1271. *
  1272. * Encodes the given message object to its serialized form in protocol buffers
  1273. * wire format.
  1274. */
  1275. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  1276. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1277. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1278. stringsink sink;
  1279. stringsink_init(&sink);
  1280. {
  1281. const upb_handlers* serialize_handlers =
  1282. msgdef_pb_serialize_handlers(desc);
  1283. stackenv se;
  1284. upb_pb_encoder* encoder;
  1285. VALUE ret;
  1286. stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
  1287. encoder = upb_pb_encoder_create(se.arena, serialize_handlers, sink.sink);
  1288. putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false, false, true);
  1289. ret = rb_str_new(sink.ptr, sink.len);
  1290. stackenv_uninit(&se);
  1291. stringsink_uninit(&sink);
  1292. return ret;
  1293. }
  1294. }
  1295. /*
  1296. * call-seq:
  1297. * MessageClass.encode_json(msg, options = {}) => json_string
  1298. *
  1299. * Encodes the given message object into its serialized JSON representation.
  1300. * @param options [Hash] options for the decoder
  1301. * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
  1302. * emit_defaults: set true to emit 0/false values (default is to omit them)
  1303. */
  1304. VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
  1305. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1306. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1307. VALUE msg_rb;
  1308. VALUE preserve_proto_fieldnames = Qfalse;
  1309. VALUE emit_defaults = Qfalse;
  1310. stringsink sink;
  1311. if (argc < 1 || argc > 2) {
  1312. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  1313. }
  1314. msg_rb = argv[0];
  1315. if (argc == 2) {
  1316. VALUE hash_args = argv[1];
  1317. if (TYPE(hash_args) != T_HASH) {
  1318. rb_raise(rb_eArgError, "Expected hash arguments.");
  1319. }
  1320. preserve_proto_fieldnames = rb_hash_lookup2(
  1321. hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
  1322. emit_defaults = rb_hash_lookup2(
  1323. hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
  1324. }
  1325. stringsink_init(&sink);
  1326. {
  1327. const upb_handlers* serialize_handlers =
  1328. msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
  1329. upb_json_printer* printer;
  1330. stackenv se;
  1331. VALUE ret;
  1332. stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
  1333. printer = upb_json_printer_create(se.arena, serialize_handlers, sink.sink);
  1334. putmsg(msg_rb, desc, upb_json_printer_input(printer), 0,
  1335. RTEST(emit_defaults), true, true);
  1336. ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
  1337. stackenv_uninit(&se);
  1338. stringsink_uninit(&sink);
  1339. return ret;
  1340. }
  1341. }
  1342. static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
  1343. MessageHeader* msg;
  1344. upb_msg_field_iter it;
  1345. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1346. {
  1347. stringsink* unknown = msg->unknown_fields;
  1348. if (unknown != NULL) {
  1349. stringsink_uninit(unknown);
  1350. msg->unknown_fields = NULL;
  1351. }
  1352. }
  1353. for (upb_msg_field_begin(&it, desc->msgdef);
  1354. !upb_msg_field_done(&it);
  1355. upb_msg_field_next(&it)) {
  1356. upb_fielddef *f = upb_msg_iter_field(&it);
  1357. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  1358. uint32_t offset =
  1359. desc->layout->fields[upb_fielddef_index(f)].offset +
  1360. sizeof(MessageHeader);
  1361. if (oneof) {
  1362. uint32_t oneof_case =
  1363. slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
  1364. // For a oneof, check that this field is actually present -- skip all the
  1365. // below if not.
  1366. if (oneof_case != upb_fielddef_number(f)) {
  1367. continue;
  1368. }
  1369. // Otherwise, fall through to the appropriate singular-field handler
  1370. // below.
  1371. }
  1372. if (!upb_fielddef_issubmsg(f)) {
  1373. continue;
  1374. }
  1375. if (is_map_field(f)) {
  1376. VALUE map;
  1377. Map_iter map_it;
  1378. if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
  1379. map = DEREF(msg, offset, VALUE);
  1380. if (map == Qnil) continue;
  1381. for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
  1382. VALUE submsg = Map_iter_value(&map_it);
  1383. VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1384. const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  1385. discard_unknown(submsg, subdesc);
  1386. }
  1387. } else if (upb_fielddef_isseq(f)) {
  1388. VALUE ary = DEREF(msg, offset, VALUE);
  1389. int size;
  1390. int i;
  1391. if (ary == Qnil) continue;
  1392. size = NUM2INT(RepeatedField_length(ary));
  1393. for (i = 0; i < size; i++) {
  1394. void* memory = RepeatedField_index_native(ary, i);
  1395. VALUE submsg = *((VALUE *)memory);
  1396. VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1397. const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  1398. discard_unknown(submsg, subdesc);
  1399. }
  1400. } else {
  1401. VALUE submsg = DEREF(msg, offset, VALUE);
  1402. VALUE descriptor;
  1403. const Descriptor* subdesc;
  1404. if (submsg == Qnil) continue;
  1405. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1406. subdesc = ruby_to_Descriptor(descriptor);
  1407. discard_unknown(submsg, subdesc);
  1408. }
  1409. }
  1410. }
  1411. /*
  1412. * call-seq:
  1413. * Google::Protobuf.discard_unknown(msg)
  1414. *
  1415. * Discard unknown fields in the given message object and recursively discard
  1416. * unknown fields in submessages.
  1417. */
  1418. VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
  1419. VALUE klass = CLASS_OF(msg_rb);
  1420. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1421. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1422. if (klass == cRepeatedField || klass == cMap) {
  1423. rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
  1424. } else {
  1425. discard_unknown(msg_rb, desc);
  1426. }
  1427. return Qnil;
  1428. }