encode_decode.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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. // A handler that starts a repeated field. Gets the Repeated*Field instance for
  56. // this field (such an instance always exists even in an empty message).
  57. static void *startseq_handler(void* closure, const void* hd) {
  58. MessageHeader* msg = closure;
  59. const size_t *ofs = hd;
  60. return (void*)DEREF(Message_data(msg), *ofs, VALUE);
  61. }
  62. // Handlers that append primitive values to a repeated field (a regular Ruby
  63. // array for now).
  64. #define DEFINE_APPEND_HANDLER(type, ctype) \
  65. static bool append##type##_handler(void *closure, const void *hd, \
  66. ctype val) { \
  67. VALUE ary = (VALUE)closure; \
  68. RepeatedField_push_native(ary, &val); \
  69. return true; \
  70. }
  71. DEFINE_APPEND_HANDLER(bool, bool)
  72. DEFINE_APPEND_HANDLER(int32, int32_t)
  73. DEFINE_APPEND_HANDLER(uint32, uint32_t)
  74. DEFINE_APPEND_HANDLER(float, float)
  75. DEFINE_APPEND_HANDLER(int64, int64_t)
  76. DEFINE_APPEND_HANDLER(uint64, uint64_t)
  77. DEFINE_APPEND_HANDLER(double, double)
  78. // Appends a string to a repeated field (a regular Ruby array for now).
  79. static void* appendstr_handler(void *closure,
  80. const void *hd,
  81. size_t size_hint) {
  82. VALUE ary = (VALUE)closure;
  83. VALUE str = rb_str_new2("");
  84. rb_enc_associate(str, kRubyStringUtf8Encoding);
  85. RepeatedField_push(ary, str);
  86. return (void*)str;
  87. }
  88. // Appends a 'bytes' string to a repeated field (a regular Ruby array for now).
  89. static void* appendbytes_handler(void *closure,
  90. const void *hd,
  91. size_t size_hint) {
  92. VALUE ary = (VALUE)closure;
  93. VALUE str = rb_str_new2("");
  94. rb_enc_associate(str, kRubyString8bitEncoding);
  95. RepeatedField_push(ary, str);
  96. return (void*)str;
  97. }
  98. // Sets a non-repeated string field in a message.
  99. static void* str_handler(void *closure,
  100. const void *hd,
  101. size_t size_hint) {
  102. MessageHeader* msg = closure;
  103. const size_t *ofs = hd;
  104. VALUE str = rb_str_new2("");
  105. rb_enc_associate(str, kRubyStringUtf8Encoding);
  106. DEREF(Message_data(msg), *ofs, VALUE) = str;
  107. return (void*)str;
  108. }
  109. // Sets a non-repeated 'bytes' field in a message.
  110. static void* bytes_handler(void *closure,
  111. const void *hd,
  112. size_t size_hint) {
  113. MessageHeader* msg = closure;
  114. const size_t *ofs = hd;
  115. VALUE str = rb_str_new2("");
  116. rb_enc_associate(str, kRubyString8bitEncoding);
  117. DEREF(Message_data(msg), *ofs, VALUE) = str;
  118. return (void*)str;
  119. }
  120. static size_t stringdata_handler(void* closure, const void* hd,
  121. const char* str, size_t len,
  122. const upb_bufhandle* handle) {
  123. VALUE rb_str = (VALUE)closure;
  124. rb_str_cat(rb_str, str, len);
  125. return len;
  126. }
  127. // Appends a submessage to a repeated field (a regular Ruby array for now).
  128. static void *appendsubmsg_handler(void *closure, const void *hd) {
  129. VALUE ary = (VALUE)closure;
  130. const submsg_handlerdata_t *submsgdata = hd;
  131. VALUE subdesc =
  132. get_def_obj((void*)submsgdata->md);
  133. VALUE subklass = Descriptor_msgclass(subdesc);
  134. VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
  135. RepeatedField_push(ary, submsg_rb);
  136. MessageHeader* submsg;
  137. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  138. return submsg;
  139. }
  140. // Sets a non-repeated submessage field in a message.
  141. static void *submsg_handler(void *closure, const void *hd) {
  142. MessageHeader* msg = closure;
  143. const submsg_handlerdata_t* submsgdata = hd;
  144. VALUE subdesc =
  145. get_def_obj((void*)submsgdata->md);
  146. VALUE subklass = Descriptor_msgclass(subdesc);
  147. if (DEREF(Message_data(msg), submsgdata->ofs, VALUE) == Qnil) {
  148. DEREF(Message_data(msg), submsgdata->ofs, VALUE) =
  149. rb_class_new_instance(0, NULL, subklass);
  150. }
  151. VALUE submsg_rb = DEREF(Message_data(msg), submsgdata->ofs, VALUE);
  152. MessageHeader* submsg;
  153. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  154. return submsg;
  155. }
  156. static void add_handlers_for_message(const void *closure, upb_handlers *h) {
  157. Descriptor* desc = ruby_to_Descriptor(
  158. get_def_obj((void*)upb_handlers_msgdef(h)));
  159. // Ensure layout exists. We may be invoked to create handlers for a given
  160. // message if we are included as a submsg of another message type before our
  161. // class is actually built, so to work around this, we just create the layout
  162. // (and handlers, in the class-building function) on-demand.
  163. if (desc->layout == NULL) {
  164. desc->layout = create_layout(desc->msgdef);
  165. }
  166. upb_msg_iter i;
  167. for (upb_msg_begin(&i, desc->msgdef);
  168. !upb_msg_done(&i);
  169. upb_msg_next(&i)) {
  170. const upb_fielddef *f = upb_msg_iter_field(&i);
  171. size_t offset = desc->layout->offsets[upb_fielddef_index(f)];
  172. if (upb_fielddef_isseq(f)) {
  173. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  174. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  175. upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  176. upb_handlerattr_uninit(&attr);
  177. switch (upb_fielddef_type(f)) {
  178. #define SET_HANDLER(utype, ltype) \
  179. case utype: \
  180. upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
  181. break;
  182. SET_HANDLER(UPB_TYPE_BOOL, bool);
  183. SET_HANDLER(UPB_TYPE_INT32, int32);
  184. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  185. SET_HANDLER(UPB_TYPE_ENUM, int32);
  186. SET_HANDLER(UPB_TYPE_FLOAT, float);
  187. SET_HANDLER(UPB_TYPE_INT64, int64);
  188. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  189. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  190. #undef SET_HANDLER
  191. case UPB_TYPE_STRING:
  192. case UPB_TYPE_BYTES: {
  193. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  194. upb_handlers_setstartstr(h, f, is_bytes ?
  195. appendbytes_handler : appendstr_handler,
  196. NULL);
  197. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  198. }
  199. case UPB_TYPE_MESSAGE: {
  200. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  201. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
  202. upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
  203. upb_handlerattr_uninit(&attr);
  204. break;
  205. }
  206. }
  207. }
  208. switch (upb_fielddef_type(f)) {
  209. case UPB_TYPE_BOOL:
  210. case UPB_TYPE_INT32:
  211. case UPB_TYPE_UINT32:
  212. case UPB_TYPE_ENUM:
  213. case UPB_TYPE_FLOAT:
  214. case UPB_TYPE_INT64:
  215. case UPB_TYPE_UINT64:
  216. case UPB_TYPE_DOUBLE:
  217. // The shim writes directly at the given offset (instead of using
  218. // DEREF()) so we need to add the msg overhead.
  219. upb_shim_set(h, f, offset + sizeof(MessageHeader), -1);
  220. break;
  221. case UPB_TYPE_STRING:
  222. case UPB_TYPE_BYTES: {
  223. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  224. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  225. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  226. upb_handlers_setstartstr(h, f,
  227. is_bytes ? bytes_handler : str_handler,
  228. &attr);
  229. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  230. upb_handlerattr_uninit(&attr);
  231. break;
  232. }
  233. case UPB_TYPE_MESSAGE: {
  234. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  235. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
  236. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  237. upb_handlerattr_uninit(&attr);
  238. break;
  239. }
  240. }
  241. }
  242. }
  243. // Creates upb handlers for populating a message.
  244. static const upb_handlers *new_fill_handlers(Descriptor* desc,
  245. const void* owner) {
  246. // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
  247. // handlers, reuse subdef handlers so that e.g. if we already parse
  248. // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
  249. // parse A-with-field-of-type-B-with-field-of-type-C.
  250. return upb_handlers_newfrozen(desc->msgdef, owner,
  251. add_handlers_for_message, NULL);
  252. }
  253. // Constructs the handlers for filling a message's data into an in-memory
  254. // object.
  255. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  256. if (!desc->fill_handlers) {
  257. desc->fill_handlers =
  258. new_fill_handlers(desc, &desc->fill_handlers);
  259. }
  260. return desc->fill_handlers;
  261. }
  262. // Constructs the upb decoder method for parsing messages of this type.
  263. // This is called from the message class creation code.
  264. const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
  265. const void* owner) {
  266. const upb_handlers* handlers = get_fill_handlers(desc);
  267. upb_pbdecodermethodopts opts;
  268. upb_pbdecodermethodopts_init(&opts, handlers);
  269. const upb_pbdecodermethod *ret = upb_pbdecodermethod_new(&opts, owner);
  270. return ret;
  271. }
  272. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  273. if (desc->fill_method == NULL) {
  274. desc->fill_method = new_fillmsg_decodermethod(
  275. desc, &desc->fill_method);
  276. }
  277. return desc->fill_method;
  278. }
  279. /*
  280. * call-seq:
  281. * MessageClass.decode(data) => message
  282. *
  283. * Decodes the given data (as a string containing bytes in protocol buffers wire
  284. * format) under the interpretration given by this message class's definition
  285. * and returns a message object with the corresponding field values.
  286. */
  287. VALUE Message_decode(VALUE klass, VALUE data) {
  288. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  289. Descriptor* desc = ruby_to_Descriptor(descriptor);
  290. VALUE msgklass = Descriptor_msgclass(descriptor);
  291. if (TYPE(data) != T_STRING) {
  292. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  293. }
  294. VALUE msg_rb = rb_class_new_instance(0, NULL, msgklass);
  295. MessageHeader* msg;
  296. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  297. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  298. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  299. upb_pbdecoder decoder;
  300. upb_sink sink;
  301. upb_status status = UPB_STATUS_INIT;
  302. upb_pbdecoder_init(&decoder, method, &status);
  303. upb_sink_reset(&sink, h, msg);
  304. upb_pbdecoder_resetoutput(&decoder, &sink);
  305. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  306. upb_pbdecoder_input(&decoder));
  307. upb_pbdecoder_uninit(&decoder);
  308. if (!upb_ok(&status)) {
  309. rb_raise(rb_eRuntimeError, "Error occurred during parsing: %s.",
  310. upb_status_errmsg(&status));
  311. }
  312. return msg_rb;
  313. }
  314. /*
  315. * call-seq:
  316. * MessageClass.decode_json(data) => message
  317. *
  318. * Decodes the given data (as a string containing bytes in protocol buffers wire
  319. * format) under the interpretration given by this message class's definition
  320. * and returns a message object with the corresponding field values.
  321. */
  322. VALUE Message_decode_json(VALUE klass, VALUE data) {
  323. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  324. Descriptor* desc = ruby_to_Descriptor(descriptor);
  325. VALUE msgklass = Descriptor_msgclass(descriptor);
  326. if (TYPE(data) != T_STRING) {
  327. rb_raise(rb_eArgError, "Expected string for JSON data.");
  328. }
  329. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  330. // convert, because string handlers pass data directly to message string
  331. // fields.
  332. VALUE msg_rb = rb_class_new_instance(0, NULL, msgklass);
  333. MessageHeader* msg;
  334. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  335. upb_status status = UPB_STATUS_INIT;
  336. upb_json_parser parser;
  337. upb_json_parser_init(&parser, &status);
  338. upb_sink sink;
  339. upb_sink_reset(&sink, get_fill_handlers(desc), msg);
  340. upb_json_parser_resetoutput(&parser, &sink);
  341. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  342. upb_json_parser_input(&parser));
  343. upb_json_parser_uninit(&parser);
  344. if (!upb_ok(&status)) {
  345. rb_raise(rb_eRuntimeError, "Error occurred during parsing: %s.",
  346. upb_status_errmsg(&status));
  347. }
  348. return msg_rb;
  349. }
  350. // -----------------------------------------------------------------------------
  351. // Serializing.
  352. // -----------------------------------------------------------------------------
  353. //
  354. // The code below also comes from upb's prototype Ruby binding, developed by
  355. // haberman@.
  356. /* stringsink *****************************************************************/
  357. // This should probably be factored into a common upb component.
  358. typedef struct {
  359. upb_byteshandler handler;
  360. upb_bytessink sink;
  361. char *ptr;
  362. size_t len, size;
  363. } stringsink;
  364. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  365. stringsink *sink = _sink;
  366. sink->len = 0;
  367. return sink;
  368. }
  369. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  370. size_t len, const upb_bufhandle *handle) {
  371. UPB_UNUSED(hd);
  372. UPB_UNUSED(handle);
  373. stringsink *sink = _sink;
  374. size_t new_size = sink->size;
  375. while (sink->len + len > new_size) {
  376. new_size *= 2;
  377. }
  378. if (new_size != sink->size) {
  379. sink->ptr = realloc(sink->ptr, new_size);
  380. sink->size = new_size;
  381. }
  382. memcpy(sink->ptr + sink->len, ptr, len);
  383. sink->len += len;
  384. return len;
  385. }
  386. void stringsink_init(stringsink *sink) {
  387. upb_byteshandler_init(&sink->handler);
  388. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  389. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  390. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  391. sink->size = 32;
  392. sink->ptr = malloc(sink->size);
  393. sink->len = 0;
  394. }
  395. void stringsink_uninit(stringsink *sink) {
  396. free(sink->ptr);
  397. }
  398. /* msgvisitor *****************************************************************/
  399. // TODO: If/when we support proto2 semantics in addition to the current proto3
  400. // semantics, which means that we have true field presence, we will want to
  401. // modify msgvisitor so that it emits all present fields rather than all
  402. // non-default-value fields.
  403. //
  404. // Likewise, when implementing JSON serialization, we may need to have a
  405. // 'verbose' mode that outputs all fields and a 'concise' mode that outputs only
  406. // those with non-default values.
  407. static void putmsg(VALUE msg, const Descriptor* desc,
  408. upb_sink *sink, int depth);
  409. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  410. upb_selector_t ret;
  411. bool ok = upb_handlers_getselector(f, type, &ret);
  412. UPB_ASSERT_VAR(ok, ok);
  413. return ret;
  414. }
  415. static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
  416. if (str == Qnil) return;
  417. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  418. upb_sink subsink;
  419. // Ensure that the string has the correct encoding. We also check at field-set
  420. // time, but the user may have mutated the string object since then.
  421. native_slot_validate_string_encoding(upb_fielddef_type(f), str);
  422. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  423. &subsink);
  424. upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  425. RSTRING_LEN(str), NULL);
  426. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  427. }
  428. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
  429. int depth) {
  430. if (submsg == Qnil) return;
  431. upb_sink subsink;
  432. VALUE descriptor = rb_iv_get(submsg, kDescriptorInstanceVar);
  433. Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  434. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  435. putmsg(submsg, subdesc, &subsink, depth + 1);
  436. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  437. }
  438. static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
  439. int depth) {
  440. if (ary == Qnil) return;
  441. upb_sink subsink;
  442. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  443. upb_fieldtype_t type = upb_fielddef_type(f);
  444. upb_selector_t sel = 0;
  445. if (upb_fielddef_isprimitive(f)) {
  446. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  447. }
  448. int size = NUM2INT(RepeatedField_length(ary));
  449. for (int i = 0; i < size; i++) {
  450. void* memory = RepeatedField_index_native(ary, i);
  451. switch (type) {
  452. #define T(upbtypeconst, upbtype, ctype) \
  453. case upbtypeconst: \
  454. upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
  455. break;
  456. T(UPB_TYPE_FLOAT, float, float)
  457. T(UPB_TYPE_DOUBLE, double, double)
  458. T(UPB_TYPE_BOOL, bool, int8_t)
  459. case UPB_TYPE_ENUM:
  460. T(UPB_TYPE_INT32, int32, int32_t)
  461. T(UPB_TYPE_UINT32, uint32, uint32_t)
  462. T(UPB_TYPE_INT64, int64, int64_t)
  463. T(UPB_TYPE_UINT64, uint64, uint64_t)
  464. case UPB_TYPE_STRING:
  465. case UPB_TYPE_BYTES:
  466. putstr(*((VALUE *)memory), f, &subsink);
  467. break;
  468. case UPB_TYPE_MESSAGE:
  469. putsubmsg(*((VALUE *)memory), f, &subsink, depth);
  470. break;
  471. #undef T
  472. }
  473. }
  474. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  475. }
  476. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  477. upb_sink *sink, int depth) {
  478. upb_sink_startmsg(sink);
  479. // Protect against cycles (possible because users may freely reassign message
  480. // and repeated fields) by imposing a maximum recursion depth.
  481. if (depth > UPB_SINK_MAX_NESTING) {
  482. rb_raise(rb_eRuntimeError,
  483. "Maximum recursion depth exceeded during encoding.");
  484. }
  485. MessageHeader* msg;
  486. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  487. void* msg_data = Message_data(msg);
  488. upb_msg_iter i;
  489. for (upb_msg_begin(&i, desc->msgdef);
  490. !upb_msg_done(&i);
  491. upb_msg_next(&i)) {
  492. upb_fielddef *f = upb_msg_iter_field(&i);
  493. uint32_t offset = desc->layout->offsets[upb_fielddef_index(f)];
  494. if (upb_fielddef_isseq(f)) {
  495. VALUE ary = DEREF(msg_data, offset, VALUE);
  496. if (ary != Qnil) {
  497. putary(ary, f, sink, depth);
  498. }
  499. } else if (upb_fielddef_isstring(f)) {
  500. VALUE str = DEREF(msg_data, offset, VALUE);
  501. if (RSTRING_LEN(str) > 0) {
  502. putstr(str, f, sink);
  503. }
  504. } else if (upb_fielddef_issubmsg(f)) {
  505. putsubmsg(DEREF(msg_data, offset, VALUE), f, sink, depth);
  506. } else {
  507. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  508. #define T(upbtypeconst, upbtype, ctype, default_value) \
  509. case upbtypeconst: { \
  510. ctype value = DEREF(msg_data, offset, ctype); \
  511. if (value != default_value) { \
  512. upb_sink_put##upbtype(sink, sel, value); \
  513. } \
  514. } \
  515. break;
  516. switch (upb_fielddef_type(f)) {
  517. T(UPB_TYPE_FLOAT, float, float, 0.0)
  518. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  519. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  520. case UPB_TYPE_ENUM:
  521. T(UPB_TYPE_INT32, int32, int32_t, 0)
  522. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  523. T(UPB_TYPE_INT64, int64, int64_t, 0)
  524. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  525. case UPB_TYPE_STRING:
  526. case UPB_TYPE_BYTES:
  527. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  528. }
  529. #undef T
  530. }
  531. }
  532. upb_status status;
  533. upb_sink_endmsg(sink, &status);
  534. }
  535. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  536. if (desc->pb_serialize_handlers == NULL) {
  537. desc->pb_serialize_handlers =
  538. upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
  539. }
  540. return desc->pb_serialize_handlers;
  541. }
  542. static const upb_handlers* msgdef_json_serialize_handlers(Descriptor* desc) {
  543. if (desc->json_serialize_handlers == NULL) {
  544. desc->json_serialize_handlers =
  545. upb_json_printer_newhandlers(
  546. desc->msgdef, &desc->json_serialize_handlers);
  547. }
  548. return desc->json_serialize_handlers;
  549. }
  550. /*
  551. * call-seq:
  552. * MessageClass.encode(msg) => bytes
  553. *
  554. * Encodes the given message object to its serialized form in protocol buffers
  555. * wire format.
  556. */
  557. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  558. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  559. Descriptor* desc = ruby_to_Descriptor(descriptor);
  560. stringsink sink;
  561. stringsink_init(&sink);
  562. const upb_handlers* serialize_handlers =
  563. msgdef_pb_serialize_handlers(desc);
  564. upb_pb_encoder encoder;
  565. upb_pb_encoder_init(&encoder, serialize_handlers);
  566. upb_pb_encoder_resetoutput(&encoder, &sink.sink);
  567. putmsg(msg_rb, desc, upb_pb_encoder_input(&encoder), 0);
  568. VALUE ret = rb_str_new(sink.ptr, sink.len);
  569. upb_pb_encoder_uninit(&encoder);
  570. stringsink_uninit(&sink);
  571. return ret;
  572. }
  573. /*
  574. * call-seq:
  575. * MessageClass.encode_json(msg) => json_string
  576. *
  577. * Encodes the given message object into its serialized JSON representation.
  578. */
  579. VALUE Message_encode_json(VALUE klass, VALUE msg_rb) {
  580. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  581. Descriptor* desc = ruby_to_Descriptor(descriptor);
  582. stringsink sink;
  583. stringsink_init(&sink);
  584. const upb_handlers* serialize_handlers =
  585. msgdef_json_serialize_handlers(desc);
  586. upb_json_printer printer;
  587. upb_json_printer_init(&printer, serialize_handlers);
  588. upb_json_printer_resetoutput(&printer, &sink.sink);
  589. putmsg(msg_rb, desc, upb_json_printer_input(&printer), 0);
  590. VALUE ret = rb_str_new(sink.ptr, sink.len);
  591. upb_json_printer_uninit(&printer);
  592. stringsink_uninit(&sink);
  593. return ret;
  594. }
  595. /*
  596. * call-seq:
  597. * Google::Protobuf.encode(msg) => bytes
  598. *
  599. * Encodes the given message object to protocol buffers wire format. This is an
  600. * alternative to the #encode method on msg's class.
  601. */
  602. VALUE Google_Protobuf_encode(VALUE self, VALUE msg_rb) {
  603. VALUE klass = CLASS_OF(msg_rb);
  604. return Message_encode(klass, msg_rb);
  605. }
  606. /*
  607. * call-seq:
  608. * Google::Protobuf.encode_json(msg) => json_string
  609. *
  610. * Encodes the given message object to its JSON representation. This is an
  611. * alternative to the #encode_json method on msg's class.
  612. */
  613. VALUE Google_Protobuf_encode_json(VALUE self, VALUE msg_rb) {
  614. VALUE klass = CLASS_OF(msg_rb);
  615. return Message_encode_json(klass, msg_rb);
  616. }
  617. /*
  618. * call-seq:
  619. * Google::Protobuf.decode(class, bytes) => msg
  620. *
  621. * Decodes the given bytes as protocol buffers wire format under the
  622. * interpretation given by the given class's message definition. This is an
  623. * alternative to the #decode method on the given class.
  624. */
  625. VALUE Google_Protobuf_decode(VALUE self, VALUE klass, VALUE msg_rb) {
  626. return Message_decode(klass, msg_rb);
  627. }
  628. /*
  629. * call-seq:
  630. * Google::Protobuf.decode_json(class, json_string) => msg
  631. *
  632. * Decodes the given JSON string under the interpretation given by the given
  633. * class's message definition. This is an alternative to the #decode_json method
  634. * on the given class.
  635. */
  636. VALUE Google_Protobuf_decode_json(VALUE self, VALUE klass, VALUE msg_rb) {
  637. return Message_decode_json(klass, msg_rb);
  638. }