message.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. // Class/module creation from msgdefs and enumdefs, respectively.
  33. // -----------------------------------------------------------------------------
  34. void* Message_data(void* msg) {
  35. return ((uint8_t *)msg) + sizeof(MessageHeader);
  36. }
  37. void Message_mark(void* _self) {
  38. MessageHeader* self = (MessageHeader *)_self;
  39. layout_mark(self->descriptor->layout, Message_data(self));
  40. }
  41. void Message_free(void* self) {
  42. stringsink* unknown = ((MessageHeader *)self)->unknown_fields;
  43. if (unknown != NULL) {
  44. stringsink_uninit(unknown);
  45. free(unknown);
  46. }
  47. xfree(self);
  48. }
  49. rb_data_type_t Message_type = {
  50. "Message",
  51. { Message_mark, Message_free, NULL },
  52. };
  53. VALUE Message_alloc(VALUE klass) {
  54. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  55. Descriptor* desc = ruby_to_Descriptor(descriptor);
  56. MessageHeader* msg;
  57. VALUE ret;
  58. if (desc->layout == NULL) {
  59. create_layout(desc);
  60. }
  61. msg = (void*)ALLOC_N(uint8_t, sizeof(MessageHeader) + desc->layout->size);
  62. msg->descriptor = desc;
  63. msg->unknown_fields = NULL;
  64. memcpy(Message_data(msg), desc->layout->empty_template, desc->layout->size);
  65. ret = TypedData_Wrap_Struct(klass, &Message_type, msg);
  66. rb_ivar_set(ret, descriptor_instancevar_interned, descriptor);
  67. return ret;
  68. }
  69. static const upb_fielddef* which_oneof_field(MessageHeader* self, const upb_oneofdef* o) {
  70. uint32_t oneof_case;
  71. const upb_fielddef* f;
  72. oneof_case =
  73. slot_read_oneof_case(self->descriptor->layout, Message_data(self), o);
  74. if (oneof_case == ONEOF_CASE_NONE) {
  75. return NULL;
  76. }
  77. // oneof_case is a field index, so find that field.
  78. f = upb_oneofdef_itof(o, oneof_case);
  79. assert(f != NULL);
  80. return f;
  81. }
  82. enum {
  83. METHOD_UNKNOWN = 0,
  84. METHOD_GETTER = 1,
  85. METHOD_SETTER = 2,
  86. METHOD_CLEAR = 3,
  87. METHOD_PRESENCE = 4,
  88. METHOD_ENUM_GETTER = 5,
  89. METHOD_WRAPPER_GETTER = 6,
  90. METHOD_WRAPPER_SETTER = 7
  91. };
  92. // Check if the field is a well known wrapper type
  93. bool is_wrapper_type_field(const upb_fielddef* field) {
  94. const upb_msgdef *m;
  95. if (upb_fielddef_type(field) != UPB_TYPE_MESSAGE) {
  96. return false;
  97. }
  98. m = upb_fielddef_msgsubdef(field);
  99. switch (upb_msgdef_wellknowntype(m)) {
  100. case UPB_WELLKNOWN_DOUBLEVALUE:
  101. case UPB_WELLKNOWN_FLOATVALUE:
  102. case UPB_WELLKNOWN_INT64VALUE:
  103. case UPB_WELLKNOWN_UINT64VALUE:
  104. case UPB_WELLKNOWN_INT32VALUE:
  105. case UPB_WELLKNOWN_UINT32VALUE:
  106. case UPB_WELLKNOWN_STRINGVALUE:
  107. case UPB_WELLKNOWN_BYTESVALUE:
  108. case UPB_WELLKNOWN_BOOLVALUE:
  109. return true;
  110. default:
  111. return false;
  112. }
  113. }
  114. // Get a new Ruby wrapper type and set the initial value
  115. VALUE ruby_wrapper_type(VALUE type_class, VALUE value) {
  116. if (value != Qnil) {
  117. VALUE hash = rb_hash_new();
  118. rb_hash_aset(hash, rb_str_new2("value"), value);
  119. {
  120. VALUE args[1] = {hash};
  121. return rb_class_new_instance(1, args, type_class);
  122. }
  123. }
  124. return Qnil;
  125. }
  126. static int extract_method_call(VALUE method_name, MessageHeader* self,
  127. const upb_fielddef **f, const upb_oneofdef **o) {
  128. VALUE method_str;
  129. char* name;
  130. size_t name_len;
  131. int accessor_type;
  132. const upb_oneofdef* test_o;
  133. const upb_fielddef* test_f;
  134. bool has_field;
  135. Check_Type(method_name, T_SYMBOL);
  136. method_str = rb_id2str(SYM2ID(method_name));
  137. name = RSTRING_PTR(method_str);
  138. name_len = RSTRING_LEN(method_str);
  139. if (name[name_len - 1] == '=') {
  140. accessor_type = METHOD_SETTER;
  141. name_len--;
  142. // We want to ensure if the proto has something named clear_foo or has_foo?,
  143. // we don't strip the prefix.
  144. } else if (strncmp("clear_", name, 6) == 0 &&
  145. !upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len,
  146. &test_f, &test_o)) {
  147. accessor_type = METHOD_CLEAR;
  148. name = name + 6;
  149. name_len = name_len - 6;
  150. } else if (strncmp("has_", name, 4) == 0 && name[name_len - 1] == '?' &&
  151. !upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len,
  152. &test_f, &test_o)) {
  153. accessor_type = METHOD_PRESENCE;
  154. name = name + 4;
  155. name_len = name_len - 5;
  156. } else {
  157. accessor_type = METHOD_GETTER;
  158. }
  159. has_field = upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len,
  160. &test_f, &test_o);
  161. // Look for wrapper type accessor of the form <field_name>_as_value
  162. if (!has_field &&
  163. (accessor_type == METHOD_GETTER || accessor_type == METHOD_SETTER) &&
  164. name_len > 9 && strncmp(name + name_len - 9, "_as_value", 9) == 0) {
  165. const upb_oneofdef* test_o_wrapper;
  166. const upb_fielddef* test_f_wrapper;
  167. char wrapper_field_name[name_len - 8];
  168. // Find the field name
  169. strncpy(wrapper_field_name, name, name_len - 9);
  170. wrapper_field_name[name_len - 9] = '\0';
  171. // Check if field exists and is a wrapper type
  172. if (upb_msgdef_lookupname(self->descriptor->msgdef, wrapper_field_name,
  173. name_len - 9, &test_f_wrapper, &test_o_wrapper) &&
  174. is_wrapper_type_field(test_f_wrapper)) {
  175. // It does exist!
  176. has_field = true;
  177. if (accessor_type == METHOD_SETTER) {
  178. accessor_type = METHOD_WRAPPER_SETTER;
  179. } else {
  180. accessor_type = METHOD_WRAPPER_GETTER;
  181. }
  182. test_o = test_o_wrapper;
  183. test_f = test_f_wrapper;
  184. }
  185. }
  186. // Look for enum accessor of the form <enum_name>_const
  187. if (!has_field && accessor_type == METHOD_GETTER &&
  188. name_len > 6 && strncmp(name + name_len - 6, "_const", 6) == 0) {
  189. const upb_oneofdef* test_o_enum;
  190. const upb_fielddef* test_f_enum;
  191. char enum_name[name_len - 5];
  192. // Find enum field name
  193. strncpy(enum_name, name, name_len - 6);
  194. enum_name[name_len - 6] = '\0';
  195. // Check if enum field exists
  196. if (upb_msgdef_lookupname(self->descriptor->msgdef, enum_name, name_len - 6,
  197. &test_f_enum, &test_o_enum) &&
  198. upb_fielddef_type(test_f_enum) == UPB_TYPE_ENUM) {
  199. // It does exist!
  200. has_field = true;
  201. accessor_type = METHOD_ENUM_GETTER;
  202. test_o = test_o_enum;
  203. test_f = test_f_enum;
  204. }
  205. }
  206. // Verify the name corresponds to a oneof or field in this message.
  207. if (!has_field) {
  208. return METHOD_UNKNOWN;
  209. }
  210. // Method calls like 'has_foo?' are not allowed if field "foo" does not have
  211. // a hasbit (e.g. repeated fields or non-message type fields for proto3
  212. // syntax).
  213. if (accessor_type == METHOD_PRESENCE && test_f != NULL) {
  214. if (!upb_fielddef_haspresence(test_f)) return METHOD_UNKNOWN;
  215. // TODO(haberman): remove this case, allow for proto3 oneofs.
  216. if (upb_fielddef_realcontainingoneof(test_f) &&
  217. upb_filedef_syntax(upb_fielddef_file(test_f)) == UPB_SYNTAX_PROTO3) {
  218. return METHOD_UNKNOWN;
  219. }
  220. }
  221. *o = test_o;
  222. *f = test_f;
  223. return accessor_type;
  224. }
  225. /*
  226. * call-seq:
  227. * Message.method_missing(*args)
  228. *
  229. * Provides accessors and setters and methods to clear and check for presence of
  230. * message fields according to their field names.
  231. *
  232. * For any field whose name does not conflict with a built-in method, an
  233. * accessor is provided with the same name as the field, and a setter is
  234. * provided with the name of the field plus the '=' suffix. Thus, given a
  235. * message instance 'msg' with field 'foo', the following code is valid:
  236. *
  237. * msg.foo = 42
  238. * puts msg.foo
  239. *
  240. * This method also provides read-only accessors for oneofs. If a oneof exists
  241. * with name 'my_oneof', then msg.my_oneof will return a Ruby symbol equal to
  242. * the name of the field in that oneof that is currently set, or nil if none.
  243. *
  244. * It also provides methods of the form 'clear_fieldname' to clear the value
  245. * of the field 'fieldname'. For basic data types, this will set the default
  246. * value of the field.
  247. *
  248. * Additionally, it provides methods of the form 'has_fieldname?', which returns
  249. * true if the field 'fieldname' is set in the message object, else false. For
  250. * 'proto3' syntax, calling this for a basic type field will result in an error.
  251. */
  252. VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self) {
  253. MessageHeader* self;
  254. const upb_oneofdef* o;
  255. const upb_fielddef* f;
  256. int accessor_type;
  257. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  258. if (argc < 1) {
  259. rb_raise(rb_eArgError, "Expected method name as first argument.");
  260. }
  261. accessor_type = extract_method_call(argv[0], self, &f, &o);
  262. if (accessor_type == METHOD_UNKNOWN || (o == NULL && f == NULL) ) {
  263. return rb_call_super(argc, argv);
  264. } else if (accessor_type == METHOD_SETTER || accessor_type == METHOD_WRAPPER_SETTER) {
  265. if (argc != 2) {
  266. rb_raise(rb_eArgError, "Expected 2 arguments, received %d", argc);
  267. }
  268. rb_check_frozen(_self);
  269. } else if (argc != 1) {
  270. rb_raise(rb_eArgError, "Expected 1 argument, received %d", argc);
  271. }
  272. // Return which of the oneof fields are set
  273. if (o != NULL) {
  274. const upb_fielddef* oneof_field = which_oneof_field(self, o);
  275. if (accessor_type == METHOD_SETTER) {
  276. rb_raise(rb_eRuntimeError, "Oneof accessors are read-only.");
  277. }
  278. if (accessor_type == METHOD_PRESENCE) {
  279. return oneof_field == NULL ? Qfalse : Qtrue;
  280. } else if (accessor_type == METHOD_CLEAR) {
  281. if (oneof_field != NULL) {
  282. layout_clear(self->descriptor->layout, Message_data(self), oneof_field);
  283. }
  284. return Qnil;
  285. } else {
  286. // METHOD_ACCESSOR
  287. return oneof_field == NULL ? Qnil :
  288. ID2SYM(rb_intern(upb_fielddef_name(oneof_field)));
  289. }
  290. // Otherwise we're operating on a single proto field
  291. } else if (accessor_type == METHOD_SETTER) {
  292. layout_set(self->descriptor->layout, Message_data(self), f, argv[1]);
  293. return Qnil;
  294. } else if (accessor_type == METHOD_CLEAR) {
  295. layout_clear(self->descriptor->layout, Message_data(self), f);
  296. return Qnil;
  297. } else if (accessor_type == METHOD_PRESENCE) {
  298. return layout_has(self->descriptor->layout, Message_data(self), f);
  299. } else if (accessor_type == METHOD_WRAPPER_GETTER) {
  300. VALUE value = layout_get(self->descriptor->layout, Message_data(self), f);
  301. switch (TYPE(value)) {
  302. case T_DATA:
  303. return rb_funcall(value, rb_intern("value"), 0);
  304. case T_NIL:
  305. return Qnil;
  306. default:
  307. return value;
  308. }
  309. } else if (accessor_type == METHOD_WRAPPER_SETTER) {
  310. VALUE wrapper = ruby_wrapper_type(
  311. field_type_class(self->descriptor->layout, f), argv[1]);
  312. layout_set(self->descriptor->layout, Message_data(self), f, wrapper);
  313. return Qnil;
  314. } else if (accessor_type == METHOD_ENUM_GETTER) {
  315. VALUE enum_type = field_type_class(self->descriptor->layout, f);
  316. VALUE method = rb_intern("const_get");
  317. VALUE raw_value = layout_get(self->descriptor->layout, Message_data(self), f);
  318. // Map repeated fields to a new type with ints
  319. if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
  320. int array_size = FIX2INT(rb_funcall(raw_value, rb_intern("length"), 0));
  321. int i;
  322. VALUE array_args[1] = { ID2SYM(rb_intern("int64")) };
  323. VALUE array = rb_class_new_instance(1, array_args, CLASS_OF(raw_value));
  324. for (i = 0; i < array_size; i++) {
  325. VALUE entry = rb_funcall(enum_type, method, 1, rb_funcall(raw_value,
  326. rb_intern("at"), 1, INT2NUM(i)));
  327. rb_funcall(array, rb_intern("push"), 1, entry);
  328. }
  329. return array;
  330. }
  331. // Convert the value for singular fields
  332. return rb_funcall(enum_type, method, 1, raw_value);
  333. } else {
  334. return layout_get(self->descriptor->layout, Message_data(self), f);
  335. }
  336. }
  337. VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
  338. MessageHeader* self;
  339. const upb_oneofdef* o;
  340. const upb_fielddef* f;
  341. int accessor_type;
  342. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  343. if (argc < 1) {
  344. rb_raise(rb_eArgError, "Expected method name as first argument.");
  345. }
  346. accessor_type = extract_method_call(argv[0], self, &f, &o);
  347. if (accessor_type == METHOD_UNKNOWN) {
  348. return rb_call_super(argc, argv);
  349. } else if (o != NULL) {
  350. return accessor_type == METHOD_SETTER ? Qfalse : Qtrue;
  351. } else {
  352. return Qtrue;
  353. }
  354. }
  355. VALUE create_submsg_from_hash(const MessageLayout* layout,
  356. const upb_fielddef* f, VALUE hash) {
  357. VALUE args[1] = { hash };
  358. return rb_class_new_instance(1, args, field_type_class(layout, f));
  359. }
  360. int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
  361. MessageHeader* self;
  362. char *name;
  363. const upb_fielddef* f;
  364. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  365. if (TYPE(key) == T_STRING) {
  366. name = RSTRING_PTR(key);
  367. } else if (TYPE(key) == T_SYMBOL) {
  368. name = RSTRING_PTR(rb_id2str(SYM2ID(key)));
  369. } else {
  370. rb_raise(rb_eArgError,
  371. "Expected string or symbols as hash keys when initializing proto from hash.");
  372. }
  373. f = upb_msgdef_ntofz(self->descriptor->msgdef, name);
  374. if (f == NULL) {
  375. rb_raise(rb_eArgError,
  376. "Unknown field name '%s' in initialization map entry.", name);
  377. }
  378. if (TYPE(val) == T_NIL) {
  379. return 0;
  380. }
  381. if (is_map_field(f)) {
  382. VALUE map;
  383. if (TYPE(val) != T_HASH) {
  384. rb_raise(rb_eArgError,
  385. "Expected Hash object as initializer value for map field '%s' (given %s).",
  386. name, rb_class2name(CLASS_OF(val)));
  387. }
  388. map = layout_get(self->descriptor->layout, Message_data(self), f);
  389. Map_merge_into_self(map, val);
  390. } else if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
  391. VALUE ary;
  392. int i;
  393. if (TYPE(val) != T_ARRAY) {
  394. rb_raise(rb_eArgError,
  395. "Expected array as initializer value for repeated field '%s' (given %s).",
  396. name, rb_class2name(CLASS_OF(val)));
  397. }
  398. ary = layout_get(self->descriptor->layout, Message_data(self), f);
  399. for (i = 0; i < RARRAY_LEN(val); i++) {
  400. VALUE entry = rb_ary_entry(val, i);
  401. if (TYPE(entry) == T_HASH && upb_fielddef_issubmsg(f)) {
  402. entry = create_submsg_from_hash(self->descriptor->layout, f, entry);
  403. }
  404. RepeatedField_push(ary, entry);
  405. }
  406. } else {
  407. if (TYPE(val) == T_HASH && upb_fielddef_issubmsg(f)) {
  408. val = create_submsg_from_hash(self->descriptor->layout, f, val);
  409. }
  410. layout_set(self->descriptor->layout, Message_data(self), f, val);
  411. }
  412. return 0;
  413. }
  414. /*
  415. * call-seq:
  416. * Message.new(kwargs) => new_message
  417. *
  418. * Creates a new instance of the given message class. Keyword arguments may be
  419. * provided with keywords corresponding to field names.
  420. *
  421. * Note that no literal Message class exists. Only concrete classes per message
  422. * type exist, as provided by the #msgclass method on Descriptors after they
  423. * have been added to a pool. The method definitions described here on the
  424. * Message class are provided on each concrete message class.
  425. */
  426. VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
  427. MessageHeader* self;
  428. VALUE hash_args;
  429. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  430. layout_init(self->descriptor->layout, Message_data(self));
  431. if (argc == 0) {
  432. return Qnil;
  433. }
  434. if (argc != 1) {
  435. rb_raise(rb_eArgError, "Expected 0 or 1 arguments.");
  436. }
  437. hash_args = argv[0];
  438. if (TYPE(hash_args) != T_HASH) {
  439. rb_raise(rb_eArgError, "Expected hash arguments.");
  440. }
  441. rb_hash_foreach(hash_args, Message_initialize_kwarg, _self);
  442. return Qnil;
  443. }
  444. /*
  445. * call-seq:
  446. * Message.dup => new_message
  447. *
  448. * Performs a shallow copy of this message and returns the new copy.
  449. */
  450. VALUE Message_dup(VALUE _self) {
  451. MessageHeader* self;
  452. VALUE new_msg;
  453. MessageHeader* new_msg_self;
  454. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  455. new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
  456. TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
  457. layout_dup(self->descriptor->layout,
  458. Message_data(new_msg_self),
  459. Message_data(self));
  460. return new_msg;
  461. }
  462. // Internal only; used by Google::Protobuf.deep_copy.
  463. VALUE Message_deep_copy(VALUE _self) {
  464. MessageHeader* self;
  465. MessageHeader* new_msg_self;
  466. VALUE new_msg;
  467. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  468. new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
  469. TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
  470. layout_deep_copy(self->descriptor->layout,
  471. Message_data(new_msg_self),
  472. Message_data(self));
  473. return new_msg;
  474. }
  475. /*
  476. * call-seq:
  477. * Message.==(other) => boolean
  478. *
  479. * Performs a deep comparison of this message with another. Messages are equal
  480. * if they have the same type and if each field is equal according to the :==
  481. * method's semantics (a more efficient comparison may actually be done if the
  482. * field is of a primitive type).
  483. */
  484. VALUE Message_eq(VALUE _self, VALUE _other) {
  485. MessageHeader* self;
  486. MessageHeader* other;
  487. if (TYPE(_self) != TYPE(_other)) {
  488. return Qfalse;
  489. }
  490. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  491. TypedData_Get_Struct(_other, MessageHeader, &Message_type, other);
  492. if (self->descriptor != other->descriptor) {
  493. return Qfalse;
  494. }
  495. return layout_eq(self->descriptor->layout,
  496. Message_data(self),
  497. Message_data(other));
  498. }
  499. /*
  500. * call-seq:
  501. * Message.hash => hash_value
  502. *
  503. * Returns a hash value that represents this message's field values.
  504. */
  505. VALUE Message_hash(VALUE _self) {
  506. MessageHeader* self;
  507. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  508. return layout_hash(self->descriptor->layout, Message_data(self));
  509. }
  510. /*
  511. * call-seq:
  512. * Message.inspect => string
  513. *
  514. * Returns a human-readable string representing this message. It will be
  515. * formatted as "<MessageType: field1: value1, field2: value2, ...>". Each
  516. * field's value is represented according to its own #inspect method.
  517. */
  518. VALUE Message_inspect(VALUE _self) {
  519. MessageHeader* self;
  520. VALUE str;
  521. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  522. str = rb_str_new2("<");
  523. str = rb_str_append(str, rb_str_new2(rb_class2name(CLASS_OF(_self))));
  524. str = rb_str_cat2(str, ": ");
  525. str = rb_str_append(str, layout_inspect(
  526. self->descriptor->layout, Message_data(self)));
  527. str = rb_str_cat2(str, ">");
  528. return str;
  529. }
  530. /*
  531. * call-seq:
  532. * Message.to_h => {}
  533. *
  534. * Returns the message as a Ruby Hash object, with keys as symbols.
  535. */
  536. VALUE Message_to_h(VALUE _self) {
  537. MessageHeader* self;
  538. VALUE hash = rb_hash_new();
  539. upb_msg_field_iter it;
  540. bool is_proto2;
  541. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  542. // We currently have a few behaviors that are specific to proto2.
  543. // This is unfortunate, we should key behaviors off field attributes (like
  544. // whether a field has presence), not proto2 vs. proto3. We should see if we
  545. // can change this without breaking users.
  546. is_proto2 =
  547. upb_msgdef_syntax(self->descriptor->msgdef) == UPB_SYNTAX_PROTO2;
  548. for (upb_msg_field_begin(&it, self->descriptor->msgdef);
  549. !upb_msg_field_done(&it);
  550. upb_msg_field_next(&it)) {
  551. const upb_fielddef* field = upb_msg_iter_field(&it);
  552. VALUE msg_value;
  553. VALUE msg_key;
  554. // Do not include fields that are not present (oneof or optional fields).
  555. if (is_proto2 && upb_fielddef_haspresence(field) &&
  556. !layout_has(self->descriptor->layout, Message_data(self), field)) {
  557. continue;
  558. }
  559. msg_value = layout_get(self->descriptor->layout, Message_data(self), field);
  560. msg_key = ID2SYM(rb_intern(upb_fielddef_name(field)));
  561. if (is_map_field(field)) {
  562. msg_value = Map_to_h(msg_value);
  563. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  564. msg_value = RepeatedField_to_ary(msg_value);
  565. if (is_proto2 && RARRAY_LEN(msg_value) == 0) {
  566. continue;
  567. }
  568. if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
  569. int i;
  570. for (i = 0; i < RARRAY_LEN(msg_value); i++) {
  571. VALUE elem = rb_ary_entry(msg_value, i);
  572. rb_ary_store(msg_value, i, Message_to_h(elem));
  573. }
  574. }
  575. } else if (msg_value != Qnil &&
  576. upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
  577. msg_value = Message_to_h(msg_value);
  578. }
  579. rb_hash_aset(hash, msg_key, msg_value);
  580. }
  581. return hash;
  582. }
  583. /*
  584. * call-seq:
  585. * Message.[](index) => value
  586. *
  587. * Accesses a field's value by field name. The provided field name should be a
  588. * string.
  589. */
  590. VALUE Message_index(VALUE _self, VALUE field_name) {
  591. MessageHeader* self;
  592. const upb_fielddef* field;
  593. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  594. Check_Type(field_name, T_STRING);
  595. field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
  596. if (field == NULL) {
  597. return Qnil;
  598. }
  599. return layout_get(self->descriptor->layout, Message_data(self), field);
  600. }
  601. /*
  602. * call-seq:
  603. * Message.[]=(index, value)
  604. *
  605. * Sets a field's value by field name. The provided field name should be a
  606. * string.
  607. */
  608. VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
  609. MessageHeader* self;
  610. const upb_fielddef* field;
  611. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  612. Check_Type(field_name, T_STRING);
  613. field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
  614. if (field == NULL) {
  615. rb_raise(rb_eArgError, "Unknown field: %s", RSTRING_PTR(field_name));
  616. }
  617. layout_set(self->descriptor->layout, Message_data(self), field, value);
  618. return Qnil;
  619. }
  620. /*
  621. * call-seq:
  622. * Message.descriptor => descriptor
  623. *
  624. * Class method that returns the Descriptor instance corresponding to this
  625. * message class's type.
  626. */
  627. VALUE Message_descriptor(VALUE klass) {
  628. return rb_ivar_get(klass, descriptor_instancevar_interned);
  629. }
  630. VALUE build_class_from_descriptor(VALUE descriptor) {
  631. Descriptor* desc = ruby_to_Descriptor(descriptor);
  632. const char *name;
  633. VALUE klass;
  634. name = upb_msgdef_fullname(desc->msgdef);
  635. if (name == NULL) {
  636. rb_raise(rb_eRuntimeError, "Descriptor does not have assigned name.");
  637. }
  638. klass = rb_define_class_id(
  639. // Docs say this parameter is ignored. User will assign return value to
  640. // their own toplevel constant class name.
  641. rb_intern("Message"),
  642. rb_cObject);
  643. rb_ivar_set(klass, descriptor_instancevar_interned, descriptor);
  644. rb_define_alloc_func(klass, Message_alloc);
  645. rb_require("google/protobuf/message_exts");
  646. rb_include_module(klass, rb_eval_string("::Google::Protobuf::MessageExts"));
  647. rb_extend_object(
  648. klass, rb_eval_string("::Google::Protobuf::MessageExts::ClassMethods"));
  649. rb_define_method(klass, "method_missing",
  650. Message_method_missing, -1);
  651. rb_define_method(klass, "respond_to_missing?",
  652. Message_respond_to_missing, -1);
  653. rb_define_method(klass, "initialize", Message_initialize, -1);
  654. rb_define_method(klass, "dup", Message_dup, 0);
  655. // Also define #clone so that we don't inherit Object#clone.
  656. rb_define_method(klass, "clone", Message_dup, 0);
  657. rb_define_method(klass, "==", Message_eq, 1);
  658. rb_define_method(klass, "eql?", Message_eq, 1);
  659. rb_define_method(klass, "hash", Message_hash, 0);
  660. rb_define_method(klass, "to_h", Message_to_h, 0);
  661. rb_define_method(klass, "inspect", Message_inspect, 0);
  662. rb_define_method(klass, "to_s", Message_inspect, 0);
  663. rb_define_method(klass, "[]", Message_index, 1);
  664. rb_define_method(klass, "[]=", Message_index_set, 2);
  665. rb_define_singleton_method(klass, "decode", Message_decode, 1);
  666. rb_define_singleton_method(klass, "encode", Message_encode, 1);
  667. rb_define_singleton_method(klass, "decode_json", Message_decode_json, -1);
  668. rb_define_singleton_method(klass, "encode_json", Message_encode_json, -1);
  669. rb_define_singleton_method(klass, "descriptor", Message_descriptor, 0);
  670. return klass;
  671. }
  672. /*
  673. * call-seq:
  674. * Enum.lookup(number) => name
  675. *
  676. * This module method, provided on each generated enum module, looks up an enum
  677. * value by number and returns its name as a Ruby symbol, or nil if not found.
  678. */
  679. VALUE enum_lookup(VALUE self, VALUE number) {
  680. int32_t num = NUM2INT(number);
  681. VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
  682. EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
  683. const char* name = upb_enumdef_iton(enumdesc->enumdef, num);
  684. if (name == NULL) {
  685. return Qnil;
  686. } else {
  687. return ID2SYM(rb_intern(name));
  688. }
  689. }
  690. /*
  691. * call-seq:
  692. * Enum.resolve(name) => number
  693. *
  694. * This module method, provided on each generated enum module, looks up an enum
  695. * value by name (as a Ruby symbol) and returns its name, or nil if not found.
  696. */
  697. VALUE enum_resolve(VALUE self, VALUE sym) {
  698. const char* name = rb_id2name(SYM2ID(sym));
  699. VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
  700. EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
  701. int32_t num = 0;
  702. bool found = upb_enumdef_ntoiz(enumdesc->enumdef, name, &num);
  703. if (!found) {
  704. return Qnil;
  705. } else {
  706. return INT2NUM(num);
  707. }
  708. }
  709. /*
  710. * call-seq:
  711. * Enum.descriptor
  712. *
  713. * This module method, provided on each generated enum module, returns the
  714. * EnumDescriptor corresponding to this enum type.
  715. */
  716. VALUE enum_descriptor(VALUE self) {
  717. return rb_ivar_get(self, descriptor_instancevar_interned);
  718. }
  719. VALUE build_module_from_enumdesc(VALUE _enumdesc) {
  720. EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(_enumdesc);
  721. VALUE mod = rb_define_module_id(
  722. rb_intern(upb_enumdef_fullname(enumdesc->enumdef)));
  723. upb_enum_iter it;
  724. for (upb_enum_begin(&it, enumdesc->enumdef);
  725. !upb_enum_done(&it);
  726. upb_enum_next(&it)) {
  727. const char* name = upb_enum_iter_name(&it);
  728. int32_t value = upb_enum_iter_number(&it);
  729. if (name[0] < 'A' || name[0] > 'Z') {
  730. rb_warn("Enum value '%s' does not start with an uppercase letter "
  731. "as is required for Ruby constants.",
  732. name);
  733. }
  734. rb_define_const(mod, name, INT2NUM(value));
  735. }
  736. rb_define_singleton_method(mod, "lookup", enum_lookup, 1);
  737. rb_define_singleton_method(mod, "resolve", enum_resolve, 1);
  738. rb_define_singleton_method(mod, "descriptor", enum_descriptor, 0);
  739. rb_ivar_set(mod, descriptor_instancevar_interned, _enumdesc);
  740. return mod;
  741. }
  742. /*
  743. * call-seq:
  744. * Google::Protobuf.deep_copy(obj) => copy_of_obj
  745. *
  746. * Performs a deep copy of a RepeatedField instance, a Map instance, or a
  747. * message object, recursively copying its members.
  748. */
  749. VALUE Google_Protobuf_deep_copy(VALUE self, VALUE obj) {
  750. VALUE klass = CLASS_OF(obj);
  751. if (klass == cRepeatedField) {
  752. return RepeatedField_deep_copy(obj);
  753. } else if (klass == cMap) {
  754. return Map_deep_copy(obj);
  755. } else {
  756. return Message_deep_copy(obj);
  757. }
  758. }