google-protobuf 3.14.0-x86-mingw32 → 3.15.2-x86-mingw32

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of google-protobuf might be problematic. Click here for more details.

@@ -0,0 +1,66 @@
1
+ // Protocol Buffers - Google's data interchange format
2
+ // Copyright 2008 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
+ #ifndef RUBY_PROTOBUF_MAP_H_
32
+ #define RUBY_PROTOBUF_MAP_H_
33
+
34
+ #include <ruby/ruby.h>
35
+
36
+ #include "protobuf.h"
37
+ #include "ruby-upb.h"
38
+
39
+ // Returns a Ruby wrapper object for the given map, which will be created if
40
+ // one does not exist already.
41
+ VALUE Map_GetRubyWrapper(upb_map *map, upb_fieldtype_t key_type,
42
+ TypeInfo value_type, VALUE arena);
43
+
44
+ // Gets the underlying upb_map for this Ruby map object, which must have
45
+ // key/value type that match |field|. If this is not a map or the type doesn't
46
+ // match, raises an exception.
47
+ const upb_map *Map_GetUpbMap(VALUE val, const upb_fielddef *field);
48
+
49
+ // Implements #inspect for this map by appending its contents to |b|.
50
+ void Map_Inspect(StringBuilder *b, const upb_map *map, upb_fieldtype_t key_type,
51
+ TypeInfo val_type);
52
+
53
+ // Returns a new Hash object containing the contents of this Map.
54
+ VALUE Map_CreateHash(const upb_map* map, upb_fieldtype_t key_type,
55
+ TypeInfo val_info);
56
+
57
+ // Returns a deep copy of this Map object.
58
+ VALUE Map_deep_copy(VALUE obj);
59
+
60
+ // Ruby class of Google::Protobuf::Map.
61
+ extern VALUE cMap;
62
+
63
+ // Call at startup to register all types in this module.
64
+ void Map_register(VALUE module);
65
+
66
+ #endif // RUBY_PROTOBUF_MAP_H_
@@ -28,49 +28,61 @@
28
28
  // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
29
  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
30
 
31
+ #include "message.h"
32
+
33
+ #include "convert.h"
34
+ #include "defs.h"
35
+ #include "map.h"
31
36
  #include "protobuf.h"
37
+ #include "repeated_field.h"
38
+ #include "third_party/wyhash/wyhash.h"
32
39
 
33
- // -----------------------------------------------------------------------------
34
- // Class/module creation from msgdefs and enumdefs, respectively.
35
- // -----------------------------------------------------------------------------
40
+ static VALUE cParseError = Qnil;
41
+ static ID descriptor_instancevar_interned;
36
42
 
37
- void* Message_data(void* msg) {
38
- return ((uint8_t *)msg) + sizeof(MessageHeader);
43
+ static VALUE initialize_rb_class_with_no_args(VALUE klass) {
44
+ return rb_funcall(klass, rb_intern("new"), 0);
39
45
  }
40
46
 
41
- void Message_mark(void* _self) {
42
- MessageHeader* self = (MessageHeader *)_self;
43
- layout_mark(self->descriptor->layout, Message_data(self));
47
+ VALUE MessageOrEnum_GetDescriptor(VALUE klass) {
48
+ return rb_ivar_get(klass, descriptor_instancevar_interned);
44
49
  }
45
50
 
46
- void Message_free(void* self) {
47
- stringsink* unknown = ((MessageHeader *)self)->unknown_fields;
48
- if (unknown != NULL) {
49
- stringsink_uninit(unknown);
50
- free(unknown);
51
- }
52
- xfree(self);
51
+ // -----------------------------------------------------------------------------
52
+ // Class/module creation from msgdefs and enumdefs, respectively.
53
+ // -----------------------------------------------------------------------------
54
+
55
+ typedef struct {
56
+ VALUE arena;
57
+ const upb_msg* msg; // Can get as mutable when non-frozen.
58
+ const upb_msgdef* msgdef; // kept alive by self.class.descriptor reference.
59
+ } Message;
60
+
61
+ static void Message_mark(void* _self) {
62
+ Message* self = (Message *)_self;
63
+ rb_gc_mark(self->arena);
53
64
  }
54
65
 
55
- rb_data_type_t Message_type = {
66
+ static rb_data_type_t Message_type = {
56
67
  "Message",
57
- { Message_mark, Message_free, NULL },
68
+ { Message_mark, RUBY_DEFAULT_FREE, NULL },
69
+ .flags = RUBY_TYPED_FREE_IMMEDIATELY,
58
70
  };
59
71
 
60
- VALUE Message_alloc(VALUE klass) {
72
+ static Message* ruby_to_Message(VALUE msg_rb) {
73
+ Message* msg;
74
+ TypedData_Get_Struct(msg_rb, Message, &Message_type, msg);
75
+ return msg;
76
+ }
77
+
78
+ static VALUE Message_alloc(VALUE klass) {
61
79
  VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
62
- Descriptor* desc = ruby_to_Descriptor(descriptor);
63
- MessageHeader* msg;
80
+ Message* msg = ALLOC(Message);
64
81
  VALUE ret;
65
82
 
66
- if (desc->layout == NULL) {
67
- create_layout(desc);
68
- }
69
-
70
- msg = (void*)ALLOC_N(uint8_t, sizeof(MessageHeader) + desc->layout->size);
71
- msg->descriptor = desc;
72
- msg->unknown_fields = NULL;
73
- memcpy(Message_data(msg), desc->layout->empty_template, desc->layout->size);
83
+ msg->msgdef = Descriptor_GetMsgDef(descriptor);
84
+ msg->arena = Qnil;
85
+ msg->msg = NULL;
74
86
 
75
87
  ret = TypedData_Wrap_Struct(klass, &Message_type, msg);
76
88
  rb_ivar_set(ret, descriptor_instancevar_interned, descriptor);
@@ -78,24 +90,92 @@ VALUE Message_alloc(VALUE klass) {
78
90
  return ret;
79
91
  }
80
92
 
81
- static const upb_fielddef* which_oneof_field(MessageHeader* self, const upb_oneofdef* o) {
82
- uint32_t oneof_case;
83
- const upb_fielddef* f;
93
+ const upb_msg *Message_Get(VALUE msg_rb, const upb_msgdef **m) {
94
+ Message* msg = ruby_to_Message(msg_rb);
95
+ if (m) *m = msg->msgdef;
96
+ return msg->msg;
97
+ }
98
+
99
+ upb_msg *Message_GetMutable(VALUE msg_rb, const upb_msgdef **m) {
100
+ rb_check_frozen(msg_rb);
101
+ return (upb_msg*)Message_Get(msg_rb, m);
102
+ }
103
+
104
+ void Message_InitPtr(VALUE self_, upb_msg *msg, VALUE arena) {
105
+ Message* self = ruby_to_Message(self_);
106
+ self->msg = msg;
107
+ self->arena = arena;
108
+ ObjectCache_Add(msg, self_, Arena_get(arena));
109
+ }
84
110
 
85
- oneof_case =
86
- slot_read_oneof_case(self->descriptor->layout, Message_data(self), o);
111
+ VALUE Message_GetArena(VALUE msg_rb) {
112
+ Message* msg = ruby_to_Message(msg_rb);
113
+ return msg->arena;
114
+ }
87
115
 
88
- if (oneof_case == ONEOF_CASE_NONE) {
89
- return NULL;
116
+ void Message_CheckClass(VALUE klass) {
117
+ if (rb_get_alloc_func(klass) != &Message_alloc) {
118
+ rb_raise(rb_eArgError,
119
+ "Message class was not returned by the DescriptorPool.");
90
120
  }
121
+ }
122
+
123
+ VALUE Message_GetRubyWrapper(upb_msg* msg, const upb_msgdef* m, VALUE arena) {
124
+ if (msg == NULL) return Qnil;
91
125
 
92
- // oneof_case is a field index, so find that field.
93
- f = upb_oneofdef_itof(o, oneof_case);
94
- assert(f != NULL);
126
+ VALUE val = ObjectCache_Get(msg);
95
127
 
96
- return f;
128
+ if (val == Qnil) {
129
+ VALUE klass = Descriptor_DefToClass(m);
130
+ val = Message_alloc(klass);
131
+ Message_InitPtr(val, msg, arena);
132
+ }
133
+
134
+ return val;
97
135
  }
98
136
 
137
+ void Message_PrintMessage(StringBuilder* b, const upb_msg* msg,
138
+ const upb_msgdef* m) {
139
+ bool first = true;
140
+ int n = upb_msgdef_fieldcount(m);
141
+ VALUE klass = Descriptor_DefToClass(m);
142
+ StringBuilder_Printf(b, "<%s: ", rb_class2name(klass));
143
+
144
+ for (int i = 0; i < n; i++) {
145
+ const upb_fielddef* field = upb_msgdef_field(m, i);
146
+
147
+ if (upb_fielddef_haspresence(field) && !upb_msg_has(msg, field)) {
148
+ continue;
149
+ }
150
+
151
+ if (!first) {
152
+ StringBuilder_Printf(b, ", ");
153
+ } else {
154
+ first = false;
155
+ }
156
+
157
+ upb_msgval msgval = upb_msg_get(msg, field);
158
+
159
+ StringBuilder_Printf(b, "%s: ", upb_fielddef_name(field));
160
+
161
+ if (upb_fielddef_ismap(field)) {
162
+ const upb_msgdef* entry_m = upb_fielddef_msgsubdef(field);
163
+ const upb_fielddef* key_f = upb_msgdef_itof(entry_m, 1);
164
+ const upb_fielddef* val_f = upb_msgdef_itof(entry_m, 2);
165
+ TypeInfo val_info = TypeInfo_get(val_f);
166
+ Map_Inspect(b, msgval.map_val, upb_fielddef_type(key_f), val_info);
167
+ } else if (upb_fielddef_isseq(field)) {
168
+ RepeatedField_Inspect(b, msgval.array_val, TypeInfo_get(field));
169
+ } else {
170
+ StringBuilder_PrintMsgval(b, msgval, TypeInfo_get(field));
171
+ }
172
+ }
173
+
174
+ StringBuilder_Printf(b, ">");
175
+ }
176
+
177
+ // Helper functions for #method_missing ////////////////////////////////////////
178
+
99
179
  enum {
100
180
  METHOD_UNKNOWN = 0,
101
181
  METHOD_GETTER = 1,
@@ -108,153 +188,203 @@ enum {
108
188
  };
109
189
 
110
190
  // Check if the field is a well known wrapper type
111
- bool is_wrapper_type_field(const upb_fielddef* field) {
112
- const upb_msgdef *m;
113
- if (upb_fielddef_type(field) != UPB_TYPE_MESSAGE) {
191
+ static bool IsWrapper(const upb_fielddef* f) {
192
+ return upb_fielddef_issubmsg(f) &&
193
+ upb_msgdef_iswrapper(upb_fielddef_msgsubdef(f));
194
+ }
195
+
196
+ static bool Match(const upb_msgdef* m, const char* name, const upb_fielddef** f,
197
+ const upb_oneofdef** o, const char* prefix,
198
+ const char* suffix) {
199
+ size_t sp = strlen(prefix);
200
+ size_t ss = strlen(suffix);
201
+ size_t sn = strlen(name);
202
+
203
+ if (sn <= sp + ss) return false;
204
+
205
+ if (memcmp(name, prefix, sp) != 0 ||
206
+ memcmp(name + sn - ss, suffix, ss) != 0) {
114
207
  return false;
115
208
  }
116
- m = upb_fielddef_msgsubdef(field);
117
- switch (upb_msgdef_wellknowntype(m)) {
118
- case UPB_WELLKNOWN_DOUBLEVALUE:
119
- case UPB_WELLKNOWN_FLOATVALUE:
120
- case UPB_WELLKNOWN_INT64VALUE:
121
- case UPB_WELLKNOWN_UINT64VALUE:
122
- case UPB_WELLKNOWN_INT32VALUE:
123
- case UPB_WELLKNOWN_UINT32VALUE:
124
- case UPB_WELLKNOWN_STRINGVALUE:
125
- case UPB_WELLKNOWN_BYTESVALUE:
126
- case UPB_WELLKNOWN_BOOLVALUE:
127
- return true;
128
- default:
129
- return false;
130
- }
209
+
210
+ return upb_msgdef_lookupname(m, name + sp, sn - sp - ss, f, o);
131
211
  }
132
212
 
133
- // Get a new Ruby wrapper type and set the initial value
134
- VALUE ruby_wrapper_type(VALUE type_class, VALUE value) {
135
- if (value != Qnil) {
136
- VALUE hash = rb_hash_new();
137
- rb_hash_aset(hash, rb_str_new2("value"), value);
138
- {
139
- VALUE args[1] = {hash};
140
- return rb_class_new_instance(1, args, type_class);
213
+ static int extract_method_call(VALUE method_name, Message* self,
214
+ const upb_fielddef** f, const upb_oneofdef** o) {
215
+ const upb_msgdef* m = self->msgdef;
216
+ const char* name;
217
+
218
+ Check_Type(method_name, T_SYMBOL);
219
+ name = rb_id2name(SYM2ID(method_name));
220
+
221
+ if (Match(m, name, f, o, "", "")) return METHOD_GETTER;
222
+ if (Match(m, name, f, o, "", "=")) return METHOD_SETTER;
223
+ if (Match(m, name, f, o, "clear_", "")) return METHOD_CLEAR;
224
+ if (Match(m, name, f, o, "has_", "?") &&
225
+ (*o || (*f && upb_fielddef_haspresence(*f)))) {
226
+ // Disallow oneof hazzers for proto3.
227
+ // TODO(haberman): remove this test when we are enabling oneof hazzers for
228
+ // proto3.
229
+ if (*f && !upb_fielddef_issubmsg(*f) &&
230
+ upb_fielddef_realcontainingoneof(*f) &&
231
+ upb_msgdef_syntax(upb_fielddef_containingtype(*f)) !=
232
+ UPB_SYNTAX_PROTO2) {
233
+ return METHOD_UNKNOWN;
141
234
  }
235
+ return METHOD_PRESENCE;
236
+ }
237
+ if (Match(m, name, f, o, "", "_as_value") && *f && !upb_fielddef_isseq(*f) &&
238
+ IsWrapper(*f)) {
239
+ return METHOD_WRAPPER_GETTER;
240
+ }
241
+ if (Match(m, name, f, o, "", "_as_value=") && *f && !upb_fielddef_isseq(*f) &&
242
+ IsWrapper(*f)) {
243
+ return METHOD_WRAPPER_SETTER;
244
+ }
245
+ if (Match(m, name, f, o, "", "_const") && *f &&
246
+ upb_fielddef_type(*f) == UPB_TYPE_ENUM) {
247
+ return METHOD_ENUM_GETTER;
142
248
  }
143
- return Qnil;
144
- }
145
249
 
146
- static int extract_method_call(VALUE method_name, MessageHeader* self,
147
- const upb_fielddef **f, const upb_oneofdef **o) {
148
- VALUE method_str;
149
- char* name;
150
- size_t name_len;
151
- int accessor_type;
152
- const upb_oneofdef* test_o;
153
- const upb_fielddef* test_f;
154
- bool has_field;
250
+ return METHOD_UNKNOWN;
251
+ }
155
252
 
156
- Check_Type(method_name, T_SYMBOL);
253
+ static VALUE Message_oneof_accessor(VALUE _self, const upb_oneofdef* o,
254
+ int accessor_type) {
255
+ Message* self = ruby_to_Message(_self);
256
+ const upb_fielddef* oneof_field = upb_msg_whichoneof(self->msg, o);
157
257
 
158
- method_str = rb_id2str(SYM2ID(method_name));
159
- name = RSTRING_PTR(method_str);
160
- name_len = RSTRING_LEN(method_str);
161
-
162
- if (name[name_len - 1] == '=') {
163
- accessor_type = METHOD_SETTER;
164
- name_len--;
165
- // We want to ensure if the proto has something named clear_foo or has_foo?,
166
- // we don't strip the prefix.
167
- } else if (strncmp("clear_", name, 6) == 0 &&
168
- !upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len,
169
- &test_f, &test_o)) {
170
- accessor_type = METHOD_CLEAR;
171
- name = name + 6;
172
- name_len = name_len - 6;
173
- } else if (strncmp("has_", name, 4) == 0 && name[name_len - 1] == '?' &&
174
- !upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len,
175
- &test_f, &test_o)) {
176
- accessor_type = METHOD_PRESENCE;
177
- name = name + 4;
178
- name_len = name_len - 5;
179
- } else {
180
- accessor_type = METHOD_GETTER;
181
- }
182
-
183
- has_field = upb_msgdef_lookupname(self->descriptor->msgdef, name, name_len,
184
- &test_f, &test_o);
185
-
186
- // Look for wrapper type accessor of the form <field_name>_as_value
187
- if (!has_field &&
188
- (accessor_type == METHOD_GETTER || accessor_type == METHOD_SETTER) &&
189
- name_len > 9 && strncmp(name + name_len - 9, "_as_value", 9) == 0) {
190
- const upb_oneofdef* test_o_wrapper;
191
- const upb_fielddef* test_f_wrapper;
192
- char wrapper_field_name[name_len - 8];
193
-
194
- // Find the field name
195
- strncpy(wrapper_field_name, name, name_len - 9);
196
- wrapper_field_name[name_len - 9] = '\0';
197
-
198
- // Check if field exists and is a wrapper type
199
- if (upb_msgdef_lookupname(self->descriptor->msgdef, wrapper_field_name,
200
- name_len - 9, &test_f_wrapper, &test_o_wrapper) &&
201
- is_wrapper_type_field(test_f_wrapper)) {
202
- // It does exist!
203
- has_field = true;
204
- if (accessor_type == METHOD_SETTER) {
205
- accessor_type = METHOD_WRAPPER_SETTER;
206
- } else {
207
- accessor_type = METHOD_WRAPPER_GETTER;
258
+ switch (accessor_type) {
259
+ case METHOD_PRESENCE:
260
+ return oneof_field == NULL ? Qfalse : Qtrue;
261
+ case METHOD_CLEAR:
262
+ if (oneof_field != NULL) {
263
+ upb_msg_clearfield(Message_GetMutable(_self, NULL), oneof_field);
208
264
  }
209
- test_o = test_o_wrapper;
210
- test_f = test_f_wrapper;
211
- }
265
+ return Qnil;
266
+ case METHOD_GETTER:
267
+ return oneof_field == NULL
268
+ ? Qnil
269
+ : ID2SYM(rb_intern(upb_fielddef_name(oneof_field)));
270
+ case METHOD_SETTER:
271
+ rb_raise(rb_eRuntimeError, "Oneof accessors are read-only.");
212
272
  }
273
+ rb_raise(rb_eRuntimeError, "Invalid access of oneof field.");
274
+ }
213
275
 
214
- // Look for enum accessor of the form <enum_name>_const
215
- if (!has_field && accessor_type == METHOD_GETTER &&
216
- name_len > 6 && strncmp(name + name_len - 6, "_const", 6) == 0) {
217
- const upb_oneofdef* test_o_enum;
218
- const upb_fielddef* test_f_enum;
219
- char enum_name[name_len - 5];
220
-
221
- // Find enum field name
222
- strncpy(enum_name, name, name_len - 6);
223
- enum_name[name_len - 6] = '\0';
224
-
225
- // Check if enum field exists
226
- if (upb_msgdef_lookupname(self->descriptor->msgdef, enum_name, name_len - 6,
227
- &test_f_enum, &test_o_enum) &&
228
- upb_fielddef_type(test_f_enum) == UPB_TYPE_ENUM) {
229
- // It does exist!
230
- has_field = true;
231
- accessor_type = METHOD_ENUM_GETTER;
232
- test_o = test_o_enum;
233
- test_f = test_f_enum;
276
+ static void Message_setfield(upb_msg* msg, const upb_fielddef* f, VALUE val,
277
+ upb_arena* arena) {
278
+ upb_msgval msgval;
279
+ if (upb_fielddef_ismap(f)) {
280
+ msgval.map_val = Map_GetUpbMap(val, f);
281
+ } else if (upb_fielddef_isseq(f)) {
282
+ msgval.array_val = RepeatedField_GetUpbArray(val, f);
283
+ } else {
284
+ if (val == Qnil &&
285
+ (upb_fielddef_issubmsg(f) || upb_fielddef_realcontainingoneof(f))) {
286
+ upb_msg_clearfield(msg, f);
287
+ return;
234
288
  }
289
+ msgval =
290
+ Convert_RubyToUpb(val, upb_fielddef_name(f), TypeInfo_get(f), arena);
235
291
  }
292
+ upb_msg_set(msg, f, msgval, arena);
293
+ }
236
294
 
237
- // Verify the name corresponds to a oneof or field in this message.
238
- if (!has_field) {
239
- return METHOD_UNKNOWN;
295
+ VALUE Message_getfield(VALUE _self, const upb_fielddef* f) {
296
+ Message* self = ruby_to_Message(_self);
297
+ // This is a special-case: upb_msg_mutable() for map & array are logically
298
+ // const (they will not change what is serialized) but physically
299
+ // non-const, as they do allocate a repeated field or map. The logical
300
+ // constness means it's ok to do even if the message is frozen.
301
+ upb_msg *msg = (upb_msg*)self->msg;
302
+ upb_arena *arena = Arena_get(self->arena);
303
+ if (upb_fielddef_ismap(f)) {
304
+ upb_map *map = upb_msg_mutable(msg, f, arena).map;
305
+ const upb_fielddef *key_f = map_field_key(f);
306
+ const upb_fielddef *val_f = map_field_value(f);
307
+ upb_fieldtype_t key_type = upb_fielddef_type(key_f);
308
+ TypeInfo value_type_info = TypeInfo_get(val_f);
309
+ return Map_GetRubyWrapper(map, key_type, value_type_info, self->arena);
310
+ } else if (upb_fielddef_isseq(f)) {
311
+ upb_array *arr = upb_msg_mutable(msg, f, arena).array;
312
+ return RepeatedField_GetRubyWrapper(arr, TypeInfo_get(f), self->arena);
313
+ } else if (upb_fielddef_issubmsg(f)) {
314
+ if (!upb_msg_has(self->msg, f)) return Qnil;
315
+ upb_msg *submsg = upb_msg_mutable(msg, f, arena).msg;
316
+ const upb_msgdef *m = upb_fielddef_msgsubdef(f);
317
+ return Message_GetRubyWrapper(submsg, m, self->arena);
318
+ } else {
319
+ upb_msgval msgval = upb_msg_get(self->msg, f);
320
+ return Convert_UpbToRuby(msgval, TypeInfo_get(f), self->arena);
240
321
  }
322
+ }
241
323
 
242
- // Method calls like 'has_foo?' are not allowed if field "foo" does not have
243
- // a hasbit (e.g. repeated fields or non-message type fields for proto3
244
- // syntax).
245
- if (accessor_type == METHOD_PRESENCE && test_f != NULL) {
246
- if (!upb_fielddef_haspresence(test_f)) return METHOD_UNKNOWN;
324
+ static VALUE Message_field_accessor(VALUE _self, const upb_fielddef* f,
325
+ int accessor_type, int argc, VALUE* argv) {
326
+ upb_arena *arena = Arena_get(Message_GetArena(_self));
247
327
 
248
- // TODO(haberman): remove this case, allow for proto3 oneofs.
249
- if (upb_fielddef_realcontainingoneof(test_f) &&
250
- upb_filedef_syntax(upb_fielddef_file(test_f)) == UPB_SYNTAX_PROTO3) {
251
- return METHOD_UNKNOWN;
328
+ switch (accessor_type) {
329
+ case METHOD_SETTER:
330
+ Message_setfield(Message_GetMutable(_self, NULL), f, argv[1], arena);
331
+ return Qnil;
332
+ case METHOD_CLEAR:
333
+ upb_msg_clearfield(Message_GetMutable(_self, NULL), f);
334
+ return Qnil;
335
+ case METHOD_PRESENCE:
336
+ if (!upb_fielddef_haspresence(f)) {
337
+ rb_raise(rb_eRuntimeError, "Field does not have presence.");
338
+ }
339
+ return upb_msg_has(Message_Get(_self, NULL), f);
340
+ case METHOD_WRAPPER_GETTER: {
341
+ Message* self = ruby_to_Message(_self);
342
+ if (upb_msg_has(self->msg, f)) {
343
+ PBRUBY_ASSERT(upb_fielddef_issubmsg(f) && !upb_fielddef_isseq(f));
344
+ upb_msgval wrapper = upb_msg_get(self->msg, f);
345
+ const upb_msgdef *wrapper_m = upb_fielddef_msgsubdef(f);
346
+ const upb_fielddef *value_f = upb_msgdef_itof(wrapper_m, 1);
347
+ upb_msgval value = upb_msg_get(wrapper.msg_val, value_f);
348
+ return Convert_UpbToRuby(value, TypeInfo_get(value_f), self->arena);
349
+ } else {
350
+ return Qnil;
351
+ }
352
+ }
353
+ case METHOD_WRAPPER_SETTER: {
354
+ upb_msg *msg = Message_GetMutable(_self, NULL);
355
+ if (argv[1] == Qnil) {
356
+ upb_msg_clearfield(msg, f);
357
+ } else {
358
+ const upb_fielddef *val_f = upb_msgdef_itof(upb_fielddef_msgsubdef(f), 1);
359
+ upb_msgval msgval = Convert_RubyToUpb(argv[1], upb_fielddef_name(f),
360
+ TypeInfo_get(val_f), arena);
361
+ upb_msg *wrapper = upb_msg_mutable(msg, f, arena).msg;
362
+ upb_msg_set(wrapper, val_f, msgval, arena);
363
+ }
364
+ return Qnil;
365
+ }
366
+ case METHOD_ENUM_GETTER: {
367
+ upb_msgval msgval = upb_msg_get(Message_Get(_self, NULL), f);
368
+
369
+ if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
370
+ // Map repeated fields to a new type with ints
371
+ VALUE arr = rb_ary_new();
372
+ size_t i, n = upb_array_size(msgval.array_val);
373
+ for (i = 0; i < n; i++) {
374
+ upb_msgval elem = upb_array_get(msgval.array_val, i);
375
+ rb_ary_push(arr, INT2NUM(elem.int32_val));
376
+ }
377
+ return arr;
378
+ } else {
379
+ return INT2NUM(msgval.int32_val);
380
+ }
252
381
  }
382
+ case METHOD_GETTER:
383
+ return Message_getfield(_self, f);
384
+ default:
385
+ rb_raise(rb_eRuntimeError, "Internal error, no such accessor: %d",
386
+ accessor_type);
253
387
  }
254
-
255
- *o = test_o;
256
- *f = test_f;
257
- return accessor_type;
258
388
  }
259
389
 
260
390
  /*
@@ -284,111 +414,56 @@ static int extract_method_call(VALUE method_name, MessageHeader* self,
284
414
  * true if the field 'fieldname' is set in the message object, else false. For
285
415
  * 'proto3' syntax, calling this for a basic type field will result in an error.
286
416
  */
287
- VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self) {
288
- MessageHeader* self;
417
+ static VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self) {
418
+ Message* self = ruby_to_Message(_self);
289
419
  const upb_oneofdef* o;
290
420
  const upb_fielddef* f;
291
421
  int accessor_type;
292
422
 
293
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
294
423
  if (argc < 1) {
295
424
  rb_raise(rb_eArgError, "Expected method name as first argument.");
296
425
  }
297
426
 
298
427
  accessor_type = extract_method_call(argv[0], self, &f, &o);
299
- if (accessor_type == METHOD_UNKNOWN || (o == NULL && f == NULL) ) {
300
- return rb_call_super(argc, argv);
301
- } else if (accessor_type == METHOD_SETTER || accessor_type == METHOD_WRAPPER_SETTER) {
302
- if (argc != 2) {
303
- rb_raise(rb_eArgError, "Expected 2 arguments, received %d", argc);
304
- }
305
- rb_check_frozen(_self);
306
- } else if (argc != 1) {
307
- rb_raise(rb_eArgError, "Expected 1 argument, received %d", argc);
308
- }
309
428
 
310
- // Return which of the oneof fields are set
311
- if (o != NULL) {
312
- const upb_fielddef* oneof_field = which_oneof_field(self, o);
429
+ if (accessor_type == METHOD_UNKNOWN) return rb_call_super(argc, argv);
313
430
 
314
- if (accessor_type == METHOD_SETTER) {
315
- rb_raise(rb_eRuntimeError, "Oneof accessors are read-only.");
316
- }
317
-
318
- if (accessor_type == METHOD_PRESENCE) {
319
- return oneof_field == NULL ? Qfalse : Qtrue;
320
- } else if (accessor_type == METHOD_CLEAR) {
321
- if (oneof_field != NULL) {
322
- layout_clear(self->descriptor->layout, Message_data(self), oneof_field);
431
+ // Validate argument count.
432
+ switch (accessor_type) {
433
+ case METHOD_SETTER:
434
+ case METHOD_WRAPPER_SETTER:
435
+ if (argc != 2) {
436
+ rb_raise(rb_eArgError, "Expected 2 arguments, received %d", argc);
323
437
  }
324
- return Qnil;
325
- } else {
326
- // METHOD_ACCESSOR
327
- return oneof_field == NULL ? Qnil :
328
- ID2SYM(rb_intern(upb_fielddef_name(oneof_field)));
329
- }
330
- // Otherwise we're operating on a single proto field
331
- } else if (accessor_type == METHOD_SETTER) {
332
- layout_set(self->descriptor->layout, Message_data(self), f, argv[1]);
333
- return Qnil;
334
- } else if (accessor_type == METHOD_CLEAR) {
335
- layout_clear(self->descriptor->layout, Message_data(self), f);
336
- return Qnil;
337
- } else if (accessor_type == METHOD_PRESENCE) {
338
- return layout_has(self->descriptor->layout, Message_data(self), f);
339
- } else if (accessor_type == METHOD_WRAPPER_GETTER) {
340
- VALUE value = layout_get(self->descriptor->layout, Message_data(self), f);
341
- switch (TYPE(value)) {
342
- case T_DATA:
343
- return rb_funcall(value, rb_intern("value"), 0);
344
- case T_NIL:
345
- return Qnil;
346
- default:
347
- return value;
348
- }
349
- } else if (accessor_type == METHOD_WRAPPER_SETTER) {
350
- VALUE wrapper = ruby_wrapper_type(
351
- field_type_class(self->descriptor->layout, f), argv[1]);
352
- layout_set(self->descriptor->layout, Message_data(self), f, wrapper);
353
- return Qnil;
354
- } else if (accessor_type == METHOD_ENUM_GETTER) {
355
- VALUE enum_type = field_type_class(self->descriptor->layout, f);
356
- VALUE method = rb_intern("const_get");
357
- VALUE raw_value = layout_get(self->descriptor->layout, Message_data(self), f);
358
-
359
- // Map repeated fields to a new type with ints
360
- if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
361
- int array_size = FIX2INT(rb_funcall(raw_value, rb_intern("length"), 0));
362
- int i;
363
- VALUE array_args[1] = { ID2SYM(rb_intern("int64")) };
364
- VALUE array = rb_class_new_instance(1, array_args, CLASS_OF(raw_value));
365
- for (i = 0; i < array_size; i++) {
366
- VALUE entry = rb_funcall(enum_type, method, 1, rb_funcall(raw_value,
367
- rb_intern("at"), 1, INT2NUM(i)));
368
- rb_funcall(array, rb_intern("push"), 1, entry);
438
+ rb_check_frozen(_self);
439
+ break;
440
+ default:
441
+ if (argc != 1) {
442
+ rb_raise(rb_eArgError, "Expected 1 argument, received %d", argc);
369
443
  }
370
- return array;
371
- }
372
- // Convert the value for singular fields
373
- return rb_funcall(enum_type, method, 1, raw_value);
444
+ break;
445
+ }
446
+
447
+ // Dispatch accessor.
448
+ if (o != NULL) {
449
+ return Message_oneof_accessor(_self, o, accessor_type);
374
450
  } else {
375
- return layout_get(self->descriptor->layout, Message_data(self), f);
451
+ return Message_field_accessor(_self, f, accessor_type, argc, argv);
376
452
  }
377
453
  }
378
454
 
379
-
380
- VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
381
- MessageHeader* self;
455
+ static VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
456
+ Message* self = ruby_to_Message(_self);
382
457
  const upb_oneofdef* o;
383
458
  const upb_fielddef* f;
384
459
  int accessor_type;
385
460
 
386
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
387
461
  if (argc < 1) {
388
462
  rb_raise(rb_eArgError, "Expected method name as first argument.");
389
463
  }
390
464
 
391
465
  accessor_type = extract_method_call(argv[0], self, &f, &o);
466
+
392
467
  if (accessor_type == METHOD_UNKNOWN) {
393
468
  return rb_call_super(argc, argv);
394
469
  } else if (o != NULL) {
@@ -398,17 +473,116 @@ VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
398
473
  }
399
474
  }
400
475
 
401
- VALUE create_submsg_from_hash(const MessageLayout* layout,
402
- const upb_fielddef* f, VALUE hash) {
403
- VALUE args[1] = { hash };
404
- return rb_class_new_instance(1, args, field_type_class(layout, f));
476
+ void Message_InitFromValue(upb_msg* msg, const upb_msgdef* m, VALUE val,
477
+ upb_arena* arena);
478
+
479
+ typedef struct {
480
+ upb_map *map;
481
+ TypeInfo key_type;
482
+ TypeInfo val_type;
483
+ upb_arena *arena;
484
+ } MapInit;
485
+
486
+ static int Map_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
487
+ MapInit *map_init = (MapInit*)_self;
488
+ upb_msgval k, v;
489
+ k = Convert_RubyToUpb(key, "", map_init->key_type, NULL);
490
+
491
+ if (map_init->val_type.type == UPB_TYPE_MESSAGE && TYPE(val) == T_HASH) {
492
+ upb_msg *msg = upb_msg_new(map_init->val_type.def.msgdef, map_init->arena);
493
+ Message_InitFromValue(msg, map_init->val_type.def.msgdef, val,
494
+ map_init->arena);
495
+ v.msg_val = msg;
496
+ } else {
497
+ v = Convert_RubyToUpb(val, "", map_init->val_type, map_init->arena);
498
+ }
499
+ upb_map_set(map_init->map, k, v, map_init->arena);
500
+ return ST_CONTINUE;
405
501
  }
406
502
 
407
- int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
408
- MessageHeader* self;
409
- char *name;
410
- const upb_fielddef* f;
411
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
503
+ static void Map_InitFromValue(upb_map* map, const upb_fielddef* f, VALUE val,
504
+ upb_arena* arena) {
505
+ const upb_msgdef* entry_m = upb_fielddef_msgsubdef(f);
506
+ const upb_fielddef* key_f = upb_msgdef_itof(entry_m, 1);
507
+ const upb_fielddef* val_f = upb_msgdef_itof(entry_m, 2);
508
+ if (TYPE(val) != T_HASH) {
509
+ rb_raise(rb_eArgError,
510
+ "Expected Hash object as initializer value for map field '%s' "
511
+ "(given %s).",
512
+ upb_fielddef_name(f), rb_class2name(CLASS_OF(val)));
513
+ }
514
+ MapInit map_init = {map, TypeInfo_get(key_f), TypeInfo_get(val_f), arena};
515
+ rb_hash_foreach(val, Map_initialize_kwarg, (VALUE)&map_init);
516
+ }
517
+
518
+ static upb_msgval MessageValue_FromValue(VALUE val, TypeInfo info,
519
+ upb_arena* arena) {
520
+ if (info.type == UPB_TYPE_MESSAGE) {
521
+ upb_msgval msgval;
522
+ upb_msg* msg = upb_msg_new(info.def.msgdef, arena);
523
+ Message_InitFromValue(msg, info.def.msgdef, val, arena);
524
+ msgval.msg_val = msg;
525
+ return msgval;
526
+ } else {
527
+ return Convert_RubyToUpb(val, "", info, arena);
528
+ }
529
+ }
530
+
531
+ static void RepeatedField_InitFromValue(upb_array* arr, const upb_fielddef* f,
532
+ VALUE val, upb_arena* arena) {
533
+ TypeInfo type_info = TypeInfo_get(f);
534
+
535
+ if (TYPE(val) != T_ARRAY) {
536
+ rb_raise(rb_eArgError,
537
+ "Expected array as initializer value for repeated field '%s' (given %s).",
538
+ upb_fielddef_name(f), rb_class2name(CLASS_OF(val)));
539
+ }
540
+
541
+ for (int i = 0; i < RARRAY_LEN(val); i++) {
542
+ VALUE entry = rb_ary_entry(val, i);
543
+ upb_msgval msgval;
544
+ if (upb_fielddef_issubmsg(f) && TYPE(entry) == T_HASH) {
545
+ msgval = MessageValue_FromValue(entry, type_info, arena);
546
+ } else {
547
+ msgval = Convert_RubyToUpb(entry, upb_fielddef_name(f), type_info, arena);
548
+ }
549
+ upb_array_append(arr, msgval, arena);
550
+ }
551
+ }
552
+
553
+ static void Message_InitFieldFromValue(upb_msg* msg, const upb_fielddef* f,
554
+ VALUE val, upb_arena* arena) {
555
+ if (TYPE(val) == T_NIL) return;
556
+
557
+ if (upb_fielddef_ismap(f)) {
558
+ upb_map *map = upb_msg_mutable(msg, f, arena).map;
559
+ Map_InitFromValue(map, f, val, arena);
560
+ } else if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
561
+ upb_array *arr = upb_msg_mutable(msg, f, arena).array;
562
+ RepeatedField_InitFromValue(arr, f, val, arena);
563
+ } else if (upb_fielddef_issubmsg(f)) {
564
+ if (TYPE(val) == T_HASH) {
565
+ upb_msg *submsg = upb_msg_mutable(msg, f, arena).msg;
566
+ Message_InitFromValue(submsg, upb_fielddef_msgsubdef(f), val, arena);
567
+ } else {
568
+ Message_setfield(msg, f, val, arena);
569
+ }
570
+ } else {
571
+ upb_msgval msgval =
572
+ Convert_RubyToUpb(val, upb_fielddef_name(f), TypeInfo_get(f), arena);
573
+ upb_msg_set(msg, f, msgval, arena);
574
+ }
575
+ }
576
+
577
+ typedef struct {
578
+ upb_msg *msg;
579
+ const upb_msgdef *msgdef;
580
+ upb_arena *arena;
581
+ } MsgInit;
582
+
583
+ static int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
584
+ MsgInit *msg_init = (MsgInit*)_self;
585
+ const char *name;
412
586
 
413
587
  if (TYPE(key) == T_STRING) {
414
588
  name = RSTRING_PTR(key);
@@ -419,52 +593,26 @@ int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
419
593
  "Expected string or symbols as hash keys when initializing proto from hash.");
420
594
  }
421
595
 
422
- f = upb_msgdef_ntofz(self->descriptor->msgdef, name);
596
+ const upb_fielddef* f = upb_msgdef_ntofz(msg_init->msgdef, name);
597
+
423
598
  if (f == NULL) {
424
599
  rb_raise(rb_eArgError,
425
600
  "Unknown field name '%s' in initialization map entry.", name);
426
601
  }
427
602
 
428
- if (TYPE(val) == T_NIL) {
429
- return 0;
430
- }
431
-
432
- if (is_map_field(f)) {
433
- VALUE map;
434
-
435
- if (TYPE(val) != T_HASH) {
436
- rb_raise(rb_eArgError,
437
- "Expected Hash object as initializer value for map field '%s' (given %s).",
438
- name, rb_class2name(CLASS_OF(val)));
439
- }
440
- map = layout_get(self->descriptor->layout, Message_data(self), f);
441
- Map_merge_into_self(map, val);
442
- } else if (upb_fielddef_label(f) == UPB_LABEL_REPEATED) {
443
- VALUE ary;
444
- int i;
445
-
446
- if (TYPE(val) != T_ARRAY) {
447
- rb_raise(rb_eArgError,
448
- "Expected array as initializer value for repeated field '%s' (given %s).",
449
- name, rb_class2name(CLASS_OF(val)));
450
- }
451
- ary = layout_get(self->descriptor->layout, Message_data(self), f);
452
- for (i = 0; i < RARRAY_LEN(val); i++) {
453
- VALUE entry = rb_ary_entry(val, i);
454
- if (TYPE(entry) == T_HASH && upb_fielddef_issubmsg(f)) {
455
- entry = create_submsg_from_hash(self->descriptor->layout, f, entry);
456
- }
603
+ Message_InitFieldFromValue(msg_init->msg, f, val, msg_init->arena);
604
+ return ST_CONTINUE;
605
+ }
457
606
 
458
- RepeatedField_push(ary, entry);
459
- }
607
+ void Message_InitFromValue(upb_msg* msg, const upb_msgdef* m, VALUE val,
608
+ upb_arena* arena) {
609
+ MsgInit msg_init = {msg, m, arena};
610
+ if (TYPE(val) == T_HASH) {
611
+ rb_hash_foreach(val, Message_initialize_kwarg, (VALUE)&msg_init);
460
612
  } else {
461
- if (TYPE(val) == T_HASH && upb_fielddef_issubmsg(f)) {
462
- val = create_submsg_from_hash(self->descriptor->layout, f, val);
463
- }
464
-
465
- layout_set(self->descriptor->layout, Message_data(self), f, val);
613
+ rb_raise(rb_eArgError, "Expected hash arguments or message, not %s",
614
+ rb_class2name(CLASS_OF(val)));
466
615
  }
467
- return 0;
468
616
  }
469
617
 
470
618
  /*
@@ -479,12 +627,13 @@ int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
479
627
  * have been added to a pool. The method definitions described here on the
480
628
  * Message class are provided on each concrete message class.
481
629
  */
482
- VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
483
- MessageHeader* self;
484
- VALUE hash_args;
485
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
630
+ static VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
631
+ Message* self = ruby_to_Message(_self);
632
+ VALUE arena_rb = Arena_new();
633
+ upb_arena *arena = Arena_get(arena_rb);
634
+ upb_msg *msg = upb_msg_new(self->msgdef, arena);
486
635
 
487
- layout_init(self->descriptor->layout, Message_data(self));
636
+ Message_InitPtr(_self, msg, arena_rb);
488
637
 
489
638
  if (argc == 0) {
490
639
  return Qnil;
@@ -492,12 +641,7 @@ VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
492
641
  if (argc != 1) {
493
642
  rb_raise(rb_eArgError, "Expected 0 or 1 arguments.");
494
643
  }
495
- hash_args = argv[0];
496
- if (TYPE(hash_args) != T_HASH) {
497
- rb_raise(rb_eArgError, "Expected hash arguments.");
498
- }
499
-
500
- rb_hash_foreach(hash_args, Message_initialize_kwarg, _self);
644
+ Message_InitFromValue((upb_msg*)self->msg, self->msgdef, argv[0], arena);
501
645
  return Qnil;
502
646
  }
503
647
 
@@ -507,37 +651,40 @@ VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
507
651
  *
508
652
  * Performs a shallow copy of this message and returns the new copy.
509
653
  */
510
- VALUE Message_dup(VALUE _self) {
511
- MessageHeader* self;
512
- VALUE new_msg;
513
- MessageHeader* new_msg_self;
514
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
515
-
516
- new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
517
- TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
518
-
519
- layout_dup(self->descriptor->layout,
520
- Message_data(new_msg_self),
521
- Message_data(self));
522
-
654
+ static VALUE Message_dup(VALUE _self) {
655
+ Message* self = ruby_to_Message(_self);
656
+ VALUE new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
657
+ Message* new_msg_self = ruby_to_Message(new_msg);
658
+ size_t size = upb_msgdef_layout(self->msgdef)->size;
659
+
660
+ // TODO(copy unknown fields?)
661
+ // TODO(use official upb msg copy function)
662
+ memcpy((upb_msg*)new_msg_self->msg, self->msg, size);
663
+ upb_arena_fuse(Arena_get(new_msg_self->arena), Arena_get(self->arena));
523
664
  return new_msg;
524
665
  }
525
666
 
526
- // Internal only; used by Google::Protobuf.deep_copy.
527
- VALUE Message_deep_copy(VALUE _self) {
528
- MessageHeader* self;
529
- MessageHeader* new_msg_self;
530
- VALUE new_msg;
531
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
667
+ // Support function for Message_eq, and also used by other #eq functions.
668
+ bool Message_Equal(const upb_msg *m1, const upb_msg *m2, const upb_msgdef *m) {
669
+ if (m1 == m2) return true;
532
670
 
533
- new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
534
- TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
671
+ size_t size1, size2;
672
+ int encode_opts = UPB_ENCODE_SKIPUNKNOWN | UPB_ENCODE_DETERMINISTIC;
673
+ upb_arena *arena_tmp = upb_arena_new();
674
+ const upb_msglayout *layout = upb_msgdef_layout(m);
535
675
 
536
- layout_deep_copy(self->descriptor->layout,
537
- Message_data(new_msg_self),
538
- Message_data(self));
676
+ // Compare deterministically serialized payloads with no unknown fields.
677
+ char *data1 = upb_encode_ex(m1, layout, encode_opts, arena_tmp, &size1);
678
+ char *data2 = upb_encode_ex(m2, layout, encode_opts, arena_tmp, &size2);
539
679
 
540
- return new_msg;
680
+ if (data1 && data2) {
681
+ bool ret = (size1 == size2) && (memcmp(data1, data2, size1) == 0);
682
+ upb_arena_free(arena_tmp);
683
+ return ret;
684
+ } else {
685
+ upb_arena_free(arena_tmp);
686
+ rb_raise(cParseError, "Error comparing messages");
687
+ }
541
688
  }
542
689
 
543
690
  /*
@@ -549,22 +696,37 @@ VALUE Message_deep_copy(VALUE _self) {
549
696
  * method's semantics (a more efficient comparison may actually be done if the
550
697
  * field is of a primitive type).
551
698
  */
552
- VALUE Message_eq(VALUE _self, VALUE _other) {
553
- MessageHeader* self;
554
- MessageHeader* other;
699
+ static VALUE Message_eq(VALUE _self, VALUE _other) {
555
700
  if (TYPE(_self) != TYPE(_other)) {
556
701
  return Qfalse;
557
702
  }
558
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
559
- TypedData_Get_Struct(_other, MessageHeader, &Message_type, other);
560
703
 
561
- if (self->descriptor != other->descriptor) {
562
- return Qfalse;
563
- }
704
+ Message* self = ruby_to_Message(_self);
705
+ Message* other = ruby_to_Message(_other);
706
+
707
+ return Message_Equal(self->msg, other->msg, self->msgdef)
708
+ ? Qtrue
709
+ : Qfalse;
710
+ }
711
+
712
+ uint64_t Message_Hash(const upb_msg* msg, const upb_msgdef* m, uint64_t seed) {
713
+ upb_arena *arena = upb_arena_new();
714
+ const char *data;
715
+ size_t size;
564
716
 
565
- return layout_eq(self->descriptor->layout,
566
- Message_data(self),
567
- Message_data(other));
717
+ // Hash a deterministically serialized payloads with no unknown fields.
718
+ data = upb_encode_ex(msg, upb_msgdef_layout(m),
719
+ UPB_ENCODE_SKIPUNKNOWN | UPB_ENCODE_DETERMINISTIC, arena,
720
+ &size);
721
+
722
+ if (data) {
723
+ uint64_t ret = wyhash(data, size, seed, _wyp);
724
+ upb_arena_free(arena);
725
+ return ret;
726
+ } else {
727
+ upb_arena_free(arena);
728
+ rb_raise(cParseError, "Error calculating hash");
729
+ }
568
730
  }
569
731
 
570
732
  /*
@@ -573,11 +735,9 @@ VALUE Message_eq(VALUE _self, VALUE _other) {
573
735
  *
574
736
  * Returns a hash value that represents this message's field values.
575
737
  */
576
- VALUE Message_hash(VALUE _self) {
577
- MessageHeader* self;
578
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
579
-
580
- return layout_hash(self->descriptor->layout, Message_data(self));
738
+ static VALUE Message_hash(VALUE _self) {
739
+ Message* self = ruby_to_Message(_self);
740
+ return INT2FIX(Message_Hash(self->msg, self->msgdef, 0));
581
741
  }
582
742
 
583
743
  /*
@@ -588,81 +748,117 @@ VALUE Message_hash(VALUE _self) {
588
748
  * formatted as "<MessageType: field1: value1, field2: value2, ...>". Each
589
749
  * field's value is represented according to its own #inspect method.
590
750
  */
591
- VALUE Message_inspect(VALUE _self) {
592
- MessageHeader* self;
593
- VALUE str;
594
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
751
+ static VALUE Message_inspect(VALUE _self) {
752
+ Message* self = ruby_to_Message(_self);
753
+
754
+ StringBuilder* builder = StringBuilder_New();
755
+ Message_PrintMessage(builder, self->msg, self->msgdef);
756
+ VALUE ret = StringBuilder_ToRubyString(builder);
757
+ StringBuilder_Free(builder);
758
+ return ret;
759
+ }
760
+
761
+ // Support functions for Message_to_h //////////////////////////////////////////
762
+
763
+ static VALUE RepeatedField_CreateArray(const upb_array* arr,
764
+ TypeInfo type_info) {
765
+ int size = arr ? upb_array_size(arr) : 0;
766
+ VALUE ary = rb_ary_new2(size);
767
+
768
+ for (int i = 0; i < size; i++) {
769
+ upb_msgval msgval = upb_array_get(arr, i);
770
+ VALUE val = Scalar_CreateHash(msgval, type_info);
771
+ rb_ary_push(ary, val);
772
+ }
595
773
 
596
- str = rb_str_new2("<");
597
- str = rb_str_append(str, rb_str_new2(rb_class2name(CLASS_OF(_self))));
598
- str = rb_str_cat2(str, ": ");
599
- str = rb_str_append(str, layout_inspect(
600
- self->descriptor->layout, Message_data(self)));
601
- str = rb_str_cat2(str, ">");
602
- return str;
774
+ return ary;
603
775
  }
604
776
 
605
- /*
606
- * call-seq:
607
- * Message.to_h => {}
608
- *
609
- * Returns the message as a Ruby Hash object, with keys as symbols.
610
- */
611
- VALUE Message_to_h(VALUE _self) {
612
- MessageHeader* self;
777
+ static VALUE Message_CreateHash(const upb_msg *msg, const upb_msgdef *m) {
778
+ if (!msg) return Qnil;
779
+
613
780
  VALUE hash = rb_hash_new();
614
- upb_msg_field_iter it;
781
+ int n = upb_msgdef_fieldcount(m);
615
782
  bool is_proto2;
616
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
617
783
 
618
784
  // We currently have a few behaviors that are specific to proto2.
619
785
  // This is unfortunate, we should key behaviors off field attributes (like
620
786
  // whether a field has presence), not proto2 vs. proto3. We should see if we
621
787
  // can change this without breaking users.
622
- is_proto2 =
623
- upb_msgdef_syntax(self->descriptor->msgdef) == UPB_SYNTAX_PROTO2;
788
+ is_proto2 = upb_msgdef_syntax(m) == UPB_SYNTAX_PROTO2;
624
789
 
625
- for (upb_msg_field_begin(&it, self->descriptor->msgdef);
626
- !upb_msg_field_done(&it);
627
- upb_msg_field_next(&it)) {
628
- const upb_fielddef* field = upb_msg_iter_field(&it);
790
+ for (int i = 0; i < n; i++) {
791
+ const upb_fielddef* field = upb_msgdef_field(m, i);
792
+ TypeInfo type_info = TypeInfo_get(field);
793
+ upb_msgval msgval;
629
794
  VALUE msg_value;
630
795
  VALUE msg_key;
631
796
 
632
797
  // Do not include fields that are not present (oneof or optional fields).
633
798
  if (is_proto2 && upb_fielddef_haspresence(field) &&
634
- !layout_has(self->descriptor->layout, Message_data(self), field)) {
799
+ !upb_msg_has(msg, field)) {
635
800
  continue;
636
801
  }
637
802
 
638
- msg_value = layout_get(self->descriptor->layout, Message_data(self), field);
639
803
  msg_key = ID2SYM(rb_intern(upb_fielddef_name(field)));
640
- if (is_map_field(field)) {
641
- msg_value = Map_to_h(msg_value);
642
- } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
643
- msg_value = RepeatedField_to_ary(msg_value);
644
- if (is_proto2 && RARRAY_LEN(msg_value) == 0) {
804
+ msgval = upb_msg_get(msg, field);
805
+
806
+ // Proto2 omits empty map/repeated filds also.
807
+
808
+ if (upb_fielddef_ismap(field)) {
809
+ const upb_msgdef *entry_m = upb_fielddef_msgsubdef(field);
810
+ const upb_fielddef *key_f = upb_msgdef_itof(entry_m, 1);
811
+ const upb_fielddef *val_f = upb_msgdef_itof(entry_m, 2);
812
+ upb_fieldtype_t key_type = upb_fielddef_type(key_f);
813
+ msg_value = Map_CreateHash(msgval.map_val, key_type, TypeInfo_get(val_f));
814
+ } else if (upb_fielddef_isseq(field)) {
815
+ if (is_proto2 &&
816
+ (!msgval.array_val || upb_array_size(msgval.array_val) == 0)) {
645
817
  continue;
646
818
  }
647
-
648
- if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
649
- int i;
650
- for (i = 0; i < RARRAY_LEN(msg_value); i++) {
651
- VALUE elem = rb_ary_entry(msg_value, i);
652
- rb_ary_store(msg_value, i, Message_to_h(elem));
653
- }
654
- }
655
-
656
- } else if (msg_value != Qnil &&
657
- upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
658
- msg_value = Message_to_h(msg_value);
819
+ msg_value = RepeatedField_CreateArray(msgval.array_val, type_info);
820
+ } else {
821
+ msg_value = Scalar_CreateHash(msgval, type_info);
659
822
  }
823
+
660
824
  rb_hash_aset(hash, msg_key, msg_value);
661
825
  }
826
+
662
827
  return hash;
663
828
  }
664
829
 
830
+ VALUE Scalar_CreateHash(upb_msgval msgval, TypeInfo type_info) {
831
+ if (type_info.type == UPB_TYPE_MESSAGE) {
832
+ return Message_CreateHash(msgval.msg_val, type_info.def.msgdef);
833
+ } else {
834
+ return Convert_UpbToRuby(msgval, type_info, Qnil);
835
+ }
836
+ }
837
+
838
+ /*
839
+ * call-seq:
840
+ * Message.to_h => {}
841
+ *
842
+ * Returns the message as a Ruby Hash object, with keys as symbols.
843
+ */
844
+ static VALUE Message_to_h(VALUE _self) {
845
+ Message* self = ruby_to_Message(_self);
846
+ return Message_CreateHash(self->msg, self->msgdef);
847
+ }
665
848
 
849
+ /*
850
+ * call-seq:
851
+ * Message.freeze => self
852
+ *
853
+ * Freezes the message object. We have to intercept this so we can pin the
854
+ * Ruby object into memory so we don't forget it's frozen.
855
+ */
856
+ static VALUE Message_freeze(VALUE _self) {
857
+ Message* self = ruby_to_Message(_self);
858
+ ObjectCache_Pin(self->msg, _self, Arena_get(self->arena));
859
+ RB_OBJ_FREEZE(_self);
860
+ return _self;
861
+ }
666
862
 
667
863
  /*
668
864
  * call-seq:
@@ -671,16 +867,18 @@ VALUE Message_to_h(VALUE _self) {
671
867
  * Accesses a field's value by field name. The provided field name should be a
672
868
  * string.
673
869
  */
674
- VALUE Message_index(VALUE _self, VALUE field_name) {
675
- MessageHeader* self;
870
+ static VALUE Message_index(VALUE _self, VALUE field_name) {
871
+ Message* self = ruby_to_Message(_self);
676
872
  const upb_fielddef* field;
677
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
873
+
678
874
  Check_Type(field_name, T_STRING);
679
- field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
875
+ field = upb_msgdef_ntofz(self->msgdef, RSTRING_PTR(field_name));
876
+
680
877
  if (field == NULL) {
681
878
  return Qnil;
682
879
  }
683
- return layout_get(self->descriptor->layout, Message_data(self), field);
880
+
881
+ return Message_getfield(_self, field);
684
882
  }
685
883
 
686
884
  /*
@@ -690,19 +888,208 @@ VALUE Message_index(VALUE _self, VALUE field_name) {
690
888
  * Sets a field's value by field name. The provided field name should be a
691
889
  * string.
692
890
  */
693
- VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
694
- MessageHeader* self;
695
- const upb_fielddef* field;
696
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
891
+ static VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
892
+ Message* self = ruby_to_Message(_self);
893
+ const upb_fielddef* f;
894
+ upb_msgval val;
895
+ upb_arena *arena = Arena_get(self->arena);
896
+
697
897
  Check_Type(field_name, T_STRING);
698
- field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
699
- if (field == NULL) {
898
+ f = upb_msgdef_ntofz(self->msgdef, RSTRING_PTR(field_name));
899
+
900
+ if (f == NULL) {
700
901
  rb_raise(rb_eArgError, "Unknown field: %s", RSTRING_PTR(field_name));
701
902
  }
702
- layout_set(self->descriptor->layout, Message_data(self), field, value);
903
+
904
+ val = Convert_RubyToUpb(value, upb_fielddef_name(f), TypeInfo_get(f), arena);
905
+ upb_msg_set(Message_GetMutable(_self, NULL), f, val, arena);
906
+
703
907
  return Qnil;
704
908
  }
705
909
 
910
+ /*
911
+ * call-seq:
912
+ * MessageClass.decode(data) => message
913
+ *
914
+ * Decodes the given data (as a string containing bytes in protocol buffers wire
915
+ * format) under the interpretration given by this message class's definition
916
+ * and returns a message object with the corresponding field values.
917
+ */
918
+ static VALUE Message_decode(VALUE klass, VALUE data) {
919
+ if (TYPE(data) != T_STRING) {
920
+ rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
921
+ }
922
+
923
+ VALUE msg_rb = initialize_rb_class_with_no_args(klass);
924
+ Message* msg = ruby_to_Message(msg_rb);
925
+
926
+ if (!upb_decode(RSTRING_PTR(data), RSTRING_LEN(data), (upb_msg*)msg->msg,
927
+ upb_msgdef_layout(msg->msgdef),
928
+ Arena_get(msg->arena))) {
929
+ rb_raise(cParseError, "Error occurred during parsing");
930
+ }
931
+
932
+ return msg_rb;
933
+ }
934
+
935
+ /*
936
+ * call-seq:
937
+ * MessageClass.decode_json(data, options = {}) => message
938
+ *
939
+ * Decodes the given data (as a string containing bytes in protocol buffers wire
940
+ * format) under the interpretration given by this message class's definition
941
+ * and returns a message object with the corresponding field values.
942
+ *
943
+ * @param options [Hash] options for the decoder
944
+ * ignore_unknown_fields: set true to ignore unknown fields (default is to
945
+ * raise an error)
946
+ */
947
+ static VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
948
+ VALUE data = argv[0];
949
+ int options = 0;
950
+ upb_status status;
951
+
952
+ // TODO(haberman): use this message's pool instead.
953
+ const upb_symtab *symtab = DescriptorPool_GetSymtab(generated_pool);
954
+
955
+ if (argc < 1 || argc > 2) {
956
+ rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
957
+ }
958
+
959
+ if (argc == 2) {
960
+ VALUE hash_args = argv[1];
961
+ if (TYPE(hash_args) != T_HASH) {
962
+ rb_raise(rb_eArgError, "Expected hash arguments.");
963
+ }
964
+
965
+ if (RTEST(rb_hash_lookup2( hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse))) {
966
+ options |= UPB_JSONDEC_IGNOREUNKNOWN;
967
+ }
968
+ }
969
+
970
+ if (TYPE(data) != T_STRING) {
971
+ rb_raise(rb_eArgError, "Expected string for JSON data.");
972
+ }
973
+
974
+ // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
975
+ // convert, because string handlers pass data directly to message string
976
+ // fields.
977
+
978
+ VALUE msg_rb = initialize_rb_class_with_no_args(klass);
979
+ Message* msg = ruby_to_Message(msg_rb);
980
+
981
+ // We don't allow users to decode a wrapper type directly.
982
+ if (upb_msgdef_iswrapper(msg->msgdef)) {
983
+ rb_raise(rb_eRuntimeError, "Cannot parse a wrapper directly.");
984
+ }
985
+
986
+ upb_status_clear(&status);
987
+ if (!upb_json_decode(RSTRING_PTR(data), RSTRING_LEN(data), (upb_msg*)msg->msg,
988
+ msg->msgdef, symtab, options,
989
+ Arena_get(msg->arena), &status)) {
990
+ rb_raise(cParseError, "Error occurred during parsing: %s",
991
+ upb_status_errmsg(&status));
992
+ }
993
+
994
+ return msg_rb;
995
+ }
996
+
997
+ /*
998
+ * call-seq:
999
+ * MessageClass.encode(msg) => bytes
1000
+ *
1001
+ * Encodes the given message object to its serialized form in protocol buffers
1002
+ * wire format.
1003
+ */
1004
+ static VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1005
+ Message* msg = ruby_to_Message(msg_rb);
1006
+ upb_arena *arena = upb_arena_new();
1007
+ const char *data;
1008
+ size_t size;
1009
+
1010
+ if (CLASS_OF(msg_rb) != klass) {
1011
+ rb_raise(rb_eArgError, "Message of wrong type.");
1012
+ }
1013
+
1014
+ data = upb_encode(msg->msg, upb_msgdef_layout(msg->msgdef), arena,
1015
+ &size);
1016
+
1017
+ if (data) {
1018
+ VALUE ret = rb_str_new(data, size);
1019
+ rb_enc_associate(ret, rb_ascii8bit_encoding());
1020
+ upb_arena_free(arena);
1021
+ return ret;
1022
+ } else {
1023
+ upb_arena_free(arena);
1024
+ rb_raise(rb_eRuntimeError, "Exceeded maximum depth (possibly cycle)");
1025
+ }
1026
+ }
1027
+
1028
+ /*
1029
+ * call-seq:
1030
+ * MessageClass.encode_json(msg, options = {}) => json_string
1031
+ *
1032
+ * Encodes the given message object into its serialized JSON representation.
1033
+ * @param options [Hash] options for the decoder
1034
+ * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
1035
+ * emit_defaults: set true to emit 0/false values (default is to omit them)
1036
+ */
1037
+ static VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1038
+ Message* msg = ruby_to_Message(argv[0]);
1039
+ int options = 0;
1040
+ char buf[1024];
1041
+ size_t size;
1042
+ upb_status status;
1043
+
1044
+ // TODO(haberman): use this message's pool instead.
1045
+ const upb_symtab *symtab = DescriptorPool_GetSymtab(generated_pool);
1046
+
1047
+ if (argc < 1 || argc > 2) {
1048
+ rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1049
+ }
1050
+
1051
+ if (argc == 2) {
1052
+ VALUE hash_args = argv[1];
1053
+ if (TYPE(hash_args) != T_HASH) {
1054
+ rb_raise(rb_eArgError, "Expected hash arguments.");
1055
+ }
1056
+
1057
+ if (RTEST(rb_hash_lookup2(hash_args,
1058
+ ID2SYM(rb_intern("preserve_proto_fieldnames")),
1059
+ Qfalse))) {
1060
+ options |= UPB_JSONENC_PROTONAMES;
1061
+ }
1062
+
1063
+ if (RTEST(rb_hash_lookup2(hash_args, ID2SYM(rb_intern("emit_defaults")),
1064
+ Qfalse))) {
1065
+ options |= UPB_JSONENC_EMITDEFAULTS;
1066
+ }
1067
+ }
1068
+
1069
+ upb_status_clear(&status);
1070
+ size = upb_json_encode(msg->msg, msg->msgdef, symtab, options, buf,
1071
+ sizeof(buf), &status);
1072
+
1073
+ if (!upb_ok(&status)) {
1074
+ rb_raise(cParseError, "Error occurred during encoding: %s",
1075
+ upb_status_errmsg(&status));
1076
+ }
1077
+
1078
+ VALUE ret;
1079
+ if (size >= sizeof(buf)) {
1080
+ char* buf2 = malloc(size + 1);
1081
+ upb_json_encode(msg->msg, msg->msgdef, symtab, options, buf2, size + 1,
1082
+ &status);
1083
+ ret = rb_str_new(buf2, size);
1084
+ free(buf2);
1085
+ } else {
1086
+ ret = rb_str_new(buf, size);
1087
+ }
1088
+
1089
+ rb_enc_associate(ret, rb_utf8_encoding());
1090
+ return ret;
1091
+ }
1092
+
706
1093
  /*
707
1094
  * call-seq:
708
1095
  * Message.descriptor => descriptor
@@ -710,16 +1097,15 @@ VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
710
1097
  * Class method that returns the Descriptor instance corresponding to this
711
1098
  * message class's type.
712
1099
  */
713
- VALUE Message_descriptor(VALUE klass) {
1100
+ static VALUE Message_descriptor(VALUE klass) {
714
1101
  return rb_ivar_get(klass, descriptor_instancevar_interned);
715
1102
  }
716
1103
 
717
1104
  VALUE build_class_from_descriptor(VALUE descriptor) {
718
- Descriptor* desc = ruby_to_Descriptor(descriptor);
719
1105
  const char *name;
720
1106
  VALUE klass;
721
1107
 
722
- name = upb_msgdef_fullname(desc->msgdef);
1108
+ name = upb_msgdef_fullname(Descriptor_GetMsgDef(descriptor));
723
1109
  if (name == NULL) {
724
1110
  rb_raise(rb_eRuntimeError, "Descriptor does not have assigned name.");
725
1111
  }
@@ -746,6 +1132,7 @@ VALUE build_class_from_descriptor(VALUE descriptor) {
746
1132
  rb_define_method(klass, "clone", Message_dup, 0);
747
1133
  rb_define_method(klass, "==", Message_eq, 1);
748
1134
  rb_define_method(klass, "eql?", Message_eq, 1);
1135
+ rb_define_method(klass, "freeze", Message_freeze, 0);
749
1136
  rb_define_method(klass, "hash", Message_hash, 0);
750
1137
  rb_define_method(klass, "to_h", Message_to_h, 0);
751
1138
  rb_define_method(klass, "inspect", Message_inspect, 0);
@@ -768,12 +1155,12 @@ VALUE build_class_from_descriptor(VALUE descriptor) {
768
1155
  * This module method, provided on each generated enum module, looks up an enum
769
1156
  * value by number and returns its name as a Ruby symbol, or nil if not found.
770
1157
  */
771
- VALUE enum_lookup(VALUE self, VALUE number) {
1158
+ static VALUE enum_lookup(VALUE self, VALUE number) {
772
1159
  int32_t num = NUM2INT(number);
773
1160
  VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
774
- EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
1161
+ const upb_enumdef *e = EnumDescriptor_GetEnumDef(desc);
775
1162
 
776
- const char* name = upb_enumdef_iton(enumdesc->enumdef, num);
1163
+ const char* name = upb_enumdef_iton(e, num);
777
1164
  if (name == NULL) {
778
1165
  return Qnil;
779
1166
  } else {
@@ -788,13 +1175,13 @@ VALUE enum_lookup(VALUE self, VALUE number) {
788
1175
  * This module method, provided on each generated enum module, looks up an enum
789
1176
  * value by name (as a Ruby symbol) and returns its name, or nil if not found.
790
1177
  */
791
- VALUE enum_resolve(VALUE self, VALUE sym) {
1178
+ static VALUE enum_resolve(VALUE self, VALUE sym) {
792
1179
  const char* name = rb_id2name(SYM2ID(sym));
793
1180
  VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
794
- EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
1181
+ const upb_enumdef *e = EnumDescriptor_GetEnumDef(desc);
795
1182
 
796
1183
  int32_t num = 0;
797
- bool found = upb_enumdef_ntoiz(enumdesc->enumdef, name, &num);
1184
+ bool found = upb_enumdef_ntoiz(e, name, &num);
798
1185
  if (!found) {
799
1186
  return Qnil;
800
1187
  } else {
@@ -809,17 +1196,16 @@ VALUE enum_resolve(VALUE self, VALUE sym) {
809
1196
  * This module method, provided on each generated enum module, returns the
810
1197
  * EnumDescriptor corresponding to this enum type.
811
1198
  */
812
- VALUE enum_descriptor(VALUE self) {
1199
+ static VALUE enum_descriptor(VALUE self) {
813
1200
  return rb_ivar_get(self, descriptor_instancevar_interned);
814
1201
  }
815
1202
 
816
1203
  VALUE build_module_from_enumdesc(VALUE _enumdesc) {
817
- EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(_enumdesc);
818
- VALUE mod = rb_define_module_id(
819
- rb_intern(upb_enumdef_fullname(enumdesc->enumdef)));
1204
+ const upb_enumdef *e = EnumDescriptor_GetEnumDef(_enumdesc);
1205
+ VALUE mod = rb_define_module_id(rb_intern(upb_enumdef_fullname(e)));
820
1206
 
821
1207
  upb_enum_iter it;
822
- for (upb_enum_begin(&it, enumdesc->enumdef);
1208
+ for (upb_enum_begin(&it, e);
823
1209
  !upb_enum_done(&it);
824
1210
  upb_enum_next(&it)) {
825
1211
  const char* name = upb_enum_iter_name(&it);
@@ -840,20 +1226,92 @@ VALUE build_module_from_enumdesc(VALUE _enumdesc) {
840
1226
  return mod;
841
1227
  }
842
1228
 
843
- /*
844
- * call-seq:
845
- * Google::Protobuf.deep_copy(obj) => copy_of_obj
846
- *
847
- * Performs a deep copy of a RepeatedField instance, a Map instance, or a
848
- * message object, recursively copying its members.
849
- */
850
- VALUE Google_Protobuf_deep_copy(VALUE self, VALUE obj) {
851
- VALUE klass = CLASS_OF(obj);
852
- if (klass == cRepeatedField) {
853
- return RepeatedField_deep_copy(obj);
854
- } else if (klass == cMap) {
855
- return Map_deep_copy(obj);
856
- } else {
857
- return Message_deep_copy(obj);
1229
+ // Internal only; used by Google::Protobuf.deep_copy.
1230
+ upb_msg* Message_deep_copy(const upb_msg* msg, const upb_msgdef* m,
1231
+ upb_arena *arena) {
1232
+ // Serialize and parse.
1233
+ upb_arena *tmp_arena = upb_arena_new();
1234
+ const upb_msglayout *layout = upb_msgdef_layout(m);
1235
+ size_t size;
1236
+
1237
+ char* data = upb_encode_ex(msg, layout, 0, tmp_arena, &size);
1238
+ upb_msg* new_msg = upb_msg_new(m, arena);
1239
+
1240
+ if (!data || !upb_decode(data, size, new_msg, layout, arena)) {
1241
+ upb_arena_free(tmp_arena);
1242
+ rb_raise(cParseError, "Error occurred copying proto");
858
1243
  }
1244
+
1245
+ upb_arena_free(tmp_arena);
1246
+ return new_msg;
1247
+ }
1248
+
1249
+ const upb_msg* Message_GetUpbMessage(VALUE value, const upb_msgdef* m,
1250
+ const char* name, upb_arena* arena) {
1251
+ if (value == Qnil) return NULL;
1252
+
1253
+ VALUE klass = CLASS_OF(value);
1254
+ VALUE desc_rb = rb_ivar_get(klass, descriptor_instancevar_interned);
1255
+ const upb_msgdef* val_m =
1256
+ desc_rb == Qnil ? NULL : Descriptor_GetMsgDef(desc_rb);
1257
+
1258
+ if (val_m != m) {
1259
+ // Check for possible implicit conversions
1260
+ // TODO: hash conversion?
1261
+
1262
+ switch (upb_msgdef_wellknowntype(m)) {
1263
+ case UPB_WELLKNOWN_TIMESTAMP: {
1264
+ // Time -> Google::Protobuf::Timestamp
1265
+ upb_msg *msg = upb_msg_new(m, arena);
1266
+ upb_msgval sec, nsec;
1267
+ struct timespec time;
1268
+ const upb_fielddef *sec_f = upb_msgdef_itof(m, 1);
1269
+ const upb_fielddef *nsec_f = upb_msgdef_itof(m, 2);
1270
+
1271
+ if (!rb_obj_is_kind_of(value, rb_cTime)) goto badtype;
1272
+
1273
+ time = rb_time_timespec(value);
1274
+ sec.int64_val = time.tv_sec;
1275
+ nsec.int32_val = time.tv_nsec;
1276
+ upb_msg_set(msg, sec_f, sec, arena);
1277
+ upb_msg_set(msg, nsec_f, nsec, arena);
1278
+ return msg;
1279
+ }
1280
+ case UPB_WELLKNOWN_DURATION: {
1281
+ // Numeric -> Google::Protobuf::Duration
1282
+ upb_msg *msg = upb_msg_new(m, arena);
1283
+ upb_msgval sec, nsec;
1284
+ const upb_fielddef *sec_f = upb_msgdef_itof(m, 1);
1285
+ const upb_fielddef *nsec_f = upb_msgdef_itof(m, 2);
1286
+
1287
+ if (!rb_obj_is_kind_of(value, rb_cNumeric)) goto badtype;
1288
+
1289
+ sec.int64_val = NUM2LL(value);
1290
+ nsec.int32_val = round((NUM2DBL(value) - NUM2LL(value)) * 1000000000);
1291
+ upb_msg_set(msg, sec_f, sec, arena);
1292
+ upb_msg_set(msg, nsec_f, nsec, arena);
1293
+ return msg;
1294
+ }
1295
+ default:
1296
+ badtype:
1297
+ rb_raise(cTypeError,
1298
+ "Invalid type %s to assign to submessage field '%s'.",
1299
+ rb_class2name(CLASS_OF(value)), name);
1300
+ }
1301
+
1302
+ }
1303
+
1304
+ Message* self = ruby_to_Message(value);
1305
+ upb_arena_fuse(arena, Arena_get(self->arena));
1306
+
1307
+ return self->msg;
1308
+ }
1309
+
1310
+ void Message_register(VALUE protobuf) {
1311
+ cParseError = rb_const_get(protobuf, rb_intern("ParseError"));
1312
+
1313
+ // Ruby-interned string: "descriptor". We use this identifier to store an
1314
+ // instance variable on message classes we create in order to link them back
1315
+ // to their descriptors.
1316
+ descriptor_instancevar_interned = rb_intern("descriptor");
859
1317
  }