google-protobuf 3.22.2-aarch64-linux

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.

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