message.c 28 KB

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