encode_decode.c 40 KB

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