encode_decode.c 43 KB

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