encode_decode.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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(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(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(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(msg, submsgdata->ofs, VALUE) == Qnil) {
  148. DEREF(msg, submsgdata->ofs, VALUE) =
  149. rb_class_new_instance(0, NULL, subklass);
  150. }
  151. VALUE submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
  152. MessageHeader* submsg;
  153. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  154. return submsg;
  155. }
  156. // Handler data for startmap/endmap handlers.
  157. typedef struct {
  158. size_t ofs;
  159. upb_fieldtype_t key_field_type;
  160. upb_fieldtype_t value_field_type;
  161. VALUE value_field_typeclass;
  162. } map_handlerdata_t;
  163. // Temporary frame for map parsing: at the beginning of a map entry message, a
  164. // submsg handler allocates a frame to hold (i) a reference to the Map object
  165. // into which this message will be inserted and (ii) storage slots to
  166. // temporarily hold the key and value for this map entry until the end of the
  167. // submessage. When the submessage ends, another handler is called to insert the
  168. // value into the map.
  169. typedef struct {
  170. VALUE map;
  171. char key_storage[NATIVE_SLOT_MAX_SIZE];
  172. char value_storage[NATIVE_SLOT_MAX_SIZE];
  173. } map_parse_frame_t;
  174. // Handler to begin a map entry: allocates a temporary frame. This is the
  175. // 'startsubmsg' handler on the msgdef that contains the map field.
  176. static void *startmapentry_handler(void *closure, const void *hd) {
  177. MessageHeader* msg = closure;
  178. const map_handlerdata_t* mapdata = hd;
  179. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  180. map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
  181. frame->map = map_rb;
  182. native_slot_init(mapdata->key_field_type, &frame->key_storage);
  183. native_slot_init(mapdata->value_field_type, &frame->value_storage);
  184. return frame;
  185. }
  186. // Handler to end a map entry: inserts the value defined during the message into
  187. // the map. This is the 'endmsg' handler on the map entry msgdef.
  188. static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
  189. map_parse_frame_t* frame = closure;
  190. const map_handlerdata_t* mapdata = hd;
  191. VALUE key = native_slot_get(
  192. mapdata->key_field_type, Qnil,
  193. &frame->key_storage);
  194. VALUE value = native_slot_get(
  195. mapdata->value_field_type, mapdata->value_field_typeclass,
  196. &frame->value_storage);
  197. Map_index_set(frame->map, key, value);
  198. free(frame);
  199. return true;
  200. }
  201. // Allocates a new map_handlerdata_t given the map entry message definition. If
  202. // the offset of the field within the parent message is also given, that is
  203. // added to the handler data as well. Note that this is called *twice* per map
  204. // field: once in the parent message handler setup when setting the startsubmsg
  205. // handler and once in the map entry message handler setup when setting the
  206. // key/value and endmsg handlers. The reason is that there is no easy way to
  207. // pass the handlerdata down to the sub-message handler setup.
  208. static map_handlerdata_t* new_map_handlerdata(
  209. size_t ofs,
  210. const upb_msgdef* mapentry_def,
  211. Descriptor* desc) {
  212. map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
  213. hd->ofs = ofs;
  214. const upb_fielddef* key_field = upb_msgdef_itof(mapentry_def,
  215. MAP_KEY_FIELD);
  216. assert(key_field != NULL);
  217. hd->key_field_type = upb_fielddef_type(key_field);
  218. const upb_fielddef* value_field = upb_msgdef_itof(mapentry_def,
  219. MAP_VALUE_FIELD);
  220. assert(value_field != NULL);
  221. hd->value_field_type = upb_fielddef_type(value_field);
  222. hd->value_field_typeclass = field_type_class(value_field);
  223. // Ensure that value_field_typeclass is properly GC-rooted. We must do this
  224. // because we hold a reference to the Ruby class in the handlerdata, which is
  225. // owned by the handlers. The handlers are owned by *this* message's Ruby
  226. // object, but each Ruby object is rooted independently at the def -> Ruby
  227. // object map. So we have to ensure that the Ruby objects we depend on will
  228. // stick around as long as we're around.
  229. if (hd->value_field_typeclass != Qnil) {
  230. rb_ary_push(desc->typeclass_references, hd->value_field_typeclass);
  231. }
  232. return hd;
  233. }
  234. // Set up handlers for a repeated field.
  235. static void add_handlers_for_repeated_field(upb_handlers *h,
  236. const upb_fielddef *f,
  237. size_t offset) {
  238. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  239. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  240. upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  241. upb_handlerattr_uninit(&attr);
  242. switch (upb_fielddef_type(f)) {
  243. #define SET_HANDLER(utype, ltype) \
  244. case utype: \
  245. upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
  246. break;
  247. SET_HANDLER(UPB_TYPE_BOOL, bool);
  248. SET_HANDLER(UPB_TYPE_INT32, int32);
  249. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  250. SET_HANDLER(UPB_TYPE_ENUM, int32);
  251. SET_HANDLER(UPB_TYPE_FLOAT, float);
  252. SET_HANDLER(UPB_TYPE_INT64, int64);
  253. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  254. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  255. #undef SET_HANDLER
  256. case UPB_TYPE_STRING:
  257. case UPB_TYPE_BYTES: {
  258. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  259. upb_handlers_setstartstr(h, f, is_bytes ?
  260. appendbytes_handler : appendstr_handler,
  261. NULL);
  262. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  263. break;
  264. }
  265. case UPB_TYPE_MESSAGE: {
  266. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  267. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
  268. upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
  269. upb_handlerattr_uninit(&attr);
  270. break;
  271. }
  272. }
  273. }
  274. // Set up handlers for a singular field.
  275. static void add_handlers_for_singular_field(upb_handlers *h,
  276. const upb_fielddef *f,
  277. size_t offset) {
  278. switch (upb_fielddef_type(f)) {
  279. case UPB_TYPE_BOOL:
  280. case UPB_TYPE_INT32:
  281. case UPB_TYPE_UINT32:
  282. case UPB_TYPE_ENUM:
  283. case UPB_TYPE_FLOAT:
  284. case UPB_TYPE_INT64:
  285. case UPB_TYPE_UINT64:
  286. case UPB_TYPE_DOUBLE:
  287. upb_shim_set(h, f, offset, -1);
  288. break;
  289. case UPB_TYPE_STRING:
  290. case UPB_TYPE_BYTES: {
  291. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  292. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  293. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  294. upb_handlers_setstartstr(h, f,
  295. is_bytes ? bytes_handler : str_handler,
  296. &attr);
  297. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  298. upb_handlerattr_uninit(&attr);
  299. break;
  300. }
  301. case UPB_TYPE_MESSAGE: {
  302. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  303. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
  304. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  305. upb_handlerattr_uninit(&attr);
  306. break;
  307. }
  308. }
  309. }
  310. // Adds handlers to a map field.
  311. static void add_handlers_for_mapfield(upb_handlers* h,
  312. const upb_fielddef* fielddef,
  313. size_t offset,
  314. Descriptor* desc) {
  315. const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
  316. map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
  317. upb_handlers_addcleanup(h, hd, free);
  318. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  319. upb_handlerattr_sethandlerdata(&attr, hd);
  320. upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
  321. upb_handlerattr_uninit(&attr);
  322. }
  323. // Adds handlers to a map-entry msgdef.
  324. static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
  325. upb_handlers* h,
  326. Descriptor* desc) {
  327. const upb_fielddef* key_field = map_entry_key(msgdef);
  328. const upb_fielddef* value_field = map_entry_value(msgdef);
  329. map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
  330. upb_handlers_addcleanup(h, hd, free);
  331. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  332. upb_handlerattr_sethandlerdata(&attr, hd);
  333. upb_handlers_setendmsg(h, endmap_handler, &attr);
  334. add_handlers_for_singular_field(
  335. h, key_field,
  336. offsetof(map_parse_frame_t, key_storage));
  337. add_handlers_for_singular_field(
  338. h, value_field,
  339. offsetof(map_parse_frame_t, value_storage));
  340. }
  341. static void add_handlers_for_message(const void *closure, upb_handlers *h) {
  342. const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  343. Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
  344. // If this is a mapentry message type, set up a special set of handlers and
  345. // bail out of the normal (user-defined) message type handling.
  346. if (upb_msgdef_mapentry(msgdef)) {
  347. add_handlers_for_mapentry(msgdef, h, desc);
  348. return;
  349. }
  350. // Ensure layout exists. We may be invoked to create handlers for a given
  351. // message if we are included as a submsg of another message type before our
  352. // class is actually built, so to work around this, we just create the layout
  353. // (and handlers, in the class-building function) on-demand.
  354. if (desc->layout == NULL) {
  355. desc->layout = create_layout(desc->msgdef);
  356. }
  357. upb_msg_iter i;
  358. for (upb_msg_begin(&i, desc->msgdef);
  359. !upb_msg_done(&i);
  360. upb_msg_next(&i)) {
  361. const upb_fielddef *f = upb_msg_iter_field(&i);
  362. size_t offset = desc->layout->offsets[upb_fielddef_index(f)] +
  363. sizeof(MessageHeader);
  364. if (is_map_field(f)) {
  365. add_handlers_for_mapfield(h, f, offset, desc);
  366. } else if (upb_fielddef_isseq(f)) {
  367. add_handlers_for_repeated_field(h, f, offset);
  368. } else {
  369. add_handlers_for_singular_field(h, f, offset);
  370. }
  371. }
  372. }
  373. // Creates upb handlers for populating a message.
  374. static const upb_handlers *new_fill_handlers(Descriptor* desc,
  375. const void* owner) {
  376. // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
  377. // handlers, reuse subdef handlers so that e.g. if we already parse
  378. // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
  379. // parse A-with-field-of-type-B-with-field-of-type-C.
  380. return upb_handlers_newfrozen(desc->msgdef, owner,
  381. add_handlers_for_message, NULL);
  382. }
  383. // Constructs the handlers for filling a message's data into an in-memory
  384. // object.
  385. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  386. if (!desc->fill_handlers) {
  387. desc->fill_handlers =
  388. new_fill_handlers(desc, &desc->fill_handlers);
  389. }
  390. return desc->fill_handlers;
  391. }
  392. // Constructs the upb decoder method for parsing messages of this type.
  393. // This is called from the message class creation code.
  394. const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
  395. const void* owner) {
  396. const upb_handlers* handlers = get_fill_handlers(desc);
  397. upb_pbdecodermethodopts opts;
  398. upb_pbdecodermethodopts_init(&opts, handlers);
  399. const upb_pbdecodermethod *ret = upb_pbdecodermethod_new(&opts, owner);
  400. return ret;
  401. }
  402. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  403. if (desc->fill_method == NULL) {
  404. desc->fill_method = new_fillmsg_decodermethod(
  405. desc, &desc->fill_method);
  406. }
  407. return desc->fill_method;
  408. }
  409. /*
  410. * call-seq:
  411. * MessageClass.decode(data) => message
  412. *
  413. * Decodes the given data (as a string containing bytes in protocol buffers wire
  414. * format) under the interpretration given by this message class's definition
  415. * and returns a message object with the corresponding field values.
  416. */
  417. VALUE Message_decode(VALUE klass, VALUE data) {
  418. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  419. Descriptor* desc = ruby_to_Descriptor(descriptor);
  420. VALUE msgklass = Descriptor_msgclass(descriptor);
  421. if (TYPE(data) != T_STRING) {
  422. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  423. }
  424. VALUE msg_rb = rb_class_new_instance(0, NULL, msgklass);
  425. MessageHeader* msg;
  426. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  427. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  428. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  429. upb_pbdecoder decoder;
  430. upb_sink sink;
  431. upb_status status = UPB_STATUS_INIT;
  432. upb_pbdecoder_init(&decoder, method, &status);
  433. upb_sink_reset(&sink, h, msg);
  434. upb_pbdecoder_resetoutput(&decoder, &sink);
  435. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  436. upb_pbdecoder_input(&decoder));
  437. upb_pbdecoder_uninit(&decoder);
  438. if (!upb_ok(&status)) {
  439. rb_raise(rb_eRuntimeError, "Error occurred during parsing: %s.",
  440. upb_status_errmsg(&status));
  441. }
  442. return msg_rb;
  443. }
  444. /*
  445. * call-seq:
  446. * MessageClass.decode_json(data) => message
  447. *
  448. * Decodes the given data (as a string containing bytes in protocol buffers wire
  449. * format) under the interpretration given by this message class's definition
  450. * and returns a message object with the corresponding field values.
  451. */
  452. VALUE Message_decode_json(VALUE klass, VALUE data) {
  453. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  454. Descriptor* desc = ruby_to_Descriptor(descriptor);
  455. VALUE msgklass = Descriptor_msgclass(descriptor);
  456. if (TYPE(data) != T_STRING) {
  457. rb_raise(rb_eArgError, "Expected string for JSON data.");
  458. }
  459. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  460. // convert, because string handlers pass data directly to message string
  461. // fields.
  462. VALUE msg_rb = rb_class_new_instance(0, NULL, msgklass);
  463. MessageHeader* msg;
  464. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  465. upb_status status = UPB_STATUS_INIT;
  466. upb_json_parser parser;
  467. upb_json_parser_init(&parser, &status);
  468. upb_sink sink;
  469. upb_sink_reset(&sink, get_fill_handlers(desc), msg);
  470. upb_json_parser_resetoutput(&parser, &sink);
  471. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  472. upb_json_parser_input(&parser));
  473. upb_json_parser_uninit(&parser);
  474. if (!upb_ok(&status)) {
  475. rb_raise(rb_eRuntimeError, "Error occurred during parsing: %s.",
  476. upb_status_errmsg(&status));
  477. }
  478. return msg_rb;
  479. }
  480. // -----------------------------------------------------------------------------
  481. // Serializing.
  482. // -----------------------------------------------------------------------------
  483. //
  484. // The code below also comes from upb's prototype Ruby binding, developed by
  485. // haberman@.
  486. /* stringsink *****************************************************************/
  487. // This should probably be factored into a common upb component.
  488. typedef struct {
  489. upb_byteshandler handler;
  490. upb_bytessink sink;
  491. char *ptr;
  492. size_t len, size;
  493. } stringsink;
  494. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  495. stringsink *sink = _sink;
  496. sink->len = 0;
  497. return sink;
  498. }
  499. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  500. size_t len, const upb_bufhandle *handle) {
  501. UPB_UNUSED(hd);
  502. UPB_UNUSED(handle);
  503. stringsink *sink = _sink;
  504. size_t new_size = sink->size;
  505. while (sink->len + len > new_size) {
  506. new_size *= 2;
  507. }
  508. if (new_size != sink->size) {
  509. sink->ptr = realloc(sink->ptr, new_size);
  510. sink->size = new_size;
  511. }
  512. memcpy(sink->ptr + sink->len, ptr, len);
  513. sink->len += len;
  514. return len;
  515. }
  516. void stringsink_init(stringsink *sink) {
  517. upb_byteshandler_init(&sink->handler);
  518. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  519. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  520. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  521. sink->size = 32;
  522. sink->ptr = malloc(sink->size);
  523. sink->len = 0;
  524. }
  525. void stringsink_uninit(stringsink *sink) {
  526. free(sink->ptr);
  527. }
  528. /* msgvisitor *****************************************************************/
  529. // TODO: If/when we support proto2 semantics in addition to the current proto3
  530. // semantics, which means that we have true field presence, we will want to
  531. // modify msgvisitor so that it emits all present fields rather than all
  532. // non-default-value fields.
  533. //
  534. // Likewise, when implementing JSON serialization, we may need to have a
  535. // 'verbose' mode that outputs all fields and a 'concise' mode that outputs only
  536. // those with non-default values.
  537. static void putmsg(VALUE msg, const Descriptor* desc,
  538. upb_sink *sink, int depth);
  539. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  540. upb_selector_t ret;
  541. bool ok = upb_handlers_getselector(f, type, &ret);
  542. UPB_ASSERT_VAR(ok, ok);
  543. return ret;
  544. }
  545. static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
  546. if (str == Qnil) return;
  547. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  548. upb_sink subsink;
  549. // Ensure that the string has the correct encoding. We also check at field-set
  550. // time, but the user may have mutated the string object since then.
  551. native_slot_validate_string_encoding(upb_fielddef_type(f), str);
  552. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  553. &subsink);
  554. upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  555. RSTRING_LEN(str), NULL);
  556. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  557. }
  558. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
  559. int depth) {
  560. if (submsg == Qnil) return;
  561. upb_sink subsink;
  562. VALUE descriptor = rb_iv_get(submsg, kDescriptorInstanceVar);
  563. Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  564. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  565. putmsg(submsg, subdesc, &subsink, depth + 1);
  566. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  567. }
  568. static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
  569. int depth) {
  570. if (ary == Qnil) return;
  571. upb_sink subsink;
  572. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  573. upb_fieldtype_t type = upb_fielddef_type(f);
  574. upb_selector_t sel = 0;
  575. if (upb_fielddef_isprimitive(f)) {
  576. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  577. }
  578. int size = NUM2INT(RepeatedField_length(ary));
  579. for (int i = 0; i < size; i++) {
  580. void* memory = RepeatedField_index_native(ary, i);
  581. switch (type) {
  582. #define T(upbtypeconst, upbtype, ctype) \
  583. case upbtypeconst: \
  584. upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
  585. break;
  586. T(UPB_TYPE_FLOAT, float, float)
  587. T(UPB_TYPE_DOUBLE, double, double)
  588. T(UPB_TYPE_BOOL, bool, int8_t)
  589. case UPB_TYPE_ENUM:
  590. T(UPB_TYPE_INT32, int32, int32_t)
  591. T(UPB_TYPE_UINT32, uint32, uint32_t)
  592. T(UPB_TYPE_INT64, int64, int64_t)
  593. T(UPB_TYPE_UINT64, uint64, uint64_t)
  594. case UPB_TYPE_STRING:
  595. case UPB_TYPE_BYTES:
  596. putstr(*((VALUE *)memory), f, &subsink);
  597. break;
  598. case UPB_TYPE_MESSAGE:
  599. putsubmsg(*((VALUE *)memory), f, &subsink, depth);
  600. break;
  601. #undef T
  602. }
  603. }
  604. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  605. }
  606. static void put_ruby_value(VALUE value,
  607. const upb_fielddef *f,
  608. VALUE type_class,
  609. int depth,
  610. upb_sink *sink) {
  611. upb_selector_t sel = 0;
  612. if (upb_fielddef_isprimitive(f)) {
  613. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  614. }
  615. switch (upb_fielddef_type(f)) {
  616. case UPB_TYPE_INT32:
  617. upb_sink_putint32(sink, sel, NUM2INT(value));
  618. break;
  619. case UPB_TYPE_INT64:
  620. upb_sink_putint64(sink, sel, NUM2LL(value));
  621. break;
  622. case UPB_TYPE_UINT32:
  623. upb_sink_putuint32(sink, sel, NUM2UINT(value));
  624. break;
  625. case UPB_TYPE_UINT64:
  626. upb_sink_putuint64(sink, sel, NUM2ULL(value));
  627. break;
  628. case UPB_TYPE_FLOAT:
  629. upb_sink_putfloat(sink, sel, NUM2DBL(value));
  630. break;
  631. case UPB_TYPE_DOUBLE:
  632. upb_sink_putdouble(sink, sel, NUM2DBL(value));
  633. break;
  634. case UPB_TYPE_ENUM: {
  635. if (TYPE(value) == T_SYMBOL) {
  636. value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  637. }
  638. upb_sink_putint32(sink, sel, NUM2INT(value));
  639. break;
  640. }
  641. case UPB_TYPE_BOOL:
  642. upb_sink_putbool(sink, sel, value == Qtrue);
  643. break;
  644. case UPB_TYPE_STRING:
  645. case UPB_TYPE_BYTES:
  646. putstr(value, f, sink);
  647. break;
  648. case UPB_TYPE_MESSAGE:
  649. putsubmsg(value, f, sink, depth);
  650. }
  651. }
  652. static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
  653. int depth) {
  654. if (map == Qnil) return;
  655. Map* self = ruby_to_Map(map);
  656. upb_sink subsink;
  657. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  658. assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  659. const upb_fielddef* key_field = map_field_key(f);
  660. const upb_fielddef* value_field = map_field_value(f);
  661. Map_iter it;
  662. for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
  663. VALUE key = Map_iter_key(&it);
  664. VALUE value = Map_iter_value(&it);
  665. upb_sink entry_sink;
  666. upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG), &entry_sink);
  667. upb_sink_startmsg(&entry_sink);
  668. put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink);
  669. put_ruby_value(value, value_field, self->value_type_class, depth + 1,
  670. &entry_sink);
  671. upb_status status;
  672. upb_sink_endmsg(&entry_sink, &status);
  673. upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  674. }
  675. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  676. }
  677. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  678. upb_sink *sink, int depth) {
  679. upb_sink_startmsg(sink);
  680. // Protect against cycles (possible because users may freely reassign message
  681. // and repeated fields) by imposing a maximum recursion depth.
  682. if (depth > UPB_SINK_MAX_NESTING) {
  683. rb_raise(rb_eRuntimeError,
  684. "Maximum recursion depth exceeded during encoding.");
  685. }
  686. MessageHeader* msg;
  687. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  688. upb_msg_iter i;
  689. for (upb_msg_begin(&i, desc->msgdef);
  690. !upb_msg_done(&i);
  691. upb_msg_next(&i)) {
  692. upb_fielddef *f = upb_msg_iter_field(&i);
  693. uint32_t offset =
  694. desc->layout->offsets[upb_fielddef_index(f)] + sizeof(MessageHeader);
  695. if (is_map_field(f)) {
  696. VALUE map = DEREF(msg, offset, VALUE);
  697. if (map != Qnil) {
  698. putmap(map, f, sink, depth);
  699. }
  700. } else if (upb_fielddef_isseq(f)) {
  701. VALUE ary = DEREF(msg, offset, VALUE);
  702. if (ary != Qnil) {
  703. putary(ary, f, sink, depth);
  704. }
  705. } else if (upb_fielddef_isstring(f)) {
  706. VALUE str = DEREF(msg, offset, VALUE);
  707. if (RSTRING_LEN(str) > 0) {
  708. putstr(str, f, sink);
  709. }
  710. } else if (upb_fielddef_issubmsg(f)) {
  711. putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth);
  712. } else {
  713. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  714. #define T(upbtypeconst, upbtype, ctype, default_value) \
  715. case upbtypeconst: { \
  716. ctype value = DEREF(msg, offset, ctype); \
  717. if (value != default_value) { \
  718. upb_sink_put##upbtype(sink, sel, value); \
  719. } \
  720. } \
  721. break;
  722. switch (upb_fielddef_type(f)) {
  723. T(UPB_TYPE_FLOAT, float, float, 0.0)
  724. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  725. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  726. case UPB_TYPE_ENUM:
  727. T(UPB_TYPE_INT32, int32, int32_t, 0)
  728. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  729. T(UPB_TYPE_INT64, int64, int64_t, 0)
  730. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  731. case UPB_TYPE_STRING:
  732. case UPB_TYPE_BYTES:
  733. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  734. }
  735. #undef T
  736. }
  737. }
  738. upb_status status;
  739. upb_sink_endmsg(sink, &status);
  740. }
  741. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  742. if (desc->pb_serialize_handlers == NULL) {
  743. desc->pb_serialize_handlers =
  744. upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
  745. }
  746. return desc->pb_serialize_handlers;
  747. }
  748. static const upb_handlers* msgdef_json_serialize_handlers(Descriptor* desc) {
  749. if (desc->json_serialize_handlers == NULL) {
  750. desc->json_serialize_handlers =
  751. upb_json_printer_newhandlers(
  752. desc->msgdef, &desc->json_serialize_handlers);
  753. }
  754. return desc->json_serialize_handlers;
  755. }
  756. /*
  757. * call-seq:
  758. * MessageClass.encode(msg) => bytes
  759. *
  760. * Encodes the given message object to its serialized form in protocol buffers
  761. * wire format.
  762. */
  763. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  764. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  765. Descriptor* desc = ruby_to_Descriptor(descriptor);
  766. stringsink sink;
  767. stringsink_init(&sink);
  768. const upb_handlers* serialize_handlers =
  769. msgdef_pb_serialize_handlers(desc);
  770. upb_pb_encoder encoder;
  771. upb_pb_encoder_init(&encoder, serialize_handlers);
  772. upb_pb_encoder_resetoutput(&encoder, &sink.sink);
  773. putmsg(msg_rb, desc, upb_pb_encoder_input(&encoder), 0);
  774. VALUE ret = rb_str_new(sink.ptr, sink.len);
  775. upb_pb_encoder_uninit(&encoder);
  776. stringsink_uninit(&sink);
  777. return ret;
  778. }
  779. /*
  780. * call-seq:
  781. * MessageClass.encode_json(msg) => json_string
  782. *
  783. * Encodes the given message object into its serialized JSON representation.
  784. */
  785. VALUE Message_encode_json(VALUE klass, VALUE msg_rb) {
  786. VALUE descriptor = rb_iv_get(klass, kDescriptorInstanceVar);
  787. Descriptor* desc = ruby_to_Descriptor(descriptor);
  788. stringsink sink;
  789. stringsink_init(&sink);
  790. const upb_handlers* serialize_handlers =
  791. msgdef_json_serialize_handlers(desc);
  792. upb_json_printer printer;
  793. upb_json_printer_init(&printer, serialize_handlers);
  794. upb_json_printer_resetoutput(&printer, &sink.sink);
  795. putmsg(msg_rb, desc, upb_json_printer_input(&printer), 0);
  796. VALUE ret = rb_str_new(sink.ptr, sink.len);
  797. upb_json_printer_uninit(&printer);
  798. stringsink_uninit(&sink);
  799. return ret;
  800. }
  801. /*
  802. * call-seq:
  803. * Google::Protobuf.encode(msg) => bytes
  804. *
  805. * Encodes the given message object to protocol buffers wire format. This is an
  806. * alternative to the #encode method on msg's class.
  807. */
  808. VALUE Google_Protobuf_encode(VALUE self, VALUE msg_rb) {
  809. VALUE klass = CLASS_OF(msg_rb);
  810. return Message_encode(klass, msg_rb);
  811. }
  812. /*
  813. * call-seq:
  814. * Google::Protobuf.encode_json(msg) => json_string
  815. *
  816. * Encodes the given message object to its JSON representation. This is an
  817. * alternative to the #encode_json method on msg's class.
  818. */
  819. VALUE Google_Protobuf_encode_json(VALUE self, VALUE msg_rb) {
  820. VALUE klass = CLASS_OF(msg_rb);
  821. return Message_encode_json(klass, msg_rb);
  822. }
  823. /*
  824. * call-seq:
  825. * Google::Protobuf.decode(class, bytes) => msg
  826. *
  827. * Decodes the given bytes as protocol buffers wire format under the
  828. * interpretation given by the given class's message definition. This is an
  829. * alternative to the #decode method on the given class.
  830. */
  831. VALUE Google_Protobuf_decode(VALUE self, VALUE klass, VALUE msg_rb) {
  832. return Message_decode(klass, msg_rb);
  833. }
  834. /*
  835. * call-seq:
  836. * Google::Protobuf.decode_json(class, json_string) => msg
  837. *
  838. * Decodes the given JSON string under the interpretation given by the given
  839. * class's message definition. This is an alternative to the #decode_json method
  840. * on the given class.
  841. */
  842. VALUE Google_Protobuf_decode_json(VALUE self, VALUE klass, VALUE msg_rb) {
  843. return Message_decode_json(klass, msg_rb);
  844. }