encode_decode.c 59 KB

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