message.c 27 KB

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