encode_decode.c 40 KB

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