storage.c 34.7 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 33 34 35 36 37 38 39 40
// 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"

#include <math.h>

#include <ruby/encoding.h>

// -----------------------------------------------------------------------------
// Ruby <-> native slot management.
// -----------------------------------------------------------------------------

41 42
#define CHARPTR_AT(msg, ofs) ((char*)msg + ofs)
#define DEREF_OFFSET(msg, ofs, type) *(type*)CHARPTR_AT(msg, ofs)
Chris Fallin's avatar
Chris Fallin committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#define DEREF(memory, type) *(type*)(memory)

size_t native_slot_size(upb_fieldtype_t type) {
  switch (type) {
    case UPB_TYPE_FLOAT:   return 4;
    case UPB_TYPE_DOUBLE:  return 8;
    case UPB_TYPE_BOOL:    return 1;
    case UPB_TYPE_STRING:  return sizeof(VALUE);
    case UPB_TYPE_BYTES:   return sizeof(VALUE);
    case UPB_TYPE_MESSAGE: return sizeof(VALUE);
    case UPB_TYPE_ENUM:    return 4;
    case UPB_TYPE_INT32:   return 4;
    case UPB_TYPE_INT64:   return 8;
    case UPB_TYPE_UINT32:  return 4;
    case UPB_TYPE_UINT64:  return 8;
    default: return 0;
  }
}

62 63 64 65 66 67
static bool is_ruby_num(VALUE value) {
  return (TYPE(value) == T_FLOAT ||
          TYPE(value) == T_FIXNUM ||
          TYPE(value) == T_BIGNUM);
}

68
void native_slot_check_int_range_precision(const char* name, upb_fieldtype_t type, VALUE val) {
69
  if (!is_ruby_num(val)) {
70 71
    rb_raise(cTypeError, "Expected number type for integral field '%s' (given %s).",
             name, rb_class2name(CLASS_OF(val)));
72 73
  }

Chris Fallin's avatar
Chris Fallin committed
74 75 76 77 78 79 80
  // NUM2{INT,UINT,LL,ULL} macros do the appropriate range checks on upper
  // bound; we just need to do precision checks (i.e., disallow rounding) and
  // check for < 0 on unsigned types.
  if (TYPE(val) == T_FLOAT) {
    double dbl_val = NUM2DBL(val);
    if (floor(dbl_val) != dbl_val) {
      rb_raise(rb_eRangeError,
81 82
               "Non-integral floating point value assigned to integer field '%s' (given %s).",
               name, rb_class2name(CLASS_OF(val)));
Chris Fallin's avatar
Chris Fallin committed
83 84 85 86 87
    }
  }
  if (type == UPB_TYPE_UINT32 || type == UPB_TYPE_UINT64) {
    if (NUM2DBL(val) < 0) {
      rb_raise(rb_eRangeError,
88 89
               "Assigning negative value to unsigned integer field '%s' (given %s).",
               name, rb_class2name(CLASS_OF(val)));
Chris Fallin's avatar
Chris Fallin committed
90 91 92 93
    }
  }
}

94 95 96 97 98 99 100 101 102 103 104
VALUE native_slot_encode_and_freeze_string(upb_fieldtype_t type, VALUE value) {
  rb_encoding* desired_encoding = (type == UPB_TYPE_STRING) ?
      kRubyStringUtf8Encoding : kRubyString8bitEncoding;
  VALUE desired_encoding_value = rb_enc_from_encoding(desired_encoding);

  // Note: this will not duplicate underlying string data unless necessary.
  value = rb_str_encode(value, desired_encoding_value, 0, Qnil);

  if (type == UPB_TYPE_STRING &&
      rb_enc_str_coderange(value) == ENC_CODERANGE_BROKEN) {
    rb_raise(rb_eEncodingError, "String is invalid UTF-8");
Chris Fallin's avatar
Chris Fallin committed
105
  }
106 107 108 109 110 111

  // Ensure the data remains valid.  Since we called #encode a moment ago,
  // this does not freeze the string the user assigned.
  rb_obj_freeze(value);

  return value;
Chris Fallin's avatar
Chris Fallin committed
112 113
}

114
void native_slot_set(const char* name,
115
                     upb_fieldtype_t type, VALUE type_class,
Chris Fallin's avatar
Chris Fallin committed
116
                     void* memory, VALUE value) {
117
  native_slot_set_value_and_case(name, type, type_class, memory, value, NULL, 0);
118 119
}

120
void native_slot_set_value_and_case(const char* name,
121
                                    upb_fieldtype_t type, VALUE type_class,
122 123 124 125 126 127 128
                                    void* memory, VALUE value,
                                    uint32_t* case_memory,
                                    uint32_t case_number) {
  // Note that in order to atomically change the value in memory and the case
  // value (w.r.t. Ruby VM calls), we must set the value at |memory| only after
  // all Ruby VM calls are complete. The case is then set at the bottom of this
  // function.
Chris Fallin's avatar
Chris Fallin committed
129 130 131
  switch (type) {
    case UPB_TYPE_FLOAT:
      if (!is_ruby_num(value)) {
132 133
        rb_raise(cTypeError, "Expected number type for float field '%s' (given %s).",
                 name, rb_class2name(CLASS_OF(value)));
Chris Fallin's avatar
Chris Fallin committed
134 135 136 137 138
      }
      DEREF(memory, float) = NUM2DBL(value);
      break;
    case UPB_TYPE_DOUBLE:
      if (!is_ruby_num(value)) {
139 140
        rb_raise(cTypeError, "Expected number type for double field '%s' (given %s).",
                 name, rb_class2name(CLASS_OF(value)));
Chris Fallin's avatar
Chris Fallin committed
141 142 143 144 145 146 147 148 149 150
      }
      DEREF(memory, double) = NUM2DBL(value);
      break;
    case UPB_TYPE_BOOL: {
      int8_t val = -1;
      if (value == Qtrue) {
        val = 1;
      } else if (value == Qfalse) {
        val = 0;
      } else {
151 152
        rb_raise(cTypeError, "Invalid argument for boolean field '%s' (given %s).",
                 name, rb_class2name(CLASS_OF(value)));
Chris Fallin's avatar
Chris Fallin committed
153 154 155 156 157
      }
      DEREF(memory, int8_t) = val;
      break;
    }
    case UPB_TYPE_STRING:
158
      if (CLASS_OF(value) == rb_cSymbol) {
159
        value = rb_funcall(value, rb_intern("to_s"), 0);
160
      } else if (CLASS_OF(value) != rb_cString) {
161 162
        rb_raise(cTypeError, "Invalid argument for string field '%s' (given %s).",
                 name, rb_class2name(CLASS_OF(value)));
163 164 165 166 167
      }

      DEREF(memory, VALUE) = native_slot_encode_and_freeze_string(type, value);
      break;

Chris Fallin's avatar
Chris Fallin committed
168 169
    case UPB_TYPE_BYTES: {
      if (CLASS_OF(value) != rb_cString) {
170 171
        rb_raise(cTypeError, "Invalid argument for bytes field '%s' (given %s).",
                 name, rb_class2name(CLASS_OF(value)));
Chris Fallin's avatar
Chris Fallin committed
172
      }
173 174

      DEREF(memory, VALUE) = native_slot_encode_and_freeze_string(type, value);
Chris Fallin's avatar
Chris Fallin committed
175 176 177
      break;
    }
    case UPB_TYPE_MESSAGE: {
178 179 180
      if (CLASS_OF(value) == CLASS_OF(Qnil)) {
        value = Qnil;
      } else if (CLASS_OF(value) != type_class) {
181
        rb_raise(cTypeError,
182 183
                 "Invalid type %s to assign to submessage field '%s'.",
                rb_class2name(CLASS_OF(value)), name);
Chris Fallin's avatar
Chris Fallin committed
184 185 186 187 188
      }
      DEREF(memory, VALUE) = value;
      break;
    }
    case UPB_TYPE_ENUM: {
189
      int32_t int_val = 0;
190
      if (TYPE(value) == T_STRING) {
191
        value = rb_funcall(value, rb_intern("to_sym"), 0);
192
      } else if (!is_ruby_num(value) && TYPE(value) != T_SYMBOL) {
193
        rb_raise(cTypeError,
194
                 "Expected number or symbol type for enum field '%s'.", name);
Chris Fallin's avatar
Chris Fallin committed
195 196 197
      }
      if (TYPE(value) == T_SYMBOL) {
        // Ensure that the given symbol exists in the enum module.
198
        VALUE lookup = rb_funcall(type_class, rb_intern("resolve"), 1, value);
Chris Fallin's avatar
Chris Fallin committed
199
        if (lookup == Qnil) {
200
          rb_raise(rb_eRangeError, "Unknown symbol value for enum field '%s'.", name);
Chris Fallin's avatar
Chris Fallin committed
201 202 203 204
        } else {
          int_val = NUM2INT(lookup);
        }
      } else {
205
        native_slot_check_int_range_precision(name, UPB_TYPE_INT32, value);
Chris Fallin's avatar
Chris Fallin committed
206 207 208 209 210 211 212 213 214
        int_val = NUM2INT(value);
      }
      DEREF(memory, int32_t) = int_val;
      break;
    }
    case UPB_TYPE_INT32:
    case UPB_TYPE_INT64:
    case UPB_TYPE_UINT32:
    case UPB_TYPE_UINT64:
215
      native_slot_check_int_range_precision(name, type, value);
Chris Fallin's avatar
Chris Fallin committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
      switch (type) {
      case UPB_TYPE_INT32:
        DEREF(memory, int32_t) = NUM2INT(value);
        break;
      case UPB_TYPE_INT64:
        DEREF(memory, int64_t) = NUM2LL(value);
        break;
      case UPB_TYPE_UINT32:
        DEREF(memory, uint32_t) = NUM2UINT(value);
        break;
      case UPB_TYPE_UINT64:
        DEREF(memory, uint64_t) = NUM2ULL(value);
        break;
      default:
        break;
      }
      break;
    default:
      break;
  }
236 237 238 239

  if (case_memory != NULL) {
    *case_memory = case_number;
  }
Chris Fallin's avatar
Chris Fallin committed
240 241
}

242 243 244
VALUE native_slot_get(upb_fieldtype_t type,
                      VALUE type_class,
                      const void* memory) {
Chris Fallin's avatar
Chris Fallin committed
245 246 247 248 249 250 251 252 253 254
  switch (type) {
    case UPB_TYPE_FLOAT:
      return DBL2NUM(DEREF(memory, float));
    case UPB_TYPE_DOUBLE:
      return DBL2NUM(DEREF(memory, double));
    case UPB_TYPE_BOOL:
      return DEREF(memory, int8_t) ? Qtrue : Qfalse;
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES:
    case UPB_TYPE_MESSAGE:
255
      return DEREF(memory, VALUE);
Chris Fallin's avatar
Chris Fallin committed
256 257 258 259 260 261 262 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
    case UPB_TYPE_ENUM: {
      int32_t val = DEREF(memory, int32_t);
      VALUE symbol = enum_lookup(type_class, INT2NUM(val));
      if (symbol == Qnil) {
        return INT2NUM(val);
      } else {
        return symbol;
      }
    }
    case UPB_TYPE_INT32:
      return INT2NUM(DEREF(memory, int32_t));
    case UPB_TYPE_INT64:
      return LL2NUM(DEREF(memory, int64_t));
    case UPB_TYPE_UINT32:
      return UINT2NUM(DEREF(memory, uint32_t));
    case UPB_TYPE_UINT64:
      return ULL2NUM(DEREF(memory, uint64_t));
    default:
      return Qnil;
  }
}

void native_slot_init(upb_fieldtype_t type, void* memory) {
  switch (type) {
    case UPB_TYPE_FLOAT:
      DEREF(memory, float) = 0.0;
      break;
    case UPB_TYPE_DOUBLE:
      DEREF(memory, double) = 0.0;
      break;
    case UPB_TYPE_BOOL:
      DEREF(memory, int8_t) = 0;
      break;
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES:
      DEREF(memory, VALUE) = rb_str_new2("");
292 293
      rb_enc_associate(DEREF(memory, VALUE), (type == UPB_TYPE_BYTES) ?
                       kRubyString8bitEncoding : kRubyStringUtf8Encoding);
Chris Fallin's avatar
Chris Fallin committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
      break;
    case UPB_TYPE_MESSAGE:
      DEREF(memory, VALUE) = Qnil;
      break;
    case UPB_TYPE_ENUM:
    case UPB_TYPE_INT32:
      DEREF(memory, int32_t) = 0;
      break;
    case UPB_TYPE_INT64:
      DEREF(memory, int64_t) = 0;
      break;
    case UPB_TYPE_UINT32:
      DEREF(memory, uint32_t) = 0;
      break;
    case UPB_TYPE_UINT64:
      DEREF(memory, uint64_t) = 0;
      break;
    default:
      break;
  }
}

void native_slot_mark(upb_fieldtype_t type, void* memory) {
  switch (type) {
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES:
    case UPB_TYPE_MESSAGE:
      rb_gc_mark(DEREF(memory, VALUE));
      break;
    default:
      break;
  }
}

void native_slot_dup(upb_fieldtype_t type, void* to, void* from) {
  memcpy(to, from, native_slot_size(type));
}

void native_slot_deep_copy(upb_fieldtype_t type, void* to, void* from) {
  switch (type) {
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES: {
      VALUE from_val = DEREF(from, VALUE);
      DEREF(to, VALUE) = (from_val != Qnil) ?
          rb_funcall(from_val, rb_intern("dup"), 0) : Qnil;
      break;
    }
    case UPB_TYPE_MESSAGE: {
      VALUE from_val = DEREF(from, VALUE);
      DEREF(to, VALUE) = (from_val != Qnil) ?
          Message_deep_copy(from_val) : Qnil;
      break;
    }
    default:
      memcpy(to, from, native_slot_size(type));
  }
}

bool native_slot_eq(upb_fieldtype_t type, void* mem1, void* mem2) {
  switch (type) {
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES:
    case UPB_TYPE_MESSAGE: {
      VALUE val1 = DEREF(mem1, VALUE);
      VALUE val2 = DEREF(mem2, VALUE);
      VALUE ret = rb_funcall(val1, rb_intern("=="), 1, val2);
      return ret == Qtrue;
    }
    default:
      return !memcmp(mem1, mem2, native_slot_size(type));
  }
}

367 368 369 370
// -----------------------------------------------------------------------------
// Map field utilities.
// -----------------------------------------------------------------------------

371 372
const upb_msgdef* tryget_map_entry_msgdef(const upb_fielddef* field) {
  const upb_msgdef* subdef;
373 374
  if (upb_fielddef_label(field) != UPB_LABEL_REPEATED ||
      upb_fielddef_type(field) != UPB_TYPE_MESSAGE) {
375
    return NULL;
376
  }
377 378 379 380 381 382 383 384 385 386 387
  subdef = upb_fielddef_msgsubdef(field);
  return upb_msgdef_mapentry(subdef) ? subdef : NULL;
}

const upb_msgdef *map_entry_msgdef(const upb_fielddef* field) {
  const upb_msgdef* subdef = tryget_map_entry_msgdef(field);
  assert(subdef);
  return subdef;
}

bool is_map_field(const upb_fielddef *field) {
388 389 390 391 392 393
  const upb_msgdef* subdef = tryget_map_entry_msgdef(field);
  if (subdef == NULL) return false;

  // Map fields are a proto3 feature.
  // If we're using proto2 syntax we need to fallback to the repeated field.
  return upb_msgdef_syntax(subdef) == UPB_SYNTAX_PROTO3;
394 395 396
}

const upb_fielddef* map_field_key(const upb_fielddef* field) {
397
  const upb_msgdef* subdef = map_entry_msgdef(field);
398
  return map_entry_key(subdef);
399 400 401
}

const upb_fielddef* map_field_value(const upb_fielddef* field) {
402
  const upb_msgdef* subdef = map_entry_msgdef(field);
403 404 405 406 407 408 409 410 411 412 413
  return map_entry_value(subdef);
}

const upb_fielddef* map_entry_key(const upb_msgdef* msgdef) {
  const upb_fielddef* key_field = upb_msgdef_itof(msgdef, MAP_KEY_FIELD);
  assert(key_field != NULL);
  return key_field;
}

const upb_fielddef* map_entry_value(const upb_msgdef* msgdef) {
  const upb_fielddef* value_field = upb_msgdef_itof(msgdef, MAP_VALUE_FIELD);
414 415 416 417
  assert(value_field != NULL);
  return value_field;
}

Chris Fallin's avatar
Chris Fallin committed
418 419 420 421
// -----------------------------------------------------------------------------
// Memory layout management.
// -----------------------------------------------------------------------------

422 423 424 425 426 427
bool field_contains_hasbit(MessageLayout* layout,
                            const upb_fielddef* field) {
  return layout->fields[upb_fielddef_index(field)].hasbit !=
      MESSAGE_FIELD_NO_HASBIT;
}

428 429 430 431 432
static size_t align_up_to(size_t offset, size_t granularity) {
  // Granularity must be a power of two.
  return (offset + granularity - 1) & ~(granularity - 1);
}

Chris Fallin's avatar
Chris Fallin committed
433 434 435
MessageLayout* create_layout(const upb_msgdef* msgdef) {
  MessageLayout* layout = ALLOC(MessageLayout);
  int nfields = upb_msgdef_numfields(msgdef);
436
  upb_msg_field_iter it;
437
  upb_msg_oneof_iter oit;
Chris Fallin's avatar
Chris Fallin committed
438
  size_t off = 0;
439 440 441

  layout->fields = ALLOC_N(MessageField, nfields);

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  size_t hasbit = 0;
  for (upb_msg_field_begin(&it, msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
    const upb_fielddef* field = upb_msg_iter_field(&it);
    if (upb_fielddef_haspresence(field)) {
      layout->fields[upb_fielddef_index(field)].hasbit = hasbit++;
    } else {
      layout->fields[upb_fielddef_index(field)].hasbit =
	  MESSAGE_FIELD_NO_HASBIT;
    }
  }

  if (hasbit != 0) {
    off += (hasbit + 8 - 1) / 8;
  }

459 460 461
  for (upb_msg_field_begin(&it, msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
Chris Fallin's avatar
Chris Fallin committed
462
    const upb_fielddef* field = upb_msg_iter_field(&it);
463
    size_t field_size;
464 465 466 467 468 469 470

    if (upb_fielddef_containingoneof(field)) {
      // Oneofs are handled separately below.
      continue;
    }

    // Allocate |field_size| bytes for this field in the layout.
471
    field_size = 0;
472 473 474 475 476
    if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
      field_size = sizeof(VALUE);
    } else {
      field_size = native_slot_size(upb_fielddef_type(field));
    }
477
    // Align current offset up to |size| granularity.
478
    off = align_up_to(off, field_size);
479
    layout->fields[upb_fielddef_index(field)].offset = off;
480 481
    layout->fields[upb_fielddef_index(field)].case_offset =
        MESSAGE_FIELD_NO_CASE;
482 483 484 485 486 487 488 489 490
    off += field_size;
  }

  // Handle oneofs now -- we iterate over oneofs specifically and allocate only
  // one slot per oneof.
  //
  // We assign all value slots first, then pack the 'case' fields at the end,
  // since in the common case (modern 64-bit platform) these are 8 bytes and 4
  // bytes respectively and we want to avoid alignment overhead.
491 492 493 494 495 496 497
  //
  // Note that we reserve 4 bytes (a uint32) per 'case' slot because the value
  // space for oneof cases is conceptually as wide as field tag numbers. In
  // practice, it's unlikely that a oneof would have more than e.g. 256 or 64K
  // members (8 or 16 bits respectively), so conceivably we could assign
  // consecutive case numbers and then pick a smaller oneof case slot size, but
  // the complexity to implement this indirection is probably not worthwhile.
498 499 500 501
  for (upb_msg_oneof_begin(&oit, msgdef);
       !upb_msg_oneof_done(&oit);
       upb_msg_oneof_next(&oit)) {
    const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
502
    upb_oneof_iter fit;
503 504 505 506 507

    // Always allocate NATIVE_SLOT_MAX_SIZE bytes, but share the slot between
    // all fields.
    size_t field_size = NATIVE_SLOT_MAX_SIZE;
    // Align the offset.
508
    off = align_up_to(off, field_size);
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
    // Assign all fields in the oneof this same offset.
    for (upb_oneof_begin(&fit, oneof);
         !upb_oneof_done(&fit);
         upb_oneof_next(&fit)) {
      const upb_fielddef* field = upb_oneof_iter_field(&fit);
      layout->fields[upb_fielddef_index(field)].offset = off;
    }
    off += field_size;
  }

  // Now the case fields.
  for (upb_msg_oneof_begin(&oit, msgdef);
       !upb_msg_oneof_done(&oit);
       upb_msg_oneof_next(&oit)) {
    const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
524
    upb_oneof_iter fit;
525 526 527 528 529 530 531 532 533 534 535

    size_t field_size = sizeof(uint32_t);
    // Align the offset.
    off = (off + field_size - 1) & ~(field_size - 1);
    // Assign all fields in the oneof this same offset.
    for (upb_oneof_begin(&fit, oneof);
         !upb_oneof_done(&fit);
         upb_oneof_next(&fit)) {
      const upb_fielddef* field = upb_oneof_iter_field(&fit);
      layout->fields[upb_fielddef_index(field)].case_offset = off;
    }
Chris Fallin's avatar
Chris Fallin committed
536 537 538 539 540 541 542 543 544 545 546 547
    off += field_size;
  }

  layout->size = off;

  layout->msgdef = msgdef;
  upb_msgdef_ref(layout->msgdef, &layout->msgdef);

  return layout;
}

void free_layout(MessageLayout* layout) {
548
  xfree(layout->fields);
Chris Fallin's avatar
Chris Fallin committed
549 550 551 552
  upb_msgdef_unref(layout->msgdef, &layout->msgdef);
  xfree(layout);
}

553
VALUE field_type_class(const upb_fielddef* field) {
Chris Fallin's avatar
Chris Fallin committed
554 555 556 557 558 559 560 561 562 563 564 565 566
  VALUE type_class = Qnil;
  if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
    VALUE submsgdesc =
        get_def_obj(upb_fielddef_subdef(field));
    type_class = Descriptor_msgclass(submsgdesc);
  } else if (upb_fielddef_type(field) == UPB_TYPE_ENUM) {
    VALUE subenumdesc =
        get_def_obj(upb_fielddef_subdef(field));
    type_class = EnumDescriptor_enummodule(subenumdesc);
  }
  return type_class;
}

567 568 569 570 571 572 573 574 575 576 577 578 579 580
static void* slot_memory(MessageLayout* layout,
                         const void* storage,
                         const upb_fielddef* field) {
  return ((uint8_t *)storage) +
      layout->fields[upb_fielddef_index(field)].offset;
}

static uint32_t* slot_oneof_case(MessageLayout* layout,
                                 const void* storage,
                                 const upb_fielddef* field) {
  return (uint32_t *)(((uint8_t *)storage) +
      layout->fields[upb_fielddef_index(field)].case_offset);
}

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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
static void slot_set_hasbit(MessageLayout* layout,
                            const void* storage,
                            const upb_fielddef* field) {
  size_t hasbit = layout->fields[upb_fielddef_index(field)].hasbit;
  assert(hasbit != MESSAGE_FIELD_NO_HASBIT);

  ((uint8_t*)storage)[hasbit / 8] |= 1 << (hasbit % 8);
}

static void slot_clear_hasbit(MessageLayout* layout,
                              const void* storage,
                              const upb_fielddef* field) {
  size_t hasbit = layout->fields[upb_fielddef_index(field)].hasbit;
  assert(hasbit != MESSAGE_FIELD_NO_HASBIT);
  ((uint8_t*)storage)[hasbit / 8] &= ~(1 << (hasbit % 8));
}

static bool slot_is_hasbit_set(MessageLayout* layout,
                            const void* storage,
                            const upb_fielddef* field) {
  size_t hasbit = layout->fields[upb_fielddef_index(field)].hasbit;
  if (hasbit == MESSAGE_FIELD_NO_HASBIT) {
    return false;
  }

  return DEREF_OFFSET(
      (uint8_t*)storage, hasbit / 8, char) & (1 << (hasbit % 8));
}

VALUE layout_has(MessageLayout* layout,
                 const void* storage,
                 const upb_fielddef* field) {
  assert(field_contains_hasbit(layout, field));
  return slot_is_hasbit_set(layout, storage, field) ? Qtrue : Qfalse;
}

void layout_clear(MessageLayout* layout,
                 const void* storage,
                 const upb_fielddef* field) {
  void* memory = slot_memory(layout, storage, field);
  uint32_t* oneof_case = slot_oneof_case(layout, storage, field);

  if (field_contains_hasbit(layout, field)) {
    slot_clear_hasbit(layout, storage, field);
  }

  if (upb_fielddef_containingoneof(field)) {
    memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
    *oneof_case = ONEOF_CASE_NONE;
  } else if (is_map_field(field)) {
    VALUE map = Qnil;

    const upb_fielddef* key_field = map_field_key(field);
    const upb_fielddef* value_field = map_field_value(field);
    VALUE type_class = field_type_class(value_field);

    if (type_class != Qnil) {
      VALUE args[3] = {
        fieldtype_to_ruby(upb_fielddef_type(key_field)),
        fieldtype_to_ruby(upb_fielddef_type(value_field)),
        type_class,
      };
      map = rb_class_new_instance(3, args, cMap);
    } else {
      VALUE args[2] = {
        fieldtype_to_ruby(upb_fielddef_type(key_field)),
        fieldtype_to_ruby(upb_fielddef_type(value_field)),
      };
      map = rb_class_new_instance(2, args, cMap);
    }

    DEREF(memory, VALUE) = map;
  } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
    VALUE ary = Qnil;

    VALUE type_class = field_type_class(field);

    if (type_class != Qnil) {
      VALUE args[2] = {
        fieldtype_to_ruby(upb_fielddef_type(field)),
        type_class,
      };
      ary = rb_class_new_instance(2, args, cRepeatedField);
    } else {
      VALUE args[1] = { fieldtype_to_ruby(upb_fielddef_type(field)) };
      ary = rb_class_new_instance(1, args, cRepeatedField);
    }

    DEREF(memory, VALUE) = ary;
  } else {
671
    native_slot_set(upb_fielddef_name(field),
672 673
                    upb_fielddef_type(field), field_type_class(field),
                    memory, layout_get_default(field));
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
  }
}

VALUE layout_get_default(const upb_fielddef *field) {
  switch (upb_fielddef_type(field)) {
    case UPB_TYPE_FLOAT:   return DBL2NUM(upb_fielddef_defaultfloat(field));
    case UPB_TYPE_DOUBLE:  return DBL2NUM(upb_fielddef_defaultdouble(field));
    case UPB_TYPE_BOOL:
      return upb_fielddef_defaultbool(field) ? Qtrue : Qfalse;
    case UPB_TYPE_MESSAGE: return Qnil;
    case UPB_TYPE_ENUM: {
      const upb_enumdef *enumdef = upb_fielddef_enumsubdef(field);
      int32_t num = upb_fielddef_defaultint32(field);
      const char *label = upb_enumdef_iton(enumdef, num);
      if (label) {
        return ID2SYM(rb_intern(label));
      } else {
        return INT2NUM(num);
      }
    }
    case UPB_TYPE_INT32:   return INT2NUM(upb_fielddef_defaultint32(field));
    case UPB_TYPE_INT64:   return LL2NUM(upb_fielddef_defaultint64(field));;
    case UPB_TYPE_UINT32:  return UINT2NUM(upb_fielddef_defaultuint32(field));
    case UPB_TYPE_UINT64:  return ULL2NUM(upb_fielddef_defaultuint64(field));
    case UPB_TYPE_STRING:
    case UPB_TYPE_BYTES: {
      size_t size;
      const char *str = upb_fielddef_defaultstr(field, &size);
      VALUE str_rb = rb_str_new(str, size);

      rb_enc_associate(str_rb, (upb_fielddef_type(field) == UPB_TYPE_BYTES) ?
                 kRubyString8bitEncoding : kRubyStringUtf8Encoding);
      rb_obj_freeze(str_rb);
      return str_rb;
    }
    default: return Qnil;
  }
}
712

Chris Fallin's avatar
Chris Fallin committed
713
VALUE layout_get(MessageLayout* layout,
714
                 const void* storage,
Chris Fallin's avatar
Chris Fallin committed
715
                 const upb_fielddef* field) {
716 717
  void* memory = slot_memory(layout, storage, field);
  uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
718

719 720 721 722 723 724 725
  bool field_set;
  if (field_contains_hasbit(layout, field)) {
    field_set = slot_is_hasbit_set(layout, storage, field);
  } else {
    field_set = true;
  }

726 727
  if (upb_fielddef_containingoneof(field)) {
    if (*oneof_case != upb_fielddef_number(field)) {
728
      return layout_get_default(field);
729 730 731 732 733
    }
    return native_slot_get(upb_fielddef_type(field),
                           field_type_class(field),
                           memory);
  } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
Chris Fallin's avatar
Chris Fallin committed
734
    return *((VALUE *)memory);
735 736
  } else if (!field_set) {
    return layout_get_default(field);
Chris Fallin's avatar
Chris Fallin committed
737 738
  } else {
    return native_slot_get(upb_fielddef_type(field),
739
                           field_type_class(field),
Chris Fallin's avatar
Chris Fallin committed
740 741 742 743 744
                           memory);
  }
}

static void check_repeated_field_type(VALUE val, const upb_fielddef* field) {
745
  RepeatedField* self;
Chris Fallin's avatar
Chris Fallin committed
746 747 748 749
  assert(upb_fielddef_label(field) == UPB_LABEL_REPEATED);

  if (!RB_TYPE_P(val, T_DATA) || !RTYPEDDATA_P(val) ||
      RTYPEDDATA_TYPE(val) != &RepeatedField_type) {
750
    rb_raise(cTypeError, "Expected repeated field array");
Chris Fallin's avatar
Chris Fallin committed
751 752
  }

753
  self = ruby_to_RepeatedField(val);
Chris Fallin's avatar
Chris Fallin committed
754
  if (self->field_type != upb_fielddef_type(field)) {
755
    rb_raise(cTypeError, "Repeated field array has wrong element type");
Chris Fallin's avatar
Chris Fallin committed
756 757
  }

758
  if (self->field_type == UPB_TYPE_MESSAGE) {
Chris Fallin's avatar
Chris Fallin committed
759
    if (self->field_type_class !=
760
        Descriptor_msgclass(get_def_obj(upb_fielddef_subdef(field)))) {
761
      rb_raise(cTypeError,
762 763 764 765 766 767 768 769
               "Repeated field array has wrong message class");
    }
  }


  if (self->field_type == UPB_TYPE_ENUM) {
    if (self->field_type_class !=
        EnumDescriptor_enummodule(get_def_obj(upb_fielddef_subdef(field)))) {
770
      rb_raise(cTypeError,
771
               "Repeated field array has wrong enum class");
Chris Fallin's avatar
Chris Fallin committed
772 773 774 775
    }
  }
}

776 777 778
static void check_map_field_type(VALUE val, const upb_fielddef* field) {
  const upb_fielddef* key_field = map_field_key(field);
  const upb_fielddef* value_field = map_field_value(field);
779
  Map* self;
780 781 782

  if (!RB_TYPE_P(val, T_DATA) || !RTYPEDDATA_P(val) ||
      RTYPEDDATA_TYPE(val) != &Map_type) {
783
    rb_raise(cTypeError, "Expected Map instance");
784 785
  }

786
  self = ruby_to_Map(val);
787
  if (self->key_type != upb_fielddef_type(key_field)) {
788
    rb_raise(cTypeError, "Map key type does not match field's key type");
789 790
  }
  if (self->value_type != upb_fielddef_type(value_field)) {
791
    rb_raise(cTypeError, "Map value type does not match field's value type");
792 793 794 795 796
  }
  if (upb_fielddef_type(value_field) == UPB_TYPE_MESSAGE ||
      upb_fielddef_type(value_field) == UPB_TYPE_ENUM) {
    if (self->value_type_class !=
        get_def_obj(upb_fielddef_subdef(value_field))) {
797
      rb_raise(cTypeError,
798 799 800 801 802 803
               "Map value type has wrong message/enum class");
    }
  }
}


Chris Fallin's avatar
Chris Fallin committed
804 805 806 807
void layout_set(MessageLayout* layout,
                void* storage,
                const upb_fielddef* field,
                VALUE val) {
808 809
  void* memory = slot_memory(layout, storage, field);
  uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
810 811 812 813

  if (upb_fielddef_containingoneof(field)) {
    if (val == Qnil) {
      // Assigning nil to a oneof field clears the oneof completely.
814
      *oneof_case = ONEOF_CASE_NONE;
815 816
      memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
    } else {
817 818 819 820 821 822 823 824 825
      // The transition between field types for a single oneof (union) slot is
      // somewhat complex because we need to ensure that a GC triggered at any
      // point by a call into the Ruby VM sees a valid state for this field and
      // does not either go off into the weeds (following what it thinks is a
      // VALUE but is actually a different field type) or miss an object (seeing
      // what it thinks is a primitive field but is actually a VALUE for the new
      // field type).
      //
      // In order for the transition to be safe, the oneof case slot must be in
826 827 828 829
      // sync with the value slot whenever the Ruby VM has been called. Thus, we
      // use native_slot_set_value_and_case(), which ensures that both the value
      // and case number are altered atomically (w.r.t. the Ruby VM).
      native_slot_set_value_and_case(
830
          upb_fielddef_name(field),
831 832 833
          upb_fielddef_type(field), field_type_class(field),
          memory, val,
          oneof_case, upb_fielddef_number(field));
834 835
    }
  } else if (is_map_field(field)) {
836 837 838
    check_map_field_type(val, field);
    DEREF(memory, VALUE) = val;
  } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
Chris Fallin's avatar
Chris Fallin committed
839
    check_repeated_field_type(val, field);
840
    DEREF(memory, VALUE) = val;
Chris Fallin's avatar
Chris Fallin committed
841
  } else {
842
    native_slot_set(upb_fielddef_name(field),
843 844
                    upb_fielddef_type(field), field_type_class(field),
                    memory, val);
845 846 847 848 849
  }

  if (layout->fields[upb_fielddef_index(field)].hasbit !=
      MESSAGE_FIELD_NO_HASBIT) {
    slot_set_hasbit(layout, storage, field);
Chris Fallin's avatar
Chris Fallin committed
850 851 852 853 854
  }
}

void layout_init(MessageLayout* layout,
                 void* storage) {
855

856 857 858 859
  upb_msg_field_iter it;
  for (upb_msg_field_begin(&it, layout->msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
860
    layout_clear(layout, storage, upb_msg_iter_field(&it));
Chris Fallin's avatar
Chris Fallin committed
861 862 863 864
  }
}

void layout_mark(MessageLayout* layout, void* storage) {
865 866 867 868
  upb_msg_field_iter it;
  for (upb_msg_field_begin(&it, layout->msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
Chris Fallin's avatar
Chris Fallin committed
869
    const upb_fielddef* field = upb_msg_iter_field(&it);
870 871
    void* memory = slot_memory(layout, storage, field);
    uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
Chris Fallin's avatar
Chris Fallin committed
872

873 874 875 876 877
    if (upb_fielddef_containingoneof(field)) {
      if (*oneof_case == upb_fielddef_number(field)) {
        native_slot_mark(upb_fielddef_type(field), memory);
      }
    } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
878
      rb_gc_mark(DEREF(memory, VALUE));
Chris Fallin's avatar
Chris Fallin committed
879 880 881 882 883 884 885
    } else {
      native_slot_mark(upb_fielddef_type(field), memory);
    }
  }
}

void layout_dup(MessageLayout* layout, void* to, void* from) {
886 887 888 889
  upb_msg_field_iter it;
  for (upb_msg_field_begin(&it, layout->msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
Chris Fallin's avatar
Chris Fallin committed
890
    const upb_fielddef* field = upb_msg_iter_field(&it);
891 892 893 894 895

    void* to_memory = slot_memory(layout, to, field);
    uint32_t* to_oneof_case = slot_oneof_case(layout, to, field);
    void* from_memory = slot_memory(layout, from, field);
    uint32_t* from_oneof_case = slot_oneof_case(layout, from, field);
896 897 898 899 900 901 902

    if (upb_fielddef_containingoneof(field)) {
      if (*from_oneof_case == upb_fielddef_number(field)) {
        *to_oneof_case = *from_oneof_case;
        native_slot_dup(upb_fielddef_type(field), to_memory, from_memory);
      }
    } else if (is_map_field(field)) {
903 904 905
      DEREF(to_memory, VALUE) = Map_dup(DEREF(from_memory, VALUE));
    } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
      DEREF(to_memory, VALUE) = RepeatedField_dup(DEREF(from_memory, VALUE));
Chris Fallin's avatar
Chris Fallin committed
906
    } else {
907 908 909 910 911
      if (field_contains_hasbit(layout, field)) {
        if (!slot_is_hasbit_set(layout, from, field)) continue;
        slot_set_hasbit(layout, to, field);
      }

Chris Fallin's avatar
Chris Fallin committed
912 913 914 915 916 917
      native_slot_dup(upb_fielddef_type(field), to_memory, from_memory);
    }
  }
}

void layout_deep_copy(MessageLayout* layout, void* to, void* from) {
918 919 920 921
  upb_msg_field_iter it;
  for (upb_msg_field_begin(&it, layout->msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
Chris Fallin's avatar
Chris Fallin committed
922
    const upb_fielddef* field = upb_msg_iter_field(&it);
923 924 925 926 927

    void* to_memory = slot_memory(layout, to, field);
    uint32_t* to_oneof_case = slot_oneof_case(layout, to, field);
    void* from_memory = slot_memory(layout, from, field);
    uint32_t* from_oneof_case = slot_oneof_case(layout, from, field);
928 929 930 931 932 933 934

    if (upb_fielddef_containingoneof(field)) {
      if (*from_oneof_case == upb_fielddef_number(field)) {
        *to_oneof_case = *from_oneof_case;
        native_slot_deep_copy(upb_fielddef_type(field), to_memory, from_memory);
      }
    } else if (is_map_field(field)) {
935 936 937 938 939
      DEREF(to_memory, VALUE) =
          Map_deep_copy(DEREF(from_memory, VALUE));
    } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
      DEREF(to_memory, VALUE) =
          RepeatedField_deep_copy(DEREF(from_memory, VALUE));
Chris Fallin's avatar
Chris Fallin committed
940
    } else {
941 942 943 944 945
      if (field_contains_hasbit(layout, field)) {
        if (!slot_is_hasbit_set(layout, from, field)) continue;
        slot_set_hasbit(layout, to, field);
      }

Chris Fallin's avatar
Chris Fallin committed
946 947 948 949 950 951
      native_slot_deep_copy(upb_fielddef_type(field), to_memory, from_memory);
    }
  }
}

VALUE layout_eq(MessageLayout* layout, void* msg1, void* msg2) {
952 953 954 955
  upb_msg_field_iter it;
  for (upb_msg_field_begin(&it, layout->msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
Chris Fallin's avatar
Chris Fallin committed
956
    const upb_fielddef* field = upb_msg_iter_field(&it);
957 958 959 960 961

    void* msg1_memory = slot_memory(layout, msg1, field);
    uint32_t* msg1_oneof_case = slot_oneof_case(layout, msg1, field);
    void* msg2_memory = slot_memory(layout, msg2, field);
    uint32_t* msg2_oneof_case = slot_oneof_case(layout, msg2, field);
962 963 964 965 966 967 968 969 970 971 972 973 974 975

    if (upb_fielddef_containingoneof(field)) {
      if (*msg1_oneof_case != *msg2_oneof_case ||
          (*msg1_oneof_case == upb_fielddef_number(field) &&
           !native_slot_eq(upb_fielddef_type(field),
                           msg1_memory,
                           msg2_memory))) {
        return Qfalse;
      }
    } else if (is_map_field(field)) {
      if (!Map_eq(DEREF(msg1_memory, VALUE),
                  DEREF(msg2_memory, VALUE))) {
        return Qfalse;
      }
976
    } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
977 978 979 980
      if (!RepeatedField_eq(DEREF(msg1_memory, VALUE),
                            DEREF(msg2_memory, VALUE))) {
        return Qfalse;
      }
Chris Fallin's avatar
Chris Fallin committed
981
    } else {
982 983 984 985
      if (slot_is_hasbit_set(layout, msg1, field) !=
	  slot_is_hasbit_set(layout, msg2, field) ||
          !native_slot_eq(upb_fielddef_type(field),
			  msg1_memory, msg2_memory)) {
Chris Fallin's avatar
Chris Fallin committed
986 987 988 989 990 991 992 993
        return Qfalse;
      }
    }
  }
  return Qtrue;
}

VALUE layout_hash(MessageLayout* layout, void* storage) {
994
  upb_msg_field_iter it;
Chris Fallin's avatar
Chris Fallin committed
995 996
  st_index_t h = rb_hash_start(0);
  VALUE hash_sym = rb_intern("hash");
997 998 999
  for (upb_msg_field_begin(&it, layout->msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
Chris Fallin's avatar
Chris Fallin committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    const upb_fielddef* field = upb_msg_iter_field(&it);
    VALUE field_val = layout_get(layout, storage, field);
    h = rb_hash_uint(h, NUM2LONG(rb_funcall(field_val, hash_sym, 0)));
  }
  h = rb_hash_end(h);

  return INT2FIX(h);
}

VALUE layout_inspect(MessageLayout* layout, void* storage) {
  VALUE str = rb_str_new2("");

1012
  upb_msg_field_iter it;
Chris Fallin's avatar
Chris Fallin committed
1013
  bool first = true;
1014 1015 1016
  for (upb_msg_field_begin(&it, layout->msgdef);
       !upb_msg_field_done(&it);
       upb_msg_field_next(&it)) {
Chris Fallin's avatar
Chris Fallin committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    const upb_fielddef* field = upb_msg_iter_field(&it);
    VALUE field_val = layout_get(layout, storage, field);

    if (!first) {
      str = rb_str_cat2(str, ", ");
    } else {
      first = false;
    }
    str = rb_str_cat2(str, upb_fielddef_name(field));
    str = rb_str_cat2(str, ": ");

    str = rb_str_append(str, rb_funcall(field_val, rb_intern("inspect"), 0));
  }

  return str;
}