encode_decode.c 59 KB

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