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