encode_decode.c 44.3 KB
Newer Older
Chris Fallin's avatar
Chris Fallin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Protocol Buffers - Google's data interchange format
// Copyright 2014 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "protobuf.h"

33 34 35 36 37
// This function is equivalent to rb_str_cat(), but unlike the real
// rb_str_cat(), it doesn't leak memory in some versions of Ruby.
// For more information, see:
//   https://bugs.ruby-lang.org/issues/11328
VALUE noleak_rb_str_cat(VALUE rb_str, const char *str, long len) {
38
  char *p;
39 40
  size_t oldlen = RSTRING_LEN(rb_str);
  rb_str_modify_expand(rb_str, len);
41
  p = RSTRING_PTR(rb_str);
42 43
  memcpy(p + oldlen, str, len);
  rb_str_set_len(rb_str, oldlen + len);
44
  return rb_str;
45 46
}

Chris Fallin's avatar
Chris Fallin committed
47 48 49 50 51 52 53 54 55 56
// -----------------------------------------------------------------------------
// Parsing.
// -----------------------------------------------------------------------------

#define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)

// Creates a handlerdata that simply contains the offset for this field.
static const void* newhandlerdata(upb_handlers* h, uint32_t ofs) {
  size_t* hd_ofs = ALLOC(size_t);
  *hd_ofs = ofs;
57
  upb_handlers_addcleanup(h, hd_ofs, xfree);
Chris Fallin's avatar
Chris Fallin committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71
  return hd_ofs;
}

typedef struct {
  size_t ofs;
  const upb_msgdef *md;
} submsg_handlerdata_t;

// Creates a handlerdata that contains offset and submessage type information.
static const void *newsubmsghandlerdata(upb_handlers* h, uint32_t ofs,
                                        const upb_fielddef* f) {
  submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
  hd->ofs = ofs;
  hd->md = upb_fielddef_msgsubdef(f);
72
  upb_handlers_addcleanup(h, hd, xfree);
Chris Fallin's avatar
Chris Fallin committed
73 74 75
  return hd;
}

76
typedef struct {
77 78 79 80
  size_t ofs;              // union data slot
  size_t case_ofs;         // oneof_case field
  uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
  const upb_msgdef *md;    // msgdef, for oneof submessage handler
81 82 83 84 85 86 87 88 89
} oneof_handlerdata_t;

static const void *newoneofhandlerdata(upb_handlers *h,
                                       uint32_t ofs,
                                       uint32_t case_ofs,
                                       const upb_fielddef *f) {
  oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
  hd->ofs = ofs;
  hd->case_ofs = case_ofs;
90 91 92 93
  // We reuse the field tag number as a oneof union discriminant tag. Note that
  // we don't expose these numbers to the user, so the only requirement is that
  // we have some unique ID for each union case/possibility. The field tag
  // numbers are already present and are easy to use so there's no reason to
94 95
  // create a separate ID space. In addition, using the field tag number here
  // lets us easily look up the field in the oneof accessor.
96
  hd->oneof_case_num = upb_fielddef_number(f);
97 98 99 100 101
  if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
    hd->md = upb_fielddef_msgsubdef(f);
  } else {
    hd->md = NULL;
  }
102
  upb_handlers_addcleanup(h, hd, xfree);
103 104 105
  return hd;
}

Chris Fallin's avatar
Chris Fallin committed
106 107 108 109 110
// A handler that starts a repeated field.  Gets the Repeated*Field instance for
// this field (such an instance always exists even in an empty message).
static void *startseq_handler(void* closure, const void* hd) {
  MessageHeader* msg = closure;
  const size_t *ofs = hd;
111
  return (void*)DEREF(msg, *ofs, VALUE);
Chris Fallin's avatar
Chris Fallin committed
112 113
}

114
// Handlers that append primitive values to a repeated field.
Chris Fallin's avatar
Chris Fallin committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
#define DEFINE_APPEND_HANDLER(type, ctype)                 \
  static bool append##type##_handler(void *closure, const void *hd, \
                                     ctype val) {                   \
    VALUE ary = (VALUE)closure;                                     \
    RepeatedField_push_native(ary, &val);                           \
    return true;                                                    \
  }

DEFINE_APPEND_HANDLER(bool,   bool)
DEFINE_APPEND_HANDLER(int32,  int32_t)
DEFINE_APPEND_HANDLER(uint32, uint32_t)
DEFINE_APPEND_HANDLER(float,  float)
DEFINE_APPEND_HANDLER(int64,  int64_t)
DEFINE_APPEND_HANDLER(uint64, uint64_t)
DEFINE_APPEND_HANDLER(double, double)

131
// Appends a string to a repeated field.
Chris Fallin's avatar
Chris Fallin committed
132 133 134 135 136 137
static void* appendstr_handler(void *closure,
                               const void *hd,
                               size_t size_hint) {
  VALUE ary = (VALUE)closure;
  VALUE str = rb_str_new2("");
  rb_enc_associate(str, kRubyStringUtf8Encoding);
138
  RepeatedField_push_native(ary, &str);
Chris Fallin's avatar
Chris Fallin committed
139 140 141
  return (void*)str;
}

142
// Appends a 'bytes' string to a repeated field.
Chris Fallin's avatar
Chris Fallin committed
143 144 145 146 147 148
static void* appendbytes_handler(void *closure,
                                 const void *hd,
                                 size_t size_hint) {
  VALUE ary = (VALUE)closure;
  VALUE str = rb_str_new2("");
  rb_enc_associate(str, kRubyString8bitEncoding);
149
  RepeatedField_push_native(ary, &str);
Chris Fallin's avatar
Chris Fallin committed
150 151 152 153 154 155 156 157 158 159 160
  return (void*)str;
}

// Sets a non-repeated string field in a message.
static void* str_handler(void *closure,
                         const void *hd,
                         size_t size_hint) {
  MessageHeader* msg = closure;
  const size_t *ofs = hd;
  VALUE str = rb_str_new2("");
  rb_enc_associate(str, kRubyStringUtf8Encoding);
161
  DEREF(msg, *ofs, VALUE) = str;
Chris Fallin's avatar
Chris Fallin committed
162 163 164 165 166 167 168 169 170 171 172
  return (void*)str;
}

// Sets a non-repeated 'bytes' field in a message.
static void* bytes_handler(void *closure,
                           const void *hd,
                           size_t size_hint) {
  MessageHeader* msg = closure;
  const size_t *ofs = hd;
  VALUE str = rb_str_new2("");
  rb_enc_associate(str, kRubyString8bitEncoding);
173
  DEREF(msg, *ofs, VALUE) = str;
Chris Fallin's avatar
Chris Fallin committed
174 175 176 177 178 179 180
  return (void*)str;
}

static size_t stringdata_handler(void* closure, const void* hd,
                                 const char* str, size_t len,
                                 const upb_bufhandle* handle) {
  VALUE rb_str = (VALUE)closure;
181
  noleak_rb_str_cat(rb_str, str, len);
Chris Fallin's avatar
Chris Fallin committed
182 183 184
  return len;
}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
static bool stringdata_end_handler(void* closure, const void* hd) {
  MessageHeader* msg = closure;
  const size_t *ofs = hd;
  VALUE rb_str = DEREF(msg, *ofs, VALUE);
  rb_obj_freeze(rb_str);
  return true;
}

static bool appendstring_end_handler(void* closure, const void* hd) {
  VALUE ary = (VALUE)closure;
  int size = RepeatedField_size(ary);
  VALUE* last = RepeatedField_index_native(ary, size - 1);
  VALUE rb_str = *last;
  rb_obj_freeze(rb_str);
  return true;
}

Chris Fallin's avatar
Chris Fallin committed
202 203 204 205 206 207 208
// Appends a submessage to a repeated field (a regular Ruby array for now).
static void *appendsubmsg_handler(void *closure, const void *hd) {
  VALUE ary = (VALUE)closure;
  const submsg_handlerdata_t *submsgdata = hd;
  VALUE subdesc =
      get_def_obj((void*)submsgdata->md);
  VALUE subklass = Descriptor_msgclass(subdesc);
209
  MessageHeader* submsg;
Chris Fallin's avatar
Chris Fallin committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

  VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
  RepeatedField_push(ary, submsg_rb);

  TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  return submsg;
}

// Sets a non-repeated submessage field in a message.
static void *submsg_handler(void *closure, const void *hd) {
  MessageHeader* msg = closure;
  const submsg_handlerdata_t* submsgdata = hd;
  VALUE subdesc =
      get_def_obj((void*)submsgdata->md);
  VALUE subklass = Descriptor_msgclass(subdesc);
225 226
  VALUE submsg_rb;
  MessageHeader* submsg;
Chris Fallin's avatar
Chris Fallin committed
227

228 229
  if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
    DEREF(msg, submsgdata->ofs, VALUE) =
Chris Fallin's avatar
Chris Fallin committed
230 231 232
        rb_class_new_instance(0, NULL, subklass);
  }

233
  submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
Chris Fallin's avatar
Chris Fallin committed
234 235 236 237
  TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  return submsg;
}

238 239 240
// Handler data for startmap/endmap handlers.
typedef struct {
  size_t ofs;
241 242
  upb_fieldtype_t key_field_type;
  upb_fieldtype_t value_field_type;
243 244 245 246

  // We know that we can hold this reference because the handlerdata has the
  // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
  // a reference to the upb_msgdef, which in turn has references to its subdefs.
247
  const upb_def* value_field_subdef;
248 249 250 251 252 253 254 255 256 257
} map_handlerdata_t;

// Temporary frame for map parsing: at the beginning of a map entry message, a
// submsg handler allocates a frame to hold (i) a reference to the Map object
// into which this message will be inserted and (ii) storage slots to
// temporarily hold the key and value for this map entry until the end of the
// submessage. When the submessage ends, another handler is called to insert the
// value into the map.
typedef struct {
  VALUE map;
258
  const map_handlerdata_t* handlerdata;
259 260 261 262
  char key_storage[NATIVE_SLOT_MAX_SIZE];
  char value_storage[NATIVE_SLOT_MAX_SIZE];
} map_parse_frame_t;

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
static void MapParseFrame_mark(void* _self) {
  map_parse_frame_t* frame = _self;

  // This shouldn't strictly be necessary since this should be rooted by the
  // message itself, but it can't hurt.
  rb_gc_mark(frame->map);

  native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
  native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
}

void MapParseFrame_free(void* self) {
  xfree(self);
}

rb_data_type_t MapParseFrame_type = {
  "MapParseFrame",
  { MapParseFrame_mark, MapParseFrame_free, NULL },
};

// Array of Ruby objects wrapping map_parse_frame_t.
// We don't allow multiple concurrent decodes, so we assume that this global
// variable is specific to the "current" decode.
VALUE map_parse_frames;

static map_parse_frame_t* map_push_frame(VALUE map,
                                         const map_handlerdata_t* handlerdata) {
  map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
  frame->handlerdata = handlerdata;
  frame->map = map;
  native_slot_init(handlerdata->key_field_type, &frame->key_storage);
  native_slot_init(handlerdata->value_field_type, &frame->value_storage);

  rb_ary_push(map_parse_frames,
              TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));

  return frame;
}

static void map_pop_frame() {
  rb_ary_pop(map_parse_frames);
}

306 307 308 309 310
// Handler to begin a map entry: allocates a temporary frame. This is the
// 'startsubmsg' handler on the msgdef that contains the map field.
static void *startmapentry_handler(void *closure, const void *hd) {
  MessageHeader* msg = closure;
  const map_handlerdata_t* mapdata = hd;
311
  VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
312

313
  return map_push_frame(map_rb, mapdata);
314 315 316 317 318 319 320 321 322
}

// Handler to end a map entry: inserts the value defined during the message into
// the map. This is the 'endmsg' handler on the map entry msgdef.
static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
  map_parse_frame_t* frame = closure;
  const map_handlerdata_t* mapdata = hd;

  VALUE key = native_slot_get(
323
      mapdata->key_field_type, Qnil,
324
      &frame->key_storage);
325 326

  VALUE value_field_typeclass = Qnil;
327 328
  VALUE value;

329 330 331 332 333
  if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
      mapdata->value_field_type == UPB_TYPE_ENUM) {
    value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
  }

334
  value = native_slot_get(
335
      mapdata->value_field_type, value_field_typeclass,
336 337 338
      &frame->value_storage);

  Map_index_set(frame->map, key, value);
339
  map_pop_frame();
340 341 342 343 344 345 346 347 348 349 350 351 352

  return true;
}

// Allocates a new map_handlerdata_t given the map entry message definition. If
// the offset of the field within the parent message is also given, that is
// added to the handler data as well. Note that this is called *twice* per map
// field: once in the parent message handler setup when setting the startsubmsg
// handler and once in the map entry message handler setup when setting the
// key/value and endmsg handlers. The reason is that there is no easy way to
// pass the handlerdata down to the sub-message handler setup.
static map_handlerdata_t* new_map_handlerdata(
    size_t ofs,
353 354
    const upb_msgdef* mapentry_def,
    Descriptor* desc) {
355 356
  const upb_fielddef* key_field;
  const upb_fielddef* value_field;
357 358
  map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
  hd->ofs = ofs;
359
  key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
360 361
  assert(key_field != NULL);
  hd->key_field_type = upb_fielddef_type(key_field);
362
  value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
363 364
  assert(value_field != NULL);
  hd->value_field_type = upb_fielddef_type(value_field);
365
  hd->value_field_subdef = upb_fielddef_subdef(value_field);
366

367 368 369
  return hd;
}

370 371 372 373 374
// Handlers that set primitive values in oneofs.
#define DEFINE_ONEOF_HANDLER(type, ctype)                           \
  static bool oneof##type##_handler(void *closure, const void *hd,  \
                                     ctype val) {                   \
    const oneof_handlerdata_t *oneofdata = hd;                      \
375 376
    DEREF(closure, oneofdata->case_ofs, uint32_t) =                 \
        oneofdata->oneof_case_num;                                  \
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    DEREF(closure, oneofdata->ofs, ctype) = val;                    \
    return true;                                                    \
  }

DEFINE_ONEOF_HANDLER(bool,   bool)
DEFINE_ONEOF_HANDLER(int32,  int32_t)
DEFINE_ONEOF_HANDLER(uint32, uint32_t)
DEFINE_ONEOF_HANDLER(float,  float)
DEFINE_ONEOF_HANDLER(int64,  int64_t)
DEFINE_ONEOF_HANDLER(uint64, uint64_t)
DEFINE_ONEOF_HANDLER(double, double)

#undef DEFINE_ONEOF_HANDLER

// Handlers for strings in a oneof.
static void *oneofstr_handler(void *closure,
                              const void *hd,
                              size_t size_hint) {
  MessageHeader* msg = closure;
  const oneof_handlerdata_t *oneofdata = hd;
  VALUE str = rb_str_new2("");
  rb_enc_associate(str, kRubyStringUtf8Encoding);
399 400
  DEREF(msg, oneofdata->case_ofs, uint32_t) =
      oneofdata->oneof_case_num;
401 402 403 404 405 406 407 408 409 410 411
  DEREF(msg, oneofdata->ofs, VALUE) = str;
  return (void*)str;
}

static void *oneofbytes_handler(void *closure,
                                const void *hd,
                                size_t size_hint) {
  MessageHeader* msg = closure;
  const oneof_handlerdata_t *oneofdata = hd;
  VALUE str = rb_str_new2("");
  rb_enc_associate(str, kRubyString8bitEncoding);
412 413
  DEREF(msg, oneofdata->case_ofs, uint32_t) =
      oneofdata->oneof_case_num;
414 415 416 417
  DEREF(msg, oneofdata->ofs, VALUE) = str;
  return (void*)str;
}

418 419 420 421 422 423 424
static bool oneofstring_end_handler(void* closure, const void* hd) {
  MessageHeader* msg = closure;
  const oneof_handlerdata_t *oneofdata = hd;
  rb_obj_freeze(DEREF(msg, oneofdata->ofs, VALUE));
  return true;
}

425 426 427 428 429 430 431 432 433 434
// Handler for a submessage field in a oneof.
static void *oneofsubmsg_handler(void *closure,
                                 const void *hd) {
  MessageHeader* msg = closure;
  const oneof_handlerdata_t *oneofdata = hd;
  uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);

  VALUE subdesc =
      get_def_obj((void*)oneofdata->md);
  VALUE subklass = Descriptor_msgclass(subdesc);
435 436
  VALUE submsg_rb;
  MessageHeader* submsg;
437

438
  if (oldcase != oneofdata->oneof_case_num ||
439 440 441 442
      DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
    DEREF(msg, oneofdata->ofs, VALUE) =
        rb_class_new_instance(0, NULL, subklass);
  }
443 444 445 446 447 448
  // Set the oneof case *after* allocating the new class instance -- otherwise,
  // if the Ruby GC is invoked as part of a call into the VM, it might invoke
  // our mark routines, and our mark routines might see the case value
  // indicating a VALUE is present and expect a valid VALUE. See comment in
  // layout_set() for more detail: basically, the change to the value and the
  // case must be atomic w.r.t. the Ruby VM.
449 450
  DEREF(msg, oneofdata->case_ofs, uint32_t) =
      oneofdata->oneof_case_num;
451

452
  submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
453 454 455 456
  TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  return submsg;
}

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
// Set up handlers for a repeated field.
static void add_handlers_for_repeated_field(upb_handlers *h,
                                            const upb_fielddef *f,
                                            size_t offset) {
  upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  upb_handlerattr_uninit(&attr);

  switch (upb_fielddef_type(f)) {

#define SET_HANDLER(utype, ltype)                                 \
  case utype:                                                     \
    upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
    break;

    SET_HANDLER(UPB_TYPE_BOOL,   bool);
    SET_HANDLER(UPB_TYPE_INT32,  int32);
    SET_HANDLER(UPB_TYPE_UINT32, uint32);
    SET_HANDLER(UPB_TYPE_ENUM,   int32);
    SET_HANDLER(UPB_TYPE_FLOAT,  float);
    SET_HANDLER(UPB_TYPE_INT64,  int64);
    SET_HANDLER(UPB_TYPE_UINT64, uint64);
    SET_HANDLER(UPB_TYPE_DOUBLE, double);

#undef SET_HANDLER

    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES: {
      bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
      upb_handlers_setstartstr(h, f, is_bytes ?
                               appendbytes_handler : appendstr_handler,
                               NULL);
      upb_handlers_setstring(h, f, stringdata_handler, NULL);
491
      upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
492
      break;
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    }
    case UPB_TYPE_MESSAGE: {
      upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
      upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
      upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
      upb_handlerattr_uninit(&attr);
      break;
    }
  }
}

// Set up handlers for a singular field.
static void add_handlers_for_singular_field(upb_handlers *h,
                                            const upb_fielddef *f,
                                            size_t offset) {
  switch (upb_fielddef_type(f)) {
    case UPB_TYPE_BOOL:
    case UPB_TYPE_INT32:
    case UPB_TYPE_UINT32:
    case UPB_TYPE_ENUM:
    case UPB_TYPE_FLOAT:
    case UPB_TYPE_INT64:
    case UPB_TYPE_UINT64:
    case UPB_TYPE_DOUBLE:
517
      upb_msg_setscalarhandler(h, f, offset, -1);
518 519 520 521 522 523 524 525 526 527
      break;
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES: {
      bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
      upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
      upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
      upb_handlers_setstartstr(h, f,
                               is_bytes ? bytes_handler : str_handler,
                               &attr);
      upb_handlers_setstring(h, f, stringdata_handler, &attr);
528
      upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
      upb_handlerattr_uninit(&attr);
      break;
    }
    case UPB_TYPE_MESSAGE: {
      upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
      upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
      upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
      upb_handlerattr_uninit(&attr);
      break;
    }
  }
}

// Adds handlers to a map field.
static void add_handlers_for_mapfield(upb_handlers* h,
                                      const upb_fielddef* fielddef,
545 546
                                      size_t offset,
                                      Descriptor* desc) {
547
  const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
548
  map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
549
  upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
550

551
  upb_handlers_addcleanup(h, hd, xfree);
552 553 554 555 556 557 558
  upb_handlerattr_sethandlerdata(&attr, hd);
  upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
  upb_handlerattr_uninit(&attr);
}

// Adds handlers to a map-entry msgdef.
static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
559 560
                                      upb_handlers* h,
                                      Descriptor* desc) {
561 562
  const upb_fielddef* key_field = map_entry_key(msgdef);
  const upb_fielddef* value_field = map_entry_value(msgdef);
563
  map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
564
  upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
565

566
  upb_handlers_addcleanup(h, hd, xfree);
567 568 569 570
  upb_handlerattr_sethandlerdata(&attr, hd);
  upb_handlers_setendmsg(h, endmap_handler, &attr);

  add_handlers_for_singular_field(
571
      h, key_field,
572
      offsetof(map_parse_frame_t, key_storage));
573
  add_handlers_for_singular_field(
574
      h, value_field,
575
      offsetof(map_parse_frame_t, value_storage));
576 577
}

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
// Set up handlers for a oneof field.
static void add_handlers_for_oneof_field(upb_handlers *h,
                                         const upb_fielddef *f,
                                         size_t offset,
                                         size_t oneof_case_offset) {

  upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  upb_handlerattr_sethandlerdata(
      &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));

  switch (upb_fielddef_type(f)) {

#define SET_HANDLER(utype, ltype)                                 \
  case utype:                                                     \
    upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
    break;

    SET_HANDLER(UPB_TYPE_BOOL,   bool);
    SET_HANDLER(UPB_TYPE_INT32,  int32);
    SET_HANDLER(UPB_TYPE_UINT32, uint32);
    SET_HANDLER(UPB_TYPE_ENUM,   int32);
    SET_HANDLER(UPB_TYPE_FLOAT,  float);
    SET_HANDLER(UPB_TYPE_INT64,  int64);
    SET_HANDLER(UPB_TYPE_UINT64, uint64);
    SET_HANDLER(UPB_TYPE_DOUBLE, double);

#undef SET_HANDLER

    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES: {
      bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
      upb_handlers_setstartstr(h, f, is_bytes ?
                               oneofbytes_handler : oneofstr_handler,
                               &attr);
      upb_handlers_setstring(h, f, stringdata_handler, NULL);
613
      upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
614 615 616 617 618 619 620 621 622 623 624 625
      break;
    }
    case UPB_TYPE_MESSAGE: {
      upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
      break;
    }
  }

  upb_handlerattr_uninit(&attr);
}


Chris Fallin's avatar
Chris Fallin committed
626
static void add_handlers_for_message(const void *closure, upb_handlers *h) {
627 628
  const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
629
  upb_msg_field_iter i;
630 631 632 633

  // If this is a mapentry message type, set up a special set of handlers and
  // bail out of the normal (user-defined) message type handling.
  if (upb_msgdef_mapentry(msgdef)) {
634
    add_handlers_for_mapentry(msgdef, h, desc);
635 636 637
    return;
  }

Chris Fallin's avatar
Chris Fallin committed
638 639 640 641 642 643 644 645
  // Ensure layout exists. We may be invoked to create handlers for a given
  // message if we are included as a submsg of another message type before our
  // class is actually built, so to work around this, we just create the layout
  // (and handlers, in the class-building function) on-demand.
  if (desc->layout == NULL) {
    desc->layout = create_layout(desc->msgdef);
  }

646 647 648
  for (upb_msg_field_begin(&i, desc->msgdef);
       !upb_msg_field_done(&i);
       upb_msg_field_next(&i)) {
Chris Fallin's avatar
Chris Fallin committed
649
    const upb_fielddef *f = upb_msg_iter_field(&i);
650 651
    size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
        sizeof(MessageHeader);
Chris Fallin's avatar
Chris Fallin committed
652

653
    if (upb_fielddef_containingoneof(f)) {
654 655 656
      size_t oneof_case_offset =
          desc->layout->fields[upb_fielddef_index(f)].case_offset +
          sizeof(MessageHeader);
657 658
      add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
    } else if (is_map_field(f)) {
659
      add_handlers_for_mapfield(h, f, offset, desc);
660 661 662 663
    } else if (upb_fielddef_isseq(f)) {
      add_handlers_for_repeated_field(h, f, offset);
    } else {
      add_handlers_for_singular_field(h, f, offset);
Chris Fallin's avatar
Chris Fallin committed
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    }
  }
}

// Creates upb handlers for populating a message.
static const upb_handlers *new_fill_handlers(Descriptor* desc,
                                             const void* owner) {
  // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
  // handlers, reuse subdef handlers so that e.g. if we already parse
  // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
  // parse A-with-field-of-type-B-with-field-of-type-C.
  return upb_handlers_newfrozen(desc->msgdef, owner,
                                add_handlers_for_message, NULL);
}

// Constructs the handlers for filling a message's data into an in-memory
// object.
const upb_handlers* get_fill_handlers(Descriptor* desc) {
  if (!desc->fill_handlers) {
    desc->fill_handlers =
        new_fill_handlers(desc, &desc->fill_handlers);
  }
  return desc->fill_handlers;
}

// Constructs the upb decoder method for parsing messages of this type.
// This is called from the message class creation code.
const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
                                                     const void* owner) {
  const upb_handlers* handlers = get_fill_handlers(desc);
  upb_pbdecodermethodopts opts;
  upb_pbdecodermethodopts_init(&opts, handlers);

697
  return upb_pbdecodermethod_new(&opts, owner);
Chris Fallin's avatar
Chris Fallin committed
698 699 700 701 702 703 704 705 706 707
}

static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  if (desc->fill_method == NULL) {
    desc->fill_method = new_fillmsg_decodermethod(
        desc, &desc->fill_method);
  }
  return desc->fill_method;
}

708 709 710 711 712 713 714 715
static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
  if (desc->json_fill_method == NULL) {
    desc->json_fill_method =
        upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
  }
  return desc->json_fill_method;
}

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736

// Stack-allocated context during an encode/decode operation. Contains the upb
// environment and its stack-based allocator, an initial buffer for allocations
// to avoid malloc() when possible, and a template for Ruby exception messages
// if any error occurs.
#define STACK_ENV_STACKBYTES 4096
typedef struct {
  upb_env env;
  const char* ruby_error_template;
  char allocbuf[STACK_ENV_STACKBYTES];
} stackenv;

static void stackenv_init(stackenv* se, const char* errmsg);
static void stackenv_uninit(stackenv* se);

// Callback invoked by upb if any error occurs during parsing or serialization.
static bool env_error_func(void* ud, const upb_status* status) {
  stackenv* se = ud;
  // Free the env -- rb_raise will longjmp up the stack past the encode/decode
  // function so it would not otherwise have been freed.
  stackenv_uninit(se);
737 738 739 740

  // TODO(haberman): have a way to verify that this is actually a parse error,
  // instead of just throwing "parse error" unconditionally.
  rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
741 742 743 744 745 746 747
  // Never reached: rb_raise() always longjmp()s up the stack, past all of our
  // code, back to Ruby.
  return false;
}

static void stackenv_init(stackenv* se, const char* errmsg) {
  se->ruby_error_template = errmsg;
748
  upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
749 750 751 752 753 754 755
  upb_env_seterrorfunc(&se->env, env_error_func, se);
}

static void stackenv_uninit(stackenv* se) {
  upb_env_uninit(&se->env);
}

Chris Fallin's avatar
Chris Fallin committed
756 757 758 759 760 761 762 763 764
/*
 * call-seq:
 *     MessageClass.decode(data) => message
 *
 * Decodes the given data (as a string containing bytes in protocol buffers wire
 * format) under the interpretration given by this message class's definition
 * and returns a message object with the corresponding field values.
 */
VALUE Message_decode(VALUE klass, VALUE data) {
765
  VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
Chris Fallin's avatar
Chris Fallin committed
766 767
  Descriptor* desc = ruby_to_Descriptor(descriptor);
  VALUE msgklass = Descriptor_msgclass(descriptor);
768 769
  VALUE msg_rb;
  MessageHeader* msg;
Chris Fallin's avatar
Chris Fallin committed
770 771 772 773 774

  if (TYPE(data) != T_STRING) {
    rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  }

775
  msg_rb = rb_class_new_instance(0, NULL, msgklass);
Chris Fallin's avatar
Chris Fallin committed
776 777
  TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);

778 779 780 781
  // We generally expect this to be clear already, but clear it in case parsing
  // previously got interrupted somehow.
  rb_ary_clear(map_parse_frames);

782 783 784 785 786 787 788
  {
    const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
    const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
    stackenv se;
    upb_sink sink;
    upb_pbdecoder* decoder;
    stackenv_init(&se, "Error occurred during parsing: %s");
Chris Fallin's avatar
Chris Fallin committed
789

790 791 792 793
    upb_sink_reset(&sink, h, msg);
    decoder = upb_pbdecoder_create(&se.env, method, &sink);
    upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
                      upb_pbdecoder_input(decoder));
Chris Fallin's avatar
Chris Fallin committed
794

795 796
    stackenv_uninit(&se);
  }
Chris Fallin's avatar
Chris Fallin committed
797 798 799 800 801 802 803 804 805 806 807 808 809

  return msg_rb;
}

/*
 * call-seq:
 *     MessageClass.decode_json(data) => message
 *
 * Decodes the given data (as a string containing bytes in protocol buffers wire
 * format) under the interpretration given by this message class's definition
 * and returns a message object with the corresponding field values.
 */
VALUE Message_decode_json(VALUE klass, VALUE data) {
810
  VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
Chris Fallin's avatar
Chris Fallin committed
811 812
  Descriptor* desc = ruby_to_Descriptor(descriptor);
  VALUE msgklass = Descriptor_msgclass(descriptor);
813 814
  VALUE msg_rb;
  MessageHeader* msg;
Chris Fallin's avatar
Chris Fallin committed
815 816 817 818 819 820 821 822

  if (TYPE(data) != T_STRING) {
    rb_raise(rb_eArgError, "Expected string for JSON data.");
  }
  // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  // convert, because string handlers pass data directly to message string
  // fields.

823
  msg_rb = rb_class_new_instance(0, NULL, msgklass);
Chris Fallin's avatar
Chris Fallin committed
824 825
  TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);

826 827 828 829
  // We generally expect this to be clear already, but clear it in case parsing
  // previously got interrupted somehow.
  rb_ary_clear(map_parse_frames);

830
  {
831
    const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
832 833 834 835
    stackenv se;
    upb_sink sink;
    upb_json_parser* parser;
    stackenv_init(&se, "Error occurred during parsing: %s");
Chris Fallin's avatar
Chris Fallin committed
836

837
    upb_sink_reset(&sink, get_fill_handlers(desc), msg);
838
    parser = upb_json_parser_create(&se.env, method, &sink);
839 840
    upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
                      upb_json_parser_input(parser));
Chris Fallin's avatar
Chris Fallin committed
841

842 843
    stackenv_uninit(&se);
  }
Chris Fallin's avatar
Chris Fallin committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876

  return msg_rb;
}

// -----------------------------------------------------------------------------
// Serializing.
// -----------------------------------------------------------------------------
//
// The code below also comes from upb's prototype Ruby binding, developed by
// haberman@.

/* stringsink *****************************************************************/

// This should probably be factored into a common upb component.

typedef struct {
  upb_byteshandler handler;
  upb_bytessink sink;
  char *ptr;
  size_t len, size;
} stringsink;

static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  stringsink *sink = _sink;
  sink->len = 0;
  return sink;
}

static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
                                size_t len, const upb_bufhandle *handle) {
  stringsink *sink = _sink;
  size_t new_size = sink->size;

877 878 879
  UPB_UNUSED(hd);
  UPB_UNUSED(handle);

Chris Fallin's avatar
Chris Fallin committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  while (sink->len + len > new_size) {
    new_size *= 2;
  }

  if (new_size != sink->size) {
    sink->ptr = realloc(sink->ptr, new_size);
    sink->size = new_size;
  }

  memcpy(sink->ptr + sink->len, ptr, len);
  sink->len += len;

  return len;
}

void stringsink_init(stringsink *sink) {
  upb_byteshandler_init(&sink->handler);
  upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);

  upb_bytessink_reset(&sink->sink, &sink->handler, sink);

  sink->size = 32;
  sink->ptr = malloc(sink->size);
  sink->len = 0;
}

void stringsink_uninit(stringsink *sink) {
  free(sink->ptr);
}

/* msgvisitor *****************************************************************/

// TODO: If/when we support proto2 semantics in addition to the current proto3
// semantics, which means that we have true field presence, we will want to
// modify msgvisitor so that it emits all present fields rather than all
// non-default-value fields.
//
// Likewise, when implementing JSON serialization, we may need to have a
// 'verbose' mode that outputs all fields and a 'concise' mode that outputs only
// those with non-default values.

static void putmsg(VALUE msg, const Descriptor* desc,
                   upb_sink *sink, int depth);

static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  upb_selector_t ret;
  bool ok = upb_handlers_getselector(f, type, &ret);
928
  UPB_ASSERT(ok);
Chris Fallin's avatar
Chris Fallin committed
929 930 931 932
  return ret;
}

static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
933 934
  upb_sink subsink;

Chris Fallin's avatar
Chris Fallin committed
935 936 937 938
  if (str == Qnil) return;

  assert(BUILTIN_TYPE(str) == RUBY_T_STRING);

939 940 941
  // We should be guaranteed that the string has the correct encoding because
  // we ensured this at assignment time and then froze the string.
  if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
942
    assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
943
  } else {
944
    assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
945
  }
Chris Fallin's avatar
Chris Fallin committed
946 947 948 949 950 951 952 953 954 955

  upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
                    &subsink);
  upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
                     RSTRING_LEN(str), NULL);
  upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
}

static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
                      int depth) {
956 957 958 959
  upb_sink subsink;
  VALUE descriptor;
  Descriptor* subdesc;

Chris Fallin's avatar
Chris Fallin committed
960 961
  if (submsg == Qnil) return;

962 963
  descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  subdesc = ruby_to_Descriptor(descriptor);
Chris Fallin's avatar
Chris Fallin committed
964 965 966 967 968 969 970 971 972

  upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  putmsg(submsg, subdesc, &subsink, depth + 1);
  upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
}

static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
                   int depth) {
  upb_sink subsink;
973 974 975 976 977
  upb_fieldtype_t type = upb_fielddef_type(f);
  upb_selector_t sel = 0;
  int size;

  if (ary == Qnil) return;
Chris Fallin's avatar
Chris Fallin committed
978 979 980 981 982 983 984

  upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);

  if (upb_fielddef_isprimitive(f)) {
    sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  }

985
  size = NUM2INT(RepeatedField_length(ary));
Chris Fallin's avatar
Chris Fallin committed
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
  for (int i = 0; i < size; i++) {
    void* memory = RepeatedField_index_native(ary, i);
    switch (type) {
#define T(upbtypeconst, upbtype, ctype)                         \
  case upbtypeconst:                                            \
    upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory));   \
    break;

      T(UPB_TYPE_FLOAT,  float,  float)
      T(UPB_TYPE_DOUBLE, double, double)
      T(UPB_TYPE_BOOL,   bool,   int8_t)
      case UPB_TYPE_ENUM:
      T(UPB_TYPE_INT32,  int32,  int32_t)
      T(UPB_TYPE_UINT32, uint32, uint32_t)
      T(UPB_TYPE_INT64,  int64,  int64_t)
      T(UPB_TYPE_UINT64, uint64, uint64_t)

      case UPB_TYPE_STRING:
      case UPB_TYPE_BYTES:
        putstr(*((VALUE *)memory), f, &subsink);
        break;
      case UPB_TYPE_MESSAGE:
        putsubmsg(*((VALUE *)memory), f, &subsink, depth);
        break;

#undef T

    }
  }
  upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
}

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
static void put_ruby_value(VALUE value,
                           const upb_fielddef *f,
                           VALUE type_class,
                           int depth,
                           upb_sink *sink) {
  upb_selector_t sel = 0;
  if (upb_fielddef_isprimitive(f)) {
    sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  }

  switch (upb_fielddef_type(f)) {
    case UPB_TYPE_INT32:
      upb_sink_putint32(sink, sel, NUM2INT(value));
      break;
    case UPB_TYPE_INT64:
      upb_sink_putint64(sink, sel, NUM2LL(value));
      break;
    case UPB_TYPE_UINT32:
      upb_sink_putuint32(sink, sel, NUM2UINT(value));
      break;
    case UPB_TYPE_UINT64:
      upb_sink_putuint64(sink, sel, NUM2ULL(value));
      break;
    case UPB_TYPE_FLOAT:
      upb_sink_putfloat(sink, sel, NUM2DBL(value));
      break;
    case UPB_TYPE_DOUBLE:
      upb_sink_putdouble(sink, sel, NUM2DBL(value));
      break;
    case UPB_TYPE_ENUM: {
      if (TYPE(value) == T_SYMBOL) {
        value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
      }
      upb_sink_putint32(sink, sel, NUM2INT(value));
      break;
    }
    case UPB_TYPE_BOOL:
      upb_sink_putbool(sink, sel, value == Qtrue);
      break;
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES:
      putstr(value, f, sink);
      break;
    case UPB_TYPE_MESSAGE:
      putsubmsg(value, f, sink, depth);
  }
}

static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
                   int depth) {
1068
  Map* self;
1069
  upb_sink subsink;
1070 1071 1072 1073 1074 1075
  const upb_fielddef* key_field;
  const upb_fielddef* value_field;
  Map_iter it;

  if (map == Qnil) return;
  self = ruby_to_Map(map);
1076 1077 1078 1079

  upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);

  assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
1080 1081
  key_field = map_field_key(f);
  value_field = map_field_value(f);
1082 1083 1084 1085

  for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
    VALUE key = Map_iter_key(&it);
    VALUE value = Map_iter_value(&it);
1086
    upb_status status;
1087 1088

    upb_sink entry_sink;
1089 1090
    upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
                         &entry_sink);
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    upb_sink_startmsg(&entry_sink);

    put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink);
    put_ruby_value(value, value_field, self->value_type_class, depth + 1,
                   &entry_sink);

    upb_sink_endmsg(&entry_sink, &status);
    upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  }

  upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
}

Chris Fallin's avatar
Chris Fallin committed
1104 1105
static void putmsg(VALUE msg_rb, const Descriptor* desc,
                   upb_sink *sink, int depth) {
1106 1107 1108 1109
  MessageHeader* msg;
  upb_msg_field_iter i;
  upb_status status;

Chris Fallin's avatar
Chris Fallin committed
1110 1111 1112 1113
  upb_sink_startmsg(sink);

  // Protect against cycles (possible because users may freely reassign message
  // and repeated fields) by imposing a maximum recursion depth.
1114
  if (depth > ENCODE_MAX_NESTING) {
Chris Fallin's avatar
Chris Fallin committed
1115 1116 1117 1118 1119 1120
    rb_raise(rb_eRuntimeError,
             "Maximum recursion depth exceeded during encoding.");
  }

  TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);

1121 1122 1123
  for (upb_msg_field_begin(&i, desc->msgdef);
       !upb_msg_field_done(&i);
       upb_msg_field_next(&i)) {
Chris Fallin's avatar
Chris Fallin committed
1124
    upb_fielddef *f = upb_msg_iter_field(&i);
1125
    bool is_matching_oneof = false;
1126
    uint32_t offset =
1127 1128 1129 1130
        desc->layout->fields[upb_fielddef_index(f)].offset +
        sizeof(MessageHeader);

    if (upb_fielddef_containingoneof(f)) {
1131 1132 1133
      uint32_t oneof_case_offset =
          desc->layout->fields[upb_fielddef_index(f)].case_offset +
          sizeof(MessageHeader);
1134 1135 1136 1137 1138 1139 1140 1141
      // For a oneof, check that this field is actually present -- skip all the
      // below if not.
      if (DEREF(msg, oneof_case_offset, uint32_t) !=
          upb_fielddef_number(f)) {
        continue;
      }
      // Otherwise, fall through to the appropriate singular-field handler
      // below.
1142
      is_matching_oneof = true;
1143
    }
Chris Fallin's avatar
Chris Fallin committed
1144

1145
    if (is_map_field(f)) {
1146
      VALUE map = DEREF(msg, offset, VALUE);
1147 1148 1149 1150
      if (map != Qnil) {
        putmap(map, f, sink, depth);
      }
    } else if (upb_fielddef_isseq(f)) {
1151
      VALUE ary = DEREF(msg, offset, VALUE);
Chris Fallin's avatar
Chris Fallin committed
1152 1153 1154 1155
      if (ary != Qnil) {
        putary(ary, f, sink, depth);
      }
    } else if (upb_fielddef_isstring(f)) {
1156
      VALUE str = DEREF(msg, offset, VALUE);
1157
      if (is_matching_oneof || RSTRING_LEN(str) > 0) {
Chris Fallin's avatar
Chris Fallin committed
1158 1159 1160
        putstr(str, f, sink);
      }
    } else if (upb_fielddef_issubmsg(f)) {
1161
      putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth);
Chris Fallin's avatar
Chris Fallin committed
1162 1163 1164 1165 1166
    } else {
      upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));

#define T(upbtypeconst, upbtype, ctype, default_value)                \
  case upbtypeconst: {                                                \
1167
      ctype value = DEREF(msg, offset, ctype);                        \
1168
      if (is_matching_oneof || value != default_value) {              \
Chris Fallin's avatar
Chris Fallin committed
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        upb_sink_put##upbtype(sink, sel, value);                      \
      }                                                               \
    }                                                                 \
    break;

      switch (upb_fielddef_type(f)) {
        T(UPB_TYPE_FLOAT,  float,  float, 0.0)
        T(UPB_TYPE_DOUBLE, double, double, 0.0)
        T(UPB_TYPE_BOOL,   bool,   uint8_t, 0)
        case UPB_TYPE_ENUM:
        T(UPB_TYPE_INT32,  int32,  int32_t, 0)
        T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
        T(UPB_TYPE_INT64,  int64,  int64_t, 0)
        T(UPB_TYPE_UINT64, uint64, uint64_t, 0)

        case UPB_TYPE_STRING:
        case UPB_TYPE_BYTES:
        case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
      }

#undef T

    }
  }

  upb_sink_endmsg(sink, &status);
}

static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  if (desc->pb_serialize_handlers == NULL) {
    desc->pb_serialize_handlers =
        upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
  }
  return desc->pb_serialize_handlers;
}

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
static const upb_handlers* msgdef_json_serialize_handlers(
    Descriptor* desc, bool preserve_proto_fieldnames) {
  if (preserve_proto_fieldnames) {
    if (desc->json_serialize_handlers == NULL) {
      desc->json_serialize_handlers =
          upb_json_printer_newhandlers(
              desc->msgdef, true, &desc->json_serialize_handlers);
    }
    return desc->json_serialize_handlers;
  } else {
    if (desc->json_serialize_handlers_preserve == NULL) {
      desc->json_serialize_handlers_preserve =
          upb_json_printer_newhandlers(
              desc->msgdef, false, &desc->json_serialize_handlers_preserve);
    }
    return desc->json_serialize_handlers_preserve;
Chris Fallin's avatar
Chris Fallin committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
  }
}

/*
 * call-seq:
 *     MessageClass.encode(msg) => bytes
 *
 * Encodes the given message object to its serialized form in protocol buffers
 * wire format.
 */
VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1232
  VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
Chris Fallin's avatar
Chris Fallin committed
1233 1234 1235 1236 1237
  Descriptor* desc = ruby_to_Descriptor(descriptor);

  stringsink sink;
  stringsink_init(&sink);

1238 1239 1240
  {
    const upb_handlers* serialize_handlers =
        msgdef_pb_serialize_handlers(desc);
Chris Fallin's avatar
Chris Fallin committed
1241

1242 1243 1244
    stackenv se;
    upb_pb_encoder* encoder;
    VALUE ret;
Chris Fallin's avatar
Chris Fallin committed
1245

1246 1247
    stackenv_init(&se, "Error occurred during encoding: %s");
    encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
Chris Fallin's avatar
Chris Fallin committed
1248

1249
    putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0);
Chris Fallin's avatar
Chris Fallin committed
1250

1251
    ret = rb_str_new(sink.ptr, sink.len);
Chris Fallin's avatar
Chris Fallin committed
1252

1253 1254 1255 1256 1257
    stackenv_uninit(&se);
    stringsink_uninit(&sink);

    return ret;
  }
Chris Fallin's avatar
Chris Fallin committed
1258 1259 1260 1261 1262 1263 1264 1265
}

/*
 * call-seq:
 *     MessageClass.encode_json(msg) => json_string
 *
 * Encodes the given message object into its serialized JSON representation.
 */
1266
VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1267
  VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
Chris Fallin's avatar
Chris Fallin committed
1268
  Descriptor* desc = ruby_to_Descriptor(descriptor);
1269 1270
  VALUE msg_rb;
  VALUE preserve_proto_fieldnames = Qfalse;
Chris Fallin's avatar
Chris Fallin committed
1271
  stringsink sink;
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287

  if (argc < 1 || argc > 2) {
    rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  }

  msg_rb = argv[0];

  if (argc == 2) {
    VALUE hash_args = argv[1];
    if (TYPE(hash_args) != T_HASH) {
      rb_raise(rb_eArgError, "Expected hash arguments.");
    }
    preserve_proto_fieldnames = rb_hash_lookup2(
        hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
  }

Chris Fallin's avatar
Chris Fallin committed
1288 1289
  stringsink_init(&sink);

1290 1291
  {
    const upb_handlers* serialize_handlers =
1292
        msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
1293 1294 1295
    upb_json_printer* printer;
    stackenv se;
    VALUE ret;
Chris Fallin's avatar
Chris Fallin committed
1296

1297 1298
    stackenv_init(&se, "Error occurred during encoding: %s");
    printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
Chris Fallin's avatar
Chris Fallin committed
1299

1300
    putmsg(msg_rb, desc, upb_json_printer_input(printer), 0);
Chris Fallin's avatar
Chris Fallin committed
1301

1302
    ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
Chris Fallin's avatar
Chris Fallin committed
1303

1304 1305
    stackenv_uninit(&se);
    stringsink_uninit(&sink);
Chris Fallin's avatar
Chris Fallin committed
1306

1307 1308
    return ret;
  }
Chris Fallin's avatar
Chris Fallin committed
1309 1310
}