google-protobuf 3.11.3 → 3.19.3

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.

@@ -1,1758 +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
- typedef struct {
104
- size_t ofs;
105
- int32_t hasbit;
106
- } field_handlerdata_t;
107
-
108
- // Creates a handlerdata that contains the offset and the hasbit for the field
109
- static const void* newhandlerdata(upb_handlers* h, uint32_t ofs, int32_t hasbit) {
110
- field_handlerdata_t *hd = ALLOC(field_handlerdata_t);
111
- hd->ofs = ofs;
112
- hd->hasbit = hasbit;
113
- upb_handlers_addcleanup(h, hd, xfree);
114
- return hd;
115
- }
116
-
117
- typedef struct {
118
- size_t ofs;
119
- int32_t hasbit;
120
- VALUE subklass;
121
- } submsg_handlerdata_t;
122
-
123
- // Creates a handlerdata that contains offset and submessage type information.
124
- static const void *newsubmsghandlerdata(upb_handlers* h,
125
- uint32_t ofs,
126
- int32_t hasbit,
127
- VALUE subklass) {
128
- submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
129
- hd->ofs = ofs;
130
- hd->hasbit = hasbit;
131
- hd->subklass = subklass;
132
- upb_handlers_addcleanup(h, hd, xfree);
133
- return hd;
134
- }
135
-
136
- typedef struct {
137
- size_t ofs; // union data slot
138
- size_t case_ofs; // oneof_case field
139
- uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
140
- VALUE subklass;
141
- } oneof_handlerdata_t;
142
-
143
- static const void *newoneofhandlerdata(upb_handlers *h,
144
- uint32_t ofs,
145
- uint32_t case_ofs,
146
- const upb_fielddef *f,
147
- const Descriptor* desc) {
148
- oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
149
- hd->ofs = ofs;
150
- hd->case_ofs = case_ofs;
151
- // We reuse the field tag number as a oneof union discriminant tag. Note that
152
- // we don't expose these numbers to the user, so the only requirement is that
153
- // we have some unique ID for each union case/possibility. The field tag
154
- // numbers are already present and are easy to use so there's no reason to
155
- // create a separate ID space. In addition, using the field tag number here
156
- // lets us easily look up the field in the oneof accessor.
157
- hd->oneof_case_num = upb_fielddef_number(f);
158
- if (is_value_field(f)) {
159
- hd->oneof_case_num |= ONEOF_CASE_MASK;
160
- }
161
- hd->subklass = field_type_class(desc->layout, f);
162
- upb_handlers_addcleanup(h, hd, xfree);
163
- return hd;
164
- }
165
-
166
- // A handler that starts a repeated field. Gets the Repeated*Field instance for
167
- // this field (such an instance always exists even in an empty message).
168
- static void *startseq_handler(void* closure, const void* hd) {
169
- MessageHeader* msg = closure;
170
- const size_t *ofs = hd;
171
- return (void*)DEREF(msg, *ofs, VALUE);
172
- }
173
-
174
- // Handlers that append primitive values to a repeated field.
175
- #define DEFINE_APPEND_HANDLER(type, ctype) \
176
- static bool append##type##_handler(void *closure, const void *hd, \
177
- ctype val) { \
178
- VALUE ary = (VALUE)closure; \
179
- RepeatedField_push_native(ary, &val); \
180
- return true; \
181
- }
182
-
183
- DEFINE_APPEND_HANDLER(bool, bool)
184
- DEFINE_APPEND_HANDLER(int32, int32_t)
185
- DEFINE_APPEND_HANDLER(uint32, uint32_t)
186
- DEFINE_APPEND_HANDLER(float, float)
187
- DEFINE_APPEND_HANDLER(int64, int64_t)
188
- DEFINE_APPEND_HANDLER(uint64, uint64_t)
189
- DEFINE_APPEND_HANDLER(double, double)
190
-
191
- // Appends a string to a repeated field.
192
- static void* appendstr_handler(void *closure,
193
- const void *hd,
194
- size_t size_hint) {
195
- VALUE ary = (VALUE)closure;
196
- VALUE str = rb_str_new2("");
197
- rb_enc_associate(str, kRubyStringUtf8Encoding);
198
- RepeatedField_push_native(ary, &str);
199
- return (void*)str;
200
- }
201
-
202
- static void set_hasbit(void *closure, int32_t hasbit) {
203
- if (hasbit > 0) {
204
- uint8_t* storage = closure;
205
- storage[hasbit/8] |= 1 << (hasbit % 8);
206
- }
207
- }
208
-
209
- // Appends a 'bytes' string to a repeated field.
210
- static void* appendbytes_handler(void *closure,
211
- const void *hd,
212
- size_t size_hint) {
213
- VALUE ary = (VALUE)closure;
214
- VALUE str = rb_str_new2("");
215
- rb_enc_associate(str, kRubyString8bitEncoding);
216
- RepeatedField_push_native(ary, &str);
217
- return (void*)str;
218
- }
219
-
220
- // Sets a non-repeated string field in a message.
221
- static void* str_handler(void *closure,
222
- const void *hd,
223
- size_t size_hint) {
224
- MessageHeader* msg = closure;
225
- const field_handlerdata_t *fieldhandler = hd;
226
-
227
- VALUE str = rb_str_new2("");
228
- rb_enc_associate(str, kRubyStringUtf8Encoding);
229
- DEREF(msg, fieldhandler->ofs, VALUE) = str;
230
- set_hasbit(closure, fieldhandler->hasbit);
231
- return (void*)str;
232
- }
233
-
234
- // Sets a non-repeated 'bytes' field in a message.
235
- static void* bytes_handler(void *closure,
236
- const void *hd,
237
- size_t size_hint) {
238
- MessageHeader* msg = closure;
239
- const field_handlerdata_t *fieldhandler = hd;
240
-
241
- VALUE str = rb_str_new2("");
242
- rb_enc_associate(str, kRubyString8bitEncoding);
243
- DEREF(msg, fieldhandler->ofs, VALUE) = str;
244
- set_hasbit(closure, fieldhandler->hasbit);
245
- return (void*)str;
246
- }
247
-
248
- static size_t stringdata_handler(void* closure, const void* hd,
249
- const char* str, size_t len,
250
- const upb_bufhandle* handle) {
251
- VALUE rb_str = (VALUE)closure;
252
- noleak_rb_str_cat(rb_str, str, len);
253
- return len;
254
- }
255
-
256
- static bool stringdata_end_handler(void* closure, const void* hd) {
257
- VALUE rb_str = (VALUE)closure;
258
- rb_obj_freeze(rb_str);
259
- return true;
260
- }
261
-
262
- static bool appendstring_end_handler(void* closure, const void* hd) {
263
- VALUE rb_str = (VALUE)closure;
264
- rb_obj_freeze(rb_str);
265
- return true;
266
- }
267
-
268
- // Appends a submessage to a repeated field (a regular Ruby array for now).
269
- static void *appendsubmsg_handler(void *closure, const void *hd) {
270
- VALUE ary = (VALUE)closure;
271
- const submsg_handlerdata_t *submsgdata = hd;
272
- MessageHeader* submsg;
273
-
274
- VALUE submsg_rb = rb_class_new_instance(0, NULL, submsgdata->subklass);
275
- RepeatedField_push(ary, submsg_rb);
276
-
277
- TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
278
- return submsg;
279
- }
280
-
281
- // Appends a wrapper to a repeated field (a regular Ruby array for now).
282
- static void *appendwrapper_handler(void *closure, const void *hd) {
283
- VALUE ary = (VALUE)closure;
284
- int size = RepeatedField_size(ary);
285
- (void)hd;
286
-
287
- RepeatedField_push(ary, Qnil);
288
-
289
- return RepeatedField_index_native(ary, size);
290
- }
291
-
292
- // Sets a non-repeated submessage field in a message.
293
- static void *submsg_handler(void *closure, const void *hd) {
294
- MessageHeader* msg = closure;
295
- const submsg_handlerdata_t* submsgdata = hd;
296
- VALUE submsg_rb;
297
- MessageHeader* submsg;
298
-
299
- if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
300
- DEREF(msg, submsgdata->ofs, VALUE) =
301
- rb_class_new_instance(0, NULL, submsgdata->subklass);
302
- }
303
-
304
- set_hasbit(closure, submsgdata->hasbit);
305
-
306
- submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
307
- TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
308
-
309
- return submsg;
310
- }
311
-
312
- static void* startwrapper(void* closure, const void* hd) {
313
- char* msg = closure;
314
- const submsg_handlerdata_t* submsgdata = hd;
315
-
316
- set_hasbit(closure, submsgdata->hasbit);
317
-
318
- return msg + submsgdata->ofs;
319
- }
320
-
321
- // Handler data for startmap/endmap handlers.
322
- typedef struct {
323
- size_t ofs;
324
- upb_fieldtype_t key_field_type;
325
- upb_fieldtype_t value_field_type;
326
- VALUE subklass;
327
- } map_handlerdata_t;
328
-
329
- // Temporary frame for map parsing: at the beginning of a map entry message, a
330
- // submsg handler allocates a frame to hold (i) a reference to the Map object
331
- // into which this message will be inserted and (ii) storage slots to
332
- // temporarily hold the key and value for this map entry until the end of the
333
- // submessage. When the submessage ends, another handler is called to insert the
334
- // value into the map.
335
- typedef struct {
336
- VALUE map;
337
- const map_handlerdata_t* handlerdata;
338
- char key_storage[NATIVE_SLOT_MAX_SIZE];
339
- char value_storage[NATIVE_SLOT_MAX_SIZE];
340
- } map_parse_frame_t;
341
-
342
- static void MapParseFrame_mark(void* _self) {
343
- map_parse_frame_t* frame = _self;
344
-
345
- // This shouldn't strictly be necessary since this should be rooted by the
346
- // message itself, but it can't hurt.
347
- rb_gc_mark(frame->map);
348
-
349
- native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
350
- native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
351
- }
352
-
353
- void MapParseFrame_free(void* self) {
354
- xfree(self);
355
- }
356
-
357
- rb_data_type_t MapParseFrame_type = {
358
- "MapParseFrame",
359
- { MapParseFrame_mark, MapParseFrame_free, NULL },
360
- };
361
-
362
- // Handler to begin a map entry: allocates a temporary frame. This is the
363
- // 'startsubmsg' handler on the msgdef that contains the map field.
364
- static void *startmap_handler(void *closure, const void *hd) {
365
- MessageHeader* msg = closure;
366
- const map_handlerdata_t* mapdata = hd;
367
- map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
368
- VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
369
-
370
- frame->handlerdata = mapdata;
371
- frame->map = map_rb;
372
- native_slot_init(mapdata->key_field_type, &frame->key_storage);
373
- native_slot_init(mapdata->value_field_type, &frame->value_storage);
374
-
375
- Map_set_frame(map_rb,
376
- TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
377
-
378
- return frame;
379
- }
380
-
381
- static bool endmap_handler(void *closure, const void *hd) {
382
- MessageHeader* msg = closure;
383
- const map_handlerdata_t* mapdata = hd;
384
- VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
385
- Map_set_frame(map_rb, Qnil);
386
- return true;
387
- }
388
-
389
- // Handler to end a map entry: inserts the value defined during the message into
390
- // the map. This is the 'endmsg' handler on the map entry msgdef.
391
- static bool endmapentry_handler(void* closure, const void* hd, upb_status* s) {
392
- map_parse_frame_t* frame = closure;
393
- const map_handlerdata_t* mapdata = hd;
394
-
395
- VALUE key = native_slot_get(
396
- mapdata->key_field_type, Qnil,
397
- &frame->key_storage);
398
-
399
- VALUE value = native_slot_get(
400
- mapdata->value_field_type, mapdata->subklass,
401
- &frame->value_storage);
402
-
403
- Map_index_set(frame->map, key, value);
404
-
405
- return true;
406
- }
407
-
408
- // Allocates a new map_handlerdata_t given the map entry message definition. If
409
- // the offset of the field within the parent message is also given, that is
410
- // added to the handler data as well. Note that this is called *twice* per map
411
- // field: once in the parent message handler setup when setting the startsubmsg
412
- // handler and once in the map entry message handler setup when setting the
413
- // key/value and endmsg handlers. The reason is that there is no easy way to
414
- // pass the handlerdata down to the sub-message handler setup.
415
- static map_handlerdata_t* new_map_handlerdata(
416
- size_t ofs,
417
- const upb_msgdef* mapentry_def,
418
- const Descriptor* desc) {
419
- const upb_fielddef* key_field;
420
- const upb_fielddef* value_field;
421
- map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
422
- hd->ofs = ofs;
423
- key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
424
- assert(key_field != NULL);
425
- hd->key_field_type = upb_fielddef_type(key_field);
426
- value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
427
- assert(value_field != NULL);
428
- hd->value_field_type = upb_fielddef_type(value_field);
429
- hd->subklass = field_type_class(desc->layout, value_field);
430
-
431
- return hd;
432
- }
433
-
434
- // Handlers that set primitive values in oneofs.
435
- #define DEFINE_ONEOF_HANDLER(type, ctype) \
436
- static bool oneof##type##_handler(void *closure, const void *hd, \
437
- ctype val) { \
438
- const oneof_handlerdata_t *oneofdata = hd; \
439
- DEREF(closure, oneofdata->case_ofs, uint32_t) = \
440
- oneofdata->oneof_case_num; \
441
- DEREF(closure, oneofdata->ofs, ctype) = val; \
442
- return true; \
443
- }
444
-
445
- DEFINE_ONEOF_HANDLER(bool, bool)
446
- DEFINE_ONEOF_HANDLER(int32, int32_t)
447
- DEFINE_ONEOF_HANDLER(uint32, uint32_t)
448
- DEFINE_ONEOF_HANDLER(float, float)
449
- DEFINE_ONEOF_HANDLER(int64, int64_t)
450
- DEFINE_ONEOF_HANDLER(uint64, uint64_t)
451
- DEFINE_ONEOF_HANDLER(double, double)
452
-
453
- #undef DEFINE_ONEOF_HANDLER
454
-
455
- // Handlers for strings in a oneof.
456
- static void *oneofstr_handler(void *closure,
457
- const void *hd,
458
- size_t size_hint) {
459
- MessageHeader* msg = closure;
460
- const oneof_handlerdata_t *oneofdata = hd;
461
- VALUE str = rb_str_new2("");
462
- rb_enc_associate(str, kRubyStringUtf8Encoding);
463
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
464
- oneofdata->oneof_case_num;
465
- DEREF(msg, oneofdata->ofs, VALUE) = str;
466
- return (void*)str;
467
- }
468
-
469
- static void *oneofbytes_handler(void *closure,
470
- const void *hd,
471
- size_t size_hint) {
472
- MessageHeader* msg = closure;
473
- const oneof_handlerdata_t *oneofdata = hd;
474
- VALUE str = rb_str_new2("");
475
- rb_enc_associate(str, kRubyString8bitEncoding);
476
- DEREF(msg, oneofdata->case_ofs, uint32_t) =
477
- oneofdata->oneof_case_num;
478
- DEREF(msg, oneofdata->ofs, VALUE) = str;
479
- return (void*)str;
480
- }
481
-
482
- static bool oneofstring_end_handler(void* closure, const void* hd) {
483
- VALUE rb_str = rb_str_new2("");
484
- rb_obj_freeze(rb_str);
485
- return true;
486
- }
487
-
488
- // Handler for a submessage field in a oneof.
489
- static void *oneofsubmsg_handler(void *closure,
490
- const void *hd) {
491
- MessageHeader* msg = closure;
492
- const oneof_handlerdata_t *oneofdata = hd;
493
- uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
494
-
495
- VALUE submsg_rb;
496
- MessageHeader* submsg;
497
-
498
- if (oldcase != oneofdata->oneof_case_num ||
499
- DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
500
- DEREF(msg, oneofdata->ofs, VALUE) =
501
- rb_class_new_instance(0, NULL, oneofdata->subklass);
502
- }
503
- // Set the oneof case *after* allocating the new class instance -- otherwise,
504
- // if the Ruby GC is invoked as part of a call into the VM, it might invoke
505
- // our mark routines, and our mark routines might see the case value
506
- // indicating a VALUE is present and expect a valid VALUE. See comment in
507
- // layout_set() for more detail: basically, the change to the value and the
508
- // case must be atomic w.r.t. the Ruby VM.
509
- DEREF(msg, oneofdata->case_ofs, uint32_t) = oneofdata->oneof_case_num;
510
-
511
- submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
512
- TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
513
- return submsg;
514
- }
515
-
516
- static void* oneof_startwrapper(void* closure, const void* hd) {
517
- char* msg = closure;
518
- const oneof_handlerdata_t *oneofdata = hd;
519
-
520
- DEREF(msg, oneofdata->case_ofs, uint32_t) = oneofdata->oneof_case_num;
521
-
522
- return msg + oneofdata->ofs;
523
- }
524
-
525
- bool is_wrapper(const upb_msgdef* m) {
526
- switch (upb_msgdef_wellknowntype(m)) {
527
- case UPB_WELLKNOWN_DOUBLEVALUE:
528
- case UPB_WELLKNOWN_FLOATVALUE:
529
- case UPB_WELLKNOWN_INT64VALUE:
530
- case UPB_WELLKNOWN_UINT64VALUE:
531
- case UPB_WELLKNOWN_INT32VALUE:
532
- case UPB_WELLKNOWN_UINT32VALUE:
533
- case UPB_WELLKNOWN_STRINGVALUE:
534
- case UPB_WELLKNOWN_BYTESVALUE:
535
- case UPB_WELLKNOWN_BOOLVALUE:
536
- return true;
537
- default:
538
- return false;
539
- }
540
- }
541
-
542
- // Set up handlers for a repeated field.
543
- static void add_handlers_for_repeated_field(upb_handlers *h,
544
- const Descriptor* desc,
545
- const upb_fielddef *f,
546
- size_t offset) {
547
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
548
- attr.handler_data = newhandlerdata(h, offset, -1);
549
- upb_handlers_setstartseq(h, f, startseq_handler, &attr);
550
-
551
- switch (upb_fielddef_type(f)) {
552
-
553
- #define SET_HANDLER(utype, ltype) \
554
- case utype: \
555
- upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
556
- break;
557
-
558
- SET_HANDLER(UPB_TYPE_BOOL, bool);
559
- SET_HANDLER(UPB_TYPE_INT32, int32);
560
- SET_HANDLER(UPB_TYPE_UINT32, uint32);
561
- SET_HANDLER(UPB_TYPE_ENUM, int32);
562
- SET_HANDLER(UPB_TYPE_FLOAT, float);
563
- SET_HANDLER(UPB_TYPE_INT64, int64);
564
- SET_HANDLER(UPB_TYPE_UINT64, uint64);
565
- SET_HANDLER(UPB_TYPE_DOUBLE, double);
566
-
567
- #undef SET_HANDLER
568
-
569
- case UPB_TYPE_STRING:
570
- case UPB_TYPE_BYTES: {
571
- bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
572
- upb_handlers_setstartstr(h, f, is_bytes ?
573
- appendbytes_handler : appendstr_handler,
574
- NULL);
575
- upb_handlers_setstring(h, f, stringdata_handler, NULL);
576
- upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
577
- break;
578
- }
579
- case UPB_TYPE_MESSAGE: {
580
- VALUE subklass = field_type_class(desc->layout, f);
581
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
582
- attr.handler_data = newsubmsghandlerdata(h, 0, -1, subklass);
583
- if (is_wrapper(upb_fielddef_msgsubdef(f))) {
584
- upb_handlers_setstartsubmsg(h, f, appendwrapper_handler, &attr);
585
- } else {
586
- upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
587
- }
588
- break;
589
- }
590
- }
591
- }
592
-
593
- static bool doublewrapper_handler(void* closure, const void* hd, double val) {
594
- VALUE* rbval = closure;
595
- *rbval = DBL2NUM(val);
596
- return true;
597
- }
598
-
599
- static bool floatwrapper_handler(void* closure, const void* hd, float val) {
600
- VALUE* rbval = closure;
601
- *rbval = DBL2NUM(val);
602
- return true;
603
- }
604
-
605
- static bool int64wrapper_handler(void* closure, const void* hd, int64_t val) {
606
- VALUE* rbval = closure;
607
- *rbval = LL2NUM(val);
608
- return true;
609
- }
610
-
611
- static bool uint64wrapper_handler(void* closure, const void* hd, uint64_t val) {
612
- VALUE* rbval = closure;
613
- *rbval = ULL2NUM(val);
614
- return true;
615
- }
616
-
617
- static bool int32wrapper_handler(void* closure, const void* hd, int32_t val) {
618
- VALUE* rbval = closure;
619
- *rbval = INT2NUM(val);
620
- return true;
621
- }
622
-
623
- static bool uint32wrapper_handler(void* closure, const void* hd, uint32_t val) {
624
- VALUE* rbval = closure;
625
- *rbval = UINT2NUM(val);
626
- return true;
627
- }
628
-
629
- static void* startstringwrapper_handler(void* closure, const void* hd,
630
- size_t size_hint) {
631
- VALUE* rbval = closure;
632
- (void)size_hint;
633
- *rbval = rb_str_new(NULL, 0);
634
- rb_enc_associate(*rbval, kRubyStringUtf8Encoding);
635
- return closure;
636
- }
637
-
638
- static size_t stringwrapper_handler(void* closure, const void* hd,
639
- const char* ptr, size_t len,
640
- const upb_bufhandle* handle) {
641
- VALUE* rbval = closure;
642
- *rbval = noleak_rb_str_cat(*rbval, ptr, len);
643
- return len;
644
- }
645
-
646
- static void* startbyteswrapper_handler(void* closure, const void* hd,
647
- size_t size_hint) {
648
- VALUE* rbval = closure;
649
- (void)size_hint;
650
- *rbval = rb_str_new(NULL, 0);
651
- rb_enc_associate(*rbval, kRubyString8bitEncoding);
652
- return closure;
653
- }
654
-
655
- static size_t byteswrapper_handler(void* closure, const void* hd,
656
- const char* ptr, size_t len,
657
- const upb_bufhandle* handle) {
658
- VALUE* rbval = closure;
659
- *rbval = noleak_rb_str_cat(*rbval, ptr, len);
660
- return len;
661
- }
662
-
663
- static bool boolwrapper_handler(void* closure, const void* hd, bool val) {
664
- VALUE* rbval = closure;
665
- if (val) {
666
- *rbval = Qtrue;
667
- } else {
668
- *rbval = Qfalse;
669
- }
670
- return true;
671
- }
672
-
673
- // Set up handlers for a singular field.
674
- static void add_handlers_for_singular_field(const Descriptor* desc,
675
- upb_handlers* h,
676
- const upb_fielddef* f,
677
- size_t offset, size_t hasbit_off) {
678
- // The offset we pass to UPB points to the start of the Message,
679
- // rather than the start of where our data is stored.
680
- int32_t hasbit = -1;
681
- if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
682
- hasbit = hasbit_off + sizeof(MessageHeader) * 8;
683
- }
684
-
685
- switch (upb_fielddef_type(f)) {
686
- case UPB_TYPE_BOOL:
687
- case UPB_TYPE_INT32:
688
- case UPB_TYPE_UINT32:
689
- case UPB_TYPE_ENUM:
690
- case UPB_TYPE_FLOAT:
691
- case UPB_TYPE_INT64:
692
- case UPB_TYPE_UINT64:
693
- case UPB_TYPE_DOUBLE:
694
- upb_msg_setscalarhandler(h, f, offset, hasbit);
695
- break;
696
- case UPB_TYPE_STRING:
697
- case UPB_TYPE_BYTES: {
698
- bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
699
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
700
- attr.handler_data = newhandlerdata(h, offset, hasbit);
701
- upb_handlers_setstartstr(h, f,
702
- is_bytes ? bytes_handler : str_handler,
703
- &attr);
704
- upb_handlers_setstring(h, f, stringdata_handler, &attr);
705
- upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
706
- break;
707
- }
708
- case UPB_TYPE_MESSAGE: {
709
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
710
- attr.handler_data = newsubmsghandlerdata(
711
- h, offset, hasbit, field_type_class(desc->layout, f));
712
- if (is_wrapper(upb_fielddef_msgsubdef(f))) {
713
- upb_handlers_setstartsubmsg(h, f, startwrapper, &attr);
714
- } else {
715
- upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
716
- }
717
- }
718
- }
719
- }
720
-
721
- // Adds handlers to a map field.
722
- static void add_handlers_for_mapfield(upb_handlers* h,
723
- const upb_fielddef* fielddef,
724
- size_t offset,
725
- const Descriptor* desc) {
726
- const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
727
- map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
728
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
729
-
730
- upb_handlers_addcleanup(h, hd, xfree);
731
- attr.handler_data = hd;
732
- upb_handlers_setstartsubmsg(h, fielddef, startmap_handler, &attr);
733
- upb_handlers_setendsubmsg(h, fielddef, endmap_handler, &attr);
734
- }
735
-
736
- // Adds handlers to a map-entry msgdef.
737
- static void add_handlers_for_mapentry(const upb_msgdef* msgdef, upb_handlers* h,
738
- const Descriptor* desc) {
739
- const upb_fielddef* key_field = map_entry_key(msgdef);
740
- const upb_fielddef* value_field = map_entry_value(msgdef);
741
- map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
742
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
743
-
744
- upb_handlers_addcleanup(h, hd, xfree);
745
- attr.handler_data = hd;
746
- upb_handlers_setendmsg(h, endmapentry_handler, &attr);
747
-
748
- add_handlers_for_singular_field(
749
- desc, h, key_field,
750
- offsetof(map_parse_frame_t, key_storage),
751
- MESSAGE_FIELD_NO_HASBIT);
752
- add_handlers_for_singular_field(
753
- desc, h, value_field,
754
- offsetof(map_parse_frame_t, value_storage),
755
- MESSAGE_FIELD_NO_HASBIT);
756
- }
757
-
758
- static void add_handlers_for_wrapper(const upb_msgdef* msgdef,
759
- upb_handlers* h) {
760
- const upb_fielddef* f = upb_msgdef_itof(msgdef, 1);
761
- switch (upb_msgdef_wellknowntype(msgdef)) {
762
- case UPB_WELLKNOWN_DOUBLEVALUE:
763
- upb_handlers_setdouble(h, f, doublewrapper_handler, NULL);
764
- break;
765
- case UPB_WELLKNOWN_FLOATVALUE:
766
- upb_handlers_setfloat(h, f, floatwrapper_handler, NULL);
767
- break;
768
- case UPB_WELLKNOWN_INT64VALUE:
769
- upb_handlers_setint64(h, f, int64wrapper_handler, NULL);
770
- break;
771
- case UPB_WELLKNOWN_UINT64VALUE:
772
- upb_handlers_setuint64(h, f, uint64wrapper_handler, NULL);
773
- break;
774
- case UPB_WELLKNOWN_INT32VALUE:
775
- upb_handlers_setint32(h, f, int32wrapper_handler, NULL);
776
- break;
777
- case UPB_WELLKNOWN_UINT32VALUE:
778
- upb_handlers_setuint32(h, f, uint32wrapper_handler, NULL);
779
- break;
780
- case UPB_WELLKNOWN_STRINGVALUE:
781
- upb_handlers_setstartstr(h, f, startstringwrapper_handler, NULL);
782
- upb_handlers_setstring(h, f, stringwrapper_handler, NULL);
783
- break;
784
- case UPB_WELLKNOWN_BYTESVALUE:
785
- upb_handlers_setstartstr(h, f, startbyteswrapper_handler, NULL);
786
- upb_handlers_setstring(h, f, byteswrapper_handler, NULL);
787
- break;
788
- case UPB_WELLKNOWN_BOOLVALUE:
789
- upb_handlers_setbool(h, f, boolwrapper_handler, NULL);
790
- return;
791
- default:
792
- rb_raise(rb_eRuntimeError,
793
- "Internal logic error with well-known types.");
794
- }
795
- }
796
-
797
- // Set up handlers for a oneof field.
798
- static void add_handlers_for_oneof_field(upb_handlers *h,
799
- const upb_fielddef *f,
800
- size_t offset,
801
- size_t oneof_case_offset,
802
- const Descriptor* desc) {
803
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
804
- attr.handler_data =
805
- newoneofhandlerdata(h, offset, oneof_case_offset, f, desc);
806
-
807
- switch (upb_fielddef_type(f)) {
808
-
809
- #define SET_HANDLER(utype, ltype) \
810
- case utype: \
811
- upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
812
- break;
813
-
814
- SET_HANDLER(UPB_TYPE_BOOL, bool);
815
- SET_HANDLER(UPB_TYPE_INT32, int32);
816
- SET_HANDLER(UPB_TYPE_UINT32, uint32);
817
- SET_HANDLER(UPB_TYPE_ENUM, int32);
818
- SET_HANDLER(UPB_TYPE_FLOAT, float);
819
- SET_HANDLER(UPB_TYPE_INT64, int64);
820
- SET_HANDLER(UPB_TYPE_UINT64, uint64);
821
- SET_HANDLER(UPB_TYPE_DOUBLE, double);
822
-
823
- #undef SET_HANDLER
824
-
825
- case UPB_TYPE_STRING:
826
- case UPB_TYPE_BYTES: {
827
- bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
828
- upb_handlers_setstartstr(h, f, is_bytes ?
829
- oneofbytes_handler : oneofstr_handler,
830
- &attr);
831
- upb_handlers_setstring(h, f, stringdata_handler, NULL);
832
- upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
833
- break;
834
- }
835
- case UPB_TYPE_MESSAGE: {
836
- if (is_wrapper(upb_fielddef_msgsubdef(f))) {
837
- upb_handlers_setstartsubmsg(h, f, oneof_startwrapper, &attr);
838
- } else {
839
- upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
840
- }
841
- break;
842
- }
843
- }
844
- }
845
-
846
- static bool unknown_field_handler(void* closure, const void* hd,
847
- const char* buf, size_t size) {
848
- MessageHeader* msg = (MessageHeader*)closure;
849
- UPB_UNUSED(hd);
850
-
851
- if (msg->unknown_fields == NULL) {
852
- msg->unknown_fields = malloc(sizeof(stringsink));
853
- stringsink_init(msg->unknown_fields);
854
- }
855
-
856
- stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
857
-
858
- return true;
859
- }
860
-
861
- size_t get_field_offset(MessageLayout* layout, const upb_fielddef* f) {
862
- return layout->fields[upb_fielddef_index(f)].offset + sizeof(MessageHeader);
863
- }
864
-
865
- void add_handlers_for_message(const void *closure, upb_handlers *h) {
866
- const VALUE descriptor_pool = (VALUE)closure;
867
- const upb_msgdef* msgdef = upb_handlers_msgdef(h);
868
- Descriptor* desc =
869
- ruby_to_Descriptor(get_msgdef_obj(descriptor_pool, msgdef));
870
- upb_msg_field_iter i;
871
- upb_handlerattr attr = UPB_HANDLERATTR_INIT;
872
-
873
- // Ensure layout exists. We may be invoked to create handlers for a given
874
- // message if we are included as a submsg of another message type before our
875
- // class is actually built, so to work around this, we just create the layout
876
- // (and handlers, in the class-building function) on-demand.
877
- if (desc->layout == NULL) {
878
- create_layout(desc);
879
- }
880
-
881
- // If this is a mapentry message type, set up a special set of handlers and
882
- // bail out of the normal (user-defined) message type handling.
883
- if (upb_msgdef_mapentry(msgdef)) {
884
- add_handlers_for_mapentry(msgdef, h, desc);
885
- return;
886
- }
887
-
888
- // If this is a wrapper type, use special handlers and bail.
889
- if (is_wrapper(msgdef)) {
890
- add_handlers_for_wrapper(msgdef, h);
891
- return;
892
- }
893
-
894
- upb_handlers_setunknown(h, unknown_field_handler, &attr);
895
-
896
- for (upb_msg_field_begin(&i, desc->msgdef);
897
- !upb_msg_field_done(&i);
898
- upb_msg_field_next(&i)) {
899
- const upb_fielddef *f = upb_msg_iter_field(&i);
900
- const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
901
- size_t offset = get_field_offset(desc->layout, f);
902
-
903
- if (oneof) {
904
- size_t oneof_case_offset =
905
- desc->layout->oneofs[upb_oneofdef_index(oneof)].case_offset +
906
- sizeof(MessageHeader);
907
- add_handlers_for_oneof_field(h, f, offset, oneof_case_offset, desc);
908
- } else if (is_map_field(f)) {
909
- add_handlers_for_mapfield(h, f, offset, desc);
910
- } else if (upb_fielddef_isseq(f)) {
911
- add_handlers_for_repeated_field(h, desc, f, offset);
912
- } else {
913
- add_handlers_for_singular_field(
914
- desc, h, f, offset,
915
- desc->layout->fields[upb_fielddef_index(f)].hasbit);
916
- }
917
- }
918
- }
919
-
920
- // Constructs the handlers for filling a message's data into an in-memory
921
- // object.
922
- const upb_handlers* get_fill_handlers(Descriptor* desc) {
923
- DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
924
- return upb_handlercache_get(pool->fill_handler_cache, desc->msgdef);
925
- }
926
-
927
- static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
928
- DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
929
- return upb_pbcodecache_get(pool->fill_method_cache, desc->msgdef);
930
- }
931
-
932
- static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
933
- DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
934
- return upb_json_codecache_get(pool->json_fill_method_cache, desc->msgdef);
935
- }
936
-
937
- static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
938
- DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
939
- return upb_handlercache_get(pool->pb_serialize_handler_cache, desc->msgdef);
940
- }
941
-
942
- static const upb_handlers* msgdef_json_serialize_handlers(
943
- Descriptor* desc, bool preserve_proto_fieldnames) {
944
- DescriptorPool* pool = ruby_to_DescriptorPool(desc->descriptor_pool);
945
- if (preserve_proto_fieldnames) {
946
- return upb_handlercache_get(pool->json_serialize_handler_preserve_cache,
947
- desc->msgdef);
948
- } else {
949
- return upb_handlercache_get(pool->json_serialize_handler_cache,
950
- desc->msgdef);
951
- }
952
- }
953
-
954
-
955
- // Stack-allocated context during an encode/decode operation. Contains the upb
956
- // environment and its stack-based allocator, an initial buffer for allocations
957
- // to avoid malloc() when possible, and a template for Ruby exception messages
958
- // if any error occurs.
959
- #define STACK_ENV_STACKBYTES 4096
960
- typedef struct {
961
- upb_arena *arena;
962
- upb_status status;
963
- const char* ruby_error_template;
964
- char allocbuf[STACK_ENV_STACKBYTES];
965
- } stackenv;
966
-
967
- static void stackenv_init(stackenv* se, const char* errmsg);
968
- static void stackenv_uninit(stackenv* se);
969
-
970
- static void stackenv_init(stackenv* se, const char* errmsg) {
971
- se->ruby_error_template = errmsg;
972
- se->arena =
973
- upb_arena_init(se->allocbuf, sizeof(se->allocbuf), &upb_alloc_global);
974
- upb_status_clear(&se->status);
975
- }
976
-
977
- static void stackenv_uninit(stackenv* se) {
978
- upb_arena_free(se->arena);
979
-
980
- if (!upb_ok(&se->status)) {
981
- // TODO(haberman): have a way to verify that this is actually a parse error,
982
- // instead of just throwing "parse error" unconditionally.
983
- VALUE errmsg = rb_str_new2(upb_status_errmsg(&se->status));
984
- rb_raise(cParseError, se->ruby_error_template, errmsg);
985
- }
986
- }
987
-
988
- /*
989
- * call-seq:
990
- * MessageClass.decode(data) => message
991
- *
992
- * Decodes the given data (as a string containing bytes in protocol buffers wire
993
- * format) under the interpretration given by this message class's definition
994
- * and returns a message object with the corresponding field values.
995
- */
996
- VALUE Message_decode(VALUE klass, VALUE data) {
997
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
998
- Descriptor* desc = ruby_to_Descriptor(descriptor);
999
- VALUE msgklass = Descriptor_msgclass(descriptor);
1000
- VALUE msg_rb;
1001
- MessageHeader* msg;
1002
-
1003
- if (TYPE(data) != T_STRING) {
1004
- rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
1005
- }
1006
-
1007
- msg_rb = rb_class_new_instance(0, NULL, msgklass);
1008
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1009
-
1010
- {
1011
- const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
1012
- const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
1013
- const upb_msgdef* m = upb_handlers_msgdef(h);
1014
- VALUE wrapper = Qnil;
1015
- void* ptr = msg;
1016
- stackenv se;
1017
- upb_sink sink;
1018
- upb_pbdecoder* decoder;
1019
- stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
1020
-
1021
- if (is_wrapper(m)) {
1022
- ptr = &wrapper;
1023
- }
1024
-
1025
- upb_sink_reset(&sink, h, ptr);
1026
- decoder = upb_pbdecoder_create(se.arena, method, sink, &se.status);
1027
- upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
1028
- upb_pbdecoder_input(decoder));
1029
-
1030
- stackenv_uninit(&se);
1031
-
1032
- if (is_wrapper(m)) {
1033
- msg_rb = ruby_wrapper_type(msgklass, wrapper);
1034
- }
1035
- }
1036
-
1037
- return msg_rb;
1038
- }
1039
-
1040
- /*
1041
- * call-seq:
1042
- * MessageClass.decode_json(data, options = {}) => message
1043
- *
1044
- * Decodes the given data (as a string containing bytes in protocol buffers wire
1045
- * format) under the interpretration given by this message class's definition
1046
- * and returns a message object with the corresponding field values.
1047
- *
1048
- * @param options [Hash] options for the decoder
1049
- * ignore_unknown_fields: set true to ignore unknown fields (default is to
1050
- * raise an error)
1051
- */
1052
- VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
1053
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1054
- Descriptor* desc = ruby_to_Descriptor(descriptor);
1055
- VALUE msgklass = Descriptor_msgclass(descriptor);
1056
- VALUE msg_rb;
1057
- VALUE data = argv[0];
1058
- VALUE ignore_unknown_fields = Qfalse;
1059
- MessageHeader* msg;
1060
-
1061
- if (argc < 1 || argc > 2) {
1062
- rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1063
- }
1064
-
1065
- if (argc == 2) {
1066
- VALUE hash_args = argv[1];
1067
- if (TYPE(hash_args) != T_HASH) {
1068
- rb_raise(rb_eArgError, "Expected hash arguments.");
1069
- }
1070
-
1071
- ignore_unknown_fields = rb_hash_lookup2(
1072
- hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse);
1073
- }
1074
-
1075
- if (TYPE(data) != T_STRING) {
1076
- rb_raise(rb_eArgError, "Expected string for JSON data.");
1077
- }
1078
-
1079
- // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
1080
- // convert, because string handlers pass data directly to message string
1081
- // fields.
1082
-
1083
- msg_rb = rb_class_new_instance(0, NULL, msgklass);
1084
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1085
-
1086
- {
1087
- const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
1088
- const upb_handlers* h = get_fill_handlers(desc);
1089
- const upb_msgdef* m = upb_handlers_msgdef(h);
1090
- stackenv se;
1091
- upb_sink sink;
1092
- upb_json_parser* parser;
1093
- DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
1094
- stackenv_init(&se, "Error occurred during parsing: %" PRIsVALUE);
1095
-
1096
- if (is_wrapper(m)) {
1097
- rb_raise(
1098
- rb_eRuntimeError,
1099
- "Parsing a wrapper type from JSON at the top level does not work.");
1100
- }
1101
-
1102
- upb_sink_reset(&sink, h, msg);
1103
- parser = upb_json_parser_create(se.arena, method, pool->symtab, sink,
1104
- &se.status, RTEST(ignore_unknown_fields));
1105
- upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
1106
- upb_json_parser_input(parser));
1107
-
1108
- stackenv_uninit(&se);
1109
- }
1110
-
1111
- return msg_rb;
1112
- }
1113
-
1114
- // -----------------------------------------------------------------------------
1115
- // Serializing.
1116
- // -----------------------------------------------------------------------------
1117
-
1118
- /* msgvisitor *****************************************************************/
1119
-
1120
- static void putmsg(VALUE msg, const Descriptor* desc, upb_sink sink, int depth,
1121
- bool emit_defaults, bool is_json, bool open_msg);
1122
-
1123
- static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
1124
- upb_selector_t ret;
1125
- bool ok = upb_handlers_getselector(f, type, &ret);
1126
- UPB_ASSERT(ok);
1127
- return ret;
1128
- }
1129
-
1130
- static void putstr(VALUE str, const upb_fielddef *f, upb_sink sink) {
1131
- upb_sink subsink;
1132
-
1133
- if (str == Qnil) return;
1134
-
1135
- assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
1136
-
1137
- // We should be guaranteed that the string has the correct encoding because
1138
- // we ensured this at assignment time and then froze the string.
1139
- if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
1140
- assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
1141
- } else {
1142
- assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
1143
- }
1144
-
1145
- upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
1146
- &subsink);
1147
- upb_sink_putstring(subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
1148
- RSTRING_LEN(str), NULL);
1149
- upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
1150
- }
1151
-
1152
- static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink sink,
1153
- int depth, bool emit_defaults, bool is_json) {
1154
- upb_sink subsink;
1155
- VALUE descriptor;
1156
- Descriptor* subdesc;
1157
-
1158
- if (submsg == Qnil) return;
1159
-
1160
- descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1161
- subdesc = ruby_to_Descriptor(descriptor);
1162
-
1163
- upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
1164
- putmsg(submsg, subdesc, subsink, depth + 1, emit_defaults, is_json, true);
1165
- upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1166
- }
1167
-
1168
- static void putary(VALUE ary, const upb_fielddef* f, upb_sink sink, int depth,
1169
- bool emit_defaults, bool is_json) {
1170
- upb_sink subsink;
1171
- upb_fieldtype_t type = upb_fielddef_type(f);
1172
- upb_selector_t sel = 0;
1173
- int size;
1174
- int i;
1175
- VALUE type_class = ruby_to_RepeatedField(ary)->field_type_class;
1176
-
1177
- if (ary == Qnil) return;
1178
- if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
1179
-
1180
- size = NUM2INT(RepeatedField_length(ary));
1181
- if (size == 0 && !emit_defaults) return;
1182
-
1183
- upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1184
-
1185
- if (upb_fielddef_isprimitive(f)) {
1186
- sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1187
- }
1188
-
1189
- for (i = 0; i < size; i++) {
1190
- void* memory = RepeatedField_index_native(ary, i);
1191
- switch (type) {
1192
- #define T(upbtypeconst, upbtype, ctype) \
1193
- case upbtypeconst: \
1194
- upb_sink_put##upbtype(subsink, sel, *((ctype*)memory)); \
1195
- break;
1196
-
1197
- T(UPB_TYPE_FLOAT, float, float)
1198
- T(UPB_TYPE_DOUBLE, double, double)
1199
- T(UPB_TYPE_BOOL, bool, int8_t)
1200
- case UPB_TYPE_ENUM:
1201
- T(UPB_TYPE_INT32, int32, int32_t)
1202
- T(UPB_TYPE_UINT32, uint32, uint32_t)
1203
- T(UPB_TYPE_INT64, int64, int64_t)
1204
- T(UPB_TYPE_UINT64, uint64, uint64_t)
1205
-
1206
- case UPB_TYPE_STRING:
1207
- case UPB_TYPE_BYTES:
1208
- putstr(*((VALUE *)memory), f, subsink);
1209
- break;
1210
- case UPB_TYPE_MESSAGE: {
1211
- VALUE val = native_slot_get(UPB_TYPE_MESSAGE, type_class, memory);
1212
- putsubmsg(val, f, subsink, depth, emit_defaults, is_json);
1213
- break;
1214
- }
1215
-
1216
- #undef T
1217
-
1218
- }
1219
- }
1220
- upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1221
- }
1222
-
1223
- static void put_ruby_value(VALUE value, const upb_fielddef* f, VALUE type_class,
1224
- int depth, upb_sink sink, bool emit_defaults,
1225
- bool is_json) {
1226
- upb_selector_t sel = 0;
1227
-
1228
- if (depth > ENCODE_MAX_NESTING) {
1229
- rb_raise(rb_eRuntimeError,
1230
- "Maximum recursion depth exceeded during encoding.");
1231
- }
1232
-
1233
- if (upb_fielddef_isprimitive(f)) {
1234
- sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1235
- }
1236
-
1237
- switch (upb_fielddef_type(f)) {
1238
- case UPB_TYPE_INT32:
1239
- upb_sink_putint32(sink, sel, NUM2INT(value));
1240
- break;
1241
- case UPB_TYPE_INT64:
1242
- upb_sink_putint64(sink, sel, NUM2LL(value));
1243
- break;
1244
- case UPB_TYPE_UINT32:
1245
- upb_sink_putuint32(sink, sel, NUM2UINT(value));
1246
- break;
1247
- case UPB_TYPE_UINT64:
1248
- upb_sink_putuint64(sink, sel, NUM2ULL(value));
1249
- break;
1250
- case UPB_TYPE_FLOAT:
1251
- upb_sink_putfloat(sink, sel, NUM2DBL(value));
1252
- break;
1253
- case UPB_TYPE_DOUBLE:
1254
- upb_sink_putdouble(sink, sel, NUM2DBL(value));
1255
- break;
1256
- case UPB_TYPE_ENUM: {
1257
- if (TYPE(value) == T_SYMBOL) {
1258
- value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
1259
- }
1260
- upb_sink_putint32(sink, sel, NUM2INT(value));
1261
- break;
1262
- }
1263
- case UPB_TYPE_BOOL:
1264
- upb_sink_putbool(sink, sel, value == Qtrue);
1265
- break;
1266
- case UPB_TYPE_STRING:
1267
- case UPB_TYPE_BYTES:
1268
- putstr(value, f, sink);
1269
- break;
1270
- case UPB_TYPE_MESSAGE:
1271
- putsubmsg(value, f, sink, depth, emit_defaults, is_json);
1272
- }
1273
- }
1274
-
1275
- static void putmap(VALUE map, const upb_fielddef* f, upb_sink sink, int depth,
1276
- bool emit_defaults, bool is_json) {
1277
- Map* self;
1278
- upb_sink subsink;
1279
- const upb_fielddef* key_field;
1280
- const upb_fielddef* value_field;
1281
- Map_iter it;
1282
-
1283
- if (map == Qnil) return;
1284
- if (!emit_defaults && Map_length(map) == 0) return;
1285
-
1286
- self = ruby_to_Map(map);
1287
-
1288
- upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1289
-
1290
- assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
1291
- key_field = map_field_key(f);
1292
- value_field = map_field_value(f);
1293
-
1294
- for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
1295
- VALUE key = Map_iter_key(&it);
1296
- VALUE value = Map_iter_value(&it);
1297
- upb_status status;
1298
-
1299
- upb_sink entry_sink;
1300
- upb_sink_startsubmsg(subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
1301
- &entry_sink);
1302
- upb_sink_startmsg(entry_sink);
1303
-
1304
- put_ruby_value(key, key_field, Qnil, depth + 1, entry_sink, emit_defaults,
1305
- is_json);
1306
- put_ruby_value(value, value_field, self->value_type_class, depth + 1,
1307
- entry_sink, emit_defaults, is_json);
1308
-
1309
- upb_sink_endmsg(entry_sink, &status);
1310
- upb_sink_endsubmsg(subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1311
- }
1312
-
1313
- upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1314
- }
1315
-
1316
- static const upb_handlers* msgdef_json_serialize_handlers(
1317
- Descriptor* desc, bool preserve_proto_fieldnames);
1318
-
1319
- static void putjsonany(VALUE msg_rb, const Descriptor* desc, upb_sink sink,
1320
- int depth, bool emit_defaults) {
1321
- upb_status status;
1322
- MessageHeader* msg = NULL;
1323
- const upb_fielddef* type_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_TYPE);
1324
- const upb_fielddef* value_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_VALUE);
1325
-
1326
- size_t type_url_offset;
1327
- VALUE type_url_str_rb;
1328
- const upb_msgdef *payload_type = NULL;
1329
-
1330
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1331
-
1332
- upb_sink_startmsg(sink);
1333
-
1334
- /* Handle type url */
1335
- type_url_offset = desc->layout->fields[upb_fielddef_index(type_field)].offset;
1336
- type_url_str_rb = DEREF(Message_data(msg), type_url_offset, VALUE);
1337
- if (RSTRING_LEN(type_url_str_rb) > 0) {
1338
- putstr(type_url_str_rb, type_field, sink);
1339
- }
1340
-
1341
- {
1342
- const char* type_url_str = RSTRING_PTR(type_url_str_rb);
1343
- size_t type_url_len = RSTRING_LEN(type_url_str_rb);
1344
- DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
1345
-
1346
- if (type_url_len <= 20 ||
1347
- strncmp(type_url_str, "type.googleapis.com/", 20) != 0) {
1348
- rb_raise(rb_eRuntimeError, "Invalid type url: %s", type_url_str);
1349
- return;
1350
- }
1351
-
1352
- /* Resolve type url */
1353
- type_url_str += 20;
1354
- type_url_len -= 20;
1355
-
1356
- payload_type = upb_symtab_lookupmsg2(
1357
- pool->symtab, type_url_str, type_url_len);
1358
- if (payload_type == NULL) {
1359
- rb_raise(rb_eRuntimeError, "Unknown type: %s", type_url_str);
1360
- return;
1361
- }
1362
- }
1363
-
1364
- {
1365
- uint32_t value_offset;
1366
- VALUE value_str_rb;
1367
- size_t value_len;
1368
-
1369
- value_offset = desc->layout->fields[upb_fielddef_index(value_field)].offset;
1370
- value_str_rb = DEREF(Message_data(msg), value_offset, VALUE);
1371
- value_len = RSTRING_LEN(value_str_rb);
1372
-
1373
- if (value_len > 0) {
1374
- VALUE payload_desc_rb = get_msgdef_obj(generated_pool, payload_type);
1375
- Descriptor* payload_desc = ruby_to_Descriptor(payload_desc_rb);
1376
- VALUE payload_class = Descriptor_msgclass(payload_desc_rb);
1377
- upb_sink subsink;
1378
- bool is_wellknown;
1379
-
1380
- VALUE payload_msg_rb = Message_decode(payload_class, value_str_rb);
1381
-
1382
- is_wellknown =
1383
- upb_msgdef_wellknowntype(payload_desc->msgdef) !=
1384
- UPB_WELLKNOWN_UNSPECIFIED;
1385
- if (is_wellknown) {
1386
- upb_sink_startstr(sink, getsel(value_field, UPB_HANDLER_STARTSTR), 0,
1387
- &subsink);
1388
- }
1389
-
1390
- subsink.handlers =
1391
- msgdef_json_serialize_handlers(payload_desc, true);
1392
- subsink.closure = sink.closure;
1393
- putmsg(payload_msg_rb, payload_desc, subsink, depth, emit_defaults, true,
1394
- is_wellknown);
1395
- }
1396
- }
1397
-
1398
- upb_sink_endmsg(sink, &status);
1399
- }
1400
-
1401
- static void putjsonlistvalue(
1402
- VALUE msg_rb, const Descriptor* desc,
1403
- upb_sink sink, int depth, bool emit_defaults) {
1404
- upb_status status;
1405
- upb_sink subsink;
1406
- MessageHeader* msg = NULL;
1407
- const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
1408
- uint32_t offset =
1409
- desc->layout->fields[upb_fielddef_index(f)].offset +
1410
- sizeof(MessageHeader);
1411
- VALUE ary;
1412
-
1413
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1414
-
1415
- upb_sink_startmsg(sink);
1416
-
1417
- ary = DEREF(msg, offset, VALUE);
1418
-
1419
- if (ary == Qnil || RepeatedField_size(ary) == 0) {
1420
- upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1421
- upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1422
- } else {
1423
- putary(ary, f, sink, depth, emit_defaults, true);
1424
- }
1425
-
1426
- upb_sink_endmsg(sink, &status);
1427
- }
1428
-
1429
- static void putmsg(VALUE msg_rb, const Descriptor* desc,
1430
- upb_sink sink, int depth, bool emit_defaults,
1431
- bool is_json, bool open_msg) {
1432
- MessageHeader* msg;
1433
- upb_msg_field_iter i;
1434
- upb_status status;
1435
-
1436
- if (is_json &&
1437
- upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
1438
- putjsonany(msg_rb, desc, sink, depth, emit_defaults);
1439
- return;
1440
- }
1441
-
1442
- if (is_json &&
1443
- upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_LISTVALUE) {
1444
- putjsonlistvalue(msg_rb, desc, sink, depth, emit_defaults);
1445
- return;
1446
- }
1447
-
1448
- if (open_msg) {
1449
- upb_sink_startmsg(sink);
1450
- }
1451
-
1452
- // Protect against cycles (possible because users may freely reassign message
1453
- // and repeated fields) by imposing a maximum recursion depth.
1454
- if (depth > ENCODE_MAX_NESTING) {
1455
- rb_raise(rb_eRuntimeError,
1456
- "Maximum recursion depth exceeded during encoding.");
1457
- }
1458
-
1459
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1460
-
1461
- if (desc != msg->descriptor) {
1462
- rb_raise(rb_eArgError,
1463
- "The type of given msg is '%s', expect '%s'.",
1464
- upb_msgdef_fullname(msg->descriptor->msgdef),
1465
- upb_msgdef_fullname(desc->msgdef));
1466
- }
1467
-
1468
- for (upb_msg_field_begin(&i, desc->msgdef);
1469
- !upb_msg_field_done(&i);
1470
- upb_msg_field_next(&i)) {
1471
- upb_fielddef *f = upb_msg_iter_field(&i);
1472
- const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
1473
- bool is_matching_oneof = false;
1474
- uint32_t offset =
1475
- desc->layout->fields[upb_fielddef_index(f)].offset +
1476
- sizeof(MessageHeader);
1477
-
1478
- if (oneof) {
1479
- uint32_t oneof_case =
1480
- slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
1481
- // For a oneof, check that this field is actually present -- skip all the
1482
- // below if not.
1483
- if (oneof_case != upb_fielddef_number(f)) {
1484
- continue;
1485
- }
1486
- // Otherwise, fall through to the appropriate singular-field handler
1487
- // below.
1488
- is_matching_oneof = true;
1489
- }
1490
-
1491
- if (is_map_field(f)) {
1492
- VALUE map = DEREF(msg, offset, VALUE);
1493
- if (map != Qnil || emit_defaults) {
1494
- putmap(map, f, sink, depth, emit_defaults, is_json);
1495
- }
1496
- } else if (upb_fielddef_isseq(f)) {
1497
- VALUE ary = DEREF(msg, offset, VALUE);
1498
- if (ary != Qnil) {
1499
- putary(ary, f, sink, depth, emit_defaults, is_json);
1500
- }
1501
- } else if (upb_fielddef_isstring(f)) {
1502
- VALUE str = DEREF(msg, offset, VALUE);
1503
- bool is_default = false;
1504
-
1505
- if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
1506
- is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
1507
- } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
1508
- is_default = RSTRING_LEN(str) == 0;
1509
- }
1510
-
1511
- if (is_matching_oneof || emit_defaults || !is_default) {
1512
- putstr(str, f, sink);
1513
- }
1514
- } else if (upb_fielddef_issubmsg(f)) {
1515
- // OPT: could try to avoid the layout_get() (which will expand lazy
1516
- // wrappers).
1517
- VALUE val = layout_get(desc->layout, Message_data(msg), f);
1518
- putsubmsg(val, f, sink, depth, emit_defaults, is_json);
1519
- } else {
1520
- upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1521
-
1522
- #define T(upbtypeconst, upbtype, ctype, default_value) \
1523
- case upbtypeconst: { \
1524
- ctype value = DEREF(msg, offset, ctype); \
1525
- bool is_default = false; \
1526
- if (upb_fielddef_haspresence(f)) { \
1527
- is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse; \
1528
- } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) { \
1529
- is_default = default_value == value; \
1530
- } \
1531
- if (is_matching_oneof || emit_defaults || !is_default) { \
1532
- upb_sink_put##upbtype(sink, sel, value); \
1533
- } \
1534
- } break;
1535
-
1536
- switch (upb_fielddef_type(f)) {
1537
- T(UPB_TYPE_FLOAT, float, float, 0.0)
1538
- T(UPB_TYPE_DOUBLE, double, double, 0.0)
1539
- T(UPB_TYPE_BOOL, bool, uint8_t, 0)
1540
- case UPB_TYPE_ENUM:
1541
- T(UPB_TYPE_INT32, int32, int32_t, 0)
1542
- T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
1543
- T(UPB_TYPE_INT64, int64, int64_t, 0)
1544
- T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
1545
-
1546
- case UPB_TYPE_STRING:
1547
- case UPB_TYPE_BYTES:
1548
- case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
1549
- }
1550
-
1551
- #undef T
1552
- }
1553
- }
1554
-
1555
- {
1556
- stringsink* unknown = msg->unknown_fields;
1557
- if (unknown != NULL) {
1558
- upb_sink_putunknown(sink, unknown->ptr, unknown->len);
1559
- }
1560
- }
1561
-
1562
- if (open_msg) {
1563
- upb_sink_endmsg(sink, &status);
1564
- }
1565
- }
1566
-
1567
- /*
1568
- * call-seq:
1569
- * MessageClass.encode(msg) => bytes
1570
- *
1571
- * Encodes the given message object to its serialized form in protocol buffers
1572
- * wire format.
1573
- */
1574
- VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1575
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1576
- Descriptor* desc = ruby_to_Descriptor(descriptor);
1577
-
1578
- stringsink sink;
1579
- stringsink_init(&sink);
1580
-
1581
- {
1582
- const upb_handlers* serialize_handlers =
1583
- msgdef_pb_serialize_handlers(desc);
1584
-
1585
- stackenv se;
1586
- upb_pb_encoder* encoder;
1587
- VALUE ret;
1588
-
1589
- stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
1590
- encoder = upb_pb_encoder_create(se.arena, serialize_handlers, sink.sink);
1591
-
1592
- putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false, false, true);
1593
-
1594
- ret = rb_str_new(sink.ptr, sink.len);
1595
-
1596
- stackenv_uninit(&se);
1597
- stringsink_uninit(&sink);
1598
-
1599
- return ret;
1600
- }
1601
- }
1602
-
1603
- /*
1604
- * call-seq:
1605
- * MessageClass.encode_json(msg, options = {}) => json_string
1606
- *
1607
- * Encodes the given message object into its serialized JSON representation.
1608
- * @param options [Hash] options for the decoder
1609
- * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
1610
- * emit_defaults: set true to emit 0/false values (default is to omit them)
1611
- */
1612
- VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1613
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1614
- Descriptor* desc = ruby_to_Descriptor(descriptor);
1615
- VALUE msg_rb;
1616
- VALUE preserve_proto_fieldnames = Qfalse;
1617
- VALUE emit_defaults = Qfalse;
1618
- stringsink sink;
1619
-
1620
- if (argc < 1 || argc > 2) {
1621
- rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1622
- }
1623
-
1624
- msg_rb = argv[0];
1625
-
1626
- if (argc == 2) {
1627
- VALUE hash_args = argv[1];
1628
- if (TYPE(hash_args) != T_HASH) {
1629
- rb_raise(rb_eArgError, "Expected hash arguments.");
1630
- }
1631
- preserve_proto_fieldnames = rb_hash_lookup2(
1632
- hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
1633
-
1634
- emit_defaults = rb_hash_lookup2(
1635
- hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
1636
- }
1637
-
1638
- stringsink_init(&sink);
1639
-
1640
- {
1641
- const upb_handlers* serialize_handlers =
1642
- msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
1643
- upb_json_printer* printer;
1644
- stackenv se;
1645
- VALUE ret;
1646
-
1647
- stackenv_init(&se, "Error occurred during encoding: %" PRIsVALUE);
1648
- printer = upb_json_printer_create(se.arena, serialize_handlers, sink.sink);
1649
-
1650
- putmsg(msg_rb, desc, upb_json_printer_input(printer), 0,
1651
- RTEST(emit_defaults), true, true);
1652
-
1653
- ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
1654
-
1655
- stackenv_uninit(&se);
1656
- stringsink_uninit(&sink);
1657
-
1658
- return ret;
1659
- }
1660
- }
1661
-
1662
- static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
1663
- MessageHeader* msg;
1664
- upb_msg_field_iter it;
1665
-
1666
- TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1667
-
1668
- {
1669
- stringsink* unknown = msg->unknown_fields;
1670
- if (unknown != NULL) {
1671
- stringsink_uninit(unknown);
1672
- msg->unknown_fields = NULL;
1673
- }
1674
- }
1675
-
1676
- for (upb_msg_field_begin(&it, desc->msgdef);
1677
- !upb_msg_field_done(&it);
1678
- upb_msg_field_next(&it)) {
1679
- upb_fielddef *f = upb_msg_iter_field(&it);
1680
- const upb_oneofdef *oneof = upb_fielddef_containingoneof(f);
1681
- uint32_t offset =
1682
- desc->layout->fields[upb_fielddef_index(f)].offset +
1683
- sizeof(MessageHeader);
1684
-
1685
- if (oneof) {
1686
- uint32_t oneof_case =
1687
- slot_read_oneof_case(desc->layout, Message_data(msg), oneof);
1688
- // For a oneof, check that this field is actually present -- skip all the
1689
- // below if not.
1690
- if (oneof_case != upb_fielddef_number(f)) {
1691
- continue;
1692
- }
1693
- // Otherwise, fall through to the appropriate singular-field handler
1694
- // below.
1695
- }
1696
-
1697
- if (!upb_fielddef_issubmsg(f)) {
1698
- continue;
1699
- }
1700
-
1701
- if (is_map_field(f)) {
1702
- VALUE map;
1703
- Map_iter map_it;
1704
-
1705
- if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
1706
- map = DEREF(msg, offset, VALUE);
1707
- if (map == Qnil) continue;
1708
- for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
1709
- VALUE submsg = Map_iter_value(&map_it);
1710
- VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1711
- const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1712
- discard_unknown(submsg, subdesc);
1713
- }
1714
- } else if (upb_fielddef_isseq(f)) {
1715
- VALUE ary = DEREF(msg, offset, VALUE);
1716
- int size;
1717
- int i;
1718
-
1719
- if (ary == Qnil) continue;
1720
- size = NUM2INT(RepeatedField_length(ary));
1721
- for (i = 0; i < size; i++) {
1722
- void* memory = RepeatedField_index_native(ary, i);
1723
- VALUE submsg = *((VALUE *)memory);
1724
- VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1725
- const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1726
- discard_unknown(submsg, subdesc);
1727
- }
1728
- } else {
1729
- VALUE submsg = DEREF(msg, offset, VALUE);
1730
- VALUE descriptor;
1731
- const Descriptor* subdesc;
1732
-
1733
- if (submsg == Qnil) continue;
1734
- descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1735
- subdesc = ruby_to_Descriptor(descriptor);
1736
- discard_unknown(submsg, subdesc);
1737
- }
1738
- }
1739
- }
1740
-
1741
- /*
1742
- * call-seq:
1743
- * Google::Protobuf.discard_unknown(msg)
1744
- *
1745
- * Discard unknown fields in the given message object and recursively discard
1746
- * unknown fields in submessages.
1747
- */
1748
- VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
1749
- VALUE klass = CLASS_OF(msg_rb);
1750
- VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1751
- Descriptor* desc = ruby_to_Descriptor(descriptor);
1752
- if (klass == cRepeatedField || klass == cMap) {
1753
- rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
1754
- } else {
1755
- discard_unknown(msg_rb, desc);
1756
- }
1757
- return Qnil;
1758
- }