encode_decode.c 58 KB

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