google-protobuf 3.14.0 → 3.25.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. checksums.yaml +4 -4
  2. data/ext/google/protobuf_c/Rakefile +3 -0
  3. data/ext/google/protobuf_c/convert.c +317 -0
  4. data/ext/google/protobuf_c/convert.h +50 -0
  5. data/ext/google/protobuf_c/defs.c +743 -1706
  6. data/ext/google/protobuf_c/defs.h +82 -0
  7. data/ext/google/protobuf_c/extconf.rb +15 -8
  8. data/ext/google/protobuf_c/glue.c +56 -0
  9. data/ext/google/protobuf_c/map.c +336 -486
  10. data/ext/google/protobuf_c/map.h +44 -0
  11. data/ext/google/protobuf_c/message.c +1088 -518
  12. data/ext/google/protobuf_c/message.h +86 -0
  13. data/ext/google/protobuf_c/protobuf.c +301 -94
  14. data/ext/google/protobuf_c/protobuf.h +66 -621
  15. data/ext/google/protobuf_c/repeated_field.c +323 -353
  16. data/ext/google/protobuf_c/repeated_field.h +41 -0
  17. data/ext/google/protobuf_c/ruby-upb.c +14440 -0
  18. data/ext/google/protobuf_c/ruby-upb.h +13044 -0
  19. data/ext/google/protobuf_c/shared_convert.c +64 -0
  20. data/ext/google/protobuf_c/shared_convert.h +26 -0
  21. data/ext/google/protobuf_c/shared_message.c +66 -0
  22. data/ext/google/protobuf_c/shared_message.h +25 -0
  23. data/ext/google/protobuf_c/third_party/utf8_range/LICENSE +22 -0
  24. data/ext/google/protobuf_c/third_party/utf8_range/naive.c +92 -0
  25. data/ext/google/protobuf_c/third_party/utf8_range/range2-neon.c +157 -0
  26. data/ext/google/protobuf_c/third_party/utf8_range/range2-sse.c +170 -0
  27. data/ext/google/protobuf_c/third_party/utf8_range/utf8_range.h +21 -0
  28. data/ext/google/protobuf_c/wrap_memcpy.c +7 -29
  29. data/lib/google/protobuf/any_pb.rb +24 -5
  30. data/lib/google/protobuf/api_pb.rb +27 -23
  31. data/lib/google/protobuf/descriptor_dsl.rb +465 -0
  32. data/lib/google/protobuf/descriptor_pb.rb +86 -0
  33. data/lib/google/protobuf/duration_pb.rb +24 -5
  34. data/lib/google/protobuf/empty_pb.rb +24 -3
  35. data/lib/google/protobuf/ffi/descriptor.rb +165 -0
  36. data/lib/google/protobuf/ffi/descriptor_pool.rb +75 -0
  37. data/lib/google/protobuf/ffi/enum_descriptor.rb +171 -0
  38. data/lib/google/protobuf/ffi/ffi.rb +213 -0
  39. data/lib/google/protobuf/ffi/field_descriptor.rb +319 -0
  40. data/lib/google/protobuf/ffi/file_descriptor.rb +59 -0
  41. data/lib/google/protobuf/ffi/internal/arena.rb +66 -0
  42. data/lib/google/protobuf/ffi/internal/convert.rb +305 -0
  43. data/lib/google/protobuf/ffi/internal/pointer_helper.rb +35 -0
  44. data/lib/google/protobuf/ffi/internal/type_safety.rb +25 -0
  45. data/lib/google/protobuf/ffi/map.rb +407 -0
  46. data/lib/google/protobuf/ffi/message.rb +662 -0
  47. data/lib/google/protobuf/ffi/object_cache.rb +30 -0
  48. data/lib/google/protobuf/ffi/oneof_descriptor.rb +95 -0
  49. data/lib/google/protobuf/ffi/repeated_field.rb +383 -0
  50. data/lib/google/protobuf/field_mask_pb.rb +24 -4
  51. data/lib/google/protobuf/message_exts.rb +10 -28
  52. data/lib/google/protobuf/object_cache.rb +97 -0
  53. data/lib/google/protobuf/plugin_pb.rb +47 -0
  54. data/lib/google/protobuf/repeated_field.rb +18 -28
  55. data/lib/google/protobuf/source_context_pb.rb +24 -4
  56. data/lib/google/protobuf/struct_pb.rb +24 -20
  57. data/lib/google/protobuf/timestamp_pb.rb +24 -5
  58. data/lib/google/protobuf/type_pb.rb +27 -68
  59. data/lib/google/protobuf/well_known_types.rb +17 -36
  60. data/lib/google/protobuf/wrappers_pb.rb +24 -28
  61. data/lib/google/protobuf.rb +32 -118
  62. data/lib/google/protobuf_ffi.rb +50 -0
  63. data/lib/google/protobuf_native.rb +20 -0
  64. data/lib/google/tasks/ffi.rake +102 -0
  65. metadata +92 -38
  66. data/ext/google/protobuf_c/encode_decode.c +0 -1795
  67. data/ext/google/protobuf_c/storage.c +0 -1198
  68. data/ext/google/protobuf_c/upb.c +0 -13817
  69. data/ext/google/protobuf_c/upb.h +0 -6777
  70. data/tests/basic.rb +0 -543
  71. data/tests/generated_code_test.rb +0 -23
  72. data/tests/stress.rb +0 -38
@@ -1,76 +1,69 @@
1
1
  // Protocol Buffers - Google's data interchange format
2
2
  // Copyright 2014 Google Inc. All rights reserved.
3
- // https://developers.google.com/protocol-buffers/
4
3
  //
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.
4
+ // Use of this source code is governed by a BSD-style
5
+ // license that can be found in the LICENSE file or at
6
+ // https://developers.google.com/open-source/licenses/bsd
30
7
 
8
+ #include "message.h"
9
+
10
+ #include "convert.h"
11
+ #include "defs.h"
12
+ #include "map.h"
31
13
  #include "protobuf.h"
14
+ #include "repeated_field.h"
15
+ #include "shared_message.h"
32
16
 
33
- // -----------------------------------------------------------------------------
34
- // Class/module creation from msgdefs and enumdefs, respectively.
35
- // -----------------------------------------------------------------------------
17
+ static VALUE cParseError = Qnil;
18
+ static VALUE cAbstractMessage = Qnil;
19
+ static ID descriptor_instancevar_interned;
36
20
 
37
- void* Message_data(void* msg) {
38
- return ((uint8_t *)msg) + sizeof(MessageHeader);
21
+ static VALUE initialize_rb_class_with_no_args(VALUE klass) {
22
+ return rb_funcall(klass, rb_intern("new"), 0);
39
23
  }
40
24
 
41
- void Message_mark(void* _self) {
42
- MessageHeader* self = (MessageHeader *)_self;
43
- layout_mark(self->descriptor->layout, Message_data(self));
25
+ VALUE MessageOrEnum_GetDescriptor(VALUE klass) {
26
+ return rb_ivar_get(klass, descriptor_instancevar_interned);
44
27
  }
45
28
 
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);
29
+ // -----------------------------------------------------------------------------
30
+ // Class/module creation from msgdefs and enumdefs, respectively.
31
+ // -----------------------------------------------------------------------------
32
+
33
+ typedef struct {
34
+ // IMPORTANT: WB_PROTECTED objects must only use the RB_OBJ_WRITE()
35
+ // macro to update VALUE references, as to trigger write barriers.
36
+ VALUE arena;
37
+ const upb_Message* msg; // Can get as mutable when non-frozen.
38
+ const upb_MessageDef*
39
+ msgdef; // kept alive by self.class.descriptor reference.
40
+ } Message;
41
+
42
+ static void Message_mark(void* _self) {
43
+ Message* self = (Message*)_self;
44
+ rb_gc_mark(self->arena);
53
45
  }
54
46
 
55
- rb_data_type_t Message_type = {
56
- "Message",
57
- { Message_mark, Message_free, NULL },
47
+ static rb_data_type_t Message_type = {
48
+ "Google::Protobuf::Message",
49
+ {Message_mark, RUBY_DEFAULT_FREE, NULL},
50
+ .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
58
51
  };
59
52
 
60
- VALUE Message_alloc(VALUE klass) {
53
+ static Message* ruby_to_Message(VALUE msg_rb) {
54
+ Message* msg;
55
+ TypedData_Get_Struct(msg_rb, Message, &Message_type, msg);
56
+ return msg;
57
+ }
58
+
59
+ static VALUE Message_alloc(VALUE klass) {
61
60
  VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
62
- Descriptor* desc = ruby_to_Descriptor(descriptor);
63
- MessageHeader* msg;
61
+ Message* msg = ALLOC(Message);
64
62
  VALUE ret;
65
63
 
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);
64
+ msg->msgdef = Descriptor_GetMsgDef(descriptor);
65
+ msg->arena = Qnil;
66
+ msg->msg = NULL;
74
67
 
75
68
  ret = TypedData_Wrap_Struct(klass, &Message_type, msg);
76
69
  rb_ivar_set(ret, descriptor_instancevar_interned, descriptor);
@@ -78,24 +71,96 @@ VALUE Message_alloc(VALUE klass) {
78
71
  return ret;
79
72
  }
80
73
 
81
- static const upb_fielddef* which_oneof_field(MessageHeader* self, const upb_oneofdef* o) {
82
- uint32_t oneof_case;
83
- const upb_fielddef* f;
74
+ const upb_Message* Message_Get(VALUE msg_rb, const upb_MessageDef** m) {
75
+ Message* msg = ruby_to_Message(msg_rb);
76
+ if (m) *m = msg->msgdef;
77
+ return msg->msg;
78
+ }
79
+
80
+ upb_Message* Message_GetMutable(VALUE msg_rb, const upb_MessageDef** m) {
81
+ rb_check_frozen(msg_rb);
82
+ return (upb_Message*)Message_Get(msg_rb, m);
83
+ }
84
+
85
+ void Message_InitPtr(VALUE self_, upb_Message* msg, VALUE arena) {
86
+ Message* self = ruby_to_Message(self_);
87
+ self->msg = msg;
88
+ RB_OBJ_WRITE(self_, &self->arena, arena);
89
+ VALUE stored = ObjectCache_TryAdd(msg, self_);
90
+ (void)stored;
91
+ PBRUBY_ASSERT(stored == self_);
92
+ }
84
93
 
85
- oneof_case =
86
- slot_read_oneof_case(self->descriptor->layout, Message_data(self), o);
94
+ VALUE Message_GetArena(VALUE msg_rb) {
95
+ Message* msg = ruby_to_Message(msg_rb);
96
+ return msg->arena;
97
+ }
87
98
 
88
- if (oneof_case == ONEOF_CASE_NONE) {
89
- return NULL;
99
+ void Message_CheckClass(VALUE klass) {
100
+ if (rb_get_alloc_func(klass) != &Message_alloc) {
101
+ rb_raise(rb_eArgError,
102
+ "Message class was not returned by the DescriptorPool.");
90
103
  }
104
+ }
105
+
106
+ VALUE Message_GetRubyWrapper(upb_Message* msg, const upb_MessageDef* m,
107
+ VALUE arena) {
108
+ if (msg == NULL) return Qnil;
91
109
 
92
- // oneof_case is a field index, so find that field.
93
- f = upb_oneofdef_itof(o, oneof_case);
94
- assert(f != NULL);
110
+ VALUE val = ObjectCache_Get(msg);
95
111
 
96
- return f;
112
+ if (val == Qnil) {
113
+ VALUE klass = Descriptor_DefToClass(m);
114
+ val = Message_alloc(klass);
115
+ Message_InitPtr(val, msg, arena);
116
+ }
117
+
118
+ return val;
119
+ }
120
+
121
+ void Message_PrintMessage(StringBuilder* b, const upb_Message* msg,
122
+ const upb_MessageDef* m) {
123
+ bool first = true;
124
+ int n = upb_MessageDef_FieldCount(m);
125
+ VALUE klass = Descriptor_DefToClass(m);
126
+ StringBuilder_Printf(b, "<%s: ", rb_class2name(klass));
127
+
128
+ for (int i = 0; i < n; i++) {
129
+ const upb_FieldDef* field = upb_MessageDef_Field(m, i);
130
+
131
+ if (upb_FieldDef_HasPresence(field) &&
132
+ !upb_Message_HasFieldByDef(msg, field)) {
133
+ continue;
134
+ }
135
+
136
+ if (!first) {
137
+ StringBuilder_Printf(b, ", ");
138
+ } else {
139
+ first = false;
140
+ }
141
+
142
+ upb_MessageValue msgval = upb_Message_GetFieldByDef(msg, field);
143
+
144
+ StringBuilder_Printf(b, "%s: ", upb_FieldDef_Name(field));
145
+
146
+ if (upb_FieldDef_IsMap(field)) {
147
+ const upb_MessageDef* entry_m = upb_FieldDef_MessageSubDef(field);
148
+ const upb_FieldDef* key_f = upb_MessageDef_FindFieldByNumber(entry_m, 1);
149
+ const upb_FieldDef* val_f = upb_MessageDef_FindFieldByNumber(entry_m, 2);
150
+ TypeInfo val_info = TypeInfo_get(val_f);
151
+ Map_Inspect(b, msgval.map_val, upb_FieldDef_CType(key_f), val_info);
152
+ } else if (upb_FieldDef_IsRepeated(field)) {
153
+ RepeatedField_Inspect(b, msgval.array_val, TypeInfo_get(field));
154
+ } else {
155
+ StringBuilder_PrintMsgval(b, msgval, TypeInfo_get(field));
156
+ }
157
+ }
158
+
159
+ StringBuilder_Printf(b, ">");
97
160
  }
98
161
 
162
+ // Helper functions for #method_missing ////////////////////////////////////////
163
+
99
164
  enum {
100
165
  METHOD_UNKNOWN = 0,
101
166
  METHOD_GETTER = 1,
@@ -108,153 +173,217 @@ enum {
108
173
  };
109
174
 
110
175
  // 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) {
114
- return false;
115
- }
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:
176
+ static bool IsWrapper(const upb_MessageDef* m) {
177
+ if (!m) return false;
178
+ switch (upb_MessageDef_WellKnownType(m)) {
179
+ case kUpb_WellKnown_DoubleValue:
180
+ case kUpb_WellKnown_FloatValue:
181
+ case kUpb_WellKnown_Int64Value:
182
+ case kUpb_WellKnown_UInt64Value:
183
+ case kUpb_WellKnown_Int32Value:
184
+ case kUpb_WellKnown_UInt32Value:
185
+ case kUpb_WellKnown_StringValue:
186
+ case kUpb_WellKnown_BytesValue:
187
+ case kUpb_WellKnown_BoolValue:
127
188
  return true;
128
189
  default:
129
190
  return false;
130
191
  }
131
192
  }
132
193
 
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);
141
- }
194
+ static bool IsFieldWrapper(const upb_FieldDef* f) {
195
+ return IsWrapper(upb_FieldDef_MessageSubDef(f));
196
+ }
197
+
198
+ static bool Match(const upb_MessageDef* m, const char* name,
199
+ const upb_FieldDef** f, const upb_OneofDef** o,
200
+ const char* prefix, const char* suffix) {
201
+ size_t sp = strlen(prefix);
202
+ size_t ss = strlen(suffix);
203
+ size_t sn = strlen(name);
204
+
205
+ if (sn <= sp + ss) return false;
206
+
207
+ if (memcmp(name, prefix, sp) != 0 ||
208
+ memcmp(name + sn - ss, suffix, ss) != 0) {
209
+ return false;
142
210
  }
143
- return Qnil;
211
+
212
+ return upb_MessageDef_FindByNameWithSize(m, name + sp, sn - sp - ss, f, o);
144
213
  }
145
214
 
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;
215
+ static int extract_method_call(VALUE method_name, Message* self,
216
+ const upb_FieldDef** f, const upb_OneofDef** o) {
217
+ const upb_MessageDef* m = self->msgdef;
218
+ const char* name;
155
219
 
156
220
  Check_Type(method_name, T_SYMBOL);
221
+ name = rb_id2name(SYM2ID(method_name));
222
+
223
+ if (Match(m, name, f, o, "", "")) return METHOD_GETTER;
224
+ if (Match(m, name, f, o, "", "=")) return METHOD_SETTER;
225
+ if (Match(m, name, f, o, "clear_", "")) return METHOD_CLEAR;
226
+ if (Match(m, name, f, o, "has_", "?") &&
227
+ (*o || (*f && upb_FieldDef_HasPresence(*f)))) {
228
+ return METHOD_PRESENCE;
229
+ }
230
+ if (Match(m, name, f, o, "", "_as_value") && *f &&
231
+ !upb_FieldDef_IsRepeated(*f) && IsFieldWrapper(*f)) {
232
+ return METHOD_WRAPPER_GETTER;
233
+ }
234
+ if (Match(m, name, f, o, "", "_as_value=") && *f &&
235
+ !upb_FieldDef_IsRepeated(*f) && IsFieldWrapper(*f)) {
236
+ return METHOD_WRAPPER_SETTER;
237
+ }
238
+ if (Match(m, name, f, o, "", "_const") && *f &&
239
+ upb_FieldDef_CType(*f) == kUpb_CType_Enum) {
240
+ return METHOD_ENUM_GETTER;
241
+ }
157
242
 
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;
243
+ return METHOD_UNKNOWN;
244
+ }
245
+
246
+ static VALUE Message_oneof_accessor(VALUE _self, const upb_OneofDef* o,
247
+ int accessor_type) {
248
+ Message* self = ruby_to_Message(_self);
249
+ const upb_FieldDef* oneof_field = upb_Message_WhichOneof(self->msg, o);
250
+
251
+ switch (accessor_type) {
252
+ case METHOD_PRESENCE:
253
+ return oneof_field == NULL ? Qfalse : Qtrue;
254
+ case METHOD_CLEAR:
255
+ if (oneof_field != NULL) {
256
+ upb_Message_ClearFieldByDef(Message_GetMutable(_self, NULL),
257
+ oneof_field);
208
258
  }
209
- test_o = test_o_wrapper;
210
- test_f = test_f_wrapper;
211
- }
259
+ return Qnil;
260
+ case METHOD_GETTER:
261
+ return oneof_field == NULL
262
+ ? Qnil
263
+ : ID2SYM(rb_intern(upb_FieldDef_Name(oneof_field)));
264
+ case METHOD_SETTER:
265
+ rb_raise(rb_eRuntimeError, "Oneof accessors are read-only.");
212
266
  }
267
+ rb_raise(rb_eRuntimeError, "Invalid access of oneof field.");
268
+ }
213
269
 
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;
270
+ static void Message_setfield(upb_Message* msg, const upb_FieldDef* f, VALUE val,
271
+ upb_Arena* arena) {
272
+ upb_MessageValue msgval;
273
+ if (upb_FieldDef_IsMap(f)) {
274
+ msgval.map_val = Map_GetUpbMap(val, f, arena);
275
+ } else if (upb_FieldDef_IsRepeated(f)) {
276
+ msgval.array_val = RepeatedField_GetUpbArray(val, f, arena);
277
+ } else {
278
+ if (val == Qnil &&
279
+ (upb_FieldDef_IsSubMessage(f) || upb_FieldDef_RealContainingOneof(f))) {
280
+ upb_Message_ClearFieldByDef(msg, f);
281
+ return;
234
282
  }
283
+ msgval =
284
+ Convert_RubyToUpb(val, upb_FieldDef_Name(f), TypeInfo_get(f), arena);
235
285
  }
286
+ upb_Message_SetFieldByDef(msg, f, msgval, arena);
287
+ }
236
288
 
237
- // Verify the name corresponds to a oneof or field in this message.
238
- if (!has_field) {
239
- return METHOD_UNKNOWN;
289
+ VALUE Message_getfield(VALUE _self, const upb_FieldDef* f) {
290
+ Message* self = ruby_to_Message(_self);
291
+ // This is a special-case: upb_Message_Mutable() for map & array are logically
292
+ // const (they will not change what is serialized) but physically
293
+ // non-const, as they do allocate a repeated field or map. The logical
294
+ // constness means it's ok to do even if the message is frozen.
295
+ upb_Message* msg = (upb_Message*)self->msg;
296
+ upb_Arena* arena = Arena_get(self->arena);
297
+ if (upb_FieldDef_IsMap(f)) {
298
+ upb_Map* map = upb_Message_Mutable(msg, f, arena).map;
299
+ const upb_FieldDef* key_f = map_field_key(f);
300
+ const upb_FieldDef* val_f = map_field_value(f);
301
+ upb_CType key_type = upb_FieldDef_CType(key_f);
302
+ TypeInfo value_type_info = TypeInfo_get(val_f);
303
+ return Map_GetRubyWrapper(map, key_type, value_type_info, self->arena);
304
+ } else if (upb_FieldDef_IsRepeated(f)) {
305
+ upb_Array* arr = upb_Message_Mutable(msg, f, arena).array;
306
+ return RepeatedField_GetRubyWrapper(arr, TypeInfo_get(f), self->arena);
307
+ } else if (upb_FieldDef_IsSubMessage(f)) {
308
+ if (!upb_Message_HasFieldByDef(self->msg, f)) return Qnil;
309
+ upb_Message* submsg = upb_Message_Mutable(msg, f, arena).msg;
310
+ const upb_MessageDef* m = upb_FieldDef_MessageSubDef(f);
311
+ return Message_GetRubyWrapper(submsg, m, self->arena);
312
+ } else {
313
+ upb_MessageValue msgval = upb_Message_GetFieldByDef(self->msg, f);
314
+ return Convert_UpbToRuby(msgval, TypeInfo_get(f), self->arena);
240
315
  }
316
+ }
241
317
 
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;
318
+ static VALUE Message_field_accessor(VALUE _self, const upb_FieldDef* f,
319
+ int accessor_type, int argc, VALUE* argv) {
320
+ upb_Arena* arena = Arena_get(Message_GetArena(_self));
247
321
 
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;
322
+ switch (accessor_type) {
323
+ case METHOD_SETTER:
324
+ Message_setfield(Message_GetMutable(_self, NULL), f, argv[1], arena);
325
+ return Qnil;
326
+ case METHOD_CLEAR:
327
+ upb_Message_ClearFieldByDef(Message_GetMutable(_self, NULL), f);
328
+ return Qnil;
329
+ case METHOD_PRESENCE:
330
+ if (!upb_FieldDef_HasPresence(f)) {
331
+ rb_raise(rb_eRuntimeError, "Field does not have presence.");
332
+ }
333
+ return upb_Message_HasFieldByDef(Message_Get(_self, NULL), f);
334
+ case METHOD_WRAPPER_GETTER: {
335
+ Message* self = ruby_to_Message(_self);
336
+ if (upb_Message_HasFieldByDef(self->msg, f)) {
337
+ PBRUBY_ASSERT(upb_FieldDef_IsSubMessage(f) &&
338
+ !upb_FieldDef_IsRepeated(f));
339
+ upb_MessageValue wrapper = upb_Message_GetFieldByDef(self->msg, f);
340
+ const upb_MessageDef* wrapper_m = upb_FieldDef_MessageSubDef(f);
341
+ const upb_FieldDef* value_f =
342
+ upb_MessageDef_FindFieldByNumber(wrapper_m, 1);
343
+ upb_MessageValue value =
344
+ upb_Message_GetFieldByDef(wrapper.msg_val, value_f);
345
+ return Convert_UpbToRuby(value, TypeInfo_get(value_f), self->arena);
346
+ } else {
347
+ return Qnil;
348
+ }
349
+ }
350
+ case METHOD_WRAPPER_SETTER: {
351
+ upb_Message* msg = Message_GetMutable(_self, NULL);
352
+ if (argv[1] == Qnil) {
353
+ upb_Message_ClearFieldByDef(msg, f);
354
+ } else {
355
+ const upb_FieldDef* val_f =
356
+ upb_MessageDef_FindFieldByNumber(upb_FieldDef_MessageSubDef(f), 1);
357
+ upb_MessageValue msgval = Convert_RubyToUpb(
358
+ argv[1], upb_FieldDef_Name(f), TypeInfo_get(val_f), arena);
359
+ upb_Message* wrapper = upb_Message_Mutable(msg, f, arena).msg;
360
+ upb_Message_SetFieldByDef(wrapper, val_f, msgval, arena);
361
+ }
362
+ return Qnil;
363
+ }
364
+ case METHOD_ENUM_GETTER: {
365
+ upb_MessageValue msgval =
366
+ upb_Message_GetFieldByDef(Message_Get(_self, NULL), f);
367
+
368
+ if (upb_FieldDef_Label(f) == kUpb_Label_Repeated) {
369
+ // Map repeated fields to a new type with ints
370
+ VALUE arr = rb_ary_new();
371
+ size_t i, n = upb_Array_Size(msgval.array_val);
372
+ for (i = 0; i < n; i++) {
373
+ upb_MessageValue elem = upb_Array_Get(msgval.array_val, i);
374
+ rb_ary_push(arr, INT2NUM(elem.int32_val));
375
+ }
376
+ return arr;
377
+ } else {
378
+ return INT2NUM(msgval.int32_val);
379
+ }
252
380
  }
381
+ case METHOD_GETTER:
382
+ return Message_getfield(_self, f);
383
+ default:
384
+ rb_raise(rb_eRuntimeError, "Internal error, no such accessor: %d",
385
+ accessor_type);
253
386
  }
254
-
255
- *o = test_o;
256
- *f = test_f;
257
- return accessor_type;
258
387
  }
259
388
 
260
389
  /*
@@ -284,111 +413,56 @@ static int extract_method_call(VALUE method_name, MessageHeader* self,
284
413
  * true if the field 'fieldname' is set in the message object, else false. For
285
414
  * 'proto3' syntax, calling this for a basic type field will result in an error.
286
415
  */
287
- VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self) {
288
- MessageHeader* self;
289
- const upb_oneofdef* o;
290
- const upb_fielddef* f;
416
+ static VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self) {
417
+ Message* self = ruby_to_Message(_self);
418
+ const upb_OneofDef* o;
419
+ const upb_FieldDef* f;
291
420
  int accessor_type;
292
421
 
293
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
294
422
  if (argc < 1) {
295
423
  rb_raise(rb_eArgError, "Expected method name as first argument.");
296
424
  }
297
425
 
298
426
  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
-
310
- // Return which of the oneof fields are set
311
- if (o != NULL) {
312
- const upb_fielddef* oneof_field = which_oneof_field(self, o);
313
427
 
314
- if (accessor_type == METHOD_SETTER) {
315
- rb_raise(rb_eRuntimeError, "Oneof accessors are read-only.");
316
- }
428
+ if (accessor_type == METHOD_UNKNOWN) return rb_call_super(argc, argv);
317
429
 
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);
430
+ // Validate argument count.
431
+ switch (accessor_type) {
432
+ case METHOD_SETTER:
433
+ case METHOD_WRAPPER_SETTER:
434
+ if (argc != 2) {
435
+ rb_raise(rb_eArgError, "Expected 2 arguments, received %d", argc);
323
436
  }
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);
437
+ rb_check_frozen(_self);
438
+ break;
439
+ default:
440
+ if (argc != 1) {
441
+ rb_raise(rb_eArgError, "Expected 1 argument, received %d", argc);
369
442
  }
370
- return array;
371
- }
372
- // Convert the value for singular fields
373
- return rb_funcall(enum_type, method, 1, raw_value);
443
+ break;
444
+ }
445
+
446
+ // Dispatch accessor.
447
+ if (o != NULL) {
448
+ return Message_oneof_accessor(_self, o, accessor_type);
374
449
  } else {
375
- return layout_get(self->descriptor->layout, Message_data(self), f);
450
+ return Message_field_accessor(_self, f, accessor_type, argc, argv);
376
451
  }
377
452
  }
378
453
 
379
-
380
- VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
381
- MessageHeader* self;
382
- const upb_oneofdef* o;
383
- const upb_fielddef* f;
454
+ static VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
455
+ Message* self = ruby_to_Message(_self);
456
+ const upb_OneofDef* o;
457
+ const upb_FieldDef* f;
384
458
  int accessor_type;
385
459
 
386
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
387
460
  if (argc < 1) {
388
461
  rb_raise(rb_eArgError, "Expected method name as first argument.");
389
462
  }
390
463
 
391
464
  accessor_type = extract_method_call(argv[0], self, &f, &o);
465
+
392
466
  if (accessor_type == METHOD_UNKNOWN) {
393
467
  return rb_call_super(argc, argv);
394
468
  } else if (o != NULL) {
@@ -398,17 +472,120 @@ VALUE Message_respond_to_missing(int argc, VALUE* argv, VALUE _self) {
398
472
  }
399
473
  }
400
474
 
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));
475
+ void Message_InitFromValue(upb_Message* msg, const upb_MessageDef* m, VALUE val,
476
+ upb_Arena* arena);
477
+
478
+ typedef struct {
479
+ upb_Map* map;
480
+ TypeInfo key_type;
481
+ TypeInfo val_type;
482
+ upb_Arena* arena;
483
+ } MapInit;
484
+
485
+ static int Map_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
486
+ MapInit* map_init = (MapInit*)_self;
487
+ upb_MessageValue k, v;
488
+ k = Convert_RubyToUpb(key, "", map_init->key_type, NULL);
489
+
490
+ if (map_init->val_type.type == kUpb_CType_Message && TYPE(val) == T_HASH) {
491
+ const upb_MiniTable* t =
492
+ upb_MessageDef_MiniTable(map_init->val_type.def.msgdef);
493
+ upb_Message* msg = upb_Message_New(t, map_init->arena);
494
+ Message_InitFromValue(msg, map_init->val_type.def.msgdef, val,
495
+ map_init->arena);
496
+ v.msg_val = msg;
497
+ } else {
498
+ v = Convert_RubyToUpb(val, "", map_init->val_type, map_init->arena);
499
+ }
500
+ upb_Map_Set(map_init->map, k, v, map_init->arena);
501
+ return ST_CONTINUE;
405
502
  }
406
503
 
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);
504
+ static void Map_InitFromValue(upb_Map* map, const upb_FieldDef* f, VALUE val,
505
+ upb_Arena* arena) {
506
+ const upb_MessageDef* entry_m = upb_FieldDef_MessageSubDef(f);
507
+ const upb_FieldDef* key_f = upb_MessageDef_FindFieldByNumber(entry_m, 1);
508
+ const upb_FieldDef* val_f = upb_MessageDef_FindFieldByNumber(entry_m, 2);
509
+ if (TYPE(val) != T_HASH) {
510
+ rb_raise(rb_eArgError,
511
+ "Expected Hash object as initializer value for map field '%s' "
512
+ "(given %s).",
513
+ upb_FieldDef_Name(f), rb_class2name(CLASS_OF(val)));
514
+ }
515
+ MapInit map_init = {map, TypeInfo_get(key_f), TypeInfo_get(val_f), arena};
516
+ rb_hash_foreach(val, Map_initialize_kwarg, (VALUE)&map_init);
517
+ }
518
+
519
+ static upb_MessageValue MessageValue_FromValue(VALUE val, TypeInfo info,
520
+ upb_Arena* arena) {
521
+ if (info.type == kUpb_CType_Message) {
522
+ upb_MessageValue msgval;
523
+ const upb_MiniTable* t = upb_MessageDef_MiniTable(info.def.msgdef);
524
+ upb_Message* msg = upb_Message_New(t, arena);
525
+ Message_InitFromValue(msg, info.def.msgdef, val, arena);
526
+ msgval.msg_val = msg;
527
+ return msgval;
528
+ } else {
529
+ return Convert_RubyToUpb(val, "", info, arena);
530
+ }
531
+ }
532
+
533
+ static void RepeatedField_InitFromValue(upb_Array* arr, const upb_FieldDef* f,
534
+ VALUE val, upb_Arena* arena) {
535
+ TypeInfo type_info = TypeInfo_get(f);
536
+
537
+ if (TYPE(val) != T_ARRAY) {
538
+ rb_raise(rb_eArgError,
539
+ "Expected array as initializer value for repeated field '%s' "
540
+ "(given %s).",
541
+ upb_FieldDef_Name(f), rb_class2name(CLASS_OF(val)));
542
+ }
543
+
544
+ for (int i = 0; i < RARRAY_LEN(val); i++) {
545
+ VALUE entry = rb_ary_entry(val, i);
546
+ upb_MessageValue msgval;
547
+ if (upb_FieldDef_IsSubMessage(f) && TYPE(entry) == T_HASH) {
548
+ msgval = MessageValue_FromValue(entry, type_info, arena);
549
+ } else {
550
+ msgval = Convert_RubyToUpb(entry, upb_FieldDef_Name(f), type_info, arena);
551
+ }
552
+ upb_Array_Append(arr, msgval, arena);
553
+ }
554
+ }
555
+
556
+ static void Message_InitFieldFromValue(upb_Message* msg, const upb_FieldDef* f,
557
+ VALUE val, upb_Arena* arena) {
558
+ if (TYPE(val) == T_NIL) return;
559
+
560
+ if (upb_FieldDef_IsMap(f)) {
561
+ upb_Map* map = upb_Message_Mutable(msg, f, arena).map;
562
+ Map_InitFromValue(map, f, val, arena);
563
+ } else if (upb_FieldDef_Label(f) == kUpb_Label_Repeated) {
564
+ upb_Array* arr = upb_Message_Mutable(msg, f, arena).array;
565
+ RepeatedField_InitFromValue(arr, f, val, arena);
566
+ } else if (upb_FieldDef_IsSubMessage(f)) {
567
+ if (TYPE(val) == T_HASH) {
568
+ upb_Message* submsg = upb_Message_Mutable(msg, f, arena).msg;
569
+ Message_InitFromValue(submsg, upb_FieldDef_MessageSubDef(f), val, arena);
570
+ } else {
571
+ Message_setfield(msg, f, val, arena);
572
+ }
573
+ } else {
574
+ upb_MessageValue msgval =
575
+ Convert_RubyToUpb(val, upb_FieldDef_Name(f), TypeInfo_get(f), arena);
576
+ upb_Message_SetFieldByDef(msg, f, msgval, arena);
577
+ }
578
+ }
579
+
580
+ typedef struct {
581
+ upb_Message* msg;
582
+ const upb_MessageDef* msgdef;
583
+ upb_Arena* arena;
584
+ } MsgInit;
585
+
586
+ static int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
587
+ MsgInit* msg_init = (MsgInit*)_self;
588
+ const char* name;
412
589
 
413
590
  if (TYPE(key) == T_STRING) {
414
591
  name = RSTRING_PTR(key);
@@ -416,55 +593,31 @@ int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
416
593
  name = RSTRING_PTR(rb_id2str(SYM2ID(key)));
417
594
  } else {
418
595
  rb_raise(rb_eArgError,
419
- "Expected string or symbols as hash keys when initializing proto from hash.");
596
+ "Expected string or symbols as hash keys when initializing proto "
597
+ "from hash.");
420
598
  }
421
599
 
422
- f = upb_msgdef_ntofz(self->descriptor->msgdef, name);
600
+ const upb_FieldDef* f =
601
+ upb_MessageDef_FindFieldByName(msg_init->msgdef, name);
602
+
423
603
  if (f == NULL) {
424
604
  rb_raise(rb_eArgError,
425
605
  "Unknown field name '%s' in initialization map entry.", name);
426
606
  }
427
607
 
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
- }
608
+ Message_InitFieldFromValue(msg_init->msg, f, val, msg_init->arena);
609
+ return ST_CONTINUE;
610
+ }
457
611
 
458
- RepeatedField_push(ary, entry);
459
- }
612
+ void Message_InitFromValue(upb_Message* msg, const upb_MessageDef* m, VALUE val,
613
+ upb_Arena* arena) {
614
+ MsgInit msg_init = {msg, m, arena};
615
+ if (TYPE(val) == T_HASH) {
616
+ rb_hash_foreach(val, Message_initialize_kwarg, (VALUE)&msg_init);
460
617
  } 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);
618
+ rb_raise(rb_eArgError, "Expected hash arguments or message, not %s",
619
+ rb_class2name(CLASS_OF(val)));
466
620
  }
467
- return 0;
468
621
  }
469
622
 
470
623
  /*
@@ -479,12 +632,14 @@ int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
479
632
  * have been added to a pool. The method definitions described here on the
480
633
  * Message class are provided on each concrete message class.
481
634
  */
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);
635
+ static VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
636
+ Message* self = ruby_to_Message(_self);
637
+ VALUE arena_rb = Arena_new();
638
+ upb_Arena* arena = Arena_get(arena_rb);
639
+ const upb_MiniTable* t = upb_MessageDef_MiniTable(self->msgdef);
640
+ upb_Message* msg = upb_Message_New(t, arena);
486
641
 
487
- layout_init(self->descriptor->layout, Message_data(self));
642
+ Message_InitPtr(_self, msg, arena_rb);
488
643
 
489
644
  if (argc == 0) {
490
645
  return Qnil;
@@ -492,12 +647,7 @@ VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
492
647
  if (argc != 1) {
493
648
  rb_raise(rb_eArgError, "Expected 0 or 1 arguments.");
494
649
  }
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);
650
+ Message_InitFromValue((upb_Message*)self->msg, self->msgdef, argv[0], arena);
501
651
  return Qnil;
502
652
  }
503
653
 
@@ -507,37 +657,31 @@ VALUE Message_initialize(int argc, VALUE* argv, VALUE _self) {
507
657
  *
508
658
  * Performs a shallow copy of this message and returns the new copy.
509
659
  */
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
-
660
+ static VALUE Message_dup(VALUE _self) {
661
+ Message* self = ruby_to_Message(_self);
662
+ VALUE new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
663
+ Message* new_msg_self = ruby_to_Message(new_msg);
664
+ size_t size = upb_MessageDef_MiniTable(self->msgdef)->size;
665
+
666
+ // TODO
667
+ // TODO
668
+ memcpy((upb_Message*)new_msg_self->msg, self->msg, size);
669
+ Arena_fuse(self->arena, Arena_get(new_msg_self->arena));
523
670
  return new_msg;
524
671
  }
525
672
 
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);
532
-
533
- new_msg = rb_class_new_instance(0, NULL, CLASS_OF(_self));
534
- TypedData_Get_Struct(new_msg, MessageHeader, &Message_type, new_msg_self);
535
-
536
- layout_deep_copy(self->descriptor->layout,
537
- Message_data(new_msg_self),
538
- Message_data(self));
539
-
540
- return new_msg;
673
+ // Support function for Message_eq, and also used by other #eq functions.
674
+ bool Message_Equal(const upb_Message* m1, const upb_Message* m2,
675
+ const upb_MessageDef* m) {
676
+ upb_Status status;
677
+ upb_Status_Clear(&status);
678
+ bool return_value = shared_Message_Equal(m1, m2, m, &status);
679
+ if (upb_Status_IsOk(&status)) {
680
+ return return_value;
681
+ } else {
682
+ rb_raise(cParseError, "Message_Equal(): %s",
683
+ upb_Status_ErrorMessage(&status));
684
+ }
541
685
  }
542
686
 
543
687
  /*
@@ -549,22 +693,27 @@ VALUE Message_deep_copy(VALUE _self) {
549
693
  * method's semantics (a more efficient comparison may actually be done if the
550
694
  * field is of a primitive type).
551
695
  */
552
- VALUE Message_eq(VALUE _self, VALUE _other) {
553
- MessageHeader* self;
554
- MessageHeader* other;
555
- if (TYPE(_self) != TYPE(_other)) {
556
- return Qfalse;
557
- }
558
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
559
- TypedData_Get_Struct(_other, MessageHeader, &Message_type, other);
696
+ static VALUE Message_eq(VALUE _self, VALUE _other) {
697
+ if (CLASS_OF(_self) != CLASS_OF(_other)) return Qfalse;
560
698
 
561
- if (self->descriptor != other->descriptor) {
562
- return Qfalse;
563
- }
699
+ Message* self = ruby_to_Message(_self);
700
+ Message* other = ruby_to_Message(_other);
701
+ assert(self->msgdef == other->msgdef);
702
+
703
+ return Message_Equal(self->msg, other->msg, self->msgdef) ? Qtrue : Qfalse;
704
+ }
564
705
 
565
- return layout_eq(self->descriptor->layout,
566
- Message_data(self),
567
- Message_data(other));
706
+ uint64_t Message_Hash(const upb_Message* msg, const upb_MessageDef* m,
707
+ uint64_t seed) {
708
+ upb_Status status;
709
+ upb_Status_Clear(&status);
710
+ uint64_t return_value = shared_Message_Hash(msg, m, seed, &status);
711
+ if (upb_Status_IsOk(&status)) {
712
+ return return_value;
713
+ } else {
714
+ rb_raise(cParseError, "Message_Hash(): %s",
715
+ upb_Status_ErrorMessage(&status));
716
+ }
568
717
  }
569
718
 
570
719
  /*
@@ -573,11 +722,12 @@ VALUE Message_eq(VALUE _self, VALUE _other) {
573
722
  *
574
723
  * Returns a hash value that represents this message's field values.
575
724
  */
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));
725
+ static VALUE Message_hash(VALUE _self) {
726
+ Message* self = ruby_to_Message(_self);
727
+ uint64_t hash_value = Message_Hash(self->msg, self->msgdef, 0);
728
+ // RUBY_FIXNUM_MAX should be one less than a power of 2.
729
+ assert((RUBY_FIXNUM_MAX & (RUBY_FIXNUM_MAX + 1)) == 0);
730
+ return INT2FIX(hash_value & RUBY_FIXNUM_MAX);
581
731
  }
582
732
 
583
733
  /*
@@ -588,81 +738,155 @@ VALUE Message_hash(VALUE _self) {
588
738
  * formatted as "<MessageType: field1: value1, field2: value2, ...>". Each
589
739
  * field's value is represented according to its own #inspect method.
590
740
  */
591
- VALUE Message_inspect(VALUE _self) {
592
- MessageHeader* self;
593
- VALUE str;
594
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
741
+ static VALUE Message_inspect(VALUE _self) {
742
+ Message* self = ruby_to_Message(_self);
595
743
 
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;
744
+ StringBuilder* builder = StringBuilder_New();
745
+ Message_PrintMessage(builder, self->msg, self->msgdef);
746
+ VALUE ret = StringBuilder_ToRubyString(builder);
747
+ StringBuilder_Free(builder);
748
+ return ret;
603
749
  }
604
750
 
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;
751
+ // Support functions for Message_to_h //////////////////////////////////////////
752
+
753
+ static VALUE RepeatedField_CreateArray(const upb_Array* arr,
754
+ TypeInfo type_info) {
755
+ int size = arr ? upb_Array_Size(arr) : 0;
756
+ VALUE ary = rb_ary_new2(size);
757
+
758
+ for (int i = 0; i < size; i++) {
759
+ upb_MessageValue msgval = upb_Array_Get(arr, i);
760
+ VALUE val = Scalar_CreateHash(msgval, type_info);
761
+ rb_ary_push(ary, val);
762
+ }
763
+
764
+ return ary;
765
+ }
766
+
767
+ static VALUE Message_CreateHash(const upb_Message* msg,
768
+ const upb_MessageDef* m) {
769
+ if (!msg) return Qnil;
770
+
613
771
  VALUE hash = rb_hash_new();
614
- upb_msg_field_iter it;
772
+ int n = upb_MessageDef_FieldCount(m);
615
773
  bool is_proto2;
616
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
617
774
 
618
775
  // We currently have a few behaviors that are specific to proto2.
619
776
  // This is unfortunate, we should key behaviors off field attributes (like
620
777
  // whether a field has presence), not proto2 vs. proto3. We should see if we
621
778
  // can change this without breaking users.
622
- is_proto2 =
623
- upb_msgdef_syntax(self->descriptor->msgdef) == UPB_SYNTAX_PROTO2;
779
+ is_proto2 = upb_MessageDef_Syntax(m) == kUpb_Syntax_Proto2;
624
780
 
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);
781
+ for (int i = 0; i < n; i++) {
782
+ const upb_FieldDef* field = upb_MessageDef_Field(m, i);
783
+ TypeInfo type_info = TypeInfo_get(field);
784
+ upb_MessageValue msgval;
629
785
  VALUE msg_value;
630
786
  VALUE msg_key;
631
787
 
788
+ if (!is_proto2 && upb_FieldDef_IsSubMessage(field) &&
789
+ !upb_FieldDef_IsRepeated(field) &&
790
+ !upb_Message_HasFieldByDef(msg, field)) {
791
+ // TODO: Legacy behavior, remove when we fix the is_proto2 differences.
792
+ msg_key = ID2SYM(rb_intern(upb_FieldDef_Name(field)));
793
+ rb_hash_aset(hash, msg_key, Qnil);
794
+ continue;
795
+ }
796
+
632
797
  // Do not include fields that are not present (oneof or optional fields).
633
- if (is_proto2 && upb_fielddef_haspresence(field) &&
634
- !layout_has(self->descriptor->layout, Message_data(self), field)) {
798
+ if (is_proto2 && upb_FieldDef_HasPresence(field) &&
799
+ !upb_Message_HasFieldByDef(msg, field)) {
635
800
  continue;
636
801
  }
637
802
 
638
- msg_value = layout_get(self->descriptor->layout, Message_data(self), field);
639
- 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) {
645
- continue;
646
- }
803
+ msg_key = ID2SYM(rb_intern(upb_FieldDef_Name(field)));
804
+ msgval = upb_Message_GetFieldByDef(msg, field);
647
805
 
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
- }
806
+ // Proto2 omits empty map/repeated filds also.
655
807
 
656
- } else if (msg_value != Qnil &&
657
- upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
658
- msg_value = Message_to_h(msg_value);
808
+ if (upb_FieldDef_IsMap(field)) {
809
+ const upb_MessageDef* entry_m = upb_FieldDef_MessageSubDef(field);
810
+ const upb_FieldDef* key_f = upb_MessageDef_FindFieldByNumber(entry_m, 1);
811
+ const upb_FieldDef* val_f = upb_MessageDef_FindFieldByNumber(entry_m, 2);
812
+ upb_CType key_type = upb_FieldDef_CType(key_f);
813
+ msg_value = Map_CreateHash(msgval.map_val, key_type, TypeInfo_get(val_f));
814
+ } else if (upb_FieldDef_IsRepeated(field)) {
815
+ if (is_proto2 &&
816
+ (!msgval.array_val || upb_Array_Size(msgval.array_val) == 0)) {
817
+ continue;
818
+ }
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_MessageValue msgval, TypeInfo type_info) {
831
+ if (type_info.type == kUpb_CType_Message) {
832
+ return Message_CreateHash(msgval.msg_val, type_info.def.msgdef);
833
+ } else {
834
+ return Convert_UpbToRuby(msgval, type_info, Qnil);
835
+ }
836
+ }
665
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
+ }
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
+ if (!RB_OBJ_FROZEN(_self)) {
859
+ Arena_Pin(self->arena, _self);
860
+ RB_OBJ_FREEZE(_self);
861
+ }
862
+ return _self;
863
+ }
864
+
865
+ /*
866
+ * Deep freezes the message object recursively.
867
+ * Internal use only.
868
+ */
869
+ VALUE Message_internal_deep_freeze(VALUE _self) {
870
+ Message* self = ruby_to_Message(_self);
871
+ Message_freeze(_self);
872
+
873
+ int n = upb_MessageDef_FieldCount(self->msgdef);
874
+ for (int i = 0; i < n; i++) {
875
+ const upb_FieldDef* f = upb_MessageDef_Field(self->msgdef, i);
876
+ VALUE field = Message_getfield(_self, f);
877
+
878
+ if (field != Qnil) {
879
+ if (upb_FieldDef_IsMap(f)) {
880
+ Map_internal_deep_freeze(field);
881
+ } else if (upb_FieldDef_IsRepeated(f)) {
882
+ RepeatedField_internal_deep_freeze(field);
883
+ } else if (upb_FieldDef_IsSubMessage(f)) {
884
+ Message_internal_deep_freeze(field);
885
+ }
886
+ }
887
+ }
888
+ return _self;
889
+ }
666
890
 
667
891
  /*
668
892
  * call-seq:
@@ -671,16 +895,18 @@ VALUE Message_to_h(VALUE _self) {
671
895
  * Accesses a field's value by field name. The provided field name should be a
672
896
  * string.
673
897
  */
674
- VALUE Message_index(VALUE _self, VALUE field_name) {
675
- MessageHeader* self;
676
- const upb_fielddef* field;
677
- TypedData_Get_Struct(_self, MessageHeader, &Message_type, self);
898
+ static VALUE Message_index(VALUE _self, VALUE field_name) {
899
+ Message* self = ruby_to_Message(_self);
900
+ const upb_FieldDef* field;
901
+
678
902
  Check_Type(field_name, T_STRING);
679
- field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
903
+ field = upb_MessageDef_FindFieldByName(self->msgdef, RSTRING_PTR(field_name));
904
+
680
905
  if (field == NULL) {
681
906
  return Qnil;
682
907
  }
683
- return layout_get(self->descriptor->layout, Message_data(self), field);
908
+
909
+ return Message_getfield(_self, field);
684
910
  }
685
911
 
686
912
  /*
@@ -690,19 +916,278 @@ VALUE Message_index(VALUE _self, VALUE field_name) {
690
916
  * Sets a field's value by field name. The provided field name should be a
691
917
  * string.
692
918
  */
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);
919
+ static VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
920
+ Message* self = ruby_to_Message(_self);
921
+ const upb_FieldDef* f;
922
+ upb_MessageValue val;
923
+ upb_Arena* arena = Arena_get(self->arena);
924
+
697
925
  Check_Type(field_name, T_STRING);
698
- field = upb_msgdef_ntofz(self->descriptor->msgdef, RSTRING_PTR(field_name));
699
- if (field == NULL) {
926
+ f = upb_MessageDef_FindFieldByName(self->msgdef, RSTRING_PTR(field_name));
927
+
928
+ if (f == NULL) {
700
929
  rb_raise(rb_eArgError, "Unknown field: %s", RSTRING_PTR(field_name));
701
930
  }
702
- layout_set(self->descriptor->layout, Message_data(self), field, value);
931
+
932
+ val = Convert_RubyToUpb(value, upb_FieldDef_Name(f), TypeInfo_get(f), arena);
933
+ upb_Message_SetFieldByDef(Message_GetMutable(_self, NULL), f, val, arena);
934
+
703
935
  return Qnil;
704
936
  }
705
937
 
938
+ /*
939
+ * call-seq:
940
+ * MessageClass.decode(data, options) => message
941
+ *
942
+ * Decodes the given data (as a string containing bytes in protocol buffers wire
943
+ * format) under the interpretation given by this message class's definition
944
+ * and returns a message object with the corresponding field values.
945
+ * @param options [Hash] options for the decoder
946
+ * recursion_limit: set to maximum decoding depth for message (default is 64)
947
+ */
948
+ static VALUE Message_decode(int argc, VALUE* argv, VALUE klass) {
949
+ VALUE data = argv[0];
950
+ int options = 0;
951
+
952
+ if (argc < 1 || argc > 2) {
953
+ rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
954
+ }
955
+
956
+ if (argc == 2) {
957
+ VALUE hash_args = argv[1];
958
+ if (TYPE(hash_args) != T_HASH) {
959
+ rb_raise(rb_eArgError, "Expected hash arguments.");
960
+ }
961
+
962
+ VALUE depth =
963
+ rb_hash_lookup(hash_args, ID2SYM(rb_intern("recursion_limit")));
964
+
965
+ if (depth != Qnil && TYPE(depth) == T_FIXNUM) {
966
+ options |= upb_DecodeOptions_MaxDepth(FIX2INT(depth));
967
+ }
968
+ }
969
+
970
+ if (TYPE(data) != T_STRING) {
971
+ rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
972
+ }
973
+
974
+ return Message_decode_bytes(RSTRING_LEN(data), RSTRING_PTR(data), options,
975
+ klass, /*freeze*/ false);
976
+ }
977
+
978
+ VALUE Message_decode_bytes(int size, const char* bytes, int options,
979
+ VALUE klass, bool freeze) {
980
+ VALUE msg_rb = initialize_rb_class_with_no_args(klass);
981
+ Message* msg = ruby_to_Message(msg_rb);
982
+
983
+ const upb_FileDef* file = upb_MessageDef_File(msg->msgdef);
984
+ const upb_ExtensionRegistry* extreg =
985
+ upb_DefPool_ExtensionRegistry(upb_FileDef_Pool(file));
986
+ upb_DecodeStatus status = upb_Decode(bytes, size, (upb_Message*)msg->msg,
987
+ upb_MessageDef_MiniTable(msg->msgdef),
988
+ extreg, options, Arena_get(msg->arena));
989
+ if (status != kUpb_DecodeStatus_Ok) {
990
+ rb_raise(cParseError, "Error occurred during parsing");
991
+ }
992
+ if (freeze) {
993
+ Message_internal_deep_freeze(msg_rb);
994
+ }
995
+ return msg_rb;
996
+ }
997
+
998
+ /*
999
+ * call-seq:
1000
+ * MessageClass.decode_json(data, options = {}) => message
1001
+ *
1002
+ * Decodes the given data (as a string containing bytes in protocol buffers wire
1003
+ * format) under the interpretration given by this message class's definition
1004
+ * and returns a message object with the corresponding field values.
1005
+ *
1006
+ * @param options [Hash] options for the decoder
1007
+ * ignore_unknown_fields: set true to ignore unknown fields (default is to
1008
+ * raise an error)
1009
+ */
1010
+ static VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
1011
+ VALUE data = argv[0];
1012
+ int options = 0;
1013
+ upb_Status status;
1014
+
1015
+ // TODO: use this message's pool instead.
1016
+ const upb_DefPool* symtab = DescriptorPool_GetSymtab(generated_pool);
1017
+
1018
+ if (argc < 1 || argc > 2) {
1019
+ rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1020
+ }
1021
+
1022
+ if (argc == 2) {
1023
+ VALUE hash_args = argv[1];
1024
+ if (TYPE(hash_args) != T_HASH) {
1025
+ rb_raise(rb_eArgError, "Expected hash arguments.");
1026
+ }
1027
+
1028
+ if (RTEST(rb_hash_lookup2(
1029
+ hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse))) {
1030
+ options |= upb_JsonDecode_IgnoreUnknown;
1031
+ }
1032
+ }
1033
+
1034
+ if (TYPE(data) != T_STRING) {
1035
+ rb_raise(rb_eArgError, "Expected string for JSON data.");
1036
+ }
1037
+
1038
+ // TODO: Check and respect string encoding. If not UTF-8, we need to
1039
+ // convert, because string handlers pass data directly to message string
1040
+ // fields.
1041
+
1042
+ VALUE msg_rb = initialize_rb_class_with_no_args(klass);
1043
+ Message* msg = ruby_to_Message(msg_rb);
1044
+
1045
+ // We don't allow users to decode a wrapper type directly.
1046
+ if (IsWrapper(msg->msgdef)) {
1047
+ rb_raise(rb_eRuntimeError, "Cannot parse a wrapper directly.");
1048
+ }
1049
+
1050
+ upb_Status_Clear(&status);
1051
+ if (!upb_JsonDecode(RSTRING_PTR(data), RSTRING_LEN(data),
1052
+ (upb_Message*)msg->msg, msg->msgdef, symtab, options,
1053
+ Arena_get(msg->arena), &status)) {
1054
+ rb_raise(cParseError, "Error occurred during parsing: %s",
1055
+ upb_Status_ErrorMessage(&status));
1056
+ }
1057
+
1058
+ return msg_rb;
1059
+ }
1060
+
1061
+ /*
1062
+ * call-seq:
1063
+ * MessageClass.encode(msg, options) => bytes
1064
+ *
1065
+ * Encodes the given message object to its serialized form in protocol buffers
1066
+ * wire format.
1067
+ * @param options [Hash] options for the encoder
1068
+ * recursion_limit: set to maximum encoding depth for message (default is 64)
1069
+ */
1070
+ static VALUE Message_encode(int argc, VALUE* argv, VALUE klass) {
1071
+ Message* msg = ruby_to_Message(argv[0]);
1072
+ int options = 0;
1073
+ char* data;
1074
+ size_t size;
1075
+
1076
+ if (CLASS_OF(argv[0]) != klass) {
1077
+ rb_raise(rb_eArgError, "Message of wrong type.");
1078
+ }
1079
+
1080
+ if (argc < 1 || argc > 2) {
1081
+ rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1082
+ }
1083
+
1084
+ if (argc == 2) {
1085
+ VALUE hash_args = argv[1];
1086
+ if (TYPE(hash_args) != T_HASH) {
1087
+ rb_raise(rb_eArgError, "Expected hash arguments.");
1088
+ }
1089
+ VALUE depth =
1090
+ rb_hash_lookup(hash_args, ID2SYM(rb_intern("recursion_limit")));
1091
+
1092
+ if (depth != Qnil && TYPE(depth) == T_FIXNUM) {
1093
+ options |= upb_DecodeOptions_MaxDepth(FIX2INT(depth));
1094
+ }
1095
+ }
1096
+
1097
+ upb_Arena* arena = upb_Arena_New();
1098
+
1099
+ upb_EncodeStatus status =
1100
+ upb_Encode(msg->msg, upb_MessageDef_MiniTable(msg->msgdef), options,
1101
+ arena, &data, &size);
1102
+
1103
+ if (status == kUpb_EncodeStatus_Ok) {
1104
+ VALUE ret = rb_str_new(data, size);
1105
+ rb_enc_associate(ret, rb_ascii8bit_encoding());
1106
+ upb_Arena_Free(arena);
1107
+ return ret;
1108
+ } else {
1109
+ upb_Arena_Free(arena);
1110
+ rb_raise(rb_eRuntimeError, "Exceeded maximum depth (possibly cycle)");
1111
+ }
1112
+ }
1113
+
1114
+ /*
1115
+ * call-seq:
1116
+ * MessageClass.encode_json(msg, options = {}) => json_string
1117
+ *
1118
+ * Encodes the given message object into its serialized JSON representation.
1119
+ * @param options [Hash] options for the decoder
1120
+ * preserve_proto_fieldnames: set true to use original fieldnames (default is
1121
+ * to camelCase) emit_defaults: set true to emit 0/false values (default is to
1122
+ * omit them)
1123
+ */
1124
+ static VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1125
+ Message* msg = ruby_to_Message(argv[0]);
1126
+ int options = 0;
1127
+ char buf[1024];
1128
+ size_t size;
1129
+ upb_Status status;
1130
+
1131
+ // TODO: use this message's pool instead.
1132
+ const upb_DefPool* symtab = DescriptorPool_GetSymtab(generated_pool);
1133
+
1134
+ if (argc < 1 || argc > 2) {
1135
+ rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1136
+ }
1137
+
1138
+ if (argc == 2) {
1139
+ VALUE hash_args = argv[1];
1140
+ if (TYPE(hash_args) != T_HASH) {
1141
+ if (RTEST(rb_funcall(hash_args, rb_intern("respond_to?"), 1,
1142
+ rb_str_new2("to_h")))) {
1143
+ hash_args = rb_funcall(hash_args, rb_intern("to_h"), 0);
1144
+ } else {
1145
+ rb_raise(rb_eArgError, "Expected hash arguments.");
1146
+ }
1147
+ }
1148
+
1149
+ if (RTEST(rb_hash_lookup2(hash_args,
1150
+ ID2SYM(rb_intern("preserve_proto_fieldnames")),
1151
+ Qfalse))) {
1152
+ options |= upb_JsonEncode_UseProtoNames;
1153
+ }
1154
+
1155
+ if (RTEST(rb_hash_lookup2(hash_args, ID2SYM(rb_intern("emit_defaults")),
1156
+ Qfalse))) {
1157
+ options |= upb_JsonEncode_EmitDefaults;
1158
+ }
1159
+
1160
+ if (RTEST(rb_hash_lookup2(hash_args,
1161
+ ID2SYM(rb_intern("format_enums_as_integers")),
1162
+ Qfalse))) {
1163
+ options |= upb_JsonEncode_FormatEnumsAsIntegers;
1164
+ }
1165
+ }
1166
+
1167
+ upb_Status_Clear(&status);
1168
+ size = upb_JsonEncode(msg->msg, msg->msgdef, symtab, options, buf,
1169
+ sizeof(buf), &status);
1170
+
1171
+ if (!upb_Status_IsOk(&status)) {
1172
+ rb_raise(cParseError, "Error occurred during encoding: %s",
1173
+ upb_Status_ErrorMessage(&status));
1174
+ }
1175
+
1176
+ VALUE ret;
1177
+ if (size >= sizeof(buf)) {
1178
+ char* buf2 = malloc(size + 1);
1179
+ upb_JsonEncode(msg->msg, msg->msgdef, symtab, options, buf2, size + 1,
1180
+ &status);
1181
+ ret = rb_str_new(buf2, size);
1182
+ free(buf2);
1183
+ } else {
1184
+ ret = rb_str_new(buf, size);
1185
+ }
1186
+
1187
+ rb_enc_associate(ret, rb_utf8_encoding());
1188
+ return ret;
1189
+ }
1190
+
706
1191
  /*
707
1192
  * call-seq:
708
1193
  * Message.descriptor => descriptor
@@ -710,16 +1195,15 @@ VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value) {
710
1195
  * Class method that returns the Descriptor instance corresponding to this
711
1196
  * message class's type.
712
1197
  */
713
- VALUE Message_descriptor(VALUE klass) {
1198
+ static VALUE Message_descriptor(VALUE klass) {
714
1199
  return rb_ivar_get(klass, descriptor_instancevar_interned);
715
1200
  }
716
1201
 
717
1202
  VALUE build_class_from_descriptor(VALUE descriptor) {
718
- Descriptor* desc = ruby_to_Descriptor(descriptor);
719
- const char *name;
1203
+ const char* name;
720
1204
  VALUE klass;
721
1205
 
722
- name = upb_msgdef_fullname(desc->msgdef);
1206
+ name = upb_MessageDef_FullName(Descriptor_GetMsgDef(descriptor));
723
1207
  if (name == NULL) {
724
1208
  rb_raise(rb_eRuntimeError, "Descriptor does not have assigned name.");
725
1209
  }
@@ -727,37 +1211,8 @@ VALUE build_class_from_descriptor(VALUE descriptor) {
727
1211
  klass = rb_define_class_id(
728
1212
  // Docs say this parameter is ignored. User will assign return value to
729
1213
  // their own toplevel constant class name.
730
- rb_intern("Message"),
731
- rb_cObject);
1214
+ rb_intern("Message"), cAbstractMessage);
732
1215
  rb_ivar_set(klass, descriptor_instancevar_interned, descriptor);
733
- rb_define_alloc_func(klass, Message_alloc);
734
- rb_require("google/protobuf/message_exts");
735
- rb_include_module(klass, rb_eval_string("::Google::Protobuf::MessageExts"));
736
- rb_extend_object(
737
- klass, rb_eval_string("::Google::Protobuf::MessageExts::ClassMethods"));
738
-
739
- rb_define_method(klass, "method_missing",
740
- Message_method_missing, -1);
741
- rb_define_method(klass, "respond_to_missing?",
742
- Message_respond_to_missing, -1);
743
- rb_define_method(klass, "initialize", Message_initialize, -1);
744
- rb_define_method(klass, "dup", Message_dup, 0);
745
- // Also define #clone so that we don't inherit Object#clone.
746
- rb_define_method(klass, "clone", Message_dup, 0);
747
- rb_define_method(klass, "==", Message_eq, 1);
748
- rb_define_method(klass, "eql?", Message_eq, 1);
749
- rb_define_method(klass, "hash", Message_hash, 0);
750
- rb_define_method(klass, "to_h", Message_to_h, 0);
751
- rb_define_method(klass, "inspect", Message_inspect, 0);
752
- rb_define_method(klass, "to_s", Message_inspect, 0);
753
- rb_define_method(klass, "[]", Message_index, 1);
754
- rb_define_method(klass, "[]=", Message_index_set, 2);
755
- rb_define_singleton_method(klass, "decode", Message_decode, 1);
756
- rb_define_singleton_method(klass, "encode", Message_encode, 1);
757
- rb_define_singleton_method(klass, "decode_json", Message_decode_json, -1);
758
- rb_define_singleton_method(klass, "encode_json", Message_encode_json, -1);
759
- rb_define_singleton_method(klass, "descriptor", Message_descriptor, 0);
760
-
761
1216
  return klass;
762
1217
  }
763
1218
 
@@ -768,16 +1223,15 @@ VALUE build_class_from_descriptor(VALUE descriptor) {
768
1223
  * This module method, provided on each generated enum module, looks up an enum
769
1224
  * value by number and returns its name as a Ruby symbol, or nil if not found.
770
1225
  */
771
- VALUE enum_lookup(VALUE self, VALUE number) {
1226
+ static VALUE enum_lookup(VALUE self, VALUE number) {
772
1227
  int32_t num = NUM2INT(number);
773
1228
  VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
774
- EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
775
-
776
- const char* name = upb_enumdef_iton(enumdesc->enumdef, num);
777
- if (name == NULL) {
778
- return Qnil;
1229
+ const upb_EnumDef* e = EnumDescriptor_GetEnumDef(desc);
1230
+ const upb_EnumValueDef* ev = upb_EnumDef_FindValueByNumber(e, num);
1231
+ if (ev) {
1232
+ return ID2SYM(rb_intern(upb_EnumValueDef_Name(ev)));
779
1233
  } else {
780
- return ID2SYM(rb_intern(name));
1234
+ return Qnil;
781
1235
  }
782
1236
  }
783
1237
 
@@ -788,17 +1242,15 @@ VALUE enum_lookup(VALUE self, VALUE number) {
788
1242
  * This module method, provided on each generated enum module, looks up an enum
789
1243
  * value by name (as a Ruby symbol) and returns its name, or nil if not found.
790
1244
  */
791
- VALUE enum_resolve(VALUE self, VALUE sym) {
1245
+ static VALUE enum_resolve(VALUE self, VALUE sym) {
792
1246
  const char* name = rb_id2name(SYM2ID(sym));
793
1247
  VALUE desc = rb_ivar_get(self, descriptor_instancevar_interned);
794
- EnumDescriptor* enumdesc = ruby_to_EnumDescriptor(desc);
795
-
796
- int32_t num = 0;
797
- bool found = upb_enumdef_ntoiz(enumdesc->enumdef, name, &num);
798
- if (!found) {
799
- return Qnil;
1248
+ const upb_EnumDef* e = EnumDescriptor_GetEnumDef(desc);
1249
+ const upb_EnumValueDef* ev = upb_EnumDef_FindValueByName(e, name);
1250
+ if (ev) {
1251
+ return INT2NUM(upb_EnumValueDef_Number(ev));
800
1252
  } else {
801
- return INT2NUM(num);
1253
+ return Qnil;
802
1254
  }
803
1255
  }
804
1256
 
@@ -809,27 +1261,33 @@ VALUE enum_resolve(VALUE self, VALUE sym) {
809
1261
  * This module method, provided on each generated enum module, returns the
810
1262
  * EnumDescriptor corresponding to this enum type.
811
1263
  */
812
- VALUE enum_descriptor(VALUE self) {
1264
+ static VALUE enum_descriptor(VALUE self) {
813
1265
  return rb_ivar_get(self, descriptor_instancevar_interned);
814
1266
  }
815
1267
 
816
1268
  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)));
820
-
821
- upb_enum_iter it;
822
- for (upb_enum_begin(&it, enumdesc->enumdef);
823
- !upb_enum_done(&it);
824
- upb_enum_next(&it)) {
825
- const char* name = upb_enum_iter_name(&it);
826
- int32_t value = upb_enum_iter_number(&it);
1269
+ const upb_EnumDef* e = EnumDescriptor_GetEnumDef(_enumdesc);
1270
+ VALUE mod = rb_define_module_id(rb_intern(upb_EnumDef_FullName(e)));
1271
+
1272
+ int n = upb_EnumDef_ValueCount(e);
1273
+ for (int i = 0; i < n; i++) {
1274
+ const upb_EnumValueDef* ev = upb_EnumDef_Value(e, i);
1275
+ upb_Arena* arena = upb_Arena_New();
1276
+ const char* src_name = upb_EnumValueDef_Name(ev);
1277
+ char* name = upb_strdup2(src_name, strlen(src_name), arena);
1278
+ int32_t value = upb_EnumValueDef_Number(ev);
827
1279
  if (name[0] < 'A' || name[0] > 'Z') {
828
- rb_warn("Enum value '%s' does not start with an uppercase letter "
829
- "as is required for Ruby constants.",
830
- name);
1280
+ if (name[0] >= 'a' && name[0] <= 'z') {
1281
+ name[0] -= 32; // auto capitalize
1282
+ } else {
1283
+ rb_warn(
1284
+ "Enum value '%s' does not start with an uppercase letter "
1285
+ "as is required for Ruby constants.",
1286
+ name);
1287
+ }
831
1288
  }
832
1289
  rb_define_const(mod, name, INT2NUM(value));
1290
+ upb_Arena_Free(arena);
833
1291
  }
834
1292
 
835
1293
  rb_define_singleton_method(mod, "lookup", enum_lookup, 1);
@@ -840,20 +1298,132 @@ VALUE build_module_from_enumdesc(VALUE _enumdesc) {
840
1298
  return mod;
841
1299
  }
842
1300
 
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);
1301
+ // Internal to the library; used by Google::Protobuf.deep_copy.
1302
+ upb_Message* Message_deep_copy(const upb_Message* msg, const upb_MessageDef* m,
1303
+ upb_Arena* arena) {
1304
+ // Serialize and parse.
1305
+ upb_Arena* tmp_arena = upb_Arena_New();
1306
+ const upb_MiniTable* layout = upb_MessageDef_MiniTable(m);
1307
+ size_t size;
1308
+
1309
+ upb_Message* new_msg = upb_Message_New(layout, arena);
1310
+ char* data;
1311
+
1312
+ const upb_FileDef* file = upb_MessageDef_File(m);
1313
+ const upb_ExtensionRegistry* extreg =
1314
+ upb_DefPool_ExtensionRegistry(upb_FileDef_Pool(file));
1315
+ if (upb_Encode(msg, layout, 0, tmp_arena, &data, &size) !=
1316
+ kUpb_EncodeStatus_Ok ||
1317
+ upb_Decode(data, size, new_msg, layout, extreg, 0, arena) !=
1318
+ kUpb_DecodeStatus_Ok) {
1319
+ upb_Arena_Free(tmp_arena);
1320
+ rb_raise(cParseError, "Error occurred copying proto");
1321
+ }
1322
+
1323
+ upb_Arena_Free(tmp_arena);
1324
+ return new_msg;
1325
+ }
1326
+
1327
+ const upb_Message* Message_GetUpbMessage(VALUE value, const upb_MessageDef* m,
1328
+ const char* name, upb_Arena* arena) {
1329
+ if (value == Qnil) {
1330
+ rb_raise(cTypeError, "nil message not allowed here.");
1331
+ }
1332
+
1333
+ VALUE klass = CLASS_OF(value);
1334
+ VALUE desc_rb = rb_ivar_get(klass, descriptor_instancevar_interned);
1335
+ const upb_MessageDef* val_m =
1336
+ desc_rb == Qnil ? NULL : Descriptor_GetMsgDef(desc_rb);
1337
+
1338
+ if (val_m != m) {
1339
+ // Check for possible implicit conversions
1340
+ // TODO: hash conversion?
1341
+
1342
+ switch (upb_MessageDef_WellKnownType(m)) {
1343
+ case kUpb_WellKnown_Timestamp: {
1344
+ // Time -> Google::Protobuf::Timestamp
1345
+ const upb_MiniTable* t = upb_MessageDef_MiniTable(m);
1346
+ upb_Message* msg = upb_Message_New(t, arena);
1347
+ upb_MessageValue sec, nsec;
1348
+ struct timespec time;
1349
+ const upb_FieldDef* sec_f = upb_MessageDef_FindFieldByNumber(m, 1);
1350
+ const upb_FieldDef* nsec_f = upb_MessageDef_FindFieldByNumber(m, 2);
1351
+
1352
+ if (!rb_obj_is_kind_of(value, rb_cTime)) goto badtype;
1353
+
1354
+ time = rb_time_timespec(value);
1355
+ sec.int64_val = time.tv_sec;
1356
+ nsec.int32_val = time.tv_nsec;
1357
+ upb_Message_SetFieldByDef(msg, sec_f, sec, arena);
1358
+ upb_Message_SetFieldByDef(msg, nsec_f, nsec, arena);
1359
+ return msg;
1360
+ }
1361
+ case kUpb_WellKnown_Duration: {
1362
+ // Numeric -> Google::Protobuf::Duration
1363
+ const upb_MiniTable* t = upb_MessageDef_MiniTable(m);
1364
+ upb_Message* msg = upb_Message_New(t, arena);
1365
+ upb_MessageValue sec, nsec;
1366
+ const upb_FieldDef* sec_f = upb_MessageDef_FindFieldByNumber(m, 1);
1367
+ const upb_FieldDef* nsec_f = upb_MessageDef_FindFieldByNumber(m, 2);
1368
+
1369
+ if (!rb_obj_is_kind_of(value, rb_cNumeric)) goto badtype;
1370
+
1371
+ sec.int64_val = NUM2LL(value);
1372
+ nsec.int32_val = round((NUM2DBL(value) - NUM2LL(value)) * 1000000000);
1373
+ upb_Message_SetFieldByDef(msg, sec_f, sec, arena);
1374
+ upb_Message_SetFieldByDef(msg, nsec_f, nsec, arena);
1375
+ return msg;
1376
+ }
1377
+ default:
1378
+ badtype:
1379
+ rb_raise(cTypeError,
1380
+ "Invalid type %s to assign to submessage field '%s'.",
1381
+ rb_class2name(CLASS_OF(value)), name);
1382
+ }
858
1383
  }
1384
+
1385
+ Message* self = ruby_to_Message(value);
1386
+ Arena_fuse(self->arena, arena);
1387
+
1388
+ return self->msg;
1389
+ }
1390
+
1391
+ static void Message_define_class(VALUE klass) {
1392
+ rb_define_alloc_func(klass, Message_alloc);
1393
+
1394
+ rb_require("google/protobuf/message_exts");
1395
+ rb_define_method(klass, "method_missing", Message_method_missing, -1);
1396
+ rb_define_method(klass, "respond_to_missing?", Message_respond_to_missing,
1397
+ -1);
1398
+ rb_define_method(klass, "initialize", Message_initialize, -1);
1399
+ rb_define_method(klass, "dup", Message_dup, 0);
1400
+ // Also define #clone so that we don't inherit Object#clone.
1401
+ rb_define_method(klass, "clone", Message_dup, 0);
1402
+ rb_define_method(klass, "==", Message_eq, 1);
1403
+ rb_define_method(klass, "eql?", Message_eq, 1);
1404
+ rb_define_method(klass, "freeze", Message_freeze, 0);
1405
+ rb_define_method(klass, "hash", Message_hash, 0);
1406
+ rb_define_method(klass, "to_h", Message_to_h, 0);
1407
+ rb_define_method(klass, "inspect", Message_inspect, 0);
1408
+ rb_define_method(klass, "to_s", Message_inspect, 0);
1409
+ rb_define_method(klass, "[]", Message_index, 1);
1410
+ rb_define_method(klass, "[]=", Message_index_set, 2);
1411
+ rb_define_singleton_method(klass, "decode", Message_decode, -1);
1412
+ rb_define_singleton_method(klass, "encode", Message_encode, -1);
1413
+ rb_define_singleton_method(klass, "decode_json", Message_decode_json, -1);
1414
+ rb_define_singleton_method(klass, "encode_json", Message_encode_json, -1);
1415
+ rb_define_singleton_method(klass, "descriptor", Message_descriptor, 0);
1416
+ }
1417
+
1418
+ void Message_register(VALUE protobuf) {
1419
+ cParseError = rb_const_get(protobuf, rb_intern("ParseError"));
1420
+ cAbstractMessage =
1421
+ rb_define_class_under(protobuf, "AbstractMessage", rb_cObject);
1422
+ Message_define_class(cAbstractMessage);
1423
+ rb_gc_register_address(&cAbstractMessage);
1424
+
1425
+ // Ruby-interned string: "descriptor". We use this identifier to store an
1426
+ // instance variable on message classes we create in order to link them back
1427
+ // to their descriptors.
1428
+ descriptor_instancevar_interned = rb_intern("@descriptor");
859
1429
  }