encode_decode.c 34 KB

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