encode_decode.c 41 KB

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