message.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. xfree(self);
  43. }
  44. rb_data_type_t Message_type = {
  45. "Message",
  46. { Message_mark, Message_free, NULL },
  47. };
  48. VALUE Message_alloc(VALUE klass) {
  49. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  50. Descriptor* desc = ruby_to_Descriptor(descriptor);
  51. MessageHeader* msg = (MessageHeader*)ALLOC_N(
  52. uint8_t, sizeof(MessageHeader) + desc->layout->size);
  53. VALUE ret;
  54. memset(Message_data(msg), 0, desc->layout->size);
  55. // We wrap first so that everything in the message object is GC-rooted in case
  56. // a collection happens during object creation in layout_init().
  57. ret = TypedData_Wrap_Struct(klass, &Message_type, msg);
  58. msg->descriptor = desc;
  59. rb_ivar_set(ret, descriptor_instancevar_interned, descriptor);
  60. layout_init(desc->layout, Message_data(msg));
  61. return ret;
  62. }
  63. static VALUE which_oneof_field(MessageHeader* self, const upb_oneofdef* o) {
  64. upb_oneof_iter it;
  65. size_t case_ofs;
  66. uint32_t oneof_case;
  67. const upb_fielddef* first_field;
  68. const upb_fielddef* f;
  69. // If no fields in the oneof, always nil.
  70. if (upb_oneofdef_numfields(o) == 0) {
  71. return Qnil;
  72. }
  73. // Grab the first field in the oneof so we can get its layout info to find the
  74. // oneof_case field.
  75. upb_oneof_begin(&it, o);
  76. assert(!upb_oneof_done(&it));
  77. first_field = upb_oneof_iter_field(&it);
  78. assert(upb_fielddef_containingoneof(first_field) != NULL);
  79. case_ofs =
  80. self->descriptor->layout->
  81. fields[upb_fielddef_index(first_field)].case_offset;
  82. oneof_case = *((uint32_t*)((char*)Message_data(self) + case_ofs));
  83. if (oneof_case == ONEOF_CASE_NONE) {
  84. return Qnil;
  85. }
  86. // oneof_case is a field index, so find that field.
  87. f = upb_oneofdef_itof(o, oneof_case);
  88. assert(f != NULL);
  89. return ID2SYM(rb_intern(upb_fielddef_name(f)));
  90. }
  91. /*
  92. * call-seq:
  93. * Message.method_missing(*args)
  94. *
  95. * Provides accessors and setters for message fields according to their field
  96. * names. For any field whose name does not conflict with a built-in method, an
  97. * accessor is provided with the same name as the field, and a setter is
  98. * provided with the name of the field plus the '=' suffix. Thus, given a
  99. * message instance 'msg' with field 'foo', the following code is valid:
  100. *
  101. * msg.foo = 42
  102. * puts msg.foo
  103. *
  104. * This method also provides read-only accessors for oneofs. If a oneof exists
  105. * with name 'my_oneof', then msg.my_oneof will return a Ruby symbol equal to
  106. * the name of the field in that oneof that is currently set, or nil if none.
  107. */
  108. VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self) {
  109. MessageHeader* self;
  110. VALUE method_name, method_str;
  111. char* name;
  112. size_t name_len;
  113. bool setter;
  114. const upb_oneofdef* o;
  115. const upb_fielddef* f;
  116. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  117. if (argc < 1) {
  118. rb_raise(rb_eArgError, "Expected method name as first argument.");
  119. }
  120. method_name = argv[0];
  121. if (!SYMBOL_P(method_name)) {
  122. rb_raise(rb_eArgError, "Expected symbol as method name.");
  123. }
  124. method_str = rb_id2str(SYM2ID(method_name));
  125. name = RSTRING_PTR(method_str);
  126. name_len = RSTRING_LEN(method_str);
  127. setter = false;
  128. // Setters have names that end in '='.
  129. if (name[name_len - 1] == '=') {
  130. setter = true;
  131. name_len--;
  132. }
  133. // See if this name corresponds to either a oneof or field in this message.
  134. if (!upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len, &f,
  135. &o)) {
  136. return rb_call_super(argc, argv);
  137. }
  138. if (o != NULL) {
  139. // This is a oneof -- return which field inside the oneof is set.
  140. if (setter) {
  141. rb_raise(rb_eRuntimeError, "Oneof accessors are read-only.");
  142. }
  143. return which_oneof_field(self, o);
  144. } else {
  145. // This is a field -- get or set the field's value.
  146. assert(f);
  147. if (setter) {
  148. if (argc < 2) {
  149. rb_raise(rb_eArgError, "No value provided to setter.");
  150. }
  151. layout_set(self->descriptor->layout, Message_data(self), f, argv[1]);
  152. return Qnil;
  153. } else {
  154. return layout_get(self->descriptor->layout, Message_data(self), f);
  155. }
  156. }
  157. }
  158. VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
  159. MessageHeader* self;
  160. VALUE method_name, method_str;
  161. char* name;
  162. size_t name_len;
  163. bool setter;
  164. const upb_oneofdef* o;
  165. const upb_fielddef* f;
  166. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  167. if (argc < 1) {
  168. rb_raise(rb_eArgError, "Expected method name as first argument.");
  169. }
  170. method_name = argv[0];
  171. if (!SYMBOL_P(method_name)) {
  172. rb_raise(rb_eArgError, "Expected symbol as method name.");
  173. }
  174. method_str = rb_id2str(SYM2ID(method_name));
  175. name = RSTRING_PTR(method_str);
  176. name_len = RSTRING_LEN(method_str);
  177. setter = false;
  178. // Setters have names that end in '='.
  179. if (name[name_len - 1] == '=') {
  180. setter = true;
  181. name_len--;
  182. }
  183. // See if this name corresponds to either a oneof or field in this message.
  184. if (!upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len, &f,
  185. &o)) {
  186. return rb_call_super(argc, argv);
  187. }
  188. if (o != NULL) {
  189. return setter ? Qfalse : Qtrue;
  190. }
  191. return Qtrue;
  192. }
  193. VALUE create_submsg_from_hash(const upb_fielddef *f, VALUE hash) {
  194. const upb_def *d = upb_fielddef_subdef(f);
  195. assert(d != NULL);
  196. VALUE descriptor = get_def_obj(d);
  197. VALUE msgclass = rb_funcall(descriptor, rb_intern("msgclass"), 0, NULL);
  198. VALUE args[1] = { hash };
  199. return rb_class_new_instance(1, args, msgclass);
  200. }
  201. int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
  202. MessageHeader* self;
  203. char *name;
  204. const upb_fielddef* f;
  205. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  206. if (TYPE(key) == T_STRING) {
  207. name = RSTRING_PTR(key);
  208. } else if (TYPE(key) == T_SYMBOL) {
  209. name = RSTRING_PTR(rb_id2str(SYM2ID(key)));
  210. } else {
  211. rb_raise(rb_eArgError,
  212. "Expected string or symbols as hash keys when initializing proto from hash.");
  213. }
  214. f = upb_msgdef_ntofz(self->descriptor->msgdef, name);
  215. if (f == NULL) {
  216. rb_raise(rb_eArgError,
  217. "Unknown field name '%s' in initialization map entry.", name);
  218. }
  219. if (is_map_field(f)) {
  220. VALUE map;
  221. if (TYPE(val) != T_HASH) {
  222. rb_raise(rb_eArgError,
  223. "Expected Hash object as initializer value for map field '%s'.", name);
  224. }
  225. map = layout_get(self->descriptor->layout, Message_data(self), f);
  226. Map_merge_into_self(map, val);
  227. } else if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
  228. VALUE ary;
  229. if (TYPE(val) != T_ARRAY) {
  230. rb_raise(rb_eArgError,
  231. "Expected array as initializer value for repeated field '%s'.", name);
  232. }
  233. ary = layout_get(self->descriptor->layout, Message_data(self), f);
  234. for (int i = 0; i < RARRAY_LEN(val); i++) {
  235. VALUE entry = rb_ary_entry(val, i);
  236. if (TYPE(entry) == T_HASH && upb_fielddef_issubmsg(f)) {
  237. entry = create_submsg_from_hash(f, entry);
  238. }
  239. RepeatedField_push(ary, entry);
  240. }
  241. } else {
  242. if (TYPE(val) == T_HASH && upb_fielddef_issubmsg(f)) {
  243. val = create_submsg_from_hash(f, val);
  244. }
  245. layout_set(self->descriptor->layout, Message_data(self), f, val);
  246. }
  247. return 0;
  248. }
  249. /*
  250. * call-seq:
  251. * Message.new(kwargs) => new_message
  252. *
  253. * Creates a new instance of the given message class. Keyword arguments may be
  254. * provided with keywords corresponding to field names.
  255. *
  256. * Note that no literal Message class exists. Only concrete classes per message
  257. * type exist, as provided by the #msgclass method on Descriptors after they
  258. * have been added to a pool. The method definitions described here on the
  259. * Message class are provided on each concrete message class.
  260. */
  261. VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
  262. VALUE hash_args;
  263. if (argc == 0) {
  264. return Qnil;
  265. }
  266. if (argc != 1) {
  267. rb_raise(rb_eArgError, "Expected 0 or 1 arguments.");
  268. }
  269. hash_args = argv[0];
  270. if (TYPE(hash_args) != T_HASH) {
  271. rb_raise(rb_eArgError, "Expected hash arguments.");
  272. }
  273. rb_hash_foreach(hash_args, Message_initialize_kwarg, _self);
  274. return Qnil;
  275. }
  276. /*
  277. * call-seq:
  278. * Message.dup => new_message
  279. *
  280. * Performs a shallow copy of this message and returns the new copy.
  281. */
  282. VALUE Message_dup(VALUE _self) {
  283. MessageHeader* self;
  284. VALUE new_msg;
  285. MessageHeader* new_msg_self;
  286. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  287. new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
  288. TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
  289. layout_dup(self->descriptor->layout,
  290. Message_data(new_msg_self),
  291. Message_data(self));
  292. return new_msg;
  293. }
  294. // Internal only; used by Google::Protobuf.deep_copy.
  295. VALUE Message_deep_copy(VALUE _self) {
  296. MessageHeader* self;
  297. MessageHeader* new_msg_self;
  298. VALUE new_msg;
  299. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  300. new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
  301. TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
  302. layout_deep_copy(self->descriptor->layout,
  303. Message_data(new_msg_self),
  304. Message_data(self));
  305. return new_msg;
  306. }
  307. /*
  308. * call-seq:
  309. * Message.==(other) => boolean
  310. *
  311. * Performs a deep comparison of this message with another. Messages are equal
  312. * if they have the same type and if each field is equal according to the :==
  313. * method's semantics (a more efficient comparison may actually be done if the
  314. * field is of a primitive type).
  315. */
  316. VALUE Message_eq(VALUE _self, VALUE _other) {
  317. MessageHeader* self;
  318. MessageHeader* other;
  319. if (TYPE(_self) != TYPE(_other)) {
  320. return Qfalse;
  321. }
  322. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  323. TypedData_Get_Struct(_other, MessageHeader, &Message_type, other);
  324. if (self->descriptor != other->descriptor) {
  325. return Qfalse;
  326. }
  327. return layout_eq(self->descriptor->layout,
  328. Message_data(self),
  329. Message_data(other));
  330. }
  331. /*
  332. * call-seq:
  333. * Message.hash => hash_value
  334. *
  335. * Returns a hash value that represents this message's field values.
  336. */
  337. VALUE Message_hash(VALUE _self) {
  338. MessageHeader* self;
  339. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  340. return layout_hash(self->descriptor->layout, Message_data(self));
  341. }
  342. /*
  343. * call-seq:
  344. * Message.inspect => string
  345. *
  346. * Returns a human-readable string representing this message. It will be
  347. * formatted as "<MessageType: field1: value1, field2: value2, ...>". Each
  348. * field's value is represented according to its own #inspect method.
  349. */
  350. VALUE Message_inspect(VALUE _self) {
  351. MessageHeader* self;
  352. VALUE str;
  353. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  354. str = rb_str_new2("<");
  355. str = rb_str_append(str, rb_str_new2(rb_class2name(CLASS_OF(_self))));
  356. str = rb_str_cat2(str, ": ");
  357. str = rb_str_append(str, layout_inspect(
  358. self->descriptor->layout, Message_data(self)));
  359. str = rb_str_cat2(str, ">");
  360. return str;
  361. }
  362. /*
  363. * call-seq:
  364. * Message.to_h => {}
  365. *
  366. * Returns the message as a Ruby Hash object, with keys as symbols.
  367. */
  368. VALUE Message_to_h(VALUE _self) {
  369. MessageHeader* self;
  370. VALUE hash;
  371. upb_msg_field_iter it;
  372. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  373. hash = rb_hash_new();
  374. for (upb_msg_field_begin(&it, self->descriptor->msgdef);
  375. !upb_msg_field_done(&it);
  376. upb_msg_field_next(&it)) {
  377. const upb_fielddef* field = upb_msg_iter_field(&it);
  378. VALUE msg_value = layout_get(self->descriptor->layout, Message_data(self),
  379. field);
  380. VALUE msg_key = ID2SYM(rb_intern(upb_fielddef_name(field)));
  381. if (upb_fielddef_ismap(field)) {
  382. msg_value = Map_to_h(msg_value);
  383. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  384. msg_value = RepeatedField_to_ary(msg_value);
  385. if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
  386. for (int i = 0; i < RARRAY_LEN(msg_value); i++) {
  387. VALUE elem = rb_ary_entry(msg_value, i);
  388. rb_ary_store(msg_value, i, Message_to_h(elem));
  389. }
  390. }
  391. } else if (msg_value != Qnil &&
  392. upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
  393. msg_value = Message_to_h(msg_value);
  394. }
  395. rb_hash_aset(hash, msg_key, msg_value);
  396. }
  397. return hash;
  398. }
  399. /*
  400. * call-seq:
  401. * Message.[](index) => value
  402. *
  403. * Accesses a field's value by field name. The provided field name should be a
  404. * string.
  405. */
  406. VALUE Message_index(VALUE _self, VALUE field_name) {
  407. MessageHeader* self;
  408. const upb_fielddef* field;
  409. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  410. Check_Type(field_name, T_STRING);
  411. field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
  412. if (field == NULL) {
  413. return Qnil;
  414. }
  415. return layout_get(self->descriptor->layout, Message_data(self), field);
  416. }
  417. /*
  418. * call-seq:
  419. * Message.[]=(index, value)
  420. *
  421. * Sets a field's value by field name. The provided field name should be a
  422. * string.
  423. */
  424. VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
  425. MessageHeader* self;
  426. const upb_fielddef* field;
  427. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  428. Check_Type(field_name, T_STRING);
  429. field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
  430. if (field == NULL) {
  431. rb_raise(rb_eArgError, "Unknown field: %s", RSTRING_PTR(field_name));
  432. }
  433. layout_set(self->descriptor->layout, Message_data(self), field, value);
  434. return Qnil;
  435. }
  436. /*
  437. * call-seq:
  438. * Message.descriptor => descriptor
  439. *
  440. * Class method that returns the Descriptor instance corresponding to this
  441. * message class's type.
  442. */
  443. VALUE Message_descriptor(VALUE klass) {
  444. return rb_ivar_get(klass, descriptor_instancevar_interned);
  445. }
  446. VALUE build_class_from_descriptor(Descriptor* desc) {
  447. const char *name;
  448. VALUE klass;
  449. if (desc->layout == NULL) {
  450. desc->layout = create_layout(desc->msgdef);
  451. }
  452. if (desc->fill_method == NULL) {
  453. desc->fill_method = new_fillmsg_decodermethod(desc, &desc->fill_method);
  454. }
  455. name = upb_msgdef_fullname(desc->msgdef);
  456. if (name == NULL) {
  457. rb_raise(rb_eRuntimeError, "Descriptor does not have assigned name.");
  458. }
  459. klass = rb_define_class_id(
  460. // Docs say this parameter is ignored. User will assign return value to
  461. // their own toplevel constant class name.
  462. rb_intern("Message"),
  463. rb_cObject);
  464. rb_ivar_set(klass, descriptor_instancevar_interned,
  465. get_def_obj(desc->msgdef));
  466. rb_define_alloc_func(klass, Message_alloc);
  467. rb_require("google/protobuf/message_exts");
  468. rb_include_module(klass, rb_eval_string("Google::Protobuf::MessageExts"));
  469. rb_extend_object(
  470. klass, rb_eval_string("Google::Protobuf::MessageExts::ClassMethods"));
  471. rb_define_method(klass, "method_missing",
  472. Message_method_missing, -1);
  473. rb_define_method(klass, "respond_to_missing?",
  474. Message_respond_to_missing, -1);
  475. rb_define_method(klass, "initialize", Message_initialize, -1);
  476. rb_define_method(klass, "dup", Message_dup, 0);
  477. // Also define #clone so that we don't inherit Object#clone.
  478. rb_define_method(klass, "clone", Message_dup, 0);
  479. rb_define_method(klass, "==", Message_eq, 1);
  480. rb_define_method(klass, "hash", Message_hash, 0);
  481. rb_define_method(klass, "to_h", Message_to_h, 0);
  482. rb_define_method(klass, "to_hash", Message_to_h, 0);
  483. rb_define_method(klass, "inspect", Message_inspect, 0);
  484. rb_define_method(klass, "[]", Message_index, 1);
  485. rb_define_method(klass, "[]=", Message_index_set, 2);
  486. rb_define_singleton_method(klass, "decode", Message_decode, 1);
  487. rb_define_singleton_method(klass, "encode", Message_encode, 1);
  488. rb_define_singleton_method(klass, "decode_json", Message_decode_json, 1);
  489. rb_define_singleton_method(klass, "encode_json", Message_encode_json, -1);
  490. rb_define_singleton_method(klass, "descriptor", Message_descriptor, 0);
  491. return klass;
  492. }
  493. /*
  494. * call-seq:
  495. * Enum.lookup(number) => name
  496. *
  497. * This module method, provided on each generated enum module, looks up an enum
  498. * value by number and returns its name as a Ruby symbol, or nil if not found.
  499. */
  500. VALUE enum_lookup(VALUE self, VALUE number) {
  501. int32_t num = NUM2INT(number);
  502. VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
  503. EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
  504. const char* name = upb_enumdef_iton(enumdesc->enumdef, num);
  505. if (name == NULL) {
  506. return Qnil;
  507. } else {
  508. return ID2SYM(rb_intern(name));
  509. }
  510. }
  511. /*
  512. * call-seq:
  513. * Enum.resolve(name) => number
  514. *
  515. * This module method, provided on each generated enum module, looks up an enum
  516. * value by name (as a Ruby symbol) and returns its name, or nil if not found.
  517. */
  518. VALUE enum_resolve(VALUE self, VALUE sym) {
  519. const char* name = rb_id2name(SYM2ID(sym));
  520. VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
  521. EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
  522. int32_t num = 0;
  523. bool found = upb_enumdef_ntoiz(enumdesc->enumdef, name, &num);
  524. if (!found) {
  525. return Qnil;
  526. } else {
  527. return INT2NUM(num);
  528. }
  529. }
  530. /*
  531. * call-seq:
  532. * Enum.descriptor
  533. *
  534. * This module method, provided on each generated enum module, returns the
  535. * EnumDescriptor corresponding to this enum type.
  536. */
  537. VALUE enum_descriptor(VALUE self) {
  538. return rb_ivar_get(self, descriptor_instancevar_interned);
  539. }
  540. VALUE build_module_from_enumdesc(EnumDescriptor* enumdesc) {
  541. VALUE mod = rb_define_module_id(
  542. rb_intern(upb_enumdef_fullname(enumdesc->enumdef)));
  543. upb_enum_iter it;
  544. for (upb_enum_begin(&it, enumdesc->enumdef);
  545. !upb_enum_done(&it);
  546. upb_enum_next(&it)) {
  547. const char* name = upb_enum_iter_name(&it);
  548. int32_t value = upb_enum_iter_number(&it);
  549. if (name[0] < 'A' || name[0] > 'Z') {
  550. rb_raise(rb_eTypeError,
  551. "Enum value '%s' does not start with an uppercase letter "
  552. "as is required for Ruby constants.",
  553. name);
  554. }
  555. rb_define_const(mod, name, INT2NUM(value));
  556. }
  557. rb_define_singleton_method(mod, "lookup", enum_lookup, 1);
  558. rb_define_singleton_method(mod, "resolve", enum_resolve, 1);
  559. rb_define_singleton_method(mod, "descriptor", enum_descriptor, 0);
  560. rb_ivar_set(mod, descriptor_instancevar_interned,
  561. get_def_obj(enumdesc->enumdef));
  562. return mod;
  563. }
  564. /*
  565. * call-seq:
  566. * Google::Protobuf.deep_copy(obj) => copy_of_obj
  567. *
  568. * Performs a deep copy of a RepeatedField instance, a Map instance, or a
  569. * message object, recursively copying its members.
  570. */
  571. VALUE Google_Protobuf_deep_copy(VALUE self, VALUE obj) {
  572. VALUE klass = CLASS_OF(obj);
  573. if (klass == cRepeatedField) {
  574. return RepeatedField_deep_copy(obj);
  575. } else if (klass == cMap) {
  576. return Map_deep_copy(obj);
  577. } else {
  578. return Message_deep_copy(obj);
  579. }
  580. }