text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 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.

#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__

#include <google/protobuf/generated_message_table_driven.h>

#include <google/protobuf/stubs/type_traits.h>

#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/wire_format_lite_inl.h>

namespace google {
namespace protobuf {
namespace internal {

enum StringType {
  StringType_STRING = 0,
  StringType_CORD = 1,
  StringType_STRING_PIECE = 2
};

// Logically a superset of StringType, consisting of all field types that
// require special initialization.
enum ProcessingType {
  ProcessingType_STRING = 0,
  ProcessingType_CORD = 1,
  ProcessingType_STRING_PIECE = 2,
  ProcessingType_MESSAGE = 3
};

enum Cardinality {
  Cardinality_SINGULAR = 0,
  Cardinality_REPEATED = 1,
  Cardinality_ONEOF = 3
};

template <typename Type>
inline Type* Raw(MessageLite* msg, int64 offset) {
  return reinterpret_cast<Type*>(reinterpret_cast<uint8*>(msg) + offset);
}

template <typename Type>
inline const Type* Raw(const MessageLite* msg, int64 offset) {
  return reinterpret_cast<const Type*>(reinterpret_cast<const uint8*>(msg) +
                                       offset);
}

template <typename InternalMetadata>
inline Arena* GetArena(MessageLite* msg, int64 arena_offset) {
  if (GOOGLE_PREDICT_FALSE(arena_offset == -1)) {
    return NULL;
  }

  return Raw<InternalMetadata>(msg, arena_offset)->arena();
}

inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64 extension_offset) {
  if (extension_offset == -1) {
    return NULL;
  }

  return Raw<ExtensionSet>(msg, extension_offset);
}

template <typename Type>
inline Type* AddField(MessageLite* msg, int64 offset) {
#if LANG_CXX11
  static_assert(has_trivial_copy<Type>::value,
                "Do not assign");
#endif

  google::protobuf::RepeatedField<Type>* repeated =
      Raw<google::protobuf::RepeatedField<Type> >(msg, offset);
  return repeated->Add();
}

template <>
inline string* AddField<string>(MessageLite* msg, int64 offset) {
  google::protobuf::RepeatedPtrField<string>* repeated =
      Raw<google::protobuf::RepeatedPtrField<string> >(msg, offset);
  return repeated->Add();
}

template <typename Type>
inline void AddField(MessageLite* msg, int64 offset, Type value) {
#if LANG_CXX11
  static_assert(has_trivial_copy<Type>::value,
                "Do not assign");
#endif
  *AddField<Type>(msg, offset) = value;
}

inline void SetBit(uint32* has_bits, uint32 has_bit_index) {
  GOOGLE_DCHECK(has_bits != NULL);

  uint32 mask = static_cast<uint32>(1u) << (has_bit_index % 32);
  has_bits[has_bit_index / 32u] |= mask;
}

template <typename Type>
inline Type* MutableField(MessageLite* msg, uint32* has_bits,
                          uint32 has_bit_index, int64 offset) {
  SetBit(has_bits, has_bit_index);
  return Raw<Type>(msg, offset);
}

template <typename Type>
inline void SetField(MessageLite* msg, uint32* has_bits, uint32 has_bit_index,
                     int64 offset, Type value) {
#if LANG_CXX11
  static_assert(has_trivial_copy<Type>::value,
                "Do not assign");
#endif
  *MutableField<Type>(msg, has_bits, has_bit_index, offset) = value;
}

template <typename Type>
inline void SetOneofField(MessageLite* msg, uint32* oneof_case,
                          uint32 oneof_case_index, int64 offset,
                          int field_number, Type value) {
  oneof_case[oneof_case_index] = field_number;
  *Raw<Type>(msg, offset) = value;
}

// Clears a oneof field. The field argument should correspond to the particular
// field that is currently set in the oneof.
inline void ClearOneofField(const ParseTableField& field, Arena* arena,
                     MessageLite* msg) {
  switch (field.processing_type & kTypeMask) {
    case WireFormatLite::TYPE_MESSAGE:
      if (arena == NULL) {
        delete *Raw<MessageLite*>(msg, field.offset);
      }
      break;

    case WireFormatLite::TYPE_STRING:
    case WireFormatLite::TYPE_BYTES:
      Raw<ArenaStringPtr>(msg, field.offset)
          ->Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
      break;

    default:
      // No cleanup needed.
      break;
  }
}

// Clears and reinitializes a oneof field as necessary, in preparation for
// parsing a new value with type field_type and field number field_number.
//
// Note: the oneof_case argument should point directly to the _oneof_case_
// element corresponding to this particular oneof, not to the beginning of the
// _oneof_case_ array.
template <ProcessingType field_type>
inline void ResetOneofField(const ParseTable& table, int field_number,
                            Arena* arena, MessageLite* msg, uint32* oneof_case,
                            int64 offset, const void* default_ptr) {
  if (*oneof_case == field_number) {
    // The oneof is already set to the right type, so there is no need to clear
    // it.
    return;
  }

  if (*oneof_case != 0) {
    ClearOneofField(table.fields[*oneof_case], arena, msg);
  }
  *oneof_case = field_number;

  switch (field_type) {
    case ProcessingType_STRING:
      Raw<ArenaStringPtr>(msg, offset)
          ->UnsafeSetDefault(static_cast<const string*>(default_ptr));
      break;
    case ProcessingType_MESSAGE:
      MessageLite** submessage = Raw<MessageLite*>(msg, offset);
      const MessageLite* prototype =
          table.aux[field_number].messages.default_message();
      *submessage = prototype->New(arena);
      break;
  }
}

template <Cardinality cardinality, bool validate, StringType ctype>
static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg,
                                Arena* arena, uint32* has_bits,
                                uint32 has_bit_index, int64 offset,
                                const void* default_ptr,
                                const char* field_name) {
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  const char* sdata;
  size_t size;
#endif

    string* value;
    switch (cardinality) {
      case Cardinality_SINGULAR:
        // TODO(ckennelly): Is this optimal?
        value =
            MutableField<ArenaStringPtr>(msg, has_bits, has_bit_index, offset)
                ->Mutable(static_cast<const string*>(default_ptr), arena);
        break;
      case Cardinality_REPEATED:
        value = AddField<string>(msg, offset);
        break;
      case Cardinality_ONEOF:
        value = Raw<ArenaStringPtr>(msg, offset)
                    ->Mutable(static_cast<const string*>(default_ptr), arena);
        break;
    }
    GOOGLE_DCHECK(value != NULL);

    if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
      return false;
    }

#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
    sdata = value->data();
    size = value->size();
#endif

#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  if (validate) {
    WireFormatLite::VerifyUtf8String(sdata, size, WireFormatLite::PARSE,
                                     field_name);
  }
#endif

  return true;
}

template <typename UnknownFieldHandler, typename InternalMetadata,
          Cardinality cardinality>
inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input,
                       MessageLite* msg, uint32* presence,
                       uint32 presence_index, int64 offset, uint32 tag,
                       int field_number) {
  int value;
  if (GOOGLE_PREDICT_FALSE(
          (!WireFormatLite::ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(
              input, &value)))) {
    return false;
  }

  AuxillaryParseTableField::EnumValidator validator =
      table.aux[field_number].enums.validator;
  if (validator(value)) {
    switch (cardinality) {
      case Cardinality_SINGULAR:
        SetField(msg, presence, presence_index, offset, value);
        break;
      case Cardinality_REPEATED:
        AddField(msg, offset, value);
        break;
      case Cardinality_ONEOF:
        ClearOneofField(table.fields[presence[presence_index]],
                        GetArena<InternalMetadata>(msg, table.arena_offset),
                        msg);
        SetOneofField(msg, presence, presence_index, offset, field_number,
                      value);
        break;
    }
  } else {
    UnknownFieldHandler::Varint(msg, table, tag, value);
  }

  return true;
}

// RepeatedMessageTypeHandler allows us to operate on RepeatedPtrField fields
// without instantiating the specific template.
class RepeatedMessageTypeHandler {
 public:
  typedef MessageLite Type;
  static Arena* GetArena(Type* t) { return t->GetArena(); }
  static void* GetMaybeArenaPointer(Type* t) {
    return t->GetMaybeArenaPointer();
  }
  static inline Type* NewFromPrototype(const Type* prototype,
                                       Arena* arena = NULL) {
    return prototype->New(arena);
  }
  static void Delete(Type* t, Arena* arena = NULL) {
    if (arena == NULL) {
      delete t;
    }
  }
};

inline bool ReadGroup(int field_number, io::CodedInputStream* input,
                      MessageLite* value) {
  if (GOOGLE_PREDICT_FALSE(!input->IncrementRecursionDepth())) {
    return false;
  }

  if (GOOGLE_PREDICT_FALSE(!value->MergePartialFromCodedStream(input))) {
    return false;
  }

  input->DecrementRecursionDepth();
  // Make sure the last thing read was an end tag for this group.
  if (GOOGLE_PREDICT_FALSE(!input->LastTagWas(WireFormatLite::MakeTag(
          field_number, WireFormatLite::WIRETYPE_END_GROUP)))) {
    return false;
  }

  return true;
}

inline bool ReadMessage(io::CodedInputStream* input, MessageLite* value) {
  int length;
  if (GOOGLE_PREDICT_FALSE(!input->ReadVarintSizeAsInt(&length))) {
    return false;
  }

  std::pair<io::CodedInputStream::Limit, int> p =
      input->IncrementRecursionDepthAndPushLimit(length);
  if (GOOGLE_PREDICT_FALSE(p.second < 0 ||
                    !value->MergePartialFromCodedStream(input))) {
    return false;
  }

  // Make sure that parsing stopped when the limit was hit, not at an endgroup
  // tag.
  return input->DecrementRecursionDepthAndPopLimit(p.first);
}

class MergePartialFromCodedStreamHelper {
 public:
  static MessageLite* Add(RepeatedPtrFieldBase* field,
                          const MessageLite* prototype) {
    return field->Add<RepeatedMessageTypeHandler>(
        const_cast<MessageLite*>(prototype));
  }
};

template <typename UnknownFieldHandler, typename InternalMetadata>
bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
                                     io::CodedInputStream* input) {
  // We require that has_bits are present, as to avoid having to check for them
  // for every field.
  //
  // TODO(ckennelly):  Make this a compile-time parameter with templates.
  GOOGLE_DCHECK_GE(table.has_bits_offset, 0);
  uint32* has_bits = Raw<uint32>(msg, table.has_bits_offset);
  GOOGLE_DCHECK(has_bits != NULL);

  while (true) {
    uint32 tag = input->ReadTag();

    const WireFormatLite::WireType wire_type =
        WireFormatLite::GetTagWireType(tag);
    const int field_number = WireFormatLite::GetTagFieldNumber(tag);

    if (field_number > table.max_field_number) {
      // check for possible extensions
      if (UnknownFieldHandler::ParseExtension(msg, table, input, tag)) {
        // successfully parsed
        continue;
      }

      if (GOOGLE_PREDICT_FALSE(!UnknownFieldHandler::Skip(msg, table, input, tag))) {
        return false;
      }

      continue;
    }

    // We implicitly verify that data points to a valid field as we check the
    // wire types.  Entries in table.fields[i] that do not correspond to valid
    // field numbers have their normal_wiretype and packed_wiretype fields set
    // with the kInvalidMask value.  As wire_type cannot take on that value, we
    // will never match.
    const ParseTableField* data = table.fields + field_number;

    // TODO(ckennelly): Avoid sign extension
    const int64 presence_index = data->presence_index;
    const int64 offset = data->offset;
    const unsigned char processing_type = data->processing_type;

    if (data->normal_wiretype == static_cast<unsigned char>(wire_type)) {
      // TODO(ckennelly): Use a computed goto on GCC/LLVM or otherwise eliminate
      // the bounds check on processing_type.

      switch (processing_type) {
#define HANDLE_TYPE(TYPE, CPPTYPE)                                             \
  case (WireFormatLite::TYPE_##TYPE): {                                        \
    CPPTYPE value;                                                             \
    if (GOOGLE_PREDICT_FALSE(                                                         \
            (!WireFormatLite::ReadPrimitive<                                   \
                CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) {      \
      return false;                                                            \
    }                                                                          \
    SetField(msg, has_bits, presence_index, offset, value);                    \
    break;                                                                     \
  }                                                                            \
  case (WireFormatLite::TYPE_##TYPE) | kRepeatedMask: {                        \
    google::protobuf::RepeatedField<CPPTYPE>* values =                                   \
        Raw<google::protobuf::RepeatedField<CPPTYPE> >(msg, offset);                     \
    if (GOOGLE_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive<                 \
                       CPPTYPE, WireFormatLite::TYPE_##TYPE>(                  \
            data->tag_size, tag, input, values)))) {                           \
      return false;                                                            \
    }                                                                          \
    break;                                                                     \
  }                                                                            \
  case (WireFormatLite::TYPE_##TYPE) | kOneofMask: {                           \
    uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);            \
    CPPTYPE value;                                                             \
    if (GOOGLE_PREDICT_FALSE(                                                         \
            (!WireFormatLite::ReadPrimitive<                                   \
                CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) {      \
      return false;                                                            \
    }                                                                          \
    ClearOneofField(table.fields[oneof_case[presence_index]],                  \
                    GetArena<InternalMetadata>(msg, table.arena_offset), msg); \
    SetOneofField(msg, oneof_case, presence_index, offset, field_number,       \
                  value);                                                      \
    break;                                                                     \
  }

        HANDLE_TYPE(INT32, int32)
        HANDLE_TYPE(INT64, int64)
        HANDLE_TYPE(SINT32, int32)
        HANDLE_TYPE(SINT64, int64)
        HANDLE_TYPE(UINT32, uint32)
        HANDLE_TYPE(UINT64, uint64)

        HANDLE_TYPE(FIXED32, uint32)
        HANDLE_TYPE(FIXED64, uint64)
        HANDLE_TYPE(SFIXED32, int32)
        HANDLE_TYPE(SFIXED64, int64)

        HANDLE_TYPE(FLOAT, float)
        HANDLE_TYPE(DOUBLE, double)

        HANDLE_TYPE(BOOL, bool)
#undef HANDLE_TYPE
        case WireFormatLite::TYPE_BYTES:
#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
        case WireFormatLite::TYPE_STRING:
#endif
        {
          Arena* const arena =
              GetArena<InternalMetadata>(msg, table.arena_offset);
          const void* default_ptr = table.aux[field_number].strings.default_ptr;

          if (GOOGLE_PREDICT_FALSE((
                  !HandleString<Cardinality_SINGULAR, false, StringType_STRING>(
                      input, msg, arena, has_bits, presence_index, offset,
                      default_ptr, NULL)))) {
            return false;
          }
          break;
        }
        case WireFormatLite::TYPE_BYTES | kOneofMask:
#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
        case WireFormatLite::TYPE_STRING | kOneofMask:
#endif
        {
          Arena* const arena =
              GetArena<InternalMetadata>(msg, table.arena_offset);
          uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
          const void* default_ptr = table.aux[field_number].strings.default_ptr;

          ResetOneofField<ProcessingType_STRING>(
              table, field_number, arena, msg, oneof_case + presence_index,
              offset, default_ptr);

          if (GOOGLE_PREDICT_FALSE(
                  (!HandleString<Cardinality_ONEOF, false, StringType_STRING>(
                      input, msg, arena, has_bits, presence_index, offset,
                      default_ptr, NULL)))) {
            return false;
          }
          break;
        }
        case (WireFormatLite::TYPE_BYTES) | kRepeatedMask:
#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
        case (WireFormatLite::TYPE_STRING) | kRepeatedMask:
#endif
        {
          Arena* const arena =
              GetArena<InternalMetadata>(msg, table.arena_offset);
          const void* default_ptr =
              table.aux[field_number].strings.default_ptr;

          if (GOOGLE_PREDICT_FALSE((
                  !HandleString<Cardinality_REPEATED, false, StringType_STRING>(
                      input, msg, arena, has_bits, presence_index, offset,
                      default_ptr, NULL)))) {
            return false;
          }
          break;
        }
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
        case (WireFormatLite::TYPE_STRING): {
          Arena* const arena =
              GetArena<InternalMetadata>(msg, table.arena_offset);
          const void* default_ptr = table.aux[field_number].strings.default_ptr;
          const char* field_name = table.aux[field_number].strings.field_name;

          if (GOOGLE_PREDICT_FALSE(
                  (!HandleString<Cardinality_SINGULAR, true, StringType_STRING>(
                      input, msg, arena, has_bits, presence_index, offset,
                      default_ptr, field_name)))) {
            return false;
          }
          break;
        }
        case (WireFormatLite::TYPE_STRING) | kRepeatedMask: {
          Arena* const arena =
              GetArena<InternalMetadata>(msg, table.arena_offset);
          const void* default_ptr = table.aux[field_number].strings.default_ptr;
          const char* field_name = table.aux[field_number].strings.field_name;

          if (GOOGLE_PREDICT_FALSE(
                  (!HandleString<Cardinality_REPEATED, true, StringType_STRING>(
                      input, msg, arena, has_bits, presence_index, offset,
                      default_ptr, field_name)))) {
            return false;
          }
          break;
        }
        case (WireFormatLite::TYPE_STRING) | kOneofMask: {
          Arena* const arena =
              GetArena<InternalMetadata>(msg, table.arena_offset);
          uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
          const void* default_ptr = table.aux[field_number].strings.default_ptr;
          const char* field_name = table.aux[field_number].strings.field_name;

          ResetOneofField<ProcessingType_STRING>(
              table, field_number, arena, msg, oneof_case + presence_index,
              offset, default_ptr);

          if (GOOGLE_PREDICT_FALSE(
                  (!HandleString<Cardinality_ONEOF, true, StringType_STRING>(
                      input, msg, arena, has_bits, presence_index, offset,
                      default_ptr, field_name)))) {
            return false;
          }
          break;
        }
#endif
        case WireFormatLite::TYPE_ENUM: {
          if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
                                         Cardinality_SINGULAR>(
                  table, input, msg, has_bits, presence_index, offset, tag,
                  field_number)))) {
            return false;
          }
          break;
        }
        case WireFormatLite::TYPE_ENUM | kRepeatedMask: {
          if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
                                         Cardinality_REPEATED>(
                  table, input, msg, has_bits, presence_index, offset, tag,
                  field_number)))) {
            return false;
          }
          break;
        }
        case WireFormatLite::TYPE_ENUM | kOneofMask: {
          uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
          if (GOOGLE_PREDICT_FALSE((!HandleEnum<UnknownFieldHandler, InternalMetadata,
                                         Cardinality_ONEOF>(
                  table, input, msg, oneof_case, presence_index, offset, tag,
                  field_number)))) {
            return false;
          }
          break;
        }
        case WireFormatLite::TYPE_GROUP: {
          MessageLite** submsg_holder =
              MutableField<MessageLite*>(msg, has_bits, presence_index, offset);
          MessageLite* submsg = *submsg_holder;

          if (submsg == NULL) {
            Arena* const arena =
                GetArena<InternalMetadata>(msg, table.arena_offset);
            const MessageLite* prototype =
                table.aux[field_number].messages.default_message();
            submsg = prototype->New(arena);
            *submsg_holder = submsg;
          }

          if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadGroup(
              field_number, input, submsg))) {
            return false;
          }

          break;
        }
        case WireFormatLite::TYPE_GROUP | kRepeatedMask: {
          RepeatedPtrFieldBase* field = Raw<RepeatedPtrFieldBase>(msg, offset);
          const MessageLite* prototype =
              table.aux[field_number].messages.default_message();
          GOOGLE_DCHECK(prototype != NULL);

          MessageLite* submsg =
              MergePartialFromCodedStreamHelper::Add(field, prototype);

          if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadGroup(
              field_number, input, submsg))) {
            return false;
          }

          break;
        }
        case WireFormatLite::TYPE_MESSAGE: {
          MessageLite** submsg_holder =
              MutableField<MessageLite*>(msg, has_bits, presence_index, offset);
          MessageLite* submsg = *submsg_holder;

          if (submsg == NULL) {
            Arena* const arena =
                GetArena<InternalMetadata>(msg, table.arena_offset);
            const MessageLite* prototype =
                table.aux[field_number].messages.default_message();
            submsg = prototype->New(arena);
            *submsg_holder = submsg;
          }

          if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
            return false;
          }

          break;
        }
        // TODO(ckennelly):  Adapt ReadMessageNoVirtualNoRecursionDepth and
        // manage input->IncrementRecursionDepth() here.
        case WireFormatLite::TYPE_MESSAGE | kRepeatedMask: {
          RepeatedPtrFieldBase* field = Raw<RepeatedPtrFieldBase>(msg, offset);
          const MessageLite* prototype =
              table.aux[field_number].messages.default_message();
          GOOGLE_DCHECK(prototype != NULL);

          MessageLite* submsg =
              MergePartialFromCodedStreamHelper::Add(field, prototype);

          if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
            return false;
          }

          break;
        }
        case WireFormatLite::TYPE_MESSAGE | kOneofMask: {
          Arena* const arena =
              GetArena<InternalMetadata>(msg, table.arena_offset);
          uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
          MessageLite** submsg_holder = Raw<MessageLite*>(msg, offset);
          ResetOneofField<ProcessingType_MESSAGE>(
              table, field_number, arena, msg, oneof_case + presence_index,
              offset, NULL);
          MessageLite* submsg = *submsg_holder;

          if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
            return false;
          }

          break;
        }
        case TYPE_MAP: {
          if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)(
                  input, Raw<void>(msg, offset)))) {
            return false;
          }
          break;
        }
        case 0: {
          // Done.
          return true;
        }
        default:
          break;
      }
    } else if (data->packed_wiretype == static_cast<unsigned char>(wire_type)) {
      // Non-packable fields have their packed_wiretype masked with
      // kNotPackedMask, which is impossible to match here.
      GOOGLE_DCHECK(processing_type & kRepeatedMask);
      GOOGLE_DCHECK_NE(processing_type, kRepeatedMask);
      GOOGLE_DCHECK_EQ(0, processing_type & kOneofMask);

      // TODO(ckennelly): Use a computed goto on GCC/LLVM.
      //
      // Mask out kRepeatedMask bit, allowing the jump table to be smaller.
      switch (static_cast<WireFormatLite::FieldType>(
          processing_type ^ kRepeatedMask)) {
#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD)                 \
  case WireFormatLite::TYPE_##TYPE: {                                     \
    google::protobuf::RepeatedField<CPPTYPE>* values =                              \
        Raw<google::protobuf::RepeatedField<CPPTYPE> >(msg, offset);                \
    if (GOOGLE_PREDICT_FALSE(                                                    \
            (!WireFormatLite::ReadPackedPrimitive<                        \
                CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, values)))) { \
      return false;                                                       \
    }                                                                     \
    break;                                                                \
  }

        HANDLE_PACKED_TYPE(INT32, int32, Int32)
        HANDLE_PACKED_TYPE(INT64, int64, Int64)
        HANDLE_PACKED_TYPE(SINT32, int32, Int32)
        HANDLE_PACKED_TYPE(SINT64, int64, Int64)
        HANDLE_PACKED_TYPE(UINT32, uint32, UInt32)
        HANDLE_PACKED_TYPE(UINT64, uint64, UInt64)

        HANDLE_PACKED_TYPE(FIXED32, uint32, UInt32)
        HANDLE_PACKED_TYPE(FIXED64, uint64, UInt64)
        HANDLE_PACKED_TYPE(SFIXED32, int32, Int32)
        HANDLE_PACKED_TYPE(SFIXED64, int64, Int64)

        HANDLE_PACKED_TYPE(FLOAT, float, Float)
        HANDLE_PACKED_TYPE(DOUBLE, double, Double)

        HANDLE_PACKED_TYPE(BOOL, bool, Bool)
#undef HANDLE_PACKED_TYPE
        case WireFormatLite::TYPE_ENUM: {
          // To avoid unnecessarily calling MutableUnknownFields (which mutates
          // InternalMetadataWithArena) when all inputs in the repeated series
          // are valid, we implement our own parser rather than call
          // WireFormat::ReadPackedEnumPreserveUnknowns.
          uint32 length;
          if (GOOGLE_PREDICT_FALSE(!input->ReadVarint32(&length))) {
            return false;
          }

          AuxillaryParseTableField::EnumValidator validator =
              table.aux[field_number].enums.validator;
          google::protobuf::RepeatedField<int>* values =
              Raw<google::protobuf::RepeatedField<int> >(msg, offset);

          io::CodedInputStream::Limit limit = input->PushLimit(length);
          while (input->BytesUntilLimit() > 0) {
            int value;
            if (GOOGLE_PREDICT_FALSE(
                    (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
                        int, WireFormatLite::TYPE_ENUM>(input, &value)))) {
              return false;
            }

            if (validator(value)) {
              values->Add(value);
            } else {
              // TODO(ckennelly): Consider caching here.
              UnknownFieldHandler::Varint(msg, table, tag, value);
            }
          }
          input->PopLimit(limit);

          break;
        }
        case WireFormatLite::TYPE_STRING:
        case WireFormatLite::TYPE_GROUP:
        case WireFormatLite::TYPE_MESSAGE:
        case WireFormatLite::TYPE_BYTES:
          GOOGLE_DCHECK(false);
          return false;
        default:
          break;
      }
    } else {
      if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) {
        // Must be the end of the message.
        return true;
      }

      // check for possible extensions
      if (UnknownFieldHandler::ParseExtension(msg, table, input, tag)) {
        // successfully parsed
        continue;
      }

      // process unknown field.
      if (GOOGLE_PREDICT_FALSE(!UnknownFieldHandler::Skip(msg, table, input, tag))) {
        return false;
      }
    }
  }
}

}  // namespace internal
}  // namespace protobuf

}  // namespace google
#endif  // GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_LITE_H__

mime_type: text/plain


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 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.

// Author: kenton@google.com (Kenton Varda)

#include <string>
#include <iostream>

#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/arena_test_util.h>
#include <google/protobuf/map_lite_test_util.h>
#include <google/protobuf/map_lite_unittest.pb.h>
#include <google/protobuf/test_util_lite.h>
#include <google/protobuf/unittest_lite.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <gtest/gtest.h>

#include <google/protobuf/stubs/strutil.h>

using std::string;

namespace {
// Helper methods to test parsing merge behavior.
void ExpectMessageMerged(const google::protobuf::unittest::TestAllTypesLite& message) {
  EXPECT_EQ(message.optional_int32(), 3);
  EXPECT_EQ(message.optional_int64(), 2);
  EXPECT_EQ(message.optional_string(), "hello");
}

void AssignParsingMergeMessages(
    google::protobuf::unittest::TestAllTypesLite* msg1,
    google::protobuf::unittest::TestAllTypesLite* msg2,
    google::protobuf::unittest::TestAllTypesLite* msg3) {
  msg1->set_optional_int32(1);
  msg2->set_optional_int64(2);
  msg3->set_optional_int32(3);
  msg3->set_optional_string("hello");
}

void SetAllTypesInEmptyMessageUnknownFields(
    google::protobuf::unittest::TestEmptyMessageLite* empty_message) {
  protobuf_unittest::TestAllTypesLite message;
  google::protobuf::TestUtilLite::ExpectClear(message);
  google::protobuf::TestUtilLite::SetAllFields(&message);
  string data = message.SerializeAsString();
  empty_message->ParseFromString(data);
}

void SetSomeTypesInEmptyMessageUnknownFields(
    google::protobuf::unittest::TestEmptyMessageLite* empty_message) {
  protobuf_unittest::TestAllTypesLite message;
  google::protobuf::TestUtilLite::ExpectClear(message);
  message.set_optional_int32(101);
  message.set_optional_int64(102);
  message.set_optional_uint32(103);
  message.set_optional_uint64(104);
  string data = message.SerializeAsString();
  empty_message->ParseFromString(data);
}

}  // namespace

TEST(Lite, AllLite1) {
  string data;

  {
    protobuf_unittest::TestAllTypesLite message, message2, message3;
    google::protobuf::TestUtilLite::ExpectClear(message);
    google::protobuf::TestUtilLite::SetAllFields(&message);
    message2.CopyFrom(message);
    data = message.SerializeAsString();
    message3.ParseFromString(data);
    google::protobuf::TestUtilLite::ExpectAllFieldsSet(message);
    google::protobuf::TestUtilLite::ExpectAllFieldsSet(message2);
    google::protobuf::TestUtilLite::ExpectAllFieldsSet(message3);
    google::protobuf::TestUtilLite::ModifyRepeatedFields(&message);
    google::protobuf::TestUtilLite::ExpectRepeatedFieldsModified(message);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectClear(message);
  }
}

TEST(Lite, AllLite2) {
  string data;
  {
    protobuf_unittest::TestAllExtensionsLite message, message2, message3;
    google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
    google::protobuf::TestUtilLite::SetAllExtensions(&message);
    message2.CopyFrom(message);
    string extensions_data = message.SerializeAsString();
    message3.ParseFromString(extensions_data);
    google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message);
    google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message2);
    google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message3);
    google::protobuf::TestUtilLite::ModifyRepeatedExtensions(&message);
    google::protobuf::TestUtilLite::ExpectRepeatedExtensionsModified(message);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
  }
}

TEST(Lite, AllLite3) {
  string data, packed_data;

  {
    protobuf_unittest::TestPackedTypesLite message, message2, message3;
    google::protobuf::TestUtilLite::ExpectPackedClear(message);
    google::protobuf::TestUtilLite::SetPackedFields(&message);
    message2.CopyFrom(message);
    packed_data = message.SerializeAsString();
    message3.ParseFromString(packed_data);
    google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message);
    google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message2);
    google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message3);
    google::protobuf::TestUtilLite::ModifyPackedFields(&message);
    google::protobuf::TestUtilLite::ExpectPackedFieldsModified(message);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectPackedClear(message);
  }

  {
    protobuf_unittest::TestPackedExtensionsLite message, message2, message3;
    google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
    google::protobuf::TestUtilLite::SetPackedExtensions(&message);
    message2.CopyFrom(message);
    string packed_extensions_data = message.SerializeAsString();
    EXPECT_EQ(packed_extensions_data, packed_data);
    message3.ParseFromString(packed_extensions_data);
    google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message);
    google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2);
    google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message3);
    google::protobuf::TestUtilLite::ModifyPackedExtensions(&message);
    google::protobuf::TestUtilLite::ExpectPackedExtensionsModified(message);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
  }
}

TEST(Lite, AllLite5) {
  string data;

  {
    // Test that if an optional or required message/group field appears multiple
    // times in the input, they need to be merged.
    google::protobuf::unittest::TestParsingMergeLite::RepeatedFieldsGenerator generator;
    google::protobuf::unittest::TestAllTypesLite* msg1;
    google::protobuf::unittest::TestAllTypesLite* msg2;
    google::protobuf::unittest::TestAllTypesLite* msg3;

#define ASSIGN_REPEATED_FIELD(FIELD)                \
  msg1 = generator.add_##FIELD();                   \
  msg2 = generator.add_##FIELD();                   \
  msg3 = generator.add_##FIELD();                   \
  AssignParsingMergeMessages(msg1, msg2, msg3)

    ASSIGN_REPEATED_FIELD(field1);
    ASSIGN_REPEATED_FIELD(field2);
    ASSIGN_REPEATED_FIELD(field3);
    ASSIGN_REPEATED_FIELD(ext1);
    ASSIGN_REPEATED_FIELD(ext2);

#undef ASSIGN_REPEATED_FIELD
#define ASSIGN_REPEATED_GROUP(FIELD)                \
  msg1 = generator.add_##FIELD()->mutable_field1(); \
  msg2 = generator.add_##FIELD()->mutable_field1(); \
  msg3 = generator.add_##FIELD()->mutable_field1(); \
  AssignParsingMergeMessages(msg1, msg2, msg3)

    ASSIGN_REPEATED_GROUP(group1);
    ASSIGN_REPEATED_GROUP(group2);

#undef ASSIGN_REPEATED_GROUP

    string buffer;
    generator.SerializeToString(&buffer);
    google::protobuf::unittest::TestParsingMergeLite parsing_merge;
    parsing_merge.ParseFromString(buffer);

    // Required and optional fields should be merged.
    ExpectMessageMerged(parsing_merge.required_all_types());
    ExpectMessageMerged(parsing_merge.optional_all_types());
    ExpectMessageMerged(
        parsing_merge.optionalgroup().optional_group_all_types());
    ExpectMessageMerged(parsing_merge.GetExtension(
        google::protobuf::unittest::TestParsingMergeLite::optional_ext));

    // Repeated fields should not be merged.
    EXPECT_EQ(parsing_merge.repeated_all_types_size(), 3);
    EXPECT_EQ(parsing_merge.repeatedgroup_size(), 3);
    EXPECT_EQ(parsing_merge.ExtensionSize(
                  google::protobuf::unittest::TestParsingMergeLite::repeated_ext),
              3);
  }
}

TEST(Lite, AllLite6) {
  string data;

  // Test unknown fields support for lite messages.
  {
    protobuf_unittest::TestAllTypesLite message, message2;
    protobuf_unittest::TestEmptyMessageLite empty_message;
    google::protobuf::TestUtilLite::ExpectClear(message);
    google::protobuf::TestUtilLite::SetAllFields(&message);
    data = message.SerializeAsString();
    empty_message.ParseFromString(data);
    data.clear();
    data = empty_message.SerializeAsString();
    message2.ParseFromString(data);
    data = message2.SerializeAsString();
    google::protobuf::TestUtilLite::ExpectAllFieldsSet(message2);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectClear(message);
  }
}

TEST(Lite, AllLite7) {
  string data;

  {
    protobuf_unittest::TestAllExtensionsLite message, message2;
    protobuf_unittest::TestEmptyMessageLite empty_message;
    google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
    google::protobuf::TestUtilLite::SetAllExtensions(&message);
    data = message.SerializeAsString();
    empty_message.ParseFromString(data);
    data.clear();
    data = empty_message.SerializeAsString();
    message2.ParseFromString(data);
    data = message2.SerializeAsString();
    google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message2);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
  }
}

TEST(Lite, AllLite8) {
  string data;

  {
    protobuf_unittest::TestPackedTypesLite message, message2;
    protobuf_unittest::TestEmptyMessageLite empty_message;
    google::protobuf::TestUtilLite::ExpectPackedClear(message);
    google::protobuf::TestUtilLite::SetPackedFields(&message);
    data = message.SerializeAsString();
    empty_message.ParseFromString(data);
    data.clear();
    data = empty_message.SerializeAsString();
    message2.ParseFromString(data);
    data = message2.SerializeAsString();
    google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message2);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectPackedClear(message);
  }
}

TEST(Lite, AllLite9) {
  string data;

  {
    protobuf_unittest::TestPackedExtensionsLite message, message2;
    protobuf_unittest::TestEmptyMessageLite empty_message;
    google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
    google::protobuf::TestUtilLite::SetPackedExtensions(&message);
    data = message.SerializeAsString();
    empty_message.ParseFromString(data);
    data.clear();
    data = empty_message.SerializeAsString();
    message2.ParseFromString(data);
    data = message2.SerializeAsString();
    google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2);
    message.Clear();
    google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
  }
}

TEST(Lite, AllLite10) {
  string data;

  {
    // Test Unknown fields swap
    protobuf_unittest::TestEmptyMessageLite empty_message, empty_message2;
    SetAllTypesInEmptyMessageUnknownFields(&empty_message);
    SetSomeTypesInEmptyMessageUnknownFields(&empty_message2);
    data = empty_message.SerializeAsString();
    string data2 = empty_message2.SerializeAsString();
    empty_message.Swap(&empty_message2);
    EXPECT_EQ(data, empty_message2.SerializeAsString());
    EXPECT_EQ(data2, empty_message.SerializeAsString());
  }
}

TEST(Lite, AllLite11) {
  string data;

  {
    // Test unknown fields swap with self
    protobuf_unittest::TestEmptyMessageLite empty_message;
    SetAllTypesInEmptyMessageUnknownFields(&empty_message);
    data = empty_message.SerializeAsString();
    empty_message.Swap(&empty_message);
    EXPECT_EQ(data, empty_message.SerializeAsString());
  }
}

TEST(Lite, AllLite12) {
  string data;

  {
    // Test MergeFrom with unknown fields
    protobuf_unittest::TestAllTypesLite message, message2;
    protobuf_unittest::TestEmptyMessageLite empty_message, empty_message2;
    message.set_optional_int32(101);
    message.add_repeated_int32(201);
    message.set_optional_nested_enum(google::protobuf::unittest::TestAllTypesLite::BAZ);
    message2.set_optional_int64(102);
    message2.add_repeated_int64(202);
    message2.set_optional_foreign_enum(google::protobuf::unittest::FOREIGN_LITE_BAZ);

    data = message.SerializeAsString();
    empty_message.ParseFromString(data);
    data = message2.SerializeAsString();
    empty_message2.ParseFromString(data);
    message.MergeFrom(message2);
    empty_message.MergeFrom(empty_message2);

    data = empty_message.SerializeAsString();
    message2.ParseFromString(data);
    // We do not compare the serialized output of a normal message and a lite
    // message because the order of fields do not match. We convert lite message
    // back into normal message, then compare.
    EXPECT_EQ(message.SerializeAsString(), message2.SerializeAsString());
  }
}

TEST(Lite, AllLite13) {
  string data;

  {
    // Test unknown enum value
    protobuf_unittest::TestAllTypesLite message;
    string buffer;
    {
      google::protobuf::io::StringOutputStream output_stream(&buffer);
      google::protobuf::io::CodedOutputStream coded_output(&output_stream);
      google::protobuf::internal::WireFormatLite::WriteTag(
          protobuf_unittest::TestAllTypesLite::kOptionalNestedEnumFieldNumber,
          google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT, &coded_output);
      coded_output.WriteVarint32(10);
      google::protobuf::internal::WireFormatLite::WriteTag(
          protobuf_unittest::TestAllTypesLite::kRepeatedNestedEnumFieldNumber,
          google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT, &coded_output);
      coded_output.WriteVarint32(20);
    }
    message.ParseFromString(buffer);
    data = message.SerializeAsString();
    EXPECT_EQ(data, buffer);
  }
}

TEST(Lite, AllLite14) {
  string data;

  {
    // Test Clear with unknown fields
    protobuf_unittest::TestEmptyMessageLite empty_message;
    SetAllTypesInEmptyMessageUnknownFields(&empty_message);
    empty_message.Clear();
    EXPECT_EQ(0, empty_message.unknown_fields().size());
  }
}

// Tests for map lite =============================================

TEST(Lite, AllLite15) {
  string data;

  {
    // Accessors
    protobuf_unittest::TestMapLite message;

    google::protobuf::MapLiteTestUtil::SetMapFields(&message);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message);

    google::protobuf::MapLiteTestUtil::ModifyMapFields(&message);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message);
  }
}

TEST(Lite, AllLite16) {
  string data;

  {
    // SetMapFieldsInitialized
    protobuf_unittest::TestMapLite message;

    google::protobuf::MapLiteTestUtil::SetMapFieldsInitialized(&message);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSetInitialized(message);
  }
}

TEST(Lite, AllLite17) {
  string data;

  {
    // Clear
    protobuf_unittest::TestMapLite message;

    google::protobuf::MapLiteTestUtil::SetMapFields(&message);
    message.Clear();
    google::protobuf::MapLiteTestUtil::ExpectClear(message);
  }
}

TEST(Lite, AllLite18) {
  string data;

  {
    // ClearMessageMap
    protobuf_unittest::TestMessageMapLite message;

    // Creates a TestAllTypes with default value
    google::protobuf::TestUtilLite::ExpectClear(
        (*message.mutable_map_int32_message())[0]);
  }
}

TEST(Lite, AllLite19) {
  string data;

  {
    // CopyFrom
    protobuf_unittest::TestMapLite message1, message2;

    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
    message2.CopyFrom(message1);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);

    // Copying from self should be a no-op.
    message2.CopyFrom(message2);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
  }
}

TEST(Lite, AllLite20) {
  string data;

  {
    // CopyFromMessageMap
    protobuf_unittest::TestMessageMapLite message1, message2;

    (*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
    (*message2.mutable_map_int32_message())[0].add_repeated_int32(101);

    message1.CopyFrom(message2);

    // Checks repeated field is overwritten.
    EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
    EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
  }
}

TEST(Lite, AllLite21) {
  string data;

  {
    // SwapWithEmpty
    protobuf_unittest::TestMapLite message1, message2;

    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message1);
    google::protobuf::MapLiteTestUtil::ExpectClear(message2);

    message1.Swap(&message2);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
    google::protobuf::MapLiteTestUtil::ExpectClear(message1);
  }
}

TEST(Lite, AllLite22) {
  string data;

  {
    // SwapWithSelf
    protobuf_unittest::TestMapLite message;

    google::protobuf::MapLiteTestUtil::SetMapFields(&message);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message);

    message.Swap(&message);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message);
  }
}

TEST(Lite, AllLite23) {
  string data;

  {
    // SwapWithOther
    protobuf_unittest::TestMapLite message1, message2;

    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
    google::protobuf::MapLiteTestUtil::SetMapFields(&message2);
    google::protobuf::MapLiteTestUtil::ModifyMapFields(&message2);

    message1.Swap(&message2);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message1);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
  }
}

TEST(Lite, AllLite24) {
  string data;

  {
    // CopyConstructor
    protobuf_unittest::TestMapLite message1;
    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);

    protobuf_unittest::TestMapLite message2(message1);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
  }
}

TEST(Lite, AllLite25) {
  string data;

  {
    // CopyAssignmentOperator
    protobuf_unittest::TestMapLite message1;
    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);

    protobuf_unittest::TestMapLite message2;
    message2 = message1;
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);

    // Make sure that self-assignment does something sane.
    message2.operator=(message2);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
  }
}

TEST(Lite, AllLite26) {
  string data;

  {
    // NonEmptyMergeFrom
    protobuf_unittest::TestMapLite message1, message2;

    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);

    // This field will test merging into an empty spot.
    (*message2.mutable_map_int32_int32())[1] = 1;
    message1.mutable_map_int32_int32()->erase(1);

    // This tests overwriting.
    (*message2.mutable_map_int32_double())[1] = 1;
    (*message1.mutable_map_int32_double())[1] = 2;

    message1.MergeFrom(message2);
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message1);
  }
}

TEST(Lite, AllLite27) {
  string data;

  {
    // MergeFromMessageMap
    protobuf_unittest::TestMessageMapLite message1, message2;

    (*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
    (*message2.mutable_map_int32_message())[0].add_repeated_int32(101);

    message1.MergeFrom(message2);

    // Checks repeated field is overwritten.
    EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
    EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
  }
}

TEST(Lite, AllLite28) {
  string data;

  {
    // Test the generated SerializeWithCachedSizesToArray()
    protobuf_unittest::TestMapLite message1, message2;
    string data;
    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
    int size = message1.ByteSize();
    data.resize(size);
    ::google::protobuf::uint8* start = reinterpret_cast< ::google::protobuf::uint8*>(::google::protobuf::string_as_array(&data));
    ::google::protobuf::uint8* end = message1.SerializeWithCachedSizesToArray(start);
    EXPECT_EQ(size, end - start);
    EXPECT_TRUE(message2.ParseFromString(data));
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
  }
}

TEST(Lite, AllLite29) {
  string data;

  {
    // Test the generated SerializeWithCachedSizes()
    protobuf_unittest::TestMapLite message1, message2;
    google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
    int size = message1.ByteSize();
    string data;
    data.resize(size);
    {
      // Allow the output stream to buffer only one byte at a time.
      google::protobuf::io::ArrayOutputStream array_stream(
          ::google::protobuf::string_as_array(&data), size, 1);
      google::protobuf::io::CodedOutputStream output_stream(&array_stream);
      message1.SerializeWithCachedSizes(&output_stream);
      EXPECT_FALSE(output_stream.HadError());
      EXPECT_EQ(size, output_stream.ByteCount());
    }
    EXPECT_TRUE(message2.ParseFromString(data));
    google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
  }
}

TEST(Lite, AllLite32) {
  string data;

  {
    // Proto2UnknownEnum
    protobuf_unittest::TestEnumMapPlusExtraLite from;
    (*from.mutable_known_map_field())[0] =
        protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE;
    (*from.mutable_unknown_map_field())[0] =
        protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE;
    string data;
    from.SerializeToString(&data);

    protobuf_unittest::TestEnumMapLite to;
    EXPECT_TRUE(to.ParseFromString(data));
    EXPECT_EQ(0, to.unknown_map_field().size());
    EXPECT_FALSE(to.mutable_unknown_fields()->empty());
    EXPECT_EQ(1, to.known_map_field().size());
    EXPECT_EQ(protobuf_unittest::PROTO2_MAP_ENUM_FOO_LITE,
              to.known_map_field().at(0));

    data.clear();
    from.Clear();
    to.SerializeToString(&data);
    EXPECT_TRUE(from.ParseFromString(data));
    EXPECT_EQ(1, from.known_map_field().size());
    EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE,
              from.known_map_field().at(0));
    EXPECT_EQ(1, from.unknown_map_field().size());
    EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE,
              from.unknown_map_field().at(0));
  }
}

TEST(Lite, AllLite33) {
  string data;

  {
    // StandardWireFormat
    protobuf_unittest::TestMapLite message;
    string data = "\x0A\x04\x08\x01\x10\x01";

    EXPECT_TRUE(message.ParseFromString(data));
    EXPECT_EQ(1, message.map_int32_int32().size());
    EXPECT_EQ(1, message.map_int32_int32().at(1));
  }
}

TEST(Lite, AllLite34) {
  string data;

  {
    // UnorderedWireFormat
    protobuf_unittest::TestMapLite message;

    // put value before key in wire format
    string data = "\x0A\x04\x10\x01\x08\x02";

    EXPECT_TRUE(message.ParseFromString(data));
    EXPECT_EQ(1, message.map_int32_int32().size());
    EXPECT_EQ(1, message.map_int32_int32().at(2));
  }
}

TEST(Lite, AllLite35) {
  string data;

  {
    // DuplicatedKeyWireFormat
    protobuf_unittest::TestMapLite message;

    // Two key fields in wire format
    string data = "\x0A\x06\x08\x01\x08\x02\x10\x01";

    EXPECT_TRUE(message.ParseFromString(data));
    EXPECT_EQ(1, message.map_int32_int32().size());
    EXPECT_EQ(1, message.map_int32_int32().at(2));
  }
}

TEST(Lite, AllLite36) {
  string data;

  {
    // DuplicatedValueWireFormat
    protobuf_unittest::TestMapLite message;

    // Two value fields in wire format
    string data = "\x0A\x06\x08\x01\x10\x01\x10\x02";

    EXPECT_TRUE(message.ParseFromString(data));
    EXPECT_EQ(1, message.map_int32_int32().size());
    EXPECT_EQ(2, message.map_int32_int32().at(1));
  }
}

TEST(Lite, AllLite37) {
  string data;

  {
    // MissedKeyWireFormat
    protobuf_unittest::TestMapLite message;

    // No key field in wire format
    string data = "\x0A\x02\x10\x01";

    EXPECT_TRUE(message.ParseFromString(data));
    EXPECT_EQ(1, message.map_int32_int32().size());
    EXPECT_EQ(1, message.map_int32_int32().at(0));
  }
}

TEST(Lite, AllLite38) {
  string data;

  {
    // MissedValueWireFormat
    protobuf_unittest::TestMapLite message;

    // No value field in wire format
    string data = "\x0A\x02\x08\x01";

    EXPECT_TRUE(message.ParseFromString(data));
    EXPECT_EQ(1, message.map_int32_int32().size());
    EXPECT_EQ(0, message.map_int32_int32().at(1));
  }
}

TEST(Lite, AllLite39) {
  string data;

  {
    // UnknownFieldWireFormat
    protobuf_unittest::TestMapLite message;

    // Unknown field in wire format
    string data = "\x0A\x06\x08\x02\x10\x03\x18\x01";

    EXPECT_TRUE(message.ParseFromString(data));
    EXPECT_EQ(1, message.map_int32_int32().size());
    EXPECT_EQ(3, message.map_int32_int32().at(2));
  }
}

TEST(Lite, AllLite40) {
  string data;

  {
    // CorruptedWireFormat
    protobuf_unittest::TestMapLite message;

    // corrupted data in wire format
    string data = "\x0A\x06\x08\x02\x11\x03";

    EXPECT_FALSE(message.ParseFromString(data));
  }
}

TEST(Lite, AllLite41) {
  string data;

  {
    // IsInitialized
    protobuf_unittest::TestRequiredMessageMapLite map_message;

    // Add an uninitialized message.
    (*map_message.mutable_map_field())[0];
    EXPECT_FALSE(map_message.IsInitialized());

    // Initialize uninitialized message
    (*map_message.mutable_map_field())[0].set_a(0);
    (*map_message.mutable_map_field())[0].set_b(0);
    (*map_message.mutable_map_field())[0].set_c(0);
    EXPECT_TRUE(map_message.IsInitialized());
  }
}

TEST(Lite, AllLite42) {
  string data;

  {
      // Check that adding more values to enum does not corrupt message
      // when passed through an old client.
      protobuf_unittest::V2MessageLite v2_message;
      v2_message.set_int_field(800);
      // Set enum field to the value not understood by the old client.
      v2_message.set_enum_field(protobuf_unittest::V2_SECOND);
      string v2_bytes = v2_message.SerializeAsString();

      protobuf_unittest::V1MessageLite v1_message;
      v1_message.ParseFromString(v2_bytes);
      EXPECT_TRUE(v1_message.IsInitialized());
      EXPECT_EQ(v1_message.int_field(), v2_message.int_field());
      // V1 client does not understand V2_SECOND value, so it discards it and
      // uses default value instead.
      EXPECT_EQ(v1_message.enum_field(), protobuf_unittest::V1_FIRST);

      // However, when re-serialized, it should preserve enum value.
      string v1_bytes = v1_message.SerializeAsString();

      protobuf_unittest::V2MessageLite same_v2_message;
      same_v2_message.ParseFromString(v1_bytes);

      EXPECT_EQ(v2_message.int_field(), same_v2_message.int_field());
      EXPECT_EQ(v2_message.enum_field(), same_v2_message.enum_field());
  }
}

// Test that when parsing a oneof, we can successfully clear whatever already
// happened to be stored in the oneof.
TEST(Lite, AllLite43) {
  protobuf_unittest::TestOneofParsingLite message1;

  message1.set_oneof_int32(17);
  string serialized;
  EXPECT_TRUE(message1.SerializeToString(&serialized));

  // Submessage
  {
    protobuf_unittest::TestOneofParsingLite message2;
    message2.mutable_oneof_submessage();
    google::protobuf::io::CodedInputStream input_stream(
        reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()), serialized.size());
    EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream));
    EXPECT_EQ(17, message2.oneof_int32());
  }

  // String
  {
    protobuf_unittest::TestOneofParsingLite message2;
    message2.set_oneof_string("string");
    google::protobuf::io::CodedInputStream input_stream(
        reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()), serialized.size());
    EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream));
    EXPECT_EQ(17, message2.oneof_int32());
  }

  // Bytes
  {
    protobuf_unittest::TestOneofParsingLite message2;
    message2.set_oneof_bytes("bytes");
    google::protobuf::io::CodedInputStream input_stream(
        reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()), serialized.size());
    EXPECT_TRUE(message2.MergeFromCodedStream(&input_stream));
    EXPECT_EQ(17, message2.oneof_int32());
  }
}

// Verify that we can successfully parse fields of various types within oneof
// fields. We also verify that we can parse the same data twice into the same
// message.
TEST(Lite, AllLite44) {
  // Int32
  {
    protobuf_unittest::TestOneofParsingLite original;
    original.set_oneof_int32(17);
    string serialized;
    EXPECT_TRUE(original.SerializeToString(&serialized));
    protobuf_unittest::TestOneofParsingLite parsed;
    for (int i = 0; i < 2; ++i) {
      google::protobuf::io::CodedInputStream input_stream(
          reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
          serialized.size());
      EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
      EXPECT_EQ(17, parsed.oneof_int32());
    }
  }

  // Submessage
  {
    protobuf_unittest::TestOneofParsingLite original;
    original.mutable_oneof_submessage()->set_optional_int32(5);
    string serialized;
    EXPECT_TRUE(original.SerializeToString(&serialized));
    protobuf_unittest::TestOneofParsingLite parsed;
    for (int i = 0; i < 2; ++i) {
      google::protobuf::io::CodedInputStream input_stream(
          reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
          serialized.size());
      EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
      EXPECT_EQ(5, parsed.oneof_submessage().optional_int32());
    }
  }

  // String
  {
    protobuf_unittest::TestOneofParsingLite original;
    original.set_oneof_string("string");
    string serialized;
    EXPECT_TRUE(original.SerializeToString(&serialized));
    protobuf_unittest::TestOneofParsingLite parsed;
    for (int i = 0; i < 2; ++i) {
      google::protobuf::io::CodedInputStream input_stream(
          reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
          serialized.size());
      EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
      EXPECT_EQ("string", parsed.oneof_string());
    }
  }

  // Bytes
  {
    protobuf_unittest::TestOneofParsingLite original;
    original.set_oneof_bytes("bytes");
    string serialized;
    EXPECT_TRUE(original.SerializeToString(&serialized));
    protobuf_unittest::TestOneofParsingLite parsed;
    for (int i = 0; i < 2; ++i) {
      google::protobuf::io::CodedInputStream input_stream(
          reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
          serialized.size());
      EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
      EXPECT_EQ("bytes", parsed.oneof_bytes());
    }
  }

  // Enum
  {
    protobuf_unittest::TestOneofParsingLite original;
    original.set_oneof_enum(protobuf_unittest::V2_SECOND);
    string serialized;
    EXPECT_TRUE(original.SerializeToString(&serialized));
    protobuf_unittest::TestOneofParsingLite parsed;
    for (int i = 0; i < 2; ++i) {
      google::protobuf::io::CodedInputStream input_stream(
          reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
          serialized.size());
      EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
      EXPECT_EQ(protobuf_unittest::V2_SECOND, parsed.oneof_enum());
    }
  }

  std::cout << "PASS" << std::endl;
}

TEST(Lite, AllLite45) {
  // Test unknown fields are not discarded upon parsing.
  string data = "\20\1";  // varint 1 with field number 2

  protobuf_unittest::ForeignMessageLite a;
  EXPECT_TRUE(a.ParseFromString(data));
  google::protobuf::io::CodedInputStream input_stream(
      reinterpret_cast<const ::google::protobuf::uint8*>(data.data()), data.size());
  EXPECT_TRUE(a.MergePartialFromCodedStream(&input_stream));

  string serialized = a.SerializeAsString();
  EXPECT_EQ(serialized.substr(0, 2), data);
  EXPECT_EQ(serialized.substr(2), data);
}


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 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.

syntax = "proto3";

option optimize_for = SPEED;

import "google/protobuf/unittest_import.proto";

package proto3_unittest;

// This proto includes every type of field in both singular and repeated
// forms.
message TestAllTypes {
  message NestedMessage {
    // The field name "b" fails to compile in proto1 because it conflicts with
    // a local variable named "b" in one of the generated methods.  Doh.
    // This file needs to compile in proto1 to test backwards-compatibility.
    int32 bb = 1;
  }

  enum NestedEnum {
    ZERO = 0;
    FOO = 1;
    BAR = 2;
    BAZ = 3;
    NEG = -1;  // Intentionally negative.
  }

  // Singular
     int32 optional_int32    =  1;
     int64 optional_int64    =  2;
    uint32 optional_uint32   =  3;
    uint64 optional_uint64   =  4;
    sint32 optional_sint32   =  5;
    sint64 optional_sint64   =  6;
   fixed32 optional_fixed32  =  7;
   fixed64 optional_fixed64  =  8;
  sfixed32 optional_sfixed32 =  9;
  sfixed64 optional_sfixed64 = 10;
     float optional_float    = 11;
    double optional_double   = 12;
      bool optional_bool     = 13;
    string optional_string   = 14;
     bytes optional_bytes    = 15;

  // Groups are not allowed in proto3.
  // optional group OptionalGroup = 16 {
  //   optional int32 a = 17;
  // }

  NestedMessage                        optional_nested_message  = 18;
  ForeignMessage                       optional_foreign_message = 19;
  protobuf_unittest_import.ImportMessage optional_import_message  = 20;

  NestedEnum                           optional_nested_enum     = 21;
  ForeignEnum                          optional_foreign_enum    = 22;

  // Omitted (compared to unittest.proto) because proto2 enums are not allowed
  // inside proto2 messages.
  //
  // optional protobuf_unittest_import.ImportEnum    optional_import_enum  = 23;

  string optional_string_piece = 24 [ctype=STRING_PIECE];
  string optional_cord = 25 [ctype=CORD];

  // Defined in unittest_import_public.proto
  protobuf_unittest_import.PublicImportMessage
      optional_public_import_message = 26;

  NestedMessage optional_lazy_message = 27 [lazy=true];
  protobuf_unittest_import.ImportMessage optional_lazy_import_message = 115
      [lazy = true];

  // Repeated
  repeated    int32 repeated_int32    = 31;
  repeated    int64 repeated_int64    = 32;
  repeated   uint32 repeated_uint32   = 33;
  repeated   uint64 repeated_uint64   = 34;
  repeated   sint32 repeated_sint32   = 35;
  repeated   sint64 repeated_sint64   = 36;
  repeated  fixed32 repeated_fixed32  = 37;
  repeated  fixed64 repeated_fixed64  = 38;
  repeated sfixed32 repeated_sfixed32 = 39;
  repeated sfixed64 repeated_sfixed64 = 40;
  repeated    float repeated_float    = 41;
  repeated   double repeated_double   = 42;
  repeated     bool repeated_bool     = 43;
  repeated   string repeated_string   = 44;
  repeated    bytes repeated_bytes    = 45;

  // Groups are not allowed in proto3.
  // repeated group RepeatedGroup = 46 {
  //   optional int32 a = 47;
  // }

  repeated NestedMessage                        repeated_nested_message  = 48;
  repeated ForeignMessage                       repeated_foreign_message = 49;
  repeated protobuf_unittest_import.ImportMessage repeated_import_message  = 50;

  repeated NestedEnum                           repeated_nested_enum     = 51;
  repeated ForeignEnum                          repeated_foreign_enum    = 52;

  // Omitted (compared to unittest.proto) because proto2 enums are not allowed
  // inside proto2 messages.
  //
  // repeated protobuf_unittest_import.ImportEnum    repeated_import_enum  = 53;

  repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
  repeated string repeated_cord = 55 [ctype=CORD];

  repeated NestedMessage repeated_lazy_message = 57 [lazy=true];

  oneof oneof_field {
    uint32 oneof_uint32 = 111;
    NestedMessage oneof_nested_message = 112;
    string oneof_string = 113;
    bytes oneof_bytes = 114;
  }
}

// Test messages for packed fields

message TestPackedTypes {
  repeated    int32 packed_int32    =  90 [packed = true];
  repeated    int64 packed_int64    =  91 [packed = true];
  repeated   uint32 packed_uint32   =  92 [packed = true];
  repeated   uint64 packed_uint64   =  93 [packed = true];
  repeated   sint32 packed_sint32   =  94 [packed = true];
  repeated   sint64 packed_sint64   =  95 [packed = true];
  repeated  fixed32 packed_fixed32  =  96 [packed = true];
  repeated  fixed64 packed_fixed64  =  97 [packed = true];
  repeated sfixed32 packed_sfixed32 =  98 [packed = true];
  repeated sfixed64 packed_sfixed64 =  99 [packed = true];
  repeated    float packed_float    = 100 [packed = true];
  repeated   double packed_double   = 101 [packed = true];
  repeated     bool packed_bool     = 102 [packed = true];
  repeated ForeignEnum packed_enum  = 103 [packed = true];
}

// Explicitly set packed to false
message TestUnpackedTypes {
  repeated    int32 repeated_int32    =  1 [packed = false];
  repeated    int64 repeated_int64    =  2 [packed = false];
  repeated   uint32 repeated_uint32   =  3 [packed = false];
  repeated   uint64 repeated_uint64   =  4 [packed = false];
  repeated   sint32 repeated_sint32   =  5 [packed = false];
  repeated   sint64 repeated_sint64   =  6 [packed = false];
  repeated  fixed32 repeated_fixed32  =  7 [packed = false];
  repeated  fixed64 repeated_fixed64  =  8 [packed = false];
  repeated sfixed32 repeated_sfixed32 =  9 [packed = false];
  repeated sfixed64 repeated_sfixed64 = 10 [packed = false];
  repeated    float repeated_float    = 11 [packed = false];
  repeated   double repeated_double   = 12 [packed = false];
  repeated     bool repeated_bool     = 13 [packed = false];
  repeated TestAllTypes.NestedEnum repeated_nested_enum = 14 [packed = false];
}

// This proto includes a recusively nested message.
message NestedTestAllTypes {
  NestedTestAllTypes child = 1;
  TestAllTypes payload = 2;
}

// Define these after TestAllTypes to make sure the compiler can handle
// that.
message ForeignMessage {
  int32 c = 1;
}

enum ForeignEnum {
  FOREIGN_ZERO = 0;
  FOREIGN_FOO = 4;
  FOREIGN_BAR = 5;
  FOREIGN_BAZ = 6;
}

// TestEmptyMessage is used to test behavior of unknown fields.
message TestEmptyMessage {
}