encode_decode.c 59 KB

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