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