1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2014 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
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
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.
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.
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) {
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);
47 // The code below also comes from upb's prototype Ruby binding, developed by
50 /* stringsink *****************************************************************/
52 static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
53 stringsink *sink = _sink;
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;
66 while (sink->len + len > new_size) {
70 if (new_size != sink->size) {
71 sink->ptr = realloc(sink->ptr, new_size);
72 sink->size = new_size;
75 memcpy(sink->ptr + sink->len, ptr, len);
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);
86 upb_bytessink_reset(&sink->sink, &sink->handler, sink);
89 sink->ptr = malloc(sink->size);
93 void stringsink_uninit(stringsink *sink) {
97 // -----------------------------------------------------------------------------
99 // -----------------------------------------------------------------------------
101 #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
106 } field_handlerdata_t;
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);
113 upb_handlers_addcleanup(h, hd, xfree);
120 const upb_msgdef *md;
121 } submsg_handlerdata_t;
123 // Creates a handlerdata that contains offset and submessage type information.
124 static const void *newsubmsghandlerdata(upb_handlers* h,
127 const upb_fielddef* f) {
128 submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
131 hd->md = upb_fielddef_msgsubdef(f);
132 upb_handlers_addcleanup(h, hd, xfree);
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;
143 static const void *newoneofhandlerdata(upb_handlers *h,
146 const upb_fielddef *f) {
147 oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
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);
162 upb_handlers_addcleanup(h, hd, xfree);
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);
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, \
178 VALUE ary = (VALUE)closure; \
179 RepeatedField_push_native(ary, &val); \
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)
191 // Appends a string to a repeated field.
192 static void* appendstr_handler(void *closure,
195 VALUE ary = (VALUE)closure;
196 VALUE str = rb_str_new2("");
197 rb_enc_associate(str, kRubyStringUtf8Encoding);
198 RepeatedField_push_native(ary, &str);
202 static void set_hasbit(void *closure, int32_t hasbit) {
204 uint8_t* storage = closure;
205 storage[hasbit/8] |= 1 << (hasbit % 8);
209 // Appends a 'bytes' string to a repeated field.
210 static void* appendbytes_handler(void *closure,
213 VALUE ary = (VALUE)closure;
214 VALUE str = rb_str_new2("");
215 rb_enc_associate(str, kRubyString8bitEncoding);
216 RepeatedField_push_native(ary, &str);
220 // Sets a non-repeated string field in a message.
221 static void* str_handler(void *closure,
224 MessageHeader* msg = closure;
225 const field_handlerdata_t *fieldhandler = hd;
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);
234 // Sets a non-repeated 'bytes' field in a message.
235 static void* bytes_handler(void *closure,
238 MessageHeader* msg = closure;
239 const field_handlerdata_t *fieldhandler = hd;
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);
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);
256 static bool stringdata_end_handler(void* closure, const void* hd) {
257 VALUE rb_str = closure;
258 rb_obj_freeze(rb_str);
262 static bool appendstring_end_handler(void* closure, const void* hd) {
263 VALUE rb_str = closure;
264 rb_obj_freeze(rb_str);
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;
273 get_def_obj((void*)submsgdata->md);
274 VALUE subklass = Descriptor_msgclass(subdesc);
275 MessageHeader* submsg;
277 VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
278 RepeatedField_push(ary, submsg_rb);
280 TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
284 // Sets a non-repeated submessage field in a message.
285 static void *submsg_handler(void *closure, const void *hd) {
286 MessageHeader* msg = closure;
287 const submsg_handlerdata_t* submsgdata = hd;
289 get_def_obj((void*)submsgdata->md);
290 VALUE subklass = Descriptor_msgclass(subdesc);
292 MessageHeader* submsg;
294 if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
295 DEREF(msg, submsgdata->ofs, VALUE) =
296 rb_class_new_instance(0, NULL, subklass);
299 set_hasbit(closure, submsgdata->hasbit);
301 submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
302 TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
307 // Handler data for startmap/endmap handlers.
310 upb_fieldtype_t key_field_type;
311 upb_fieldtype_t value_field_type;
313 // We know that we can hold this reference because the handlerdata has the
314 // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
315 // a reference to the upb_msgdef, which in turn has references to its subdefs.
316 const upb_def* value_field_subdef;
319 // Temporary frame for map parsing: at the beginning of a map entry message, a
320 // submsg handler allocates a frame to hold (i) a reference to the Map object
321 // into which this message will be inserted and (ii) storage slots to
322 // temporarily hold the key and value for this map entry until the end of the
323 // submessage. When the submessage ends, another handler is called to insert the
324 // value into the map.
327 const map_handlerdata_t* handlerdata;
328 char key_storage[NATIVE_SLOT_MAX_SIZE];
329 char value_storage[NATIVE_SLOT_MAX_SIZE];
332 static void MapParseFrame_mark(void* _self) {
333 map_parse_frame_t* frame = _self;
335 // This shouldn't strictly be necessary since this should be rooted by the
336 // message itself, but it can't hurt.
337 rb_gc_mark(frame->map);
339 native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
340 native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
343 void MapParseFrame_free(void* self) {
347 rb_data_type_t MapParseFrame_type = {
349 { MapParseFrame_mark, MapParseFrame_free, NULL },
352 static map_parse_frame_t* map_push_frame(VALUE map,
353 const map_handlerdata_t* handlerdata) {
354 map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
355 frame->handlerdata = handlerdata;
357 native_slot_init(handlerdata->key_field_type, &frame->key_storage);
358 native_slot_init(handlerdata->value_field_type, &frame->value_storage);
361 TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
366 // Handler to begin a map entry: allocates a temporary frame. This is the
367 // 'startsubmsg' handler on the msgdef that contains the map field.
368 static void *startmapentry_handler(void *closure, const void *hd) {
369 MessageHeader* msg = closure;
370 const map_handlerdata_t* mapdata = hd;
371 VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
373 return map_push_frame(map_rb, mapdata);
376 // Handler to end a map entry: inserts the value defined during the message into
377 // the map. This is the 'endmsg' handler on the map entry msgdef.
378 static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
379 map_parse_frame_t* frame = closure;
380 const map_handlerdata_t* mapdata = hd;
382 VALUE key = native_slot_get(
383 mapdata->key_field_type, Qnil,
384 &frame->key_storage);
386 VALUE value_field_typeclass = Qnil;
389 if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
390 mapdata->value_field_type == UPB_TYPE_ENUM) {
391 value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
394 value = native_slot_get(
395 mapdata->value_field_type, value_field_typeclass,
396 &frame->value_storage);
398 Map_index_set(frame->map, key, value);
399 Map_set_frame(frame->map, Qnil);
404 // Allocates a new map_handlerdata_t given the map entry message definition. If
405 // the offset of the field within the parent message is also given, that is
406 // added to the handler data as well. Note that this is called *twice* per map
407 // field: once in the parent message handler setup when setting the startsubmsg
408 // handler and once in the map entry message handler setup when setting the
409 // key/value and endmsg handlers. The reason is that there is no easy way to
410 // pass the handlerdata down to the sub-message handler setup.
411 static map_handlerdata_t* new_map_handlerdata(
413 const upb_msgdef* mapentry_def,
415 const upb_fielddef* key_field;
416 const upb_fielddef* value_field;
417 map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
419 key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
420 assert(key_field != NULL);
421 hd->key_field_type = upb_fielddef_type(key_field);
422 value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
423 assert(value_field != NULL);
424 hd->value_field_type = upb_fielddef_type(value_field);
425 hd->value_field_subdef = upb_fielddef_subdef(value_field);
430 // Handlers that set primitive values in oneofs.
431 #define DEFINE_ONEOF_HANDLER(type, ctype) \
432 static bool oneof##type##_handler(void *closure, const void *hd, \
434 const oneof_handlerdata_t *oneofdata = hd; \
435 DEREF(closure, oneofdata->case_ofs, uint32_t) = \
436 oneofdata->oneof_case_num; \
437 DEREF(closure, oneofdata->ofs, ctype) = val; \
441 DEFINE_ONEOF_HANDLER(bool, bool)
442 DEFINE_ONEOF_HANDLER(int32, int32_t)
443 DEFINE_ONEOF_HANDLER(uint32, uint32_t)
444 DEFINE_ONEOF_HANDLER(float, float)
445 DEFINE_ONEOF_HANDLER(int64, int64_t)
446 DEFINE_ONEOF_HANDLER(uint64, uint64_t)
447 DEFINE_ONEOF_HANDLER(double, double)
449 #undef DEFINE_ONEOF_HANDLER
451 // Handlers for strings in a oneof.
452 static void *oneofstr_handler(void *closure,
455 MessageHeader* msg = closure;
456 const oneof_handlerdata_t *oneofdata = hd;
457 VALUE str = rb_str_new2("");
458 rb_enc_associate(str, kRubyStringUtf8Encoding);
459 DEREF(msg, oneofdata->case_ofs, uint32_t) =
460 oneofdata->oneof_case_num;
461 DEREF(msg, oneofdata->ofs, VALUE) = str;
465 static void *oneofbytes_handler(void *closure,
468 MessageHeader* msg = closure;
469 const oneof_handlerdata_t *oneofdata = hd;
470 VALUE str = rb_str_new2("");
471 rb_enc_associate(str, kRubyString8bitEncoding);
472 DEREF(msg, oneofdata->case_ofs, uint32_t) =
473 oneofdata->oneof_case_num;
474 DEREF(msg, oneofdata->ofs, VALUE) = str;
478 static bool oneofstring_end_handler(void* closure, const void* hd) {
479 VALUE rb_str = rb_str_new2("");
480 rb_obj_freeze(rb_str);
484 // Handler for a submessage field in a oneof.
485 static void *oneofsubmsg_handler(void *closure,
487 MessageHeader* msg = closure;
488 const oneof_handlerdata_t *oneofdata = hd;
489 uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
492 get_def_obj((void*)oneofdata->md);
493 VALUE subklass = Descriptor_msgclass(subdesc);
495 MessageHeader* submsg;
497 if (oldcase != oneofdata->oneof_case_num ||
498 DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
499 DEREF(msg, oneofdata->ofs, VALUE) =
500 rb_class_new_instance(0, NULL, subklass);
502 // Set the oneof case *after* allocating the new class instance -- otherwise,
503 // if the Ruby GC is invoked as part of a call into the VM, it might invoke
504 // our mark routines, and our mark routines might see the case value
505 // indicating a VALUE is present and expect a valid VALUE. See comment in
506 // layout_set() for more detail: basically, the change to the value and the
507 // case must be atomic w.r.t. the Ruby VM.
508 DEREF(msg, oneofdata->case_ofs, uint32_t) =
509 oneofdata->oneof_case_num;
511 submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
512 TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
516 // Set up handlers for a repeated field.
517 static void add_handlers_for_repeated_field(upb_handlers *h,
518 const upb_fielddef *f,
520 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
521 upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, -1));
522 upb_handlers_setstartseq(h, f, startseq_handler, &attr);
523 upb_handlerattr_uninit(&attr);
525 switch (upb_fielddef_type(f)) {
527 #define SET_HANDLER(utype, ltype) \
529 upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
532 SET_HANDLER(UPB_TYPE_BOOL, bool);
533 SET_HANDLER(UPB_TYPE_INT32, int32);
534 SET_HANDLER(UPB_TYPE_UINT32, uint32);
535 SET_HANDLER(UPB_TYPE_ENUM, int32);
536 SET_HANDLER(UPB_TYPE_FLOAT, float);
537 SET_HANDLER(UPB_TYPE_INT64, int64);
538 SET_HANDLER(UPB_TYPE_UINT64, uint64);
539 SET_HANDLER(UPB_TYPE_DOUBLE, double);
543 case UPB_TYPE_STRING:
544 case UPB_TYPE_BYTES: {
545 bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
546 upb_handlers_setstartstr(h, f, is_bytes ?
547 appendbytes_handler : appendstr_handler,
549 upb_handlers_setstring(h, f, stringdata_handler, NULL);
550 upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
553 case UPB_TYPE_MESSAGE: {
554 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
555 upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, -1, f));
556 upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
557 upb_handlerattr_uninit(&attr);
563 // Set up handlers for a singular field.
564 static void add_handlers_for_singular_field(upb_handlers *h,
565 const upb_fielddef *f,
568 // The offset we pass to UPB points to the start of the Message,
569 // rather than the start of where our data is stored.
571 if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
572 hasbit = hasbit_off + sizeof(MessageHeader) * 8;
575 switch (upb_fielddef_type(f)) {
578 case UPB_TYPE_UINT32:
582 case UPB_TYPE_UINT64:
583 case UPB_TYPE_DOUBLE:
584 upb_msg_setscalarhandler(h, f, offset, hasbit);
586 case UPB_TYPE_STRING:
587 case UPB_TYPE_BYTES: {
588 bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
589 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
590 upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, hasbit));
591 upb_handlers_setstartstr(h, f,
592 is_bytes ? bytes_handler : str_handler,
594 upb_handlers_setstring(h, f, stringdata_handler, &attr);
595 upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
596 upb_handlerattr_uninit(&attr);
599 case UPB_TYPE_MESSAGE: {
600 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
601 upb_handlerattr_sethandlerdata(&attr,
602 newsubmsghandlerdata(h, offset,
604 upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
605 upb_handlerattr_uninit(&attr);
611 // Adds handlers to a map field.
612 static void add_handlers_for_mapfield(upb_handlers* h,
613 const upb_fielddef* fielddef,
616 const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
617 map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
618 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
620 upb_handlers_addcleanup(h, hd, xfree);
621 upb_handlerattr_sethandlerdata(&attr, hd);
622 upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
623 upb_handlerattr_uninit(&attr);
626 // Adds handlers to a map-entry msgdef.
627 static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
630 const upb_fielddef* key_field = map_entry_key(msgdef);
631 const upb_fielddef* value_field = map_entry_value(msgdef);
632 map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
633 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
635 upb_handlers_addcleanup(h, hd, xfree);
636 upb_handlerattr_sethandlerdata(&attr, hd);
637 upb_handlers_setendmsg(h, endmap_handler, &attr);
639 add_handlers_for_singular_field(
641 offsetof(map_parse_frame_t, key_storage),
642 MESSAGE_FIELD_NO_HASBIT);
643 add_handlers_for_singular_field(
645 offsetof(map_parse_frame_t, value_storage),
646 MESSAGE_FIELD_NO_HASBIT);
649 // Set up handlers for a oneof field.
650 static void add_handlers_for_oneof_field(upb_handlers *h,
651 const upb_fielddef *f,
653 size_t oneof_case_offset) {
655 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
656 upb_handlerattr_sethandlerdata(
657 &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
659 switch (upb_fielddef_type(f)) {
661 #define SET_HANDLER(utype, ltype) \
663 upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
666 SET_HANDLER(UPB_TYPE_BOOL, bool);
667 SET_HANDLER(UPB_TYPE_INT32, int32);
668 SET_HANDLER(UPB_TYPE_UINT32, uint32);
669 SET_HANDLER(UPB_TYPE_ENUM, int32);
670 SET_HANDLER(UPB_TYPE_FLOAT, float);
671 SET_HANDLER(UPB_TYPE_INT64, int64);
672 SET_HANDLER(UPB_TYPE_UINT64, uint64);
673 SET_HANDLER(UPB_TYPE_DOUBLE, double);
677 case UPB_TYPE_STRING:
678 case UPB_TYPE_BYTES: {
679 bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
680 upb_handlers_setstartstr(h, f, is_bytes ?
681 oneofbytes_handler : oneofstr_handler,
683 upb_handlers_setstring(h, f, stringdata_handler, NULL);
684 upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
687 case UPB_TYPE_MESSAGE: {
688 upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
693 upb_handlerattr_uninit(&attr);
696 static bool unknown_field_handler(void* closure, const void* hd,
697 const char* buf, size_t size) {
700 MessageHeader* msg = (MessageHeader*)closure;
701 if (msg->unknown_fields == NULL) {
702 msg->unknown_fields = malloc(sizeof(stringsink));
703 stringsink_init(msg->unknown_fields);
706 stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
711 static void add_handlers_for_message(const void *closure, upb_handlers *h) {
712 const upb_msgdef* msgdef = upb_handlers_msgdef(h);
713 Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
714 upb_msg_field_iter i;
716 // If this is a mapentry message type, set up a special set of handlers and
717 // bail out of the normal (user-defined) message type handling.
718 if (upb_msgdef_mapentry(msgdef)) {
719 add_handlers_for_mapentry(msgdef, h, desc);
723 // Ensure layout exists. We may be invoked to create handlers for a given
724 // message if we are included as a submsg of another message type before our
725 // class is actually built, so to work around this, we just create the layout
726 // (and handlers, in the class-building function) on-demand.
727 if (desc->layout == NULL) {
728 desc->layout = create_layout(desc->msgdef);
731 upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
732 upb_handlers_setunknown(h, unknown_field_handler, &attr);
734 for (upb_msg_field_begin(&i, desc->msgdef);
735 !upb_msg_field_done(&i);
736 upb_msg_field_next(&i)) {
737 const upb_fielddef *f = upb_msg_iter_field(&i);
738 size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
739 sizeof(MessageHeader);
741 if (upb_fielddef_containingoneof(f)) {
742 size_t oneof_case_offset =
743 desc->layout->fields[upb_fielddef_index(f)].case_offset +
744 sizeof(MessageHeader);
745 add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
746 } else if (is_map_field(f)) {
747 add_handlers_for_mapfield(h, f, offset, desc);
748 } else if (upb_fielddef_isseq(f)) {
749 add_handlers_for_repeated_field(h, f, offset);
751 add_handlers_for_singular_field(
752 h, f, offset, desc->layout->fields[upb_fielddef_index(f)].hasbit);
757 // Creates upb handlers for populating a message.
758 static const upb_handlers *new_fill_handlers(Descriptor* desc,
760 // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
761 // handlers, reuse subdef handlers so that e.g. if we already parse
762 // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
763 // parse A-with-field-of-type-B-with-field-of-type-C.
764 return upb_handlers_newfrozen(desc->msgdef, owner,
765 add_handlers_for_message, NULL);
768 // Constructs the handlers for filling a message's data into an in-memory
770 const upb_handlers* get_fill_handlers(Descriptor* desc) {
771 if (!desc->fill_handlers) {
772 desc->fill_handlers =
773 new_fill_handlers(desc, &desc->fill_handlers);
775 return desc->fill_handlers;
778 // Constructs the upb decoder method for parsing messages of this type.
779 // This is called from the message class creation code.
780 const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
782 const upb_handlers* handlers = get_fill_handlers(desc);
783 upb_pbdecodermethodopts opts;
784 upb_pbdecodermethodopts_init(&opts, handlers);
786 return upb_pbdecodermethod_new(&opts, owner);
789 static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
790 if (desc->fill_method == NULL) {
791 desc->fill_method = new_fillmsg_decodermethod(
792 desc, &desc->fill_method);
794 return desc->fill_method;
797 static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
798 if (desc->json_fill_method == NULL) {
799 desc->json_fill_method =
800 upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
802 return desc->json_fill_method;
806 // Stack-allocated context during an encode/decode operation. Contains the upb
807 // environment and its stack-based allocator, an initial buffer for allocations
808 // to avoid malloc() when possible, and a template for Ruby exception messages
809 // if any error occurs.
810 #define STACK_ENV_STACKBYTES 4096
813 const char* ruby_error_template;
814 char allocbuf[STACK_ENV_STACKBYTES];
817 static void stackenv_init(stackenv* se, const char* errmsg);
818 static void stackenv_uninit(stackenv* se);
820 // Callback invoked by upb if any error occurs during parsing or serialization.
821 static bool env_error_func(void* ud, const upb_status* status) {
823 // Free the env -- rb_raise will longjmp up the stack past the encode/decode
824 // function so it would not otherwise have been freed.
827 // TODO(haberman): have a way to verify that this is actually a parse error,
828 // instead of just throwing "parse error" unconditionally.
829 rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
830 // Never reached: rb_raise() always longjmp()s up the stack, past all of our
831 // code, back to Ruby.
835 static void stackenv_init(stackenv* se, const char* errmsg) {
836 se->ruby_error_template = errmsg;
837 upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
838 upb_env_seterrorfunc(&se->env, env_error_func, se);
841 static void stackenv_uninit(stackenv* se) {
842 upb_env_uninit(&se->env);
847 * MessageClass.decode(data) => message
849 * Decodes the given data (as a string containing bytes in protocol buffers wire
850 * format) under the interpretration given by this message class's definition
851 * and returns a message object with the corresponding field values.
853 VALUE Message_decode(VALUE klass, VALUE data) {
854 VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
855 Descriptor* desc = ruby_to_Descriptor(descriptor);
856 VALUE msgklass = Descriptor_msgclass(descriptor);
860 if (TYPE(data) != T_STRING) {
861 rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
864 msg_rb = rb_class_new_instance(0, NULL, msgklass);
865 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
868 const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
869 const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
872 upb_pbdecoder* decoder;
873 stackenv_init(&se, "Error occurred during parsing: %s");
875 upb_sink_reset(&sink, h, msg);
876 decoder = upb_pbdecoder_create(&se.env, method, &sink);
877 upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
878 upb_pbdecoder_input(decoder));
880 stackenv_uninit(&se);
888 * MessageClass.decode_json(data, options = {}) => message
890 * Decodes the given data (as a string containing bytes in protocol buffers wire
891 * format) under the interpretration given by this message class's definition
892 * and returns a message object with the corresponding field values.
894 * @param options [Hash] options for the decoder
895 * ignore_unknown_fields: set true to ignore unknown fields (default is to raise an error)
897 VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
898 VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
899 Descriptor* desc = ruby_to_Descriptor(descriptor);
900 VALUE msgklass = Descriptor_msgclass(descriptor);
902 VALUE data = argv[0];
903 VALUE ignore_unknown_fields = Qfalse;
906 if (argc < 1 || argc > 2) {
907 rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
911 VALUE hash_args = argv[1];
912 if (TYPE(hash_args) != T_HASH) {
913 rb_raise(rb_eArgError, "Expected hash arguments.");
916 ignore_unknown_fields = rb_hash_lookup2(
917 hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse);
920 if (TYPE(data) != T_STRING) {
921 rb_raise(rb_eArgError, "Expected string for JSON data.");
923 // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
924 // convert, because string handlers pass data directly to message string
927 msg_rb = rb_class_new_instance(0, NULL, msgklass);
928 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
931 const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
934 upb_json_parser* parser;
935 DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
936 stackenv_init(&se, "Error occurred during parsing: %s");
938 upb_sink_reset(&sink, get_fill_handlers(desc), msg);
939 parser = upb_json_parser_create(&se.env, method, pool->symtab,
940 &sink, ignore_unknown_fields);
941 upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
942 upb_json_parser_input(parser));
944 stackenv_uninit(&se);
950 // -----------------------------------------------------------------------------
952 // -----------------------------------------------------------------------------
954 /* msgvisitor *****************************************************************/
956 static void putmsg(VALUE msg, const Descriptor* desc,
957 upb_sink *sink, int depth, bool emit_defaults,
958 bool is_json, bool open_msg);
960 static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
962 bool ok = upb_handlers_getselector(f, type, &ret);
967 static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
970 if (str == Qnil) return;
972 assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
974 // We should be guaranteed that the string has the correct encoding because
975 // we ensured this at assignment time and then froze the string.
976 if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
977 assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
979 assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
982 upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
984 upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
985 RSTRING_LEN(str), NULL);
986 upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
989 static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
990 int depth, bool emit_defaults, bool is_json) {
995 if (submsg == Qnil) return;
997 descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
998 subdesc = ruby_to_Descriptor(descriptor);
1000 upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
1001 putmsg(submsg, subdesc, &subsink, depth + 1, emit_defaults, is_json, true);
1002 upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1005 static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
1006 int depth, bool emit_defaults, bool is_json) {
1008 upb_fieldtype_t type = upb_fielddef_type(f);
1009 upb_selector_t sel = 0;
1012 if (ary == Qnil) return;
1013 if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
1015 size = NUM2INT(RepeatedField_length(ary));
1016 if (size == 0 && !emit_defaults) return;
1018 upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1020 if (upb_fielddef_isprimitive(f)) {
1021 sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1024 for (int i = 0; i < size; i++) {
1025 void* memory = RepeatedField_index_native(ary, i);
1027 #define T(upbtypeconst, upbtype, ctype) \
1028 case upbtypeconst: \
1029 upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
1032 T(UPB_TYPE_FLOAT, float, float)
1033 T(UPB_TYPE_DOUBLE, double, double)
1034 T(UPB_TYPE_BOOL, bool, int8_t)
1036 T(UPB_TYPE_INT32, int32, int32_t)
1037 T(UPB_TYPE_UINT32, uint32, uint32_t)
1038 T(UPB_TYPE_INT64, int64, int64_t)
1039 T(UPB_TYPE_UINT64, uint64, uint64_t)
1041 case UPB_TYPE_STRING:
1042 case UPB_TYPE_BYTES:
1043 putstr(*((VALUE *)memory), f, &subsink);
1045 case UPB_TYPE_MESSAGE:
1046 putsubmsg(*((VALUE *)memory), f, &subsink, depth,
1047 emit_defaults, is_json);
1054 upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1057 static void put_ruby_value(VALUE value,
1058 const upb_fielddef *f,
1064 if (depth > ENCODE_MAX_NESTING) {
1065 rb_raise(rb_eRuntimeError,
1066 "Maximum recursion depth exceeded during encoding.");
1069 upb_selector_t sel = 0;
1070 if (upb_fielddef_isprimitive(f)) {
1071 sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1074 switch (upb_fielddef_type(f)) {
1075 case UPB_TYPE_INT32:
1076 upb_sink_putint32(sink, sel, NUM2INT(value));
1078 case UPB_TYPE_INT64:
1079 upb_sink_putint64(sink, sel, NUM2LL(value));
1081 case UPB_TYPE_UINT32:
1082 upb_sink_putuint32(sink, sel, NUM2UINT(value));
1084 case UPB_TYPE_UINT64:
1085 upb_sink_putuint64(sink, sel, NUM2ULL(value));
1087 case UPB_TYPE_FLOAT:
1088 upb_sink_putfloat(sink, sel, NUM2DBL(value));
1090 case UPB_TYPE_DOUBLE:
1091 upb_sink_putdouble(sink, sel, NUM2DBL(value));
1093 case UPB_TYPE_ENUM: {
1094 if (TYPE(value) == T_SYMBOL) {
1095 value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
1097 upb_sink_putint32(sink, sel, NUM2INT(value));
1101 upb_sink_putbool(sink, sel, value == Qtrue);
1103 case UPB_TYPE_STRING:
1104 case UPB_TYPE_BYTES:
1105 putstr(value, f, sink);
1107 case UPB_TYPE_MESSAGE:
1108 putsubmsg(value, f, sink, depth, emit_defaults, is_json);
1112 static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
1113 int depth, bool emit_defaults, bool is_json) {
1116 const upb_fielddef* key_field;
1117 const upb_fielddef* value_field;
1120 if (map == Qnil) return;
1121 if (!emit_defaults && Map_length(map) == 0) return;
1123 self = ruby_to_Map(map);
1125 upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1127 assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
1128 key_field = map_field_key(f);
1129 value_field = map_field_value(f);
1131 for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
1132 VALUE key = Map_iter_key(&it);
1133 VALUE value = Map_iter_value(&it);
1136 upb_sink entry_sink;
1137 upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
1139 upb_sink_startmsg(&entry_sink);
1141 put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink,
1142 emit_defaults, is_json);
1143 put_ruby_value(value, value_field, self->value_type_class, depth + 1,
1144 &entry_sink, emit_defaults, is_json);
1146 upb_sink_endmsg(&entry_sink, &status);
1147 upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1150 upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1153 static const upb_handlers* msgdef_json_serialize_handlers(
1154 Descriptor* desc, bool preserve_proto_fieldnames);
1156 static void putjsonany(VALUE msg_rb, const Descriptor* desc,
1157 upb_sink* sink, int depth, bool emit_defaults) {
1159 MessageHeader* msg = NULL;
1160 const upb_fielddef* type_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_TYPE);
1161 const upb_fielddef* value_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_VALUE);
1163 size_t type_url_offset;
1164 VALUE type_url_str_rb;
1165 const upb_msgdef *payload_type = NULL;
1167 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1169 upb_sink_startmsg(sink);
1171 /* Handle type url */
1172 type_url_offset = desc->layout->fields[upb_fielddef_index(type_field)].offset;
1173 type_url_str_rb = DEREF(Message_data(msg), type_url_offset, VALUE);
1174 if (RSTRING_LEN(type_url_str_rb) > 0) {
1175 putstr(type_url_str_rb, type_field, sink);
1179 const char* type_url_str = RSTRING_PTR(type_url_str_rb);
1180 size_t type_url_len = RSTRING_LEN(type_url_str_rb);
1181 DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
1183 if (type_url_len <= 20 ||
1184 strncmp(type_url_str, "type.googleapis.com/", 20) != 0) {
1185 rb_raise(rb_eRuntimeError, "Invalid type url: %s", type_url_str);
1189 /* Resolve type url */
1193 payload_type = upb_symtab_lookupmsg2(
1194 pool->symtab, type_url_str, type_url_len);
1195 if (payload_type == NULL) {
1196 rb_raise(rb_eRuntimeError, "Unknown type: %s", type_url_str);
1202 uint32_t value_offset;
1204 const char* value_str;
1207 value_offset = desc->layout->fields[upb_fielddef_index(value_field)].offset;
1208 value_str_rb = DEREF(Message_data(msg), value_offset, VALUE);
1209 value_str = RSTRING_PTR(value_str_rb);
1210 value_len = RSTRING_LEN(value_str_rb);
1212 if (value_len > 0) {
1213 VALUE payload_desc_rb = get_def_obj(payload_type);
1214 Descriptor* payload_desc = ruby_to_Descriptor(payload_desc_rb);
1215 VALUE payload_class = Descriptor_msgclass(payload_desc_rb);
1219 VALUE payload_msg_rb = Message_decode(payload_class, value_str_rb);
1222 upb_msgdef_wellknowntype(payload_desc->msgdef) !=
1223 UPB_WELLKNOWN_UNSPECIFIED;
1225 upb_sink_startstr(sink, getsel(value_field, UPB_HANDLER_STARTSTR), 0,
1230 msgdef_json_serialize_handlers(payload_desc, true);
1231 subsink.closure = sink->closure;
1232 putmsg(payload_msg_rb, payload_desc, &subsink, depth, emit_defaults, true,
1237 upb_sink_endmsg(sink, &status);
1240 static void putjsonlistvalue(
1241 VALUE msg_rb, const Descriptor* desc,
1242 upb_sink* sink, int depth, bool emit_defaults) {
1245 MessageHeader* msg = NULL;
1246 const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
1248 desc->layout->fields[upb_fielddef_index(f)].offset +
1249 sizeof(MessageHeader);
1252 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1254 upb_sink_startmsg(sink);
1256 ary = DEREF(msg, offset, VALUE);
1258 if (ary == Qnil || RepeatedField_size(ary) == 0) {
1259 upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1260 upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1262 putary(ary, f, sink, depth, emit_defaults, true);
1265 upb_sink_endmsg(sink, &status);
1268 static void putmsg(VALUE msg_rb, const Descriptor* desc,
1269 upb_sink *sink, int depth, bool emit_defaults,
1270 bool is_json, bool open_msg) {
1272 upb_msg_field_iter i;
1276 upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
1277 putjsonany(msg_rb, desc, sink, depth, emit_defaults);
1282 upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_LISTVALUE) {
1283 putjsonlistvalue(msg_rb, desc, sink, depth, emit_defaults);
1288 upb_sink_startmsg(sink);
1291 // Protect against cycles (possible because users may freely reassign message
1292 // and repeated fields) by imposing a maximum recursion depth.
1293 if (depth > ENCODE_MAX_NESTING) {
1294 rb_raise(rb_eRuntimeError,
1295 "Maximum recursion depth exceeded during encoding.");
1298 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1300 if (desc != msg->descriptor) {
1301 rb_raise(rb_eArgError,
1302 "The type of given msg is '%s', expect '%s'.",
1303 upb_msgdef_fullname(msg->descriptor->msgdef),
1304 upb_msgdef_fullname(desc->msgdef));
1307 for (upb_msg_field_begin(&i, desc->msgdef);
1308 !upb_msg_field_done(&i);
1309 upb_msg_field_next(&i)) {
1310 upb_fielddef *f = upb_msg_iter_field(&i);
1311 bool is_matching_oneof = false;
1313 desc->layout->fields[upb_fielddef_index(f)].offset +
1314 sizeof(MessageHeader);
1316 if (upb_fielddef_containingoneof(f)) {
1317 uint32_t oneof_case_offset =
1318 desc->layout->fields[upb_fielddef_index(f)].case_offset +
1319 sizeof(MessageHeader);
1320 // For a oneof, check that this field is actually present -- skip all the
1322 if (DEREF(msg, oneof_case_offset, uint32_t) !=
1323 upb_fielddef_number(f)) {
1326 // Otherwise, fall through to the appropriate singular-field handler
1328 is_matching_oneof = true;
1331 if (is_map_field(f)) {
1332 VALUE map = DEREF(msg, offset, VALUE);
1333 if (map != Qnil || emit_defaults) {
1334 putmap(map, f, sink, depth, emit_defaults, is_json);
1336 } else if (upb_fielddef_isseq(f)) {
1337 VALUE ary = DEREF(msg, offset, VALUE);
1339 putary(ary, f, sink, depth, emit_defaults, is_json);
1341 } else if (upb_fielddef_isstring(f)) {
1342 VALUE str = DEREF(msg, offset, VALUE);
1343 bool is_default = false;
1345 if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
1346 is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
1347 } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
1348 is_default = RSTRING_LEN(str) == 0;
1351 if (is_matching_oneof || emit_defaults || !is_default) {
1352 putstr(str, f, sink);
1354 } else if (upb_fielddef_issubmsg(f)) {
1355 putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth,
1356 emit_defaults, is_json);
1358 upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1360 #define T(upbtypeconst, upbtype, ctype, default_value) \
1361 case upbtypeconst: { \
1362 ctype value = DEREF(msg, offset, ctype); \
1363 bool is_default = false; \
1364 if (upb_fielddef_haspresence(f)) { \
1365 is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse; \
1366 } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) { \
1367 is_default = default_value == value; \
1369 if (is_matching_oneof || emit_defaults || !is_default) { \
1370 upb_sink_put##upbtype(sink, sel, value); \
1375 switch (upb_fielddef_type(f)) {
1376 T(UPB_TYPE_FLOAT, float, float, 0.0)
1377 T(UPB_TYPE_DOUBLE, double, double, 0.0)
1378 T(UPB_TYPE_BOOL, bool, uint8_t, 0)
1380 T(UPB_TYPE_INT32, int32, int32_t, 0)
1381 T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
1382 T(UPB_TYPE_INT64, int64, int64_t, 0)
1383 T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
1385 case UPB_TYPE_STRING:
1386 case UPB_TYPE_BYTES:
1387 case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
1395 stringsink* unknown = msg->unknown_fields;
1396 if (unknown != NULL) {
1397 upb_sink_putunknown(sink, unknown->ptr, unknown->len);
1401 upb_sink_endmsg(sink, &status);
1405 static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
1406 if (desc->pb_serialize_handlers == NULL) {
1407 desc->pb_serialize_handlers =
1408 upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
1410 return desc->pb_serialize_handlers;
1413 static const upb_handlers* msgdef_json_serialize_handlers(
1414 Descriptor* desc, bool preserve_proto_fieldnames) {
1415 if (preserve_proto_fieldnames) {
1416 if (desc->json_serialize_handlers == NULL) {
1417 desc->json_serialize_handlers =
1418 upb_json_printer_newhandlers(
1419 desc->msgdef, true, &desc->json_serialize_handlers);
1421 return desc->json_serialize_handlers;
1423 if (desc->json_serialize_handlers_preserve == NULL) {
1424 desc->json_serialize_handlers_preserve =
1425 upb_json_printer_newhandlers(
1426 desc->msgdef, false, &desc->json_serialize_handlers_preserve);
1428 return desc->json_serialize_handlers_preserve;
1434 * MessageClass.encode(msg) => bytes
1436 * Encodes the given message object to its serialized form in protocol buffers
1439 VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1440 VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1441 Descriptor* desc = ruby_to_Descriptor(descriptor);
1444 stringsink_init(&sink);
1447 const upb_handlers* serialize_handlers =
1448 msgdef_pb_serialize_handlers(desc);
1451 upb_pb_encoder* encoder;
1454 stackenv_init(&se, "Error occurred during encoding: %s");
1455 encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
1457 putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false, false, true);
1459 ret = rb_str_new(sink.ptr, sink.len);
1461 stackenv_uninit(&se);
1462 stringsink_uninit(&sink);
1470 * MessageClass.encode_json(msg, options = {}) => json_string
1472 * Encodes the given message object into its serialized JSON representation.
1473 * @param options [Hash] options for the decoder
1474 * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
1475 * emit_defaults: set true to emit 0/false values (default is to omit them)
1477 VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1478 VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1479 Descriptor* desc = ruby_to_Descriptor(descriptor);
1481 VALUE preserve_proto_fieldnames = Qfalse;
1482 VALUE emit_defaults = Qfalse;
1485 if (argc < 1 || argc > 2) {
1486 rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1492 VALUE hash_args = argv[1];
1493 if (TYPE(hash_args) != T_HASH) {
1494 rb_raise(rb_eArgError, "Expected hash arguments.");
1496 preserve_proto_fieldnames = rb_hash_lookup2(
1497 hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
1499 emit_defaults = rb_hash_lookup2(
1500 hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
1503 stringsink_init(&sink);
1506 const upb_handlers* serialize_handlers =
1507 msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
1508 upb_json_printer* printer;
1512 stackenv_init(&se, "Error occurred during encoding: %s");
1513 printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
1515 putmsg(msg_rb, desc, upb_json_printer_input(printer), 0,
1516 RTEST(emit_defaults), true, true);
1518 ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
1520 stackenv_uninit(&se);
1521 stringsink_uninit(&sink);
1527 static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
1529 upb_msg_field_iter it;
1531 TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1533 stringsink* unknown = msg->unknown_fields;
1534 if (unknown != NULL) {
1535 stringsink_uninit(unknown);
1536 msg->unknown_fields = NULL;
1539 for (upb_msg_field_begin(&it, desc->msgdef);
1540 !upb_msg_field_done(&it);
1541 upb_msg_field_next(&it)) {
1542 upb_fielddef *f = upb_msg_iter_field(&it);
1544 desc->layout->fields[upb_fielddef_index(f)].offset +
1545 sizeof(MessageHeader);
1547 if (upb_fielddef_containingoneof(f)) {
1548 uint32_t oneof_case_offset =
1549 desc->layout->fields[upb_fielddef_index(f)].case_offset +
1550 sizeof(MessageHeader);
1551 // For a oneof, check that this field is actually present -- skip all the
1553 if (DEREF(msg, oneof_case_offset, uint32_t) !=
1554 upb_fielddef_number(f)) {
1557 // Otherwise, fall through to the appropriate singular-field handler
1561 if (!upb_fielddef_issubmsg(f)) {
1565 if (is_map_field(f)) {
1566 if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
1567 VALUE map = DEREF(msg, offset, VALUE);
1568 if (map == Qnil) continue;
1570 for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
1571 VALUE submsg = Map_iter_value(&map_it);
1572 VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1573 const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1574 discard_unknown(submsg, subdesc);
1576 } else if (upb_fielddef_isseq(f)) {
1577 VALUE ary = DEREF(msg, offset, VALUE);
1578 if (ary == Qnil) continue;
1579 int size = NUM2INT(RepeatedField_length(ary));
1580 for (int i = 0; i < size; i++) {
1581 void* memory = RepeatedField_index_native(ary, i);
1582 VALUE submsg = *((VALUE *)memory);
1583 VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1584 const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1585 discard_unknown(submsg, subdesc);
1588 VALUE submsg = DEREF(msg, offset, VALUE);
1589 if (submsg == Qnil) continue;
1590 VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1591 const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1592 discard_unknown(submsg, subdesc);
1599 * Google::Protobuf.discard_unknown(msg)
1601 * Discard unknown fields in the given message object and recursively discard
1602 * unknown fields in submessages.
1604 VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
1605 VALUE klass = CLASS_OF(msg_rb);
1606 VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1607 Descriptor* desc = ruby_to_Descriptor(descriptor);
1608 if (klass == cRepeatedField || klass == cMap) {
1609 rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
1611 discard_unknown(msg_rb, desc);