message.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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_iv_get(klass, kDescriptorInstanceVar);
  50. Descriptor* desc = ruby_to_Descriptor(descriptor);
  51. MessageHeader* msg = (MessageHeader*)ALLOC_N(
  52. uint8_t, sizeof(MessageHeader) + desc->layout->size);
  53. memset(Message_data(msg), 0, desc->layout->size);
  54. // We wrap first so that everything in the message object is GC-rooted in case
  55. // a collection happens during object creation in layout_init().
  56. VALUE ret = TypedData_Wrap_Struct(klass, &Message_type, msg);
  57. msg->descriptor = desc;
  58. rb_iv_set(ret, kDescriptorInstanceVar, descriptor);
  59. layout_init(desc->layout, Message_data(msg));
  60. return ret;
  61. }
  62. /*
  63. * call-seq:
  64. * Message.method_missing(*args)
  65. *
  66. * Provides accessors and setters for message fields according to their field
  67. * names. For any field whose name does not conflict with a built-in method, an
  68. * accessor is provided with the same name as the field, and a setter is
  69. * provided with the name of the field plus the '=' suffix. Thus, given a
  70. * message instance 'msg' with field 'foo', the following code is valid:
  71. *
  72. * msg.foo = 42
  73. * puts msg.foo
  74. */
  75. VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self) {
  76. MessageHeader* self;
  77. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  78. if (argc < 1) {
  79. rb_raise(rb_eArgError, "Expected method name as first argument.");
  80. }
  81. VALUE method_name = argv[0];
  82. if (!SYMBOL_P(method_name)) {
  83. rb_raise(rb_eArgError, "Expected symbol as method name.");
  84. }
  85. VALUE method_str = rb_id2str(SYM2ID(method_name));
  86. char* name = RSTRING_PTR(method_str);
  87. size_t name_len = RSTRING_LEN(method_str);
  88. bool setter = false;
  89. // Setters have names that end in '='.
  90. if (name[name_len - 1] == '=') {
  91. setter = true;
  92. name_len--;
  93. }
  94. const upb_fielddef* f = upb_msgdef_ntof(self->descriptor->msgdef,
  95. name, name_len);
  96. if (f == NULL) {
  97. rb_raise(rb_eArgError, "Unknown field");
  98. }
  99. if (setter) {
  100. if (argc < 2) {
  101. rb_raise(rb_eArgError, "No value provided to setter.");
  102. }
  103. layout_set(self->descriptor->layout, Message_data(self), f, argv[1]);
  104. return Qnil;
  105. } else {
  106. return layout_get(self->descriptor->layout, Message_data(self), f);
  107. }
  108. }
  109. int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
  110. MessageHeader* self;
  111. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  112. if (!SYMBOL_P(key)) {
  113. rb_raise(rb_eArgError,
  114. "Expected symbols as hash keys in initialization map.");
  115. }
  116. VALUE method_str = rb_id2str(SYM2ID(key));
  117. char* name = RSTRING_PTR(method_str);
  118. const upb_fielddef* f = upb_msgdef_ntofz(self->descriptor->msgdef, name);
  119. if (f == NULL) {
  120. rb_raise(rb_eArgError,
  121. "Unknown field name in initialization map entry.");
  122. }
  123. if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
  124. if (TYPE(val) != T_ARRAY) {
  125. rb_raise(rb_eArgError,
  126. "Expected array as initializer value for repeated field.");
  127. }
  128. VALUE ary = layout_get(self->descriptor->layout, Message_data(self), f);
  129. for (int i = 0; i < RARRAY_LEN(val); i++) {
  130. RepeatedField_push(ary, rb_ary_entry(val, i));
  131. }
  132. } else {
  133. layout_set(self->descriptor->layout, Message_data(self), f, val);
  134. }
  135. return 0;
  136. }
  137. /*
  138. * call-seq:
  139. * Message.new(kwargs) => new_message
  140. *
  141. * Creates a new instance of the given message class. Keyword arguments may be
  142. * provided with keywords corresponding to field names.
  143. *
  144. * Note that no literal Message class exists. Only concrete classes per message
  145. * type exist, as provided by the #msgclass method on Descriptors after they
  146. * have been added to a pool. The method definitions described here on the
  147. * Message class are provided on each concrete message class.
  148. */
  149. VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
  150. if (argc == 0) {
  151. return Qnil;
  152. }
  153. if (argc != 1) {
  154. rb_raise(rb_eArgError, "Expected 0 or 1 arguments.");
  155. }
  156. VALUE hash_args = argv[0];
  157. if (TYPE(hash_args) != T_HASH) {
  158. rb_raise(rb_eArgError, "Expected hash arguments.");
  159. }
  160. rb_hash_foreach(hash_args, Message_initialize_kwarg, _self);
  161. return Qnil;
  162. }
  163. /*
  164. * call-seq:
  165. * Message.dup => new_message
  166. *
  167. * Performs a shallow copy of this message and returns the new copy.
  168. */
  169. VALUE Message_dup(VALUE _self) {
  170. MessageHeader* self;
  171. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  172. VALUE new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
  173. MessageHeader* new_msg_self;
  174. TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
  175. layout_dup(self->descriptor->layout,
  176. Message_data(new_msg_self),
  177. Message_data(self));
  178. return new_msg;
  179. }
  180. // Internal only; used by Google::Protobuf.deep_copy.
  181. VALUE Message_deep_copy(VALUE _self) {
  182. MessageHeader* self;
  183. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  184. VALUE new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
  185. MessageHeader* new_msg_self;
  186. TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
  187. layout_deep_copy(self->descriptor->layout,
  188. Message_data(new_msg_self),
  189. Message_data(self));
  190. return new_msg;
  191. }
  192. /*
  193. * call-seq:
  194. * Message.==(other) => boolean
  195. *
  196. * Performs a deep comparison of this message with another. Messages are equal
  197. * if they have the same type and if each field is equal according to the :==
  198. * method's semantics (a more efficient comparison may actually be done if the
  199. * field is of a primitive type).
  200. */
  201. VALUE Message_eq(VALUE _self, VALUE _other) {
  202. MessageHeader* self;
  203. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  204. MessageHeader* other;
  205. TypedData_Get_Struct(_other, MessageHeader, &Message_type, other);
  206. if (self->descriptor != other->descriptor) {
  207. return Qfalse;
  208. }
  209. return layout_eq(self->descriptor->layout,
  210. Message_data(self),
  211. Message_data(other));
  212. }
  213. /*
  214. * call-seq:
  215. * Message.hash => hash_value
  216. *
  217. * Returns a hash value that represents this message's field values.
  218. */
  219. VALUE Message_hash(VALUE _self) {
  220. MessageHeader* self;
  221. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  222. return layout_hash(self->descriptor->layout, Message_data(self));
  223. }
  224. /*
  225. * call-seq:
  226. * Message.inspect => string
  227. *
  228. * Returns a human-readable string representing this message. It will be
  229. * formatted as "<MessageType: field1: value1, field2: value2, ...>". Each
  230. * field's value is represented according to its own #inspect method.
  231. */
  232. VALUE Message_inspect(VALUE _self) {
  233. MessageHeader* self;
  234. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  235. VALUE str = rb_str_new2("<");
  236. str = rb_str_append(str, rb_str_new2(rb_class2name(CLASS_OF(_self))));
  237. str = rb_str_cat2(str, ": ");
  238. str = rb_str_append(str, layout_inspect(
  239. self->descriptor->layout, Message_data(self)));
  240. str = rb_str_cat2(str, ">");
  241. return str;
  242. }
  243. /*
  244. * call-seq:
  245. * Message.[](index) => value
  246. *
  247. * Accesses a field's value by field name. The provided field name should be a
  248. * string.
  249. */
  250. VALUE Message_index(VALUE _self, VALUE field_name) {
  251. MessageHeader* self;
  252. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  253. Check_Type(field_name, T_STRING);
  254. const upb_fielddef* field =
  255. upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
  256. if (field == NULL) {
  257. return Qnil;
  258. }
  259. return layout_get(self->descriptor->layout, Message_data(self), field);
  260. }
  261. /*
  262. * call-seq:
  263. * Message.[]=(index, value)
  264. *
  265. * Sets a field's value by field name. The provided field name should be a
  266. * string.
  267. */
  268. VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
  269. MessageHeader* self;
  270. TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
  271. Check_Type(field_name, T_STRING);
  272. const upb_fielddef* field =
  273. upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
  274. if (field == NULL) {
  275. rb_raise(rb_eArgError, "Unknown field: %s", RSTRING_PTR(field_name));
  276. }
  277. layout_set(self->descriptor->layout, Message_data(self), field, value);
  278. return Qnil;
  279. }
  280. /*
  281. * call-seq:
  282. * Message.descriptor => descriptor
  283. *
  284. * Class method that returns the Descriptor instance corresponding to this
  285. * message class's type.
  286. */
  287. VALUE Message_descriptor(VALUE klass) {
  288. return rb_iv_get(klass, kDescriptorInstanceVar);
  289. }
  290. VALUE build_class_from_descriptor(Descriptor* desc) {
  291. if (desc->layout == NULL) {
  292. desc->layout = create_layout(desc->msgdef);
  293. }
  294. if (desc->fill_method == NULL) {
  295. desc->fill_method = new_fillmsg_decodermethod(desc, &desc->fill_method);
  296. }
  297. const char* name = upb_msgdef_fullname(desc->msgdef);
  298. if (name == NULL) {
  299. rb_raise(rb_eRuntimeError, "Descriptor does not have assigned name.");
  300. }
  301. VALUE klass = rb_define_class_id(
  302. // Docs say this parameter is ignored. User will assign return value to
  303. // their own toplevel constant class name.
  304. rb_intern("Message"),
  305. rb_cObject);
  306. rb_iv_set(klass, kDescriptorInstanceVar, get_def_obj(desc->msgdef));
  307. rb_define_alloc_func(klass, Message_alloc);
  308. rb_define_method(klass, "method_missing",
  309. Message_method_missing, -1);
  310. rb_define_method(klass, "initialize", Message_initialize, -1);
  311. rb_define_method(klass, "dup", Message_dup, 0);
  312. // Also define #clone so that we don't inherit Object#clone.
  313. rb_define_method(klass, "clone", Message_dup, 0);
  314. rb_define_method(klass, "==", Message_eq, 1);
  315. rb_define_method(klass, "hash", Message_hash, 0);
  316. rb_define_method(klass, "inspect", Message_inspect, 0);
  317. rb_define_method(klass, "[]", Message_index, 1);
  318. rb_define_method(klass, "[]=", Message_index_set, 2);
  319. rb_define_singleton_method(klass, "decode", Message_decode, 1);
  320. rb_define_singleton_method(klass, "encode", Message_encode, 1);
  321. rb_define_singleton_method(klass, "decode_json", Message_decode_json, 1);
  322. rb_define_singleton_method(klass, "encode_json", Message_encode_json, 1);
  323. rb_define_singleton_method(klass, "descriptor", Message_descriptor, 0);
  324. return klass;
  325. }
  326. /*
  327. * call-seq:
  328. * Enum.lookup(number) => name
  329. *
  330. * This module method, provided on each generated enum module, looks up an enum
  331. * value by number and returns its name as a Ruby symbol, or nil if not found.
  332. */
  333. VALUE enum_lookup(VALUE self, VALUE number) {
  334. int32_t num = NUM2INT(number);
  335. VALUE desc = rb_iv_get(self, kDescriptorInstanceVar);
  336. EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
  337. const char* name = upb_enumdef_iton(enumdesc->enumdef, num);
  338. if (name == NULL) {
  339. return Qnil;
  340. } else {
  341. return ID2SYM(rb_intern(name));
  342. }
  343. }
  344. /*
  345. * call-seq:
  346. * Enum.resolve(name) => number
  347. *
  348. * This module method, provided on each generated enum module, looks up an enum
  349. * value by name (as a Ruby symbol) and returns its name, or nil if not found.
  350. */
  351. VALUE enum_resolve(VALUE self, VALUE sym) {
  352. const char* name = rb_id2name(SYM2ID(sym));
  353. VALUE desc = rb_iv_get(self, kDescriptorInstanceVar);
  354. EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
  355. int32_t num = 0;
  356. bool found = upb_enumdef_ntoiz(enumdesc->enumdef, name, &num);
  357. if (!found) {
  358. return Qnil;
  359. } else {
  360. return INT2NUM(num);
  361. }
  362. }
  363. /*
  364. * call-seq:
  365. * Enum.descriptor
  366. *
  367. * This module method, provided on each generated enum module, returns the
  368. * EnumDescriptor corresponding to this enum type.
  369. */
  370. VALUE enum_descriptor(VALUE self) {
  371. return rb_iv_get(self, kDescriptorInstanceVar);
  372. }
  373. VALUE build_module_from_enumdesc(EnumDescriptor* enumdesc) {
  374. VALUE mod = rb_define_module_id(
  375. rb_intern(upb_enumdef_fullname(enumdesc->enumdef)));
  376. upb_enum_iter it;
  377. for (upb_enum_begin(&it, enumdesc->enumdef);
  378. !upb_enum_done(&it);
  379. upb_enum_next(&it)) {
  380. const char* name = upb_enum_iter_name(&it);
  381. int32_t value = upb_enum_iter_number(&it);
  382. if (name[0] < 'A' || name[0] > 'Z') {
  383. rb_raise(rb_eTypeError,
  384. "Enum value '%s' does not start with an uppercase letter "
  385. "as is required for Ruby constants.",
  386. name);
  387. }
  388. rb_define_const(mod, name, INT2NUM(value));
  389. }
  390. rb_define_singleton_method(mod, "lookup", enum_lookup, 1);
  391. rb_define_singleton_method(mod, "resolve", enum_resolve, 1);
  392. rb_define_singleton_method(mod, "descriptor", enum_descriptor, 0);
  393. rb_iv_set(mod, kDescriptorInstanceVar, get_def_obj(enumdesc->enumdef));
  394. return mod;
  395. }
  396. /*
  397. * call-seq:
  398. * Google::Protobuf.deep_copy(obj) => copy_of_obj
  399. *
  400. * Performs a deep copy of either a RepeatedField instance or a message object,
  401. * recursively copying its members.
  402. */
  403. VALUE Google_Protobuf_deep_copy(VALUE self, VALUE obj) {
  404. VALUE klass = CLASS_OF(obj);
  405. if (klass == cRepeatedField) {
  406. return RepeatedField_deep_copy(obj);
  407. } else {
  408. return Message_deep_copy(obj);
  409. }
  410. }