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