google-protobuf-z 3.5.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1453 @@
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
+ const upb_msgdef *md;
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
+ const upb_fielddef* f) {
128
+ submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
129
+ hd->ofs = ofs;
130
+ hd->hasbit = hasbit;
131
+ hd->md = upb_fielddef_msgsubdef(f);
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
+ const upb_msgdef *md; // msgdef, for oneof submessage handler
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
+ oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
148
+ hd->ofs = ofs;
149
+ hd->case_ofs = case_ofs;
150
+ // We reuse the field tag number as a oneof union discriminant tag. Note that
151
+ // we don't expose these numbers to the user, so the only requirement is that
152
+ // we have some unique ID for each union case/possibility. The field tag
153
+ // numbers are already present and are easy to use so there's no reason to
154
+ // create a separate ID space. In addition, using the field tag number here
155
+ // lets us easily look up the field in the oneof accessor.
156
+ hd->oneof_case_num = upb_fielddef_number(f);
157
+ if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
158
+ hd->md = upb_fielddef_msgsubdef(f);
159
+ } else {
160
+ hd->md = NULL;
161
+ }
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
+ MessageHeader* msg = closure;
258
+ const size_t *ofs = hd;
259
+ VALUE rb_str = DEREF(msg, *ofs, VALUE);
260
+ rb_obj_freeze(rb_str);
261
+ return true;
262
+ }
263
+
264
+ static bool appendstring_end_handler(void* closure, const void* hd) {
265
+ VALUE ary = (VALUE)closure;
266
+ int size = RepeatedField_size(ary);
267
+ VALUE* last = RepeatedField_index_native(ary, size - 1);
268
+ VALUE rb_str = *last;
269
+ rb_obj_freeze(rb_str);
270
+ return true;
271
+ }
272
+
273
+ // Appends a submessage to a repeated field (a regular Ruby array for now).
274
+ static void *appendsubmsg_handler(void *closure, const void *hd) {
275
+ VALUE ary = (VALUE)closure;
276
+ const submsg_handlerdata_t *submsgdata = hd;
277
+ VALUE subdesc =
278
+ get_def_obj((void*)submsgdata->md);
279
+ VALUE subklass = Descriptor_msgclass(subdesc);
280
+ MessageHeader* submsg;
281
+
282
+ VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
283
+ RepeatedField_push(ary, submsg_rb);
284
+
285
+ TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
286
+ return submsg;
287
+ }
288
+
289
+ // Sets a non-repeated submessage field in a message.
290
+ static void *submsg_handler(void *closure, const void *hd) {
291
+ MessageHeader* msg = closure;
292
+ const submsg_handlerdata_t* submsgdata = hd;
293
+ VALUE subdesc =
294
+ get_def_obj((void*)submsgdata->md);
295
+ VALUE subklass = Descriptor_msgclass(subdesc);
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, 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
+ // Handler data for startmap/endmap handlers.
313
+ typedef struct {
314
+ size_t ofs;
315
+ upb_fieldtype_t key_field_type;
316
+ upb_fieldtype_t value_field_type;
317
+
318
+ // We know that we can hold this reference because the handlerdata has the
319
+ // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
320
+ // a reference to the upb_msgdef, which in turn has references to its subdefs.
321
+ const upb_def* value_field_subdef;
322
+ } map_handlerdata_t;
323
+
324
+ // Temporary frame for map parsing: at the beginning of a map entry message, a
325
+ // submsg handler allocates a frame to hold (i) a reference to the Map object
326
+ // into which this message will be inserted and (ii) storage slots to
327
+ // temporarily hold the key and value for this map entry until the end of the
328
+ // submessage. When the submessage ends, another handler is called to insert the
329
+ // value into the map.
330
+ typedef struct {
331
+ VALUE map;
332
+ const map_handlerdata_t* handlerdata;
333
+ char key_storage[NATIVE_SLOT_MAX_SIZE];
334
+ char value_storage[NATIVE_SLOT_MAX_SIZE];
335
+ } map_parse_frame_t;
336
+
337
+ static void MapParseFrame_mark(void* _self) {
338
+ map_parse_frame_t* frame = _self;
339
+
340
+ // This shouldn't strictly be necessary since this should be rooted by the
341
+ // message itself, but it can't hurt.
342
+ rb_gc_mark(frame->map);
343
+
344
+ native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
345
+ native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
346
+ }
347
+
348
+ void MapParseFrame_free(void* self) {
349
+ xfree(self);
350
+ }
351
+
352
+ rb_data_type_t MapParseFrame_type = {
353
+ "MapParseFrame",
354
+ { MapParseFrame_mark, MapParseFrame_free, NULL },
355
+ };
356
+
357
+ static map_parse_frame_t* map_push_frame(VALUE map,
358
+ const map_handlerdata_t* handlerdata) {
359
+ map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
360
+ frame->handlerdata = handlerdata;
361
+ frame->map = map;
362
+ native_slot_init(handlerdata->key_field_type, &frame->key_storage);
363
+ native_slot_init(handlerdata->value_field_type, &frame->value_storage);
364
+
365
+ Map_set_frame(map,
366
+ TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
367
+
368
+ return frame;
369
+ }
370
+
371
+ // Handler to begin a map entry: allocates a temporary frame. This is the
372
+ // 'startsubmsg' handler on the msgdef that contains the map field.
373
+ static void *startmapentry_handler(void *closure, const void *hd) {
374
+ MessageHeader* msg = closure;
375
+ const map_handlerdata_t* mapdata = hd;
376
+ VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
377
+
378
+ return map_push_frame(map_rb, mapdata);
379
+ }
380
+
381
+ // Handler to end a map entry: inserts the value defined during the message into
382
+ // the map. This is the 'endmsg' handler on the map entry msgdef.
383
+ static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
384
+ map_parse_frame_t* frame = closure;
385
+ const map_handlerdata_t* mapdata = hd;
386
+
387
+ VALUE key = native_slot_get(
388
+ mapdata->key_field_type, Qnil,
389
+ &frame->key_storage);
390
+
391
+ VALUE value_field_typeclass = Qnil;
392
+ VALUE value;
393
+
394
+ if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
395
+ mapdata->value_field_type == UPB_TYPE_ENUM) {
396
+ value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
397
+ }
398
+
399
+ value = native_slot_get(
400
+ mapdata->value_field_type, value_field_typeclass,
401
+ &frame->value_storage);
402
+
403
+ Map_index_set(frame->map, key, value);
404
+ Map_set_frame(frame->map, Qnil);
405
+
406
+ return true;
407
+ }
408
+
409
+ // Allocates a new map_handlerdata_t given the map entry message definition. If
410
+ // the offset of the field within the parent message is also given, that is
411
+ // added to the handler data as well. Note that this is called *twice* per map
412
+ // field: once in the parent message handler setup when setting the startsubmsg
413
+ // handler and once in the map entry message handler setup when setting the
414
+ // key/value and endmsg handlers. The reason is that there is no easy way to
415
+ // pass the handlerdata down to the sub-message handler setup.
416
+ static map_handlerdata_t* new_map_handlerdata(
417
+ size_t ofs,
418
+ const upb_msgdef* mapentry_def,
419
+ Descriptor* desc) {
420
+ const upb_fielddef* key_field;
421
+ const upb_fielddef* value_field;
422
+ map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
423
+ hd->ofs = ofs;
424
+ key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
425
+ assert(key_field != NULL);
426
+ hd->key_field_type = upb_fielddef_type(key_field);
427
+ value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
428
+ assert(value_field != NULL);
429
+ hd->value_field_type = upb_fielddef_type(value_field);
430
+ hd->value_field_subdef = upb_fielddef_subdef(value_field);
431
+
432
+ return hd;
433
+ }
434
+
435
+ // Handlers that set primitive values in oneofs.
436
+ #define DEFINE_ONEOF_HANDLER(type, ctype) \
437
+ static bool oneof##type##_handler(void *closure, const void *hd, \
438
+ ctype val) { \
439
+ const oneof_handlerdata_t *oneofdata = hd; \
440
+ DEREF(closure, oneofdata->case_ofs, uint32_t) = \
441
+ oneofdata->oneof_case_num; \
442
+ DEREF(closure, oneofdata->ofs, ctype) = val; \
443
+ return true; \
444
+ }
445
+
446
+ DEFINE_ONEOF_HANDLER(bool, bool)
447
+ DEFINE_ONEOF_HANDLER(int32, int32_t)
448
+ DEFINE_ONEOF_HANDLER(uint32, uint32_t)
449
+ DEFINE_ONEOF_HANDLER(float, float)
450
+ DEFINE_ONEOF_HANDLER(int64, int64_t)
451
+ DEFINE_ONEOF_HANDLER(uint64, uint64_t)
452
+ DEFINE_ONEOF_HANDLER(double, double)
453
+
454
+ #undef DEFINE_ONEOF_HANDLER
455
+
456
+ // Handlers for strings in a oneof.
457
+ static void *oneofstr_handler(void *closure,
458
+ const void *hd,
459
+ size_t size_hint) {
460
+ MessageHeader* msg = closure;
461
+ const oneof_handlerdata_t *oneofdata = hd;
462
+ VALUE str = rb_str_new2("");
463
+ rb_enc_associate(str, kRubyStringUtf8Encoding);
464
+ DEREF(msg, oneofdata->case_ofs, uint32_t) =
465
+ oneofdata->oneof_case_num;
466
+ DEREF(msg, oneofdata->ofs, VALUE) = str;
467
+ return (void*)str;
468
+ }
469
+
470
+ static void *oneofbytes_handler(void *closure,
471
+ const void *hd,
472
+ size_t size_hint) {
473
+ MessageHeader* msg = closure;
474
+ const oneof_handlerdata_t *oneofdata = hd;
475
+ VALUE str = rb_str_new2("");
476
+ rb_enc_associate(str, kRubyString8bitEncoding);
477
+ DEREF(msg, oneofdata->case_ofs, uint32_t) =
478
+ oneofdata->oneof_case_num;
479
+ DEREF(msg, oneofdata->ofs, VALUE) = str;
480
+ return (void*)str;
481
+ }
482
+
483
+ static bool oneofstring_end_handler(void* closure, const void* hd) {
484
+ MessageHeader* msg = closure;
485
+ const oneof_handlerdata_t *oneofdata = hd;
486
+ rb_obj_freeze(DEREF(msg, oneofdata->ofs, VALUE));
487
+ return true;
488
+ }
489
+
490
+ // Handler for a submessage field in a oneof.
491
+ static void *oneofsubmsg_handler(void *closure,
492
+ const void *hd) {
493
+ MessageHeader* msg = closure;
494
+ const oneof_handlerdata_t *oneofdata = hd;
495
+ uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
496
+
497
+ VALUE subdesc =
498
+ get_def_obj((void*)oneofdata->md);
499
+ VALUE subklass = Descriptor_msgclass(subdesc);
500
+ VALUE submsg_rb;
501
+ MessageHeader* submsg;
502
+
503
+ if (oldcase != oneofdata->oneof_case_num ||
504
+ DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
505
+ DEREF(msg, oneofdata->ofs, VALUE) =
506
+ rb_class_new_instance(0, NULL, subklass);
507
+ }
508
+ // Set the oneof case *after* allocating the new class instance -- otherwise,
509
+ // if the Ruby GC is invoked as part of a call into the VM, it might invoke
510
+ // our mark routines, and our mark routines might see the case value
511
+ // indicating a VALUE is present and expect a valid VALUE. See comment in
512
+ // layout_set() for more detail: basically, the change to the value and the
513
+ // case must be atomic w.r.t. the Ruby VM.
514
+ DEREF(msg, oneofdata->case_ofs, uint32_t) =
515
+ oneofdata->oneof_case_num;
516
+
517
+ submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
518
+ TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
519
+ return submsg;
520
+ }
521
+
522
+ // Set up handlers for a repeated field.
523
+ static void add_handlers_for_repeated_field(upb_handlers *h,
524
+ const upb_fielddef *f,
525
+ size_t offset) {
526
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
527
+ upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, -1));
528
+ upb_handlers_setstartseq(h, f, startseq_handler, &attr);
529
+ upb_handlerattr_uninit(&attr);
530
+
531
+ switch (upb_fielddef_type(f)) {
532
+
533
+ #define SET_HANDLER(utype, ltype) \
534
+ case utype: \
535
+ upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
536
+ break;
537
+
538
+ SET_HANDLER(UPB_TYPE_BOOL, bool);
539
+ SET_HANDLER(UPB_TYPE_INT32, int32);
540
+ SET_HANDLER(UPB_TYPE_UINT32, uint32);
541
+ SET_HANDLER(UPB_TYPE_ENUM, int32);
542
+ SET_HANDLER(UPB_TYPE_FLOAT, float);
543
+ SET_HANDLER(UPB_TYPE_INT64, int64);
544
+ SET_HANDLER(UPB_TYPE_UINT64, uint64);
545
+ SET_HANDLER(UPB_TYPE_DOUBLE, double);
546
+
547
+ #undef SET_HANDLER
548
+
549
+ case UPB_TYPE_STRING:
550
+ case UPB_TYPE_BYTES: {
551
+ bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
552
+ upb_handlers_setstartstr(h, f, is_bytes ?
553
+ appendbytes_handler : appendstr_handler,
554
+ NULL);
555
+ upb_handlers_setstring(h, f, stringdata_handler, NULL);
556
+ upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
557
+ break;
558
+ }
559
+ case UPB_TYPE_MESSAGE: {
560
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
561
+ upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, -1, f));
562
+ upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
563
+ upb_handlerattr_uninit(&attr);
564
+ break;
565
+ }
566
+ }
567
+ }
568
+
569
+ // Set up handlers for a singular field.
570
+ static void add_handlers_for_singular_field(upb_handlers *h,
571
+ const upb_fielddef *f,
572
+ size_t offset,
573
+ size_t hasbit_off) {
574
+ // The offset we pass to UPB points to the start of the Message,
575
+ // rather than the start of where our data is stored.
576
+ int32_t hasbit = -1;
577
+ if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
578
+ hasbit = hasbit_off + sizeof(MessageHeader) * 8;
579
+ }
580
+
581
+ switch (upb_fielddef_type(f)) {
582
+ case UPB_TYPE_BOOL:
583
+ case UPB_TYPE_INT32:
584
+ case UPB_TYPE_UINT32:
585
+ case UPB_TYPE_ENUM:
586
+ case UPB_TYPE_FLOAT:
587
+ case UPB_TYPE_INT64:
588
+ case UPB_TYPE_UINT64:
589
+ case UPB_TYPE_DOUBLE:
590
+ upb_msg_setscalarhandler(h, f, offset, hasbit);
591
+ break;
592
+ case UPB_TYPE_STRING:
593
+ case UPB_TYPE_BYTES: {
594
+ bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
595
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
596
+ upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, hasbit));
597
+ upb_handlers_setstartstr(h, f,
598
+ is_bytes ? bytes_handler : str_handler,
599
+ &attr);
600
+ upb_handlers_setstring(h, f, stringdata_handler, &attr);
601
+ upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
602
+ upb_handlerattr_uninit(&attr);
603
+ break;
604
+ }
605
+ case UPB_TYPE_MESSAGE: {
606
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
607
+ upb_handlerattr_sethandlerdata(&attr,
608
+ newsubmsghandlerdata(h, offset,
609
+ hasbit, f));
610
+ upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
611
+ upb_handlerattr_uninit(&attr);
612
+ break;
613
+ }
614
+ }
615
+ }
616
+
617
+ // Adds handlers to a map field.
618
+ static void add_handlers_for_mapfield(upb_handlers* h,
619
+ const upb_fielddef* fielddef,
620
+ size_t offset,
621
+ Descriptor* desc) {
622
+ const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
623
+ map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
624
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
625
+
626
+ upb_handlers_addcleanup(h, hd, xfree);
627
+ upb_handlerattr_sethandlerdata(&attr, hd);
628
+ upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
629
+ upb_handlerattr_uninit(&attr);
630
+ }
631
+
632
+ // Adds handlers to a map-entry msgdef.
633
+ static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
634
+ upb_handlers* h,
635
+ Descriptor* desc) {
636
+ const upb_fielddef* key_field = map_entry_key(msgdef);
637
+ const upb_fielddef* value_field = map_entry_value(msgdef);
638
+ map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
639
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
640
+
641
+ upb_handlers_addcleanup(h, hd, xfree);
642
+ upb_handlerattr_sethandlerdata(&attr, hd);
643
+ upb_handlers_setendmsg(h, endmap_handler, &attr);
644
+
645
+ add_handlers_for_singular_field(
646
+ h, key_field,
647
+ offsetof(map_parse_frame_t, key_storage),
648
+ MESSAGE_FIELD_NO_HASBIT);
649
+ add_handlers_for_singular_field(
650
+ h, value_field,
651
+ offsetof(map_parse_frame_t, value_storage),
652
+ MESSAGE_FIELD_NO_HASBIT);
653
+ }
654
+
655
+ // Set up handlers for a oneof field.
656
+ static void add_handlers_for_oneof_field(upb_handlers *h,
657
+ const upb_fielddef *f,
658
+ size_t offset,
659
+ size_t oneof_case_offset) {
660
+
661
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
662
+ upb_handlerattr_sethandlerdata(
663
+ &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
664
+
665
+ switch (upb_fielddef_type(f)) {
666
+
667
+ #define SET_HANDLER(utype, ltype) \
668
+ case utype: \
669
+ upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
670
+ break;
671
+
672
+ SET_HANDLER(UPB_TYPE_BOOL, bool);
673
+ SET_HANDLER(UPB_TYPE_INT32, int32);
674
+ SET_HANDLER(UPB_TYPE_UINT32, uint32);
675
+ SET_HANDLER(UPB_TYPE_ENUM, int32);
676
+ SET_HANDLER(UPB_TYPE_FLOAT, float);
677
+ SET_HANDLER(UPB_TYPE_INT64, int64);
678
+ SET_HANDLER(UPB_TYPE_UINT64, uint64);
679
+ SET_HANDLER(UPB_TYPE_DOUBLE, double);
680
+
681
+ #undef SET_HANDLER
682
+
683
+ case UPB_TYPE_STRING:
684
+ case UPB_TYPE_BYTES: {
685
+ bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
686
+ upb_handlers_setstartstr(h, f, is_bytes ?
687
+ oneofbytes_handler : oneofstr_handler,
688
+ &attr);
689
+ upb_handlers_setstring(h, f, stringdata_handler, NULL);
690
+ upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
691
+ break;
692
+ }
693
+ case UPB_TYPE_MESSAGE: {
694
+ upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
695
+ break;
696
+ }
697
+ }
698
+
699
+ upb_handlerattr_uninit(&attr);
700
+ }
701
+
702
+ static bool unknown_field_handler(void* closure, const void* hd,
703
+ const char* buf, size_t size) {
704
+ UPB_UNUSED(hd);
705
+
706
+ MessageHeader* msg = (MessageHeader*)closure;
707
+ if (msg->unknown_fields == NULL) {
708
+ msg->unknown_fields = malloc(sizeof(stringsink));
709
+ stringsink_init(msg->unknown_fields);
710
+ }
711
+
712
+ stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
713
+
714
+ return true;
715
+ }
716
+
717
+ static void add_handlers_for_message(const void *closure, upb_handlers *h) {
718
+ const upb_msgdef* msgdef = upb_handlers_msgdef(h);
719
+ Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
720
+ upb_msg_field_iter i;
721
+
722
+ // If this is a mapentry message type, set up a special set of handlers and
723
+ // bail out of the normal (user-defined) message type handling.
724
+ if (upb_msgdef_mapentry(msgdef)) {
725
+ add_handlers_for_mapentry(msgdef, h, desc);
726
+ return;
727
+ }
728
+
729
+ // Ensure layout exists. We may be invoked to create handlers for a given
730
+ // message if we are included as a submsg of another message type before our
731
+ // class is actually built, so to work around this, we just create the layout
732
+ // (and handlers, in the class-building function) on-demand.
733
+ if (desc->layout == NULL) {
734
+ desc->layout = create_layout(desc->msgdef);
735
+ }
736
+
737
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
738
+ upb_handlers_setunknown(h, unknown_field_handler, &attr);
739
+
740
+ for (upb_msg_field_begin(&i, desc->msgdef);
741
+ !upb_msg_field_done(&i);
742
+ upb_msg_field_next(&i)) {
743
+ const upb_fielddef *f = upb_msg_iter_field(&i);
744
+ size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
745
+ sizeof(MessageHeader);
746
+
747
+ if (upb_fielddef_containingoneof(f)) {
748
+ size_t oneof_case_offset =
749
+ desc->layout->fields[upb_fielddef_index(f)].case_offset +
750
+ sizeof(MessageHeader);
751
+ add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
752
+ } else if (is_map_field(f)) {
753
+ add_handlers_for_mapfield(h, f, offset, desc);
754
+ } else if (upb_fielddef_isseq(f)) {
755
+ add_handlers_for_repeated_field(h, f, offset);
756
+ } else {
757
+ add_handlers_for_singular_field(
758
+ h, f, offset, desc->layout->fields[upb_fielddef_index(f)].hasbit);
759
+ }
760
+ }
761
+ }
762
+
763
+ // Creates upb handlers for populating a message.
764
+ static const upb_handlers *new_fill_handlers(Descriptor* desc,
765
+ const void* owner) {
766
+ // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
767
+ // handlers, reuse subdef handlers so that e.g. if we already parse
768
+ // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
769
+ // parse A-with-field-of-type-B-with-field-of-type-C.
770
+ return upb_handlers_newfrozen(desc->msgdef, owner,
771
+ add_handlers_for_message, NULL);
772
+ }
773
+
774
+ // Constructs the handlers for filling a message's data into an in-memory
775
+ // object.
776
+ const upb_handlers* get_fill_handlers(Descriptor* desc) {
777
+ if (!desc->fill_handlers) {
778
+ desc->fill_handlers =
779
+ new_fill_handlers(desc, &desc->fill_handlers);
780
+ }
781
+ return desc->fill_handlers;
782
+ }
783
+
784
+ // Constructs the upb decoder method for parsing messages of this type.
785
+ // This is called from the message class creation code.
786
+ const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
787
+ const void* owner) {
788
+ const upb_handlers* handlers = get_fill_handlers(desc);
789
+ upb_pbdecodermethodopts opts;
790
+ upb_pbdecodermethodopts_init(&opts, handlers);
791
+
792
+ return upb_pbdecodermethod_new(&opts, owner);
793
+ }
794
+
795
+ static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
796
+ if (desc->fill_method == NULL) {
797
+ desc->fill_method = new_fillmsg_decodermethod(
798
+ desc, &desc->fill_method);
799
+ }
800
+ return desc->fill_method;
801
+ }
802
+
803
+ static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
804
+ if (desc->json_fill_method == NULL) {
805
+ desc->json_fill_method =
806
+ upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
807
+ }
808
+ return desc->json_fill_method;
809
+ }
810
+
811
+
812
+ // Stack-allocated context during an encode/decode operation. Contains the upb
813
+ // environment and its stack-based allocator, an initial buffer for allocations
814
+ // to avoid malloc() when possible, and a template for Ruby exception messages
815
+ // if any error occurs.
816
+ #define STACK_ENV_STACKBYTES 4096
817
+ typedef struct {
818
+ upb_env env;
819
+ const char* ruby_error_template;
820
+ char allocbuf[STACK_ENV_STACKBYTES];
821
+ } stackenv;
822
+
823
+ static void stackenv_init(stackenv* se, const char* errmsg);
824
+ static void stackenv_uninit(stackenv* se);
825
+
826
+ // Callback invoked by upb if any error occurs during parsing or serialization.
827
+ static bool env_error_func(void* ud, const upb_status* status) {
828
+ stackenv* se = ud;
829
+ // Free the env -- rb_raise will longjmp up the stack past the encode/decode
830
+ // function so it would not otherwise have been freed.
831
+ stackenv_uninit(se);
832
+
833
+ // TODO(haberman): have a way to verify that this is actually a parse error,
834
+ // instead of just throwing "parse error" unconditionally.
835
+ rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
836
+ // Never reached: rb_raise() always longjmp()s up the stack, past all of our
837
+ // code, back to Ruby.
838
+ return false;
839
+ }
840
+
841
+ static void stackenv_init(stackenv* se, const char* errmsg) {
842
+ se->ruby_error_template = errmsg;
843
+ upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
844
+ upb_env_seterrorfunc(&se->env, env_error_func, se);
845
+ }
846
+
847
+ static void stackenv_uninit(stackenv* se) {
848
+ upb_env_uninit(&se->env);
849
+ }
850
+
851
+ /*
852
+ * call-seq:
853
+ * MessageClass.decode(data) => message
854
+ *
855
+ * Decodes the given data (as a string containing bytes in protocol buffers wire
856
+ * format) under the interpretration given by this message class's definition
857
+ * and returns a message object with the corresponding field values.
858
+ */
859
+ VALUE Message_decode(VALUE klass, VALUE data) {
860
+ VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
861
+ Descriptor* desc = ruby_to_Descriptor(descriptor);
862
+ VALUE msgklass = Descriptor_msgclass(descriptor);
863
+ VALUE msg_rb;
864
+ MessageHeader* msg;
865
+
866
+ if (TYPE(data) != T_STRING) {
867
+ rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
868
+ }
869
+
870
+ msg_rb = rb_class_new_instance(0, NULL, msgklass);
871
+ TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
872
+
873
+ {
874
+ const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
875
+ const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
876
+ stackenv se;
877
+ upb_sink sink;
878
+ upb_pbdecoder* decoder;
879
+ stackenv_init(&se, "Error occurred during parsing: %s");
880
+
881
+ upb_sink_reset(&sink, h, msg);
882
+ decoder = upb_pbdecoder_create(&se.env, method, &sink);
883
+ upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
884
+ upb_pbdecoder_input(decoder));
885
+
886
+ stackenv_uninit(&se);
887
+ }
888
+
889
+ return msg_rb;
890
+ }
891
+
892
+ /*
893
+ * call-seq:
894
+ * MessageClass.decode_json(data) => message
895
+ *
896
+ * Decodes the given data (as a string containing bytes in protocol buffers wire
897
+ * format) under the interpretration given by this message class's definition
898
+ * and returns a message object with the corresponding field values.
899
+ */
900
+ VALUE Message_decode_json(VALUE klass, VALUE data) {
901
+ VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
902
+ Descriptor* desc = ruby_to_Descriptor(descriptor);
903
+ VALUE msgklass = Descriptor_msgclass(descriptor);
904
+ VALUE msg_rb;
905
+ MessageHeader* msg;
906
+
907
+ if (TYPE(data) != T_STRING) {
908
+ rb_raise(rb_eArgError, "Expected string for JSON data.");
909
+ }
910
+ // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
911
+ // convert, because string handlers pass data directly to message string
912
+ // fields.
913
+
914
+ msg_rb = rb_class_new_instance(0, NULL, msgklass);
915
+ TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
916
+
917
+ {
918
+ const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
919
+ stackenv se;
920
+ upb_sink sink;
921
+ upb_json_parser* parser;
922
+ stackenv_init(&se, "Error occurred during parsing: %s");
923
+
924
+ upb_sink_reset(&sink, get_fill_handlers(desc), msg);
925
+ parser = upb_json_parser_create(&se.env, method, &sink);
926
+ upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
927
+ upb_json_parser_input(parser));
928
+
929
+ stackenv_uninit(&se);
930
+ }
931
+
932
+ return msg_rb;
933
+ }
934
+
935
+ // -----------------------------------------------------------------------------
936
+ // Serializing.
937
+ // -----------------------------------------------------------------------------
938
+
939
+ /* msgvisitor *****************************************************************/
940
+
941
+ static void putmsg(VALUE msg, const Descriptor* desc,
942
+ upb_sink *sink, int depth, bool emit_defaults);
943
+
944
+ static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
945
+ upb_selector_t ret;
946
+ bool ok = upb_handlers_getselector(f, type, &ret);
947
+ UPB_ASSERT(ok);
948
+ return ret;
949
+ }
950
+
951
+ static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
952
+ upb_sink subsink;
953
+
954
+ if (str == Qnil) return;
955
+
956
+ assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
957
+
958
+ // We should be guaranteed that the string has the correct encoding because
959
+ // we ensured this at assignment time and then froze the string.
960
+ if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
961
+ assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
962
+ } else {
963
+ assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
964
+ }
965
+
966
+ upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
967
+ &subsink);
968
+ upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
969
+ RSTRING_LEN(str), NULL);
970
+ upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
971
+ }
972
+
973
+ static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
974
+ int depth, bool emit_defaults) {
975
+ upb_sink subsink;
976
+ VALUE descriptor;
977
+ Descriptor* subdesc;
978
+
979
+ if (submsg == Qnil) return;
980
+
981
+ descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
982
+ subdesc = ruby_to_Descriptor(descriptor);
983
+
984
+ upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
985
+ putmsg(submsg, subdesc, &subsink, depth + 1, emit_defaults);
986
+ upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
987
+ }
988
+
989
+ static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
990
+ int depth, bool emit_defaults) {
991
+ upb_sink subsink;
992
+ upb_fieldtype_t type = upb_fielddef_type(f);
993
+ upb_selector_t sel = 0;
994
+ int size;
995
+
996
+ if (ary == Qnil) return;
997
+ if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
998
+
999
+ size = NUM2INT(RepeatedField_length(ary));
1000
+ if (size == 0 && !emit_defaults) return;
1001
+
1002
+ upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1003
+
1004
+ if (upb_fielddef_isprimitive(f)) {
1005
+ sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1006
+ }
1007
+
1008
+ for (int i = 0; i < size; i++) {
1009
+ void* memory = RepeatedField_index_native(ary, i);
1010
+ switch (type) {
1011
+ #define T(upbtypeconst, upbtype, ctype) \
1012
+ case upbtypeconst: \
1013
+ upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
1014
+ break;
1015
+
1016
+ T(UPB_TYPE_FLOAT, float, float)
1017
+ T(UPB_TYPE_DOUBLE, double, double)
1018
+ T(UPB_TYPE_BOOL, bool, int8_t)
1019
+ case UPB_TYPE_ENUM:
1020
+ T(UPB_TYPE_INT32, int32, int32_t)
1021
+ T(UPB_TYPE_UINT32, uint32, uint32_t)
1022
+ T(UPB_TYPE_INT64, int64, int64_t)
1023
+ T(UPB_TYPE_UINT64, uint64, uint64_t)
1024
+
1025
+ case UPB_TYPE_STRING:
1026
+ case UPB_TYPE_BYTES:
1027
+ putstr(*((VALUE *)memory), f, &subsink);
1028
+ break;
1029
+ case UPB_TYPE_MESSAGE:
1030
+ putsubmsg(*((VALUE *)memory), f, &subsink, depth, emit_defaults);
1031
+ break;
1032
+
1033
+ #undef T
1034
+
1035
+ }
1036
+ }
1037
+ upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1038
+ }
1039
+
1040
+ static void put_ruby_value(VALUE value,
1041
+ const upb_fielddef *f,
1042
+ VALUE type_class,
1043
+ int depth,
1044
+ upb_sink *sink,
1045
+ bool emit_defaults) {
1046
+ upb_selector_t sel = 0;
1047
+ if (upb_fielddef_isprimitive(f)) {
1048
+ sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1049
+ }
1050
+
1051
+ switch (upb_fielddef_type(f)) {
1052
+ case UPB_TYPE_INT32:
1053
+ upb_sink_putint32(sink, sel, NUM2INT(value));
1054
+ break;
1055
+ case UPB_TYPE_INT64:
1056
+ upb_sink_putint64(sink, sel, NUM2LL(value));
1057
+ break;
1058
+ case UPB_TYPE_UINT32:
1059
+ upb_sink_putuint32(sink, sel, NUM2UINT(value));
1060
+ break;
1061
+ case UPB_TYPE_UINT64:
1062
+ upb_sink_putuint64(sink, sel, NUM2ULL(value));
1063
+ break;
1064
+ case UPB_TYPE_FLOAT:
1065
+ upb_sink_putfloat(sink, sel, NUM2DBL(value));
1066
+ break;
1067
+ case UPB_TYPE_DOUBLE:
1068
+ upb_sink_putdouble(sink, sel, NUM2DBL(value));
1069
+ break;
1070
+ case UPB_TYPE_ENUM: {
1071
+ if (TYPE(value) == T_SYMBOL) {
1072
+ value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
1073
+ }
1074
+ upb_sink_putint32(sink, sel, NUM2INT(value));
1075
+ break;
1076
+ }
1077
+ case UPB_TYPE_BOOL:
1078
+ upb_sink_putbool(sink, sel, value == Qtrue);
1079
+ break;
1080
+ case UPB_TYPE_STRING:
1081
+ case UPB_TYPE_BYTES:
1082
+ putstr(value, f, sink);
1083
+ break;
1084
+ case UPB_TYPE_MESSAGE:
1085
+ putsubmsg(value, f, sink, depth, emit_defaults);
1086
+ }
1087
+ }
1088
+
1089
+ static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
1090
+ int depth, bool emit_defaults) {
1091
+ Map* self;
1092
+ upb_sink subsink;
1093
+ const upb_fielddef* key_field;
1094
+ const upb_fielddef* value_field;
1095
+ Map_iter it;
1096
+
1097
+ if (map == Qnil) return;
1098
+ if (!emit_defaults && Map_length(map) == 0) return;
1099
+
1100
+ self = ruby_to_Map(map);
1101
+
1102
+ upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1103
+
1104
+ assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
1105
+ key_field = map_field_key(f);
1106
+ value_field = map_field_value(f);
1107
+
1108
+ for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
1109
+ VALUE key = Map_iter_key(&it);
1110
+ VALUE value = Map_iter_value(&it);
1111
+ upb_status status;
1112
+
1113
+ upb_sink entry_sink;
1114
+ upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
1115
+ &entry_sink);
1116
+ upb_sink_startmsg(&entry_sink);
1117
+
1118
+ put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink, emit_defaults);
1119
+ put_ruby_value(value, value_field, self->value_type_class, depth + 1,
1120
+ &entry_sink, emit_defaults);
1121
+
1122
+ upb_sink_endmsg(&entry_sink, &status);
1123
+ upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1124
+ }
1125
+
1126
+ upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1127
+ }
1128
+
1129
+ static void putmsg(VALUE msg_rb, const Descriptor* desc,
1130
+ upb_sink *sink, int depth, bool emit_defaults) {
1131
+ MessageHeader* msg;
1132
+ upb_msg_field_iter i;
1133
+ upb_status status;
1134
+
1135
+ upb_sink_startmsg(sink);
1136
+
1137
+ // Protect against cycles (possible because users may freely reassign message
1138
+ // and repeated fields) by imposing a maximum recursion depth.
1139
+ if (depth > ENCODE_MAX_NESTING) {
1140
+ rb_raise(rb_eRuntimeError,
1141
+ "Maximum recursion depth exceeded during encoding.");
1142
+ }
1143
+
1144
+ TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1145
+
1146
+ if (desc != msg->descriptor) {
1147
+ rb_raise(rb_eArgError,
1148
+ "The type of given msg is '%s', expect '%s'.",
1149
+ upb_msgdef_fullname(msg->descriptor->msgdef),
1150
+ upb_msgdef_fullname(desc->msgdef));
1151
+ }
1152
+
1153
+ for (upb_msg_field_begin(&i, desc->msgdef);
1154
+ !upb_msg_field_done(&i);
1155
+ upb_msg_field_next(&i)) {
1156
+ upb_fielddef *f = upb_msg_iter_field(&i);
1157
+ bool is_matching_oneof = false;
1158
+ uint32_t offset =
1159
+ desc->layout->fields[upb_fielddef_index(f)].offset +
1160
+ sizeof(MessageHeader);
1161
+
1162
+ if (upb_fielddef_containingoneof(f)) {
1163
+ uint32_t oneof_case_offset =
1164
+ desc->layout->fields[upb_fielddef_index(f)].case_offset +
1165
+ sizeof(MessageHeader);
1166
+ // For a oneof, check that this field is actually present -- skip all the
1167
+ // below if not.
1168
+ if (DEREF(msg, oneof_case_offset, uint32_t) !=
1169
+ upb_fielddef_number(f)) {
1170
+ continue;
1171
+ }
1172
+ // Otherwise, fall through to the appropriate singular-field handler
1173
+ // below.
1174
+ is_matching_oneof = true;
1175
+ }
1176
+
1177
+ if (is_map_field(f)) {
1178
+ VALUE map = DEREF(msg, offset, VALUE);
1179
+ if (map != Qnil || emit_defaults) {
1180
+ putmap(map, f, sink, depth, emit_defaults);
1181
+ }
1182
+ } else if (upb_fielddef_isseq(f)) {
1183
+ VALUE ary = DEREF(msg, offset, VALUE);
1184
+ if (ary != Qnil) {
1185
+ putary(ary, f, sink, depth, emit_defaults);
1186
+ }
1187
+ } else if (upb_fielddef_isstring(f)) {
1188
+ VALUE str = DEREF(msg, offset, VALUE);
1189
+ bool is_default = false;
1190
+
1191
+ if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
1192
+ is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
1193
+ } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
1194
+ is_default = RSTRING_LEN(str) == 0;
1195
+ }
1196
+
1197
+ if (is_matching_oneof || emit_defaults || !is_default) {
1198
+ putstr(str, f, sink);
1199
+ }
1200
+ } else if (upb_fielddef_issubmsg(f)) {
1201
+ putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth, emit_defaults);
1202
+ } else {
1203
+ upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1204
+
1205
+ #define T(upbtypeconst, upbtype, ctype, default_value) \
1206
+ case upbtypeconst: { \
1207
+ ctype value = DEREF(msg, offset, ctype); \
1208
+ bool is_default = false; \
1209
+ if (upb_fielddef_haspresence(f)) { \
1210
+ is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse; \
1211
+ } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) { \
1212
+ is_default = default_value == value; \
1213
+ } \
1214
+ if (is_matching_oneof || emit_defaults || !is_default) { \
1215
+ upb_sink_put##upbtype(sink, sel, value); \
1216
+ } \
1217
+ } \
1218
+ break;
1219
+
1220
+ switch (upb_fielddef_type(f)) {
1221
+ T(UPB_TYPE_FLOAT, float, float, 0.0)
1222
+ T(UPB_TYPE_DOUBLE, double, double, 0.0)
1223
+ T(UPB_TYPE_BOOL, bool, uint8_t, 0)
1224
+ case UPB_TYPE_ENUM:
1225
+ T(UPB_TYPE_INT32, int32, int32_t, 0)
1226
+ T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
1227
+ T(UPB_TYPE_INT64, int64, int64_t, 0)
1228
+ T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
1229
+
1230
+ case UPB_TYPE_STRING:
1231
+ case UPB_TYPE_BYTES:
1232
+ case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
1233
+ }
1234
+
1235
+ #undef T
1236
+
1237
+ }
1238
+ }
1239
+
1240
+ stringsink* unknown = msg->unknown_fields;
1241
+ if (unknown != NULL) {
1242
+ upb_sink_putunknown(sink, unknown->ptr, unknown->len);
1243
+ }
1244
+
1245
+ upb_sink_endmsg(sink, &status);
1246
+ }
1247
+
1248
+ static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
1249
+ if (desc->pb_serialize_handlers == NULL) {
1250
+ desc->pb_serialize_handlers =
1251
+ upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
1252
+ }
1253
+ return desc->pb_serialize_handlers;
1254
+ }
1255
+
1256
+ static const upb_handlers* msgdef_json_serialize_handlers(
1257
+ Descriptor* desc, bool preserve_proto_fieldnames) {
1258
+ if (preserve_proto_fieldnames) {
1259
+ if (desc->json_serialize_handlers == NULL) {
1260
+ desc->json_serialize_handlers =
1261
+ upb_json_printer_newhandlers(
1262
+ desc->msgdef, true, &desc->json_serialize_handlers);
1263
+ }
1264
+ return desc->json_serialize_handlers;
1265
+ } else {
1266
+ if (desc->json_serialize_handlers_preserve == NULL) {
1267
+ desc->json_serialize_handlers_preserve =
1268
+ upb_json_printer_newhandlers(
1269
+ desc->msgdef, false, &desc->json_serialize_handlers_preserve);
1270
+ }
1271
+ return desc->json_serialize_handlers_preserve;
1272
+ }
1273
+ }
1274
+
1275
+ /*
1276
+ * call-seq:
1277
+ * MessageClass.encode(msg) => bytes
1278
+ *
1279
+ * Encodes the given message object to its serialized form in protocol buffers
1280
+ * wire format.
1281
+ */
1282
+ VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1283
+ VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1284
+ Descriptor* desc = ruby_to_Descriptor(descriptor);
1285
+
1286
+ stringsink sink;
1287
+ stringsink_init(&sink);
1288
+
1289
+ {
1290
+ const upb_handlers* serialize_handlers =
1291
+ msgdef_pb_serialize_handlers(desc);
1292
+
1293
+ stackenv se;
1294
+ upb_pb_encoder* encoder;
1295
+ VALUE ret;
1296
+
1297
+ stackenv_init(&se, "Error occurred during encoding: %s");
1298
+ encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
1299
+
1300
+ putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false);
1301
+
1302
+ ret = rb_str_new(sink.ptr, sink.len);
1303
+
1304
+ stackenv_uninit(&se);
1305
+ stringsink_uninit(&sink);
1306
+
1307
+ return ret;
1308
+ }
1309
+ }
1310
+
1311
+ /*
1312
+ * call-seq:
1313
+ * MessageClass.encode_json(msg) => json_string
1314
+ *
1315
+ * Encodes the given message object into its serialized JSON representation.
1316
+ */
1317
+ VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1318
+ VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1319
+ Descriptor* desc = ruby_to_Descriptor(descriptor);
1320
+ VALUE msg_rb;
1321
+ VALUE preserve_proto_fieldnames = Qfalse;
1322
+ VALUE emit_defaults = Qfalse;
1323
+ stringsink sink;
1324
+
1325
+ if (argc < 1 || argc > 2) {
1326
+ rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1327
+ }
1328
+
1329
+ msg_rb = argv[0];
1330
+
1331
+ if (argc == 2) {
1332
+ VALUE hash_args = argv[1];
1333
+ if (TYPE(hash_args) != T_HASH) {
1334
+ rb_raise(rb_eArgError, "Expected hash arguments.");
1335
+ }
1336
+ preserve_proto_fieldnames = rb_hash_lookup2(
1337
+ hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
1338
+
1339
+ emit_defaults = rb_hash_lookup2(
1340
+ hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
1341
+ }
1342
+
1343
+ stringsink_init(&sink);
1344
+
1345
+ {
1346
+ const upb_handlers* serialize_handlers =
1347
+ msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
1348
+ upb_json_printer* printer;
1349
+ stackenv se;
1350
+ VALUE ret;
1351
+
1352
+ stackenv_init(&se, "Error occurred during encoding: %s");
1353
+ printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
1354
+
1355
+ putmsg(msg_rb, desc, upb_json_printer_input(printer), 0, RTEST(emit_defaults));
1356
+
1357
+ ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
1358
+
1359
+ stackenv_uninit(&se);
1360
+ stringsink_uninit(&sink);
1361
+
1362
+ return ret;
1363
+ }
1364
+ }
1365
+
1366
+ static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
1367
+ MessageHeader* msg;
1368
+ upb_msg_field_iter it;
1369
+
1370
+ TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1371
+
1372
+ stringsink* unknown = msg->unknown_fields;
1373
+ if (unknown != NULL) {
1374
+ stringsink_uninit(unknown);
1375
+ msg->unknown_fields = NULL;
1376
+ }
1377
+
1378
+ for (upb_msg_field_begin(&it, desc->msgdef);
1379
+ !upb_msg_field_done(&it);
1380
+ upb_msg_field_next(&it)) {
1381
+ upb_fielddef *f = upb_msg_iter_field(&it);
1382
+ uint32_t offset =
1383
+ desc->layout->fields[upb_fielddef_index(f)].offset +
1384
+ sizeof(MessageHeader);
1385
+
1386
+ if (upb_fielddef_containingoneof(f)) {
1387
+ uint32_t oneof_case_offset =
1388
+ desc->layout->fields[upb_fielddef_index(f)].case_offset +
1389
+ sizeof(MessageHeader);
1390
+ // For a oneof, check that this field is actually present -- skip all the
1391
+ // below if not.
1392
+ if (DEREF(msg, oneof_case_offset, uint32_t) !=
1393
+ upb_fielddef_number(f)) {
1394
+ continue;
1395
+ }
1396
+ // Otherwise, fall through to the appropriate singular-field handler
1397
+ // below.
1398
+ }
1399
+
1400
+ if (!upb_fielddef_issubmsg(f)) {
1401
+ continue;
1402
+ }
1403
+
1404
+ if (is_map_field(f)) {
1405
+ if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
1406
+ VALUE map = DEREF(msg, offset, VALUE);
1407
+ if (map == Qnil) continue;
1408
+ Map_iter map_it;
1409
+ for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
1410
+ VALUE submsg = Map_iter_value(&map_it);
1411
+ VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1412
+ const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1413
+ discard_unknown(submsg, subdesc);
1414
+ }
1415
+ } else if (upb_fielddef_isseq(f)) {
1416
+ VALUE ary = DEREF(msg, offset, VALUE);
1417
+ if (ary == Qnil) continue;
1418
+ int size = NUM2INT(RepeatedField_length(ary));
1419
+ for (int i = 0; i < size; i++) {
1420
+ void* memory = RepeatedField_index_native(ary, i);
1421
+ VALUE submsg = *((VALUE *)memory);
1422
+ VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1423
+ const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1424
+ discard_unknown(submsg, subdesc);
1425
+ }
1426
+ } else {
1427
+ VALUE submsg = DEREF(msg, offset, VALUE);
1428
+ if (submsg == Qnil) continue;
1429
+ VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1430
+ const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1431
+ discard_unknown(submsg, subdesc);
1432
+ }
1433
+ }
1434
+ }
1435
+
1436
+ /*
1437
+ * call-seq:
1438
+ * Google::Protobuf.discard_unknown(msg)
1439
+ *
1440
+ * Discard unknown fields in the given message object and recursively discard
1441
+ * unknown fields in submessages.
1442
+ */
1443
+ VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
1444
+ VALUE klass = CLASS_OF(msg_rb);
1445
+ VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1446
+ Descriptor* desc = ruby_to_Descriptor(descriptor);
1447
+ if (klass == cRepeatedField || klass == cMap) {
1448
+ rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
1449
+ } else {
1450
+ discard_unknown(msg_rb, desc);
1451
+ }
1452
+ return Qnil;
1453
+ }