encode_decode.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  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. // This function is equivalent to rb_str_cat(), but unlike the real
  32. // rb_str_cat(), it doesn't leak memory in some versions of Ruby.
  33. // For more information, see:
  34. // https://bugs.ruby-lang.org/issues/11328
  35. VALUE noleak_rb_str_cat(VALUE rb_str, const char *str, long len) {
  36. char *p;
  37. size_t oldlen = RSTRING_LEN(rb_str);
  38. rb_str_modify_expand(rb_str, len);
  39. p = RSTRING_PTR(rb_str);
  40. memcpy(p + oldlen, str, len);
  41. rb_str_set_len(rb_str, oldlen + len);
  42. return rb_str;
  43. }
  44. bool is_wrapper(const upb_msgdef* m) {
  45. switch (upb_msgdef_wellknowntype(m)) {
  46. case UPB_WELLKNOWN_DOUBLEVALUE:
  47. case UPB_WELLKNOWN_FLOATVALUE:
  48. case UPB_WELLKNOWN_INT64VALUE:
  49. case UPB_WELLKNOWN_UINT64VALUE:
  50. case UPB_WELLKNOWN_INT32VALUE:
  51. case UPB_WELLKNOWN_UINT32VALUE:
  52. case UPB_WELLKNOWN_STRINGVALUE:
  53. case UPB_WELLKNOWN_BYTESVALUE:
  54. case UPB_WELLKNOWN_BOOLVALUE:
  55. return true;
  56. default:
  57. return false;
  58. }
  59. }
  60. // The code below also comes from upb's prototype Ruby binding, developed by
  61. // haberman@.
  62. /* stringsink *****************************************************************/
  63. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  64. stringsink *sink = _sink;
  65. sink->len = 0;
  66. return sink;
  67. }
  68. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  69. size_t len, const upb_bufhandle *handle) {
  70. stringsink *sink = _sink;
  71. size_t new_size = sink->size;
  72. UPB_UNUSED(hd);
  73. UPB_UNUSED(handle);
  74. while (sink->len + len > new_size) {
  75. new_size *= 2;
  76. }
  77. if (new_size != sink->size) {
  78. sink->ptr = realloc(sink->ptr, new_size);
  79. sink->size = new_size;
  80. }
  81. memcpy(sink->ptr + sink->len, ptr, len);
  82. sink->len += len;
  83. return len;
  84. }
  85. void stringsink_init(stringsink *sink) {
  86. upb_byteshandler_init(&sink->handler);
  87. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  88. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  89. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  90. sink->size = 32;
  91. sink->ptr = malloc(sink->size);
  92. sink->len = 0;
  93. }
  94. void stringsink_uninit(stringsink *sink) {
  95. free(sink->ptr);
  96. }
  97. // -----------------------------------------------------------------------------
  98. // Parsing.
  99. // -----------------------------------------------------------------------------
  100. #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
  101. typedef struct {
  102. size_t ofs;
  103. int32_t hasbit;
  104. } field_handlerdata_t;
  105. // Creates a handlerdata that contains the offset and the hasbit for the field
  106. static const void* newhandlerdata(upb_handlers* h, uint32_t ofs, int32_t hasbit) {
  107. field_handlerdata_t *hd = ALLOC(field_handlerdata_t);
  108. hd->ofs = ofs;
  109. hd->hasbit = hasbit;
  110. upb_handlers_addcleanup(h, hd, xfree);
  111. return hd;
  112. }
  113. typedef struct {
  114. size_t ofs;
  115. int32_t hasbit;
  116. upb_fieldtype_t wrapped_type; // Only for wrappers.
  117. VALUE subklass;
  118. } submsg_handlerdata_t;
  119. // Creates a handlerdata that contains offset and submessage type information.
  120. static const void *newsubmsghandlerdata(upb_handlers* h,
  121. const upb_fielddef *f,
  122. uint32_t ofs,
  123. int32_t hasbit,
  124. VALUE subklass) {
  125. submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
  126. const upb_msgdef *subm = upb_fielddef_msgsubdef(f);
  127. hd->ofs = ofs;
  128. hd->hasbit = hasbit;
  129. hd->subklass = subklass;
  130. upb_handlers_addcleanup(h, hd, xfree);
  131. if (is_wrapper(subm)) {
  132. const upb_fielddef *value_f = upb_msgdef_itof(subm, 1);
  133. hd->wrapped_type = upb_fielddef_type(value_f);
  134. }
  135. return hd;
  136. }
  137. typedef struct {
  138. size_t ofs; // union data slot
  139. size_t case_ofs; // oneof_case field
  140. uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
  141. VALUE subklass;
  142. } oneof_handlerdata_t;
  143. static const void *newoneofhandlerdata(upb_handlers *h,
  144. uint32_t ofs,
  145. uint32_t case_ofs,
  146. const upb_fielddef *f,
  147. const Descriptor* desc) {
  148. oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
  149. hd->ofs = ofs;
  150. hd->case_ofs = case_ofs;
  151. // We reuse the field tag number as a oneof union discriminant tag. Note that
  152. // we don't expose these numbers to the user, so the only requirement is that
  153. // we have some unique ID for each union case/possibility. The field tag
  154. // numbers are already present and are easy to use so there's no reason to
  155. // create a separate ID space. In addition, using the field tag number here
  156. // lets us easily look up the field in the oneof accessor.
  157. hd->oneof_case_num = upb_fielddef_number(f);
  158. if (is_value_field(f)) {
  159. hd->oneof_case_num |= ONEOF_CASE_MASK;
  160. }
  161. hd->subklass = field_type_class(desc->layout, f);
  162. upb_handlers_addcleanup(h, hd, xfree);
  163. return hd;
  164. }
  165. // A handler that starts a repeated field. Gets the Repeated*Field instance for
  166. // this field (such an instance always exists even in an empty message).
  167. static void *startseq_handler(void* closure, const void* hd) {
  168. MessageHeader* msg = closure;
  169. const size_t *ofs = hd;
  170. return (void*)DEREF(msg, *ofs, VALUE);
  171. }
  172. // Handlers that append primitive values to a repeated field.
  173. #define DEFINE_APPEND_HANDLER(type, ctype) \
  174. static bool append##type##_handler(void *closure, const void *hd, \
  175. ctype val) { \
  176. VALUE ary = (VALUE)closure; \
  177. RepeatedField_push_native(ary, &val); \
  178. return true; \
  179. }
  180. DEFINE_APPEND_HANDLER(bool, bool)
  181. DEFINE_APPEND_HANDLER(int32, int32_t)
  182. DEFINE_APPEND_HANDLER(uint32, uint32_t)
  183. DEFINE_APPEND_HANDLER(float, float)
  184. DEFINE_APPEND_HANDLER(int64, int64_t)
  185. DEFINE_APPEND_HANDLER(uint64, uint64_t)
  186. DEFINE_APPEND_HANDLER(double, double)
  187. // Appends a string to a repeated field.
  188. static void* appendstr_handler(void *closure,
  189. const void *hd,
  190. size_t size_hint) {
  191. VALUE ary = (VALUE)closure;
  192. VALUE str = rb_str_new2("");
  193. rb_enc_associate(str, kRubyStringUtf8Encoding);
  194. RepeatedField_push_native(ary, &str);
  195. return (void*)str;
  196. }
  197. static void set_hasbit(void *closure, int32_t hasbit) {
  198. if (hasbit > 0) {
  199. uint8_t* storage = closure;
  200. storage[hasbit/8] |= 1 << (hasbit % 8);
  201. }
  202. }
  203. // Appends a 'bytes' string to a repeated field.
  204. static void* appendbytes_handler(void *closure,
  205. const void *hd,
  206. size_t size_hint) {
  207. VALUE ary = (VALUE)closure;
  208. VALUE str = rb_str_new2("");
  209. rb_enc_associate(str, kRubyString8bitEncoding);
  210. RepeatedField_push_native(ary, &str);
  211. return (void*)str;
  212. }
  213. // Sets a non-repeated string field in a message.
  214. static void* str_handler(void *closure,
  215. const void *hd,
  216. size_t size_hint) {
  217. MessageHeader* msg = closure;
  218. const field_handlerdata_t *fieldhandler = hd;
  219. VALUE str = rb_str_new2("");
  220. rb_enc_associate(str, kRubyStringUtf8Encoding);
  221. DEREF(msg, fieldhandler->ofs, VALUE) = str;
  222. set_hasbit(closure, fieldhandler->hasbit);
  223. return (void*)str;
  224. }
  225. // Sets a non-repeated 'bytes' field in a message.
  226. static void* bytes_handler(void *closure,
  227. const void *hd,
  228. size_t size_hint) {
  229. MessageHeader* msg = closure;
  230. const field_handlerdata_t *fieldhandler = hd;
  231. VALUE str = rb_str_new2("");
  232. rb_enc_associate(str, kRubyString8bitEncoding);
  233. DEREF(msg, fieldhandler->ofs, VALUE) = str;
  234. set_hasbit(closure, fieldhandler->hasbit);
  235. return (void*)str;
  236. }
  237. static size_t stringdata_handler(void* closure, const void* hd,
  238. const char* str, size_t len,
  239. const upb_bufhandle* handle) {
  240. VALUE rb_str = (VALUE)closure;
  241. noleak_rb_str_cat(rb_str, str, len);
  242. return len;
  243. }
  244. static bool stringdata_end_handler(void* closure, const void* hd) {
  245. VALUE rb_str = (VALUE)closure;
  246. rb_obj_freeze(rb_str);
  247. return true;
  248. }
  249. static bool appendstring_end_handler(void* closure, const void* hd) {
  250. VALUE rb_str = (VALUE)closure;
  251. rb_obj_freeze(rb_str);
  252. return true;
  253. }
  254. // Appends a submessage to a repeated field (a regular Ruby array for now).
  255. static void *appendsubmsg_handler(void *closure, const void *hd) {
  256. VALUE ary = (VALUE)closure;
  257. const submsg_handlerdata_t *submsgdata = hd;
  258. MessageHeader* submsg;
  259. VALUE submsg_rb = rb_class_new_instance(0, NULL, submsgdata->subklass);
  260. RepeatedField_push(ary, submsg_rb);
  261. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  262. return submsg;
  263. }
  264. // Appends a wrapper to a repeated field (a regular Ruby array for now).
  265. static void *appendwrapper_handler(void *closure, const void *hd) {
  266. VALUE ary = (VALUE)closure;
  267. int size = RepeatedField_size(ary);
  268. (void)hd;
  269. RepeatedField_push(ary, Qnil);
  270. return RepeatedField_index_native(ary, size);
  271. }
  272. // Sets a non-repeated submessage field in a message.
  273. static void *submsg_handler(void *closure, const void *hd) {
  274. MessageHeader* msg = closure;
  275. const submsg_handlerdata_t* submsgdata = hd;
  276. VALUE submsg_rb;
  277. MessageHeader* submsg;
  278. if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
  279. DEREF(msg, submsgdata->ofs, VALUE) =
  280. rb_class_new_instance(0, NULL, submsgdata->subklass);
  281. }
  282. set_hasbit(closure, submsgdata->hasbit);
  283. submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
  284. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  285. return submsg;
  286. }
  287. static void* startwrapper(void* closure, const void* hd) {
  288. const submsg_handlerdata_t* submsgdata = hd;
  289. char* msg = closure;
  290. VALUE* field = (VALUE*)(msg + submsgdata->ofs);
  291. set_hasbit(closure, submsgdata->hasbit);
  292. switch (submsgdata->wrapped_type) {
  293. case UPB_TYPE_FLOAT:
  294. case UPB_TYPE_DOUBLE:
  295. *field = DBL2NUM(0);
  296. break;
  297. case UPB_TYPE_BOOL:
  298. *field = Qfalse;
  299. break;
  300. case UPB_TYPE_STRING:
  301. *field = get_frozen_string(NULL, 0, false);
  302. break;
  303. case UPB_TYPE_BYTES:
  304. *field = get_frozen_string(NULL, 0, true);
  305. break;
  306. case UPB_TYPE_ENUM:
  307. case UPB_TYPE_INT32:
  308. case UPB_TYPE_INT64:
  309. case UPB_TYPE_UINT32:
  310. case UPB_TYPE_UINT64:
  311. *field = INT2NUM(0);
  312. break;
  313. case UPB_TYPE_MESSAGE:
  314. rb_raise(rb_eRuntimeError,
  315. "Internal logic error with well-known types.");
  316. }
  317. return field;
  318. }
  319. // Handler data for startmap/endmap handlers.
  320. typedef struct {
  321. size_t ofs;
  322. upb_fieldtype_t key_field_type;
  323. upb_fieldtype_t value_field_type;
  324. VALUE subklass;
  325. } map_handlerdata_t;
  326. // Temporary frame for map parsing: at the beginning of a map entry message, a
  327. // submsg handler allocates a frame to hold (i) a reference to the Map object
  328. // into which this message will be inserted and (ii) storage slots to
  329. // temporarily hold the key and value for this map entry until the end of the
  330. // submessage. When the submessage ends, another handler is called to insert the
  331. // value into the map.
  332. typedef struct {
  333. VALUE map;
  334. const map_handlerdata_t* handlerdata;
  335. char key_storage[NATIVE_SLOT_MAX_SIZE];
  336. char value_storage[NATIVE_SLOT_MAX_SIZE];
  337. } map_parse_frame_t;
  338. static void MapParseFrame_mark(void* _self) {
  339. map_parse_frame_t* frame = _self;
  340. // This shouldn't strictly be necessary since this should be rooted by the
  341. // message itself, but it can't hurt.
  342. rb_gc_mark(frame->map);
  343. native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
  344. native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
  345. }
  346. void MapParseFrame_free(void* self) {
  347. xfree(self);
  348. }
  349. rb_data_type_t MapParseFrame_type = {
  350. "MapParseFrame",
  351. { MapParseFrame_mark, MapParseFrame_free, NULL },
  352. };
  353. // Handler to begin a map entry: allocates a temporary frame. This is the
  354. // 'startsubmsg' handler on the msgdef that contains the map field.
  355. static void *startmap_handler(void *closure, const void *hd) {
  356. MessageHeader* msg = closure;
  357. const map_handlerdata_t* mapdata = hd;
  358. map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
  359. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  360. frame->handlerdata = mapdata;
  361. frame->map = map_rb;
  362. native_slot_init(mapdata->key_field_type, &frame->key_storage);
  363. native_slot_init(mapdata->value_field_type, &frame->value_storage);
  364. Map_set_frame(map_rb,
  365. TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
  366. return frame;
  367. }
  368. static bool endmap_handler(void *closure, const void *hd) {
  369. MessageHeader* msg = closure;
  370. const map_handlerdata_t* mapdata = hd;
  371. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  372. Map_set_frame(map_rb, Qnil);
  373. return true;
  374. }
  375. // Handler to end a map entry: inserts the value defined during the message into
  376. // the map. This is the 'endmsg' handler on the map entry msgdef.
  377. static bool endmapentry_handler(void* closure, const void* hd, upb_status* s) {
  378. map_parse_frame_t* frame = closure;
  379. const map_handlerdata_t* mapdata = hd;
  380. VALUE key = native_slot_get(
  381. mapdata->key_field_type, Qnil,
  382. &frame->key_storage);
  383. VALUE value = native_slot_get(
  384. mapdata->value_field_type, mapdata->subklass,
  385. &frame->value_storage);
  386. Map_index_set(frame->map, key, value);
  387. return true;
  388. }
  389. // Allocates a new map_handlerdata_t given the map entry message definition. If
  390. // the offset of the field within the parent message is also given, that is
  391. // added to the handler data as well. Note that this is called *twice* per map
  392. // field: once in the parent message handler setup when setting the startsubmsg
  393. // handler and once in the map entry message handler setup when setting the
  394. // key/value and endmsg handlers. The reason is that there is no easy way to
  395. // pass the handlerdata down to the sub-message handler setup.
  396. static map_handlerdata_t* new_map_handlerdata(
  397. size_t ofs,
  398. const upb_msgdef* mapentry_def,
  399. const Descriptor* desc) {
  400. const upb_fielddef* key_field;
  401. const upb_fielddef* value_field;
  402. map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
  403. hd->ofs = ofs;
  404. key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
  405. assert(key_field != NULL);
  406. hd->key_field_type = upb_fielddef_type(key_field);
  407. value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
  408. assert(value_field != NULL);
  409. hd->value_field_type = upb_fielddef_type(value_field);
  410. hd->subklass = field_type_class(desc->layout, value_field);
  411. return hd;
  412. }
  413. // Handlers that set primitive values in oneofs.
  414. #define DEFINE_ONEOF_HANDLER(type, ctype) \
  415. static bool oneof##type##_handler(void *closure, const void *hd, \
  416. ctype val) { \
  417. const oneof_handlerdata_t *oneofdata = hd; \
  418. DEREF(closure, oneofdata->case_ofs, uint32_t) = \
  419. oneofdata->oneof_case_num; \
  420. DEREF(closure, oneofdata->ofs, ctype) = val; \
  421. return true; \
  422. }
  423. DEFINE_ONEOF_HANDLER(bool, bool)
  424. DEFINE_ONEOF_HANDLER(int32, int32_t)
  425. DEFINE_ONEOF_HANDLER(uint32, uint32_t)
  426. DEFINE_ONEOF_HANDLER(float, float)
  427. DEFINE_ONEOF_HANDLER(int64, int64_t)
  428. DEFINE_ONEOF_HANDLER(uint64, uint64_t)
  429. DEFINE_ONEOF_HANDLER(double, double)
  430. #undef DEFINE_ONEOF_HANDLER
  431. // Handlers for strings in a oneof.
  432. static void *oneofstr_handler(void *closure,
  433. const void *hd,
  434. size_t size_hint) {
  435. MessageHeader* msg = closure;
  436. const oneof_handlerdata_t *oneofdata = hd;
  437. VALUE str = rb_str_new2("");
  438. rb_enc_associate(str, kRubyStringUtf8Encoding);
  439. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  440. oneofdata->oneof_case_num;
  441. DEREF(msg, oneofdata->ofs, VALUE) = str;
  442. return (void*)str;
  443. }
  444. static void *oneofbytes_handler(void *closure,
  445. const void *hd,
  446. size_t size_hint) {
  447. MessageHeader* msg = closure;
  448. const oneof_handlerdata_t *oneofdata = hd;
  449. VALUE str = rb_str_new2("");
  450. rb_enc_associate(str, kRubyString8bitEncoding);
  451. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  452. oneofdata->oneof_case_num;
  453. DEREF(msg, oneofdata->ofs, VALUE) = str;
  454. return (void*)str;
  455. }
  456. static bool oneofstring_end_handler(void* closure, const void* hd) {
  457. VALUE rb_str = rb_str_new2("");
  458. rb_obj_freeze(rb_str);
  459. return true;
  460. }
  461. // Handler for a submessage field in a oneof.
  462. static void *oneofsubmsg_handler(void *closure,
  463. const void *hd) {
  464. MessageHeader* msg = closure;
  465. const oneof_handlerdata_t *oneofdata = hd;
  466. uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
  467. VALUE submsg_rb;
  468. MessageHeader* submsg;
  469. if (oldcase != oneofdata->oneof_case_num ||
  470. DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
  471. DEREF(msg, oneofdata->ofs, VALUE) =
  472. rb_class_new_instance(0, NULL, oneofdata->subklass);
  473. }
  474. // Set the oneof case *after* allocating the new class instance -- otherwise,
  475. // if the Ruby GC is invoked as part of a call into the VM, it might invoke
  476. // our mark routines, and our mark routines might see the case value
  477. // indicating a VALUE is present and expect a valid VALUE. See comment in
  478. // layout_set() for more detail: basically, the change to the value and the
  479. // case must be atomic w.r.t. the Ruby VM.
  480. DEREF(msg, oneofdata->case_ofs, uint32_t) = oneofdata->oneof_case_num;
  481. submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
  482. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  483. return submsg;
  484. }
  485. static void* oneof_startwrapper(void* closure, const void* hd) {
  486. char* msg = closure;
  487. const oneof_handlerdata_t *oneofdata = hd;
  488. DEREF(msg, oneofdata->case_ofs, uint32_t) = oneofdata->oneof_case_num;
  489. return msg + oneofdata->ofs;
  490. }
  491. // Set up handlers for a repeated field.
  492. static void add_handlers_for_repeated_field(upb_handlers *h,
  493. const Descriptor* desc,
  494. const upb_fielddef *f,
  495. size_t offset) {
  496. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  497. attr.handler_data = newhandlerdata(h, offset, -1);
  498. upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  499. switch (upb_fielddef_type(f)) {
  500. #define SET_HANDLER(utype, ltype) \
  501. case utype: \
  502. upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
  503. break;
  504. SET_HANDLER(UPB_TYPE_BOOL, bool);
  505. SET_HANDLER(UPB_TYPE_INT32, int32);
  506. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  507. SET_HANDLER(UPB_TYPE_ENUM, int32);
  508. SET_HANDLER(UPB_TYPE_FLOAT, float);
  509. SET_HANDLER(UPB_TYPE_INT64, int64);
  510. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  511. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  512. #undef SET_HANDLER
  513. case UPB_TYPE_STRING:
  514. case UPB_TYPE_BYTES: {
  515. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  516. upb_handlers_setstartstr(h, f, is_bytes ?
  517. appendbytes_handler : appendstr_handler,
  518. NULL);
  519. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  520. upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
  521. break;
  522. }
  523. case UPB_TYPE_MESSAGE: {
  524. VALUE subklass = field_type_class(desc->layout, f);
  525. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  526. attr.handler_data = newsubmsghandlerdata(h, f, 0, -1, subklass);
  527. if (is_wrapper(upb_fielddef_msgsubdef(f))) {
  528. upb_handlers_setstartsubmsg(h, f, appendwrapper_handler, &attr);
  529. } else {
  530. upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
  531. }
  532. break;
  533. }
  534. }
  535. }
  536. static bool doublewrapper_handler(void* closure, const void* hd, double val) {
  537. VALUE* rbval = closure;
  538. *rbval = DBL2NUM(val);
  539. return true;
  540. }
  541. static bool floatwrapper_handler(void* closure, const void* hd, float val) {
  542. VALUE* rbval = closure;
  543. *rbval = DBL2NUM(val);
  544. return true;
  545. }
  546. static bool int64wrapper_handler(void* closure, const void* hd, int64_t val) {
  547. VALUE* rbval = closure;
  548. *rbval = LL2NUM(val);
  549. return true;
  550. }
  551. static bool uint64wrapper_handler(void* closure, const void* hd, uint64_t val) {
  552. VALUE* rbval = closure;
  553. *rbval = ULL2NUM(val);
  554. return true;
  555. }
  556. static bool int32wrapper_handler(void* closure, const void* hd, int32_t val) {
  557. VALUE* rbval = closure;
  558. *rbval = INT2NUM(val);
  559. return true;
  560. }
  561. static bool uint32wrapper_handler(void* closure, const void* hd, uint32_t val) {
  562. VALUE* rbval = closure;
  563. *rbval = UINT2NUM(val);
  564. return true;
  565. }
  566. static void* startstringwrapper_handler(void* closure, const void* hd,
  567. size_t size_hint) {
  568. VALUE* rbval = closure;
  569. (void)size_hint;
  570. *rbval = rb_str_new(NULL, 0);
  571. rb_enc_associate(*rbval, kRubyStringUtf8Encoding);
  572. return closure;
  573. }
  574. static size_t stringwrapper_handler(void* closure, const void* hd,
  575. const char* ptr, size_t len,
  576. const upb_bufhandle* handle) {
  577. VALUE* rbval = closure;
  578. *rbval = noleak_rb_str_cat(*rbval, ptr, len);
  579. return len;
  580. }
  581. static void* startbyteswrapper_handler(void* closure, const void* hd,
  582. size_t size_hint) {
  583. VALUE* rbval = closure;
  584. (void)size_hint;
  585. *rbval = rb_str_new(NULL, 0);
  586. rb_enc_associate(*rbval, kRubyString8bitEncoding);
  587. return closure;
  588. }
  589. static size_t byteswrapper_handler(void* closure, const void* hd,
  590. const char* ptr, size_t len,
  591. const upb_bufhandle* handle) {
  592. VALUE* rbval = closure;
  593. *rbval = noleak_rb_str_cat(*rbval, ptr, len);
  594. return len;
  595. }
  596. static bool boolwrapper_handler(void* closure, const void* hd, bool val) {
  597. VALUE* rbval = closure;
  598. if (val) {
  599. *rbval = Qtrue;
  600. } else {
  601. *rbval = Qfalse;
  602. }
  603. return true;
  604. }
  605. // Set up handlers for a singular field.
  606. static void add_handlers_for_singular_field(const Descriptor* desc,
  607. upb_handlers* h,
  608. const upb_fielddef* f,
  609. size_t offset, size_t hasbit_off) {
  610. // The offset we pass to UPB points to the start of the Message,
  611. // rather than the start of where our data is stored.
  612. int32_t hasbit = -1;
  613. if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
  614. hasbit = hasbit_off + sizeof(MessageHeader) * 8;
  615. }
  616. switch (upb_fielddef_type(f)) {
  617. case UPB_TYPE_BOOL:
  618. case UPB_TYPE_INT32:
  619. case UPB_TYPE_UINT32:
  620. case UPB_TYPE_ENUM:
  621. case UPB_TYPE_FLOAT:
  622. case UPB_TYPE_INT64:
  623. case UPB_TYPE_UINT64:
  624. case UPB_TYPE_DOUBLE:
  625. upb_msg_setscalarhandler(h, f, offset, hasbit);
  626. break;
  627. case UPB_TYPE_STRING:
  628. case UPB_TYPE_BYTES: {
  629. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  630. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  631. attr.handler_data = newhandlerdata(h, offset, hasbit);
  632. upb_handlers_setstartstr(h, f,
  633. is_bytes ? bytes_handler : str_handler,
  634. &attr);
  635. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  636. upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
  637. break;
  638. }
  639. case UPB_TYPE_MESSAGE: {
  640. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  641. attr.handler_data = newsubmsghandlerdata(
  642. h, f, offset, hasbit, field_type_class(desc->layout, f));
  643. if (is_wrapper(upb_fielddef_msgsubdef(f))) {
  644. upb_handlers_setstartsubmsg(h, f, startwrapper, &attr);
  645. } else {
  646. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  647. }
  648. }
  649. }
  650. }
  651. // Adds handlers to a map field.
  652. static void add_handlers_for_mapfield(upb_handlers* h,
  653. const upb_fielddef* fielddef,
  654. size_t offset,
  655. const Descriptor* desc) {
  656. const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
  657. map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
  658. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  659. upb_handlers_addcleanup(h, hd, xfree);
  660. attr.handler_data = hd;
  661. upb_handlers_setstartsubmsg(h, fielddef, startmap_handler, &attr);
  662. upb_handlers_setendsubmsg(h, fielddef, endmap_handler, &attr);
  663. }
  664. // Adds handlers to a map-entry msgdef.
  665. static void add_handlers_for_mapentry(const upb_msgdef* msgdef, upb_handlers* h,
  666. const Descriptor* desc) {
  667. const upb_fielddef* key_field = map_entry_key(msgdef);
  668. const upb_fielddef* value_field = map_entry_value(msgdef);
  669. map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
  670. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  671. upb_handlers_addcleanup(h, hd, xfree);
  672. attr.handler_data = hd;
  673. upb_handlers_setendmsg(h, endmapentry_handler, &attr);
  674. add_handlers_for_singular_field(
  675. desc, h, key_field,
  676. offsetof(map_parse_frame_t, key_storage),
  677. MESSAGE_FIELD_NO_HASBIT);
  678. add_handlers_for_singular_field(
  679. desc, h, value_field,
  680. offsetof(map_parse_frame_t, value_storage),
  681. MESSAGE_FIELD_NO_HASBIT);
  682. }
  683. static void add_handlers_for_wrapper(const upb_msgdef* msgdef,
  684. upb_handlers* h) {
  685. const upb_fielddef* f = upb_msgdef_itof(msgdef, 1);
  686. switch (upb_msgdef_wellknowntype(msgdef)) {
  687. case UPB_WELLKNOWN_DOUBLEVALUE:
  688. upb_handlers_setdouble(h, f, doublewrapper_handler, NULL);
  689. break;
  690. case UPB_WELLKNOWN_FLOATVALUE:
  691. upb_handlers_setfloat(h, f, floatwrapper_handler, NULL);
  692. break;
  693. case UPB_WELLKNOWN_INT64VALUE:
  694. upb_handlers_setint64(h, f, int64wrapper_handler, NULL);
  695. break;
  696. case UPB_WELLKNOWN_UINT64VALUE:
  697. upb_handlers_setuint64(h, f, uint64wrapper_handler, NULL);
  698. break;
  699. case UPB_WELLKNOWN_INT32VALUE:
  700. upb_handlers_setint32(h, f, int32wrapper_handler, NULL);
  701. break;
  702. case UPB_WELLKNOWN_UINT32VALUE:
  703. upb_handlers_setuint32(h, f, uint32wrapper_handler, NULL);
  704. break;
  705. case UPB_WELLKNOWN_STRINGVALUE:
  706. upb_handlers_setstartstr(h, f, startstringwrapper_handler, NULL);
  707. upb_handlers_setstring(h, f, stringwrapper_handler, NULL);
  708. break;
  709. case UPB_WELLKNOWN_BYTESVALUE:
  710. upb_handlers_setstartstr(h, f, startbyteswrapper_handler, NULL);
  711. upb_handlers_setstring(h, f, byteswrapper_handler, NULL);
  712. break;
  713. case UPB_WELLKNOWN_BOOLVALUE:
  714. upb_handlers_setbool(h, f, boolwrapper_handler, NULL);
  715. return;
  716. default:
  717. rb_raise(rb_eRuntimeError,
  718. "Internal logic error with well-known types.");
  719. }
  720. }
  721. // Set up handlers for a oneof field.
  722. static void add_handlers_for_oneof_field(upb_handlers *h,
  723. const upb_fielddef *f,
  724. size_t offset,
  725. size_t oneof_case_offset,
  726. const Descriptor* desc) {
  727. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  728. attr.handler_data =
  729. newoneofhandlerdata(h, offset, oneof_case_offset, f, desc);
  730. switch (upb_fielddef_type(f)) {
  731. #define SET_HANDLER(utype, ltype) \
  732. case utype: \
  733. upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
  734. break;
  735. SET_HANDLER(UPB_TYPE_BOOL, bool);
  736. SET_HANDLER(UPB_TYPE_INT32, int32);
  737. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  738. SET_HANDLER(UPB_TYPE_ENUM, int32);
  739. SET_HANDLER(UPB_TYPE_FLOAT, float);
  740. SET_HANDLER(UPB_TYPE_INT64, int64);
  741. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  742. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  743. #undef SET_HANDLER
  744. case UPB_TYPE_STRING:
  745. case UPB_TYPE_BYTES: {
  746. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  747. upb_handlers_setstartstr(h, f, is_bytes ?
  748. oneofbytes_handler : oneofstr_handler,
  749. &attr);
  750. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  751. upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
  752. break;
  753. }
  754. case UPB_TYPE_MESSAGE: {
  755. if (is_wrapper(upb_fielddef_msgsubdef(f))) {
  756. upb_handlers_setstartsubmsg(h, f, oneof_startwrapper, &attr);
  757. } else {
  758. upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
  759. }
  760. break;
  761. }
  762. }
  763. }
  764. static bool unknown_field_handler(void* closure, const void* hd,
  765. const char* buf, size_t size) {
  766. MessageHeader* msg = (MessageHeader*)closure;
  767. UPB_UNUSED(hd);
  768. if (msg->unknown_fields == NULL) {
  769. msg->unknown_fields = malloc(sizeof(stringsink));
  770. stringsink_init(msg->unknown_fields);
  771. }
  772. stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
  773. return true;
  774. }
  775. size_t get_field_offset(MessageLayout* layout, const upb_fielddef* f) {
  776. return layout->fields[upb_fielddef_index(f)].offset + sizeof(MessageHeader);
  777. }
  778. void add_handlers_for_message(const void *closure, upb_handlers *h) {
  779. const VALUE descriptor_pool = (VALUE)closure;
  780. const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  781. Descriptor* desc =
  782. ruby_to_Descriptor(get_msgdef_obj(descriptor_pool, msgdef));
  783. upb_msg_field_iter i;
  784. upb_handlerattr attr = UPB_HANDLERATTR_INIT;
  785. // Ensure layout exists. We may be invoked to create handlers for a given
  786. // message if we are included as a submsg of another message type before our
  787. // class is actually built, so to work around this, we just create the layout
  788. // (and handlers, in the class-building function) on-demand.
  789. if (desc->layout == NULL) {
  790. create_layout(desc);
  791. }
  792. // If this is a mapentry message type, set up a special set of handlers and
  793. // bail out of the normal (user-defined) message type handling.
  794. if (upb_msgdef_mapentry(msgdef)) {
  795. add_handlers_for_mapentry(msgdef, h, desc);
  796. return;
  797. }
  798. // If this is a wrapper type, use special handlers and bail.
  799. if (is_wrapper(msgdef)) {
  800. add_handlers_for_wrapper(msgdef, h);
  801. return;
  802. }
  803. upb_handlers_setunknown(h, unknown_field_handler, &attr);
  804. for (upb_msg_field_begin(&i, desc->msgdef);
  805. !upb_msg_field_done(&i);
  806. upb_msg_field_next(&i)) {
  807. const upb_fielddef *f = upb_msg_iter_field(&i);
  808. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  809. size_t offset = get_field_offset(desc->layout, f);
  810. if (oneof) {
  811. size_t oneof_case_offset =
  812. desc->layout->oneofs[upb_oneofdef_index(oneof)].case_offset +
  813. sizeof(MessageHeader);
  814. add_handlers_for_oneof_field(h, f, offset, oneof_case_offset, desc);
  815. } else if (is_map_field(f)) {
  816. add_handlers_for_mapfield(h, f, offset, desc);
  817. } else if (upb_fielddef_isseq(f)) {
  818. add_handlers_for_repeated_field(h, desc, f, offset);
  819. } else {
  820. add_handlers_for_singular_field(
  821. desc, h, f, offset,
  822. desc->layout->fields[upb_fielddef_index(f)].hasbit);
  823. }
  824. }
  825. }
  826. // Constructs the handlers for filling a message's data into an in-memory
  827. // object.
  828. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  829. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  830. return upb_handlercache_get(pool->fill_handler_cache, desc->msgdef);
  831. }
  832. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  833. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  834. return upb_pbcodecache_get(pool->fill_method_cache, desc->msgdef);
  835. }
  836. static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
  837. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  838. return upb_json_codecache_get(pool->json_fill_method_cache, desc->msgdef);
  839. }
  840. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  841. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  842. return upb_handlercache_get(pool->pb_serialize_handler_cache, desc->msgdef);
  843. }
  844. static const upb_handlers* msgdef_json_serialize_handlers(
  845. Descriptor* desc, bool preserve_proto_fieldnames) {
  846. DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
  847. if (preserve_proto_fieldnames) {
  848. return upb_handlercache_get(pool->json_serialize_handler_preserve_cache,
  849. desc->msgdef);
  850. } else {
  851. return upb_handlercache_get(pool->json_serialize_handler_cache,
  852. desc->msgdef);
  853. }
  854. }
  855. // Stack-allocated context during an encode/decode operation. Contains the upb
  856. // environment and its stack-based allocator, an initial buffer for allocations
  857. // to avoid malloc() when possible, and a template for Ruby exception messages
  858. // if any error occurs.
  859. #define STACK_ENV_STACKBYTES 4096
  860. typedef struct {
  861. upb_arena *arena;
  862. upb_status status;
  863. const char* ruby_error_template;
  864. char allocbuf[STACK_ENV_STACKBYTES];
  865. } stackenv;
  866. static void stackenv_init(stackenv* se, const char* errmsg);
  867. static void stackenv_uninit(stackenv* se);
  868. static void stackenv_init(stackenv* se, const char* errmsg) {
  869. se->ruby_error_template = errmsg;
  870. se->arena =
  871. upb_arena_init(se->allocbuf, sizeof(se->allocbuf), &upb_alloc_global);
  872. upb_status_clear(&se->status);
  873. }
  874. static void stackenv_uninit(stackenv* se) {
  875. upb_arena_free(se->arena);
  876. if (!upb_ok(&se->status)) {
  877. // TODO(haberman): have a way to verify that this is actually a parse error,
  878. // instead of just throwing "parse error" unconditionally.
  879. VALUE errmsg = rb_str_new2(upb_status_errmsg(&se->status));
  880. rb_raise(cParseError, se->ruby_error_template, errmsg);
  881. }
  882. }
  883. /*
  884. * call-seq:
  885. * MessageClass.decode(data) => message
  886. *
  887. * Decodes the given data (as a string containing bytes in protocol buffers wire
  888. * format) under the interpretration given by this message class's definition
  889. * and returns a message object with the corresponding field values.
  890. */
  891. VALUE Message_decode(VALUE klass, VALUE data) {
  892. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  893. Descriptor* desc = ruby_to_Descriptor(descriptor);
  894. VALUE msgklass = Descriptor_msgclass(descriptor);
  895. VALUE msg_rb;
  896. MessageHeader* msg;
  897. if (TYPE(data) != T_STRING) {
  898. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  899. }
  900. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  901. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  902. {
  903. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  904. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  905. const upb_msgdef* m = upb_handlers_msgdef(h);
  906. VALUE wrapper = Qnil;
  907. void* ptr = msg;
  908. stackenv se;
  909. upb_sink sink;
  910. upb_pbdecoder* decoder;
  911. stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
  912. if (is_wrapper(m)) {
  913. ptr = &wrapper;
  914. }
  915. upb_sink_reset(&sink, h, ptr);
  916. decoder = upb_pbdecoder_create(se.arena, method, sink, &se.status);
  917. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  918. upb_pbdecoder_input(decoder));
  919. stackenv_uninit(&se);
  920. if (is_wrapper(m)) {
  921. msg_rb = ruby_wrapper_type(msgklass, wrapper);
  922. }
  923. }
  924. return msg_rb;
  925. }
  926. /*
  927. * call-seq:
  928. * MessageClass.decode_json(data, options = {}) => message
  929. *
  930. * Decodes the given data (as a string containing bytes in protocol buffers wire
  931. * format) under the interpretration given by this message class's definition
  932. * and returns a message object with the corresponding field values.
  933. *
  934. * @param options [Hash] options for the decoder
  935. * ignore_unknown_fields: set true to ignore unknown fields (default is to
  936. * raise an error)
  937. */
  938. VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
  939. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  940. Descriptor* desc = ruby_to_Descriptor(descriptor);
  941. VALUE msgklass = Descriptor_msgclass(descriptor);
  942. VALUE msg_rb;
  943. VALUE data = argv[0];
  944. VALUE ignore_unknown_fields = Qfalse;
  945. MessageHeader* msg;
  946. if (argc < 1 || argc > 2) {
  947. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  948. }
  949. if (argc == 2) {
  950. VALUE hash_args = argv[1];
  951. if (TYPE(hash_args) != T_HASH) {
  952. rb_raise(rb_eArgError, "Expected hash arguments.");
  953. }
  954. ignore_unknown_fields = rb_hash_lookup2(
  955. hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse);
  956. }
  957. if (TYPE(data) != T_STRING) {
  958. rb_raise(rb_eArgError, "Expected string for JSON data.");
  959. }
  960. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  961. // convert, because string handlers pass data directly to message string
  962. // fields.
  963. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  964. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  965. {
  966. const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
  967. const upb_handlers* h = get_fill_handlers(desc);
  968. const upb_msgdef* m = upb_handlers_msgdef(h);
  969. stackenv se;
  970. upb_sink sink;
  971. upb_json_parser* parser;
  972. DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
  973. stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
  974. if (is_wrapper(m)) {
  975. rb_raise(
  976. rb_eRuntimeError,
  977. "Parsing a wrapper type from JSON at the top level does not work.");
  978. }
  979. upb_sink_reset(&sink, h, msg);
  980. parser = upb_json_parser_create(se.arena, method, pool->symtab, sink,
  981. &se.status, RTEST(ignore_unknown_fields));
  982. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  983. upb_json_parser_input(parser));
  984. stackenv_uninit(&se);
  985. }
  986. return msg_rb;
  987. }
  988. // -----------------------------------------------------------------------------
  989. // Serializing.
  990. // -----------------------------------------------------------------------------
  991. /* msgvisitor *****************************************************************/
  992. static void putmsg(VALUE msg, const Descriptor* desc, upb_sink sink, int depth,
  993. bool emit_defaults, bool is_json, bool open_msg);
  994. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  995. upb_selector_t ret;
  996. bool ok = upb_handlers_getselector(f, type, &ret);
  997. UPB_ASSERT(ok);
  998. return ret;
  999. }
  1000. static void putstr(VALUE str, const upb_fielddef *f, upb_sink sink) {
  1001. upb_sink subsink;
  1002. if (str == Qnil) return;
  1003. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  1004. // We should be guaranteed that the string has the correct encoding because
  1005. // we ensured this at assignment time and then froze the string.
  1006. if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
  1007. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
  1008. } else {
  1009. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
  1010. }
  1011. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  1012. &subsink);
  1013. upb_sink_putstring(subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  1014. RSTRING_LEN(str), NULL);
  1015. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  1016. }
  1017. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink sink,
  1018. int depth, bool emit_defaults, bool is_json) {
  1019. upb_sink subsink;
  1020. VALUE descriptor;
  1021. Descriptor* subdesc;
  1022. if (submsg == Qnil) return;
  1023. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1024. subdesc = ruby_to_Descriptor(descriptor);
  1025. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  1026. putmsg(submsg, subdesc, subsink, depth + 1, emit_defaults, is_json, true);
  1027. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  1028. }
  1029. static void putary(VALUE ary, const upb_fielddef* f, upb_sink sink, int depth,
  1030. bool emit_defaults, bool is_json) {
  1031. upb_sink subsink;
  1032. upb_fieldtype_t type = upb_fielddef_type(f);
  1033. upb_selector_t sel = 0;
  1034. int size;
  1035. int i;
  1036. VALUE type_class = ruby_to_RepeatedField(ary)->field_type_class;
  1037. if (ary == Qnil) return;
  1038. if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
  1039. size = NUM2INT(RepeatedField_length(ary));
  1040. if (size == 0 && !emit_defaults) return;
  1041. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1042. if (upb_fielddef_isprimitive(f)) {
  1043. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  1044. }
  1045. for (i = 0; i < size; i++) {
  1046. void* memory = RepeatedField_index_native(ary, i);
  1047. switch (type) {
  1048. #define T(upbtypeconst, upbtype, ctype) \
  1049. case upbtypeconst: \
  1050. upb_sink_put##upbtype(subsink, sel, *((ctype*)memory)); \
  1051. break;
  1052. T(UPB_TYPE_FLOAT, float, float)
  1053. T(UPB_TYPE_DOUBLE, double, double)
  1054. T(UPB_TYPE_BOOL, bool, int8_t)
  1055. case UPB_TYPE_ENUM:
  1056. T(UPB_TYPE_INT32, int32, int32_t)
  1057. T(UPB_TYPE_UINT32, uint32, uint32_t)
  1058. T(UPB_TYPE_INT64, int64, int64_t)
  1059. T(UPB_TYPE_UINT64, uint64, uint64_t)
  1060. case UPB_TYPE_STRING:
  1061. case UPB_TYPE_BYTES:
  1062. putstr(*((VALUE *)memory), f, subsink);
  1063. break;
  1064. case UPB_TYPE_MESSAGE: {
  1065. VALUE val = native_slot_get(UPB_TYPE_MESSAGE, type_class, memory);
  1066. putsubmsg(val, f, subsink, depth, emit_defaults, is_json);
  1067. break;
  1068. }
  1069. #undef T
  1070. }
  1071. }
  1072. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1073. }
  1074. static void put_ruby_value(VALUE value, const upb_fielddef* f, VALUE type_class,
  1075. int depth, upb_sink sink, bool emit_defaults,
  1076. bool is_json) {
  1077. upb_selector_t sel = 0;
  1078. if (depth > ENCODE_MAX_NESTING) {
  1079. rb_raise(rb_eRuntimeError,
  1080. "Maximum recursion depth exceeded during encoding.");
  1081. }
  1082. if (upb_fielddef_isprimitive(f)) {
  1083. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  1084. }
  1085. switch (upb_fielddef_type(f)) {
  1086. case UPB_TYPE_INT32:
  1087. upb_sink_putint32(sink, sel, NUM2INT(value));
  1088. break;
  1089. case UPB_TYPE_INT64:
  1090. upb_sink_putint64(sink, sel, NUM2LL(value));
  1091. break;
  1092. case UPB_TYPE_UINT32:
  1093. upb_sink_putuint32(sink, sel, NUM2UINT(value));
  1094. break;
  1095. case UPB_TYPE_UINT64:
  1096. upb_sink_putuint64(sink, sel, NUM2ULL(value));
  1097. break;
  1098. case UPB_TYPE_FLOAT:
  1099. upb_sink_putfloat(sink, sel, NUM2DBL(value));
  1100. break;
  1101. case UPB_TYPE_DOUBLE:
  1102. upb_sink_putdouble(sink, sel, NUM2DBL(value));
  1103. break;
  1104. case UPB_TYPE_ENUM: {
  1105. if (TYPE(value) == T_SYMBOL) {
  1106. value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  1107. }
  1108. upb_sink_putint32(sink, sel, NUM2INT(value));
  1109. break;
  1110. }
  1111. case UPB_TYPE_BOOL:
  1112. upb_sink_putbool(sink, sel, value == Qtrue);
  1113. break;
  1114. case UPB_TYPE_STRING:
  1115. case UPB_TYPE_BYTES:
  1116. putstr(value, f, sink);
  1117. break;
  1118. case UPB_TYPE_MESSAGE:
  1119. putsubmsg(value, f, sink, depth, emit_defaults, is_json);
  1120. }
  1121. }
  1122. static void putmap(VALUE map, const upb_fielddef* f, upb_sink sink, int depth,
  1123. bool emit_defaults, bool is_json) {
  1124. Map* self;
  1125. upb_sink subsink;
  1126. const upb_fielddef* key_field;
  1127. const upb_fielddef* value_field;
  1128. Map_iter it;
  1129. if (map == Qnil) return;
  1130. if (!emit_defaults && Map_length(map) == 0) return;
  1131. self = ruby_to_Map(map);
  1132. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1133. assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  1134. key_field = map_field_key(f);
  1135. value_field = map_field_value(f);
  1136. for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
  1137. VALUE key = Map_iter_key(&it);
  1138. VALUE value = Map_iter_value(&it);
  1139. upb_status status;
  1140. upb_sink entry_sink;
  1141. upb_sink_startsubmsg(subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
  1142. &entry_sink);
  1143. upb_sink_startmsg(entry_sink);
  1144. put_ruby_value(key, key_field, Qnil, depth + 1, entry_sink, emit_defaults,
  1145. is_json);
  1146. put_ruby_value(value, value_field, self->value_type_class, depth + 1,
  1147. entry_sink, emit_defaults, is_json);
  1148. upb_sink_endmsg(entry_sink, &status);
  1149. upb_sink_endsubmsg(subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  1150. }
  1151. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1152. }
  1153. static const upb_handlers* msgdef_json_serialize_handlers(
  1154. Descriptor* desc, bool preserve_proto_fieldnames);
  1155. static void putjsonany(VALUE msg_rb, const Descriptor* desc, upb_sink sink,
  1156. int depth, bool emit_defaults) {
  1157. upb_status status;
  1158. MessageHeader* msg = NULL;
  1159. const upb_fielddef* type_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_TYPE);
  1160. const upb_fielddef* value_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_VALUE);
  1161. size_t type_url_offset;
  1162. VALUE type_url_str_rb;
  1163. const upb_msgdef *payload_type = NULL;
  1164. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1165. upb_sink_startmsg(sink);
  1166. /* Handle type url */
  1167. type_url_offset = desc->layout->fields[upb_fielddef_index(type_field)].offset;
  1168. type_url_str_rb = DEREF(Message_data(msg), type_url_offset, VALUE);
  1169. if (RSTRING_LEN(type_url_str_rb) > 0) {
  1170. putstr(type_url_str_rb, type_field, sink);
  1171. }
  1172. {
  1173. const char* type_url_str = RSTRING_PTR(type_url_str_rb);
  1174. size_t type_url_len = RSTRING_LEN(type_url_str_rb);
  1175. DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
  1176. if (type_url_len <= 20 ||
  1177. strncmp(type_url_str, "type.googleapis.com/", 20) != 0) {
  1178. rb_raise(rb_eRuntimeError, "Invalid type url: %s", type_url_str);
  1179. return;
  1180. }
  1181. /* Resolve type url */
  1182. type_url_str += 20;
  1183. type_url_len -= 20;
  1184. payload_type = upb_symtab_lookupmsg2(
  1185. pool->symtab, type_url_str, type_url_len);
  1186. if (payload_type == NULL) {
  1187. rb_raise(rb_eRuntimeError, "Unknown type: %s", type_url_str);
  1188. return;
  1189. }
  1190. }
  1191. {
  1192. uint32_t value_offset;
  1193. VALUE value_str_rb;
  1194. size_t value_len;
  1195. value_offset = desc->layout->fields[upb_fielddef_index(value_field)].offset;
  1196. value_str_rb = DEREF(Message_data(msg), value_offset, VALUE);
  1197. value_len = RSTRING_LEN(value_str_rb);
  1198. if (value_len > 0) {
  1199. VALUE payload_desc_rb = get_msgdef_obj(generated_pool, payload_type);
  1200. Descriptor* payload_desc = ruby_to_Descriptor(payload_desc_rb);
  1201. VALUE payload_class = Descriptor_msgclass(payload_desc_rb);
  1202. upb_sink subsink;
  1203. bool is_wellknown;
  1204. VALUE payload_msg_rb = Message_decode(payload_class, value_str_rb);
  1205. is_wellknown =
  1206. upb_msgdef_wellknowntype(payload_desc->msgdef) !=
  1207. UPB_WELLKNOWN_UNSPECIFIED;
  1208. if (is_wellknown) {
  1209. upb_sink_startstr(sink, getsel(value_field, UPB_HANDLER_STARTSTR), 0,
  1210. &subsink);
  1211. }
  1212. subsink.handlers =
  1213. msgdef_json_serialize_handlers(payload_desc, true);
  1214. subsink.closure = sink.closure;
  1215. putmsg(payload_msg_rb, payload_desc, subsink, depth, emit_defaults, true,
  1216. is_wellknown);
  1217. }
  1218. }
  1219. upb_sink_endmsg(sink, &status);
  1220. }
  1221. static void putjsonlistvalue(
  1222. VALUE msg_rb, const Descriptor* desc,
  1223. upb_sink sink, int depth, bool emit_defaults) {
  1224. upb_status status;
  1225. upb_sink subsink;
  1226. MessageHeader* msg = NULL;
  1227. const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
  1228. uint32_t offset =
  1229. desc->layout->fields[upb_fielddef_index(f)].offset +
  1230. sizeof(MessageHeader);
  1231. VALUE ary;
  1232. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1233. upb_sink_startmsg(sink);
  1234. ary = DEREF(msg, offset, VALUE);
  1235. if (ary == Qnil || RepeatedField_size(ary) == 0) {
  1236. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  1237. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  1238. } else {
  1239. putary(ary, f, sink, depth, emit_defaults, true);
  1240. }
  1241. upb_sink_endmsg(sink, &status);
  1242. }
  1243. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  1244. upb_sink sink, int depth, bool emit_defaults,
  1245. bool is_json, bool open_msg) {
  1246. MessageHeader* msg;
  1247. upb_msg_field_iter i;
  1248. upb_status status;
  1249. bool json_wrapper = is_wrapper(desc->msgdef) && is_json;
  1250. if (is_json &&
  1251. upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
  1252. putjsonany(msg_rb, desc, sink, depth, emit_defaults);
  1253. return;
  1254. }
  1255. if (is_json &&
  1256. upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_LISTVALUE) {
  1257. putjsonlistvalue(msg_rb, desc, sink, depth, emit_defaults);
  1258. return;
  1259. }
  1260. if (open_msg) {
  1261. upb_sink_startmsg(sink);
  1262. }
  1263. // Protect against cycles (possible because users may freely reassign message
  1264. // and repeated fields) by imposing a maximum recursion depth.
  1265. if (depth > ENCODE_MAX_NESTING) {
  1266. rb_raise(rb_eRuntimeError,
  1267. "Maximum recursion depth exceeded during encoding.");
  1268. }
  1269. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1270. if (desc != msg->descriptor) {
  1271. rb_raise(rb_eArgError,
  1272. "The type of given msg is '%s', expect '%s'.",
  1273. upb_msgdef_fullname(msg->descriptor->msgdef),
  1274. upb_msgdef_fullname(desc->msgdef));
  1275. }
  1276. for (upb_msg_field_begin(&i, desc->msgdef);
  1277. !upb_msg_field_done(&i);
  1278. upb_msg_field_next(&i)) {
  1279. upb_fielddef *f = upb_msg_iter_field(&i);
  1280. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  1281. bool is_matching_oneof = false;
  1282. uint32_t offset =
  1283. desc->layout->fields[upb_fielddef_index(f)].offset +
  1284. sizeof(MessageHeader);
  1285. if (oneof) {
  1286. uint32_t oneof_case =
  1287. slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
  1288. // For a oneof, check that this field is actually present -- skip all the
  1289. // below if not.
  1290. if (oneof_case != upb_fielddef_number(f)) {
  1291. continue;
  1292. }
  1293. // Otherwise, fall through to the appropriate singular-field handler
  1294. // below.
  1295. is_matching_oneof = true;
  1296. }
  1297. if (is_map_field(f)) {
  1298. VALUE map = DEREF(msg, offset, VALUE);
  1299. if (map != Qnil || emit_defaults) {
  1300. putmap(map, f, sink, depth, emit_defaults, is_json);
  1301. }
  1302. } else if (upb_fielddef_isseq(f)) {
  1303. VALUE ary = DEREF(msg, offset, VALUE);
  1304. if (ary != Qnil) {
  1305. putary(ary, f, sink, depth, emit_defaults, is_json);
  1306. }
  1307. } else if (upb_fielddef_isstring(f)) {
  1308. VALUE str = DEREF(msg, offset, VALUE);
  1309. bool is_default = false;
  1310. if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
  1311. is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
  1312. } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
  1313. is_default = RSTRING_LEN(str) == 0;
  1314. }
  1315. if (is_matching_oneof || emit_defaults || !is_default || json_wrapper) {
  1316. putstr(str, f, sink);
  1317. }
  1318. } else if (upb_fielddef_issubmsg(f)) {
  1319. // OPT: could try to avoid the layout_get() (which will expand lazy
  1320. // wrappers).
  1321. VALUE val = layout_get(desc->layout, Message_data(msg), f);
  1322. putsubmsg(val, f, sink, depth, emit_defaults, is_json);
  1323. } else {
  1324. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  1325. #define T(upbtypeconst, upbtype, ctype, default_value) \
  1326. case upbtypeconst: { \
  1327. ctype value = DEREF(msg, offset, ctype); \
  1328. bool is_default = false; \
  1329. if (upb_fielddef_haspresence(f)) { \
  1330. is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse; \
  1331. } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) { \
  1332. is_default = default_value == value; \
  1333. } \
  1334. if (is_matching_oneof || emit_defaults || !is_default || json_wrapper) { \
  1335. upb_sink_put##upbtype(sink, sel, value); \
  1336. } \
  1337. } break;
  1338. switch (upb_fielddef_type(f)) {
  1339. T(UPB_TYPE_FLOAT, float, float, 0.0)
  1340. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  1341. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  1342. case UPB_TYPE_ENUM:
  1343. T(UPB_TYPE_INT32, int32, int32_t, 0)
  1344. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  1345. T(UPB_TYPE_INT64, int64, int64_t, 0)
  1346. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  1347. case UPB_TYPE_STRING:
  1348. case UPB_TYPE_BYTES:
  1349. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  1350. }
  1351. #undef T
  1352. }
  1353. }
  1354. {
  1355. stringsink* unknown = msg->unknown_fields;
  1356. if (unknown != NULL) {
  1357. upb_sink_putunknown(sink, unknown->ptr, unknown->len);
  1358. }
  1359. }
  1360. if (open_msg) {
  1361. upb_sink_endmsg(sink, &status);
  1362. }
  1363. }
  1364. /*
  1365. * call-seq:
  1366. * MessageClass.encode(msg) => bytes
  1367. *
  1368. * Encodes the given message object to its serialized form in protocol buffers
  1369. * wire format.
  1370. */
  1371. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  1372. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1373. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1374. stringsink sink;
  1375. stringsink_init(&sink);
  1376. {
  1377. const upb_handlers* serialize_handlers =
  1378. msgdef_pb_serialize_handlers(desc);
  1379. stackenv se;
  1380. upb_pb_encoder* encoder;
  1381. VALUE ret;
  1382. stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
  1383. encoder = upb_pb_encoder_create(se.arena, serialize_handlers, sink.sink);
  1384. putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false, false, true);
  1385. ret = rb_str_new(sink.ptr, sink.len);
  1386. stackenv_uninit(&se);
  1387. stringsink_uninit(&sink);
  1388. return ret;
  1389. }
  1390. }
  1391. /*
  1392. * call-seq:
  1393. * MessageClass.encode_json(msg, options = {}) => json_string
  1394. *
  1395. * Encodes the given message object into its serialized JSON representation.
  1396. * @param options [Hash] options for the decoder
  1397. * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
  1398. * emit_defaults: set true to emit 0/false values (default is to omit them)
  1399. */
  1400. VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
  1401. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1402. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1403. VALUE msg_rb;
  1404. VALUE preserve_proto_fieldnames = Qfalse;
  1405. VALUE emit_defaults = Qfalse;
  1406. stringsink sink;
  1407. if (argc < 1 || argc > 2) {
  1408. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  1409. }
  1410. msg_rb = argv[0];
  1411. if (argc == 2) {
  1412. VALUE hash_args = argv[1];
  1413. if (TYPE(hash_args) != T_HASH) {
  1414. rb_raise(rb_eArgError, "Expected hash arguments.");
  1415. }
  1416. preserve_proto_fieldnames = rb_hash_lookup2(
  1417. hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
  1418. emit_defaults = rb_hash_lookup2(
  1419. hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
  1420. }
  1421. stringsink_init(&sink);
  1422. {
  1423. const upb_handlers* serialize_handlers =
  1424. msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
  1425. upb_json_printer* printer;
  1426. stackenv se;
  1427. VALUE ret;
  1428. stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
  1429. printer = upb_json_printer_create(se.arena, serialize_handlers, sink.sink);
  1430. putmsg(msg_rb, desc, upb_json_printer_input(printer), 0,
  1431. RTEST(emit_defaults), true, true);
  1432. ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
  1433. stackenv_uninit(&se);
  1434. stringsink_uninit(&sink);
  1435. return ret;
  1436. }
  1437. }
  1438. static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
  1439. MessageHeader* msg;
  1440. upb_msg_field_iter it;
  1441. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  1442. {
  1443. stringsink* unknown = msg->unknown_fields;
  1444. if (unknown != NULL) {
  1445. stringsink_uninit(unknown);
  1446. msg->unknown_fields = NULL;
  1447. }
  1448. }
  1449. for (upb_msg_field_begin(&it, desc->msgdef);
  1450. !upb_msg_field_done(&it);
  1451. upb_msg_field_next(&it)) {
  1452. upb_fielddef *f = upb_msg_iter_field(&it);
  1453. const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
  1454. uint32_t offset =
  1455. desc->layout->fields[upb_fielddef_index(f)].offset +
  1456. sizeof(MessageHeader);
  1457. if (oneof) {
  1458. uint32_t oneof_case =
  1459. slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
  1460. // For a oneof, check that this field is actually present -- skip all the
  1461. // below if not.
  1462. if (oneof_case != upb_fielddef_number(f)) {
  1463. continue;
  1464. }
  1465. // Otherwise, fall through to the appropriate singular-field handler
  1466. // below.
  1467. }
  1468. if (!upb_fielddef_issubmsg(f)) {
  1469. continue;
  1470. }
  1471. if (is_map_field(f)) {
  1472. VALUE map;
  1473. Map_iter map_it;
  1474. if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
  1475. map = DEREF(msg, offset, VALUE);
  1476. if (map == Qnil) continue;
  1477. for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
  1478. VALUE submsg = Map_iter_value(&map_it);
  1479. VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1480. const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  1481. discard_unknown(submsg, subdesc);
  1482. }
  1483. } else if (upb_fielddef_isseq(f)) {
  1484. VALUE ary = DEREF(msg, offset, VALUE);
  1485. int size;
  1486. int i;
  1487. if (ary == Qnil) continue;
  1488. size = NUM2INT(RepeatedField_length(ary));
  1489. for (i = 0; i < size; i++) {
  1490. void* memory = RepeatedField_index_native(ary, i);
  1491. VALUE submsg = *((VALUE *)memory);
  1492. VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1493. const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
  1494. discard_unknown(submsg, subdesc);
  1495. }
  1496. } else {
  1497. VALUE submsg = DEREF(msg, offset, VALUE);
  1498. VALUE descriptor;
  1499. const Descriptor* subdesc;
  1500. if (submsg == Qnil) continue;
  1501. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  1502. subdesc = ruby_to_Descriptor(descriptor);
  1503. discard_unknown(submsg, subdesc);
  1504. }
  1505. }
  1506. }
  1507. /*
  1508. * call-seq:
  1509. * Google::Protobuf.discard_unknown(msg)
  1510. *
  1511. * Discard unknown fields in the given message object and recursively discard
  1512. * unknown fields in submessages.
  1513. */
  1514. VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
  1515. VALUE klass = CLASS_OF(msg_rb);
  1516. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1517. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1518. if (klass == cRepeatedField || klass == cMap) {
  1519. rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
  1520. } else {
  1521. discard_unknown(msg_rb, desc);
  1522. }
  1523. return Qnil;
  1524. }