google-protobuf 3.4.0.2 → 3.19.4

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 (41) hide show
  1. checksums.yaml +5 -5
  2. data/ext/google/protobuf_c/convert.c +348 -0
  3. data/ext/google/protobuf_c/convert.h +72 -0
  4. data/ext/google/protobuf_c/defs.c +709 -1188
  5. data/ext/google/protobuf_c/defs.h +107 -0
  6. data/ext/google/protobuf_c/extconf.rb +7 -4
  7. data/ext/google/protobuf_c/map.c +316 -463
  8. data/ext/google/protobuf_c/map.h +67 -0
  9. data/ext/google/protobuf_c/message.c +993 -296
  10. data/ext/google/protobuf_c/message.h +101 -0
  11. data/ext/google/protobuf_c/protobuf.c +403 -50
  12. data/ext/google/protobuf_c/protobuf.h +47 -473
  13. data/ext/google/protobuf_c/repeated_field.c +314 -309
  14. data/ext/google/protobuf_c/repeated_field.h +63 -0
  15. data/ext/google/protobuf_c/ruby-upb.c +9171 -0
  16. data/ext/google/protobuf_c/ruby-upb.h +4704 -0
  17. data/ext/google/protobuf_c/wrap_memcpy.c +1 -1
  18. data/lib/google/protobuf/any_pb.rb +6 -4
  19. data/lib/google/protobuf/api_pb.rb +27 -24
  20. data/lib/google/protobuf/descriptor_dsl.rb +458 -0
  21. data/lib/google/protobuf/descriptor_pb.rb +268 -0
  22. data/lib/google/protobuf/duration_pb.rb +6 -4
  23. data/lib/google/protobuf/empty_pb.rb +4 -2
  24. data/lib/google/protobuf/field_mask_pb.rb +5 -3
  25. data/lib/google/protobuf/message_exts.rb +2 -2
  26. data/lib/google/protobuf/repeated_field.rb +3 -3
  27. data/lib/google/protobuf/source_context_pb.rb +5 -3
  28. data/lib/google/protobuf/struct_pb.rb +23 -21
  29. data/lib/google/protobuf/timestamp_pb.rb +6 -4
  30. data/lib/google/protobuf/type_pb.rb +77 -74
  31. data/lib/google/protobuf/well_known_types.rb +25 -2
  32. data/lib/google/protobuf/wrappers_pb.rb +37 -35
  33. data/lib/google/protobuf.rb +7 -4
  34. data/tests/basic.rb +432 -1115
  35. data/tests/generated_code_test.rb +6 -2
  36. data/tests/stress.rb +1 -1
  37. metadata +22 -30
  38. data/ext/google/protobuf_c/encode_decode.c +0 -1311
  39. data/ext/google/protobuf_c/storage.c +0 -893
  40. data/ext/google/protobuf_c/upb.c +0 -13911
  41. data/ext/google/protobuf_c/upb.h +0 -8872
@@ -1,1311 +0,0 @@
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 "protobuf.h"
32
-
33
- // This function is equivalent to rb_str_cat(), but unlike the real
34
- // rb_str_cat(), it doesn't leak memory in some versions of Ruby.
35
- // For more information, see:
36
- // https://bugs.ruby-lang.org/issues/11328
37
- VALUE noleak_rb_str_cat(VALUE rb_str, const char *str, long len) {
38
- char *p;
39
- size_t oldlen = RSTRING_LEN(rb_str);
40
- rb_str_modify_expand(rb_str, len);
41
- p = RSTRING_PTR(rb_str);
42
- memcpy(p + oldlen, str, len);
43
- rb_str_set_len(rb_str, oldlen + len);
44
- return rb_str;
45
- }
46
-
47
- // -----------------------------------------------------------------------------
48
- // Parsing.
49
- // -----------------------------------------------------------------------------
50
-
51
- #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
52
-
53
- // Creates a handlerdata that simply contains the offset for this field.
54
- static const void* newhandlerdata(upb_handlers* h, uint32_t ofs) {
55
- size_t* hd_ofs = ALLOC(size_t);
56
- *hd_ofs = ofs;
57
- upb_handlers_addcleanup(h, hd_ofs, xfree);
58
- return hd_ofs;
59
- }
60
-
61
- typedef struct {
62
- size_t ofs;
63
- const upb_msgdef *md;
64
- } submsg_handlerdata_t;
65
-
66
- // Creates a handlerdata that contains offset and submessage type information.
67
- static const void *newsubmsghandlerdata(upb_handlers* h, uint32_t ofs,
68
- const upb_fielddef* f) {
69
- submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
70
- hd->ofs = ofs;
71
- hd->md = upb_fielddef_msgsubdef(f);
72
- upb_handlers_addcleanup(h, hd, xfree);
73
- return hd;
74
- }
75
-
76
- typedef struct {
77
- size_t ofs; // union data slot
78
- size_t case_ofs; // oneof_case field
79
- uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
80
- const upb_msgdef *md; // msgdef, for oneof submessage handler
81
- } oneof_handlerdata_t;
82
-
83
- static const void *newoneofhandlerdata(upb_handlers *h,
84
- uint32_t ofs,
85
- uint32_t case_ofs,
86
- const upb_fielddef *f) {
87
- oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
88
- hd->ofs = ofs;
89
- hd->case_ofs = case_ofs;
90
- // We reuse the field tag number as a oneof union discriminant tag. Note that
91
- // we don't expose these numbers to the user, so the only requirement is that
92
- // we have some unique ID for each union case/possibility. The field tag
93
- // numbers are already present and are easy to use so there's no reason to
94
- // create a separate ID space. In addition, using the field tag number here
95
- // lets us easily look up the field in the oneof accessor.
96
- hd->oneof_case_num = upb_fielddef_number(f);
97
- if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
98
- hd->md = upb_fielddef_msgsubdef(f);
99
- } else {
100
- hd->md = NULL;
101
- }
102
- upb_handlers_addcleanup(h, hd, xfree);
103
- return hd;
104
- }
105
-
106
- // A handler that starts a repeated field. Gets the Repeated*Field instance for
107
- // this field (such an instance always exists even in an empty message).
108
- static void *startseq_handler(void* closure, const void* hd) {
109
- MessageHeader* msg = closure;
110
- const size_t *ofs = hd;
111
- return (void*)DEREF(msg, *ofs, VALUE);
112
- }
113
-
114
- // Handlers that append primitive values to a repeated field.
115
- #define DEFINE_APPEND_HANDLER(type, ctype) \
116
- static bool append##type##_handler(void *closure, const void *hd, \
117
- ctype val) { \
118
- VALUE ary = (VALUE)closure; \
119
- RepeatedField_push_native(ary, &val); \
120
- return true; \
121
- }
122
-
123
- DEFINE_APPEND_HANDLER(bool, bool)
124
- DEFINE_APPEND_HANDLER(int32, int32_t)
125
- DEFINE_APPEND_HANDLER(uint32, uint32_t)
126
- DEFINE_APPEND_HANDLER(float, float)
127
- DEFINE_APPEND_HANDLER(int64, int64_t)
128
- DEFINE_APPEND_HANDLER(uint64, uint64_t)
129
- DEFINE_APPEND_HANDLER(double, double)
130
-
131
- // Appends a string to a repeated field.
132
- static void* appendstr_handler(void *closure,
133
- const void *hd,
134
- size_t size_hint) {
135
- VALUE ary = (VALUE)closure;
136
- VALUE str = rb_str_new2("");
137
- rb_enc_associate(str, kRubyStringUtf8Encoding);
138
- RepeatedField_push_native(ary, &str);
139
- return (void*)str;
140
- }
141
-
142
- // Appends a 'bytes' string to a repeated field.
143
- static void* appendbytes_handler(void *closure,
144
- const void *hd,
145
- size_t size_hint) {
146
- VALUE ary = (VALUE)closure;
147
- VALUE str = rb_str_new2("");
148
- rb_enc_associate(str, kRubyString8bitEncoding);
149
- RepeatedField_push_native(ary, &str);
150
- return (void*)str;
151
- }
152
-
153
- // Sets a non-repeated string field in a message.
154
- static void* str_handler(void *closure,
155
- const void *hd,
156
- size_t size_hint) {
157
- MessageHeader* msg = closure;
158
- const size_t *ofs = hd;
159
- VALUE str = rb_str_new2("");
160
- rb_enc_associate(str, kRubyStringUtf8Encoding);
161
- DEREF(msg, *ofs, VALUE) = str;
162
- return (void*)str;
163
- }
164
-
165
- // Sets a non-repeated 'bytes' field in a message.
166
- static void* bytes_handler(void *closure,
167
- const void *hd,
168
- size_t size_hint) {
169
- MessageHeader* msg = closure;
170
- const size_t *ofs = hd;
171
- VALUE str = rb_str_new2("");
172
- rb_enc_associate(str, kRubyString8bitEncoding);
173
- DEREF(msg, *ofs, VALUE) = str;
174
- return (void*)str;
175
- }
176
-
177
- static size_t stringdata_handler(void* closure, const void* hd,
178
- const char* str, size_t len,
179
- const upb_bufhandle* handle) {
180
- VALUE rb_str = (VALUE)closure;
181
- noleak_rb_str_cat(rb_str, str, len);
182
- return len;
183
- }
184
-
185
- static bool stringdata_end_handler(void* closure, const void* hd) {
186
- MessageHeader* msg = closure;
187
- const size_t *ofs = hd;
188
- VALUE rb_str = DEREF(msg, *ofs, VALUE);
189
- rb_obj_freeze(rb_str);
190
- return true;
191
- }
192
-
193
- static bool appendstring_end_handler(void* closure, const void* hd) {
194
- VALUE ary = (VALUE)closure;
195
- int size = RepeatedField_size(ary);
196
- VALUE* last = RepeatedField_index_native(ary, size - 1);
197
- VALUE rb_str = *last;
198
- rb_obj_freeze(rb_str);
199
- return true;
200
- }
201
-
202
- // Appends a submessage to a repeated field (a regular Ruby array for now).
203
- static void *appendsubmsg_handler(void *closure, const void *hd) {
204
- VALUE ary = (VALUE)closure;
205
- const submsg_handlerdata_t *submsgdata = hd;
206
- VALUE subdesc =
207
- get_def_obj((void*)submsgdata->md);
208
- VALUE subklass = Descriptor_msgclass(subdesc);
209
- MessageHeader* submsg;
210
-
211
- VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
212
- RepeatedField_push(ary, submsg_rb);
213
-
214
- TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
215
- return submsg;
216
- }
217
-
218
- // Sets a non-repeated submessage field in a message.
219
- static void *submsg_handler(void *closure, const void *hd) {
220
- MessageHeader* msg = closure;
221
- const submsg_handlerdata_t* submsgdata = hd;
222
- VALUE subdesc =
223
- get_def_obj((void*)submsgdata->md);
224
- VALUE subklass = Descriptor_msgclass(subdesc);
225
- VALUE submsg_rb;
226
- MessageHeader* submsg;
227
-
228
- if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
229
- DEREF(msg, submsgdata->ofs, VALUE) =
230
- rb_class_new_instance(0, NULL, subklass);
231
- }
232
-
233
- submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
234
- TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
235
- return submsg;
236
- }
237
-
238
- // Handler data for startmap/endmap handlers.
239
- typedef struct {
240
- size_t ofs;
241
- upb_fieldtype_t key_field_type;
242
- upb_fieldtype_t value_field_type;
243
-
244
- // We know that we can hold this reference because the handlerdata has the
245
- // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
246
- // a reference to the upb_msgdef, which in turn has references to its subdefs.
247
- const upb_def* value_field_subdef;
248
- } map_handlerdata_t;
249
-
250
- // Temporary frame for map parsing: at the beginning of a map entry message, a
251
- // submsg handler allocates a frame to hold (i) a reference to the Map object
252
- // into which this message will be inserted and (ii) storage slots to
253
- // temporarily hold the key and value for this map entry until the end of the
254
- // submessage. When the submessage ends, another handler is called to insert the
255
- // value into the map.
256
- typedef struct {
257
- VALUE map;
258
- const map_handlerdata_t* handlerdata;
259
- char key_storage[NATIVE_SLOT_MAX_SIZE];
260
- char value_storage[NATIVE_SLOT_MAX_SIZE];
261
- } map_parse_frame_t;
262
-
263
- static void MapParseFrame_mark(void* _self) {
264
- map_parse_frame_t* frame = _self;
265
-
266
- // This shouldn't strictly be necessary since this should be rooted by the
267
- // message itself, but it can't hurt.
268
- rb_gc_mark(frame->map);
269
-
270
- native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
271
- native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
272
- }
273
-
274
- void MapParseFrame_free(void* self) {
275
- xfree(self);
276
- }
277
-
278
- rb_data_type_t MapParseFrame_type = {
279
- "MapParseFrame",
280
- { MapParseFrame_mark, MapParseFrame_free, NULL },
281
- };
282
-
283
- // Array of Ruby objects wrapping map_parse_frame_t.
284
- // We don't allow multiple concurrent decodes, so we assume that this global
285
- // variable is specific to the "current" decode.
286
- VALUE map_parse_frames;
287
-
288
- static map_parse_frame_t* map_push_frame(VALUE map,
289
- const map_handlerdata_t* handlerdata) {
290
- map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
291
- frame->handlerdata = handlerdata;
292
- frame->map = map;
293
- native_slot_init(handlerdata->key_field_type, &frame->key_storage);
294
- native_slot_init(handlerdata->value_field_type, &frame->value_storage);
295
-
296
- rb_ary_push(map_parse_frames,
297
- TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
298
-
299
- return frame;
300
- }
301
-
302
- static void map_pop_frame() {
303
- rb_ary_pop(map_parse_frames);
304
- }
305
-
306
- // Handler to begin a map entry: allocates a temporary frame. This is the
307
- // 'startsubmsg' handler on the msgdef that contains the map field.
308
- static void *startmapentry_handler(void *closure, const void *hd) {
309
- MessageHeader* msg = closure;
310
- const map_handlerdata_t* mapdata = hd;
311
- VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
312
-
313
- return map_push_frame(map_rb, mapdata);
314
- }
315
-
316
- // Handler to end a map entry: inserts the value defined during the message into
317
- // the map. This is the 'endmsg' handler on the map entry msgdef.
318
- static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
319
- map_parse_frame_t* frame = closure;
320
- const map_handlerdata_t* mapdata = hd;
321
-
322
- VALUE key = native_slot_get(
323
- mapdata->key_field_type, Qnil,
324
- &frame->key_storage);
325
-
326
- VALUE value_field_typeclass = Qnil;
327
- VALUE value;
328
-
329
- if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
330
- mapdata->value_field_type == UPB_TYPE_ENUM) {
331
- value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
332
- }
333
-
334
- value = native_slot_get(
335
- mapdata->value_field_type, value_field_typeclass,
336
- &frame->value_storage);
337
-
338
- Map_index_set(frame->map, key, value);
339
- map_pop_frame();
340
-
341
- return true;
342
- }
343
-
344
- // Allocates a new map_handlerdata_t given the map entry message definition. If
345
- // the offset of the field within the parent message is also given, that is
346
- // added to the handler data as well. Note that this is called *twice* per map
347
- // field: once in the parent message handler setup when setting the startsubmsg
348
- // handler and once in the map entry message handler setup when setting the
349
- // key/value and endmsg handlers. The reason is that there is no easy way to
350
- // pass the handlerdata down to the sub-message handler setup.
351
- static map_handlerdata_t* new_map_handlerdata(
352
- size_t ofs,
353
- const upb_msgdef* mapentry_def,
354
- Descriptor* desc) {
355
- const upb_fielddef* key_field;
356
- const upb_fielddef* value_field;
357
- map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
358
- hd->ofs = ofs;
359
- key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
360
- assert(key_field != NULL);
361
- hd->key_field_type = upb_fielddef_type(key_field);
362
- value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
363
- assert(value_field != NULL);
364
- hd->value_field_type = upb_fielddef_type(value_field);
365
- hd->value_field_subdef = upb_fielddef_subdef(value_field);
366
-
367
- return hd;
368
- }
369
-
370
- // Handlers that set primitive values in oneofs.
371
- #define DEFINE_ONEOF_HANDLER(type, ctype) \
372
- static bool oneof##type##_handler(void *closure, const void *hd, \
373
- ctype val) { \
374
- const oneof_handlerdata_t *oneofdata = hd; \
375
- DEREF(closure, oneofdata->case_ofs, uint32_t) = \
376
- oneofdata->oneof_case_num; \
377
- DEREF(closure, oneofdata->ofs, ctype) = val; \
378
- return true; \
379
- }
380
-
381
- DEFINE_ONEOF_HANDLER(bool, bool)
382
- DEFINE_ONEOF_HANDLER(int32, int32_t)
383
- DEFINE_ONEOF_HANDLER(uint32, uint32_t)
384
- DEFINE_ONEOF_HANDLER(float, float)
385
- DEFINE_ONEOF_HANDLER(int64, int64_t)
386
- DEFINE_ONEOF_HANDLER(uint64, uint64_t)
387
- DEFINE_ONEOF_HANDLER(double, double)
388
-
389
- #undef DEFINE_ONEOF_HANDLER
390
-
391
- // Handlers for strings in a oneof.
392
- static void *oneofstr_handler(void *closure,
393
- const void *hd,
394
- size_t size_hint) {
395
- MessageHeader* msg = closure;
396
- const oneof_handlerdata_t *oneofdata = hd;
397
- VALUE str = rb_str_new2("");
398
- rb_enc_associate(str, kRubyStringUtf8Encoding);
399
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
400
- oneofdata->oneof_case_num;
401
- DEREF(msg, oneofdata->ofs, VALUE) = str;
402
- return (void*)str;
403
- }
404
-
405
- static void *oneofbytes_handler(void *closure,
406
- const void *hd,
407
- size_t size_hint) {
408
- MessageHeader* msg = closure;
409
- const oneof_handlerdata_t *oneofdata = hd;
410
- VALUE str = rb_str_new2("");
411
- rb_enc_associate(str, kRubyString8bitEncoding);
412
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
413
- oneofdata->oneof_case_num;
414
- DEREF(msg, oneofdata->ofs, VALUE) = str;
415
- return (void*)str;
416
- }
417
-
418
- static bool oneofstring_end_handler(void* closure, const void* hd) {
419
- MessageHeader* msg = closure;
420
- const oneof_handlerdata_t *oneofdata = hd;
421
- rb_obj_freeze(DEREF(msg, oneofdata->ofs, VALUE));
422
- return true;
423
- }
424
-
425
- // Handler for a submessage field in a oneof.
426
- static void *oneofsubmsg_handler(void *closure,
427
- const void *hd) {
428
- MessageHeader* msg = closure;
429
- const oneof_handlerdata_t *oneofdata = hd;
430
- uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
431
-
432
- VALUE subdesc =
433
- get_def_obj((void*)oneofdata->md);
434
- VALUE subklass = Descriptor_msgclass(subdesc);
435
- VALUE submsg_rb;
436
- MessageHeader* submsg;
437
-
438
- if (oldcase != oneofdata->oneof_case_num ||
439
- DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
440
- DEREF(msg, oneofdata->ofs, VALUE) =
441
- rb_class_new_instance(0, NULL, subklass);
442
- }
443
- // Set the oneof case *after* allocating the new class instance -- otherwise,
444
- // if the Ruby GC is invoked as part of a call into the VM, it might invoke
445
- // our mark routines, and our mark routines might see the case value
446
- // indicating a VALUE is present and expect a valid VALUE. See comment in
447
- // layout_set() for more detail: basically, the change to the value and the
448
- // case must be atomic w.r.t. the Ruby VM.
449
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
450
- oneofdata->oneof_case_num;
451
-
452
- submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
453
- TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
454
- return submsg;
455
- }
456
-
457
- // Set up handlers for a repeated field.
458
- static void add_handlers_for_repeated_field(upb_handlers *h,
459
- const upb_fielddef *f,
460
- size_t offset) {
461
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
462
- upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
463
- upb_handlers_setstartseq(h, f, startseq_handler, &attr);
464
- upb_handlerattr_uninit(&attr);
465
-
466
- switch (upb_fielddef_type(f)) {
467
-
468
- #define SET_HANDLER(utype, ltype) \
469
- case utype: \
470
- upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
471
- break;
472
-
473
- SET_HANDLER(UPB_TYPE_BOOL, bool);
474
- SET_HANDLER(UPB_TYPE_INT32, int32);
475
- SET_HANDLER(UPB_TYPE_UINT32, uint32);
476
- SET_HANDLER(UPB_TYPE_ENUM, int32);
477
- SET_HANDLER(UPB_TYPE_FLOAT, float);
478
- SET_HANDLER(UPB_TYPE_INT64, int64);
479
- SET_HANDLER(UPB_TYPE_UINT64, uint64);
480
- SET_HANDLER(UPB_TYPE_DOUBLE, double);
481
-
482
- #undef SET_HANDLER
483
-
484
- case UPB_TYPE_STRING:
485
- case UPB_TYPE_BYTES: {
486
- bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
487
- upb_handlers_setstartstr(h, f, is_bytes ?
488
- appendbytes_handler : appendstr_handler,
489
- NULL);
490
- upb_handlers_setstring(h, f, stringdata_handler, NULL);
491
- upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
492
- break;
493
- }
494
- case UPB_TYPE_MESSAGE: {
495
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
496
- upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
497
- upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
498
- upb_handlerattr_uninit(&attr);
499
- break;
500
- }
501
- }
502
- }
503
-
504
- // Set up handlers for a singular field.
505
- static void add_handlers_for_singular_field(upb_handlers *h,
506
- const upb_fielddef *f,
507
- size_t offset) {
508
- switch (upb_fielddef_type(f)) {
509
- case UPB_TYPE_BOOL:
510
- case UPB_TYPE_INT32:
511
- case UPB_TYPE_UINT32:
512
- case UPB_TYPE_ENUM:
513
- case UPB_TYPE_FLOAT:
514
- case UPB_TYPE_INT64:
515
- case UPB_TYPE_UINT64:
516
- case UPB_TYPE_DOUBLE:
517
- upb_msg_setscalarhandler(h, f, offset, -1);
518
- break;
519
- case UPB_TYPE_STRING:
520
- case UPB_TYPE_BYTES: {
521
- bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
522
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
523
- upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
524
- upb_handlers_setstartstr(h, f,
525
- is_bytes ? bytes_handler : str_handler,
526
- &attr);
527
- upb_handlers_setstring(h, f, stringdata_handler, &attr);
528
- upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
529
- upb_handlerattr_uninit(&attr);
530
- break;
531
- }
532
- case UPB_TYPE_MESSAGE: {
533
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
534
- upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
535
- upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
536
- upb_handlerattr_uninit(&attr);
537
- break;
538
- }
539
- }
540
- }
541
-
542
- // Adds handlers to a map field.
543
- static void add_handlers_for_mapfield(upb_handlers* h,
544
- const upb_fielddef* fielddef,
545
- size_t offset,
546
- Descriptor* desc) {
547
- const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
548
- map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
549
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
550
-
551
- upb_handlers_addcleanup(h, hd, xfree);
552
- upb_handlerattr_sethandlerdata(&attr, hd);
553
- upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
554
- upb_handlerattr_uninit(&attr);
555
- }
556
-
557
- // Adds handlers to a map-entry msgdef.
558
- static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
559
- upb_handlers* h,
560
- Descriptor* desc) {
561
- const upb_fielddef* key_field = map_entry_key(msgdef);
562
- const upb_fielddef* value_field = map_entry_value(msgdef);
563
- map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
564
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
565
-
566
- upb_handlers_addcleanup(h, hd, xfree);
567
- upb_handlerattr_sethandlerdata(&attr, hd);
568
- upb_handlers_setendmsg(h, endmap_handler, &attr);
569
-
570
- add_handlers_for_singular_field(
571
- h, key_field,
572
- offsetof(map_parse_frame_t, key_storage));
573
- add_handlers_for_singular_field(
574
- h, value_field,
575
- offsetof(map_parse_frame_t, value_storage));
576
- }
577
-
578
- // Set up handlers for a oneof field.
579
- static void add_handlers_for_oneof_field(upb_handlers *h,
580
- const upb_fielddef *f,
581
- size_t offset,
582
- size_t oneof_case_offset) {
583
-
584
- upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
585
- upb_handlerattr_sethandlerdata(
586
- &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
587
-
588
- switch (upb_fielddef_type(f)) {
589
-
590
- #define SET_HANDLER(utype, ltype) \
591
- case utype: \
592
- upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
593
- break;
594
-
595
- SET_HANDLER(UPB_TYPE_BOOL, bool);
596
- SET_HANDLER(UPB_TYPE_INT32, int32);
597
- SET_HANDLER(UPB_TYPE_UINT32, uint32);
598
- SET_HANDLER(UPB_TYPE_ENUM, int32);
599
- SET_HANDLER(UPB_TYPE_FLOAT, float);
600
- SET_HANDLER(UPB_TYPE_INT64, int64);
601
- SET_HANDLER(UPB_TYPE_UINT64, uint64);
602
- SET_HANDLER(UPB_TYPE_DOUBLE, double);
603
-
604
- #undef SET_HANDLER
605
-
606
- case UPB_TYPE_STRING:
607
- case UPB_TYPE_BYTES: {
608
- bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
609
- upb_handlers_setstartstr(h, f, is_bytes ?
610
- oneofbytes_handler : oneofstr_handler,
611
- &attr);
612
- upb_handlers_setstring(h, f, stringdata_handler, NULL);
613
- upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
614
- break;
615
- }
616
- case UPB_TYPE_MESSAGE: {
617
- upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
618
- break;
619
- }
620
- }
621
-
622
- upb_handlerattr_uninit(&attr);
623
- }
624
-
625
-
626
- static void add_handlers_for_message(const void *closure, upb_handlers *h) {
627
- const upb_msgdef* msgdef = upb_handlers_msgdef(h);
628
- Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
629
- upb_msg_field_iter i;
630
-
631
- // If this is a mapentry message type, set up a special set of handlers and
632
- // bail out of the normal (user-defined) message type handling.
633
- if (upb_msgdef_mapentry(msgdef)) {
634
- add_handlers_for_mapentry(msgdef, h, desc);
635
- return;
636
- }
637
-
638
- // Ensure layout exists. We may be invoked to create handlers for a given
639
- // message if we are included as a submsg of another message type before our
640
- // class is actually built, so to work around this, we just create the layout
641
- // (and handlers, in the class-building function) on-demand.
642
- if (desc->layout == NULL) {
643
- desc->layout = create_layout(desc->msgdef);
644
- }
645
-
646
- for (upb_msg_field_begin(&i, desc->msgdef);
647
- !upb_msg_field_done(&i);
648
- upb_msg_field_next(&i)) {
649
- const upb_fielddef *f = upb_msg_iter_field(&i);
650
- size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
651
- sizeof(MessageHeader);
652
-
653
- if (upb_fielddef_containingoneof(f)) {
654
- size_t oneof_case_offset =
655
- desc->layout->fields[upb_fielddef_index(f)].case_offset +
656
- sizeof(MessageHeader);
657
- add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
658
- } else if (is_map_field(f)) {
659
- add_handlers_for_mapfield(h, f, offset, desc);
660
- } else if (upb_fielddef_isseq(f)) {
661
- add_handlers_for_repeated_field(h, f, offset);
662
- } else {
663
- add_handlers_for_singular_field(h, f, offset);
664
- }
665
- }
666
- }
667
-
668
- // Creates upb handlers for populating a message.
669
- static const upb_handlers *new_fill_handlers(Descriptor* desc,
670
- const void* owner) {
671
- // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
672
- // handlers, reuse subdef handlers so that e.g. if we already parse
673
- // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
674
- // parse A-with-field-of-type-B-with-field-of-type-C.
675
- return upb_handlers_newfrozen(desc->msgdef, owner,
676
- add_handlers_for_message, NULL);
677
- }
678
-
679
- // Constructs the handlers for filling a message's data into an in-memory
680
- // object.
681
- const upb_handlers* get_fill_handlers(Descriptor* desc) {
682
- if (!desc->fill_handlers) {
683
- desc->fill_handlers =
684
- new_fill_handlers(desc, &desc->fill_handlers);
685
- }
686
- return desc->fill_handlers;
687
- }
688
-
689
- // Constructs the upb decoder method for parsing messages of this type.
690
- // This is called from the message class creation code.
691
- const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
692
- const void* owner) {
693
- const upb_handlers* handlers = get_fill_handlers(desc);
694
- upb_pbdecodermethodopts opts;
695
- upb_pbdecodermethodopts_init(&opts, handlers);
696
-
697
- return upb_pbdecodermethod_new(&opts, owner);
698
- }
699
-
700
- static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
701
- if (desc->fill_method == NULL) {
702
- desc->fill_method = new_fillmsg_decodermethod(
703
- desc, &desc->fill_method);
704
- }
705
- return desc->fill_method;
706
- }
707
-
708
- static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
709
- if (desc->json_fill_method == NULL) {
710
- desc->json_fill_method =
711
- upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
712
- }
713
- return desc->json_fill_method;
714
- }
715
-
716
-
717
- // Stack-allocated context during an encode/decode operation. Contains the upb
718
- // environment and its stack-based allocator, an initial buffer for allocations
719
- // to avoid malloc() when possible, and a template for Ruby exception messages
720
- // if any error occurs.
721
- #define STACK_ENV_STACKBYTES 4096
722
- typedef struct {
723
- upb_env env;
724
- const char* ruby_error_template;
725
- char allocbuf[STACK_ENV_STACKBYTES];
726
- } stackenv;
727
-
728
- static void stackenv_init(stackenv* se, const char* errmsg);
729
- static void stackenv_uninit(stackenv* se);
730
-
731
- // Callback invoked by upb if any error occurs during parsing or serialization.
732
- static bool env_error_func(void* ud, const upb_status* status) {
733
- stackenv* se = ud;
734
- // Free the env -- rb_raise will longjmp up the stack past the encode/decode
735
- // function so it would not otherwise have been freed.
736
- stackenv_uninit(se);
737
-
738
- // TODO(haberman): have a way to verify that this is actually a parse error,
739
- // instead of just throwing "parse error" unconditionally.
740
- rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
741
- // Never reached: rb_raise() always longjmp()s up the stack, past all of our
742
- // code, back to Ruby.
743
- return false;
744
- }
745
-
746
- static void stackenv_init(stackenv* se, const char* errmsg) {
747
- se->ruby_error_template = errmsg;
748
- upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
749
- upb_env_seterrorfunc(&se->env, env_error_func, se);
750
- }
751
-
752
- static void stackenv_uninit(stackenv* se) {
753
- upb_env_uninit(&se->env);
754
- }
755
-
756
- /*
757
- * call-seq:
758
- * MessageClass.decode(data) => message
759
- *
760
- * Decodes the given data (as a string containing bytes in protocol buffers wire
761
- * format) under the interpretration given by this message class's definition
762
- * and returns a message object with the corresponding field values.
763
- */
764
- VALUE Message_decode(VALUE klass, VALUE data) {
765
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
766
- Descriptor* desc = ruby_to_Descriptor(descriptor);
767
- VALUE msgklass = Descriptor_msgclass(descriptor);
768
- VALUE msg_rb;
769
- MessageHeader* msg;
770
-
771
- if (TYPE(data) != T_STRING) {
772
- rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
773
- }
774
-
775
- msg_rb = rb_class_new_instance(0, NULL, msgklass);
776
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
777
-
778
- // We generally expect this to be clear already, but clear it in case parsing
779
- // previously got interrupted somehow.
780
- rb_ary_clear(map_parse_frames);
781
-
782
- {
783
- const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
784
- const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
785
- stackenv se;
786
- upb_sink sink;
787
- upb_pbdecoder* decoder;
788
- stackenv_init(&se, "Error occurred during parsing: %s");
789
-
790
- upb_sink_reset(&sink, h, msg);
791
- decoder = upb_pbdecoder_create(&se.env, method, &sink);
792
- upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
793
- upb_pbdecoder_input(decoder));
794
-
795
- stackenv_uninit(&se);
796
- }
797
-
798
- return msg_rb;
799
- }
800
-
801
- /*
802
- * call-seq:
803
- * MessageClass.decode_json(data) => message
804
- *
805
- * Decodes the given data (as a string containing bytes in protocol buffers wire
806
- * format) under the interpretration given by this message class's definition
807
- * and returns a message object with the corresponding field values.
808
- */
809
- VALUE Message_decode_json(VALUE klass, VALUE data) {
810
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
811
- Descriptor* desc = ruby_to_Descriptor(descriptor);
812
- VALUE msgklass = Descriptor_msgclass(descriptor);
813
- VALUE msg_rb;
814
- MessageHeader* msg;
815
-
816
- if (TYPE(data) != T_STRING) {
817
- rb_raise(rb_eArgError, "Expected string for JSON data.");
818
- }
819
- // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
820
- // convert, because string handlers pass data directly to message string
821
- // fields.
822
-
823
- msg_rb = rb_class_new_instance(0, NULL, msgklass);
824
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
825
-
826
- // We generally expect this to be clear already, but clear it in case parsing
827
- // previously got interrupted somehow.
828
- rb_ary_clear(map_parse_frames);
829
-
830
- {
831
- const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
832
- stackenv se;
833
- upb_sink sink;
834
- upb_json_parser* parser;
835
- stackenv_init(&se, "Error occurred during parsing: %s");
836
-
837
- upb_sink_reset(&sink, get_fill_handlers(desc), msg);
838
- parser = upb_json_parser_create(&se.env, method, &sink);
839
- upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
840
- upb_json_parser_input(parser));
841
-
842
- stackenv_uninit(&se);
843
- }
844
-
845
- return msg_rb;
846
- }
847
-
848
- // -----------------------------------------------------------------------------
849
- // Serializing.
850
- // -----------------------------------------------------------------------------
851
- //
852
- // The code below also comes from upb's prototype Ruby binding, developed by
853
- // haberman@.
854
-
855
- /* stringsink *****************************************************************/
856
-
857
- // This should probably be factored into a common upb component.
858
-
859
- typedef struct {
860
- upb_byteshandler handler;
861
- upb_bytessink sink;
862
- char *ptr;
863
- size_t len, size;
864
- } stringsink;
865
-
866
- static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
867
- stringsink *sink = _sink;
868
- sink->len = 0;
869
- return sink;
870
- }
871
-
872
- static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
873
- size_t len, const upb_bufhandle *handle) {
874
- stringsink *sink = _sink;
875
- size_t new_size = sink->size;
876
-
877
- UPB_UNUSED(hd);
878
- UPB_UNUSED(handle);
879
-
880
- while (sink->len + len > new_size) {
881
- new_size *= 2;
882
- }
883
-
884
- if (new_size != sink->size) {
885
- sink->ptr = realloc(sink->ptr, new_size);
886
- sink->size = new_size;
887
- }
888
-
889
- memcpy(sink->ptr + sink->len, ptr, len);
890
- sink->len += len;
891
-
892
- return len;
893
- }
894
-
895
- void stringsink_init(stringsink *sink) {
896
- upb_byteshandler_init(&sink->handler);
897
- upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
898
- upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
899
-
900
- upb_bytessink_reset(&sink->sink, &sink->handler, sink);
901
-
902
- sink->size = 32;
903
- sink->ptr = malloc(sink->size);
904
- sink->len = 0;
905
- }
906
-
907
- void stringsink_uninit(stringsink *sink) {
908
- free(sink->ptr);
909
- }
910
-
911
- /* msgvisitor *****************************************************************/
912
-
913
- // TODO: If/when we support proto2 semantics in addition to the current proto3
914
- // semantics, which means that we have true field presence, we will want to
915
- // modify msgvisitor so that it emits all present fields rather than all
916
- // non-default-value fields.
917
-
918
- static void putmsg(VALUE msg, const Descriptor* desc,
919
- upb_sink *sink, int depth, bool emit_defaults);
920
-
921
- static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
922
- upb_selector_t ret;
923
- bool ok = upb_handlers_getselector(f, type, &ret);
924
- UPB_ASSERT(ok);
925
- return ret;
926
- }
927
-
928
- static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
929
- upb_sink subsink;
930
-
931
- if (str == Qnil) return;
932
-
933
- assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
934
-
935
- // We should be guaranteed that the string has the correct encoding because
936
- // we ensured this at assignment time and then froze the string.
937
- if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
938
- assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
939
- } else {
940
- assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
941
- }
942
-
943
- upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
944
- &subsink);
945
- upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
946
- RSTRING_LEN(str), NULL);
947
- upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
948
- }
949
-
950
- static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
951
- int depth, bool emit_defaults) {
952
- upb_sink subsink;
953
- VALUE descriptor;
954
- Descriptor* subdesc;
955
-
956
- if (submsg == Qnil) return;
957
-
958
- descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
959
- subdesc = ruby_to_Descriptor(descriptor);
960
-
961
- upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
962
- putmsg(submsg, subdesc, &subsink, depth + 1, emit_defaults);
963
- upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
964
- }
965
-
966
- static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
967
- int depth, bool emit_defaults) {
968
- upb_sink subsink;
969
- upb_fieldtype_t type = upb_fielddef_type(f);
970
- upb_selector_t sel = 0;
971
- int size;
972
-
973
- if (ary == Qnil) return;
974
-
975
- upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
976
-
977
- if (upb_fielddef_isprimitive(f)) {
978
- sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
979
- }
980
-
981
- size = NUM2INT(RepeatedField_length(ary));
982
- for (int i = 0; i < size; i++) {
983
- void* memory = RepeatedField_index_native(ary, i);
984
- switch (type) {
985
- #define T(upbtypeconst, upbtype, ctype) \
986
- case upbtypeconst: \
987
- upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
988
- break;
989
-
990
- T(UPB_TYPE_FLOAT, float, float)
991
- T(UPB_TYPE_DOUBLE, double, double)
992
- T(UPB_TYPE_BOOL, bool, int8_t)
993
- case UPB_TYPE_ENUM:
994
- T(UPB_TYPE_INT32, int32, int32_t)
995
- T(UPB_TYPE_UINT32, uint32, uint32_t)
996
- T(UPB_TYPE_INT64, int64, int64_t)
997
- T(UPB_TYPE_UINT64, uint64, uint64_t)
998
-
999
- case UPB_TYPE_STRING:
1000
- case UPB_TYPE_BYTES:
1001
- putstr(*((VALUE *)memory), f, &subsink);
1002
- break;
1003
- case UPB_TYPE_MESSAGE:
1004
- putsubmsg(*((VALUE *)memory), f, &subsink, depth, emit_defaults);
1005
- break;
1006
-
1007
- #undef T
1008
-
1009
- }
1010
- }
1011
- upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1012
- }
1013
-
1014
- static void put_ruby_value(VALUE value,
1015
- const upb_fielddef *f,
1016
- VALUE type_class,
1017
- int depth,
1018
- upb_sink *sink,
1019
- bool emit_defaults) {
1020
- upb_selector_t sel = 0;
1021
- if (upb_fielddef_isprimitive(f)) {
1022
- sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1023
- }
1024
-
1025
- switch (upb_fielddef_type(f)) {
1026
- case UPB_TYPE_INT32:
1027
- upb_sink_putint32(sink, sel, NUM2INT(value));
1028
- break;
1029
- case UPB_TYPE_INT64:
1030
- upb_sink_putint64(sink, sel, NUM2LL(value));
1031
- break;
1032
- case UPB_TYPE_UINT32:
1033
- upb_sink_putuint32(sink, sel, NUM2UINT(value));
1034
- break;
1035
- case UPB_TYPE_UINT64:
1036
- upb_sink_putuint64(sink, sel, NUM2ULL(value));
1037
- break;
1038
- case UPB_TYPE_FLOAT:
1039
- upb_sink_putfloat(sink, sel, NUM2DBL(value));
1040
- break;
1041
- case UPB_TYPE_DOUBLE:
1042
- upb_sink_putdouble(sink, sel, NUM2DBL(value));
1043
- break;
1044
- case UPB_TYPE_ENUM: {
1045
- if (TYPE(value) == T_SYMBOL) {
1046
- value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
1047
- }
1048
- upb_sink_putint32(sink, sel, NUM2INT(value));
1049
- break;
1050
- }
1051
- case UPB_TYPE_BOOL:
1052
- upb_sink_putbool(sink, sel, value == Qtrue);
1053
- break;
1054
- case UPB_TYPE_STRING:
1055
- case UPB_TYPE_BYTES:
1056
- putstr(value, f, sink);
1057
- break;
1058
- case UPB_TYPE_MESSAGE:
1059
- putsubmsg(value, f, sink, depth, emit_defaults);
1060
- }
1061
- }
1062
-
1063
- static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
1064
- int depth, bool emit_defaults) {
1065
- Map* self;
1066
- upb_sink subsink;
1067
- const upb_fielddef* key_field;
1068
- const upb_fielddef* value_field;
1069
- Map_iter it;
1070
-
1071
- if (map == Qnil) return;
1072
- self = ruby_to_Map(map);
1073
-
1074
- upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1075
-
1076
- assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
1077
- key_field = map_field_key(f);
1078
- value_field = map_field_value(f);
1079
-
1080
- for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
1081
- VALUE key = Map_iter_key(&it);
1082
- VALUE value = Map_iter_value(&it);
1083
- upb_status status;
1084
-
1085
- upb_sink entry_sink;
1086
- upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
1087
- &entry_sink);
1088
- upb_sink_startmsg(&entry_sink);
1089
-
1090
- put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink, emit_defaults);
1091
- put_ruby_value(value, value_field, self->value_type_class, depth + 1,
1092
- &entry_sink, emit_defaults);
1093
-
1094
- upb_sink_endmsg(&entry_sink, &status);
1095
- upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1096
- }
1097
-
1098
- upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1099
- }
1100
-
1101
- static void putmsg(VALUE msg_rb, const Descriptor* desc,
1102
- upb_sink *sink, int depth, bool emit_defaults) {
1103
- MessageHeader* msg;
1104
- upb_msg_field_iter i;
1105
- upb_status status;
1106
-
1107
- upb_sink_startmsg(sink);
1108
-
1109
- // Protect against cycles (possible because users may freely reassign message
1110
- // and repeated fields) by imposing a maximum recursion depth.
1111
- if (depth > ENCODE_MAX_NESTING) {
1112
- rb_raise(rb_eRuntimeError,
1113
- "Maximum recursion depth exceeded during encoding.");
1114
- }
1115
-
1116
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1117
-
1118
- for (upb_msg_field_begin(&i, desc->msgdef);
1119
- !upb_msg_field_done(&i);
1120
- upb_msg_field_next(&i)) {
1121
- upb_fielddef *f = upb_msg_iter_field(&i);
1122
- bool is_matching_oneof = false;
1123
- uint32_t offset =
1124
- desc->layout->fields[upb_fielddef_index(f)].offset +
1125
- sizeof(MessageHeader);
1126
-
1127
- if (upb_fielddef_containingoneof(f)) {
1128
- uint32_t oneof_case_offset =
1129
- desc->layout->fields[upb_fielddef_index(f)].case_offset +
1130
- sizeof(MessageHeader);
1131
- // For a oneof, check that this field is actually present -- skip all the
1132
- // below if not.
1133
- if (DEREF(msg, oneof_case_offset, uint32_t) !=
1134
- upb_fielddef_number(f)) {
1135
- continue;
1136
- }
1137
- // Otherwise, fall through to the appropriate singular-field handler
1138
- // below.
1139
- is_matching_oneof = true;
1140
- }
1141
-
1142
- if (is_map_field(f)) {
1143
- VALUE map = DEREF(msg, offset, VALUE);
1144
- if (map != Qnil || emit_defaults) {
1145
- putmap(map, f, sink, depth, emit_defaults);
1146
- }
1147
- } else if (upb_fielddef_isseq(f)) {
1148
- VALUE ary = DEREF(msg, offset, VALUE);
1149
- if (ary != Qnil) {
1150
- putary(ary, f, sink, depth, emit_defaults);
1151
- }
1152
- } else if (upb_fielddef_isstring(f)) {
1153
- VALUE str = DEREF(msg, offset, VALUE);
1154
- if (is_matching_oneof || emit_defaults || RSTRING_LEN(str) > 0) {
1155
- putstr(str, f, sink);
1156
- }
1157
- } else if (upb_fielddef_issubmsg(f)) {
1158
- putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth, emit_defaults);
1159
- } else {
1160
- upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1161
-
1162
- #define T(upbtypeconst, upbtype, ctype, default_value) \
1163
- case upbtypeconst: { \
1164
- ctype value = DEREF(msg, offset, ctype); \
1165
- if (is_matching_oneof || emit_defaults || value != default_value) { \
1166
- upb_sink_put##upbtype(sink, sel, value); \
1167
- } \
1168
- } \
1169
- break;
1170
-
1171
- switch (upb_fielddef_type(f)) {
1172
- T(UPB_TYPE_FLOAT, float, float, 0.0)
1173
- T(UPB_TYPE_DOUBLE, double, double, 0.0)
1174
- T(UPB_TYPE_BOOL, bool, uint8_t, 0)
1175
- case UPB_TYPE_ENUM:
1176
- T(UPB_TYPE_INT32, int32, int32_t, 0)
1177
- T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
1178
- T(UPB_TYPE_INT64, int64, int64_t, 0)
1179
- T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
1180
-
1181
- case UPB_TYPE_STRING:
1182
- case UPB_TYPE_BYTES:
1183
- case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
1184
- }
1185
-
1186
- #undef T
1187
-
1188
- }
1189
- }
1190
-
1191
- upb_sink_endmsg(sink, &status);
1192
- }
1193
-
1194
- static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
1195
- if (desc->pb_serialize_handlers == NULL) {
1196
- desc->pb_serialize_handlers =
1197
- upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
1198
- }
1199
- return desc->pb_serialize_handlers;
1200
- }
1201
-
1202
- static const upb_handlers* msgdef_json_serialize_handlers(
1203
- Descriptor* desc, bool preserve_proto_fieldnames) {
1204
- if (preserve_proto_fieldnames) {
1205
- if (desc->json_serialize_handlers == NULL) {
1206
- desc->json_serialize_handlers =
1207
- upb_json_printer_newhandlers(
1208
- desc->msgdef, true, &desc->json_serialize_handlers);
1209
- }
1210
- return desc->json_serialize_handlers;
1211
- } else {
1212
- if (desc->json_serialize_handlers_preserve == NULL) {
1213
- desc->json_serialize_handlers_preserve =
1214
- upb_json_printer_newhandlers(
1215
- desc->msgdef, false, &desc->json_serialize_handlers_preserve);
1216
- }
1217
- return desc->json_serialize_handlers_preserve;
1218
- }
1219
- }
1220
-
1221
- /*
1222
- * call-seq:
1223
- * MessageClass.encode(msg) => bytes
1224
- *
1225
- * Encodes the given message object to its serialized form in protocol buffers
1226
- * wire format.
1227
- */
1228
- VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1229
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1230
- Descriptor* desc = ruby_to_Descriptor(descriptor);
1231
-
1232
- stringsink sink;
1233
- stringsink_init(&sink);
1234
-
1235
- {
1236
- const upb_handlers* serialize_handlers =
1237
- msgdef_pb_serialize_handlers(desc);
1238
-
1239
- stackenv se;
1240
- upb_pb_encoder* encoder;
1241
- VALUE ret;
1242
-
1243
- stackenv_init(&se, "Error occurred during encoding: %s");
1244
- encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
1245
-
1246
- putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false);
1247
-
1248
- ret = rb_str_new(sink.ptr, sink.len);
1249
-
1250
- stackenv_uninit(&se);
1251
- stringsink_uninit(&sink);
1252
-
1253
- return ret;
1254
- }
1255
- }
1256
-
1257
- /*
1258
- * call-seq:
1259
- * MessageClass.encode_json(msg) => json_string
1260
- *
1261
- * Encodes the given message object into its serialized JSON representation.
1262
- */
1263
- VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1264
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1265
- Descriptor* desc = ruby_to_Descriptor(descriptor);
1266
- VALUE msg_rb;
1267
- VALUE preserve_proto_fieldnames = Qfalse;
1268
- VALUE emit_defaults = Qfalse;
1269
- stringsink sink;
1270
-
1271
- if (argc < 1 || argc > 2) {
1272
- rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1273
- }
1274
-
1275
- msg_rb = argv[0];
1276
-
1277
- if (argc == 2) {
1278
- VALUE hash_args = argv[1];
1279
- if (TYPE(hash_args) != T_HASH) {
1280
- rb_raise(rb_eArgError, "Expected hash arguments.");
1281
- }
1282
- preserve_proto_fieldnames = rb_hash_lookup2(
1283
- hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
1284
-
1285
- emit_defaults = rb_hash_lookup2(
1286
- hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
1287
- }
1288
-
1289
- stringsink_init(&sink);
1290
-
1291
- {
1292
- const upb_handlers* serialize_handlers =
1293
- msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
1294
- upb_json_printer* printer;
1295
- stackenv se;
1296
- VALUE ret;
1297
-
1298
- stackenv_init(&se, "Error occurred during encoding: %s");
1299
- printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
1300
-
1301
- putmsg(msg_rb, desc, upb_json_printer_input(printer), 0, RTEST(emit_defaults));
1302
-
1303
- ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
1304
-
1305
- stackenv_uninit(&se);
1306
- stringsink_uninit(&sink);
1307
-
1308
- return ret;
1309
- }
1310
- }
1311
-