encode_decode.c 34 KB

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