encode_decode.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  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 = get_frozen_string(NULL, 0, false);
  538. return closure;
  539. }
  540. static size_t stringwrapper_handler(void* closure, const void* hd,
  541. const char* ptr, size_t len,
  542. const upb_bufhandle* handle) {
  543. VALUE* rbval = closure;
  544. *rbval = get_frozen_string(ptr, len, false);
  545. return len;
  546. }
  547. static void* startbyteswrapper_handler(void* closure, const void* hd,
  548. size_t size_hint) {
  549. VALUE* rbval = closure;
  550. (void)size_hint;
  551. *rbval = get_frozen_string(NULL, 0, true);
  552. return closure;
  553. }
  554. static size_t byteswrapper_handler(void* closure, const void* hd,
  555. const char* ptr, size_t len,
  556. const upb_bufhandle* handle) {
  557. VALUE* rbval = closure;
  558. *rbval = get_frozen_string(ptr, len, true);
  559. return len;
  560. }
  561. static bool boolwrapper_handler(void* closure, const void* hd, bool val) {
  562. VALUE* rbval = closure;
  563. if (val) {
  564. *rbval = Qtrue;
  565. } else {
  566. *rbval = Qfalse;
  567. }
  568. return true;
  569. }
  570. // Set up handlers for a singular field.
  571. static void add_handlers_for_singular_field(const Descriptor* desc,
  572. upb_handlers* h,
  573. const upb_fielddef* f,
  574. size_t offset, size_t hasbit_off) {
  575. // The offset we pass to UPB points to the start of the Message,
  576. // rather than the start of where our data is stored.
  577. int32_t hasbit = -1;
  578. if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
  579. hasbit = hasbit_off + sizeof(MessageHeader) * 8;
  580. }
  581. switch (upb_fielddef_type(f)) {
  582. case UPB_TYPE_BOOL:
  583. case UPB_TYPE_INT32:
  584. case UPB_TYPE_UINT32:
  585. case UPB_TYPE_ENUM:
  586. case UPB_TYPE_FLOAT:
  587. case UPB_TYPE_INT64:
  588. case UPB_TYPE_UINT64:
  589. case UPB_TYPE_DOUBLE:
  590. upb_msg_setscalarhandler(h, f, offset, hasbit);
  591. break;
  592. case UPB_TYPE_STRING:
  593. case UPB_TYPE_BYTES: {
  594. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  595. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  596. attr.handler_data = newhandlerdata(h, offset, hasbit);
  597. upb_handlers_setstartstr(h, f,
  598. is_bytes ? bytes_handler : str_handler,
  599. &attr);
  600. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  601. upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
  602. break;
  603. }
  604. case UPB_TYPE_MESSAGE: {
  605. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  606. attr.handler_data = newsubmsghandlerdata(
  607. h, offset, hasbit, field_type_class(desc->layout, f));
  608. if (is_wrapper(upb_fielddef_msgsubdef(f))) {
  609. upb_handlers_setstartsubmsg(h, f, startwrapper, &attr);
  610. } else {
  611. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  612. }
  613. }
  614. }
  615. }
  616. // Adds handlers to a map field.
  617. static void add_handlers_for_mapfield(upb_handlers* h,
  618. const upb_fielddef* fielddef,
  619. size_t offset,
  620. const Descriptor* desc) {
  621. const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
  622. map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
  623. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  624. upb_handlers_addcleanup(h, hd, xfree);
  625. attr.handler_data = hd;
  626. upb_handlers_setstartsubmsg(h, fielddef, startmap_handler, &attr);
  627. upb_handlers_setendsubmsg(h, fielddef, endmap_handler, &attr);
  628. }
  629. // Adds handlers to a map-entry msgdef.
  630. static void add_handlers_for_mapentry(const upb_msgdef* msgdef, upb_handlers* h,
  631. const Descriptor* desc) {
  632. const upb_fielddef* key_field = map_entry_key(msgdef);
  633. const upb_fielddef* value_field = map_entry_value(msgdef);
  634. map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
  635. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  636. upb_handlers_addcleanup(h, hd, xfree);
  637. attr.handler_data = hd;
  638. upb_handlers_setendmsg(h, endmapentry_handler, &attr);
  639. add_handlers_for_singular_field(
  640. desc, h, key_field,
  641. offsetof(map_parse_frame_t, key_storage),
  642. MESSAGE_FIELD_NO_HASBIT);
  643. add_handlers_for_singular_field(
  644. desc, h, value_field,
  645. offsetof(map_parse_frame_t, value_storage),
  646. MESSAGE_FIELD_NO_HASBIT);
  647. }
  648. static void add_handlers_for_wrapper(const upb_msgdef* msgdef,
  649. upb_handlers* h) {
  650. const upb_fielddef* f = upb_msgdef_itof(msgdef, 1);
  651. switch (upb_msgdef_wellknowntype(msgdef)) {
  652. case UPB_WELLKNOWN_DOUBLEVALUE:
  653. upb_handlers_setdouble(h, f, doublewrapper_handler, NULL);
  654. break;
  655. case UPB_WELLKNOWN_FLOATVALUE:
  656. upb_handlers_setfloat(h, f, floatwrapper_handler, NULL);
  657. break;
  658. case UPB_WELLKNOWN_INT64VALUE:
  659. upb_handlers_setint64(h, f, int64wrapper_handler, NULL);
  660. break;
  661. case UPB_WELLKNOWN_UINT64VALUE:
  662. upb_handlers_setuint64(h, f, uint64wrapper_handler, NULL);
  663. break;
  664. case UPB_WELLKNOWN_INT32VALUE:
  665. upb_handlers_setint32(h, f, int32wrapper_handler, NULL);
  666. break;
  667. case UPB_WELLKNOWN_UINT32VALUE:
  668. upb_handlers_setuint32(h, f, uint32wrapper_handler, NULL);
  669. break;
  670. case UPB_WELLKNOWN_STRINGVALUE:
  671. upb_handlers_setstartstr(h, f, startstringwrapper_handler, NULL);
  672. upb_handlers_setstring(h, f, stringwrapper_handler, NULL);
  673. break;
  674. case UPB_WELLKNOWN_BYTESVALUE:
  675. upb_handlers_setstartstr(h, f, startbyteswrapper_handler, NULL);
  676. upb_handlers_setstring(h, f, byteswrapper_handler, NULL);
  677. break;
  678. case UPB_WELLKNOWN_BOOLVALUE:
  679. upb_handlers_setbool(h, f, boolwrapper_handler, NULL);
  680. return;
  681. default:
  682. rb_raise(rb_eRuntimeError,
  683. "Internal logic error with well-known types.");
  684. }
  685. }
  686. // Set up handlers for a oneof field.
  687. static void add_handlers_for_oneof_field(upb_handlers *h,
  688. const upb_fielddef *f,
  689. size_t offset,
  690. size_t oneof_case_offset,
  691. const Descriptor* desc) {
  692. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  693. attr.handler_data =
  694. newoneofhandlerdata(h, offset, oneof_case_offset, f, desc);
  695. switch (upb_fielddef_type(f)) {
  696. #define SET_HANDLER(utype, ltype) \
  697. case utype: \
  698. upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
  699. break;
  700. SET_HANDLER(UPB_TYPE_BOOL, bool);
  701. SET_HANDLER(UPB_TYPE_INT32, int32);
  702. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  703. SET_HANDLER(UPB_TYPE_ENUM, int32);
  704. SET_HANDLER(UPB_TYPE_FLOAT, float);
  705. SET_HANDLER(UPB_TYPE_INT64, int64);
  706. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  707. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  708. #undef SET_HANDLER
  709. case UPB_TYPE_STRING:
  710. case UPB_TYPE_BYTES: {
  711. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  712. upb_handlers_setstartstr(h, f, is_bytes ?
  713. oneofbytes_handler : oneofstr_handler,
  714. &attr);
  715. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  716. upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
  717. break;
  718. }
  719. case UPB_TYPE_MESSAGE: {
  720. if (is_wrapper(upb_fielddef_msgsubdef(f))) {
  721. upb_handlers_setstartsubmsg(h, f, oneof_startwrapper, &attr);
  722. } else {
  723. upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
  724. }
  725. break;
  726. }
  727. }
  728. }
  729. static bool unknown_field_handler(void* closure, const void* hd,
  730. const char* buf, size_t size) {
  731. MessageHeader* msg = (MessageHeader*)closure;
  732. UPB_UNUSED(hd);
  733. if (msg->unknown_fields == NULL) {
  734. msg->unknown_fields = malloc(sizeof(stringsink));
  735. stringsink_init(msg->unknown_fields);
  736. }
  737. stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
  738. return true;
  739. }
  740. size_t get_field_offset(MessageLayout* layout, const upb_fielddef* f) {
  741. return layout->fields[upb_fielddef_index(f)].offset + sizeof(MessageHeader);
  742. }
  743. void add_handlers_for_message(const void *closure, upb_handlers *h) {
  744. const VALUE descriptor_pool = (VALUE)closure;
  745. const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  746. Descriptor* desc =
  747. ruby_to_Descriptor(get_msgdef_obj(descriptor_pool, msgdef));
  748. upb_msg_field_iter i;
  749. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  750. // Ensure layout exists. We may be invoked to create handlers for a given
  751. // message if we are included as a submsg of another message type before our
  752. // class is actually built, so to work around this, we just create the layout
  753. // (and handlers, in the class-building function) on-demand.
  754. if (desc->layout == NULL) {
  755. create_layout(desc);
  756. }
  757. // If this is a mapentry message type, set up a special set of handlers and
  758. // bail out of the normal (user-defined) message type handling.
  759. if (upb_msgdef_mapentry(msgdef)) {
  760. add_handlers_for_mapentry(msgdef, h, desc);
  761. return;
  762. }
  763. // If this is a wrapper type, use special handlers and bail.
  764. if (is_wrapper(msgdef)) {
  765. add_handlers_for_wrapper(msgdef, h);
  766. return;
  767. }
  768. upb_handlers_setunknown(h, unknown_field_handler, &attr);
  769. for (upb_msg_field_begin(&i, desc->msgdef);
  770. !upb_msg_field_done(&i);
  771. upb_msg_field_next(&i)) {
  772. const upb_fielddef *f = upb_msg_iter_field(&i);
  773. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  774. size_t offset = get_field_offset(desc->layout, f);
  775. if (oneof) {
  776. size_t oneof_case_offset =
  777. desc->layout->oneofs[upb_oneofdef_index(oneof)].case_offset +
  778. sizeof(MessageHeader);
  779. add_handlers_for_oneof_field(h, f, offset, oneof_case_offset, desc);
  780. } else if (is_map_field(f)) {
  781. add_handlers_for_mapfield(h, f, offset, desc);
  782. } else if (upb_fielddef_isseq(f)) {
  783. add_handlers_for_repeated_field(h, desc, f, offset);
  784. } else {
  785. add_handlers_for_singular_field(
  786. desc, h, f, offset,
  787. desc->layout->fields[upb_fielddef_index(f)].hasbit);
  788. }
  789. }
  790. }
  791. // Constructs the handlers for filling a message's data into an in-memory
  792. // object.
  793. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  794. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  795. return upb_handlercache_get(pool->fill_handler_cache, desc->msgdef);
  796. }
  797. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  798. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  799. return upb_pbcodecache_get(pool->fill_method_cache, desc->msgdef);
  800. }
  801. static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
  802. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  803. return upb_json_codecache_get(pool->json_fill_method_cache, desc->msgdef);
  804. }
  805. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  806. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  807. return upb_handlercache_get(pool->pb_serialize_handler_cache, desc->msgdef);
  808. }
  809. static const upb_handlers* msgdef_json_serialize_handlers(
  810. Descriptor* desc, bool preserve_proto_fieldnames) {
  811. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  812. if (preserve_proto_fieldnames) {
  813. return upb_handlercache_get(pool->json_serialize_handler_preserve_cache,
  814. desc->msgdef);
  815. } else {
  816. return upb_handlercache_get(pool->json_serialize_handler_cache,
  817. desc->msgdef);
  818. }
  819. }
  820. // Stack-allocated context during an encode/decode operation. Contains the upb
  821. // environment and its stack-based allocator, an initial buffer for allocations
  822. // to avoid malloc() when possible, and a template for Ruby exception messages
  823. // if any error occurs.
  824. #define STACK_ENV_STACKBYTES 4096
  825. typedef struct {
  826. upb_arena *arena;
  827. upb_status status;
  828. const char* ruby_error_template;
  829. char allocbuf[STACK_ENV_STACKBYTES];
  830. } stackenv;
  831. static void stackenv_init(stackenv* se, const char* errmsg);
  832. static void stackenv_uninit(stackenv* se);
  833. static void stackenv_init(stackenv* se, const char* errmsg) {
  834. se->ruby_error_template = errmsg;
  835. se->arena =
  836. upb_arena_init(se->allocbuf, sizeof(se->allocbuf), &upb_alloc_global);
  837. upb_status_clear(&se->status);
  838. }
  839. static void stackenv_uninit(stackenv* se) {
  840. upb_arena_free(se->arena);
  841. if (!upb_ok(&se->status)) {
  842. // TODO(haberman): have a way to verify that this is actually a parse error,
  843. // instead of just throwing "parse error" unconditionally.
  844. VALUE errmsg = rb_str_new2(upb_status_errmsg(&se->status));
  845. rb_raise(cParseError, se->ruby_error_template, errmsg);
  846. }
  847. }
  848. /*
  849. * call-seq:
  850. * MessageClass.decode(data) => message
  851. *
  852. * Decodes the given data (as a string containing bytes in protocol buffers wire
  853. * format) under the interpretration given by this message class's definition
  854. * and returns a message object with the corresponding field values.
  855. */
  856. VALUE Message_decode(VALUE klass, VALUE data) {
  857. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  858. Descriptor* desc = ruby_to_Descriptor(descriptor);
  859. VALUE msgklass = Descriptor_msgclass(descriptor);
  860. VALUE msg_rb;
  861. MessageHeader* msg;
  862. if (TYPE(data) != T_STRING) {
  863. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  864. }
  865. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  866. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  867. {
  868. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  869. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  870. const upb_msgdef* m = upb_handlers_msgdef(h);
  871. VALUE wrapper = Qnil;
  872. void* ptr = msg;
  873. stackenv se;
  874. upb_sink sink;
  875. upb_pbdecoder* decoder;
  876. stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
  877. if (is_wrapper(m)) {
  878. ptr = &wrapper;
  879. }
  880. upb_sink_reset(&sink, h, ptr);
  881. decoder = upb_pbdecoder_create(se.arena, method, sink, &se.status);
  882. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  883. upb_pbdecoder_input(decoder));
  884. stackenv_uninit(&se);
  885. if (is_wrapper(m)) {
  886. msg_rb = ruby_wrapper_type(msgklass, wrapper);
  887. }
  888. }
  889. return msg_rb;
  890. }
  891. /*
  892. * call-seq:
  893. * MessageClass.decode_json(data, options = {}) => message
  894. *
  895. * Decodes the given data (as a string containing bytes in protocol buffers wire
  896. * format) under the interpretration given by this message class's definition
  897. * and returns a message object with the corresponding field values.
  898. *
  899. * @param options [Hash] options for the decoder
  900. * ignore_unknown_fields: set true to ignore unknown fields (default is to
  901. * raise an error)
  902. */
  903. VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
  904. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  905. Descriptor* desc = ruby_to_Descriptor(descriptor);
  906. VALUE msgklass = Descriptor_msgclass(descriptor);
  907. VALUE msg_rb;
  908. VALUE data = argv[0];
  909. VALUE ignore_unknown_fields = Qfalse;
  910. MessageHeader* msg;
  911. if (argc < 1 || argc > 2) {
  912. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  913. }
  914. if (argc == 2) {
  915. VALUE hash_args = argv[1];
  916. if (TYPE(hash_args) != T_HASH) {
  917. rb_raise(rb_eArgError, "Expected hash arguments.");
  918. }
  919. ignore_unknown_fields = rb_hash_lookup2(
  920. hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse);
  921. }
  922. if (TYPE(data) != T_STRING) {
  923. rb_raise(rb_eArgError, "Expected string for JSON data.");
  924. }
  925. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  926. // convert, because string handlers pass data directly to message string
  927. // fields.
  928. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  929. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  930. {
  931. const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
  932. const upb_handlers* h = get_fill_handlers(desc);
  933. const upb_msgdef* m = upb_handlers_msgdef(h);
  934. stackenv se;
  935. upb_sink sink;
  936. upb_json_parser* parser;
  937. DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
  938. stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
  939. if (is_wrapper(m)) {
  940. rb_raise(
  941. rb_eRuntimeError,
  942. "Parsing a wrapper type from JSON at the top level does not work.");
  943. }
  944. upb_sink_reset(&sink, h, msg);
  945. parser = upb_json_parser_create(se.arena, method, pool->symtab, sink,
  946. &se.status, RTEST(ignore_unknown_fields));
  947. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  948. upb_json_parser_input(parser));
  949. stackenv_uninit(&se);
  950. }
  951. return msg_rb;
  952. }
  953. // -----------------------------------------------------------------------------
  954. // Serializing.
  955. // -----------------------------------------------------------------------------
  956. /* msgvisitor *****************************************************************/
  957. static void putmsg(VALUE msg, const Descriptor* desc, upb_sink sink, int depth,
  958. bool emit_defaults, bool is_json, bool open_msg);
  959. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  960. upb_selector_t ret;
  961. bool ok = upb_handlers_getselector(f, type, &ret);
  962. UPB_ASSERT(ok);
  963. return ret;
  964. }
  965. static void putstr(VALUE str, const upb_fielddef *f, upb_sink sink) {
  966. upb_sink subsink;
  967. if (str == Qnil) return;
  968. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  969. // We should be guaranteed that the string has the correct encoding because
  970. // we ensured this at assignment time and then froze the string.
  971. if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
  972. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
  973. } else {
  974. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
  975. }
  976. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  977. &subsink);
  978. upb_sink_putstring(subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  979. RSTRING_LEN(str), NULL);
  980. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  981. }
  982. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink sink,
  983. int depth, bool emit_defaults, bool is_json) {
  984. upb_sink subsink;
  985. VALUE descriptor;
  986. Descriptor* subdesc;
  987. if (submsg == Qnil) return;
  988. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  989. subdesc = ruby_to_Descriptor(descriptor);
  990. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  991. putmsg(submsg, subdesc, subsink, depth + 1, emit_defaults, is_json, true);
  992. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  993. }
  994. static void putary(VALUE ary, const upb_fielddef* f, upb_sink sink, int depth,
  995. bool emit_defaults, bool is_json) {
  996. upb_sink subsink;
  997. upb_fieldtype_t type = upb_fielddef_type(f);
  998. upb_selector_t sel = 0;
  999. int size;
  1000. int i;
  1001. VALUE type_class = ruby_to_RepeatedField(ary)->field_type_class;
  1002. if (ary == Qnil) return;
  1003. if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
  1004. size = NUM2INT(RepeatedField_length(ary));
  1005. if (size == 0 && !emit_defaults) return;
  1006. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1007. if (upb_fielddef_isprimitive(f)) {
  1008. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  1009. }
  1010. for (i = 0; i < size; i++) {
  1011. void* memory = RepeatedField_index_native(ary, i);
  1012. switch (type) {
  1013. #define T(upbtypeconst, upbtype, ctype) \
  1014. case upbtypeconst: \
  1015. upb_sink_put##upbtype(subsink, sel, *((ctype*)memory)); \
  1016. break;
  1017. T(UPB_TYPE_FLOAT, float, float)
  1018. T(UPB_TYPE_DOUBLE, double, double)
  1019. T(UPB_TYPE_BOOL, bool, int8_t)
  1020. case UPB_TYPE_ENUM:
  1021. T(UPB_TYPE_INT32, int32, int32_t)
  1022. T(UPB_TYPE_UINT32, uint32, uint32_t)
  1023. T(UPB_TYPE_INT64, int64, int64_t)
  1024. T(UPB_TYPE_UINT64, uint64, uint64_t)
  1025. case UPB_TYPE_STRING:
  1026. case UPB_TYPE_BYTES:
  1027. putstr(*((VALUE *)memory), f, subsink);
  1028. break;
  1029. case UPB_TYPE_MESSAGE: {
  1030. VALUE val = native_slot_get(UPB_TYPE_MESSAGE, type_class, memory);
  1031. putsubmsg(val, f, subsink, depth, emit_defaults, is_json);
  1032. break;
  1033. }
  1034. #undef T
  1035. }
  1036. }
  1037. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1038. }
  1039. static void put_ruby_value(VALUE value, const upb_fielddef* f, VALUE type_class,
  1040. int depth, upb_sink sink, bool emit_defaults,
  1041. bool is_json) {
  1042. upb_selector_t sel = 0;
  1043. if (depth > ENCODE_MAX_NESTING) {
  1044. rb_raise(rb_eRuntimeError,
  1045. "Maximum recursion depth exceeded during encoding.");
  1046. }
  1047. if (upb_fielddef_isprimitive(f)) {
  1048. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  1049. }
  1050. switch (upb_fielddef_type(f)) {
  1051. case UPB_TYPE_INT32:
  1052. upb_sink_putint32(sink, sel, NUM2INT(value));
  1053. break;
  1054. case UPB_TYPE_INT64:
  1055. upb_sink_putint64(sink, sel, NUM2LL(value));
  1056. break;
  1057. case UPB_TYPE_UINT32:
  1058. upb_sink_putuint32(sink, sel, NUM2UINT(value));
  1059. break;
  1060. case UPB_TYPE_UINT64:
  1061. upb_sink_putuint64(sink, sel, NUM2ULL(value));
  1062. break;
  1063. case UPB_TYPE_FLOAT:
  1064. upb_sink_putfloat(sink, sel, NUM2DBL(value));
  1065. break;
  1066. case UPB_TYPE_DOUBLE:
  1067. upb_sink_putdouble(sink, sel, NUM2DBL(value));
  1068. break;
  1069. case UPB_TYPE_ENUM: {
  1070. if (TYPE(value) == T_SYMBOL) {
  1071. value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  1072. }
  1073. upb_sink_putint32(sink, sel, NUM2INT(value));
  1074. break;
  1075. }
  1076. case UPB_TYPE_BOOL:
  1077. upb_sink_putbool(sink, sel, value == Qtrue);
  1078. break;
  1079. case UPB_TYPE_STRING:
  1080. case UPB_TYPE_BYTES:
  1081. putstr(value, f, sink);
  1082. break;
  1083. case UPB_TYPE_MESSAGE:
  1084. putsubmsg(value, f, sink, depth, emit_defaults, is_json);
  1085. }
  1086. }
  1087. static void putmap(VALUE map, const upb_fielddef* f, upb_sink sink, int depth,
  1088. bool emit_defaults, bool is_json) {
  1089. Map* self;
  1090. upb_sink subsink;
  1091. const upb_fielddef* key_field;
  1092. const upb_fielddef* value_field;
  1093. Map_iter it;
  1094. if (map == Qnil) return;
  1095. if (!emit_defaults && Map_length(map) == 0) return;
  1096. self = ruby_to_Map(map);
  1097. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1098. assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  1099. key_field = map_field_key(f);
  1100. value_field = map_field_value(f);
  1101. for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
  1102. VALUE key = Map_iter_key(&it);
  1103. VALUE value = Map_iter_value(&it);
  1104. upb_status status;
  1105. upb_sink entry_sink;
  1106. upb_sink_startsubmsg(subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
  1107. &entry_sink);
  1108. upb_sink_startmsg(entry_sink);
  1109. put_ruby_value(key, key_field, Qnil, depth + 1, entry_sink, emit_defaults,
  1110. is_json);
  1111. put_ruby_value(value, value_field, self->value_type_class, depth + 1,
  1112. entry_sink, emit_defaults, is_json);
  1113. upb_sink_endmsg(entry_sink, &status);
  1114. upb_sink_endsubmsg(subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  1115. }
  1116. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1117. }
  1118. static const upb_handlers* msgdef_json_serialize_handlers(
  1119. Descriptor* desc, bool preserve_proto_fieldnames);
  1120. static void putjsonany(VALUE msg_rb, const Descriptor* desc, upb_sink sink,
  1121. int depth, bool emit_defaults) {
  1122. upb_status status;
  1123. MessageHeader* msg = NULL;
  1124. const upb_fielddef* type_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_TYPE);
  1125. const upb_fielddef* value_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_VALUE);
  1126. size_t type_url_offset;
  1127. VALUE type_url_str_rb;
  1128. const upb_msgdef *payload_type = NULL;
  1129. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1130. upb_sink_startmsg(sink);
  1131. /* Handle type url */
  1132. type_url_offset = desc->layout->fields[upb_fielddef_index(type_field)].offset;
  1133. type_url_str_rb = DEREF(Message_data(msg), type_url_offset, VALUE);
  1134. if (RSTRING_LEN(type_url_str_rb) > 0) {
  1135. putstr(type_url_str_rb, type_field, sink);
  1136. }
  1137. {
  1138. const char* type_url_str = RSTRING_PTR(type_url_str_rb);
  1139. size_t type_url_len = RSTRING_LEN(type_url_str_rb);
  1140. DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
  1141. if (type_url_len <= 20 ||
  1142. strncmp(type_url_str, "type.googleapis.com/", 20) != 0) {
  1143. rb_raise(rb_eRuntimeError, "Invalid type url: %s", type_url_str);
  1144. return;
  1145. }
  1146. /* Resolve type url */
  1147. type_url_str += 20;
  1148. type_url_len -= 20;
  1149. payload_type = upb_symtab_lookupmsg2(
  1150. pool->symtab, type_url_str, type_url_len);
  1151. if (payload_type == NULL) {
  1152. rb_raise(rb_eRuntimeError, "Unknown type: %s", type_url_str);
  1153. return;
  1154. }
  1155. }
  1156. {
  1157. uint32_t value_offset;
  1158. VALUE value_str_rb;
  1159. size_t value_len;
  1160. value_offset = desc->layout->fields[upb_fielddef_index(value_field)].offset;
  1161. value_str_rb = DEREF(Message_data(msg), value_offset, VALUE);
  1162. value_len = RSTRING_LEN(value_str_rb);
  1163. if (value_len > 0) {
  1164. VALUE payload_desc_rb = get_msgdef_obj(generated_pool, payload_type);
  1165. Descriptor* payload_desc = ruby_to_Descriptor(payload_desc_rb);
  1166. VALUE payload_class = Descriptor_msgclass(payload_desc_rb);
  1167. upb_sink subsink;
  1168. bool is_wellknown;
  1169. VALUE payload_msg_rb = Message_decode(payload_class, value_str_rb);
  1170. is_wellknown =
  1171. upb_msgdef_wellknowntype(payload_desc->msgdef) !=
  1172. UPB_WELLKNOWN_UNSPECIFIED;
  1173. if (is_wellknown) {
  1174. upb_sink_startstr(sink, getsel(value_field, UPB_HANDLER_STARTSTR), 0,
  1175. &subsink);
  1176. }
  1177. subsink.handlers =
  1178. msgdef_json_serialize_handlers(payload_desc, true);
  1179. subsink.closure = sink.closure;
  1180. putmsg(payload_msg_rb, payload_desc, subsink, depth, emit_defaults, true,
  1181. is_wellknown);
  1182. }
  1183. }
  1184. upb_sink_endmsg(sink, &status);
  1185. }
  1186. static void putjsonlistvalue(
  1187. VALUE msg_rb, const Descriptor* desc,
  1188. upb_sink sink, int depth, bool emit_defaults) {
  1189. upb_status status;
  1190. upb_sink subsink;
  1191. MessageHeader* msg = NULL;
  1192. const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
  1193. uint32_t offset =
  1194. desc->layout->fields[upb_fielddef_index(f)].offset +
  1195. sizeof(MessageHeader);
  1196. VALUE ary;
  1197. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1198. upb_sink_startmsg(sink);
  1199. ary = DEREF(msg, offset, VALUE);
  1200. if (ary == Qnil || RepeatedField_size(ary) == 0) {
  1201. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1202. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1203. } else {
  1204. putary(ary, f, sink, depth, emit_defaults, true);
  1205. }
  1206. upb_sink_endmsg(sink, &status);
  1207. }
  1208. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  1209. upb_sink sink, int depth, bool emit_defaults,
  1210. bool is_json, bool open_msg) {
  1211. MessageHeader* msg;
  1212. upb_msg_field_iter i;
  1213. upb_status status;
  1214. if (is_json &&
  1215. upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
  1216. putjsonany(msg_rb, desc, sink, depth, emit_defaults);
  1217. return;
  1218. }
  1219. if (is_json &&
  1220. upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_LISTVALUE) {
  1221. putjsonlistvalue(msg_rb, desc, sink, depth, emit_defaults);
  1222. return;
  1223. }
  1224. if (open_msg) {
  1225. upb_sink_startmsg(sink);
  1226. }
  1227. // Protect against cycles (possible because users may freely reassign message
  1228. // and repeated fields) by imposing a maximum recursion depth.
  1229. if (depth > ENCODE_MAX_NESTING) {
  1230. rb_raise(rb_eRuntimeError,
  1231. "Maximum recursion depth exceeded during encoding.");
  1232. }
  1233. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1234. if (desc != msg->descriptor) {
  1235. rb_raise(rb_eArgError,
  1236. "The type of given msg is '%s', expect '%s'.",
  1237. upb_msgdef_fullname(msg->descriptor->msgdef),
  1238. upb_msgdef_fullname(desc->msgdef));
  1239. }
  1240. for (upb_msg_field_begin(&i, desc->msgdef);
  1241. !upb_msg_field_done(&i);
  1242. upb_msg_field_next(&i)) {
  1243. upb_fielddef *f = upb_msg_iter_field(&i);
  1244. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  1245. bool is_matching_oneof = false;
  1246. uint32_t offset =
  1247. desc->layout->fields[upb_fielddef_index(f)].offset +
  1248. sizeof(MessageHeader);
  1249. if (oneof) {
  1250. uint32_t oneof_case =
  1251. slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
  1252. // For a oneof, check that this field is actually present -- skip all the
  1253. // below if not.
  1254. if (oneof_case != upb_fielddef_number(f)) {
  1255. continue;
  1256. }
  1257. // Otherwise, fall through to the appropriate singular-field handler
  1258. // below.
  1259. is_matching_oneof = true;
  1260. }
  1261. if (is_map_field(f)) {
  1262. VALUE map = DEREF(msg, offset, VALUE);
  1263. if (map != Qnil || emit_defaults) {
  1264. putmap(map, f, sink, depth, emit_defaults, is_json);
  1265. }
  1266. } else if (upb_fielddef_isseq(f)) {
  1267. VALUE ary = DEREF(msg, offset, VALUE);
  1268. if (ary != Qnil) {
  1269. putary(ary, f, sink, depth, emit_defaults, is_json);
  1270. }
  1271. } else if (upb_fielddef_isstring(f)) {
  1272. VALUE str = DEREF(msg, offset, VALUE);
  1273. bool is_default = false;
  1274. if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
  1275. is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
  1276. } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
  1277. is_default = RSTRING_LEN(str) == 0;
  1278. }
  1279. if (is_matching_oneof || emit_defaults || !is_default) {
  1280. putstr(str, f, sink);
  1281. }
  1282. } else if (upb_fielddef_issubmsg(f)) {
  1283. // OPT: could try to avoid the layout_get() (which will expand lazy
  1284. // wrappers).
  1285. VALUE val = layout_get(desc->layout, Message_data(msg), f);
  1286. putsubmsg(val, f, sink, depth, emit_defaults, is_json);
  1287. } else {
  1288. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  1289. #define T(upbtypeconst, upbtype, ctype, default_value) \
  1290. case upbtypeconst: { \
  1291. ctype value = DEREF(msg, offset, ctype); \
  1292. bool is_default = false; \
  1293. if (upb_fielddef_haspresence(f)) { \
  1294. is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse; \
  1295. } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) { \
  1296. is_default = default_value == value; \
  1297. } \
  1298. if (is_matching_oneof || emit_defaults || !is_default) { \
  1299. upb_sink_put##upbtype(sink, sel, value); \
  1300. } \
  1301. } break;
  1302. switch (upb_fielddef_type(f)) {
  1303. T(UPB_TYPE_FLOAT, float, float, 0.0)
  1304. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  1305. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  1306. case UPB_TYPE_ENUM:
  1307. T(UPB_TYPE_INT32, int32, int32_t, 0)
  1308. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  1309. T(UPB_TYPE_INT64, int64, int64_t, 0)
  1310. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  1311. case UPB_TYPE_STRING:
  1312. case UPB_TYPE_BYTES:
  1313. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  1314. }
  1315. #undef T
  1316. }
  1317. }
  1318. {
  1319. stringsink* unknown = msg->unknown_fields;
  1320. if (unknown != NULL) {
  1321. upb_sink_putunknown(sink, unknown->ptr, unknown->len);
  1322. }
  1323. }
  1324. if (open_msg) {
  1325. upb_sink_endmsg(sink, &status);
  1326. }
  1327. }
  1328. /*
  1329. * call-seq:
  1330. * MessageClass.encode(msg) => bytes
  1331. *
  1332. * Encodes the given message object to its serialized form in protocol buffers
  1333. * wire format.
  1334. */
  1335. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  1336. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1337. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1338. stringsink sink;
  1339. stringsink_init(&sink);
  1340. {
  1341. const upb_handlers* serialize_handlers =
  1342. msgdef_pb_serialize_handlers(desc);
  1343. stackenv se;
  1344. upb_pb_encoder* encoder;
  1345. VALUE ret;
  1346. stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
  1347. encoder = upb_pb_encoder_create(se.arena, serialize_handlers, sink.sink);
  1348. putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false, false, true);
  1349. ret = rb_str_new(sink.ptr, sink.len);
  1350. stackenv_uninit(&se);
  1351. stringsink_uninit(&sink);
  1352. return ret;
  1353. }
  1354. }
  1355. /*
  1356. * call-seq:
  1357. * MessageClass.encode_json(msg, options = {}) => json_string
  1358. *
  1359. * Encodes the given message object into its serialized JSON representation.
  1360. * @param options [Hash] options for the decoder
  1361. * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
  1362. * emit_defaults: set true to emit 0/false values (default is to omit them)
  1363. */
  1364. VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
  1365. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1366. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1367. VALUE msg_rb;
  1368. VALUE preserve_proto_fieldnames = Qfalse;
  1369. VALUE emit_defaults = Qfalse;
  1370. stringsink sink;
  1371. if (argc < 1 || argc > 2) {
  1372. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  1373. }
  1374. msg_rb = argv[0];
  1375. if (argc == 2) {
  1376. VALUE hash_args = argv[1];
  1377. if (TYPE(hash_args) != T_HASH) {
  1378. rb_raise(rb_eArgError, "Expected hash arguments.");
  1379. }
  1380. preserve_proto_fieldnames = rb_hash_lookup2(
  1381. hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
  1382. emit_defaults = rb_hash_lookup2(
  1383. hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
  1384. }
  1385. stringsink_init(&sink);
  1386. {
  1387. const upb_handlers* serialize_handlers =
  1388. msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
  1389. upb_json_printer* printer;
  1390. stackenv se;
  1391. VALUE ret;
  1392. stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
  1393. printer = upb_json_printer_create(se.arena, serialize_handlers, sink.sink);
  1394. putmsg(msg_rb, desc, upb_json_printer_input(printer), 0,
  1395. RTEST(emit_defaults), true, true);
  1396. ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
  1397. stackenv_uninit(&se);
  1398. stringsink_uninit(&sink);
  1399. return ret;
  1400. }
  1401. }
  1402. static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
  1403. MessageHeader* msg;
  1404. upb_msg_field_iter it;
  1405. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1406. {
  1407. stringsink* unknown = msg->unknown_fields;
  1408. if (unknown != NULL) {
  1409. stringsink_uninit(unknown);
  1410. msg->unknown_fields = NULL;
  1411. }
  1412. }
  1413. for (upb_msg_field_begin(&it, desc->msgdef);
  1414. !upb_msg_field_done(&it);
  1415. upb_msg_field_next(&it)) {
  1416. upb_fielddef *f = upb_msg_iter_field(&it);
  1417. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  1418. uint32_t offset =
  1419. desc->layout->fields[upb_fielddef_index(f)].offset +
  1420. sizeof(MessageHeader);
  1421. if (oneof) {
  1422. uint32_t oneof_case =
  1423. slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
  1424. // For a oneof, check that this field is actually present -- skip all the
  1425. // below if not.
  1426. if (oneof_case != upb_fielddef_number(f)) {
  1427. continue;
  1428. }
  1429. // Otherwise, fall through to the appropriate singular-field handler
  1430. // below.
  1431. }
  1432. if (!upb_fielddef_issubmsg(f)) {
  1433. continue;
  1434. }
  1435. if (is_map_field(f)) {
  1436. VALUE map;
  1437. Map_iter map_it;
  1438. if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
  1439. map = DEREF(msg, offset, VALUE);
  1440. if (map == Qnil) continue;
  1441. for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
  1442. VALUE submsg = Map_iter_value(&map_it);
  1443. VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1444. const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  1445. discard_unknown(submsg, subdesc);
  1446. }
  1447. } else if (upb_fielddef_isseq(f)) {
  1448. VALUE ary = DEREF(msg, offset, VALUE);
  1449. int size;
  1450. int i;
  1451. if (ary == Qnil) continue;
  1452. size = NUM2INT(RepeatedField_length(ary));
  1453. for (i = 0; i < size; i++) {
  1454. void* memory = RepeatedField_index_native(ary, i);
  1455. VALUE submsg = *((VALUE *)memory);
  1456. VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1457. const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  1458. discard_unknown(submsg, subdesc);
  1459. }
  1460. } else {
  1461. VALUE submsg = DEREF(msg, offset, VALUE);
  1462. VALUE descriptor;
  1463. const Descriptor* subdesc;
  1464. if (submsg == Qnil) continue;
  1465. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1466. subdesc = ruby_to_Descriptor(descriptor);
  1467. discard_unknown(submsg, subdesc);
  1468. }
  1469. }
  1470. }
  1471. /*
  1472. * call-seq:
  1473. * Google::Protobuf.discard_unknown(msg)
  1474. *
  1475. * Discard unknown fields in the given message object and recursively discard
  1476. * unknown fields in submessages.
  1477. */
  1478. VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
  1479. VALUE klass = CLASS_OF(msg_rb);
  1480. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1481. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1482. if (klass == cRepeatedField || klass == cMap) {
  1483. rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
  1484. } else {
  1485. discard_unknown(msg_rb, desc);
  1486. }
  1487. return Qnil;
  1488. }