message.c 23 KB

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