encode_decode.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2014 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #include "protobuf.h"
  31. // This function is equivalent to rb_str_cat(), but unlike the real
  32. // rb_str_cat(), it doesn't leak memory in some versions of Ruby.
  33. // For more information, see:
  34. // https://bugs.ruby-lang.org/issues/11328
  35. VALUE noleak_rb_str_cat(VALUE rb_str, const char *str, long len) {
  36. char *p;
  37. size_t oldlen = RSTRING_LEN(rb_str);
  38. rb_str_modify_expand(rb_str, len);
  39. p = RSTRING_PTR(rb_str);
  40. memcpy(p + oldlen, str, len);
  41. rb_str_set_len(rb_str, oldlen + len);
  42. return rb_str;
  43. }
  44. // -----------------------------------------------------------------------------
  45. // Parsing.
  46. // -----------------------------------------------------------------------------
  47. #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
  48. // Creates a handlerdata that simply contains the offset for this field.
  49. static const void* newhandlerdata(upb_handlers* h, uint32_t ofs) {
  50. size_t* hd_ofs = ALLOC(size_t);
  51. *hd_ofs = ofs;
  52. upb_handlers_addcleanup(h, hd_ofs, free);
  53. return hd_ofs;
  54. }
  55. typedef struct {
  56. size_t ofs;
  57. const upb_msgdef *md;
  58. } submsg_handlerdata_t;
  59. // Creates a handlerdata that contains offset and submessage type information.
  60. static const void *newsubmsghandlerdata(upb_handlers* h, uint32_t ofs,
  61. const upb_fielddef* f) {
  62. submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
  63. hd->ofs = ofs;
  64. hd->md = upb_fielddef_msgsubdef(f);
  65. upb_handlers_addcleanup(h, hd, free);
  66. return hd;
  67. }
  68. typedef struct {
  69. size_t ofs; // union data slot
  70. size_t case_ofs; // oneof_case field
  71. uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
  72. const upb_msgdef *md; // msgdef, for oneof submessage handler
  73. } oneof_handlerdata_t;
  74. static const void *newoneofhandlerdata(upb_handlers *h,
  75. uint32_t ofs,
  76. uint32_t case_ofs,
  77. const upb_fielddef *f) {
  78. oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
  79. hd->ofs = ofs;
  80. hd->case_ofs = case_ofs;
  81. // We reuse the field tag number as a oneof union discriminant tag. Note that
  82. // we don't expose these numbers to the user, so the only requirement is that
  83. // we have some unique ID for each union case/possibility. The field tag
  84. // numbers are already present and are easy to use so there's no reason to
  85. // create a separate ID space. In addition, using the field tag number here
  86. // lets us easily look up the field in the oneof accessor.
  87. hd->oneof_case_num = upb_fielddef_number(f);
  88. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
  89. hd->md = upb_fielddef_msgsubdef(f);
  90. } else {
  91. hd->md = NULL;
  92. }
  93. upb_handlers_addcleanup(h, hd, free);
  94. return hd;
  95. }
  96. // A handler that starts a repeated field. Gets the Repeated*Field instance for
  97. // this field (such an instance always exists even in an empty message).
  98. static void *startseq_handler(void* closure, const void* hd) {
  99. MessageHeader* msg = closure;
  100. const size_t *ofs = hd;
  101. return (void*)DEREF(msg, *ofs, VALUE);
  102. }
  103. // Handlers that append primitive values to a repeated field.
  104. #define DEFINE_APPEND_HANDLER(type, ctype) \
  105. static bool append##type##_handler(void *closure, const void *hd, \
  106. ctype val) { \
  107. VALUE ary = (VALUE)closure; \
  108. RepeatedField_push_native(ary, &val); \
  109. return true; \
  110. }
  111. DEFINE_APPEND_HANDLER(bool, bool)
  112. DEFINE_APPEND_HANDLER(int32, int32_t)
  113. DEFINE_APPEND_HANDLER(uint32, uint32_t)
  114. DEFINE_APPEND_HANDLER(float, float)
  115. DEFINE_APPEND_HANDLER(int64, int64_t)
  116. DEFINE_APPEND_HANDLER(uint64, uint64_t)
  117. DEFINE_APPEND_HANDLER(double, double)
  118. // Appends a string to a repeated field.
  119. static void* appendstr_handler(void *closure,
  120. const void *hd,
  121. size_t size_hint) {
  122. VALUE ary = (VALUE)closure;
  123. VALUE str = rb_str_new2("");
  124. rb_enc_associate(str, kRubyStringUtf8Encoding);
  125. RepeatedField_push(ary, str);
  126. return (void*)str;
  127. }
  128. // Appends a 'bytes' string to a repeated field.
  129. static void* appendbytes_handler(void *closure,
  130. const void *hd,
  131. size_t size_hint) {
  132. VALUE ary = (VALUE)closure;
  133. VALUE str = rb_str_new2("");
  134. rb_enc_associate(str, kRubyString8bitEncoding);
  135. RepeatedField_push(ary, str);
  136. return (void*)str;
  137. }
  138. // Sets a non-repeated string field in a message.
  139. static void* str_handler(void *closure,
  140. const void *hd,
  141. size_t size_hint) {
  142. MessageHeader* msg = closure;
  143. const size_t *ofs = hd;
  144. VALUE str = rb_str_new2("");
  145. rb_enc_associate(str, kRubyStringUtf8Encoding);
  146. DEREF(msg, *ofs, VALUE) = str;
  147. return (void*)str;
  148. }
  149. // Sets a non-repeated 'bytes' field in a message.
  150. static void* bytes_handler(void *closure,
  151. const void *hd,
  152. size_t size_hint) {
  153. MessageHeader* msg = closure;
  154. const size_t *ofs = hd;
  155. VALUE str = rb_str_new2("");
  156. rb_enc_associate(str, kRubyString8bitEncoding);
  157. DEREF(msg, *ofs, VALUE) = str;
  158. return (void*)str;
  159. }
  160. static size_t stringdata_handler(void* closure, const void* hd,
  161. const char* str, size_t len,
  162. const upb_bufhandle* handle) {
  163. VALUE rb_str = (VALUE)closure;
  164. noleak_rb_str_cat(rb_str, str, len);
  165. return len;
  166. }
  167. // Appends a submessage to a repeated field (a regular Ruby array for now).
  168. static void *appendsubmsg_handler(void *closure, const void *hd) {
  169. VALUE ary = (VALUE)closure;
  170. const submsg_handlerdata_t *submsgdata = hd;
  171. VALUE subdesc =
  172. get_def_obj((void*)submsgdata->md);
  173. VALUE subklass = Descriptor_msgclass(subdesc);
  174. MessageHeader* submsg;
  175. VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
  176. RepeatedField_push(ary, submsg_rb);
  177. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  178. return submsg;
  179. }
  180. // Sets a non-repeated submessage field in a message.
  181. static void *submsg_handler(void *closure, const void *hd) {
  182. MessageHeader* msg = closure;
  183. const submsg_handlerdata_t* submsgdata = hd;
  184. VALUE subdesc =
  185. get_def_obj((void*)submsgdata->md);
  186. VALUE subklass = Descriptor_msgclass(subdesc);
  187. VALUE submsg_rb;
  188. MessageHeader* submsg;
  189. if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
  190. DEREF(msg, submsgdata->ofs, VALUE) =
  191. rb_class_new_instance(0, NULL, subklass);
  192. }
  193. submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
  194. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  195. return submsg;
  196. }
  197. // Handler data for startmap/endmap handlers.
  198. typedef struct {
  199. size_t ofs;
  200. upb_fieldtype_t key_field_type;
  201. upb_fieldtype_t value_field_type;
  202. // We know that we can hold this reference because the handlerdata has the
  203. // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
  204. // a reference to the upb_msgdef, which in turn has references to its subdefs.
  205. const upb_def* value_field_subdef;
  206. } map_handlerdata_t;
  207. // Temporary frame for map parsing: at the beginning of a map entry message, a
  208. // submsg handler allocates a frame to hold (i) a reference to the Map object
  209. // into which this message will be inserted and (ii) storage slots to
  210. // temporarily hold the key and value for this map entry until the end of the
  211. // submessage. When the submessage ends, another handler is called to insert the
  212. // value into the map.
  213. typedef struct {
  214. VALUE map;
  215. char key_storage[NATIVE_SLOT_MAX_SIZE];
  216. char value_storage[NATIVE_SLOT_MAX_SIZE];
  217. } map_parse_frame_t;
  218. // Handler to begin a map entry: allocates a temporary frame. This is the
  219. // 'startsubmsg' handler on the msgdef that contains the map field.
  220. static void *startmapentry_handler(void *closure, const void *hd) {
  221. MessageHeader* msg = closure;
  222. const map_handlerdata_t* mapdata = hd;
  223. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  224. map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
  225. frame->map = map_rb;
  226. native_slot_init(mapdata->key_field_type, &frame->key_storage);
  227. native_slot_init(mapdata->value_field_type, &frame->value_storage);
  228. return frame;
  229. }
  230. // Handler to end a map entry: inserts the value defined during the message into
  231. // the map. This is the 'endmsg' handler on the map entry msgdef.
  232. static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
  233. map_parse_frame_t* frame = closure;
  234. const map_handlerdata_t* mapdata = hd;
  235. VALUE key = native_slot_get(
  236. mapdata->key_field_type, Qnil,
  237. &frame->key_storage);
  238. VALUE value_field_typeclass = Qnil;
  239. VALUE value;
  240. if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
  241. mapdata->value_field_type == UPB_TYPE_ENUM) {
  242. value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
  243. }
  244. value = native_slot_get(
  245. mapdata->value_field_type, value_field_typeclass,
  246. &frame->value_storage);
  247. Map_index_set(frame->map, key, value);
  248. free(frame);
  249. return true;
  250. }
  251. // Allocates a new map_handlerdata_t given the map entry message definition. If
  252. // the offset of the field within the parent message is also given, that is
  253. // added to the handler data as well. Note that this is called *twice* per map
  254. // field: once in the parent message handler setup when setting the startsubmsg
  255. // handler and once in the map entry message handler setup when setting the
  256. // key/value and endmsg handlers. The reason is that there is no easy way to
  257. // pass the handlerdata down to the sub-message handler setup.
  258. static map_handlerdata_t* new_map_handlerdata(
  259. size_t ofs,
  260. const upb_msgdef* mapentry_def,
  261. Descriptor* desc) {
  262. const upb_fielddef* key_field;
  263. const upb_fielddef* value_field;
  264. map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
  265. hd->ofs = ofs;
  266. key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
  267. assert(key_field != NULL);
  268. hd->key_field_type = upb_fielddef_type(key_field);
  269. value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
  270. assert(value_field != NULL);
  271. hd->value_field_type = upb_fielddef_type(value_field);
  272. hd->value_field_subdef = upb_fielddef_subdef(value_field);
  273. return hd;
  274. }
  275. // Handlers that set primitive values in oneofs.
  276. #define DEFINE_ONEOF_HANDLER(type, ctype) \
  277. static bool oneof##type##_handler(void *closure, const void *hd, \
  278. ctype val) { \
  279. const oneof_handlerdata_t *oneofdata = hd; \
  280. DEREF(closure, oneofdata->case_ofs, uint32_t) = \
  281. oneofdata->oneof_case_num; \
  282. DEREF(closure, oneofdata->ofs, ctype) = val; \
  283. return true; \
  284. }
  285. DEFINE_ONEOF_HANDLER(bool, bool)
  286. DEFINE_ONEOF_HANDLER(int32, int32_t)
  287. DEFINE_ONEOF_HANDLER(uint32, uint32_t)
  288. DEFINE_ONEOF_HANDLER(float, float)
  289. DEFINE_ONEOF_HANDLER(int64, int64_t)
  290. DEFINE_ONEOF_HANDLER(uint64, uint64_t)
  291. DEFINE_ONEOF_HANDLER(double, double)
  292. #undef DEFINE_ONEOF_HANDLER
  293. // Handlers for strings in a oneof.
  294. static void *oneofstr_handler(void *closure,
  295. const void *hd,
  296. size_t size_hint) {
  297. MessageHeader* msg = closure;
  298. const oneof_handlerdata_t *oneofdata = hd;
  299. VALUE str = rb_str_new2("");
  300. rb_enc_associate(str, kRubyStringUtf8Encoding);
  301. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  302. oneofdata->oneof_case_num;
  303. DEREF(msg, oneofdata->ofs, VALUE) = str;
  304. return (void*)str;
  305. }
  306. static void *oneofbytes_handler(void *closure,
  307. const void *hd,
  308. size_t size_hint) {
  309. MessageHeader* msg = closure;
  310. const oneof_handlerdata_t *oneofdata = hd;
  311. VALUE str = rb_str_new2("");
  312. rb_enc_associate(str, kRubyString8bitEncoding);
  313. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  314. oneofdata->oneof_case_num;
  315. DEREF(msg, oneofdata->ofs, VALUE) = str;
  316. return (void*)str;
  317. }
  318. // Handler for a submessage field in a oneof.
  319. static void *oneofsubmsg_handler(void *closure,
  320. const void *hd) {
  321. MessageHeader* msg = closure;
  322. const oneof_handlerdata_t *oneofdata = hd;
  323. uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
  324. VALUE subdesc =
  325. get_def_obj((void*)oneofdata->md);
  326. VALUE subklass = Descriptor_msgclass(subdesc);
  327. VALUE submsg_rb;
  328. MessageHeader* submsg;
  329. if (oldcase != oneofdata->oneof_case_num ||
  330. DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
  331. DEREF(msg, oneofdata->ofs, VALUE) =
  332. rb_class_new_instance(0, NULL, subklass);
  333. }
  334. // Set the oneof case *after* allocating the new class instance -- otherwise,
  335. // if the Ruby GC is invoked as part of a call into the VM, it might invoke
  336. // our mark routines, and our mark routines might see the case value
  337. // indicating a VALUE is present and expect a valid VALUE. See comment in
  338. // layout_set() for more detail: basically, the change to the value and the
  339. // case must be atomic w.r.t. the Ruby VM.
  340. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  341. oneofdata->oneof_case_num;
  342. submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
  343. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  344. return submsg;
  345. }
  346. // Set up handlers for a repeated field.
  347. static void add_handlers_for_repeated_field(upb_handlers *h,
  348. const upb_fielddef *f,
  349. size_t offset) {
  350. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  351. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  352. upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  353. upb_handlerattr_uninit(&attr);
  354. switch (upb_fielddef_type(f)) {
  355. #define SET_HANDLER(utype, ltype) \
  356. case utype: \
  357. upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
  358. break;
  359. SET_HANDLER(UPB_TYPE_BOOL, bool);
  360. SET_HANDLER(UPB_TYPE_INT32, int32);
  361. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  362. SET_HANDLER(UPB_TYPE_ENUM, int32);
  363. SET_HANDLER(UPB_TYPE_FLOAT, float);
  364. SET_HANDLER(UPB_TYPE_INT64, int64);
  365. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  366. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  367. #undef SET_HANDLER
  368. case UPB_TYPE_STRING:
  369. case UPB_TYPE_BYTES: {
  370. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  371. upb_handlers_setstartstr(h, f, is_bytes ?
  372. appendbytes_handler : appendstr_handler,
  373. NULL);
  374. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  375. break;
  376. }
  377. case UPB_TYPE_MESSAGE: {
  378. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  379. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
  380. upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
  381. upb_handlerattr_uninit(&attr);
  382. break;
  383. }
  384. }
  385. }
  386. // Set up handlers for a singular field.
  387. static void add_handlers_for_singular_field(upb_handlers *h,
  388. const upb_fielddef *f,
  389. size_t offset) {
  390. switch (upb_fielddef_type(f)) {
  391. case UPB_TYPE_BOOL:
  392. case UPB_TYPE_INT32:
  393. case UPB_TYPE_UINT32:
  394. case UPB_TYPE_ENUM:
  395. case UPB_TYPE_FLOAT:
  396. case UPB_TYPE_INT64:
  397. case UPB_TYPE_UINT64:
  398. case UPB_TYPE_DOUBLE:
  399. upb_shim_set(h, f, offset, -1);
  400. break;
  401. case UPB_TYPE_STRING:
  402. case UPB_TYPE_BYTES: {
  403. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  404. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  405. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  406. upb_handlers_setstartstr(h, f,
  407. is_bytes ? bytes_handler : str_handler,
  408. &attr);
  409. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  410. upb_handlerattr_uninit(&attr);
  411. break;
  412. }
  413. case UPB_TYPE_MESSAGE: {
  414. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  415. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
  416. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  417. upb_handlerattr_uninit(&attr);
  418. break;
  419. }
  420. }
  421. }
  422. // Adds handlers to a map field.
  423. static void add_handlers_for_mapfield(upb_handlers* h,
  424. const upb_fielddef* fielddef,
  425. size_t offset,
  426. Descriptor* desc) {
  427. const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
  428. map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
  429. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  430. upb_handlers_addcleanup(h, hd, free);
  431. upb_handlerattr_sethandlerdata(&attr, hd);
  432. upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
  433. upb_handlerattr_uninit(&attr);
  434. }
  435. // Adds handlers to a map-entry msgdef.
  436. static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
  437. upb_handlers* h,
  438. Descriptor* desc) {
  439. const upb_fielddef* key_field = map_entry_key(msgdef);
  440. const upb_fielddef* value_field = map_entry_value(msgdef);
  441. map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
  442. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  443. upb_handlers_addcleanup(h, hd, free);
  444. upb_handlerattr_sethandlerdata(&attr, hd);
  445. upb_handlers_setendmsg(h, endmap_handler, &attr);
  446. add_handlers_for_singular_field(
  447. h, key_field,
  448. offsetof(map_parse_frame_t, key_storage));
  449. add_handlers_for_singular_field(
  450. h, value_field,
  451. offsetof(map_parse_frame_t, value_storage));
  452. }
  453. // Set up handlers for a oneof field.
  454. static void add_handlers_for_oneof_field(upb_handlers *h,
  455. const upb_fielddef *f,
  456. size_t offset,
  457. size_t oneof_case_offset) {
  458. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  459. upb_handlerattr_sethandlerdata(
  460. &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
  461. switch (upb_fielddef_type(f)) {
  462. #define SET_HANDLER(utype, ltype) \
  463. case utype: \
  464. upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
  465. break;
  466. SET_HANDLER(UPB_TYPE_BOOL, bool);
  467. SET_HANDLER(UPB_TYPE_INT32, int32);
  468. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  469. SET_HANDLER(UPB_TYPE_ENUM, int32);
  470. SET_HANDLER(UPB_TYPE_FLOAT, float);
  471. SET_HANDLER(UPB_TYPE_INT64, int64);
  472. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  473. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  474. #undef SET_HANDLER
  475. case UPB_TYPE_STRING:
  476. case UPB_TYPE_BYTES: {
  477. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  478. upb_handlers_setstartstr(h, f, is_bytes ?
  479. oneofbytes_handler : oneofstr_handler,
  480. &attr);
  481. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  482. break;
  483. }
  484. case UPB_TYPE_MESSAGE: {
  485. upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
  486. break;
  487. }
  488. }
  489. upb_handlerattr_uninit(&attr);
  490. }
  491. static void add_handlers_for_message(const void *closure, upb_handlers *h) {
  492. const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  493. Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
  494. upb_msg_field_iter i;
  495. // If this is a mapentry message type, set up a special set of handlers and
  496. // bail out of the normal (user-defined) message type handling.
  497. if (upb_msgdef_mapentry(msgdef)) {
  498. add_handlers_for_mapentry(msgdef, h, desc);
  499. return;
  500. }
  501. // Ensure layout exists. We may be invoked to create handlers for a given
  502. // message if we are included as a submsg of another message type before our
  503. // class is actually built, so to work around this, we just create the layout
  504. // (and handlers, in the class-building function) on-demand.
  505. if (desc->layout == NULL) {
  506. desc->layout = create_layout(desc->msgdef);
  507. }
  508. for (upb_msg_field_begin(&i, desc->msgdef);
  509. !upb_msg_field_done(&i);
  510. upb_msg_field_next(&i)) {
  511. const upb_fielddef *f = upb_msg_iter_field(&i);
  512. size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
  513. sizeof(MessageHeader);
  514. if (upb_fielddef_containingoneof(f)) {
  515. size_t oneof_case_offset =
  516. desc->layout->fields[upb_fielddef_index(f)].case_offset +
  517. sizeof(MessageHeader);
  518. add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
  519. } else if (is_map_field(f)) {
  520. add_handlers_for_mapfield(h, f, offset, desc);
  521. } else if (upb_fielddef_isseq(f)) {
  522. add_handlers_for_repeated_field(h, f, offset);
  523. } else {
  524. add_handlers_for_singular_field(h, f, offset);
  525. }
  526. }
  527. }
  528. // Creates upb handlers for populating a message.
  529. static const upb_handlers *new_fill_handlers(Descriptor* desc,
  530. const void* owner) {
  531. // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
  532. // handlers, reuse subdef handlers so that e.g. if we already parse
  533. // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
  534. // parse A-with-field-of-type-B-with-field-of-type-C.
  535. return upb_handlers_newfrozen(desc->msgdef, owner,
  536. add_handlers_for_message, NULL);
  537. }
  538. // Constructs the handlers for filling a message's data into an in-memory
  539. // object.
  540. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  541. if (!desc->fill_handlers) {
  542. desc->fill_handlers =
  543. new_fill_handlers(desc, &desc->fill_handlers);
  544. }
  545. return desc->fill_handlers;
  546. }
  547. // Constructs the upb decoder method for parsing messages of this type.
  548. // This is called from the message class creation code.
  549. const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
  550. const void* owner) {
  551. const upb_handlers* handlers = get_fill_handlers(desc);
  552. upb_pbdecodermethodopts opts;
  553. upb_pbdecodermethodopts_init(&opts, handlers);
  554. return upb_pbdecodermethod_new(&opts, owner);
  555. }
  556. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  557. if (desc->fill_method == NULL) {
  558. desc->fill_method = new_fillmsg_decodermethod(
  559. desc, &desc->fill_method);
  560. }
  561. return desc->fill_method;
  562. }
  563. static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
  564. if (desc->json_fill_method == NULL) {
  565. desc->json_fill_method =
  566. upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
  567. }
  568. return desc->json_fill_method;
  569. }
  570. // Stack-allocated context during an encode/decode operation. Contains the upb
  571. // environment and its stack-based allocator, an initial buffer for allocations
  572. // to avoid malloc() when possible, and a template for Ruby exception messages
  573. // if any error occurs.
  574. #define STACK_ENV_STACKBYTES 4096
  575. typedef struct {
  576. upb_env env;
  577. const char* ruby_error_template;
  578. char allocbuf[STACK_ENV_STACKBYTES];
  579. } stackenv;
  580. static void stackenv_init(stackenv* se, const char* errmsg);
  581. static void stackenv_uninit(stackenv* se);
  582. // Callback invoked by upb if any error occurs during parsing or serialization.
  583. static bool env_error_func(void* ud, const upb_status* status) {
  584. stackenv* se = ud;
  585. // Free the env -- rb_raise will longjmp up the stack past the encode/decode
  586. // function so it would not otherwise have been freed.
  587. stackenv_uninit(se);
  588. // TODO(haberman): have a way to verify that this is actually a parse error,
  589. // instead of just throwing "parse error" unconditionally.
  590. rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
  591. // Never reached: rb_raise() always longjmp()s up the stack, past all of our
  592. // code, back to Ruby.
  593. return false;
  594. }
  595. static void stackenv_init(stackenv* se, const char* errmsg) {
  596. se->ruby_error_template = errmsg;
  597. upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
  598. upb_env_seterrorfunc(&se->env, env_error_func, se);
  599. }
  600. static void stackenv_uninit(stackenv* se) {
  601. upb_env_uninit(&se->env);
  602. }
  603. /*
  604. * call-seq:
  605. * MessageClass.decode(data) => message
  606. *
  607. * Decodes the given data (as a string containing bytes in protocol buffers wire
  608. * format) under the interpretration given by this message class's definition
  609. * and returns a message object with the corresponding field values.
  610. */
  611. VALUE Message_decode(VALUE klass, VALUE data) {
  612. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  613. Descriptor* desc = ruby_to_Descriptor(descriptor);
  614. VALUE msgklass = Descriptor_msgclass(descriptor);
  615. VALUE msg_rb;
  616. MessageHeader* msg;
  617. if (TYPE(data) != T_STRING) {
  618. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  619. }
  620. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  621. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  622. {
  623. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  624. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  625. stackenv se;
  626. upb_sink sink;
  627. upb_pbdecoder* decoder;
  628. stackenv_init(&se, "Error occurred during parsing: %s");
  629. upb_sink_reset(&sink, h, msg);
  630. decoder = upb_pbdecoder_create(&se.env, method, &sink);
  631. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  632. upb_pbdecoder_input(decoder));
  633. stackenv_uninit(&se);
  634. }
  635. return msg_rb;
  636. }
  637. /*
  638. * call-seq:
  639. * MessageClass.decode_json(data) => message
  640. *
  641. * Decodes the given data (as a string containing bytes in protocol buffers wire
  642. * format) under the interpretration given by this message class's definition
  643. * and returns a message object with the corresponding field values.
  644. */
  645. VALUE Message_decode_json(VALUE klass, VALUE data) {
  646. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  647. Descriptor* desc = ruby_to_Descriptor(descriptor);
  648. VALUE msgklass = Descriptor_msgclass(descriptor);
  649. VALUE msg_rb;
  650. MessageHeader* msg;
  651. if (TYPE(data) != T_STRING) {
  652. rb_raise(rb_eArgError, "Expected string for JSON data.");
  653. }
  654. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  655. // convert, because string handlers pass data directly to message string
  656. // fields.
  657. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  658. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  659. {
  660. const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
  661. stackenv se;
  662. upb_sink sink;
  663. upb_json_parser* parser;
  664. stackenv_init(&se, "Error occurred during parsing: %s");
  665. upb_sink_reset(&sink, get_fill_handlers(desc), msg);
  666. parser = upb_json_parser_create(&se.env, method, &sink);
  667. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  668. upb_json_parser_input(parser));
  669. stackenv_uninit(&se);
  670. }
  671. return msg_rb;
  672. }
  673. // -----------------------------------------------------------------------------
  674. // Serializing.
  675. // -----------------------------------------------------------------------------
  676. //
  677. // The code below also comes from upb's prototype Ruby binding, developed by
  678. // haberman@.
  679. /* stringsink *****************************************************************/
  680. // This should probably be factored into a common upb component.
  681. typedef struct {
  682. upb_byteshandler handler;
  683. upb_bytessink sink;
  684. char *ptr;
  685. size_t len, size;
  686. } stringsink;
  687. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  688. stringsink *sink = _sink;
  689. sink->len = 0;
  690. return sink;
  691. }
  692. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  693. size_t len, const upb_bufhandle *handle) {
  694. stringsink *sink = _sink;
  695. size_t new_size = sink->size;
  696. UPB_UNUSED(hd);
  697. UPB_UNUSED(handle);
  698. while (sink->len + len > new_size) {
  699. new_size *= 2;
  700. }
  701. if (new_size != sink->size) {
  702. sink->ptr = realloc(sink->ptr, new_size);
  703. sink->size = new_size;
  704. }
  705. memcpy(sink->ptr + sink->len, ptr, len);
  706. sink->len += len;
  707. return len;
  708. }
  709. void stringsink_init(stringsink *sink) {
  710. upb_byteshandler_init(&sink->handler);
  711. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  712. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  713. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  714. sink->size = 32;
  715. sink->ptr = malloc(sink->size);
  716. sink->len = 0;
  717. }
  718. void stringsink_uninit(stringsink *sink) {
  719. free(sink->ptr);
  720. }
  721. /* msgvisitor *****************************************************************/
  722. // TODO: If/when we support proto2 semantics in addition to the current proto3
  723. // semantics, which means that we have true field presence, we will want to
  724. // modify msgvisitor so that it emits all present fields rather than all
  725. // non-default-value fields.
  726. //
  727. // Likewise, when implementing JSON serialization, we may need to have a
  728. // 'verbose' mode that outputs all fields and a 'concise' mode that outputs only
  729. // those with non-default values.
  730. static void putmsg(VALUE msg, const Descriptor* desc,
  731. upb_sink *sink, int depth);
  732. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  733. upb_selector_t ret;
  734. bool ok = upb_handlers_getselector(f, type, &ret);
  735. UPB_ASSERT_VAR(ok, ok);
  736. return ret;
  737. }
  738. static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
  739. upb_sink subsink;
  740. if (str == Qnil) return;
  741. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  742. // Ensure that the string has the correct encoding. We also check at field-set
  743. // time, but the user may have mutated the string object since then.
  744. native_slot_validate_string_encoding(upb_fielddef_type(f), str);
  745. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  746. &subsink);
  747. upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  748. RSTRING_LEN(str), NULL);
  749. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  750. }
  751. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
  752. int depth) {
  753. upb_sink subsink;
  754. VALUE descriptor;
  755. Descriptor* subdesc;
  756. if (submsg == Qnil) return;
  757. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  758. subdesc = ruby_to_Descriptor(descriptor);
  759. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  760. putmsg(submsg, subdesc, &subsink, depth + 1);
  761. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  762. }
  763. static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
  764. int depth) {
  765. upb_sink subsink;
  766. upb_fieldtype_t type = upb_fielddef_type(f);
  767. upb_selector_t sel = 0;
  768. int size;
  769. if (ary == Qnil) return;
  770. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  771. if (upb_fielddef_isprimitive(f)) {
  772. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  773. }
  774. size = NUM2INT(RepeatedField_length(ary));
  775. for (int i = 0; i < size; i++) {
  776. void* memory = RepeatedField_index_native(ary, i);
  777. switch (type) {
  778. #define T(upbtypeconst, upbtype, ctype) \
  779. case upbtypeconst: \
  780. upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
  781. break;
  782. T(UPB_TYPE_FLOAT, float, float)
  783. T(UPB_TYPE_DOUBLE, double, double)
  784. T(UPB_TYPE_BOOL, bool, int8_t)
  785. case UPB_TYPE_ENUM:
  786. T(UPB_TYPE_INT32, int32, int32_t)
  787. T(UPB_TYPE_UINT32, uint32, uint32_t)
  788. T(UPB_TYPE_INT64, int64, int64_t)
  789. T(UPB_TYPE_UINT64, uint64, uint64_t)
  790. case UPB_TYPE_STRING:
  791. case UPB_TYPE_BYTES:
  792. putstr(*((VALUE *)memory), f, &subsink);
  793. break;
  794. case UPB_TYPE_MESSAGE:
  795. putsubmsg(*((VALUE *)memory), f, &subsink, depth);
  796. break;
  797. #undef T
  798. }
  799. }
  800. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  801. }
  802. static void put_ruby_value(VALUE value,
  803. const upb_fielddef *f,
  804. VALUE type_class,
  805. int depth,
  806. upb_sink *sink) {
  807. upb_selector_t sel = 0;
  808. if (upb_fielddef_isprimitive(f)) {
  809. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  810. }
  811. switch (upb_fielddef_type(f)) {
  812. case UPB_TYPE_INT32:
  813. upb_sink_putint32(sink, sel, NUM2INT(value));
  814. break;
  815. case UPB_TYPE_INT64:
  816. upb_sink_putint64(sink, sel, NUM2LL(value));
  817. break;
  818. case UPB_TYPE_UINT32:
  819. upb_sink_putuint32(sink, sel, NUM2UINT(value));
  820. break;
  821. case UPB_TYPE_UINT64:
  822. upb_sink_putuint64(sink, sel, NUM2ULL(value));
  823. break;
  824. case UPB_TYPE_FLOAT:
  825. upb_sink_putfloat(sink, sel, NUM2DBL(value));
  826. break;
  827. case UPB_TYPE_DOUBLE:
  828. upb_sink_putdouble(sink, sel, NUM2DBL(value));
  829. break;
  830. case UPB_TYPE_ENUM: {
  831. if (TYPE(value) == T_SYMBOL) {
  832. value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  833. }
  834. upb_sink_putint32(sink, sel, NUM2INT(value));
  835. break;
  836. }
  837. case UPB_TYPE_BOOL:
  838. upb_sink_putbool(sink, sel, value == Qtrue);
  839. break;
  840. case UPB_TYPE_STRING:
  841. case UPB_TYPE_BYTES:
  842. putstr(value, f, sink);
  843. break;
  844. case UPB_TYPE_MESSAGE:
  845. putsubmsg(value, f, sink, depth);
  846. }
  847. }
  848. static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
  849. int depth) {
  850. Map* self;
  851. upb_sink subsink;
  852. const upb_fielddef* key_field;
  853. const upb_fielddef* value_field;
  854. Map_iter it;
  855. if (map == Qnil) return;
  856. self = ruby_to_Map(map);
  857. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  858. assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  859. key_field = map_field_key(f);
  860. value_field = map_field_value(f);
  861. for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
  862. VALUE key = Map_iter_key(&it);
  863. VALUE value = Map_iter_value(&it);
  864. upb_status status;
  865. upb_sink entry_sink;
  866. upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
  867. &entry_sink);
  868. upb_sink_startmsg(&entry_sink);
  869. put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink);
  870. put_ruby_value(value, value_field, self->value_type_class, depth + 1,
  871. &entry_sink);
  872. upb_sink_endmsg(&entry_sink, &status);
  873. upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  874. }
  875. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  876. }
  877. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  878. upb_sink *sink, int depth) {
  879. MessageHeader* msg;
  880. upb_msg_field_iter i;
  881. upb_status status;
  882. upb_sink_startmsg(sink);
  883. // Protect against cycles (possible because users may freely reassign message
  884. // and repeated fields) by imposing a maximum recursion depth.
  885. if (depth > ENCODE_MAX_NESTING) {
  886. rb_raise(rb_eRuntimeError,
  887. "Maximum recursion depth exceeded during encoding.");
  888. }
  889. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  890. for (upb_msg_field_begin(&i, desc->msgdef);
  891. !upb_msg_field_done(&i);
  892. upb_msg_field_next(&i)) {
  893. upb_fielddef *f = upb_msg_iter_field(&i);
  894. bool is_matching_oneof = false;
  895. uint32_t offset =
  896. desc->layout->fields[upb_fielddef_index(f)].offset +
  897. sizeof(MessageHeader);
  898. if (upb_fielddef_containingoneof(f)) {
  899. uint32_t oneof_case_offset =
  900. desc->layout->fields[upb_fielddef_index(f)].case_offset +
  901. sizeof(MessageHeader);
  902. // For a oneof, check that this field is actually present -- skip all the
  903. // below if not.
  904. if (DEREF(msg, oneof_case_offset, uint32_t) !=
  905. upb_fielddef_number(f)) {
  906. continue;
  907. }
  908. // Otherwise, fall through to the appropriate singular-field handler
  909. // below.
  910. is_matching_oneof = true;
  911. }
  912. if (is_map_field(f)) {
  913. VALUE map = DEREF(msg, offset, VALUE);
  914. if (map != Qnil) {
  915. putmap(map, f, sink, depth);
  916. }
  917. } else if (upb_fielddef_isseq(f)) {
  918. VALUE ary = DEREF(msg, offset, VALUE);
  919. if (ary != Qnil) {
  920. putary(ary, f, sink, depth);
  921. }
  922. } else if (upb_fielddef_isstring(f)) {
  923. VALUE str = DEREF(msg, offset, VALUE);
  924. if (is_matching_oneof || RSTRING_LEN(str) > 0) {
  925. putstr(str, f, sink);
  926. }
  927. } else if (upb_fielddef_issubmsg(f)) {
  928. putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth);
  929. } else {
  930. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  931. #define T(upbtypeconst, upbtype, ctype, default_value) \
  932. case upbtypeconst: { \
  933. ctype value = DEREF(msg, offset, ctype); \
  934. if (is_matching_oneof || value != default_value) { \
  935. upb_sink_put##upbtype(sink, sel, value); \
  936. } \
  937. } \
  938. break;
  939. switch (upb_fielddef_type(f)) {
  940. T(UPB_TYPE_FLOAT, float, float, 0.0)
  941. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  942. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  943. case UPB_TYPE_ENUM:
  944. T(UPB_TYPE_INT32, int32, int32_t, 0)
  945. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  946. T(UPB_TYPE_INT64, int64, int64_t, 0)
  947. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  948. case UPB_TYPE_STRING:
  949. case UPB_TYPE_BYTES:
  950. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  951. }
  952. #undef T
  953. }
  954. }
  955. upb_sink_endmsg(sink, &status);
  956. }
  957. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  958. if (desc->pb_serialize_handlers == NULL) {
  959. desc->pb_serialize_handlers =
  960. upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
  961. }
  962. return desc->pb_serialize_handlers;
  963. }
  964. static const upb_handlers* msgdef_json_serialize_handlers(
  965. Descriptor* desc, bool preserve_proto_fieldnames) {
  966. if (preserve_proto_fieldnames) {
  967. if (desc->json_serialize_handlers == NULL) {
  968. desc->json_serialize_handlers =
  969. upb_json_printer_newhandlers(
  970. desc->msgdef, true, &desc->json_serialize_handlers);
  971. }
  972. return desc->json_serialize_handlers;
  973. } else {
  974. if (desc->json_serialize_handlers_preserve == NULL) {
  975. desc->json_serialize_handlers_preserve =
  976. upb_json_printer_newhandlers(
  977. desc->msgdef, false, &desc->json_serialize_handlers_preserve);
  978. }
  979. return desc->json_serialize_handlers_preserve;
  980. }
  981. }
  982. /*
  983. * call-seq:
  984. * MessageClass.encode(msg) => bytes
  985. *
  986. * Encodes the given message object to its serialized form in protocol buffers
  987. * wire format.
  988. */
  989. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  990. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  991. Descriptor* desc = ruby_to_Descriptor(descriptor);
  992. stringsink sink;
  993. stringsink_init(&sink);
  994. {
  995. const upb_handlers* serialize_handlers =
  996. msgdef_pb_serialize_handlers(desc);
  997. stackenv se;
  998. upb_pb_encoder* encoder;
  999. VALUE ret;
  1000. stackenv_init(&se, "Error occurred during encoding: %s");
  1001. encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
  1002. putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0);
  1003. ret = rb_str_new(sink.ptr, sink.len);
  1004. stackenv_uninit(&se);
  1005. stringsink_uninit(&sink);
  1006. return ret;
  1007. }
  1008. }
  1009. /*
  1010. * call-seq:
  1011. * MessageClass.encode_json(msg) => json_string
  1012. *
  1013. * Encodes the given message object into its serialized JSON representation.
  1014. */
  1015. VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
  1016. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1017. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1018. VALUE msg_rb;
  1019. VALUE preserve_proto_fieldnames = Qfalse;
  1020. stringsink sink;
  1021. if (argc < 1 || argc > 2) {
  1022. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  1023. }
  1024. msg_rb = argv[0];
  1025. if (argc == 2) {
  1026. VALUE hash_args = argv[1];
  1027. if (TYPE(hash_args) != T_HASH) {
  1028. rb_raise(rb_eArgError, "Expected hash arguments.");
  1029. }
  1030. preserve_proto_fieldnames = rb_hash_lookup2(
  1031. hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
  1032. }
  1033. stringsink_init(&sink);
  1034. {
  1035. const upb_handlers* serialize_handlers =
  1036. msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
  1037. upb_json_printer* printer;
  1038. stackenv se;
  1039. VALUE ret;
  1040. stackenv_init(&se, "Error occurred during encoding: %s");
  1041. printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
  1042. putmsg(msg_rb, desc, upb_json_printer_input(printer), 0);
  1043. ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
  1044. stackenv_uninit(&se);
  1045. stringsink_uninit(&sink);
  1046. return ret;
  1047. }
  1048. }