message.c 28 KB

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