From 0400cca3236de1ca303af38bf81eab332d042b7c Mon Sep 17 00:00:00 2001 From: Adam Cozzette Date: Tue, 13 Mar 2018 16:37:29 -0700 Subject: [PATCH 01/14] Integrated internal changes from Google --- .../protobuf/ProtoCaliperBenchmark.java | 1 + benchmarks/py_benchmark.py | 1 + cmake/extract_includes.bat.in | 16 - cmake/libprotobuf-lite.cmake | 4 - cmake/tests.cmake | 5 +- conformance/conformance_test.cc | 4 + conformance/failure_list_java.txt | 1 + conformance/failure_list_python.txt | 1 + conformance/failure_list_python_cpp.txt | 1 + .../com/google/protobuf/AbstractMessage.java | 10 + .../google/protobuf/AbstractMessageLite.java | 10 + .../com/google/protobuf/BooleanArrayList.java | 16 +- .../com/google/protobuf/CodedInputStream.java | 6 +- .../google/protobuf/CodedOutputStream.java | 18 + .../com/google/protobuf/DoubleArrayList.java | 16 +- .../com/google/protobuf/DynamicMessage.java | 18 + .../com/google/protobuf/FloatArrayList.java | 16 +- .../google/protobuf/GeneratedMessageLite.java | 128 +- .../com/google/protobuf/IntArrayList.java | 16 +- .../com/google/protobuf/LongArrayList.java | 16 +- .../google/protobuf/MessageLiteToString.java | 96 +- .../java/com/google/protobuf/TextFormat.java | 51 +- .../google/protobuf/UnknownFieldSetLite.java | 24 +- .../java/com/google/protobuf/UnsafeUtil.java | 19 +- .../google/protobuf/BooleanArrayListTest.java | 15 + .../com/google/protobuf/CheckUtf8Test.java | 43 +- .../google/protobuf/DoubleArrayListTest.java | 15 + .../google/protobuf/FloatArrayListTest.java | 15 + .../com/google/protobuf/IntArrayListTest.java | 15 + .../java/com/google/protobuf/LiteTest.java | 1453 +++----- .../google/protobuf/LongArrayListTest.java | 15 + .../com/google/protobuf/MapForProto2Test.java | 18 + .../java/com/google/protobuf/MapTest.java | 18 + .../com/google/protobuf/TextFormatTest.java | 17 +- .../protobuf/UnknownFieldSetLiteTest.java | 21 + .../com/google/protobuf/WireFormatTest.java | 21 + js/binary/constants.js | 19 +- js/binary/decoder.js | 2 +- js/binary/writer.js | 6 +- js/binary/writer_test.js | 12 + js/debug.js | 2 +- js/map.js | 16 +- js/message.js | 82 +- js/message_test.js | 12 + python/google/protobuf/descriptor.py | 109 +- .../protobuf/internal/_parameterized.py | 50 +- .../protobuf/internal/api_implementation.py | 11 +- python/google/protobuf/internal/encoder.py | 16 +- .../protobuf/internal/json_format_test.py | 12 + .../google/protobuf/internal/message_test.py | 29 +- .../google/protobuf/internal/no_package.proto | 12 + .../protobuf/internal/text_format_test.py | 93 +- .../protobuf/internal/well_known_types.py | 10 +- .../internal/well_known_types_test.py | 16 + python/google/protobuf/json_format.py | 33 +- python/google/protobuf/pyext/descriptor.cc | 80 +- .../google/protobuf/pyext/descriptor_pool.cc | 122 +- .../google/protobuf/pyext/extension_dict.cc | 3 - python/google/protobuf/pyext/extension_dict.h | 15 +- python/google/protobuf/pyext/map_container.cc | 29 +- python/google/protobuf/pyext/map_container.h | 17 +- python/google/protobuf/pyext/message.cc | 29 +- python/google/protobuf/pyext/message.h | 24 +- .../google/protobuf/pyext/message_factory.cc | 8 +- .../pyext/repeated_composite_container.cc | 129 +- .../pyext/repeated_composite_container.h | 21 +- .../pyext/repeated_scalar_container.cc | 174 +- .../pyext/repeated_scalar_container.h | 19 +- python/google/protobuf/text_format.py | 88 +- src/Makefile.am | 27 +- src/google/protobuf/any.cc | 11 +- src/google/protobuf/any.h | 11 + src/google/protobuf/any.pb.cc | 61 +- src/google/protobuf/any.pb.h | 53 +- src/google/protobuf/api.pb.cc | 173 +- src/google/protobuf/api.pb.h | 143 +- src/google/protobuf/arena.cc | 47 +- src/google/protobuf/arena.h | 584 +-- src/google/protobuf/arena_impl.h | 23 +- src/google/protobuf/arena_test_util.h | 2 +- src/google/protobuf/arena_unittest.cc | 52 +- src/google/protobuf/arenastring.h | 52 +- src/google/protobuf/arenastring_unittest.cc | 3 - .../protobuf/compiler/annotation_test_util.cc | 3 - .../protobuf/compiler/code_generator.cc | 2 +- .../compiler/command_line_interface.cc | 43 +- .../compiler/command_line_interface.h | 5 - .../command_line_interface_unittest.cc | 7 +- .../compiler/cpp/cpp_bootstrap_unittest.cc | 79 +- src/google/protobuf/compiler/cpp/cpp_enum.cc | 2 +- .../protobuf/compiler/cpp/cpp_extension.cc | 3 +- src/google/protobuf/compiler/cpp/cpp_field.cc | 27 +- src/google/protobuf/compiler/cpp/cpp_field.h | 45 +- src/google/protobuf/compiler/cpp/cpp_file.cc | 279 +- src/google/protobuf/compiler/cpp/cpp_file.h | 11 +- .../protobuf/compiler/cpp/cpp_generator.cc | 27 +- .../protobuf/compiler/cpp/cpp_helpers.cc | 81 +- .../protobuf/compiler/cpp/cpp_helpers.h | 52 +- .../protobuf/compiler/cpp/cpp_map_field.cc | 12 +- .../protobuf/compiler/cpp/cpp_map_field.h | 1 - .../protobuf/compiler/cpp/cpp_message.cc | 447 +-- .../protobuf/compiler/cpp/cpp_message.h | 16 +- .../compiler/cpp/cpp_message_field.cc | 160 +- .../protobuf/compiler/cpp/cpp_message_field.h | 17 +- .../compiler/cpp/cpp_move_unittest.cc | 2 +- .../protobuf/compiler/cpp/cpp_options.h | 2 + .../compiler/cpp/cpp_padding_optimizer.h | 4 +- .../compiler/cpp/cpp_plugin_unittest.cc | 5 +- .../protobuf/compiler/cpp/cpp_string_field.cc | 177 +- .../protobuf/compiler/cpp/cpp_string_field.h | 5 +- .../protobuf/compiler/cpp/cpp_unittest.cc | 2243 +---------- .../protobuf/compiler/cpp/cpp_unittest.inc | 2281 ++++++++++++ .../protobuf/compiler/cpp/metadata_test.cc | 3 - src/google/protobuf/compiler/importer.cc | 12 +- .../protobuf/compiler/importer_unittest.cc | 7 +- .../protobuf/compiler/java/java_context.cc | 8 +- .../protobuf/compiler/java/java_context.h | 5 +- .../protobuf/compiler/java/java_enum.cc | 4 +- .../protobuf/compiler/java/java_enum_field.cc | 3 +- .../compiler/java/java_enum_field_lite.cc | 23 + .../protobuf/compiler/java/java_enum_lite.cc | 6 +- .../protobuf/compiler/java/java_extension.cc | 1 + .../compiler/java/java_extension_lite.cc | 1 + .../protobuf/compiler/java/java_field.cc | 7 +- .../protobuf/compiler/java/java_field.h | 13 +- .../protobuf/compiler/java/java_file.cc | 21 +- src/google/protobuf/compiler/java/java_file.h | 11 +- .../protobuf/compiler/java/java_generator.cc | 13 +- .../protobuf/compiler/java/java_helpers.cc | 33 + .../protobuf/compiler/java/java_helpers.h | 7 +- .../compiler/java/java_map_field_lite.cc | 26 + .../protobuf/compiler/java/java_message.cc | 12 +- .../compiler/java/java_message_builder.cc | 5 +- .../java/java_message_builder_lite.cc | 8 +- .../compiler/java/java_message_field_lite.cc | 23 + .../compiler/java/java_message_lite.cc | 83 +- .../compiler/java/java_plugin_unittest.cc | 5 +- .../compiler/java/java_primitive_field.cc | 3 +- .../java/java_primitive_field_lite.cc | 14 + .../java/java_shared_code_generator.cc | 11 +- .../java/java_shared_code_generator.h | 5 +- .../compiler/java/java_string_field_lite.cc | 20 + .../protobuf/compiler/js/js_generator.cc | 43 +- .../protobuf/compiler/mock_code_generator.cc | 14 +- src/google/protobuf/compiler/parser.cc | 13 +- src/google/protobuf/compiler/parser.h | 4 +- .../protobuf/compiler/parser_unittest.cc | 10 +- src/google/protobuf/compiler/plugin.cc | 2 +- src/google/protobuf/compiler/plugin.pb.cc | 215 +- src/google/protobuf/compiler/plugin.pb.h | 214 +- .../compiler/python/python_generator.cc | 87 +- .../compiler/python/python_generator.h | 3 +- .../compiler/python/python_plugin_unittest.cc | 5 +- src/google/protobuf/descriptor.cc | 56 +- src/google/protobuf/descriptor.h | 9 +- src/google/protobuf/descriptor.pb.cc | 1379 +++---- src/google/protobuf/descriptor.pb.h | 1512 ++++---- src/google/protobuf/descriptor_database.h | 2 +- .../protobuf/descriptor_database_unittest.cc | 9 +- src/google/protobuf/descriptor_unittest.cc | 47 +- .../protobuf/drop_unknown_fields_test.cc | 7 +- src/google/protobuf/duration.pb.cc | 54 +- src/google/protobuf/duration.pb.h | 55 +- src/google/protobuf/dynamic_message.cc | 9 +- src/google/protobuf/dynamic_message.h | 5 +- .../protobuf/dynamic_message_unittest.cc | 9 +- src/google/protobuf/empty.pb.cc | 54 +- src/google/protobuf/empty.pb.h | 55 +- src/google/protobuf/extension_set.cc | 519 ++- src/google/protobuf/extension_set.h | 137 +- src/google/protobuf/extension_set_heavy.cc | 142 +- src/google/protobuf/extension_set_unittest.cc | 41 +- src/google/protobuf/field_mask.pb.cc | 52 +- src/google/protobuf/field_mask.pb.h | 51 +- src/google/protobuf/field_mask.proto | 4 +- src/google/protobuf/generated_enum_util.h | 4 +- .../protobuf/generated_message_reflection.cc | 67 +- .../protobuf/generated_message_reflection.h | 45 +- .../generated_message_reflection_unittest.cc | 11 +- .../generated_message_table_driven.cc | 3 +- .../protobuf/generated_message_table_driven.h | 55 +- .../generated_message_table_driven_lite.cc | 2 +- .../generated_message_table_driven_lite.h | 196 +- src/google/protobuf/generated_message_util.cc | 91 +- src/google/protobuf/generated_message_util.h | 72 +- src/google/protobuf/implicit_weak_message.cc | 18 +- src/google/protobuf/implicit_weak_message.h | 7 +- src/google/protobuf/inlined_string_field.h | 271 ++ src/google/protobuf/io/coded_stream.cc | 26 +- src/google/protobuf/io/coded_stream.h | 23 +- .../protobuf/io/coded_stream_unittest.cc | 5 +- .../protobuf/io/zero_copy_stream_impl_lite.h | 7 +- .../protobuf/io/zero_copy_stream_unittest.cc | 5 +- src/google/protobuf/lite_arena_unittest.cc | 3 +- src/google/protobuf/lite_unittest.cc | 33 +- src/google/protobuf/map.h | 9 +- src/google/protobuf/map_entry_lite.h | 7 +- src/google/protobuf/map_field.cc | 49 +- src/google/protobuf/map_field.h | 17 +- src/google/protobuf/map_field_inl.h | 10 +- src/google/protobuf/map_field_test.cc | 23 +- src/google/protobuf/map_test.cc | 44 +- src/google/protobuf/message.cc | 4 +- src/google/protobuf/message.h | 4 +- src/google/protobuf/message_lite.h | 21 +- src/google/protobuf/message_unittest.cc | 542 +-- src/google/protobuf/message_unittest.inc | 577 +++ .../protobuf/preserve_unknown_enum_test.cc | 4 +- .../protobuf/proto3_arena_lite_unittest.cc | 29 +- src/google/protobuf/proto3_arena_unittest.cc | 5 +- src/google/protobuf/proto3_lite_unittest.cc | 27 +- src/google/protobuf/reflection.h | 25 +- src/google/protobuf/reflection_ops.cc | 4 +- src/google/protobuf/repeated_field.h | 84 +- .../repeated_field_reflection_unittest.cc | 2 +- .../protobuf/repeated_field_unittest.cc | 14 +- src/google/protobuf/source_context.pb.cc | 55 +- src/google/protobuf/source_context.pb.h | 51 +- src/google/protobuf/struct.pb.cc | 133 +- src/google/protobuf/struct.pb.h | 167 +- src/google/protobuf/stubs/callback.h | 15 +- src/google/protobuf/stubs/casts.h | 5 +- src/google/protobuf/stubs/common.cc | 80 - src/google/protobuf/stubs/common.h | 14 +- src/google/protobuf/stubs/io_win32.cc | 8 +- .../protobuf/stubs/io_win32_unittest.cc | 7 +- src/google/protobuf/stubs/mutex.h | 38 +- src/google/protobuf/stubs/once.h | 71 +- src/google/protobuf/stubs/port.h | 24 +- src/google/protobuf/stubs/singleton.h | 1 - src/google/protobuf/test_util.cc | 3303 ----------------- src/google/protobuf/test_util.h | 1410 ++++++- src/google/protobuf/test_util.inc | 2600 +++++++++++++ src/google/protobuf/text_format.cc | 184 +- src/google/protobuf/text_format.h | 92 +- src/google/protobuf/text_format_unittest.cc | 226 +- src/google/protobuf/timestamp.pb.cc | 54 +- src/google/protobuf/timestamp.pb.h | 55 +- src/google/protobuf/type.pb.cc | 279 +- src/google/protobuf/type.pb.h | 277 +- src/google/protobuf/unittest.proto | 58 +- src/google/protobuf/unittest_lite.proto | 19 + .../protobuf/unknown_field_set_unittest.cc | 1 + src/google/protobuf/util/field_mask_util.cc | 27 +- src/google/protobuf/util/field_mask_util.h | 4 +- .../protobuf/util/field_mask_util_test.cc | 13 +- .../protobuf/util/internal/datapiece.cc | 20 +- .../internal/default_value_objectwriter.cc | 84 +- .../internal/default_value_objectwriter.h | 9 +- .../default_value_objectwriter_test.cc | 4 +- .../protobuf/util/internal/error_listener.h | 3 - .../util/internal/field_mask_utility.cc | 3 +- .../util/internal/json_objectwriter.h | 7 +- .../util/internal/json_objectwriter_test.cc | 2 +- .../util/internal/json_stream_parser.cc | 5 +- .../protobuf/util/internal/proto_writer.cc | 62 +- .../protobuf/util/internal/proto_writer.h | 44 +- .../util/internal/protostream_objectsource.cc | 69 +- .../internal/protostream_objectsource_test.cc | 27 +- .../util/internal/protostream_objectwriter.cc | 78 +- .../util/internal/protostream_objectwriter.h | 8 +- .../internal/protostream_objectwriter_test.cc | 8 +- .../util/internal/structured_objectwriter.h | 9 +- .../util/internal/testdata/books.proto | 1 + .../protobuf/util/internal/type_info.cc | 4 +- .../util/internal/type_info_test_helper.cc | 3 - .../util/internal/type_info_test_helper.h | 7 +- src/google/protobuf/util/internal/utility.cc | 48 +- src/google/protobuf/util/internal/utility.h | 22 +- src/google/protobuf/util/json_util.cc | 8 +- src/google/protobuf/util/json_util_test.cc | 28 +- .../protobuf/util/message_differencer.cc | 31 +- .../protobuf/util/message_differencer.h | 10 +- .../util/message_differencer_unittest.cc | 21 + src/google/protobuf/util/time_util.cc | 5 +- .../protobuf/util/type_resolver_util.cc | 8 +- .../protobuf/util/type_resolver_util_test.cc | 26 +- src/google/protobuf/wire_format.cc | 9 +- src/google/protobuf/wire_format_lite.h | 43 +- src/google/protobuf/wire_format_lite_inl.h | 86 +- src/google/protobuf/wrappers.pb.cc | 380 +- src/google/protobuf/wrappers.pb.h | 415 +-- 282 files changed, 15223 insertions(+), 14041 deletions(-) create mode 100644 python/google/protobuf/internal/no_package.proto create mode 100644 src/google/protobuf/compiler/cpp/cpp_unittest.inc create mode 100644 src/google/protobuf/inlined_string_field.h create mode 100644 src/google/protobuf/message_unittest.inc create mode 100644 src/google/protobuf/test_util.inc diff --git a/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java b/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java index 7dff16dc8b..b50c658567 100755 --- a/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java +++ b/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java @@ -243,3 +243,4 @@ public class ProtoCaliperBenchmark { } } + diff --git a/benchmarks/py_benchmark.py b/benchmarks/py_benchmark.py index 48234f033b..c3d8049275 100755 --- a/benchmarks/py_benchmark.py +++ b/benchmarks/py_benchmark.py @@ -115,3 +115,4 @@ class Benchmark: if __name__ == "__main__": for i in range(2, len(sys.argv)): run_one_test(sys.argv[i]) + diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in index 5178f5b2da..0ab8afeb80 100644 --- a/cmake/extract_includes.bat.in +++ b/cmake/extract_includes.bat.in @@ -79,20 +79,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\repeated_field.h" inc copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\service.h" include\google\protobuf\service.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\source_context.pb.h" include\google\protobuf\source_context.pb.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\struct.pb.h" include\google\protobuf\struct.pb.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomic_sequence_num.h" include\google\protobuf\stubs\atomic_sequence_num.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops.h" include\google\protobuf\stubs\atomicops.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm64_gcc.h" include\google\protobuf\stubs\atomicops_internals_arm64_gcc.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_gcc.h" include\google\protobuf\stubs\atomicops_internals_arm_gcc.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_qnx.h" include\google\protobuf\stubs\atomicops_internals_arm_qnx.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h" include\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_gcc.h" include\google\protobuf\stubs\atomicops_internals_generic_gcc.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_mips_gcc.h" include\google\protobuf\stubs\atomicops_internals_mips_gcc.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_power.h" include\google\protobuf\stubs\atomicops_internals_power.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_ppc_gcc.h" include\google\protobuf\stubs\atomicops_internals_ppc_gcc.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_solaris.h" include\google\protobuf\stubs\atomicops_internals_solaris.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_tsan.h" include\google\protobuf\stubs\atomicops_internals_tsan.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_gcc.h" include\google\protobuf\stubs\atomicops_internals_x86_gcc.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_x86_msvc.h" include\google\protobuf\stubs\atomicops_internals_x86_msvc.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\bytestream.h" include\google\protobuf\stubs\bytestream.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\callback.h" include\google\protobuf\stubs\callback.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\casts.h" include\google\protobuf\stubs\casts.h @@ -105,8 +91,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\mutex.h" includ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\once.h" include\google\protobuf\stubs\once.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\platform_macros.h" include\google\protobuf\stubs\platform_macros.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\port.h" include\google\protobuf\stubs\port.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\scoped_ptr.h" include\google\protobuf\stubs\scoped_ptr.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\shared_ptr.h" include\google\protobuf\stubs\shared_ptr.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\singleton.h" include\google\protobuf\stubs\singleton.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\status.h" include\google\protobuf\stubs\status.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\stl_util.h" include\google\protobuf\stubs\stl_util.h diff --git a/cmake/libprotobuf-lite.cmake b/cmake/libprotobuf-lite.cmake index 2df6a29356..911fce5e5d 100644 --- a/cmake/libprotobuf-lite.cmake +++ b/cmake/libprotobuf-lite.cmake @@ -10,13 +10,10 @@ set(libprotobuf_lite_files ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.cc ${protobuf_source_dir}/src/google/protobuf/message_lite.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_gcc.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_msvc.cc ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.cc ${protobuf_source_dir}/src/google/protobuf/stubs/common.cc ${protobuf_source_dir}/src/google/protobuf/stubs/int128.cc ${protobuf_source_dir}/src/google/protobuf/stubs/io_win32.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/once.cc ${protobuf_source_dir}/src/google/protobuf/stubs/status.cc ${protobuf_source_dir}/src/google/protobuf/stubs/statusor.cc ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece.cc @@ -38,7 +35,6 @@ set(libprotobuf_lite_includes ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.h ${protobuf_source_dir}/src/google/protobuf/message_lite.h ${protobuf_source_dir}/src/google/protobuf/repeated_field.h - ${protobuf_source_dir}/src/google/protobuf/stubs/atomicops_internals_x86_msvc.h ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.h ${protobuf_source_dir}/src/google/protobuf/stubs/common.h ${protobuf_source_dir}/src/google/protobuf/stubs/int128.h diff --git a/cmake/tests.cmake b/cmake/tests.cmake index d4622c6b22..6ab3071c4c 100644 --- a/cmake/tests.cmake +++ b/cmake/tests.cmake @@ -155,7 +155,8 @@ set(tests_files ${protobuf_source_dir}/src/google/protobuf/preserve_unknown_enum_test.cc ${protobuf_source_dir}/src/google/protobuf/proto3_arena_lite_unittest.cc ${protobuf_source_dir}/src/google/protobuf/proto3_arena_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.cc +# TODO(b/74491957) Make this unittest work +# ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.cc ${protobuf_source_dir}/src/google/protobuf/reflection_ops_unittest.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field_reflection_unittest.cc ${protobuf_source_dir}/src/google/protobuf/repeated_field_unittest.cc @@ -163,7 +164,6 @@ set(tests_files ${protobuf_source_dir}/src/google/protobuf/stubs/common_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/int128_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/io_win32_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/once_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/status_test.cc ${protobuf_source_dir}/src/google/protobuf/stubs/statusor_test.cc ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece_unittest.cc @@ -172,7 +172,6 @@ set(tests_files ${protobuf_source_dir}/src/google/protobuf/stubs/strutil_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/template_util_unittest.cc ${protobuf_source_dir}/src/google/protobuf/stubs/time_test.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/type_traits_unittest.cc ${protobuf_source_dir}/src/google/protobuf/text_format_unittest.cc ${protobuf_source_dir}/src/google/protobuf/unknown_field_set_unittest.cc ${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util_test.cc diff --git a/conformance/conformance_test.cc b/conformance/conformance_test.cc index e4b046dcfd..7f68f4b256 100644 --- a/conformance/conformance_test.cc +++ b/conformance/conformance_test.cc @@ -1910,6 +1910,10 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner, { TestAllTypesProto3 messageProto3; TestAllTypesProto2 messageProto2; + //TODO(yilunchong): update this behavior when unknown field's behavior + // changed in open source. Also delete + // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput + // from failure list of python_cpp python java TestUnknownMessage(messageProto3, true); TestUnknownMessage(messageProto2, false); } diff --git a/conformance/failure_list_java.txt b/conformance/failure_list_java.txt index dc1f9ba5c9..705db01a28 100644 --- a/conformance/failure_list_java.txt +++ b/conformance/failure_list_java.txt @@ -45,3 +45,4 @@ Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValu Required.Proto3.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE Required.Proto2.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE +Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput \ No newline at end of file diff --git a/conformance/failure_list_python.txt b/conformance/failure_list_python.txt index e3ce7af759..2c650b64cf 100644 --- a/conformance/failure_list_python.txt +++ b/conformance/failure_list_python.txt @@ -19,3 +19,4 @@ Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_0 Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_1 Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_2 Required.Proto3.ProtobufInput.IllegalZeroFieldNum_Case_3 +Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput \ No newline at end of file diff --git a/conformance/failure_list_python_cpp.txt b/conformance/failure_list_python_cpp.txt index a498ad1a3e..c1c681e998 100644 --- a/conformance/failure_list_python_cpp.txt +++ b/conformance/failure_list_python_cpp.txt @@ -52,3 +52,4 @@ Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32 Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64 Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32 Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64 +Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput \ No newline at end of file diff --git a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java index 908764df6c..fc3c2a5d9a 100644 --- a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java +++ b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java @@ -124,6 +124,16 @@ public abstract class AbstractMessage protected int memoizedSize = -1; + @Override + int getMemoizedSerializedSize() { + return memoizedSize; + } + + @Override + void setMemoizedSerializedSize(int size) { + memoizedSize = size; + } + @Override public int getSerializedSize() { int size = memoizedSize; diff --git a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java index 24830c0a32..b22bbaab62 100644 --- a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java +++ b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java @@ -99,6 +99,16 @@ public abstract class AbstractMessageLite< codedOutput.flush(); } + // We'd like these to be abstract but some folks are extending this class directly. They shouldn't + // be doing that and they should feel bad. + int getMemoizedSerializedSize() { + throw new UnsupportedOperationException(); + } + + void setMemoizedSerializedSize(int size) { + throw new UnsupportedOperationException(); + } + /** * Package private helper method for AbstractParser to create diff --git a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java index fd4c142b33..4d7a9727f3 100644 --- a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java @@ -81,6 +81,18 @@ final class BooleanArrayList extends AbstractProtobufList this.size = size; } + @Override + protected void removeRange(int fromIndex, int toIndex) { + ensureIsMutable(); + if (toIndex < fromIndex) { + throw new IndexOutOfBoundsException("toIndex < fromIndex"); + } + + System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); + size -= (toIndex - fromIndex); + modCount++; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -246,7 +258,9 @@ final class BooleanArrayList extends AbstractProtobufList ensureIsMutable(); ensureIndexInRange(index); boolean value = array[index]; - System.arraycopy(array, index + 1, array, index, size - index); + if (index < size - 1) { + System.arraycopy(array, index + 1, array, index, size - index); + } size--; modCount++; return value; diff --git a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java index 7a3f0eb912..1297462e2d 100644 --- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java +++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java @@ -66,11 +66,9 @@ public abstract class CodedInputStream { /** * Whether to enable our custom UTF-8 decode codepath which does not use {@link StringCoding}. - * Enabled by default, disable by setting - * {@code -Dcom.google.protobuf.enableCustomutf8Decode=false} in JVM args. + * Currently disabled. */ - private static final boolean ENABLE_CUSTOM_UTF8_DECODE - = !"false".equals(System.getProperty("com.google.protobuf.enableCustomUtf8Decode")); + private static final boolean ENABLE_CUSTOM_UTF8_DECODE = false; /** Visible for subclasses. See setRecursionLimit() */ int recursionDepth; diff --git a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java index 093a5f616b..7b1ac65120 100644 --- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java +++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java @@ -377,6 +377,7 @@ public abstract class CodedOutputStream extends ByteOutput { public abstract void writeMessage(final int fieldNumber, final MessageLite value) throws IOException; + /** * Write a MessageSet extension field to the stream. For historical reasons, * the wire format differs from normal fields. @@ -481,6 +482,7 @@ public abstract class CodedOutputStream extends ByteOutput { // Abstract to avoid overhead of additional virtual method calls. public abstract void writeMessageNoTag(final MessageLite value) throws IOException; + //================================================================= @ExperimentalApi @@ -666,6 +668,7 @@ public abstract class CodedOutputStream extends ByteOutput { return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value); } + /** * Compute the number of bytes that would be needed to encode a * MessageSet extension to the stream. For historical reasons, @@ -913,6 +916,7 @@ public abstract class CodedOutputStream extends ByteOutput { return computeLengthDelimitedFieldSize(value.getSerializedSize()); } + static int computeLengthDelimitedFieldSize(int fieldLength) { return computeUInt32SizeNoTag(fieldLength) + fieldLength; } @@ -1049,6 +1053,7 @@ public abstract class CodedOutputStream extends ByteOutput { writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP); } + /** * Write a {@code group} field to the stream. * @@ -1059,6 +1064,7 @@ public abstract class CodedOutputStream extends ByteOutput { value.writeTo(this); } + /** * Compute the number of bytes that would be needed to encode a * {@code group} field, including tag. @@ -1070,6 +1076,7 @@ public abstract class CodedOutputStream extends ByteOutput { return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value); } + /** * Compute the number of bytes that would be needed to encode a * {@code group} field. @@ -1079,6 +1086,7 @@ public abstract class CodedOutputStream extends ByteOutput { return value.getSerializedSize(); } + /** * Encode and write a varint. {@code value} is treated as * unsigned, so it won't be sign-extended if negative. @@ -1273,6 +1281,7 @@ public abstract class CodedOutputStream extends ByteOutput { writeMessageNoTag(value); } + @Override public final void writeMessageSetExtension(final int fieldNumber, final MessageLite value) throws IOException { @@ -1297,6 +1306,7 @@ public abstract class CodedOutputStream extends ByteOutput { value.writeTo(this); } + @Override public final void write(byte value) throws IOException { try { @@ -1608,6 +1618,7 @@ public abstract class CodedOutputStream extends ByteOutput { writeMessageNoTag(value); } + @Override public void writeMessageSetExtension(final int fieldNumber, final MessageLite value) throws IOException { @@ -1632,6 +1643,7 @@ public abstract class CodedOutputStream extends ByteOutput { value.writeTo(this); } + @Override public void write(byte value) throws IOException { try { @@ -1928,6 +1940,7 @@ public abstract class CodedOutputStream extends ByteOutput { writeMessageNoTag(value); } + @Override public void writeMessageSetExtension(int fieldNumber, MessageLite value) throws IOException { writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP); @@ -1950,6 +1963,7 @@ public abstract class CodedOutputStream extends ByteOutput { value.writeTo(this); } + @Override public void write(byte value) throws IOException { if (position >= limit) { @@ -2456,6 +2470,7 @@ public abstract class CodedOutputStream extends ByteOutput { writeMessageNoTag(value); } + @Override public void writeMessageSetExtension(final int fieldNumber, final MessageLite value) throws IOException { @@ -2480,6 +2495,7 @@ public abstract class CodedOutputStream extends ByteOutput { value.writeTo(this); } + @Override public void write(byte value) throws IOException { if (position == limit) { @@ -2759,6 +2775,7 @@ public abstract class CodedOutputStream extends ByteOutput { writeMessageNoTag(value); } + @Override public void writeMessageSetExtension(final int fieldNumber, final MessageLite value) throws IOException { @@ -2783,6 +2800,7 @@ public abstract class CodedOutputStream extends ByteOutput { value.writeTo(this); } + @Override public void write(byte value) throws IOException { if (position == limit) { diff --git a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java index 867b85ce86..5b28b4a8c7 100644 --- a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java @@ -81,6 +81,18 @@ final class DoubleArrayList extends AbstractProtobufList this.size = size; } + @Override + protected void removeRange(int fromIndex, int toIndex) { + ensureIsMutable(); + if (toIndex < fromIndex) { + throw new IndexOutOfBoundsException("toIndex < fromIndex"); + } + + System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); + size -= (toIndex - fromIndex); + modCount++; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -247,7 +259,9 @@ final class DoubleArrayList extends AbstractProtobufList ensureIsMutable(); ensureIndexInRange(index); double value = array[index]; - System.arraycopy(array, index + 1, array, index, size - index); + if (index < size - 1) { + System.arraycopy(array, index + 1, array, index, size - index); + } size--; modCount++; return value; diff --git a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java index ba5320217d..a6a774b76e 100644 --- a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java +++ b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java @@ -339,6 +339,20 @@ public final class DynamicMessage extends AbstractMessage { this.fields = FieldSet.newFieldSet(); this.unknownFields = UnknownFieldSet.getDefaultInstance(); this.oneofCases = new FieldDescriptor[type.toProto().getOneofDeclCount()]; + // A MapEntry has all of its fields present at all times. + if (type.getOptions().getMapEntry()) { + populateMapEntry(); + } + } + + private void populateMapEntry() { + for (FieldDescriptor field : type.getFields()) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + fields.setField(field, getDefaultInstance(field.getMessageType())); + } else { + fields.setField(field, field.getDefaultValue()); + } + } } // --------------------------------------------------------------- @@ -351,6 +365,10 @@ public final class DynamicMessage extends AbstractMessage { } else { fields.clear(); } + // A MapEntry has all of its fields present at all times. + if (type.getOptions().getMapEntry()) { + populateMapEntry(); + } unknownFields = UnknownFieldSet.getDefaultInstance(); return this; } diff --git a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java index 76645583eb..7c080af3ee 100644 --- a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java @@ -81,6 +81,18 @@ final class FloatArrayList extends AbstractProtobufList this.size = size; } + @Override + protected void removeRange(int fromIndex, int toIndex) { + ensureIsMutable(); + if (toIndex < fromIndex) { + throw new IndexOutOfBoundsException("toIndex < fromIndex"); + } + + System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); + size -= (toIndex - fromIndex); + modCount++; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -246,7 +258,9 @@ final class FloatArrayList extends AbstractProtobufList ensureIsMutable(); ensureIndexInRange(index); float value = array[index]; - System.arraycopy(array, index + 1, array, index, size - index); + if (index < size - 1) { + System.arraycopy(array, index + 1, array, index, size - index); + } size--; modCount++; return value; diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java index 8b8d9fc67b..df01547e56 100644 --- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java +++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java @@ -230,9 +230,13 @@ public abstract class GeneratedMessageLite< * Called by subclasses to complete parsing. For use by generated code only. */ protected void makeImmutable() { + // BEGIN REGULAR dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE); - unknownFields.makeImmutable(); + // END REGULAR + // BEGIN EXPERIMENTAL + // Protobuf.getInstance().schemaFor(this).makeImmutable(this); + // END EXPERIMENTAL } protected final < @@ -269,15 +273,15 @@ public abstract class GeneratedMessageLite< * For use by generated code only. */ public static enum MethodToInvoke { - IS_INITIALIZED, // BEGIN REGULAR + IS_INITIALIZED, VISIT, + MERGE_FROM_STREAM, + MAKE_IMMUTABLE, // END REGULAR // Rely on/modify instance state GET_MEMOIZED_IS_INITIALIZED, SET_MEMOIZED_IS_INITIALIZED, - MERGE_FROM_STREAM, - MAKE_IMMUTABLE, // Rely on static state NEW_MUTABLE_INSTANCE, @@ -339,6 +343,16 @@ public abstract class GeneratedMessageLite< } // END REGULAR + @Override + int getMemoizedSerializedSize() { + return memoizedSerializedSize; + } + + @Override + void setMemoizedSerializedSize(int size) { + memoizedSerializedSize = size; + } + /** @@ -448,6 +462,28 @@ public abstract class GeneratedMessageLite< return defaultInstance; } + @Override + public BuilderType mergeFrom(byte[] input, int offset, int length) + throws InvalidProtocolBufferException { + // BEGIN REGULAR + return super.mergeFrom(input, offset, length); + // END REGULAR + // BEGIN EXPERIMENTAL + // copyOnWrite(); + // try { + // Protobuf.getInstance().schemaFor(instance).mergeFrom( + // instance, input, offset, offset + length, new ArrayDecoders.Registers()); + // } catch (InvalidProtocolBufferException e) { + // throw e; + // } catch (IndexOutOfBoundsException e) { + // throw InvalidProtocolBufferException.truncatedMessage(); + // } catch (IOException e) { + // throw new RuntimeException("Reading from byte array should not throw IOException.", e); + // } + // return (BuilderType) this; + // END EXPERIMENTAL + } + @Override public BuilderType mergeFrom( com.google.protobuf.CodedInputStream input, @@ -455,7 +491,13 @@ public abstract class GeneratedMessageLite< throws IOException { copyOnWrite(); try { + // BEGIN REGULAR instance.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry); + // END REGULAR + // BEGIN EXPERIMENTAL + // Protobuf.getInstance().schemaFor(instance).mergeFrom( + // instance, CodedInputStreamReader.forCodedInput(input), extensionRegistry); + // END EXPERIMENTAL } catch (RuntimeException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); @@ -576,9 +618,7 @@ public abstract class GeneratedMessageLite< return parseUnknownField(tag, input); } - if (extensions.isImmutable()) { - extensions = extensions.clone(); - } + ensureExtensionsAreMutable(); if (packed) { int length = input.readRawVarint32(); @@ -794,10 +834,18 @@ public abstract class GeneratedMessageLite< if (subBuilder == null) { subBuilder = extension.getMessageDefaultInstance().newBuilderForType(); } - rawBytes.newCodedInput().readMessage(subBuilder, extensionRegistry); + subBuilder.mergeFrom(rawBytes, extensionRegistry); MessageLite value = subBuilder.build(); - extensions.setField(extension.descriptor, extension.singularToFieldSetType(value)); + ensureExtensionsAreMutable().setField( + extension.descriptor, extension.singularToFieldSetType(value)); + } + + private FieldSet ensureExtensionsAreMutable() { + if (extensions.isImmutable()) { + extensions = extensions.clone(); + } + return extensions; } private void verifyExtensionContainingType( @@ -869,10 +917,12 @@ public abstract class GeneratedMessageLite< @Override protected final void makeImmutable() { super.makeImmutable(); - + // BEGIN REGULAR extensions.makeImmutable(); + // END REGULAR } + /** * Used by subclasses to serialize extensions. Extension ranges may be * interleaved with field numbers, but we must write them in canonical @@ -1468,8 +1518,13 @@ public abstract class GeneratedMessageLite< if (memoizedIsInitialized == 0) { return false; } + // BEGIN EXPERIMENTAL + // boolean isInitialized = Protobuf.getInstance().schemaFor(message).isInitialized(message); + // END EXPERIMENTAL + // BEGIN REGULAR boolean isInitialized = message.dynamicMethod(MethodToInvoke.IS_INITIALIZED, Boolean.FALSE) != null; + // END REGULAR if (shouldMemoize) { message.dynamicMethod( MethodToInvoke.SET_MEMOIZED_IS_INITIALIZED, isInitialized ? message : null); @@ -1477,10 +1532,6 @@ public abstract class GeneratedMessageLite< return isInitialized; } - protected static final > void makeImmutable(T message) { - message.dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE); - } - protected static IntList emptyIntList() { return IntArrayList.emptyList(); } @@ -1560,6 +1611,11 @@ public abstract class GeneratedMessageLite< throws InvalidProtocolBufferException { return GeneratedMessageLite.parsePartialFrom(defaultInstance, input, extensionRegistry); } + + @Override + public T parsePartialFrom(byte[] input) throws InvalidProtocolBufferException { + return GeneratedMessageLite.parsePartialFrom(defaultInstance, input); + } } /** @@ -1573,8 +1629,21 @@ public abstract class GeneratedMessageLite< @SuppressWarnings("unchecked") // Guaranteed by protoc T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE); try { + // BEGIN REGULAR result.dynamicMethod(MethodToInvoke.MERGE_FROM_STREAM, input, extensionRegistry); + // END REGULAR + // BEGIN EXPERIMENTAL + // Protobuf.getInstance().schemaFor(result).mergeFrom( + // result, CodedInputStreamReader.forCodedInput(input), extensionRegistry); + // END EXPERIMENTAL result.makeImmutable(); + // BEGIN EXPERIMENTAL + // } catch (IOException e) { + // if (e.getCause() instanceof InvalidProtocolBufferException) { + // throw (InvalidProtocolBufferException) e.getCause(); + // } + // throw new InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(result); + // END EXPERIMENTAL } catch (RuntimeException e) { if (e.getCause() instanceof InvalidProtocolBufferException) { throw (InvalidProtocolBufferException) e.getCause(); @@ -1584,6 +1653,34 @@ public abstract class GeneratedMessageLite< return result; } + /** A static helper method for parsing a partial from byte array. */ + static > T parsePartialFrom(T instance, byte[] input) + throws InvalidProtocolBufferException { + // BEGIN REGULAR + return parsePartialFrom(instance, input, ExtensionRegistryLite.getEmptyRegistry()); + // END REGULAR + // BEGIN EXPERIMENTAL + // @SuppressWarnings("unchecked") // Guaranteed by protoc + // T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE); + // try { + // Protobuf.getInstance().schemaFor(result).mergeFrom( + // result, input, 0, input.length, new ArrayDecoders.Registers()); + // result.makeImmutable(); + // if (result.memoizedHashCode != 0) { + // throw new RuntimeException(); + // } + // } catch (IOException e) { + // if (e.getCause() instanceof InvalidProtocolBufferException) { + // throw (InvalidProtocolBufferException) e.getCause(); + // } + // throw new InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(result); + // } catch (IndexOutOfBoundsException e) { + // throw InvalidProtocolBufferException.truncatedMessage().setUnfinishedMessage(result); + // } + // return result; + // END EXPERIMENTAL + } + protected static > T parsePartialFrom( T defaultInstance, CodedInputStream input) @@ -1680,8 +1777,7 @@ public abstract class GeneratedMessageLite< protected static > T parseFrom( T defaultInstance, byte[] data) throws InvalidProtocolBufferException { - return checkMessageInitialized( - parsePartialFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry())); + return checkMessageInitialized(parsePartialFrom(defaultInstance, data)); } // Validates last tag. diff --git a/java/core/src/main/java/com/google/protobuf/IntArrayList.java b/java/core/src/main/java/com/google/protobuf/IntArrayList.java index aff5c21b26..aacd71e1ca 100644 --- a/java/core/src/main/java/com/google/protobuf/IntArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/IntArrayList.java @@ -81,6 +81,18 @@ final class IntArrayList extends AbstractProtobufList this.size = size; } + @Override + protected void removeRange(int fromIndex, int toIndex) { + ensureIsMutable(); + if (toIndex < fromIndex) { + throw new IndexOutOfBoundsException("toIndex < fromIndex"); + } + + System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); + size -= (toIndex - fromIndex); + modCount++; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -246,7 +258,9 @@ final class IntArrayList extends AbstractProtobufList ensureIsMutable(); ensureIndexInRange(index); int value = array[index]; - System.arraycopy(array, index + 1, array, index, size - index); + if (index < size - 1) { + System.arraycopy(array, index + 1, array, index, size - index); + } size--; modCount++; return value; diff --git a/java/core/src/main/java/com/google/protobuf/LongArrayList.java b/java/core/src/main/java/com/google/protobuf/LongArrayList.java index fc146e232b..95945cb723 100644 --- a/java/core/src/main/java/com/google/protobuf/LongArrayList.java +++ b/java/core/src/main/java/com/google/protobuf/LongArrayList.java @@ -81,6 +81,18 @@ final class LongArrayList extends AbstractProtobufList this.size = size; } + @Override + protected void removeRange(int fromIndex, int toIndex) { + ensureIsMutable(); + if (toIndex < fromIndex) { + throw new IndexOutOfBoundsException("toIndex < fromIndex"); + } + + System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); + size -= (toIndex - fromIndex); + modCount++; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -246,7 +258,9 @@ final class LongArrayList extends AbstractProtobufList ensureIsMutable(); ensureIndexInRange(index); long value = array[index]; - System.arraycopy(array, index + 1, array, index, size - index); + if (index < size - 1) { + System.arraycopy(array, index + 1, array, index, size - index); + } size--; modCount++; return value; diff --git a/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java b/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java index 23373ef4cd..8e2659359b 100644 --- a/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java +++ b/java/core/src/main/java/com/google/protobuf/MessageLiteToString.java @@ -31,6 +31,7 @@ package com.google.protobuf; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -38,20 +39,18 @@ import java.util.Map; import java.util.Set; import java.util.TreeSet; -/** - * Helps generate {@link String} representations of {@link MessageLite} protos. - */ -// TODO(dweis): Fix map fields. +/** Helps generate {@link String} representations of {@link MessageLite} protos. */ final class MessageLiteToString { private static final String LIST_SUFFIX = "List"; private static final String BUILDER_LIST_SUFFIX = "OrBuilderList"; + private static final String MAP_SUFFIX = "Map"; private static final String BYTES_SUFFIX = "Bytes"; - + /** - * Returns a {@link String} representation of the {@link MessageLite} object. The first line of + * Returns a {@link String} representation of the {@link MessageLite} object. The first line of * the {@code String} representation representation includes a comment string to uniquely identify - * the objcet instance. This acts as an indicator that this should not be relied on for + * the object instance. This acts as an indicator that this should not be relied on for * comparisons. * *

For use by generated code only. @@ -71,8 +70,9 @@ final class MessageLiteToString { */ private static void reflectivePrintWithIndent( MessageLite messageLite, StringBuilder buffer, int indent) { - // Build a map of method name to method. We're looking for methods like getFoo(), hasFoo(), and - // getFooList() which might be useful for building an object's string representation. + // Build a map of method name to method. We're looking for methods like getFoo(), hasFoo(), + // getFooList() and getFooMap() which might be useful for building an object's string + // representation. Map nameToNoArgMethod = new HashMap(); Map nameToMethod = new HashMap(); Set getters = new TreeSet(); @@ -89,12 +89,16 @@ final class MessageLiteToString { for (String getter : getters) { String suffix = getter.replaceFirst("get", ""); - if (suffix.endsWith(LIST_SUFFIX) && !suffix.endsWith(BUILDER_LIST_SUFFIX)) { - String camelCase = suffix.substring(0, 1).toLowerCase() - + suffix.substring(1, suffix.length() - LIST_SUFFIX.length()); + if (suffix.endsWith(LIST_SUFFIX) + && !suffix.endsWith(BUILDER_LIST_SUFFIX) + // Sometimes people have fields named 'list' that aren't repeated. + && !suffix.equals(LIST_SUFFIX)) { + String camelCase = + suffix.substring(0, 1).toLowerCase() + + suffix.substring(1, suffix.length() - LIST_SUFFIX.length()); // Try to reflectively get the value and toString() the field as if it were repeated. This - // only works if the method names have not be proguarded out or renamed. - Method listMethod = nameToNoArgMethod.get("get" + suffix); + // only works if the method names have not been proguarded out or renamed. + Method listMethod = nameToNoArgMethod.get(getter); if (listMethod != null && listMethod.getReturnType().equals(List.class)) { printField( buffer, @@ -104,6 +108,30 @@ final class MessageLiteToString { continue; } } + if (suffix.endsWith(MAP_SUFFIX) + // Sometimes people have fields named 'map' that aren't maps. + && !suffix.equals(MAP_SUFFIX)) { + String camelCase = + suffix.substring(0, 1).toLowerCase() + + suffix.substring(1, suffix.length() - MAP_SUFFIX.length()); + // Try to reflectively get the value and toString() the field as if it were a map. This only + // works if the method names have not been proguarded out or renamed. + Method mapMethod = nameToNoArgMethod.get(getter); + if (mapMethod != null + && mapMethod.getReturnType().equals(Map.class) + // Skip the deprecated getter method with no prefix "Map" when the field name ends with + // "map". + && !mapMethod.isAnnotationPresent(Deprecated.class) + // Skip the internal mutable getter method. + && Modifier.isPublic(mapMethod.getModifiers())) { + printField( + buffer, + indent, + camelCaseToSnakeCase(camelCase), + GeneratedMessageLite.invokeOrDie(mapMethod, messageLite)); + continue; + } + } Method setter = nameToMethod.get("set" + suffix); if (setter == null) { @@ -119,22 +147,19 @@ final class MessageLiteToString { String camelCase = suffix.substring(0, 1).toLowerCase() + suffix.substring(1); // Try to reflectively get the value and toString() the field as if it were optional. This - // only works if the method names have not be proguarded out or renamed. + // only works if the method names have not been proguarded out or renamed. Method getMethod = nameToNoArgMethod.get("get" + suffix); Method hasMethod = nameToNoArgMethod.get("has" + suffix); // TODO(dweis): Fix proto3 semantics. if (getMethod != null) { Object value = GeneratedMessageLite.invokeOrDie(getMethod, messageLite); - final boolean hasValue = hasMethod == null - ? !isDefaultValue(value) - : (Boolean) GeneratedMessageLite.invokeOrDie(hasMethod, messageLite); - // TODO(dweis): This doesn't stop printing oneof case twice: value and enum style. + final boolean hasValue = + hasMethod == null + ? !isDefaultValue(value) + : (Boolean) GeneratedMessageLite.invokeOrDie(hasMethod, messageLite); + // TODO(dweis): This doesn't stop printing oneof case twice: value and enum style. if (hasValue) { - printField( - buffer, - indent, - camelCaseToSnakeCase(camelCase), - value); + printField(buffer, indent, camelCaseToSnakeCase(camelCase), value); } continue; } @@ -153,7 +178,7 @@ final class MessageLiteToString { ((GeneratedMessageLite) messageLite).unknownFields.printWithIndent(buffer, indent); } } - + private static boolean isDefaultValue(Object o) { if (o instanceof Boolean) { return !((Boolean) o); @@ -179,7 +204,7 @@ final class MessageLiteToString { if (o instanceof java.lang.Enum) { // Catches oneof enums. return ((java.lang.Enum) o).ordinal() == 0; } - + return false; } @@ -201,6 +226,13 @@ final class MessageLiteToString { } return; } + if (object instanceof Map) { + Map map = (Map) object; + for (Map.Entry entry : map.entrySet()) { + printField(buffer, indent, name, entry); + } + return; + } buffer.append('\n'); for (int i = 0; i < indent; i++) { @@ -220,11 +252,21 @@ final class MessageLiteToString { buffer.append(' '); } buffer.append("}"); + } else if (object instanceof Map.Entry) { + buffer.append(" {"); + Map.Entry entry = (Map.Entry) object; + printField(buffer, indent + 2, "key", entry.getKey()); + printField(buffer, indent + 2, "value", entry.getValue()); + buffer.append("\n"); + for (int i = 0; i < indent; i++) { + buffer.append(' '); + } + buffer.append("}"); } else { buffer.append(": ").append(object.toString()); } } - + private static final String camelCaseToSnakeCase(String camelCase) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < camelCase.length(); i++) { diff --git a/java/core/src/main/java/com/google/protobuf/TextFormat.java b/java/core/src/main/java/com/google/protobuf/TextFormat.java index 0c8b898c21..25c3474f91 100644 --- a/java/core/src/main/java/com/google/protobuf/TextFormat.java +++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java @@ -987,7 +987,7 @@ public final class TextFormat { nextToken(); return false; } else { - throw parseException("Expected \"true\" or \"false\"."); + throw parseException("Expected \"true\" or \"false\". Found \"" + currentToken + "\"."); } } @@ -1311,13 +1311,17 @@ public final class TextFormat { } private final boolean allowUnknownFields; + private final boolean allowUnknownEnumValues; private final SingularOverwritePolicy singularOverwritePolicy; private TextFormatParseInfoTree.Builder parseInfoTreeBuilder; private Parser( - boolean allowUnknownFields, SingularOverwritePolicy singularOverwritePolicy, + boolean allowUnknownFields, + boolean allowUnknownEnumValues, + SingularOverwritePolicy singularOverwritePolicy, TextFormatParseInfoTree.Builder parseInfoTreeBuilder) { this.allowUnknownFields = allowUnknownFields; + this.allowUnknownEnumValues = allowUnknownEnumValues; this.singularOverwritePolicy = singularOverwritePolicy; this.parseInfoTreeBuilder = parseInfoTreeBuilder; } @@ -1334,6 +1338,7 @@ public final class TextFormat { */ public static class Builder { private boolean allowUnknownFields = false; + private boolean allowUnknownEnumValues = false; private SingularOverwritePolicy singularOverwritePolicy = SingularOverwritePolicy.ALLOW_SINGULAR_OVERWRITES; private TextFormatParseInfoTree.Builder parseInfoTreeBuilder = null; @@ -1355,7 +1360,10 @@ public final class TextFormat { public Parser build() { return new Parser( - allowUnknownFields, singularOverwritePolicy, parseInfoTreeBuilder); + allowUnknownFields, + allowUnknownEnumValues, + singularOverwritePolicy, + parseInfoTreeBuilder); } } @@ -1419,7 +1427,7 @@ public final class TextFormat { return text; } - // Check both unknown fields and unknown extensions and log warming messages + // Check both unknown fields and unknown extensions and log warning messages // or throw exceptions according to the flag. private void checkUnknownFields(final List unknownFields) throws ParseException { @@ -1737,17 +1745,40 @@ public final class TextFormat { final int number = tokenizer.consumeInt32(); value = enumType.findValueByNumber(number); if (value == null) { - throw tokenizer.parseExceptionPreviousToken( - "Enum type \"" + enumType.getFullName() - + "\" has no value with number " + number + '.'); + String unknownValueMsg = + "Enum type \"" + + enumType.getFullName() + + "\" has no value with number " + + number + + '.'; + if (allowUnknownEnumValues) { + logger.warning(unknownValueMsg); + return; + } else { + throw tokenizer.parseExceptionPreviousToken( + "Enum type \"" + + enumType.getFullName() + + "\" has no value with number " + + number + + '.'); + } } } else { final String id = tokenizer.consumeIdentifier(); value = enumType.findValueByName(id); if (value == null) { - throw tokenizer.parseExceptionPreviousToken( - "Enum type \"" + enumType.getFullName() - + "\" has no value named \"" + id + "\"."); + String unknownValueMsg = + "Enum type \"" + + enumType.getFullName() + + "\" has no value named \"" + + id + + "\"."; + if (allowUnknownEnumValues) { + logger.warning(unknownValueMsg); + return; + } else { + throw tokenizer.parseExceptionPreviousToken(unknownValueMsg); + } } } diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java index 2a614c846f..f0b919adae 100644 --- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java +++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java @@ -295,14 +295,30 @@ public final class UnknownFieldSetLite { return true; } + private static int hashCode(int[] tags, int count) { + int hashCode = 17; + for (int i = 0; i < count; ++i) { + hashCode = 31 * hashCode + tags[i]; + } + return hashCode; + } + + private static int hashCode(Object[] objects, int count) { + int hashCode = 17; + for (int i = 0; i < count; ++i) { + hashCode = 31 * hashCode + objects[i].hashCode(); + } + return hashCode; + } + @Override public int hashCode() { int hashCode = 17; - + hashCode = 31 * hashCode + count; - hashCode = 31 * hashCode + Arrays.hashCode(tags); - hashCode = 31 * hashCode + Arrays.deepHashCode(objects); - + hashCode = 31 * hashCode + hashCode(tags, count); + hashCode = 31 * hashCode + hashCode(objects, count); + return hashCode; } diff --git a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java index b09ff67326..c9e2904b4c 100644 --- a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java +++ b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java @@ -33,6 +33,7 @@ package com.google.protobuf; import java.lang.reflect.Field; import java.nio.Buffer; import java.nio.ByteBuffer; +import java.nio.ByteOrder; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.util.logging.Level; @@ -83,6 +84,7 @@ final class UnsafeUtil { return HAS_UNSAFE_BYTEBUFFER_OPERATIONS; } + static long objectFieldOffset(Field field) { return MEMORY_ACCESSOR.objectFieldOffset(field); } @@ -287,7 +289,7 @@ final class UnsafeUtil { /** * Gets the {@code sun.misc.Unsafe} instance, or {@code null} if not available on this platform. */ - private static sun.misc.Unsafe getUnsafe() { + static sun.misc.Unsafe getUnsafe() { sun.misc.Unsafe unsafe = null; try { unsafe = @@ -367,6 +369,10 @@ final class UnsafeUtil { clazz.getMethod("objectFieldOffset", Field.class); clazz.getMethod("getLong", Object.class, long.class); + if (bufferAddressField() == null) { + return false; + } + clazz.getMethod("getByte", long.class); clazz.getMethod("putByte", long.class, byte.class); clazz.getMethod("getInt", long.class); @@ -387,12 +393,14 @@ final class UnsafeUtil { /** Finds the address field within a direct {@link Buffer}. */ private static Field bufferAddressField() { - return field(Buffer.class, "address", long.class); + Field field = field(Buffer.class, "address"); + return field != null && field.getType() == long.class ? field : null; } /** Finds the value field within a {@link String}. */ private static Field stringValueField() { - return field(String.class, "value", char[].class); + Field field = field(String.class, "value"); + return field != null && field.getType() == char[].class ? field : null; } /** @@ -407,14 +415,11 @@ final class UnsafeUtil { * Gets the field with the given name within the class, or {@code null} if not found. If found, * the field is made accessible. */ - private static Field field(Class clazz, String fieldName, Class expectedType) { + private static Field field(Class clazz, String fieldName) { Field field; try { field = clazz.getDeclaredField(fieldName); field.setAccessible(true); - if (!field.getType().equals(expectedType)) { - return null; - } } catch (Throwable t) { // Failed to access the fields. field = null; diff --git a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java index 18132e9e03..4906763c35 100644 --- a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java @@ -32,6 +32,7 @@ package com.google.protobuf; import static java.util.Arrays.asList; +import com.google.protobuf.Internal.BooleanList; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -297,6 +298,20 @@ public class BooleanArrayListTest extends TestCase { } } + public void testRemoveEndOfCapacity() { + BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addBoolean(true); + toRemove.remove(0); + assertEquals(0, toRemove.size()); + } + + public void testSublistRemoveEndOfCapacity() { + BooleanList toRemove = BooleanArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addBoolean(true); + toRemove.subList(0, 1).clear(); + assertEquals(0, toRemove.size()); + } + private void assertImmutable(BooleanArrayList list) { try { diff --git a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java index cc65d19ab7..50b87ae31f 100644 --- a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java +++ b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java @@ -34,7 +34,7 @@ import proto2_test_check_utf8.TestCheckUtf8.BytesWrapper; import proto2_test_check_utf8.TestCheckUtf8.StringWrapper; import proto2_test_check_utf8_size.TestCheckUtf8Size.BytesWrapperSize; import proto2_test_check_utf8_size.TestCheckUtf8Size.StringWrapperSize; - +import java.io.ByteArrayInputStream; import junit.framework.TestCase; /** @@ -90,14 +90,9 @@ public class CheckUtf8Test extends TestCase { } public void testParseRequiredStringWithBadUtf8() throws Exception { - ByteString serialized = - BytesWrapper.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteString(); - try { - StringWrapper.parser().parseFrom(serialized); - fail("Expected InvalidProtocolBufferException for non UTF-8 byte string."); - } catch (InvalidProtocolBufferException exception) { - assertEquals("Protocol message had invalid UTF-8.", exception.getMessage()); - } + byte[] serialized = + BytesWrapper.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteArray(); + assertParseBadUtf8(StringWrapper.getDefaultInstance(), serialized); } public void testBuildRequiredStringWithBadUtf8Size() throws Exception { @@ -128,14 +123,36 @@ public class CheckUtf8Test extends TestCase { } public void testParseRequiredStringWithBadUtf8Size() throws Exception { - ByteString serialized = - BytesWrapperSize.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteString(); + byte[] serialized = + BytesWrapperSize.newBuilder().setReq(NON_UTF8_BYTE_STRING).build().toByteArray(); + assertParseBadUtf8(StringWrapperSize.getDefaultInstance(), serialized); + } + + private void assertParseBadUtf8(MessageLite defaultInstance, byte[] data) throws Exception { + // Check combinations of (parser vs. builder) x (byte[] vs. InputStream) + try { + defaultInstance.getParserForType().parseFrom(data); + fail("Expected InvalidProtocolBufferException for non UTF-8 byte string."); + } catch (InvalidProtocolBufferException exception) { + assertEquals("Protocol message had invalid UTF-8.", exception.getMessage()); + } + try { + defaultInstance.newBuilderForType().mergeFrom(data); + fail("Expected InvalidProtocolBufferException for non UTF-8 byte string."); + } catch (InvalidProtocolBufferException exception) { + assertEquals("Protocol message had invalid UTF-8.", exception.getMessage()); + } try { - StringWrapperSize.parser().parseFrom(serialized); + defaultInstance.getParserForType().parseFrom(new ByteArrayInputStream(data)); + fail("Expected InvalidProtocolBufferException for non UTF-8 byte string."); + } catch (InvalidProtocolBufferException exception) { + assertEquals("Protocol message had invalid UTF-8.", exception.getMessage()); + } + try { + defaultInstance.newBuilderForType().mergeFrom(new ByteArrayInputStream(data)); fail("Expected InvalidProtocolBufferException for non UTF-8 byte string."); } catch (InvalidProtocolBufferException exception) { assertEquals("Protocol message had invalid UTF-8.", exception.getMessage()); } } - } diff --git a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java index d894279297..923d7f4302 100644 --- a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java @@ -32,6 +32,7 @@ package com.google.protobuf; import static java.util.Arrays.asList; +import com.google.protobuf.Internal.DoubleList; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -297,6 +298,20 @@ public class DoubleArrayListTest extends TestCase { } } + public void testRemoveEndOfCapacity() { + DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addDouble(3); + toRemove.remove(0); + assertEquals(0, toRemove.size()); + } + + public void testSublistRemoveEndOfCapacity() { + DoubleList toRemove = DoubleArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addDouble(3); + toRemove.subList(0, 1).clear(); + assertEquals(0, toRemove.size()); + } + private void assertImmutable(DoubleArrayList list) { if (list.contains(1D)) { throw new RuntimeException("Cannot test the immutability of lists that contain 1."); diff --git a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java index aa36be4977..903a79dbff 100644 --- a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java @@ -32,6 +32,7 @@ package com.google.protobuf; import static java.util.Arrays.asList; +import com.google.protobuf.Internal.FloatList; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -297,6 +298,20 @@ public class FloatArrayListTest extends TestCase { } } + public void testRemoveEndOfCapacity() { + FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addFloat(3); + toRemove.remove(0); + assertEquals(0, toRemove.size()); + } + + public void testSublistRemoveEndOfCapacity() { + FloatList toRemove = FloatArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addFloat(3); + toRemove.subList(0, 1).clear(); + assertEquals(0, toRemove.size()); + } + private void assertImmutable(FloatArrayList list) { if (list.contains(1F)) { throw new RuntimeException("Cannot test the immutability of lists that contain 1."); diff --git a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java index 60c85450c3..d8e97d4f29 100644 --- a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java @@ -32,6 +32,7 @@ package com.google.protobuf; import static java.util.Arrays.asList; +import com.google.protobuf.Internal.IntList; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -297,6 +298,20 @@ public class IntArrayListTest extends TestCase { } } + public void testRemoveEndOfCapacity() { + IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addInt(3); + toRemove.remove(0); + assertEquals(0, toRemove.size()); + } + + public void testSublistRemoveEndOfCapacity() { + IntList toRemove = IntArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addInt(3); + toRemove.subList(0, 1).clear(); + assertEquals(0, toRemove.size()); + } + private void assertImmutable(IntArrayList list) { if (list.contains(1)) { throw new RuntimeException("Cannot test the immutability of lists that contain 1."); diff --git a/java/core/src/test/java/com/google/protobuf/LiteTest.java b/java/core/src/test/java/com/google/protobuf/LiteTest.java index 40b4453802..5ab80ca2ce 100644 --- a/java/core/src/test/java/com/google/protobuf/LiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/LiteTest.java @@ -48,11 +48,15 @@ import com.google.protobuf.UnittestLite.TestAllTypesLite.RepeatedGroup; import com.google.protobuf.UnittestLite.TestAllTypesLiteOrBuilder; import com.google.protobuf.UnittestLite.TestHugeFieldNumbersLite; import com.google.protobuf.UnittestLite.TestNestedExtensionLite; +import map_lite_test.MapTestProto.TestMap; +import map_lite_test.MapTestProto.TestMap.MessageValue; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Bar; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.BarPrime; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Foo; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestOneofEquals; import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestRecursiveOneof; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -88,12 +92,11 @@ public class LiteTest extends TestCase { // stuff to make sure the lite message is actually here and usable. TestAllTypesLite message = - TestAllTypesLite.newBuilder() - .setOptionalInt32(123) - .addRepeatedString("hello") - .setOptionalNestedMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) - .build(); + TestAllTypesLite.newBuilder() + .setOptionalInt32(123) + .addRepeatedString("hello") + .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) + .build(); ByteString data = message.toByteString(); @@ -105,57 +108,66 @@ public class LiteTest extends TestCase { assertEquals(7, message2.getOptionalNestedMessage().getBb()); } + public void testLite_unknownEnumAtListBoundary() throws Exception { + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + CodedOutputStream output = CodedOutputStream.newInstance(byteStream); + for (int i = 0; i < AbstractProtobufList.DEFAULT_CAPACITY; i++) { + output.writeInt32(TestAllTypesLite.REPEATED_NESTED_ENUM_FIELD_NUMBER, 1); + } + // 0 is not a valid enum value for NestedEnum + output.writeInt32(TestAllTypesLite.REPEATED_NESTED_ENUM_FIELD_NUMBER, 0); + output.flush(); + // This tests a bug we had once with removal right at the boundary of the array. It would throw + // at runtime so no need to assert. + TestAllTypesLite.parseFrom(new ByteArrayInputStream(byteStream.toByteArray())); + } + public void testLiteExtensions() throws Exception { // TODO(kenton): Unlike other features of the lite library, extensions are // implemented completely differently from the regular library. We // should probably test them more thoroughly. TestAllExtensionsLite message = - TestAllExtensionsLite.newBuilder() - .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) - .addExtension(UnittestLite.repeatedStringExtensionLite, "hello") - .setExtension(UnittestLite.optionalNestedEnumExtensionLite, - TestAllTypesLite.NestedEnum.BAZ) - .setExtension(UnittestLite.optionalNestedMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) - .build(); + TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) + .addExtension(UnittestLite.repeatedStringExtensionLite, "hello") + .setExtension( + UnittestLite.optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ) + .setExtension( + UnittestLite.optionalNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) + .build(); // Test copying a message, since coping extensions actually does use a // different code path between lite and regular libraries, and as of this // writing, parsing hasn't been implemented yet. TestAllExtensionsLite message2 = message.toBuilder().build(); - assertEquals(123, (int) message2.getExtension( - UnittestLite.optionalInt32ExtensionLite)); - assertEquals(1, message2.getExtensionCount( - UnittestLite.repeatedStringExtensionLite)); - assertEquals(1, message2.getExtension( - UnittestLite.repeatedStringExtensionLite).size()); - assertEquals("hello", message2.getExtension( - UnittestLite.repeatedStringExtensionLite, 0)); - assertEquals(TestAllTypesLite.NestedEnum.BAZ, message2.getExtension( - UnittestLite.optionalNestedEnumExtensionLite)); - assertEquals(7, message2.getExtension( - UnittestLite.optionalNestedMessageExtensionLite).getBb()); + assertEquals(123, (int) message2.getExtension(UnittestLite.optionalInt32ExtensionLite)); + assertEquals(1, message2.getExtensionCount(UnittestLite.repeatedStringExtensionLite)); + assertEquals(1, message2.getExtension(UnittestLite.repeatedStringExtensionLite).size()); + assertEquals("hello", message2.getExtension(UnittestLite.repeatedStringExtensionLite, 0)); + assertEquals( + TestAllTypesLite.NestedEnum.BAZ, + message2.getExtension(UnittestLite.optionalNestedEnumExtensionLite)); + assertEquals(7, message2.getExtension(UnittestLite.optionalNestedMessageExtensionLite).getBb()); } - + public void testClone() { - TestAllTypesLite.Builder expected = TestAllTypesLite.newBuilder() - .setOptionalInt32(123); - assertEquals( - expected.getOptionalInt32(), expected.clone().getOptionalInt32()); - - TestAllExtensionsLite.Builder expected2 = TestAllExtensionsLite.newBuilder() - .setExtension(UnittestLite.optionalInt32ExtensionLite, 123); + TestAllTypesLite.Builder expected = TestAllTypesLite.newBuilder().setOptionalInt32(123); + assertEquals(expected.getOptionalInt32(), expected.clone().getOptionalInt32()); + + TestAllExtensionsLite.Builder expected2 = + TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalInt32ExtensionLite, 123); assertEquals( expected2.getExtension(UnittestLite.optionalInt32ExtensionLite), expected2.clone().getExtension(UnittestLite.optionalInt32ExtensionLite)); } - + public void testAddAll() { try { - TestAllTypesLite.newBuilder() - .addAllRepeatedBytes(null); + TestAllTypesLite.newBuilder().addAllRepeatedBytes(null); fail(); } catch (NullPointerException e) { // expected. @@ -186,7 +198,7 @@ public class LiteTest extends TestCase { // We have to cast to Byte first. Casting to byte causes a type error assertEquals(1, ((Byte) memo.get(message)).intValue()); } - + public void testSanityCopyOnWrite() throws InvalidProtocolBufferException { // Since builders are implemented as a thin wrapper around a message // instance, we attempt to verify that we can't cause the builder to modify @@ -210,13 +222,11 @@ public class LiteTest extends TestCase { assertEquals(ByteString.EMPTY, message.getOptionalBytes()); assertEquals(ByteString.copyFromUtf8("hi"), builder.getOptionalBytes()); messageAfterBuild = builder.build(); - assertEquals( - ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes()); + assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes()); assertEquals(ByteString.EMPTY, message.getOptionalBytes()); builder.clearOptionalBytes(); assertEquals(ByteString.EMPTY, builder.getOptionalBytes()); - assertEquals( - ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes()); + assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getOptionalBytes()); message = builder.build(); builder.setOptionalCord("hi"); @@ -234,27 +244,23 @@ public class LiteTest extends TestCase { assertEquals(ByteString.EMPTY, message.getOptionalCordBytes()); assertEquals(ByteString.copyFromUtf8("no"), builder.getOptionalCordBytes()); messageAfterBuild = builder.build(); - assertEquals( - ByteString.copyFromUtf8("no"), - messageAfterBuild.getOptionalCordBytes()); + assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalCordBytes()); assertEquals(ByteString.EMPTY, message.getOptionalCordBytes()); builder.clearOptionalCord(); assertEquals(ByteString.EMPTY, builder.getOptionalCordBytes()); - assertEquals( - ByteString.copyFromUtf8("no"), - messageAfterBuild.getOptionalCordBytes()); - + assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalCordBytes()); + message = builder.build(); builder.setOptionalDouble(1); - assertEquals(0D, message.getOptionalDouble()); - assertEquals(1D, builder.getOptionalDouble()); + assertEquals(0D, message.getOptionalDouble(), 0.0); + assertEquals(1D, builder.getOptionalDouble(), 0.0); messageAfterBuild = builder.build(); - assertEquals(1D, messageAfterBuild.getOptionalDouble()); - assertEquals(0D, message.getOptionalDouble()); + assertEquals(1D, messageAfterBuild.getOptionalDouble(), 0.0); + assertEquals(0D, message.getOptionalDouble(), 0.0); builder.clearOptionalDouble(); - assertEquals(0D, builder.getOptionalDouble()); - assertEquals(1D, messageAfterBuild.getOptionalDouble()); - + assertEquals(0D, builder.getOptionalDouble(), 0.0); + assertEquals(1D, messageAfterBuild.getOptionalDouble(), 0.0); + message = builder.build(); builder.setOptionalFixed32(1); assertEquals(0, message.getOptionalFixed32()); @@ -265,7 +271,7 @@ public class LiteTest extends TestCase { builder.clearOptionalFixed32(); assertEquals(0, builder.getOptionalFixed32()); assertEquals(1, messageAfterBuild.getOptionalFixed32()); - + message = builder.build(); builder.setOptionalFixed64(1); assertEquals(0L, message.getOptionalFixed64()); @@ -279,105 +285,72 @@ public class LiteTest extends TestCase { message = builder.build(); builder.setOptionalFloat(1); - assertEquals(0F, message.getOptionalFloat()); - assertEquals(1F, builder.getOptionalFloat()); + assertEquals(0F, message.getOptionalFloat(), 0.0f); + assertEquals(1F, builder.getOptionalFloat(), 0.0f); messageAfterBuild = builder.build(); - assertEquals(1F, messageAfterBuild.getOptionalFloat()); - assertEquals(0F, message.getOptionalFloat()); + assertEquals(1F, messageAfterBuild.getOptionalFloat(), 0.0f); + assertEquals(0F, message.getOptionalFloat(), 0.0f); builder.clearOptionalFloat(); - assertEquals(0F, builder.getOptionalFloat()); - assertEquals(1F, messageAfterBuild.getOptionalFloat()); + assertEquals(0F, builder.getOptionalFloat(), 0.0f); + assertEquals(1F, messageAfterBuild.getOptionalFloat(), 0.0f); message = builder.build(); builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum()); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_BAR, builder.getOptionalForeignEnum()); + assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum()); + assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, builder.getOptionalForeignEnum()); messageAfterBuild = builder.build(); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_BAR, - messageAfterBuild.getOptionalForeignEnum()); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum()); + assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, messageAfterBuild.getOptionalForeignEnum()); + assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, message.getOptionalForeignEnum()); builder.clearOptionalForeignEnum(); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_FOO, builder.getOptionalForeignEnum()); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_BAR, - messageAfterBuild.getOptionalForeignEnum()); + assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, builder.getOptionalForeignEnum()); + assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, messageAfterBuild.getOptionalForeignEnum()); message = builder.build(); - ForeignMessageLite foreignMessage = ForeignMessageLite.newBuilder() - .setC(1) - .build(); + ForeignMessageLite foreignMessage = ForeignMessageLite.newBuilder().setC(1).build(); builder.setOptionalForeignMessage(foreignMessage); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - message.getOptionalForeignMessage()); + assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage()); assertEquals(foreignMessage, builder.getOptionalForeignMessage()); messageAfterBuild = builder.build(); assertEquals(foreignMessage, messageAfterBuild.getOptionalForeignMessage()); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - message.getOptionalForeignMessage()); + assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage()); builder.clearOptionalForeignMessage(); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - builder.getOptionalForeignMessage()); + assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getOptionalForeignMessage()); assertEquals(foreignMessage, messageAfterBuild.getOptionalForeignMessage()); message = builder.build(); - ForeignMessageLite.Builder foreignMessageBuilder = - ForeignMessageLite.newBuilder() - .setC(3); + ForeignMessageLite.Builder foreignMessageBuilder = ForeignMessageLite.newBuilder().setC(3); builder.setOptionalForeignMessage(foreignMessageBuilder); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - message.getOptionalForeignMessage()); + assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage()); assertEquals(foreignMessageBuilder.build(), builder.getOptionalForeignMessage()); messageAfterBuild = builder.build(); assertEquals(foreignMessageBuilder.build(), messageAfterBuild.getOptionalForeignMessage()); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - message.getOptionalForeignMessage()); + assertEquals(ForeignMessageLite.getDefaultInstance(), message.getOptionalForeignMessage()); builder.clearOptionalForeignMessage(); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - builder.getOptionalForeignMessage()); + assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getOptionalForeignMessage()); assertEquals(foreignMessageBuilder.build(), messageAfterBuild.getOptionalForeignMessage()); message = builder.build(); - OptionalGroup optionalGroup = OptionalGroup.newBuilder() - .setA(1) - .build(); + OptionalGroup optionalGroup = OptionalGroup.newBuilder().setA(1).build(); builder.setOptionalGroup(optionalGroup); - assertEquals( - OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); + assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); assertEquals(optionalGroup, builder.getOptionalGroup()); messageAfterBuild = builder.build(); assertEquals(optionalGroup, messageAfterBuild.getOptionalGroup()); - assertEquals( - OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); + assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); builder.clearOptionalGroup(); - assertEquals( - OptionalGroup.getDefaultInstance(), builder.getOptionalGroup()); + assertEquals(OptionalGroup.getDefaultInstance(), builder.getOptionalGroup()); assertEquals(optionalGroup, messageAfterBuild.getOptionalGroup()); message = builder.build(); - OptionalGroup.Builder optionalGroupBuilder = OptionalGroup.newBuilder() - .setA(3); + OptionalGroup.Builder optionalGroupBuilder = OptionalGroup.newBuilder().setA(3); builder.setOptionalGroup(optionalGroupBuilder); - assertEquals( - OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); + assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); assertEquals(optionalGroupBuilder.build(), builder.getOptionalGroup()); messageAfterBuild = builder.build(); assertEquals(optionalGroupBuilder.build(), messageAfterBuild.getOptionalGroup()); - assertEquals( - OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); + assertEquals(OptionalGroup.getDefaultInstance(), message.getOptionalGroup()); builder.clearOptionalGroup(); - assertEquals( - OptionalGroup.getDefaultInstance(), builder.getOptionalGroup()); + assertEquals(OptionalGroup.getDefaultInstance(), builder.getOptionalGroup()); assertEquals(optionalGroupBuilder.build(), messageAfterBuild.getOptionalGroup()); message = builder.build(); @@ -401,43 +374,29 @@ public class LiteTest extends TestCase { builder.clearOptionalInt64(); assertEquals(0L, builder.getOptionalInt64()); assertEquals(1L, messageAfterBuild.getOptionalInt64()); - + message = builder.build(); - NestedMessage nestedMessage = NestedMessage.newBuilder() - .setBb(1) - .build(); + NestedMessage nestedMessage = NestedMessage.newBuilder().setBb(1).build(); builder.setOptionalLazyMessage(nestedMessage); - assertEquals( - NestedMessage.getDefaultInstance(), - message.getOptionalLazyMessage()); + assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage()); assertEquals(nestedMessage, builder.getOptionalLazyMessage()); messageAfterBuild = builder.build(); assertEquals(nestedMessage, messageAfterBuild.getOptionalLazyMessage()); - assertEquals( - NestedMessage.getDefaultInstance(), - message.getOptionalLazyMessage()); + assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage()); builder.clearOptionalLazyMessage(); - assertEquals( - NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage()); + assertEquals(NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage()); assertEquals(nestedMessage, messageAfterBuild.getOptionalLazyMessage()); message = builder.build(); - NestedMessage.Builder nestedMessageBuilder = - NestedMessage.newBuilder() - .setBb(3); + NestedMessage.Builder nestedMessageBuilder = NestedMessage.newBuilder().setBb(3); builder.setOptionalLazyMessage(nestedMessageBuilder); - assertEquals( - NestedMessage.getDefaultInstance(), - message.getOptionalLazyMessage()); + assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage()); assertEquals(nestedMessageBuilder.build(), builder.getOptionalLazyMessage()); messageAfterBuild = builder.build(); assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getOptionalLazyMessage()); - assertEquals( - NestedMessage.getDefaultInstance(), - message.getOptionalLazyMessage()); + assertEquals(NestedMessage.getDefaultInstance(), message.getOptionalLazyMessage()); builder.clearOptionalLazyMessage(); - assertEquals( - NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage()); + assertEquals(NestedMessage.getDefaultInstance(), builder.getOptionalLazyMessage()); assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getOptionalLazyMessage()); message = builder.build(); @@ -497,19 +456,14 @@ public class LiteTest extends TestCase { message = builder.build(); builder.setOptionalStringBytes(ByteString.copyFromUtf8("no")); assertEquals(ByteString.EMPTY, message.getOptionalStringBytes()); - assertEquals( - ByteString.copyFromUtf8("no"), builder.getOptionalStringBytes()); + assertEquals(ByteString.copyFromUtf8("no"), builder.getOptionalStringBytes()); messageAfterBuild = builder.build(); - assertEquals( - ByteString.copyFromUtf8("no"), - messageAfterBuild.getOptionalStringBytes()); + assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringBytes()); assertEquals(ByteString.EMPTY, message.getOptionalStringBytes()); builder.clearOptionalString(); assertEquals(ByteString.EMPTY, builder.getOptionalStringBytes()); - assertEquals( - ByteString.copyFromUtf8("no"), - messageAfterBuild.getOptionalStringBytes()); - + assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringBytes()); + message = builder.build(); builder.setOptionalStringPiece("hi"); assertEquals("", message.getOptionalStringPiece()); @@ -524,18 +478,13 @@ public class LiteTest extends TestCase { message = builder.build(); builder.setOptionalStringPieceBytes(ByteString.copyFromUtf8("no")); assertEquals(ByteString.EMPTY, message.getOptionalStringPieceBytes()); - assertEquals( - ByteString.copyFromUtf8("no"), builder.getOptionalStringPieceBytes()); + assertEquals(ByteString.copyFromUtf8("no"), builder.getOptionalStringPieceBytes()); messageAfterBuild = builder.build(); - assertEquals( - ByteString.copyFromUtf8("no"), - messageAfterBuild.getOptionalStringPieceBytes()); + assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringPieceBytes()); assertEquals(ByteString.EMPTY, message.getOptionalStringPieceBytes()); builder.clearOptionalStringPiece(); assertEquals(ByteString.EMPTY, builder.getOptionalStringPieceBytes()); - assertEquals( - ByteString.copyFromUtf8("no"), - messageAfterBuild.getOptionalStringPieceBytes()); + assertEquals(ByteString.copyFromUtf8("no"), messageAfterBuild.getOptionalStringPieceBytes()); message = builder.build(); builder.setOptionalUint32(1); @@ -572,16 +521,13 @@ public class LiteTest extends TestCase { message = builder.build(); builder.addAllRepeatedBytes(singletonList(ByteString.copyFromUtf8("hi"))); assertEquals(emptyList(), message.getRepeatedBytesList()); - assertEquals( - singletonList(ByteString.copyFromUtf8("hi")), - builder.getRepeatedBytesList()); + assertEquals(singletonList(ByteString.copyFromUtf8("hi")), builder.getRepeatedBytesList()); assertEquals(emptyList(), message.getRepeatedBytesList()); messageAfterBuild = builder.build(); builder.clearRepeatedBytes(); assertEquals(emptyList(), builder.getRepeatedBytesList()); assertEquals( - singletonList(ByteString.copyFromUtf8("hi")), - messageAfterBuild.getRepeatedBytesList()); + singletonList(ByteString.copyFromUtf8("hi")), messageAfterBuild.getRepeatedBytesList()); message = builder.build(); builder.addAllRepeatedCord(singletonList("hi")); @@ -634,12 +580,10 @@ public class LiteTest extends TestCase { assertEquals(singletonList(1F), messageAfterBuild.getRepeatedFloatList()); message = builder.build(); - builder.addAllRepeatedForeignEnum( - singletonList(ForeignEnumLite.FOREIGN_LITE_BAR)); + builder.addAllRepeatedForeignEnum(singletonList(ForeignEnumLite.FOREIGN_LITE_BAR)); assertEquals(emptyList(), message.getRepeatedForeignEnumList()); assertEquals( - singletonList(ForeignEnumLite.FOREIGN_LITE_BAR), - builder.getRepeatedForeignEnumList()); + singletonList(ForeignEnumLite.FOREIGN_LITE_BAR), builder.getRepeatedForeignEnumList()); assertEquals(emptyList(), message.getRepeatedForeignEnumList()); messageAfterBuild = builder.build(); builder.clearRepeatedForeignEnum(); @@ -651,23 +595,17 @@ public class LiteTest extends TestCase { message = builder.build(); builder.addAllRepeatedForeignMessage(singletonList(foreignMessage)); assertEquals(emptyList(), message.getRepeatedForeignMessageList()); - assertEquals( - singletonList(foreignMessage), builder.getRepeatedForeignMessageList()); + assertEquals(singletonList(foreignMessage), builder.getRepeatedForeignMessageList()); assertEquals(emptyList(), message.getRepeatedForeignMessageList()); messageAfterBuild = builder.build(); builder.clearRepeatedForeignMessage(); assertEquals(emptyList(), builder.getRepeatedForeignMessageList()); - assertEquals( - singletonList(foreignMessage), - messageAfterBuild.getRepeatedForeignMessageList()); + assertEquals(singletonList(foreignMessage), messageAfterBuild.getRepeatedForeignMessageList()); message = builder.build(); - builder.addAllRepeatedGroup( - singletonList(RepeatedGroup.getDefaultInstance())); + builder.addAllRepeatedGroup(singletonList(RepeatedGroup.getDefaultInstance())); assertEquals(emptyList(), message.getRepeatedGroupList()); - assertEquals( - singletonList(RepeatedGroup.getDefaultInstance()), - builder.getRepeatedGroupList()); + assertEquals(singletonList(RepeatedGroup.getDefaultInstance()), builder.getRepeatedGroupList()); assertEquals(emptyList(), message.getRepeatedGroupList()); messageAfterBuild = builder.build(); builder.clearRepeatedGroup(); @@ -699,15 +637,12 @@ public class LiteTest extends TestCase { message = builder.build(); builder.addAllRepeatedLazyMessage(singletonList(nestedMessage)); assertEquals(emptyList(), message.getRepeatedLazyMessageList()); - assertEquals( - singletonList(nestedMessage), builder.getRepeatedLazyMessageList()); + assertEquals(singletonList(nestedMessage), builder.getRepeatedLazyMessageList()); assertEquals(emptyList(), message.getRepeatedLazyMessageList()); messageAfterBuild = builder.build(); builder.clearRepeatedLazyMessage(); assertEquals(emptyList(), builder.getRepeatedLazyMessageList()); - assertEquals( - singletonList(nestedMessage), - messageAfterBuild.getRepeatedLazyMessageList()); + assertEquals(singletonList(nestedMessage), messageAfterBuild.getRepeatedLazyMessageList()); message = builder.build(); builder.addAllRepeatedSfixed32(singletonList(1)); @@ -727,8 +662,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); builder.clearRepeatedSfixed64(); assertEquals(emptyList(), builder.getRepeatedSfixed64List()); - assertEquals( - singletonList(1L), messageAfterBuild.getRepeatedSfixed64List()); + assertEquals(singletonList(1L), messageAfterBuild.getRepeatedSfixed64List()); message = builder.build(); builder.addAllRepeatedSint32(singletonList(1)); @@ -758,8 +692,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); builder.clearRepeatedString(); assertEquals(emptyList(), builder.getRepeatedStringList()); - assertEquals( - singletonList("hi"), messageAfterBuild.getRepeatedStringList()); + assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringList()); message = builder.build(); builder.addAllRepeatedStringPiece(singletonList("hi")); @@ -769,8 +702,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); builder.clearRepeatedStringPiece(); assertEquals(emptyList(), builder.getRepeatedStringPieceList()); - assertEquals( - singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList()); + assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList()); message = builder.build(); builder.addAllRepeatedUint32(singletonList(1)); @@ -805,16 +737,13 @@ public class LiteTest extends TestCase { message = builder.build(); builder.addRepeatedBytes(ByteString.copyFromUtf8("hi")); assertEquals(emptyList(), message.getRepeatedBytesList()); - assertEquals( - singletonList(ByteString.copyFromUtf8("hi")), - builder.getRepeatedBytesList()); + assertEquals(singletonList(ByteString.copyFromUtf8("hi")), builder.getRepeatedBytesList()); assertEquals(emptyList(), message.getRepeatedBytesList()); messageAfterBuild = builder.build(); builder.clearRepeatedBytes(); assertEquals(emptyList(), builder.getRepeatedBytesList()); assertEquals( - singletonList(ByteString.copyFromUtf8("hi")), - messageAfterBuild.getRepeatedBytesList()); + singletonList(ByteString.copyFromUtf8("hi")), messageAfterBuild.getRepeatedBytesList()); message = builder.build(); builder.addRepeatedCord("hi"); @@ -870,8 +799,7 @@ public class LiteTest extends TestCase { builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR); assertEquals(emptyList(), message.getRepeatedForeignEnumList()); assertEquals( - singletonList(ForeignEnumLite.FOREIGN_LITE_BAR), - builder.getRepeatedForeignEnumList()); + singletonList(ForeignEnumLite.FOREIGN_LITE_BAR), builder.getRepeatedForeignEnumList()); assertEquals(emptyList(), message.getRepeatedForeignEnumList()); messageAfterBuild = builder.build(); builder.clearRepeatedForeignEnum(); @@ -883,22 +811,17 @@ public class LiteTest extends TestCase { message = builder.build(); builder.addRepeatedForeignMessage(foreignMessage); assertEquals(emptyList(), message.getRepeatedForeignMessageList()); - assertEquals( - singletonList(foreignMessage), builder.getRepeatedForeignMessageList()); + assertEquals(singletonList(foreignMessage), builder.getRepeatedForeignMessageList()); assertEquals(emptyList(), message.getRepeatedForeignMessageList()); messageAfterBuild = builder.build(); builder.removeRepeatedForeignMessage(0); assertEquals(emptyList(), builder.getRepeatedForeignMessageList()); - assertEquals( - singletonList(foreignMessage), - messageAfterBuild.getRepeatedForeignMessageList()); + assertEquals(singletonList(foreignMessage), messageAfterBuild.getRepeatedForeignMessageList()); message = builder.build(); builder.addRepeatedGroup(RepeatedGroup.getDefaultInstance()); assertEquals(emptyList(), message.getRepeatedGroupList()); - assertEquals( - singletonList(RepeatedGroup.getDefaultInstance()), - builder.getRepeatedGroupList()); + assertEquals(singletonList(RepeatedGroup.getDefaultInstance()), builder.getRepeatedGroupList()); assertEquals(emptyList(), message.getRepeatedGroupList()); messageAfterBuild = builder.build(); builder.removeRepeatedGroup(0); @@ -930,15 +853,12 @@ public class LiteTest extends TestCase { message = builder.build(); builder.addRepeatedLazyMessage(nestedMessage); assertEquals(emptyList(), message.getRepeatedLazyMessageList()); - assertEquals( - singletonList(nestedMessage), builder.getRepeatedLazyMessageList()); + assertEquals(singletonList(nestedMessage), builder.getRepeatedLazyMessageList()); assertEquals(emptyList(), message.getRepeatedLazyMessageList()); messageAfterBuild = builder.build(); builder.removeRepeatedLazyMessage(0); assertEquals(emptyList(), builder.getRepeatedLazyMessageList()); - assertEquals( - singletonList(nestedMessage), - messageAfterBuild.getRepeatedLazyMessageList()); + assertEquals(singletonList(nestedMessage), messageAfterBuild.getRepeatedLazyMessageList()); message = builder.build(); builder.addRepeatedSfixed32(1); @@ -958,8 +878,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); builder.clearRepeatedSfixed64(); assertEquals(emptyList(), builder.getRepeatedSfixed64List()); - assertEquals( - singletonList(1L), messageAfterBuild.getRepeatedSfixed64List()); + assertEquals(singletonList(1L), messageAfterBuild.getRepeatedSfixed64List()); message = builder.build(); builder.addRepeatedSint32(1); @@ -989,8 +908,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); builder.clearRepeatedString(); assertEquals(emptyList(), builder.getRepeatedStringList()); - assertEquals( - singletonList("hi"), messageAfterBuild.getRepeatedStringList()); + assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringList()); message = builder.build(); builder.addRepeatedStringPiece("hi"); @@ -1000,8 +918,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); builder.clearRepeatedStringPiece(); assertEquals(emptyList(), builder.getRepeatedStringPieceList()); - assertEquals( - singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList()); + assertEquals(singletonList("hi"), messageAfterBuild.getRepeatedStringPieceList()); message = builder.build(); builder.addRepeatedUint32(1); @@ -1022,7 +939,7 @@ public class LiteTest extends TestCase { builder.clearRepeatedUint64(); assertEquals(emptyList(), builder.getRepeatedUint64List()); assertEquals(singletonList(1L), messageAfterBuild.getRepeatedUint64List()); - + message = builder.build(); builder.addRepeatedBool(true); messageAfterBuild = builder.build(); @@ -1031,14 +948,13 @@ public class LiteTest extends TestCase { assertEquals(true, messageAfterBuild.getRepeatedBool(0)); assertEquals(false, builder.getRepeatedBool(0)); builder.clearRepeatedBool(); - + message = builder.build(); builder.addRepeatedBytes(ByteString.copyFromUtf8("hi")); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedBytesCount()); builder.setRepeatedBytes(0, ByteString.EMPTY); - assertEquals( - ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedBytes(0)); + assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedBytes(0)); assertEquals(ByteString.EMPTY, builder.getRepeatedBytes(0)); builder.clearRepeatedBytes(); @@ -1056,8 +972,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedCordCount()); builder.setRepeatedCord(0, ""); - assertEquals( - ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedCordBytes(0)); + assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedCordBytes(0)); assertEquals(ByteString.EMPTY, builder.getRepeatedCordBytes(0)); builder.clearRepeatedCord(); @@ -1066,8 +981,8 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedDoubleCount()); builder.setRepeatedDouble(0, 0D); - assertEquals(1D, messageAfterBuild.getRepeatedDouble(0)); - assertEquals(0D, builder.getRepeatedDouble(0)); + assertEquals(1D, messageAfterBuild.getRepeatedDouble(0), 0.0); + assertEquals(0D, builder.getRepeatedDouble(0), 0.0); builder.clearRepeatedDouble(); message = builder.build(); @@ -1093,8 +1008,8 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedFloatCount()); builder.setRepeatedFloat(0, 0F); - assertEquals(1F, messageAfterBuild.getRepeatedFloat(0)); - assertEquals(0F, builder.getRepeatedFloat(0)); + assertEquals(1F, messageAfterBuild.getRepeatedFloat(0), 0.0f); + assertEquals(0F, builder.getRepeatedFloat(0), 0.0f); builder.clearRepeatedFloat(); message = builder.build(); @@ -1102,36 +1017,26 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedForeignEnumCount()); builder.setRepeatedForeignEnum(0, ForeignEnumLite.FOREIGN_LITE_FOO); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_BAR, - messageAfterBuild.getRepeatedForeignEnum(0)); - assertEquals( - ForeignEnumLite.FOREIGN_LITE_FOO, builder.getRepeatedForeignEnum(0)); + assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, messageAfterBuild.getRepeatedForeignEnum(0)); + assertEquals(ForeignEnumLite.FOREIGN_LITE_FOO, builder.getRepeatedForeignEnum(0)); builder.clearRepeatedForeignEnum(); message = builder.build(); builder.addRepeatedForeignMessage(foreignMessage); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedForeignMessageCount()); - builder.setRepeatedForeignMessage( - 0, ForeignMessageLite.getDefaultInstance()); - assertEquals( - foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0)); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - builder.getRepeatedForeignMessage(0)); + builder.setRepeatedForeignMessage(0, ForeignMessageLite.getDefaultInstance()); + assertEquals(foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0)); + assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getRepeatedForeignMessage(0)); builder.clearRepeatedForeignMessage(); - + message = builder.build(); builder.addRepeatedForeignMessage(foreignMessageBuilder); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedForeignMessageCount()); - builder.setRepeatedForeignMessage( - 0, ForeignMessageLite.getDefaultInstance()); + builder.setRepeatedForeignMessage(0, ForeignMessageLite.getDefaultInstance()); assertEquals(foreignMessageBuilder.build(), messageAfterBuild.getRepeatedForeignMessage(0)); - assertEquals( - ForeignMessageLite.getDefaultInstance(), - builder.getRepeatedForeignMessage(0)); + assertEquals(ForeignMessageLite.getDefaultInstance(), builder.getRepeatedForeignMessage(0)); builder.clearRepeatedForeignMessage(); message = builder.build(); @@ -1139,54 +1044,46 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedForeignMessageCount()); builder.setRepeatedForeignMessage(0, foreignMessageBuilder); - assertEquals( - foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0)); + assertEquals(foreignMessage, messageAfterBuild.getRepeatedForeignMessage(0)); assertEquals(foreignMessageBuilder.build(), builder.getRepeatedForeignMessage(0)); builder.clearRepeatedForeignMessage(); message = builder.build(); - RepeatedGroup repeatedGroup = RepeatedGroup.newBuilder() - .setA(1) - .build(); + RepeatedGroup repeatedGroup = RepeatedGroup.newBuilder().setA(1).build(); builder.addRepeatedGroup(repeatedGroup); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedGroupCount()); builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance()); assertEquals(repeatedGroup, messageAfterBuild.getRepeatedGroup(0)); - assertEquals( - RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); + assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); builder.clearRepeatedGroup(); - + message = builder.build(); builder.addRepeatedGroup(0, repeatedGroup); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedGroupCount()); builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance()); assertEquals(repeatedGroup, messageAfterBuild.getRepeatedGroup(0)); - assertEquals( - RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); + assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); builder.clearRepeatedGroup(); - + message = builder.build(); - RepeatedGroup.Builder repeatedGroupBuilder = RepeatedGroup.newBuilder() - .setA(3); + RepeatedGroup.Builder repeatedGroupBuilder = RepeatedGroup.newBuilder().setA(3); builder.addRepeatedGroup(repeatedGroupBuilder); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedGroupCount()); builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance()); assertEquals(repeatedGroupBuilder.build(), messageAfterBuild.getRepeatedGroup(0)); - assertEquals( - RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); + assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); builder.clearRepeatedGroup(); - + message = builder.build(); builder.addRepeatedGroup(0, repeatedGroupBuilder); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedGroupCount()); builder.setRepeatedGroup(0, RepeatedGroup.getDefaultInstance()); assertEquals(repeatedGroupBuilder.build(), messageAfterBuild.getRepeatedGroup(0)); - assertEquals( - RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); + assertEquals(RepeatedGroup.getDefaultInstance(), builder.getRepeatedGroup(0)); builder.clearRepeatedGroup(); message = builder.build(); @@ -1206,45 +1103,41 @@ public class LiteTest extends TestCase { assertEquals(1L, messageAfterBuild.getRepeatedInt64(0)); assertEquals(0L, builder.getRepeatedInt64(0)); builder.clearRepeatedInt64(); - + message = builder.build(); builder.addRepeatedLazyMessage(nestedMessage); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedLazyMessageCount()); builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance()); assertEquals(nestedMessage, messageAfterBuild.getRepeatedLazyMessage(0)); - assertEquals( - NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); + assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); builder.clearRepeatedLazyMessage(); - + message = builder.build(); builder.addRepeatedLazyMessage(0, nestedMessage); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedLazyMessageCount()); builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance()); assertEquals(nestedMessage, messageAfterBuild.getRepeatedLazyMessage(0)); - assertEquals( - NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); + assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); builder.clearRepeatedLazyMessage(); - + message = builder.build(); builder.addRepeatedLazyMessage(nestedMessageBuilder); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedLazyMessageCount()); builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance()); assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getRepeatedLazyMessage(0)); - assertEquals( - NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); + assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); builder.clearRepeatedLazyMessage(); - + message = builder.build(); builder.addRepeatedLazyMessage(0, nestedMessageBuilder); messageAfterBuild = builder.build(); assertEquals(0, message.getRepeatedLazyMessageCount()); builder.setRepeatedLazyMessage(0, NestedMessage.getDefaultInstance()); assertEquals(nestedMessageBuilder.build(), messageAfterBuild.getRepeatedLazyMessage(0)); - assertEquals( - NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); + assertEquals(NestedMessage.getDefaultInstance(), builder.getRepeatedLazyMessage(0)); builder.clearRepeatedLazyMessage(); message = builder.build(); @@ -1297,9 +1190,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); assertEquals(0L, message.getRepeatedStringCount()); builder.setRepeatedString(0, ""); - assertEquals( - ByteString.copyFromUtf8("hi"), - messageAfterBuild.getRepeatedStringBytes(0)); + assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedStringBytes(0)); assertEquals(ByteString.EMPTY, builder.getRepeatedStringBytes(0)); builder.clearRepeatedString(); @@ -1317,9 +1208,7 @@ public class LiteTest extends TestCase { messageAfterBuild = builder.build(); assertEquals(0L, message.getRepeatedStringPieceCount()); builder.setRepeatedStringPiece(0, ""); - assertEquals( - ByteString.copyFromUtf8("hi"), - messageAfterBuild.getRepeatedStringPieceBytes(0)); + assertEquals(ByteString.copyFromUtf8("hi"), messageAfterBuild.getRepeatedStringPieceBytes(0)); assertEquals(ByteString.EMPTY, builder.getRepeatedStringPieceBytes(0)); builder.clearRepeatedStringPiece(); @@ -1343,18 +1232,14 @@ public class LiteTest extends TestCase { message = builder.build(); assertEquals(0, message.getSerializedSize()); - builder.mergeFrom(TestAllTypesLite.newBuilder() - .setOptionalBool(true) - .build()); + builder.mergeFrom(TestAllTypesLite.newBuilder().setOptionalBool(true).build()); assertEquals(0, message.getSerializedSize()); assertEquals(true, builder.build().getOptionalBool()); builder.clearOptionalBool(); message = builder.build(); assertEquals(0, message.getSerializedSize()); - builder.mergeFrom(TestAllTypesLite.newBuilder() - .setOptionalBool(true) - .build()); + builder.mergeFrom(TestAllTypesLite.newBuilder().setOptionalBool(true).build()); assertEquals(0, message.getSerializedSize()); assertEquals(true, builder.build().getOptionalBool()); builder.clear(); @@ -1364,93 +1249,68 @@ public class LiteTest extends TestCase { assertEquals(0, message.getSerializedSize()); builder.mergeOptionalForeignMessage(foreignMessage); assertEquals(0, message.getSerializedSize()); - assertEquals( - foreignMessage.getC(), - builder.build().getOptionalForeignMessage().getC()); + assertEquals(foreignMessage.getC(), builder.build().getOptionalForeignMessage().getC()); builder.clearOptionalForeignMessage(); message = builder.build(); assertEquals(0, message.getSerializedSize()); builder.mergeOptionalLazyMessage(nestedMessage); assertEquals(0, message.getSerializedSize()); - assertEquals( - nestedMessage.getBb(), - builder.build().getOptionalLazyMessage().getBb()); + assertEquals(nestedMessage.getBb(), builder.build().getOptionalLazyMessage().getBb()); builder.clearOptionalLazyMessage(); - + message = builder.build(); builder.setOneofString("hi"); - assertEquals( - OneofFieldCase.ONEOFFIELD_NOT_SET, message.getOneofFieldCase()); + assertEquals(OneofFieldCase.ONEOFFIELD_NOT_SET, message.getOneofFieldCase()); assertEquals(OneofFieldCase.ONEOF_STRING, builder.getOneofFieldCase()); assertEquals("hi", builder.getOneofString()); messageAfterBuild = builder.build(); - assertEquals( - OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase()); + assertEquals(OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase()); assertEquals("hi", messageAfterBuild.getOneofString()); builder.setOneofUint32(1); - assertEquals( - OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase()); + assertEquals(OneofFieldCase.ONEOF_STRING, messageAfterBuild.getOneofFieldCase()); assertEquals("hi", messageAfterBuild.getOneofString()); assertEquals(OneofFieldCase.ONEOF_UINT32, builder.getOneofFieldCase()); assertEquals(1, builder.getOneofUint32()); TestAllTypesLiteOrBuilder messageOrBuilder = builder; assertEquals(OneofFieldCase.ONEOF_UINT32, messageOrBuilder.getOneofFieldCase()); - - TestAllExtensionsLite.Builder extendableMessageBuilder = - TestAllExtensionsLite.newBuilder(); + + TestAllExtensionsLite.Builder extendableMessageBuilder = TestAllExtensionsLite.newBuilder(); TestAllExtensionsLite extendableMessage = extendableMessageBuilder.build(); - extendableMessageBuilder.setExtension( - UnittestLite.optionalInt32ExtensionLite, 1); - assertFalse(extendableMessage.hasExtension( - UnittestLite.optionalInt32ExtensionLite)); + extendableMessageBuilder.setExtension(UnittestLite.optionalInt32ExtensionLite, 1); + assertFalse(extendableMessage.hasExtension(UnittestLite.optionalInt32ExtensionLite)); extendableMessage = extendableMessageBuilder.build(); assertEquals( - 1, (int) extendableMessageBuilder.getExtension( - UnittestLite.optionalInt32ExtensionLite)); + 1, (int) extendableMessageBuilder.getExtension(UnittestLite.optionalInt32ExtensionLite)); + assertEquals(1, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite)); + extendableMessageBuilder.setExtension(UnittestLite.optionalInt32ExtensionLite, 3); assertEquals( - 1, (int) extendableMessage.getExtension( - UnittestLite.optionalInt32ExtensionLite)); - extendableMessageBuilder.setExtension( - UnittestLite.optionalInt32ExtensionLite, 3); - assertEquals( - 3, (int) extendableMessageBuilder.getExtension( - UnittestLite.optionalInt32ExtensionLite)); - assertEquals( - 1, (int) extendableMessage.getExtension( - UnittestLite.optionalInt32ExtensionLite)); + 3, (int) extendableMessageBuilder.getExtension(UnittestLite.optionalInt32ExtensionLite)); + assertEquals(1, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite)); extendableMessage = extendableMessageBuilder.build(); assertEquals( - 3, (int) extendableMessageBuilder.getExtension( - UnittestLite.optionalInt32ExtensionLite)); - assertEquals( - 3, (int) extendableMessage.getExtension( - UnittestLite.optionalInt32ExtensionLite)); - + 3, (int) extendableMessageBuilder.getExtension(UnittestLite.optionalInt32ExtensionLite)); + assertEquals(3, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite)); + // No extension registry, so it should be in unknown fields. - extendableMessage = - TestAllExtensionsLite.parseFrom(extendableMessage.toByteArray()); - assertFalse(extendableMessage.hasExtension( - UnittestLite.optionalInt32ExtensionLite)); - + extendableMessage = TestAllExtensionsLite.parseFrom(extendableMessage.toByteArray()); + assertFalse(extendableMessage.hasExtension(UnittestLite.optionalInt32ExtensionLite)); + extendableMessageBuilder = extendableMessage.toBuilder(); - extendableMessageBuilder.mergeFrom(TestAllExtensionsLite.newBuilder() - .setExtension(UnittestLite.optionalFixed32ExtensionLite, 11) - .build()); - + extendableMessageBuilder.mergeFrom( + TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalFixed32ExtensionLite, 11) + .build()); + extendableMessage = extendableMessageBuilder.build(); ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); UnittestLite.registerAllExtensions(registry); - extendableMessage = TestAllExtensionsLite.parseFrom( - extendableMessage.toByteArray(), registry); - + extendableMessage = TestAllExtensionsLite.parseFrom(extendableMessage.toByteArray(), registry); + // The unknown field was preserved. + assertEquals(3, (int) extendableMessage.getExtension(UnittestLite.optionalInt32ExtensionLite)); assertEquals( - 3, (int) extendableMessage.getExtension( - UnittestLite.optionalInt32ExtensionLite)); - assertEquals( - 11, (int) extendableMessage.getExtension( - UnittestLite.optionalFixed32ExtensionLite)); + 11, (int) extendableMessage.getExtension(UnittestLite.optionalFixed32ExtensionLite)); } public void testBuilderMergeFromNull() throws Exception { @@ -1497,140 +1357,174 @@ public class LiteTest extends TestCase { } public void testToStringScalarFieldsSuffixedWithList() throws Exception { - assertToStringEquals("deceptively_named_list: 7", TestAllTypesLite.newBuilder() - .setDeceptivelyNamedList(7) - .build()); + assertToStringEquals( + "deceptively_named_list: 7", + TestAllTypesLite.newBuilder().setDeceptivelyNamedList(7).build()); } public void testToStringPrimitives() throws Exception { - TestAllTypesLite proto = TestAllTypesLite.newBuilder() - .setOptionalInt32(1) - .setOptionalInt64(9223372036854775807L) - .build(); + TestAllTypesLite proto = + TestAllTypesLite.newBuilder() + .setOptionalInt32(1) + .setOptionalInt64(9223372036854775807L) + .build(); assertToStringEquals("optional_int32: 1\noptional_int64: 9223372036854775807", proto); - proto = TestAllTypesLite.newBuilder() - .setOptionalBool(true) - .setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ) - .build(); + proto = + TestAllTypesLite.newBuilder() + .setOptionalBool(true) + .setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ) + .build(); assertToStringEquals("optional_bool: true\noptional_nested_enum: BAZ", proto); - proto = TestAllTypesLite.newBuilder() - .setOptionalFloat(2.72f) - .setOptionalDouble(3.14) - .build(); + proto = TestAllTypesLite.newBuilder().setOptionalFloat(2.72f).setOptionalDouble(3.14).build(); assertToStringEquals("optional_double: 3.14\noptional_float: 2.72", proto); } public void testToStringStringFields() throws Exception { - TestAllTypesLite proto = TestAllTypesLite.newBuilder() - .setOptionalString("foo\"bar\nbaz\\") - .build(); + TestAllTypesLite proto = + TestAllTypesLite.newBuilder().setOptionalString("foo\"bar\nbaz\\").build(); assertToStringEquals("optional_string: \"foo\\\"bar\\nbaz\\\\\"", proto); - proto = TestAllTypesLite.newBuilder() - .setOptionalString("\u6587") - .build(); + proto = TestAllTypesLite.newBuilder().setOptionalString("\u6587").build(); assertToStringEquals("optional_string: \"\\346\\226\\207\"", proto); } public void testToStringNestedMessage() throws Exception { - TestAllTypesLite proto = TestAllTypesLite.newBuilder() - .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.getDefaultInstance()) - .build(); + TestAllTypesLite proto = + TestAllTypesLite.newBuilder() + .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.getDefaultInstance()) + .build(); assertToStringEquals("optional_nested_message {\n}", proto); - proto = TestAllTypesLite.newBuilder() - .setOptionalNestedMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) - .build(); + proto = + TestAllTypesLite.newBuilder() + .setOptionalNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) + .build(); assertToStringEquals("optional_nested_message {\n bb: 7\n}", proto); } public void testToStringRepeatedFields() throws Exception { - TestAllTypesLite proto = TestAllTypesLite.newBuilder() - .addRepeatedInt32(32) - .addRepeatedInt32(32) - .addRepeatedInt64(64) - .build(); + TestAllTypesLite proto = + TestAllTypesLite.newBuilder() + .addRepeatedInt32(32) + .addRepeatedInt32(32) + .addRepeatedInt64(64) + .build(); assertToStringEquals("repeated_int32: 32\nrepeated_int32: 32\nrepeated_int64: 64", proto); - proto = TestAllTypesLite.newBuilder() - .addRepeatedLazyMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) - .addRepeatedLazyMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(8)) - .build(); + proto = + TestAllTypesLite.newBuilder() + .addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(7)) + .addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(8)) + .build(); assertToStringEquals( - "repeated_lazy_message {\n bb: 7\n}\nrepeated_lazy_message {\n bb: 8\n}", - proto); + "repeated_lazy_message {\n bb: 7\n}\nrepeated_lazy_message {\n bb: 8\n}", proto); } public void testToStringForeignFields() throws Exception { - TestAllTypesLite proto = TestAllTypesLite.newBuilder() - .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) - .setOptionalForeignMessage( - ForeignMessageLite.newBuilder() - .setC(3)) - .build(); + TestAllTypesLite proto = + TestAllTypesLite.newBuilder() + .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) + .setOptionalForeignMessage(ForeignMessageLite.newBuilder().setC(3)) + .build(); assertToStringEquals( - "optional_foreign_enum: FOREIGN_LITE_BAR\noptional_foreign_message {\n c: 3\n}", - proto); + "optional_foreign_enum: FOREIGN_LITE_BAR\noptional_foreign_message {\n c: 3\n}", proto); } public void testToStringExtensions() throws Exception { - TestAllExtensionsLite message = TestAllExtensionsLite.newBuilder() - .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) - .addExtension(UnittestLite.repeatedStringExtensionLite, "spam") - .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs") - .setExtension(UnittestLite.optionalNestedEnumExtensionLite, - TestAllTypesLite.NestedEnum.BAZ) - .setExtension(UnittestLite.optionalNestedMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) - .build(); + TestAllExtensionsLite message = + TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) + .addExtension(UnittestLite.repeatedStringExtensionLite, "spam") + .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs") + .setExtension( + UnittestLite.optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ) + .setExtension( + UnittestLite.optionalNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) + .build(); assertToStringEquals( - "[1]: 123\n[18] {\n bb: 7\n}\n[21]: 3\n[44]: \"spam\"\n[44]: \"eggs\"", - message); + "[1]: 123\n[18] {\n bb: 7\n}\n[21]: 3\n[44]: \"spam\"\n[44]: \"eggs\"", message); } public void testToStringUnknownFields() throws Exception { - TestAllExtensionsLite messageWithExtensions = TestAllExtensionsLite.newBuilder() - .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) - .addExtension(UnittestLite.repeatedStringExtensionLite, "spam") - .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs") - .setExtension(UnittestLite.optionalNestedEnumExtensionLite, - TestAllTypesLite.NestedEnum.BAZ) - .setExtension(UnittestLite.optionalNestedMessageExtensionLite, - TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) - .build(); - TestAllExtensionsLite messageWithUnknownFields = TestAllExtensionsLite.parseFrom( - messageWithExtensions.toByteArray()); + TestAllExtensionsLite messageWithExtensions = + TestAllExtensionsLite.newBuilder() + .setExtension(UnittestLite.optionalInt32ExtensionLite, 123) + .addExtension(UnittestLite.repeatedStringExtensionLite, "spam") + .addExtension(UnittestLite.repeatedStringExtensionLite, "eggs") + .setExtension( + UnittestLite.optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ) + .setExtension( + UnittestLite.optionalNestedMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(7).build()) + .build(); + TestAllExtensionsLite messageWithUnknownFields = + TestAllExtensionsLite.parseFrom(messageWithExtensions.toByteArray()); assertToStringEquals( - "1: 123\n18: \"\\b\\a\"\n21: 3\n44: \"spam\"\n44: \"eggs\"", - messageWithUnknownFields); + "1: 123\n18: \"\\b\\a\"\n21: 3\n44: \"spam\"\n44: \"eggs\"", messageWithUnknownFields); } - + public void testToStringLazyMessage() throws Exception { - TestAllTypesLite message = TestAllTypesLite.newBuilder() - .setOptionalLazyMessage(NestedMessage.newBuilder().setBb(1).build()) - .build(); + TestAllTypesLite message = + TestAllTypesLite.newBuilder() + .setOptionalLazyMessage(NestedMessage.newBuilder().setBb(1).build()) + .build(); assertToStringEquals("optional_lazy_message {\n bb: 1\n}", message); } - + public void testToStringGroup() throws Exception { - TestAllTypesLite message = TestAllTypesLite.newBuilder() - .setOptionalGroup(OptionalGroup.newBuilder().setA(1).build()) - .build(); + TestAllTypesLite message = + TestAllTypesLite.newBuilder() + .setOptionalGroup(OptionalGroup.newBuilder().setA(1).build()) + .build(); assertToStringEquals("optional_group {\n a: 1\n}", message); } - + public void testToStringOneof() throws Exception { - TestAllTypesLite message = TestAllTypesLite.newBuilder() - .setOneofString("hello") - .build(); + TestAllTypesLite message = TestAllTypesLite.newBuilder().setOneofString("hello").build(); assertToStringEquals("oneof_string: \"hello\"", message); } + public void testToStringMapFields() throws Exception { + TestMap message1 = + TestMap.newBuilder() + .putInt32ToStringField(1, "alpha") + .putInt32ToStringField(2, "beta") + .build(); + assertToStringEquals( + "int32_to_string_field {\n" + + " key: 1\n" + + " value: \"alpha\"\n" + + "}\n" + + "int32_to_string_field {\n" + + " key: 2\n" + + " value: \"beta\"\n" + + "}", + message1); + + TestMap message2 = + TestMap.newBuilder() + .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(10).build()) + .putInt32ToMessageField(2, MessageValue.newBuilder().setValue(20).build()) + .build(); + assertToStringEquals( + "int32_to_message_field {\n" + + " key: 1\n" + + " value {\n" + + " value: 10\n" + + " }\n" + + "}\n" + + "int32_to_message_field {\n" + + " key: 2\n" + + " value {\n" + + " value: 20\n" + + " }\n" + + "}", + message2); + } + // Asserts that the toString() representation of the message matches the expected. This verifies // the first line starts with a comment; but, does not factor in said comment as part of the // comparison as it contains unstable addresses. @@ -1644,38 +1538,38 @@ public class LiteTest extends TestCase { } assertEquals(expected, toString); } - + public void testParseLazy() throws Exception { - ByteString bb = TestAllTypesLite.newBuilder() - .setOptionalLazyMessage(NestedMessage.newBuilder() - .setBb(11) - .build()) - .build().toByteString(); - ByteString cc = TestAllTypesLite.newBuilder() - .setOptionalLazyMessage(NestedMessage.newBuilder() - .setCc(22) - .build()) - .build().toByteString(); - + ByteString bb = + TestAllTypesLite.newBuilder() + .setOptionalLazyMessage(NestedMessage.newBuilder().setBb(11).build()) + .build() + .toByteString(); + ByteString cc = + TestAllTypesLite.newBuilder() + .setOptionalLazyMessage(NestedMessage.newBuilder().setCc(22).build()) + .build() + .toByteString(); + ByteString concat = bb.concat(cc); TestAllTypesLite message = TestAllTypesLite.parseFrom(concat); assertEquals(11, message.getOptionalLazyMessage().getBb()); assertEquals(22L, message.getOptionalLazyMessage().getCc()); } - + public void testParseLazy_oneOf() throws Exception { - ByteString bb = TestAllTypesLite.newBuilder() - .setOneofLazyNestedMessage(NestedMessage.newBuilder() - .setBb(11) - .build()) - .build().toByteString(); - ByteString cc = TestAllTypesLite.newBuilder() - .setOneofLazyNestedMessage(NestedMessage.newBuilder() - .setCc(22) - .build()) - .build().toByteString(); - + ByteString bb = + TestAllTypesLite.newBuilder() + .setOneofLazyNestedMessage(NestedMessage.newBuilder().setBb(11).build()) + .build() + .toByteString(); + ByteString cc = + TestAllTypesLite.newBuilder() + .setOneofLazyNestedMessage(NestedMessage.newBuilder().setCc(22).build()) + .build() + .toByteString(); + ByteString concat = bb.concat(cc); TestAllTypesLite message = TestAllTypesLite.parseFrom(concat); @@ -1684,27 +1578,26 @@ public class LiteTest extends TestCase { } public void testMergeFromStream_repeatedField() throws Exception { - TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder() - .addRepeatedString("hello"); + TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder().addRepeatedString("hello"); builder.mergeFrom(CodedInputStream.newInstance(builder.build().toByteArray())); assertEquals(2, builder.getRepeatedStringCount()); } public void testMergeFromStream_invalidBytes() throws Exception { - TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder() - .setDefaultBool(true); + TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder().setDefaultBool(true); try { builder.mergeFrom(CodedInputStream.newInstance("Invalid bytes".getBytes(Internal.UTF_8))); fail(); - } catch (InvalidProtocolBufferException expected) {} + } catch (InvalidProtocolBufferException expected) { + } } public void testMergeFrom_sanity() throws Exception { TestAllTypesLite one = TestUtilLite.getAllLiteSetBuilder().build(); byte[] bytes = one.toByteArray(); TestAllTypesLite two = TestAllTypesLite.parseFrom(bytes); - + one = one.toBuilder().mergeFrom(one).build(); two = two.toBuilder().mergeFrom(bytes).build(); assertEquals(one, two); @@ -1713,14 +1606,14 @@ public class LiteTest extends TestCase { } public void testMergeFromNoLazyFieldSharing() throws Exception { - TestAllTypesLite.Builder sourceBuilder = TestAllTypesLite.newBuilder().setOptionalLazyMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(1)); + TestAllTypesLite.Builder sourceBuilder = + TestAllTypesLite.newBuilder() + .setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(1)); TestAllTypesLite.Builder targetBuilder = TestAllTypesLite.newBuilder().mergeFrom(sourceBuilder.build()); assertEquals(1, sourceBuilder.getOptionalLazyMessage().getBb()); // now change the sourceBuilder, and target value shouldn't be affected. - sourceBuilder.setOptionalLazyMessage( - TestAllTypesLite.NestedMessage.newBuilder().setBb(2)); + sourceBuilder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(2)); assertEquals(1, targetBuilder.getOptionalLazyMessage().getBb()); } @@ -1728,508 +1621,373 @@ public class LiteTest extends TestCase { TestAllTypesLite one = TestUtilLite.getAllLiteSetBuilder().build(); byte[] bytes = one.toByteArray(); TestAllTypesLite two = one.toBuilder().mergeFrom(one).mergeFrom(bytes).build(); - + assertFalse(one.equals(two)); assertFalse(two.equals(one)); - + assertFalse(one.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(one)); - - TestAllTypesLite oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultBool(true) - .build(); + + TestAllTypesLite oneFieldSet = TestAllTypesLite.newBuilder().setDefaultBool(true).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultCord("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultCord("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultCordBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultCordBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultDouble(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultDouble(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultFixed32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultFixed32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultFixed64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultFixed64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultFloat(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultFloat(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder() + .setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_BAR) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder().setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_BAR).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultInt32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultInt32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultInt64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultInt64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultNestedEnum(NestedEnum.BAR) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultNestedEnum(NestedEnum.BAR).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultSfixed32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSfixed32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultSfixed64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSfixed64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultSint32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSint32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultSint64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultSint64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultString("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultString("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultStringBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultStringBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultStringPiece("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultStringPiece("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultStringPieceBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder().setDefaultStringPieceBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultUint32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultUint32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setDefaultUint64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setDefaultUint64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedBool(true) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedBool(true).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedCord("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedCord("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedCordBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedCordBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedDouble(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedDouble(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedFixed32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedFixed32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedFixed64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedFixed64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedFloat(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedFloat(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder() + .addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder().addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedInt32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedInt32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedInt64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedInt64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedNestedEnum(NestedEnum.BAR) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedNestedEnum(NestedEnum.BAR).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedSfixed32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSfixed32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedSfixed64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSfixed64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedSint32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSint32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedSint64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedSint64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedString("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedString("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedStringBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedStringBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedStringPiece("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedStringPiece("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedStringPieceBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder().addRepeatedStringPieceBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedUint32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedUint32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedUint64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().addRepeatedUint64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalBool(true) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalBool(true).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalCord("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalCord("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalCordBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalCordBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalDouble(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalDouble(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalFixed32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalFixed32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalFixed64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalFixed64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalFloat(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalFloat(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder() + .setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAR) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder().setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAR).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalInt32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalInt32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalInt64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalInt64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalNestedEnum(NestedEnum.BAR) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalNestedEnum(NestedEnum.BAR).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalSfixed32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSfixed32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalSfixed64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSfixed64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalSint32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSint32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalSint64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalSint64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalString("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalString("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalStringBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalStringBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalStringPiece("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalStringPiece("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalStringPieceBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder().setOptionalStringPieceBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalUint32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalUint32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalUint64(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOptionalUint64(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOneofBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOneofBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOneofLazyNestedMessage(NestedMessage.getDefaultInstance()) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder() + .setOneofLazyNestedMessage(NestedMessage.getDefaultInstance()) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOneofNestedMessage(NestedMessage.getDefaultInstance()) - .build(); + + oneFieldSet = + TestAllTypesLite.newBuilder() + .setOneofNestedMessage(NestedMessage.getDefaultInstance()) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOneofString("") - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOneofString("").build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOneofStringBytes(ByteString.EMPTY) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOneofStringBytes(ByteString.EMPTY).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - - oneFieldSet = TestAllTypesLite.newBuilder() - .setOneofUint32(0) - .build(); + + oneFieldSet = TestAllTypesLite.newBuilder().setOneofUint32(0).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalForeignMessage(ForeignMessageLite.getDefaultInstance()) - .build(); + oneFieldSet = + TestAllTypesLite.newBuilder() + .setOptionalForeignMessage(ForeignMessageLite.getDefaultInstance()) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalGroup(OptionalGroup.getDefaultInstance()) - .build(); + oneFieldSet = + TestAllTypesLite.newBuilder().setOptionalGroup(OptionalGroup.getDefaultInstance()).build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalPublicImportMessage(PublicImportMessageLite.getDefaultInstance()) - .build(); + oneFieldSet = + TestAllTypesLite.newBuilder() + .setOptionalPublicImportMessage(PublicImportMessageLite.getDefaultInstance()) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - oneFieldSet = TestAllTypesLite.newBuilder() - .setOptionalLazyMessage(NestedMessage.getDefaultInstance()) - .build(); + oneFieldSet = + TestAllTypesLite.newBuilder() + .setOptionalLazyMessage(NestedMessage.getDefaultInstance()) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); - + assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); - oneFieldSet = TestAllTypesLite.newBuilder() - .addRepeatedLazyMessage(NestedMessage.getDefaultInstance()) - .build(); + oneFieldSet = + TestAllTypesLite.newBuilder() + .addRepeatedLazyMessage(NestedMessage.getDefaultInstance()) + .build(); assertFalse(oneFieldSet.equals(TestAllTypesLite.getDefaultInstance())); assertFalse(TestAllTypesLite.getDefaultInstance().equals(oneFieldSet)); } public void testEquals() throws Exception { // Check that two identical objs are equal. - Foo foo1a = Foo.newBuilder() - .setValue(1) - .addBar(Bar.newBuilder().setName("foo1")) - .build(); - Foo foo1b = Foo.newBuilder() - .setValue(1) - .addBar(Bar.newBuilder().setName("foo1")) - .build(); - Foo foo2 = Foo.newBuilder() - .setValue(1) - .addBar(Bar.newBuilder().setName("foo2")) - .build(); + Foo foo1a = Foo.newBuilder().setValue(1).addBar(Bar.newBuilder().setName("foo1")).build(); + Foo foo1b = Foo.newBuilder().setValue(1).addBar(Bar.newBuilder().setName("foo1")).build(); + Foo foo2 = Foo.newBuilder().setValue(1).addBar(Bar.newBuilder().setName("foo2")).build(); // Check that equals is doing value rather than object equality. assertEquals(foo1a, foo1b); @@ -2246,17 +2004,10 @@ public class LiteTest extends TestCase { } public void testEqualsAndHashCodeForTrickySchemaTypes() { - Foo foo1 = Foo.newBuilder() - .build(); - Foo foo2 = Foo.newBuilder() - .setSint64(1) - .build(); - Foo foo3 = Foo.newBuilder() - .putMyMap("key", "value2") - .build(); - Foo foo4 = Foo.newBuilder() - .setMyGroup(Foo.MyGroup.newBuilder().setValue(4).build()) - .build(); + Foo foo1 = Foo.getDefaultInstance(); + Foo foo2 = Foo.newBuilder().setSint64(1).build(); + Foo foo3 = Foo.newBuilder().putMyMap("key", "value2").build(); + Foo foo4 = Foo.newBuilder().setMyGroup(Foo.MyGroup.newBuilder().setValue(4).build()).build(); assertEqualsAndHashCodeAreFalse(foo1, foo2); assertEqualsAndHashCodeAreFalse(foo1, foo3); @@ -2272,29 +2023,27 @@ public class LiteTest extends TestCase { TestOneofEquals message2 = builder.build(); assertFalse(message1.equals(message2)); } - + public void testEquals_sanity() throws Exception { TestAllTypesLite one = TestUtilLite.getAllLiteSetBuilder().build(); TestAllTypesLite two = TestAllTypesLite.parseFrom(one.toByteArray()); assertEquals(one, two); assertEquals(one.hashCode(), two.hashCode()); - + assertEquals( one.toBuilder().mergeFrom(two).build(), two.toBuilder().mergeFrom(two.toByteArray()).build()); } public void testEqualsAndHashCodeWithUnknownFields() throws InvalidProtocolBufferException { - Foo fooWithOnlyValue = Foo.newBuilder() - .setValue(1) - .build(); + Foo fooWithOnlyValue = Foo.newBuilder().setValue(1).build(); - Foo fooWithValueAndExtension = fooWithOnlyValue.toBuilder() - .setValue(1) - .setExtension(Bar.fooExt, Bar.newBuilder() - .setName("name") - .build()) - .build(); + Foo fooWithValueAndExtension = + fooWithOnlyValue + .toBuilder() + .setValue(1) + .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build()) + .build(); Foo fooWithValueAndUnknownFields = Foo.parseFrom(fooWithValueAndExtension.toByteArray()); @@ -2303,30 +2052,27 @@ public class LiteTest extends TestCase { } public void testEqualsAndHashCodeWithExtensions() throws InvalidProtocolBufferException { - Foo fooWithOnlyValue = Foo.newBuilder() - .setValue(1) - .build(); + Foo fooWithOnlyValue = Foo.newBuilder().setValue(1).build(); - Foo fooWithValueAndExtension = fooWithOnlyValue.toBuilder() - .setValue(1) - .setExtension(Bar.fooExt, Bar.newBuilder() - .setName("name") - .build()) - .build(); + Foo fooWithValueAndExtension = + fooWithOnlyValue + .toBuilder() + .setValue(1) + .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build()) + .build(); assertEqualsAndHashCodeAreFalse(fooWithOnlyValue, fooWithValueAndExtension); } - + // Test to ensure we avoid a class cast exception with oneofs. public void testEquals_oneOfMessages() { - TestAllTypesLite mine = TestAllTypesLite.newBuilder() - .setOneofString("Hello") - .build(); - - TestAllTypesLite other = TestAllTypesLite.newBuilder() - .setOneofNestedMessage(NestedMessage.getDefaultInstance()) - .build(); - + TestAllTypesLite mine = TestAllTypesLite.newBuilder().setOneofString("Hello").build(); + + TestAllTypesLite other = + TestAllTypesLite.newBuilder() + .setOneofNestedMessage(NestedMessage.getDefaultInstance()) + .build(); + assertFalse(mine.equals(other)); assertFalse(other.equals(mine)); } @@ -2376,16 +2122,13 @@ public class LiteTest extends TestCase { public void testParseFromByteBufferThrows() { try { - TestAllTypesLite.parseFrom(ByteBuffer.wrap(new byte[] { 0x5 })); + TestAllTypesLite.parseFrom(ByteBuffer.wrap(new byte[] {0x5})); fail(); } catch (InvalidProtocolBufferException expected) { } TestAllTypesLite message = - TestAllTypesLite.newBuilder() - .setOptionalInt32(123) - .addRepeatedString("hello") - .build(); + TestAllTypesLite.newBuilder().setOptionalInt32(123).addRepeatedString("hello").build(); ByteBuffer buffer = ByteBuffer.wrap(message.toByteArray(), 0, message.getSerializedSize() - 1); try { @@ -2393,9 +2136,7 @@ public class LiteTest extends TestCase { fail(); } catch (InvalidProtocolBufferException expected) { assertEquals( - TestAllTypesLite.newBuilder() - .setOptionalInt32(123) - .build(), + TestAllTypesLite.newBuilder().setOptionalInt32(123).build(), expected.getUnfinishedMessage()); } } @@ -2425,7 +2166,7 @@ public class LiteTest extends TestCase { ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); UnittestLite.registerAllExtensions(registry); try { - TestAllExtensionsLite.parseFrom(ByteBuffer.wrap(new byte[] { 0x5 }), registry); + TestAllExtensionsLite.parseFrom(ByteBuffer.wrap(new byte[] {0x5}), registry); fail(); } catch (InvalidProtocolBufferException expected) { } @@ -2466,26 +2207,24 @@ public class LiteTest extends TestCase { } public void testAddAllIteratesOnce() { - TestAllTypesLite message = - TestAllTypesLite.newBuilder() - .addAllRepeatedBool(new OneTimeIterableList(false)) - .addAllRepeatedInt32(new OneTimeIterableList(0)) - .addAllRepeatedInt64(new OneTimeIterableList(0L)) - .addAllRepeatedFloat(new OneTimeIterableList(0f)) - .addAllRepeatedDouble(new OneTimeIterableList(0d)) - .addAllRepeatedBytes(new OneTimeIterableList(ByteString.EMPTY)) - .addAllRepeatedString(new OneTimeIterableList("")) - .addAllRepeatedNestedMessage( - new OneTimeIterableList(NestedMessage.getDefaultInstance())) - .addAllRepeatedBool(new OneTimeIterable(false)) - .addAllRepeatedInt32(new OneTimeIterable(0)) - .addAllRepeatedInt64(new OneTimeIterable(0L)) - .addAllRepeatedFloat(new OneTimeIterable(0f)) - .addAllRepeatedDouble(new OneTimeIterable(0d)) - .addAllRepeatedBytes(new OneTimeIterable(ByteString.EMPTY)) - .addAllRepeatedString(new OneTimeIterable("")) - .addAllRepeatedNestedMessage(new OneTimeIterable(NestedMessage.getDefaultInstance())) - .build(); + TestAllTypesLite.newBuilder() + .addAllRepeatedBool(new OneTimeIterableList(false)) + .addAllRepeatedInt32(new OneTimeIterableList(0)) + .addAllRepeatedInt64(new OneTimeIterableList(0L)) + .addAllRepeatedFloat(new OneTimeIterableList(0f)) + .addAllRepeatedDouble(new OneTimeIterableList(0d)) + .addAllRepeatedBytes(new OneTimeIterableList(ByteString.EMPTY)) + .addAllRepeatedString(new OneTimeIterableList("")) + .addAllRepeatedNestedMessage(new OneTimeIterableList(NestedMessage.getDefaultInstance())) + .addAllRepeatedBool(new OneTimeIterable(false)) + .addAllRepeatedInt32(new OneTimeIterable(0)) + .addAllRepeatedInt64(new OneTimeIterable(0L)) + .addAllRepeatedFloat(new OneTimeIterable(0f)) + .addAllRepeatedDouble(new OneTimeIterable(0d)) + .addAllRepeatedBytes(new OneTimeIterable(ByteString.EMPTY)) + .addAllRepeatedString(new OneTimeIterable("")) + .addAllRepeatedNestedMessage(new OneTimeIterable(NestedMessage.getDefaultInstance())) + .build(); } public void testAddAllIteratesOnce_throwsOnNull() { diff --git a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java index 6bbdfcaa32..e50c7d1e95 100644 --- a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java +++ b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java @@ -32,6 +32,7 @@ package com.google.protobuf; import static java.util.Arrays.asList; +import com.google.protobuf.Internal.LongList; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -297,6 +298,20 @@ public class LongArrayListTest extends TestCase { } } + public void testRemoveEndOfCapacity() { + LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addLong(3); + toRemove.remove(0); + assertEquals(0, toRemove.size()); + } + + public void testSublistRemoveEndOfCapacity() { + LongList toRemove = LongArrayList.emptyList().mutableCopyWithCapacity(1); + toRemove.addLong(3); + toRemove.subList(0, 1).clear(); + assertEquals(0, toRemove.size()); + } + private void assertImmutable(LongArrayList list) { if (list.contains(1L)) { throw new RuntimeException("Cannot test the immutability of lists that contain 1."); diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java index 37827f768a..bcfd927c31 100644 --- a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java +++ b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java @@ -788,6 +788,24 @@ public class MapForProto2Test extends TestCase { assertEquals(message.hashCode(), dynamicMessage.hashCode()); } + // Check that DynamicMessage handles map field serialization the same way as generated code + // regarding unset key and value field in a map entry. + public void testDynamicMessageUnsetKeyAndValue() throws Exception { + FieldDescriptor field = f("int32_to_int32_field"); + + Message dynamicDefaultInstance = + DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); + Message.Builder builder = dynamicDefaultInstance.newBuilderForType(); + // Add an entry without key and value. + builder.addRepeatedField(field, builder.newBuilderForField(field).build()); + Message message = builder.build(); + ByteString bytes = message.toByteString(); + // Parse it back to the same generated type. + Message generatedMessage = TestMap.parseFrom(bytes); + // Assert the serialized bytes are equivalent. + assertEquals(generatedMessage.toByteString(), bytes); + } + public void testReflectionEqualsAndHashCode() throws Exception { // Test that generated equals() and hashCode() will disregard the order // of map entries when comparing/hashing map fields. diff --git a/java/core/src/test/java/com/google/protobuf/MapTest.java b/java/core/src/test/java/com/google/protobuf/MapTest.java index 64ae4435d0..58efce92c0 100644 --- a/java/core/src/test/java/com/google/protobuf/MapTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapTest.java @@ -893,6 +893,24 @@ public class MapTest extends TestCase { assertEquals(message.hashCode(), dynamicMessage.hashCode()); } + // Check that DynamicMessage handles map field serialization the same way as generated code + // regarding unset key and value field in a map entry. + public void testDynamicMessageUnsetKeyAndValue() throws Exception { + FieldDescriptor field = f("int32_to_int32_field"); + + Message dynamicDefaultInstance = + DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); + Message.Builder builder = dynamicDefaultInstance.newBuilderForType(); + // Add an entry without key and value. + builder.addRepeatedField(field, builder.newBuilderForField(field).build()); + Message message = builder.build(); + ByteString bytes = message.toByteString(); + // Parse it back to the same generated type. + Message generatedMessage = TestMap.parseFrom(bytes); + // Assert the serialized bytes are equivalent. + assertEquals(generatedMessage.toByteString(), bytes); + } + public void testReflectionEqualsAndHashCode() throws Exception { // Test that generated equals() and hashCode() will disregard the order // of map entries when comparing/hashing map fields. diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java index 5d38ca511c..720061d257 100644 --- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java +++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java @@ -61,12 +61,11 @@ import junit.framework.TestCase; public class TextFormatTest extends TestCase { // A basic string with different escapable characters for testing. - private final static String kEscapeTestString = - "\"A string with ' characters \n and \r newlines and \t tabs and \001 " - + "slashes \\"; + private static final String ESCAPE_TEST_STRING = + "\"A string with ' characters \n and \r newlines and \t tabs and \001 " + "slashes \\"; // A representation of the above string with all the characters escaped. - private final static String kEscapeTestStringEscaped = + private static final String ESCAPE_TEST_STRING_ESCAPED = "\\\"A string with \\' characters \\n and \\r newlines " + "and \\t tabs and \\001 slashes \\\\"; @@ -576,10 +575,10 @@ public class TextFormatTest extends TestCase { "integer: 82301481290849012385230157", "optional_int32: 82301481290849012385230157"); assertParseError( - "1:16: Expected \"true\" or \"false\".", + "1:16: Expected \"true\" or \"false\". Found \"maybe\".", "optional_bool: maybe"); assertParseError( - "1:16: Expected \"true\" or \"false\".", + "1:16: Expected \"true\" or \"false\". Found \"2\".", "optional_bool: 2"); assertParseError( "1:18: Expected string.", @@ -643,10 +642,8 @@ public class TextFormatTest extends TestCase { TextFormat.unescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); assertEquals("\0\001\007\b\f\n\r\t\013\\\'\"", TextFormat.unescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"")); - assertEquals(kEscapeTestStringEscaped, - TextFormat.escapeText(kEscapeTestString)); - assertEquals(kEscapeTestString, - TextFormat.unescapeText(kEscapeTestStringEscaped)); + assertEquals(ESCAPE_TEST_STRING_ESCAPED, TextFormat.escapeText(ESCAPE_TEST_STRING)); + assertEquals(ESCAPE_TEST_STRING, TextFormat.unescapeText(ESCAPE_TEST_STRING_ESCAPED)); // Invariant assertEquals("hello", diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java index 9928d44a04..8ce0ca7362 100644 --- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java @@ -30,6 +30,8 @@ package com.google.protobuf; +import static junit.framework.TestCase.assertEquals; + import com.google.protobuf.UnittestLite.TestAllExtensionsLite; import com.google.protobuf.UnittestLite.TestAllTypesLite; import protobuf_unittest.UnittestProto; @@ -133,6 +135,25 @@ public class UnknownFieldSetLiteTest extends TestCase { assertEquals(foo.toByteString().size(), instance.getSerializedSize()); } + public void testHashCodeAfterDeserialization() throws IOException { + Foo foo = Foo.newBuilder() + .setValue(2) + .build(); + + Foo fooDeserialized = Foo.parseFrom(foo.toByteArray()); + + assertEquals(fooDeserialized, foo); + assertEquals(foo.hashCode(), fooDeserialized.hashCode()); + } + + public void testNewInstanceHashCode() { + UnknownFieldSetLite emptyFieldSet = UnknownFieldSetLite.getDefaultInstance(); + UnknownFieldSetLite paddedFieldSet = UnknownFieldSetLite.newInstance(); + + assertEquals(emptyFieldSet, paddedFieldSet); + assertEquals(emptyFieldSet.hashCode(), paddedFieldSet.hashCode()); + } + public void testMergeVarintField() throws IOException { UnknownFieldSetLite unknownFields = UnknownFieldSetLite.newInstance(); unknownFields.mergeVarintField(10, 2); diff --git a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java index 625d4b420e..03c33ecfea 100644 --- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java +++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java @@ -36,6 +36,7 @@ import protobuf_unittest.UnittestMset.TestMessageSetExtension2; import protobuf_unittest.UnittestProto; import protobuf_unittest.UnittestProto.TestAllExtensions; import protobuf_unittest.UnittestProto.TestAllTypes; +import protobuf_unittest.UnittestProto.TestExtensionInsideTable; import protobuf_unittest.UnittestProto.TestFieldOrderings; import protobuf_unittest.UnittestProto.TestOneof2; import protobuf_unittest.UnittestProto.TestOneofBackwardsCompatible; @@ -235,6 +236,26 @@ public class WireFormatTest extends TestCase { getTestFieldOrderingsRegistry()); assertEquals(source, dest); } + + private static ExtensionRegistry getTestExtensionInsideTableRegistry() { + ExtensionRegistry result = ExtensionRegistry.newInstance(); + result.add(UnittestProto.testExtensionInsideTableExtension); + return result; + } + + public void testExtensionInsideTable() throws Exception { + // Make sure the extension within the range of table is parsed correctly in experimental + // runtime. + TestExtensionInsideTable source = + TestExtensionInsideTable.newBuilder() + .setField1(1) + .setExtension(UnittestProto.testExtensionInsideTableExtension, 23) + .build(); + TestExtensionInsideTable dest = + TestExtensionInsideTable.parseFrom(source.toByteString(), + getTestExtensionInsideTableRegistry()); + assertEquals(source, dest); + } public void testParseMultipleExtensionRangesDynamic() throws Exception { // Same as above except with DynamicMessage. diff --git a/js/binary/constants.js b/js/binary/constants.js index 75a8a52cdd..21c5889c93 100644 --- a/js/binary/constants.js +++ b/js/binary/constants.js @@ -60,14 +60,25 @@ goog.forwardDeclare('jsproto.BinaryExtension'); /** - * Base interface class for all const messages. Does __not__ define any - * methods, as doing so on a widely-used interface defeats dead-code - * elimination. + * Base interface class for all const messages. * @interface */ jspb.ConstBinaryMessage = function() {}; +/** + * Generate a debug string for this proto that is in proto2 text format. + * @return {string} The debug string. + */ +jspb.ConstBinaryMessage.prototype.toDebugString; +/** + * Helper to generate a debug string for this proto at some indent level. The + * first line is not indented. + * @param {number} indentLevel The number of spaces by which to indent lines. + * @return {string} The debug string. + * @protected + */ +jspb.ConstBinaryMessage.prototype.toDebugStringInternal; /** * Base interface class for all messages. Does __not__ define any methods, as @@ -97,6 +108,7 @@ jspb.ScalarFieldType; * A repeated field in jspb is an array of scalars, blobs, or messages. * @typedef {!Array| !Array| + !Array| !Array} */ jspb.RepeatedFieldType; @@ -108,6 +120,7 @@ jspb.RepeatedFieldType; * @typedef {jspb.ScalarFieldType| jspb.RepeatedFieldType| !Uint8Array| + !jspb.ConstBinaryMessage| !jspb.BinaryMessage| !jsproto.BinaryExtension} */ diff --git a/js/binary/decoder.js b/js/binary/decoder.js index d0c0bc172c..e33bf1be9c 100644 --- a/js/binary/decoder.js +++ b/js/binary/decoder.js @@ -986,7 +986,7 @@ jspb.BinaryDecoder.prototype.readString = function(length) { codeUnits.push(high, low); } - // Avoid exceeding the maximum stack size when calling {@code apply}. + // Avoid exceeding the maximum stack size when calling `apply`. if (codeUnits.length >= 8192) { result += String.fromCharCode.apply(null, codeUnits); codeUnits.length = 0; diff --git a/js/binary/writer.js b/js/binary/writer.js index 8a0180583d..287d29c3f3 100644 --- a/js/binary/writer.js +++ b/js/binary/writer.js @@ -236,10 +236,12 @@ jspb.BinaryWriter.prototype.getResultBuffer = function() { /** * Converts the encoded data into a base64-encoded string. + * @param {boolean=} opt_webSafe True indicates we should use a websafe + * alphabet, which does not require escaping for use in URLs. * @return {string} */ -jspb.BinaryWriter.prototype.getResultBase64String = function() { - return goog.crypt.base64.encodeByteArray(this.getResultBuffer()); +jspb.BinaryWriter.prototype.getResultBase64String = function(opt_webSafe) { + return goog.crypt.base64.encodeByteArray(this.getResultBuffer(), opt_webSafe); }; diff --git a/js/binary/writer_test.js b/js/binary/writer_test.js index 118eecfc6c..8a9a1bb009 100644 --- a/js/binary/writer_test.js +++ b/js/binary/writer_test.js @@ -118,4 +118,16 @@ describe('binaryWriterTest', function() { var buffer = writer.getResultBuffer(); assertEquals(expected, goog.crypt.byteArrayToHex(buffer)); }); + + + /** + * Tests websafe encodings for base64 strings. + */ + it('testWebSafeOption', function() { + var writer = new jspb.BinaryWriter(); + writer.writeBytes(1, new Uint8Array([127])); + assertEquals('CgF/', writer.getResultBase64String()); + assertEquals('CgF/', writer.getResultBase64String(false)); + assertEquals('CgF_', writer.getResultBase64String(true)); + }); }); diff --git a/js/debug.js b/js/debug.js index 4ae3c2a231..ba51bbe01c 100644 --- a/js/debug.js +++ b/js/debug.js @@ -42,7 +42,7 @@ goog.require('jspb.Message'); /** * Turns a proto into a human readable object that can i.e. be written to the - * console: {@code console.log(jspb.debug.dump(myProto))}. + * console: `console.log(jspb.debug.dump(myProto))`. * This function makes a best effort and may not work in all cases. It will not * work in obfuscated and or optimized code. * Use this in environments where {@see jspb.Message.prototype.toObject} is diff --git a/js/map.js b/js/map.js index d423499f05..7b5b2c389d 100644 --- a/js/map.js +++ b/js/map.js @@ -48,9 +48,9 @@ goog.forwardDeclare('jspb.BinaryWriter'); * * @template K, V * - * @param {!Array>} arr + * @param {!Array>} arr * - * @param {?function(new:V)|function(new:V,?)=} opt_valueCtor + * @param {?function(new:V, ?=)=} opt_valueCtor * The constructor for type V, if type V is a message type. * * @constructor @@ -118,7 +118,7 @@ jspb.Map.prototype.toArray = function() { strKeys.sort(); for (var i = 0; i < strKeys.length; i++) { var entry = this.map_[strKeys[i]]; - var valueWrapper = /** @type {!Object} */ (entry.valueWrapper); + var valueWrapper = /** @type {?jspb.Message} */ (entry.valueWrapper); if (valueWrapper) { valueWrapper.toArray(); } @@ -165,7 +165,7 @@ jspb.Map.prototype.toObject = function(includeInstance, valueToObject) { * * @template K, V * @param {!Array>} entries - * @param {!function(new:V)|function(new:V,?)} valueCtor + * @param {!function(new:V,?=)} valueCtor * The constructor for type V. * @param {!function(!Object):V} valueFromObject * The fromObject function for type V. @@ -432,7 +432,8 @@ jspb.Map.prototype.serializeBinary = function( valueWriterFn.call(writer, 2, this.wrapEntry_(entry), opt_valueWriterCallback); } else { - valueWriterFn.call(writer, 2, entry.value); + /** @type {function(this:jspb.BinaryWriter,number,?)} */ (valueWriterFn) + .call(writer, 2, entry.value); } writer.endSubMessage(); } @@ -475,10 +476,13 @@ jspb.Map.deserializeBinary = function(map, reader, keyReaderFn, valueReaderFn, } else if (field == 2) { // Value. if (map.valueCtor_) { + goog.asserts.assert(opt_valueReaderCallback); value = new map.valueCtor_(); valueReaderFn.call(reader, value, opt_valueReaderCallback); } else { - value = valueReaderFn.call(reader); + value = + (/** @type {function(this:jspb.BinaryReader):?} */ (valueReaderFn)) + .call(reader); } } } diff --git a/js/message.js b/js/message.js index 8f68cbb499..04d43339f1 100644 --- a/js/message.js +++ b/js/message.js @@ -215,17 +215,6 @@ goog.define('jspb.Message.ASSUME_LOCAL_ARRAYS', false); goog.define('jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS', true); -/** - * @define {boolean} Turning on this flag does NOT change the behavior of JSPB - * and only affects private internal state. It may, however, break some - * tests that use naive deeply-equals algorithms, because using a proto - * mutates its internal state. - * Projects are advised to turn this flag always on. - */ -goog.define('jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS', true); -// TODO(b/19419436): Delete this flag. - - /** * Does this JavaScript environment support Uint8Aray typed arrays? * @type {boolean} @@ -369,7 +358,7 @@ jspb.Message.getFieldNumber_ = function(msg, index) { */ jspb.Message.initialize = function( msg, data, messageId, suggestedPivot, repeatedFields, opt_oneofFields) { - msg.wrappers_ = jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ? null : {}; + msg.wrappers_ = null; if (!data) { data = messageId ? [messageId] : []; } @@ -394,17 +383,12 @@ jspb.Message.initialize = function( var fieldNumber = repeatedFields[i]; if (fieldNumber < msg.pivot_) { var index = jspb.Message.getIndex_(msg, fieldNumber); - msg.array[index] = msg.array[index] || - (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ? - jspb.Message.EMPTY_LIST_SENTINEL_ : - []); + msg.array[index] = + msg.array[index] || jspb.Message.EMPTY_LIST_SENTINEL_; } else { jspb.Message.maybeInitEmptyExtensionObject_(msg); - msg.extensionObject_[fieldNumber] = - msg.extensionObject_[fieldNumber] || - (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ? - jspb.Message.EMPTY_LIST_SENTINEL_ : - []); + msg.extensionObject_[fieldNumber] = msg.extensionObject_[fieldNumber] || + jspb.Message.EMPTY_LIST_SENTINEL_; } } } @@ -517,8 +501,7 @@ jspb.Message.toObjectList = function(field, toObjectFn, opt_includeInstance) { // And not using it here to avoid a function call. var result = []; for (var i = 0; i < field.length; i++) { - result[i] = toObjectFn.call(field[i], opt_includeInstance, - /** @type {!jspb.Message} */ (field[i])); + result[i] = toObjectFn.call(field[i], opt_includeInstance, field[i]); } return result; }; @@ -551,10 +534,11 @@ jspb.Message.toObjectExtension = function(proto, obj, extensions, } else { if (fieldInfo.isRepeated) { obj[name] = jspb.Message.toObjectList( - /** @type {!Array} */ (value), + /** @type {!Array} */ (value), fieldInfo.toObjectFn, opt_includeInstance); } else { - obj[name] = fieldInfo.toObjectFn(opt_includeInstance, value); + obj[name] = fieldInfo.toObjectFn( + opt_includeInstance, /** @type {!jspb.Message} */ (value)); } } } @@ -1419,7 +1403,7 @@ jspb.Message.prototype.setExtension = function(fieldInfo, value) { if (fieldInfo.isMessageType()) { self.wrappers_[fieldNumber] = value; self.extensionObject_[fieldNumber] = goog.array.map( - /** @type {Array} */ (value), function(msg) { + /** @type {!Array} */ (value), function(msg) { return msg.toArray(); }); } else { @@ -1428,7 +1412,8 @@ jspb.Message.prototype.setExtension = function(fieldInfo, value) { } else { if (fieldInfo.isMessageType()) { self.wrappers_[fieldNumber] = value; - self.extensionObject_[fieldNumber] = value ? value.toArray() : value; + self.extensionObject_[fieldNumber] = + value ? /** @type {!jspb.Message} */ (value).toArray() : value; } else { self.extensionObject_[fieldNumber] = value; } @@ -1530,9 +1515,15 @@ jspb.Message.compareFields = function(field1, field2) { // If the fields are trivially equal, they're equal. if (field1 == field2) return true; - // If the fields aren't trivially equal and one of them isn't an object, - // they can't possibly be equal. if (!goog.isObject(field1) || !goog.isObject(field2)) { + // NaN != NaN so we cover this case. + if ((goog.isNumber(field1) && isNaN(field1)) || + (goog.isNumber(field2) && isNaN(field2))) { + // One of the fields might be a string 'NaN'. + return String(field1) == String(field2); + } + // If the fields aren't trivially equal and one of them isn't an object, + // they can't possibly be equal. return false; } @@ -1555,24 +1546,26 @@ jspb.Message.compareFields = function(field1, field2) { // If they're both Arrays, compare them element by element except for the // optional extension objects at the end, which we compare separately. if (field1.constructor === Array) { + var typedField1 = /** @type {!Array} */ (field1); + var typedField2 = /** @type {!Array} */ (field2); var extension1 = undefined; var extension2 = undefined; - var length = Math.max(field1.length, field2.length); + var length = Math.max(typedField1.length, typedField2.length); for (var i = 0; i < length; i++) { - var val1 = field1[i]; - var val2 = field2[i]; + var val1 = typedField1[i]; + var val2 = typedField2[i]; if (val1 && (val1.constructor == Object)) { goog.asserts.assert(extension1 === undefined); - goog.asserts.assert(i === field1.length - 1); + goog.asserts.assert(i === typedField1.length - 1); extension1 = val1; val1 = undefined; } if (val2 && (val2.constructor == Object)) { goog.asserts.assert(extension2 === undefined); - goog.asserts.assert(i === field2.length - 1); + goog.asserts.assert(i === typedField2.length - 1); extension2 = val2; val2 = undefined; } @@ -1695,8 +1688,13 @@ jspb.Message.clone_ = function(obj) { var clonedArray = new Array(obj.length); // Use array iteration where possible because it is faster than for-in. for (var i = 0; i < obj.length; i++) { - if ((o = obj[i]) != null) { - clonedArray[i] = typeof o == 'object' ? jspb.Message.clone_(o) : o; + o = obj[i]; + if (o != null) { + // NOTE:redundant null check existing for NTI compatibility. + // see b/70515949 + clonedArray[i] = (typeof o == 'object') ? + jspb.Message.clone_(goog.asserts.assert(o)) : + o; } } return clonedArray; @@ -1706,8 +1704,13 @@ jspb.Message.clone_ = function(obj) { } var clone = {}; for (var key in obj) { - if ((o = obj[key]) != null) { - clone[key] = typeof o == 'object' ? jspb.Message.clone_(o) : o; + o = obj[key]; + if (o != null) { + // NOTE:redundant null check existing for NTI compatibility. + // see b/70515949 + clone[key] = (typeof o == 'object') ? + jspb.Message.clone_(goog.asserts.assert(o)) : + o; } } return clone; @@ -1723,6 +1726,9 @@ jspb.Message.registerMessageType = function(id, constructor) { jspb.Message.registry_[id] = constructor; // This is needed so we can later access messageId directly on the contructor, // otherwise it is not available due to 'property collapsing' by the compiler. + /** + * @suppress {strictMissingProperties} messageId is not defined on Function + */ constructor.messageId = id; }; diff --git a/js/message_test.js b/js/message_test.js index 0acebb75f9..1be4109384 100644 --- a/js/message_test.js +++ b/js/message_test.js @@ -418,6 +418,18 @@ describe('Message test suite', function() { ['hi',,, {100: [{200: 'a'}]}], ['hi', {100: [{200: 'a'}]}])); }); + it('testEqualsNonFinite', function() { + assertTrue(jspb.Message.compareFields(NaN, NaN)); + assertTrue(jspb.Message.compareFields(NaN, 'NaN')); + assertTrue(jspb.Message.compareFields('NaN', NaN)); + assertTrue(jspb.Message.compareFields(Infinity, Infinity)); + assertTrue(jspb.Message.compareFields(Infinity, 'Infinity')); + assertTrue(jspb.Message.compareFields('-Infinity', -Infinity)); + assertTrue(jspb.Message.compareFields([NaN], ['NaN'])); + assertFalse(jspb.Message.compareFields(undefined, NaN)); + assertFalse(jspb.Message.compareFields(NaN, undefined)); + }); + it('testToMap', function() { var p1 = new proto.jspb.test.Simple1(['k', ['v']]); var p2 = new proto.jspb.test.Simple1(['k1', ['v1', 'v2']]); diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py index 0d35425f81..8a9ba3da48 100755 --- a/python/google/protobuf/descriptor.py +++ b/python/google/protobuf/descriptor.py @@ -34,6 +34,7 @@ file, in types that make this information accessible in Python. __author__ = 'robinson@google.com (Will Robinson)' +import threading import six from google.protobuf.internal import api_implementation @@ -72,6 +73,24 @@ else: DescriptorMetaclass = type +class _Lock(object): + """Wrapper class of threading.Lock(), which is allowed by 'with'.""" + + def __new__(cls): + self = object.__new__(cls) + self._lock = threading.Lock() # pylint: disable=protected-access + return self + + def __enter__(self): + self._lock.acquire() + + def __exit__(self, exc_type, exc_value, exc_tb): + self._lock.release() + + +_lock = threading.Lock() + + class DescriptorBase(six.with_metaclass(DescriptorMetaclass)): """Descriptors base class. @@ -92,16 +111,17 @@ class DescriptorBase(six.with_metaclass(DescriptorMetaclass)): # subclasses" of this descriptor class. _C_DESCRIPTOR_CLASS = () - def __init__(self, options, options_class_name): + def __init__(self, options, serialized_options, options_class_name): """Initialize the descriptor given its options message and the name of the class of the options message. The name of the class is required in case the options message is None and has to be created. """ self._options = options self._options_class_name = options_class_name + self._serialized_options = serialized_options # Does this descriptor have non-default options? - self.has_options = options is not None + self.has_options = (options is not None) or (serialized_options is not None) def _SetOptions(self, options, options_class_name): """Sets the descriptor's options @@ -123,14 +143,23 @@ class DescriptorBase(six.with_metaclass(DescriptorMetaclass)): """ if self._options: return self._options + from google.protobuf import descriptor_pb2 try: - options_class = getattr(descriptor_pb2, self._options_class_name) + options_class = getattr(descriptor_pb2, + self._options_class_name) except AttributeError: raise RuntimeError('Unknown options class name %s!' % (self._options_class_name)) - self._options = options_class() - return self._options + + with _lock: + if self._serialized_options is None: + self._options = options_class() + else: + self._options = _ParseOptions(options_class(), + self._serialized_options) + + return self._options class _NestedDescriptorBase(DescriptorBase): @@ -138,7 +167,7 @@ class _NestedDescriptorBase(DescriptorBase): def __init__(self, options, options_class_name, name, full_name, file, containing_type, serialized_start=None, - serialized_end=None): + serialized_end=None, serialized_options=None): """Constructor. Args: @@ -157,9 +186,10 @@ class _NestedDescriptorBase(DescriptorBase): file.serialized_pb that describes this descriptor. serialized_end: The end index (exclusive) in block in the file.serialized_pb that describes this descriptor. + serialized_options: Protocol message serilized options or None. """ super(_NestedDescriptorBase, self).__init__( - options, options_class_name) + options, serialized_options, options_class_name) self.name = name # TODO(falk): Add function to calculate full_name instead of having it in @@ -250,6 +280,7 @@ class Descriptor(_NestedDescriptorBase): def __new__(cls, name, full_name, filename, containing_type, fields, nested_types, enum_types, extensions, options=None, + serialized_options=None, is_extendable=True, extension_ranges=None, oneofs=None, file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin syntax=None): @@ -261,6 +292,7 @@ class Descriptor(_NestedDescriptorBase): # name of the argument. def __init__(self, name, full_name, filename, containing_type, fields, nested_types, enum_types, extensions, options=None, + serialized_options=None, is_extendable=True, extension_ranges=None, oneofs=None, file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin syntax=None): @@ -273,7 +305,7 @@ class Descriptor(_NestedDescriptorBase): super(Descriptor, self).__init__( options, 'MessageOptions', name, full_name, file, containing_type, serialized_start=serialized_start, - serialized_end=serialized_end) + serialized_end=serialized_end, serialized_options=serialized_options) # We have fields in addition to fields_by_name and fields_by_number, # so that: @@ -492,8 +524,9 @@ class FieldDescriptor(DescriptorBase): def __new__(cls, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options=None, + serialized_options=None, has_default_value=True, containing_oneof=None, json_name=None, - file=None): + file=None): # pylint: disable=redefined-builtin _message.Message._CheckCalledFromGeneratedFile() if is_extension: return _message.default_pool.FindExtensionByName(full_name) @@ -503,8 +536,9 @@ class FieldDescriptor(DescriptorBase): def __init__(self, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options=None, + serialized_options=None, has_default_value=True, containing_oneof=None, json_name=None, - file=None): + file=None): # pylint: disable=redefined-builtin """The arguments are as described in the description of FieldDescriptor attributes above. @@ -512,7 +546,8 @@ class FieldDescriptor(DescriptorBase): (to deal with circular references between message types, for example). Likewise for extension_scope. """ - super(FieldDescriptor, self).__init__(options, 'FieldOptions') + super(FieldDescriptor, self).__init__( + options, serialized_options, 'FieldOptions') self.name = name self.full_name = full_name self.file = file @@ -598,13 +633,15 @@ class EnumDescriptor(_NestedDescriptorBase): _C_DESCRIPTOR_CLASS = _message.EnumDescriptor def __new__(cls, name, full_name, filename, values, - containing_type=None, options=None, file=None, + containing_type=None, options=None, + serialized_options=None, file=None, # pylint: disable=redefined-builtin serialized_start=None, serialized_end=None): _message.Message._CheckCalledFromGeneratedFile() return _message.default_pool.FindEnumTypeByName(full_name) def __init__(self, name, full_name, filename, values, - containing_type=None, options=None, file=None, + containing_type=None, options=None, + serialized_options=None, file=None, # pylint: disable=redefined-builtin serialized_start=None, serialized_end=None): """Arguments are as described in the attribute description above. @@ -614,7 +651,7 @@ class EnumDescriptor(_NestedDescriptorBase): super(EnumDescriptor, self).__init__( options, 'EnumOptions', name, full_name, file, containing_type, serialized_start=serialized_start, - serialized_end=serialized_end) + serialized_end=serialized_end, serialized_options=serialized_options) self.values = values for value in self.values: @@ -650,7 +687,9 @@ class EnumValueDescriptor(DescriptorBase): if _USE_C_DESCRIPTORS: _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor - def __new__(cls, name, index, number, type=None, options=None): + def __new__(cls, name, index, number, + type=None, # pylint: disable=redefined-builtin + options=None, serialized_options=None): _message.Message._CheckCalledFromGeneratedFile() # There is no way we can build a complete EnumValueDescriptor with the # given parameters (the name of the Enum is not known, for example). @@ -658,9 +697,12 @@ class EnumValueDescriptor(DescriptorBase): # constructor, which will ignore it, so returning None is good enough. return None - def __init__(self, name, index, number, type=None, options=None): + def __init__(self, name, index, number, + type=None, # pylint: disable=redefined-builtin + options=None, serialized_options=None): """Arguments are as described in the attribute description above.""" - super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions') + super(EnumValueDescriptor, self).__init__( + options, serialized_options, 'EnumValueOptions') self.name = name self.index = index self.number = number @@ -685,14 +727,17 @@ class OneofDescriptor(DescriptorBase): _C_DESCRIPTOR_CLASS = _message.OneofDescriptor def __new__( - cls, name, full_name, index, containing_type, fields, options=None): + cls, name, full_name, index, containing_type, fields, options=None, + serialized_options=None): _message.Message._CheckCalledFromGeneratedFile() return _message.default_pool.FindOneofByName(full_name) def __init__( - self, name, full_name, index, containing_type, fields, options=None): + self, name, full_name, index, containing_type, fields, options=None, + serialized_options=None): """Arguments are as described in the attribute description above.""" - super(OneofDescriptor, self).__init__(options, 'OneofOptions') + super(OneofDescriptor, self).__init__( + options, serialized_options, 'OneofOptions') self.name = name self.full_name = full_name self.index = index @@ -721,17 +766,19 @@ class ServiceDescriptor(_NestedDescriptorBase): if _USE_C_DESCRIPTORS: _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor - def __new__(cls, name, full_name, index, methods, options=None, file=None, # pylint: disable=redefined-builtin + def __new__(cls, name, full_name, index, methods, options=None, + serialized_options=None, file=None, # pylint: disable=redefined-builtin serialized_start=None, serialized_end=None): _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access return _message.default_pool.FindServiceByName(full_name) - def __init__(self, name, full_name, index, methods, options=None, file=None, + def __init__(self, name, full_name, index, methods, options=None, + serialized_options=None, file=None, # pylint: disable=redefined-builtin serialized_start=None, serialized_end=None): super(ServiceDescriptor, self).__init__( options, 'ServiceOptions', name, full_name, file, None, serialized_start=serialized_start, - serialized_end=serialized_end) + serialized_end=serialized_end, serialized_options=serialized_options) self.index = index self.methods = methods self.methods_by_name = dict((m.name, m) for m in methods) @@ -772,18 +819,19 @@ class MethodDescriptor(DescriptorBase): _C_DESCRIPTOR_CLASS = _message.MethodDescriptor def __new__(cls, name, full_name, index, containing_service, - input_type, output_type, options=None): + input_type, output_type, options=None, serialized_options=None): _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access return _message.default_pool.FindMethodByName(full_name) def __init__(self, name, full_name, index, containing_service, - input_type, output_type, options=None): + input_type, output_type, options=None, serialized_options=None): """The arguments are as described in the description of MethodDescriptor attributes above. Note that containing_service may be None, and may be set later if necessary. """ - super(MethodDescriptor, self).__init__(options, 'MethodOptions') + super(MethodDescriptor, self).__init__( + options, serialized_options, 'MethodOptions') self.name = name self.full_name = full_name self.index = index @@ -818,7 +866,8 @@ class FileDescriptor(DescriptorBase): if _USE_C_DESCRIPTORS: _C_DESCRIPTOR_CLASS = _message.FileDescriptor - def __new__(cls, name, package, options=None, serialized_pb=None, + def __new__(cls, name, package, options=None, + serialized_options=None, serialized_pb=None, dependencies=None, public_dependencies=None, syntax=None, pool=None): # FileDescriptor() is called from various places, not only from generated @@ -830,11 +879,13 @@ class FileDescriptor(DescriptorBase): else: return super(FileDescriptor, cls).__new__(cls) - def __init__(self, name, package, options=None, serialized_pb=None, + def __init__(self, name, package, options=None, + serialized_options=None, serialized_pb=None, dependencies=None, public_dependencies=None, syntax=None, pool=None): """Constructor.""" - super(FileDescriptor, self).__init__(options, 'FileOptions') + super(FileDescriptor, self).__init__( + options, serialized_options, 'FileOptions') if pool is None: from google.protobuf import descriptor_pool diff --git a/python/google/protobuf/internal/_parameterized.py b/python/google/protobuf/internal/_parameterized.py index 23a78f037e..f2c0b305b9 100755 --- a/python/google/protobuf/internal/_parameterized.py +++ b/python/google/protobuf/internal/_parameterized.py @@ -37,8 +37,8 @@ argument tuples. A simple example: - class AdditionExample(parameterized.ParameterizedTestCase): - @parameterized.Parameters( + class AdditionExample(parameterized.TestCase): + @parameterized.parameters( (1, 2, 3), (4, 5, 9), (1, 1, 3)) @@ -54,8 +54,8 @@ fail due to an assertion error (1 + 1 != 3). Parameters for invididual test cases can be tuples (with positional parameters) or dictionaries (with named parameters): - class AdditionExample(parameterized.ParameterizedTestCase): - @parameterized.Parameters( + class AdditionExample(parameterized.TestCase): + @parameterized.parameters( {'op1': 1, 'op2': 2, 'result': 3}, {'op1': 4, 'op2': 5, 'result': 9}, ) @@ -77,13 +77,13 @@ stay the same across several invocations, object representations like '<__main__.Foo object at 0x23d8610>' are turned into '<__main__.Foo>'. For even more descriptive names, -especially in test logs, you can use the NamedParameters decorator. In +especially in test logs, you can use the named_parameters decorator. In this case, only tuples are supported, and the first parameters has to be a string (or an object that returns an apt name when converted via str()): - class NamedExample(parameterized.ParameterizedTestCase): - @parameterized.NamedParameters( + class NamedExample(parameterized.TestCase): + @parameterized.named_parameters( ('Normal', 'aa', 'aaa', True), ('EmptyPrefix', '', 'abc', True), ('BothEmpty', '', '', True)) @@ -103,13 +103,13 @@ from the command line: Parameterized Classes ===================== If invocation arguments are shared across test methods in a single -ParameterizedTestCase class, instead of decorating all test methods +TestCase class, instead of decorating all test methods individually, the class itself can be decorated: - @parameterized.Parameters( + @parameterized.parameters( (1, 2, 3) (4, 5, 9)) - class ArithmeticTest(parameterized.ParameterizedTestCase): + class ArithmeticTest(parameterized.TestCase): def testAdd(self, arg1, arg2, result): self.assertEqual(arg1 + arg2, result) @@ -122,8 +122,8 @@ If parameters should be shared across several test cases, or are dynamically created from other sources, a single non-tuple iterable can be passed into the decorator. This iterable will be used to obtain the test cases: - class AdditionExample(parameterized.ParameterizedTestCase): - @parameterized.Parameters( + class AdditionExample(parameterized.TestCase): + @parameterized.parameters( c.op1, c.op2, c.result for c in testcases ) def testAddition(self, op1, op2, result): @@ -135,8 +135,8 @@ Single-Argument Test Methods If a test method takes only one argument, the single argument does not need to be wrapped into a tuple: - class NegativeNumberExample(parameterized.ParameterizedTestCase): - @parameterized.Parameters( + class NegativeNumberExample(parameterized.TestCase): + @parameterized.parameters( -1, -3, -4, -5 ) def testIsNegative(self, arg): @@ -212,7 +212,7 @@ class _ParameterizedTestIter(object): def __call__(self, *args, **kwargs): raise RuntimeError('You appear to be running a parameterized test case ' 'without having inherited from parameterized.' - 'ParameterizedTestCase. This is bad because none of ' + 'TestCase. This is bad because none of ' 'your test cases are actually being run.') def __iter__(self): @@ -306,7 +306,7 @@ def _ParameterDecorator(naming_type, testcases): return _Apply -def Parameters(*testcases): +def parameters(*testcases): # pylint: disable=invalid-name """A decorator for creating parameterized tests. See the module docstring for a usage example. @@ -321,7 +321,7 @@ def Parameters(*testcases): return _ParameterDecorator(_ARGUMENT_REPR, testcases) -def NamedParameters(*testcases): +def named_parameters(*testcases): # pylint: disable=invalid-name """A decorator for creating parameterized tests. See the module docstring for a usage example. The first element of @@ -348,7 +348,7 @@ class TestGeneratorMetaclass(type): up as tests by the unittest framework. In general, it is supposed to be used in conjunction with the - Parameters decorator. + parameters decorator. """ def __new__(mcs, class_name, bases, dct): @@ -385,8 +385,8 @@ def _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator): id_suffix[new_name] = getattr(func, '__x_extra_id__', '') -class ParameterizedTestCase(unittest.TestCase): - """Base class for test cases using the Parameters decorator.""" +class TestCase(unittest.TestCase): + """Base class for test cases using the parameters decorator.""" __metaclass__ = TestGeneratorMetaclass def _OriginalName(self): @@ -409,10 +409,10 @@ class ParameterizedTestCase(unittest.TestCase): self._id_suffix.get(self._testMethodName, '')) -def CoopParameterizedTestCase(other_base_class): +def CoopTestCase(other_base_class): """Returns a new base class with a cooperative metaclass base. - This enables the ParameterizedTestCase to be used in combination + This enables the TestCase to be used in combination with other base classes that have custom metaclasses, such as mox.MoxTestBase. @@ -425,7 +425,7 @@ def CoopParameterizedTestCase(other_base_class): from google3.testing.pybase import parameterized - class ExampleTest(parameterized.CoopParameterizedTestCase(mox.MoxTestBase)): + class ExampleTest(parameterized.CoopTestCase(mox.MoxTestBase)): ... Args: @@ -439,5 +439,5 @@ def CoopParameterizedTestCase(other_base_class): (other_base_class.__metaclass__, TestGeneratorMetaclass), {}) return metaclass( - 'CoopParameterizedTestCase', - (other_base_class, ParameterizedTestCase), {}) + 'CoopTestCase', + (other_base_class, TestCase), {}) diff --git a/python/google/protobuf/internal/api_implementation.py b/python/google/protobuf/internal/api_implementation.py index 553fcdb60c..ab9e7812c5 100755 --- a/python/google/protobuf/internal/api_implementation.py +++ b/python/google/protobuf/internal/api_implementation.py @@ -66,10 +66,13 @@ if _api_version < 0: # Still unspecified? from google.protobuf.internal import use_pure_python del use_pure_python # Avoids a pylint error and namespace pollution. except ImportError: - if _proto_extension_modules_exist_in_build: - if sys.version_info[0] >= 3: # Python 3 defaults to C++ impl v2. - _api_version = 2 - # TODO(b/17427486): Make Python 2 default to C++ impl v2. + # TODO(b/74017912): It's unsafe to enable :use_fast_cpp_protos by default; + # it can cause data loss if you have any Python-only extensions to any + # message passed back and forth with C++ code. + # + # TODO(b/17427486): Once that bug is fixed, we want to make both Python 2 + # and Python 3 default to `_api_version = 2` (C++ implementation V2). + pass _default_implementation_type = ( 'python' if _api_version <= 0 else 'cpp') diff --git a/python/google/protobuf/internal/encoder.py b/python/google/protobuf/internal/encoder.py index dc7a8ce846..0d1f49dd9c 100755 --- a/python/google/protobuf/internal/encoder.py +++ b/python/google/protobuf/internal/encoder.py @@ -372,7 +372,7 @@ def MapSizer(field_descriptor, is_message_map): def _VarintEncoder(): """Return an encoder for a basic varint value (does not include tag).""" - def EncodeVarint(write, value, unused_deterministic): + def EncodeVarint(write, value, unused_deterministic=None): bits = value & 0x7f value >>= 7 while value: @@ -388,7 +388,7 @@ def _SignedVarintEncoder(): """Return an encoder for a basic signed varint value (does not include tag).""" - def EncodeSignedVarint(write, value, unused_deterministic): + def EncodeSignedVarint(write, value, unused_deterministic=None): if value < 0: value += (1 << 64) bits = value & 0x7f @@ -524,14 +524,14 @@ def _StructPackEncoder(wire_type, format): return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_type) - def EncodeRepeatedField(write, value, unused_deterministic): + def EncodeRepeatedField(write, value, unused_deterministic=None): for element in value: write(tag_bytes) write(local_struct_pack(format, element)) return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_type) - def EncodeField(write, value, unused_deterministic): + def EncodeField(write, value, unused_deterministic=None): write(tag_bytes) return write(local_struct_pack(format, value)) return EncodeField @@ -595,7 +595,7 @@ def _FloatingPointEncoder(wire_type, format): return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_type) - def EncodeRepeatedField(write, value, unused_deterministic): + def EncodeRepeatedField(write, value, unused_deterministic=None): for element in value: write(tag_bytes) try: @@ -605,7 +605,7 @@ def _FloatingPointEncoder(wire_type, format): return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_type) - def EncodeField(write, value, unused_deterministic): + def EncodeField(write, value, unused_deterministic=None): write(tag_bytes) try: write(local_struct_pack(format, value)) @@ -662,7 +662,7 @@ def BoolEncoder(field_number, is_repeated, is_packed): return EncodePackedField elif is_repeated: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT) - def EncodeRepeatedField(write, value, unused_deterministic): + def EncodeRepeatedField(write, value, unused_deterministic=None): for element in value: write(tag_bytes) if element: @@ -672,7 +672,7 @@ def BoolEncoder(field_number, is_repeated, is_packed): return EncodeRepeatedField else: tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_VARINT) - def EncodeField(write, value, unused_deterministic): + def EncodeField(write, value, unused_deterministic=None): write(tag_bytes) if value: return write(true_byte) diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py index 19182b7f73..d891dce12d 100644 --- a/python/google/protobuf/internal/json_format_test.py +++ b/python/google/protobuf/internal/json_format_test.py @@ -983,6 +983,18 @@ class JsonFormatTest(JsonFormatBase): self.assertEqual('{\n"int32Value": 12345\n}', json_format.MessageToJson(message, indent=0)) + def testFormatEnumsAsInts(self): + message = json_format_proto3_pb2.TestMessage() + message.enum_value = json_format_proto3_pb2.BAR + message.repeated_enum_value.append(json_format_proto3_pb2.FOO) + message.repeated_enum_value.append(json_format_proto3_pb2.BAR) + self.assertEqual(json.loads('{\n' + ' "enumValue": 1,\n' + ' "repeatedEnumValue": [0, 1]\n' + '}\n'), + json.loads(json_format.MessageToJson( + message, use_integers_for_enums=True))) + def testParseDict(self): expected = 12345 js_dict = {'int32Value': expected} diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py index 8dae6377ef..61a56a678c 100755 --- a/python/google/protobuf/internal/message_test.py +++ b/python/google/protobuf/internal/message_test.py @@ -99,7 +99,7 @@ def IsNegInf(val): BaseTestCase = testing_refleaks.BaseTestCase -@_parameterized.NamedParameters( +@_parameterized.named_parameters( ('_proto2', unittest_pb2), ('_proto3', unittest_proto3_arena_pb2)) class MessageTest(BaseTestCase): @@ -1694,6 +1694,33 @@ class Proto3Test(BaseTestCase): with self.assertRaises(TypeError): del msg2.map_int32_foreign_message[''] + def testMapMergeFrom(self): + msg = map_unittest_pb2.TestMap() + msg.map_int32_int32[12] = 34 + msg.map_int32_int32[56] = 78 + msg.map_int64_int64[22] = 33 + msg.map_int32_foreign_message[111].c = 5 + msg.map_int32_foreign_message[222].c = 10 + + msg2 = map_unittest_pb2.TestMap() + msg2.map_int32_int32[12] = 55 + msg2.map_int64_int64[88] = 99 + msg2.map_int32_foreign_message[222].c = 15 + msg2.map_int32_foreign_message[222].d = 20 + + msg2.map_int32_int32.MergeFrom(msg.map_int32_int32) + self.assertEqual(34, msg2.map_int32_int32[12]) + self.assertEqual(78, msg2.map_int32_int32[56]) + + msg2.map_int64_int64.MergeFrom(msg.map_int64_int64) + self.assertEqual(33, msg2.map_int64_int64[22]) + self.assertEqual(99, msg2.map_int64_int64[88]) + + msg2.map_int32_foreign_message.MergeFrom(msg.map_int32_foreign_message) + self.assertEqual(5, msg2.map_int32_foreign_message[111].c) + self.assertEqual(10, msg2.map_int32_foreign_message[222].c) + self.assertFalse(msg2.map_int32_foreign_message[222].HasField('d')) + def testMergeFromBadType(self): msg = map_unittest_pb2.TestMap() with self.assertRaisesRegexp( diff --git a/python/google/protobuf/internal/no_package.proto b/python/google/protobuf/internal/no_package.proto new file mode 100644 index 0000000000..f6d2673536 --- /dev/null +++ b/python/google/protobuf/internal/no_package.proto @@ -0,0 +1,12 @@ +syntax = "proto2"; + +option py_api_version = 2; + +enum NoPackageEnum { + NO_PACKAGE_VALUE_0 = 0; + NO_PACKAGE_VALUE_1 = 1; +} + +message NoPackageMessage { + optional NoPackageEnum no_package_enum = 1; +} \ No newline at end of file diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py index ed3445f281..237a2d50d1 100755 --- a/python/google/protobuf/internal/text_format_test.py +++ b/python/google/protobuf/internal/text_format_test.py @@ -48,6 +48,7 @@ except ImportError: from google.protobuf.internal import _parameterized +from google.protobuf import any_pb2 from google.protobuf import any_test_pb2 from google.protobuf import map_unittest_pb2 from google.protobuf import unittest_mset_pb2 @@ -99,7 +100,7 @@ class TextFormatBase(unittest.TestCase): return text -@_parameterized.Parameters((unittest_pb2), (unittest_proto3_arena_pb2)) +@_parameterized.parameters((unittest_pb2), (unittest_proto3_arena_pb2)) class TextFormatTest(TextFormatBase): def testPrintExotic(self, message_module): @@ -369,6 +370,7 @@ class TextFormatTest(TextFormatBase): def testParseRepeatedScalarShortFormat(self, message_module): message = message_module.TestAllTypes() text = ('repeated_int64: [100, 200];\n' + 'repeated_int64: []\n' 'repeated_int64: 300,\n' 'repeated_string: ["one", "two"];\n') text_format.Parse(text, message) @@ -524,20 +526,68 @@ class OnlyWorksWithProto2RightNowTests(TextFormatBase): def testPrintInIndexOrder(self): message = unittest_pb2.TestFieldOrderings() - message.my_string = '115' + # Fields are listed in index order instead of field number. + message.my_string = 'str' message.my_int = 101 message.my_float = 111 message.optional_nested_message.oo = 0 message.optional_nested_message.bb = 1 + message.Extensions[unittest_pb2.my_extension_string] = 'ext_str0' + # Extensions are listed based on the order of extension number. + # Extension number 12. + message.Extensions[unittest_pb2.TestExtensionOrderings2. + test_ext_orderings2].my_string = 'ext_str2' + # Extension number 13. + message.Extensions[unittest_pb2.TestExtensionOrderings1. + test_ext_orderings1].my_string = 'ext_str1' + # Extension number 14. + message.Extensions[ + unittest_pb2.TestExtensionOrderings2.TestExtensionOrderings3. + test_ext_orderings3].my_string = 'ext_str3' + + # Print in index order. self.CompareToGoldenText( - self.RemoveRedundantZeros(text_format.MessageToString( - message, use_index_order=True)), - 'my_string: \"115\"\nmy_int: 101\nmy_float: 111\n' - 'optional_nested_message {\n oo: 0\n bb: 1\n}\n') + self.RemoveRedundantZeros( + text_format.MessageToString(message, use_index_order=True)), + 'my_string: "str"\n' + 'my_int: 101\n' + 'my_float: 111\n' + 'optional_nested_message {\n' + ' oo: 0\n' + ' bb: 1\n' + '}\n' + '[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {\n' + ' my_string: "ext_str2"\n' + '}\n' + '[protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {\n' + ' my_string: "ext_str1"\n' + '}\n' + '[protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3' + '.test_ext_orderings3] {\n' + ' my_string: "ext_str3"\n' + '}\n' + '[protobuf_unittest.my_extension_string]: "ext_str0"\n') + # By default, print in field number order. self.CompareToGoldenText( self.RemoveRedundantZeros(text_format.MessageToString(message)), - 'my_int: 101\nmy_string: \"115\"\nmy_float: 111\n' - 'optional_nested_message {\n bb: 1\n oo: 0\n}\n') + 'my_int: 101\n' + 'my_string: "str"\n' + '[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {\n' + ' my_string: "ext_str2"\n' + '}\n' + '[protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {\n' + ' my_string: "ext_str1"\n' + '}\n' + '[protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3' + '.test_ext_orderings3] {\n' + ' my_string: "ext_str3"\n' + '}\n' + '[protobuf_unittest.my_extension_string]: "ext_str0"\n' + 'my_float: 111\n' + 'optional_nested_message {\n' + ' bb: 1\n' + ' oo: 0\n' + '}\n') def testMergeLinesGolden(self): opened = self.ReadGolden('text_format_unittest_data_oneof_implemented.txt') @@ -970,15 +1020,26 @@ class Proto2Tests(TextFormatBase): '"protobuf_unittest.optional_int32_extension" extensions.'), text_format.Parse, text, message) - def testParseDuplicateNestedMessageScalars(self): + def testParseDuplicateMessages(self): message = unittest_pb2.TestAllTypes() text = ('optional_nested_message { bb: 1 } ' 'optional_nested_message { bb: 2 }') six.assertRaisesRegex(self, text_format.ParseError, ( - '1:65 : Message type "protobuf_unittest.TestAllTypes.NestedMessage" ' - 'should not have multiple "bb" fields.'), text_format.Parse, text, + '1:59 : Message type "protobuf_unittest.TestAllTypes" ' + 'should not have multiple "optional_nested_message" fields.'), + text_format.Parse, text, message) + def testParseDuplicateExtensionMessages(self): + message = unittest_pb2.TestAllExtensions() + text = ('[protobuf_unittest.optional_nested_message_extension]: {} ' + '[protobuf_unittest.optional_nested_message_extension]: {}') + six.assertRaisesRegex(self, text_format.ParseError, ( + '1:114 : Message type "protobuf_unittest.TestAllExtensions" ' + 'should not have multiple ' + '"protobuf_unittest.optional_nested_message_extension" extensions.'), + text_format.Parse, text, message) + def testParseDuplicateScalars(self): message = unittest_pb2.TestAllTypes() text = ('optional_int32: 42 ' 'optional_int32: 67') @@ -1065,6 +1126,14 @@ class Proto3Tests(unittest.TestCase): ' }\n' '}\n') + def testTopAnyMessage(self): + packed_msg = unittest_pb2.OneString() + msg = any_pb2.Any() + msg.Pack(packed_msg) + text = text_format.MessageToString(msg) + other_msg = text_format.Parse(text, any_pb2.Any()) + self.assertEqual(msg, other_msg) + def testPrintMessageExpandAnyRepeated(self): packed_message = unittest_pb2.OneString() message = any_test_pb2.TestAny() @@ -1489,7 +1558,7 @@ class TokenizerTest(unittest.TestCase): # Tests for pretty printer functionality. -@_parameterized.Parameters((unittest_pb2), (unittest_proto3_arena_pb2)) +@_parameterized.parameters((unittest_pb2), (unittest_proto3_arena_pb2)) class PrettyPrinterTest(TextFormatBase): def testPrettyPrintNoMatch(self, message_module): diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py index 3573770bae..37a65cfab1 100644 --- a/python/google/protobuf/internal/well_known_types.py +++ b/python/google/protobuf/internal/well_known_types.py @@ -375,6 +375,9 @@ def _CheckDurationValid(seconds, nanos): raise Error( 'Duration is not valid: Nanos {0} must be in range ' '[-999999999, 999999999].'.format(nanos)) + if (nanos < 0 and seconds > 0) or (nanos > 0 and seconds < 0): + raise Error( + 'Duration is not valid: Sign mismatch.') def _RoundTowardZero(value, divider): @@ -649,9 +652,10 @@ def _MergeMessage( raise ValueError('Error: Field {0} in message {1} is not a singular ' 'message field and cannot have sub-fields.'.format( name, source_descriptor.full_name)) - _MergeMessage( - child, getattr(source, name), getattr(destination, name), - replace_message, replace_repeated) + if source.HasField(name): + _MergeMessage( + child, getattr(source, name), getattr(destination, name), + replace_message, replace_repeated) continue if field.label == FieldDescriptor.LABEL_REPEATED: if replace_repeated: diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py index 573bc37d6c..965940b261 100644 --- a/python/google/protobuf/internal/well_known_types_test.py +++ b/python/google/protobuf/internal/well_known_types_test.py @@ -345,6 +345,12 @@ class TimeUtilTest(TimeUtilTestBase): r'Duration is not valid\: Nanos 1000000000 must be in range' r' \[-999999999\, 999999999\].', message.ToJsonString) + message.seconds = -1 + message.nanos = 1 + self.assertRaisesRegexp( + well_known_types.Error, + r'Duration is not valid\: Sign mismatch.', + message.ToJsonString) class FieldMaskTest(unittest.TestCase): @@ -599,6 +605,16 @@ class FieldMaskTest(unittest.TestCase): self.assertEqual(1, len(nested_dst.payload.repeated_int32)) self.assertEqual(1234, nested_dst.payload.repeated_int32[0]) + # Test Merge oneof field. + new_msg = unittest_pb2.TestOneof2() + dst = unittest_pb2.TestOneof2() + dst.foo_message.qux_int = 1 + mask = field_mask_pb2.FieldMask() + mask.FromJsonString('fooMessage,fooLazyMessage.quxInt') + mask.MergeMessage(new_msg, dst) + self.assertTrue(dst.HasField('foo_message')) + self.assertFalse(dst.HasField('foo_lazy_message')) + def testMergeErrors(self): src = unittest_pb2.TestAllTypes() dst = unittest_pb2.TestAllTypes() diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py index 878291db6d..8d338d3e00 100644 --- a/python/google/protobuf/json_format.py +++ b/python/google/protobuf/json_format.py @@ -42,21 +42,28 @@ Simple usage example: __author__ = 'jieluo@google.com (Jie Luo)' +# pylint: disable=g-statement-before-imports,g-import-not-at-top try: from collections import OrderedDict except ImportError: - from ordereddict import OrderedDict #PY26 + from ordereddict import OrderedDict # PY26 +# pylint: enable=g-statement-before-imports,g-import-not-at-top + import base64 import json import math + +from operator import methodcaller + import re -import six import sys -from operator import methodcaller +import six + from google.protobuf import descriptor from google.protobuf import symbol_database + _TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S' _INT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT32, descriptor.FieldDescriptor.CPPTYPE_UINT32, @@ -93,7 +100,8 @@ def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False, indent=2, - sort_keys=False): + sort_keys=False, + use_integers_for_enums=False): """Converts protobuf message to JSON format. Args: @@ -108,18 +116,21 @@ def MessageToJson(message, indent: The JSON object will be pretty-printed with this indent level. An indent level of 0 or negative will only insert newlines. sort_keys: If True, then the output will be sorted by field names. + use_integers_for_enums: If true, print integers instead of enum names. Returns: A string containing the JSON formatted protocol buffer message. """ printer = _Printer(including_default_value_fields, - preserving_proto_field_name) + preserving_proto_field_name, + use_integers_for_enums) return printer.ToJsonString(message, indent, sort_keys) def MessageToDict(message, including_default_value_fields=False, - preserving_proto_field_name=False): + preserving_proto_field_name=False, + use_integers_for_enums=False): """Converts protobuf message to a dictionary. When the dictionary is encoded to JSON, it conforms to proto3 JSON spec. @@ -133,12 +144,14 @@ def MessageToDict(message, preserving_proto_field_name: If True, use the original proto field names as defined in the .proto file. If False, convert the field names to lowerCamelCase. + use_integers_for_enums: If true, print integers instead of enum names. Returns: A dict representation of the protocol buffer message. """ printer = _Printer(including_default_value_fields, - preserving_proto_field_name) + preserving_proto_field_name, + use_integers_for_enums) # pylint: disable=protected-access return printer._MessageToJsonObject(message) @@ -154,9 +167,11 @@ class _Printer(object): def __init__(self, including_default_value_fields=False, - preserving_proto_field_name=False): + preserving_proto_field_name=False, + use_integers_for_enums=False): self.including_default_value_fields = including_default_value_fields self.preserving_proto_field_name = preserving_proto_field_name + self.use_integers_for_enums = use_integers_for_enums def ToJsonString(self, message, indent, sort_keys): js = self._MessageToJsonObject(message) @@ -247,6 +262,8 @@ class _Printer(object): if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: return self._MessageToJsonObject(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: + if self.use_integers_for_enums: + return value enum_value = field.enum_type.values_by_number.get(value, None) if enum_value is not None: return enum_value.name diff --git a/python/google/protobuf/pyext/descriptor.cc b/python/google/protobuf/pyext/descriptor.cc index 9634ea05ff..bacaaf3136 100644 --- a/python/google/protobuf/pyext/descriptor.cc +++ b/python/google/protobuf/pyext/descriptor.cc @@ -188,38 +188,35 @@ const FileDescriptor* GetFileDescriptor(const MethodDescriptor* descriptor) { // Always returns a new reference. template static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) { - // Options (and their extensions) are completely resolved in the proto file - // containing the descriptor. - PyDescriptorPool* pool = GetDescriptorPool_FromPool( + // Options are cached in the pool that owns the descriptor. + // First search in the cache. + PyDescriptorPool* caching_pool = GetDescriptorPool_FromPool( GetFileDescriptor(descriptor)->pool()); - hash_map* descriptor_options = - pool->descriptor_options; - // First search in the cache. + caching_pool->descriptor_options; if (descriptor_options->find(descriptor) != descriptor_options->end()) { PyObject *value = (*descriptor_options)[descriptor]; Py_INCREF(value); return value; } + // Similar to the C++ implementation, we return an Options object from the + // default (generated) factory, so that client code know that they can use + // extensions from generated files: + // d.GetOptions().Extensions[some_pb2.extension] + // + // The consequence is that extensions not defined in the default pool won't + // be available. If needed, we could add an optional 'message_factory' + // parameter to the GetOptions() function. + PyMessageFactory* message_factory = + GetDefaultDescriptorPool()->py_message_factory; + // Build the Options object: get its Python class, and make a copy of the C++ // read-only instance. const Message& options(descriptor->options()); const Descriptor *message_type = options.GetDescriptor(); - PyMessageFactory* message_factory = pool->py_message_factory; - CMessageClass* message_class = message_factory::GetMessageClass( + CMessageClass* message_class = message_factory::GetOrCreateMessageClass( message_factory, message_type); - if (message_class == NULL) { - // The Options message was not found in the current DescriptorPool. - // This means that the pool cannot contain any extensions to the Options - // message either, so falling back to the basic pool we can only increase - // the chances of successfully parsing the options. - PyErr_Clear(); - pool = GetDefaultDescriptorPool(); - message_factory = pool->py_message_factory; - message_class = message_factory::GetMessageClass( - message_factory, message_type); - } if (message_class == NULL) { PyErr_Format(PyExc_TypeError, "Could not retrieve class for Options: %s", message_type->full_name().c_str()); @@ -248,7 +245,8 @@ static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) { options.SerializeToString(&serialized); io::CodedInputStream input( reinterpret_cast(serialized.c_str()), serialized.size()); - input.SetExtensionRegistry(pool->pool, message_factory->message_factory); + input.SetExtensionRegistry(message_factory->pool->pool, + message_factory->message_factory); bool success = cmsg->message->MergePartialFromCodedStream(&input); if (!success) { PyErr_Format(PyExc_ValueError, "Error parsing Options message"); @@ -564,6 +562,11 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value, return CheckCalledFromGeneratedFile("_options"); } +static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, + void *closure) { + return CheckCalledFromGeneratedFile("_serialized_options"); +} + static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) { return CopyToPythonProto(_GetDescriptor(self), target); } @@ -623,6 +626,8 @@ static PyGetSetDef Getters[] = { { "is_extendable", (getter)IsExtendable, (setter)NULL}, { "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"}, { "_options", (getter)NULL, (setter)SetOptions, "Options"}, + { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions, + "Serialized Options"}, { "syntax", (getter)GetSyntax, (setter)NULL, "Syntax"}, {NULL} }; @@ -785,7 +790,7 @@ static PyObject* GetDefaultValue(PyBaseDescriptor *self, void *closure) { break; } case FieldDescriptor::CPPTYPE_STRING: { - string value = _GetDescriptor(self)->default_value_string(); + const string& value = _GetDescriptor(self)->default_value_string(); result = ToStringObject(_GetDescriptor(self), value); break; } @@ -897,6 +902,10 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value, return CheckCalledFromGeneratedFile("_options"); } +static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, + void *closure) { + return CheckCalledFromGeneratedFile("_serialized_options"); +} static PyGetSetDef Getters[] = { { "full_name", (getter)GetFullName, NULL, "Full name"}, @@ -926,6 +935,8 @@ static PyGetSetDef Getters[] = { "Containing oneof"}, { "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"}, { "_options", (getter)NULL, (setter)SetOptions, "Options"}, + { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions, + "Serialized Options"}, {NULL} }; @@ -1055,6 +1066,11 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value, return CheckCalledFromGeneratedFile("_options"); } +static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, + void *closure) { + return CheckCalledFromGeneratedFile("_serialized_options"); +} + static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) { return CopyToPythonProto(_GetDescriptor(self), target); } @@ -1079,6 +1095,8 @@ static PyGetSetDef Getters[] = { "Containing type"}, { "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"}, { "_options", (getter)NULL, (setter)SetOptions, "Options"}, + { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions, + "Serialized Options"}, {NULL} }; @@ -1179,6 +1197,10 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value, return CheckCalledFromGeneratedFile("_options"); } +static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, + void *closure) { + return CheckCalledFromGeneratedFile("_serialized_options"); +} static PyGetSetDef Getters[] = { { "name", (getter)GetName, NULL, "name"}, @@ -1188,6 +1210,8 @@ static PyGetSetDef Getters[] = { { "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"}, { "_options", (getter)NULL, (setter)SetOptions, "Options"}, + { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions, + "Serialized Options"}, {NULL} }; @@ -1330,6 +1354,11 @@ static int SetOptions(PyFileDescriptor *self, PyObject *value, return CheckCalledFromGeneratedFile("_options"); } +static int SetSerializedOptions(PyFileDescriptor *self, PyObject *value, + void *closure) { + return CheckCalledFromGeneratedFile("_serialized_options"); +} + static PyObject* GetSyntax(PyFileDescriptor *self, void *closure) { return PyString_InternFromString( FileDescriptor::SyntaxName(_GetDescriptor(self)->syntax())); @@ -1355,6 +1384,8 @@ static PyGetSetDef Getters[] = { { "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"}, { "_options", (getter)NULL, (setter)SetOptions, "Options"}, + { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions, + "Serialized Options"}, { "syntax", (getter)GetSyntax, (setter)NULL, "Syntax"}, {NULL} }; @@ -1500,6 +1531,11 @@ static int SetOptions(PyBaseDescriptor *self, PyObject *value, return CheckCalledFromGeneratedFile("_options"); } +static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, + void *closure) { + return CheckCalledFromGeneratedFile("_serialized_options"); +} + static PyGetSetDef Getters[] = { { "name", (getter)GetName, NULL, "Name"}, { "full_name", (getter)GetFullName, NULL, "Full name"}, @@ -1508,6 +1544,8 @@ static PyGetSetDef Getters[] = { { "containing_type", (getter)GetContainingType, NULL, "Containing type"}, { "has_options", (getter)GetHasOptions, (setter)SetHasOptions, "Has Options"}, { "_options", (getter)NULL, (setter)SetOptions, "Options"}, + { "_serialized_options", (getter)NULL, (setter)SetSerializedOptions, + "Serialized Options"}, { "fields", (getter)GetFields, NULL, "Fields"}, {NULL} }; diff --git a/python/google/protobuf/pyext/descriptor_pool.cc b/python/google/protobuf/pyext/descriptor_pool.cc index 16f4d49d25..95882aeb35 100644 --- a/python/google/protobuf/pyext/descriptor_pool.cc +++ b/python/google/protobuf/pyext/descriptor_pool.cc @@ -149,7 +149,8 @@ static PyObject* New(PyTypeObject* type, PyDescriptorPool_NewWithDatabase(database)); } -static void Dealloc(PyDescriptorPool* self) { +static void Dealloc(PyObject* pself) { + PyDescriptorPool* self = reinterpret_cast(pself); descriptor_pool_map.erase(self->pool); Py_CLEAR(self->py_message_factory); for (hash_map::iterator it = @@ -163,7 +164,7 @@ static void Dealloc(PyDescriptorPool* self) { Py_TYPE(self)->tp_free(reinterpret_cast(self)); } -PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) { +static PyObject* FindMessageByName(PyObject* self, PyObject* arg) { Py_ssize_t name_size; char* name; if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { @@ -171,7 +172,8 @@ PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) { } const Descriptor* message_descriptor = - self->pool->FindMessageTypeByName(string(name, name_size)); + reinterpret_cast(self)->pool->FindMessageTypeByName( + string(name, name_size)); if (message_descriptor == NULL) { PyErr_Format(PyExc_KeyError, "Couldn't find message %.200s", name); @@ -184,7 +186,7 @@ PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) { -PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) { +static PyObject* FindFileByName(PyObject* self, PyObject* arg) { Py_ssize_t name_size; char* name; if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { @@ -192,7 +194,8 @@ PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) { } const FileDescriptor* file_descriptor = - self->pool->FindFileByName(string(name, name_size)); + reinterpret_cast(self)->pool->FindFileByName( + string(name, name_size)); if (file_descriptor == NULL) { PyErr_Format(PyExc_KeyError, "Couldn't find file %.200s", name); return NULL; @@ -218,6 +221,10 @@ PyObject* FindFieldByName(PyDescriptorPool* self, PyObject* arg) { return PyFieldDescriptor_FromDescriptor(field_descriptor); } +static PyObject* FindFieldByNameMethod(PyObject* self, PyObject* arg) { + return FindFieldByName(reinterpret_cast(self), arg); +} + PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) { Py_ssize_t name_size; char* name; @@ -235,6 +242,10 @@ PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) { return PyFieldDescriptor_FromDescriptor(field_descriptor); } +static PyObject* FindExtensionByNameMethod(PyObject* self, PyObject* arg) { + return FindExtensionByName(reinterpret_cast(self), arg); +} + PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) { Py_ssize_t name_size; char* name; @@ -252,6 +263,10 @@ PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) { return PyEnumDescriptor_FromDescriptor(enum_descriptor); } +static PyObject* FindEnumTypeByNameMethod(PyObject* self, PyObject* arg) { + return FindEnumTypeByName(reinterpret_cast(self), arg); +} + PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) { Py_ssize_t name_size; char* name; @@ -269,7 +284,11 @@ PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) { return PyOneofDescriptor_FromDescriptor(oneof_descriptor); } -PyObject* FindServiceByName(PyDescriptorPool* self, PyObject* arg) { +static PyObject* FindOneofByNameMethod(PyObject* self, PyObject* arg) { + return FindOneofByName(reinterpret_cast(self), arg); +} + +static PyObject* FindServiceByName(PyObject* self, PyObject* arg) { Py_ssize_t name_size; char* name; if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { @@ -277,7 +296,8 @@ PyObject* FindServiceByName(PyDescriptorPool* self, PyObject* arg) { } const ServiceDescriptor* service_descriptor = - self->pool->FindServiceByName(string(name, name_size)); + reinterpret_cast(self)->pool->FindServiceByName( + string(name, name_size)); if (service_descriptor == NULL) { PyErr_Format(PyExc_KeyError, "Couldn't find service %.200s", name); return NULL; @@ -286,7 +306,7 @@ PyObject* FindServiceByName(PyDescriptorPool* self, PyObject* arg) { return PyServiceDescriptor_FromDescriptor(service_descriptor); } -PyObject* FindMethodByName(PyDescriptorPool* self, PyObject* arg) { +static PyObject* FindMethodByName(PyObject* self, PyObject* arg) { Py_ssize_t name_size; char* name; if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { @@ -294,7 +314,8 @@ PyObject* FindMethodByName(PyDescriptorPool* self, PyObject* arg) { } const MethodDescriptor* method_descriptor = - self->pool->FindMethodByName(string(name, name_size)); + reinterpret_cast(self)->pool->FindMethodByName( + string(name, name_size)); if (method_descriptor == NULL) { PyErr_Format(PyExc_KeyError, "Couldn't find method %.200s", name); return NULL; @@ -303,7 +324,7 @@ PyObject* FindMethodByName(PyDescriptorPool* self, PyObject* arg) { return PyMethodDescriptor_FromDescriptor(method_descriptor); } -PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) { +static PyObject* FindFileContainingSymbol(PyObject* self, PyObject* arg) { Py_ssize_t name_size; char* name; if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { @@ -311,7 +332,8 @@ PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) { } const FileDescriptor* file_descriptor = - self->pool->FindFileContainingSymbol(string(name, name_size)); + reinterpret_cast(self)->pool->FindFileContainingSymbol( + string(name, name_size)); if (file_descriptor == NULL) { PyErr_Format(PyExc_KeyError, "Couldn't find symbol %.200s", name); return NULL; @@ -320,7 +342,7 @@ PyObject* FindFileContainingSymbol(PyDescriptorPool* self, PyObject* arg) { return PyFileDescriptor_FromDescriptor(file_descriptor); } -PyObject* FindExtensionByNumber(PyDescriptorPool* self, PyObject* args) { +static PyObject* FindExtensionByNumber(PyObject* self, PyObject* args) { PyObject* message_descriptor; int number; if (!PyArg_ParseTuple(args, "Oi", &message_descriptor, &number)) { @@ -333,7 +355,8 @@ PyObject* FindExtensionByNumber(PyDescriptorPool* self, PyObject* args) { } const FieldDescriptor* extension_descriptor = - self->pool->FindExtensionByNumber(descriptor, number); + reinterpret_cast(self)->pool->FindExtensionByNumber( + descriptor, number); if (extension_descriptor == NULL) { PyErr_Format(PyExc_KeyError, "Couldn't find extension %d", number); return NULL; @@ -342,14 +365,15 @@ PyObject* FindExtensionByNumber(PyDescriptorPool* self, PyObject* args) { return PyFieldDescriptor_FromDescriptor(extension_descriptor); } -PyObject* FindAllExtensions(PyDescriptorPool* self, PyObject* arg) { +static PyObject* FindAllExtensions(PyObject* self, PyObject* arg) { const Descriptor* descriptor = PyMessageDescriptor_AsDescriptor(arg); if (descriptor == NULL) { return NULL; } std::vector extensions; - self->pool->FindAllExtensions(descriptor, &extensions); + reinterpret_cast(self)->pool->FindAllExtensions( + descriptor, &extensions); ScopedPyObjectPtr result(PyList_New(extensions.size())); if (result == NULL) { @@ -374,14 +398,15 @@ PyObject* FindAllExtensions(PyDescriptorPool* self, PyObject* arg) { // call a function that will just be a no-op? // TODO(amauryfa): Need to investigate further. -PyObject* AddFileDescriptor(PyDescriptorPool* self, PyObject* descriptor) { +static PyObject* AddFileDescriptor(PyObject* self, PyObject* descriptor) { const FileDescriptor* file_descriptor = PyFileDescriptor_AsDescriptor(descriptor); if (!file_descriptor) { return NULL; } if (file_descriptor != - self->pool->FindFileByName(file_descriptor->name())) { + reinterpret_cast(self)->pool->FindFileByName( + file_descriptor->name())) { PyErr_Format(PyExc_ValueError, "The file descriptor %s does not belong to this pool", file_descriptor->name().c_str()); @@ -390,14 +415,15 @@ PyObject* AddFileDescriptor(PyDescriptorPool* self, PyObject* descriptor) { Py_RETURN_NONE; } -PyObject* AddDescriptor(PyDescriptorPool* self, PyObject* descriptor) { +static PyObject* AddDescriptor(PyObject* self, PyObject* descriptor) { const Descriptor* message_descriptor = PyMessageDescriptor_AsDescriptor(descriptor); if (!message_descriptor) { return NULL; } if (message_descriptor != - self->pool->FindMessageTypeByName(message_descriptor->full_name())) { + reinterpret_cast(self)->pool->FindMessageTypeByName( + message_descriptor->full_name())) { PyErr_Format(PyExc_ValueError, "The message descriptor %s does not belong to this pool", message_descriptor->full_name().c_str()); @@ -406,14 +432,15 @@ PyObject* AddDescriptor(PyDescriptorPool* self, PyObject* descriptor) { Py_RETURN_NONE; } -PyObject* AddEnumDescriptor(PyDescriptorPool* self, PyObject* descriptor) { +static PyObject* AddEnumDescriptor(PyObject* self, PyObject* descriptor) { const EnumDescriptor* enum_descriptor = PyEnumDescriptor_AsDescriptor(descriptor); if (!enum_descriptor) { return NULL; } if (enum_descriptor != - self->pool->FindEnumTypeByName(enum_descriptor->full_name())) { + reinterpret_cast(self)->pool->FindEnumTypeByName( + enum_descriptor->full_name())) { PyErr_Format(PyExc_ValueError, "The enum descriptor %s does not belong to this pool", enum_descriptor->full_name().c_str()); @@ -422,14 +449,15 @@ PyObject* AddEnumDescriptor(PyDescriptorPool* self, PyObject* descriptor) { Py_RETURN_NONE; } -PyObject* AddExtensionDescriptor(PyDescriptorPool* self, PyObject* descriptor) { +static PyObject* AddExtensionDescriptor(PyObject* self, PyObject* descriptor) { const FieldDescriptor* extension_descriptor = PyFieldDescriptor_AsDescriptor(descriptor); if (!extension_descriptor) { return NULL; } if (extension_descriptor != - self->pool->FindExtensionByName(extension_descriptor->full_name())) { + reinterpret_cast(self)->pool->FindExtensionByName( + extension_descriptor->full_name())) { PyErr_Format(PyExc_ValueError, "The extension descriptor %s does not belong to this pool", extension_descriptor->full_name().c_str()); @@ -438,14 +466,15 @@ PyObject* AddExtensionDescriptor(PyDescriptorPool* self, PyObject* descriptor) { Py_RETURN_NONE; } -PyObject* AddServiceDescriptor(PyDescriptorPool* self, PyObject* descriptor) { +static PyObject* AddServiceDescriptor(PyObject* self, PyObject* descriptor) { const ServiceDescriptor* service_descriptor = PyServiceDescriptor_AsDescriptor(descriptor); if (!service_descriptor) { return NULL; } if (service_descriptor != - self->pool->FindServiceByName(service_descriptor->full_name())) { + reinterpret_cast(self)->pool->FindServiceByName( + service_descriptor->full_name())) { PyErr_Format(PyExc_ValueError, "The service descriptor %s does not belong to this pool", service_descriptor->full_name().c_str()); @@ -481,7 +510,8 @@ class BuildFileErrorCollector : public DescriptorPool::ErrorCollector { bool had_errors; }; -PyObject* AddSerializedFile(PyDescriptorPool* self, PyObject* serialized_pb) { +static PyObject* AddSerializedFile(PyObject* pself, PyObject* serialized_pb) { + PyDescriptorPool* self = reinterpret_cast(pself); char* message_type; Py_ssize_t message_len; @@ -529,7 +559,7 @@ PyObject* AddSerializedFile(PyDescriptorPool* self, PyObject* serialized_pb) { descriptor, serialized_pb); } -PyObject* Add(PyDescriptorPool* self, PyObject* file_descriptor_proto) { +static PyObject* Add(PyObject* self, PyObject* file_descriptor_proto) { ScopedPyObjectPtr serialized_pb( PyObject_CallMethod(file_descriptor_proto, "SerializeToString", NULL)); if (serialized_pb == NULL) { @@ -539,46 +569,46 @@ PyObject* Add(PyDescriptorPool* self, PyObject* file_descriptor_proto) { } static PyMethodDef Methods[] = { - { "Add", (PyCFunction)Add, METH_O, + { "Add", Add, METH_O, "Adds the FileDescriptorProto and its types to this pool." }, - { "AddSerializedFile", (PyCFunction)AddSerializedFile, METH_O, + { "AddSerializedFile", AddSerializedFile, METH_O, "Adds a serialized FileDescriptorProto to this pool." }, // TODO(amauryfa): Understand why the Python implementation differs from // this one, ask users to use another API and deprecate these functions. - { "AddFileDescriptor", (PyCFunction)AddFileDescriptor, METH_O, + { "AddFileDescriptor", AddFileDescriptor, METH_O, "No-op. Add() must have been called before." }, - { "AddDescriptor", (PyCFunction)AddDescriptor, METH_O, + { "AddDescriptor", AddDescriptor, METH_O, "No-op. Add() must have been called before." }, - { "AddEnumDescriptor", (PyCFunction)AddEnumDescriptor, METH_O, + { "AddEnumDescriptor", AddEnumDescriptor, METH_O, "No-op. Add() must have been called before." }, - { "AddExtensionDescriptor", (PyCFunction)AddExtensionDescriptor, METH_O, + { "AddExtensionDescriptor", AddExtensionDescriptor, METH_O, "No-op. Add() must have been called before." }, - { "AddServiceDescriptor", (PyCFunction)AddServiceDescriptor, METH_O, + { "AddServiceDescriptor", AddServiceDescriptor, METH_O, "No-op. Add() must have been called before." }, - { "FindFileByName", (PyCFunction)FindFileByName, METH_O, + { "FindFileByName", FindFileByName, METH_O, "Searches for a file descriptor by its .proto name." }, - { "FindMessageTypeByName", (PyCFunction)FindMessageByName, METH_O, + { "FindMessageTypeByName", FindMessageByName, METH_O, "Searches for a message descriptor by full name." }, - { "FindFieldByName", (PyCFunction)FindFieldByName, METH_O, + { "FindFieldByName", FindFieldByNameMethod, METH_O, "Searches for a field descriptor by full name." }, - { "FindExtensionByName", (PyCFunction)FindExtensionByName, METH_O, + { "FindExtensionByName", FindExtensionByNameMethod, METH_O, "Searches for extension descriptor by full name." }, - { "FindEnumTypeByName", (PyCFunction)FindEnumTypeByName, METH_O, + { "FindEnumTypeByName", FindEnumTypeByNameMethod, METH_O, "Searches for enum type descriptor by full name." }, - { "FindOneofByName", (PyCFunction)FindOneofByName, METH_O, + { "FindOneofByName", FindOneofByNameMethod, METH_O, "Searches for oneof descriptor by full name." }, - { "FindServiceByName", (PyCFunction)FindServiceByName, METH_O, + { "FindServiceByName", FindServiceByName, METH_O, "Searches for service descriptor by full name." }, - { "FindMethodByName", (PyCFunction)FindMethodByName, METH_O, + { "FindMethodByName", FindMethodByName, METH_O, "Searches for method descriptor by full name." }, - { "FindFileContainingSymbol", (PyCFunction)FindFileContainingSymbol, METH_O, + { "FindFileContainingSymbol", FindFileContainingSymbol, METH_O, "Gets the FileDescriptor containing the specified symbol." }, - { "FindExtensionByNumber", (PyCFunction)FindExtensionByNumber, METH_VARARGS, + { "FindExtensionByNumber", FindExtensionByNumber, METH_VARARGS, "Gets the extension descriptor for the given number." }, - { "FindAllExtensions", (PyCFunction)FindAllExtensions, METH_O, + { "FindAllExtensions", FindAllExtensions, METH_O, "Gets all known extensions of the given message descriptor." }, {NULL} }; @@ -590,7 +620,7 @@ PyTypeObject PyDescriptorPool_Type = { FULL_MODULE_NAME ".DescriptorPool", // tp_name sizeof(PyDescriptorPool), // tp_basicsize 0, // tp_itemsize - (destructor)cdescriptor_pool::Dealloc, // tp_dealloc + cdescriptor_pool::Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/google/protobuf/pyext/extension_dict.cc b/python/google/protobuf/pyext/extension_dict.cc index 6830b10d4f..018b5c2c49 100644 --- a/python/google/protobuf/pyext/extension_dict.cc +++ b/python/google/protobuf/pyext/extension_dict.cc @@ -33,9 +33,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include diff --git a/python/google/protobuf/pyext/extension_dict.h b/python/google/protobuf/pyext/extension_dict.h index 65b878625a..0de2c4ee85 100644 --- a/python/google/protobuf/pyext/extension_dict.h +++ b/python/google/protobuf/pyext/extension_dict.h @@ -37,9 +37,8 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif + +#include namespace google { namespace protobuf { @@ -47,16 +46,8 @@ namespace protobuf { class Message; class FieldDescriptor; -#ifdef _SHARED_PTR_H -using std::shared_ptr; -#else -using internal::shared_ptr; -#endif - namespace python { -struct CMessage; - typedef struct ExtensionDict { PyObject_HEAD; @@ -64,7 +55,7 @@ typedef struct ExtensionDict { // proto tree. Every Python container class holds a // reference to it in order to keep it alive as long as there's a // Python object that references any part of the tree. - shared_ptr owner; + CMessage::OwnerRef owner; // Weak reference to parent message. Used to make sure // the parent is writable when an extension field is modified. diff --git a/python/google/protobuf/pyext/map_container.cc b/python/google/protobuf/pyext/map_container.cc index abd15b778b..6d7ee285b2 100644 --- a/python/google/protobuf/pyext/map_container.cc +++ b/python/google/protobuf/pyext/map_container.cc @@ -33,9 +33,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -76,7 +73,7 @@ class MapReflectionFriend { struct MapIterator { PyObject_HEAD; - google::protobuf::scoped_ptr< ::google::protobuf::MapIterator> iter; + std::unique_ptr<::google::protobuf::MapIterator> iter; // A pointer back to the container, so we can notice changes to the version. // We own a ref on this. @@ -94,7 +91,7 @@ struct MapIterator { // as this iterator does. This is solely for the benefit of the MapIterator // destructor -- we should never actually access the iterator in this state // except to delete it. - shared_ptr owner; + CMessage::OwnerRef owner; // The version of the map when we took the iterator to it. // @@ -339,6 +336,24 @@ PyObject* GetEntryClass(PyObject* _self) { return reinterpret_cast(message_class); } +PyObject* MergeFrom(PyObject* _self, PyObject* arg) { + MapContainer* self = GetMap(_self); + MapContainer* other_map = GetMap(arg); + Message* message = self->GetMutableMessage(); + const Message* other_message = other_map->message; + const Reflection* reflection = message->GetReflection(); + const Reflection* other_reflection = other_message->GetReflection(); + int count = other_reflection->FieldSize( + *other_message, other_map->parent_field_descriptor); + for (int i = 0 ; i < count; i ++) { + reflection->AddMessage(message, self->parent_field_descriptor)->MergeFrom( + other_reflection->GetRepeatedMessage( + *other_message, other_map->parent_field_descriptor, i)); + } + self->version++; + Py_RETURN_NONE; +} + PyObject* MapReflectionFriend::Contains(PyObject* _self, PyObject* key) { MapContainer* self = GetMap(_self); @@ -535,6 +550,8 @@ static PyMethodDef ScalarMapMethods[] = { "Gets the value for the given key if present, or otherwise a default" }, { "GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS, "Return the class used to build Entries of (key, value) pairs." }, + { "MergeFrom", (PyCFunction)MergeFrom, METH_O, + "Merges a map into the current map." }, /* { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS, "Makes a deep copy of the class." }, @@ -810,6 +827,8 @@ static PyMethodDef MessageMapMethods[] = { "Alias for getitem, useful to make explicit that the map is mutated." }, { "GetEntryClass", (PyCFunction)GetEntryClass, METH_NOARGS, "Return the class used to build Entries of (key, value) pairs." }, + { "MergeFrom", (PyCFunction)MergeFrom, METH_O, + "Merges a map into the current map." }, /* { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS, "Makes a deep copy of the class." }, diff --git a/python/google/protobuf/pyext/map_container.h b/python/google/protobuf/pyext/map_container.h index 615657b03b..111fafbf3f 100644 --- a/python/google/protobuf/pyext/map_container.h +++ b/python/google/protobuf/pyext/map_container.h @@ -34,27 +34,18 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include +#include namespace google { namespace protobuf { class Message; -#ifdef _SHARED_PTR_H -using std::shared_ptr; -#else -using internal::shared_ptr; -#endif - namespace python { -struct CMessage; struct CMessageClass; // This struct is used directly for ScalarMap, and is the base class of @@ -66,7 +57,7 @@ struct MapContainer { // proto tree. Every Python MapContainer holds a // reference to it in order to keep it alive as long as there's a // Python object that references any part of the tree. - shared_ptr owner; + CMessage::OwnerRef owner; // Pointer to the C++ Message that contains this container. The // MapContainer does not own this pointer. @@ -99,9 +90,7 @@ struct MapContainer { int Release(); // Set the owner field of self and any children of self. - void SetOwner(const shared_ptr& new_owner) { - owner = new_owner; - } + void SetOwner(const CMessage::OwnerRef& new_owner) { owner = new_owner; } }; struct MessageMapContainer : public MapContainer { diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc index f515b560ec..5893533adf 100644 --- a/python/google/protobuf/pyext/message.cc +++ b/python/google/protobuf/pyext/message.cc @@ -35,9 +35,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include // A Python header file. @@ -658,7 +655,7 @@ bool CheckAndGetInteger(PyObject* arg, T* value) { // Unlike PyLong_AsLongLong, PyLong_AsUnsignedLongLong is very // picky about the exact type. PyObject* casted = PyNumber_Long(arg); - if (GOOGLE_PREDICT_FALSE(casted == NULL)) { + if (GOOGLE_PREDICT_FALSE(casted == nullptr)) { // Propagate existing error. return false; } @@ -683,7 +680,7 @@ bool CheckAndGetInteger(PyObject* arg, T* value) { // Valid subclasses of numbers.Integral should have a __long__() method // so fall back to that. PyObject* casted = PyNumber_Long(arg); - if (GOOGLE_PREDICT_FALSE(casted == NULL)) { + if (GOOGLE_PREDICT_FALSE(casted == nullptr)) { // Propagate existing error. return false; } @@ -830,7 +827,8 @@ bool CheckAndSetString( return true; } -PyObject* ToStringObject(const FieldDescriptor* descriptor, string value) { +PyObject* ToStringObject(const FieldDescriptor* descriptor, + const string& value) { if (descriptor->type() != FieldDescriptor::TYPE_STRING) { return PyBytes_FromStringAndSize(value.c_str(), value.length()); } @@ -1318,6 +1316,8 @@ CMessage* NewEmptyMessage(CMessageClass* type) { return NULL; } + // Use "placement new" syntax to initialize the C++ object. + new (&self->owner) CMessage::OwnerRef(NULL); self->message = NULL; self->parent = NULL; self->parent_field_descriptor = NULL; @@ -1414,7 +1414,7 @@ static void Dealloc(CMessage* self) { Py_CLEAR(self->extensions); Py_CLEAR(self->composite_fields); - self->owner.reset(); + self->owner.~ThreadUnsafeSharedPtr(); Py_TYPE(self)->tp_free(reinterpret_cast(self)); } @@ -1616,9 +1616,10 @@ PyObject* HasExtension(CMessage* self, PyObject* extension) { // * Clear the weak references from the released container to the // parent. -struct SetOwnerVisitor : public ChildVisitor { +class SetOwnerVisitor : public ChildVisitor { + public: // new_owner must outlive this object. - explicit SetOwnerVisitor(const shared_ptr& new_owner) + explicit SetOwnerVisitor(const CMessage::OwnerRef& new_owner) : new_owner_(new_owner) {} int VisitRepeatedCompositeContainer(RepeatedCompositeContainer* container) { @@ -1642,11 +1643,11 @@ struct SetOwnerVisitor : public ChildVisitor { } private: - const shared_ptr& new_owner_; + const CMessage::OwnerRef& new_owner_; }; // Change the owner of this CMessage and all its children, recursively. -int SetOwner(CMessage* self, const shared_ptr& new_owner) { +int SetOwner(CMessage* self, const CMessage::OwnerRef& new_owner) { self->owner = new_owner; if (ForEachCompositeField(self, SetOwnerVisitor(new_owner)) == -1) return -1; @@ -1679,7 +1680,7 @@ int ReleaseSubMessage(CMessage* self, const FieldDescriptor* field_descriptor, CMessage* child_cmessage) { // Release the Message - shared_ptr released_message(ReleaseMessage( + CMessage::OwnerRef released_message(ReleaseMessage( self, child_cmessage->message->GetDescriptor(), field_descriptor)); child_cmessage->message = released_message.get(); child_cmessage->owner.swap(released_message); @@ -2329,7 +2330,9 @@ PyObject* InternalGetScalar(const Message* message, break; } case FieldDescriptor::CPPTYPE_STRING: { - string value = reflection->GetString(*message, field_descriptor); + string scratch; + const string& value = + reflection->GetStringReference(*message, field_descriptor, &scratch); result = ToStringObject(field_descriptor, value); break; } diff --git a/python/google/protobuf/pyext/message.h b/python/google/protobuf/pyext/message.h index 576d098cf7..7050f87618 100644 --- a/python/google/protobuf/pyext/message.h +++ b/python/google/protobuf/pyext/message.h @@ -37,11 +37,11 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include +#include +#include + namespace google { namespace protobuf { @@ -71,7 +71,9 @@ typedef struct CMessage { // proto tree. Every Python CMessage holds a reference to it in // order to keep it alive as long as there's a Python object that // references any part of the tree. - shared_ptr owner; + + typedef ThreadUnsafeSharedPtr OwnerRef; + OwnerRef owner; // Weak reference to a parent CMessage object. This is NULL for any top-level // message and is set for any child message (i.e. a child submessage or a @@ -255,7 +257,7 @@ PyObject* FindInitializationErrors(CMessage* self); // Set the owner field of self and any children of self, recursively. // Used when self is being released and thus has a new owner (the // released Message.) -int SetOwner(CMessage* self, const shared_ptr& new_owner); +int SetOwner(CMessage* self, const CMessage::OwnerRef& new_owner); int AssureWritable(CMessage* self); @@ -336,7 +338,8 @@ bool CheckAndSetString( const Reflection* reflection, bool append, int index); -PyObject* ToStringObject(const FieldDescriptor* descriptor, string value); +PyObject* ToStringObject(const FieldDescriptor* descriptor, + const string& value); // Check if the passed field descriptor belongs to the given message. // If not, return false and set a Python exception (a KeyError) @@ -347,6 +350,15 @@ extern PyObject* PickleError_class; bool InitProto2MessageModule(PyObject *m); +#if LANG_CXX11 +// These are referenced by repeated_scalar_container, and must +// be explicitly instantiated. +extern template bool CheckAndGetInteger(PyObject*, int32*); +extern template bool CheckAndGetInteger(PyObject*, int64*); +extern template bool CheckAndGetInteger(PyObject*, uint32*); +extern template bool CheckAndGetInteger(PyObject*, uint64*); +#endif + } // namespace python } // namespace protobuf diff --git a/python/google/protobuf/pyext/message_factory.cc b/python/google/protobuf/pyext/message_factory.cc index 571bae2be4..bacc76a69f 100644 --- a/python/google/protobuf/pyext/message_factory.cc +++ b/python/google/protobuf/pyext/message_factory.cc @@ -100,7 +100,9 @@ PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) { NewMessageFactory(type, reinterpret_cast(pool))); } -static void Dealloc(PyMessageFactory* self) { +static void Dealloc(PyObject* pself) { + PyMessageFactory* self = reinterpret_cast(pself); + // TODO(amauryfa): When the MessageFactory is not created from the // DescriptorPool this reference should be owned, not borrowed. // Py_CLEAR(self->pool); @@ -111,7 +113,7 @@ static void Dealloc(PyMessageFactory* self) { } delete self->classes_by_descriptor; delete self->message_factory; - Py_TYPE(self)->tp_free(reinterpret_cast(self)); + Py_TYPE(self)->tp_free(pself); } // Add a message class to our database. @@ -231,7 +233,7 @@ PyTypeObject PyMessageFactory_Type = { ".MessageFactory", // tp_name sizeof(PyMessageFactory), // tp_basicsize 0, // tp_itemsize - (destructor)message_factory::Dealloc, // tp_dealloc + message_factory::Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr diff --git a/python/google/protobuf/pyext/repeated_composite_container.cc b/python/google/protobuf/pyext/repeated_composite_container.cc index 5ad71db598..5874d5de8b 100644 --- a/python/google/protobuf/pyext/repeated_composite_container.cc +++ b/python/google/protobuf/pyext/repeated_composite_container.cc @@ -34,9 +34,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -81,7 +78,10 @@ namespace repeated_composite_container { // --------------------------------------------------------------------- // len() -static Py_ssize_t Length(RepeatedCompositeContainer* self) { +static Py_ssize_t Length(PyObject* pself) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + Message* message = self->message; if (message != NULL) { return message->GetReflection()->FieldSize(*message, @@ -102,7 +102,7 @@ static int UpdateChildMessages(RepeatedCompositeContainer* self) { // A MergeFrom on a parent message could have caused extra messages to be // added in the underlying protobuf so add them to our list. They can never // be removed in such a way so there's no need to worry about that. - Py_ssize_t message_length = Length(self); + Py_ssize_t message_length = Length(reinterpret_cast(self)); Py_ssize_t child_length = PyList_GET_SIZE(self->child_messages); Message* message = self->message; const Reflection* reflection = message->GetReflection(); @@ -191,6 +191,10 @@ PyObject* Add(RepeatedCompositeContainer* self, return AddToAttached(self, args, kwargs); } +static PyObject* AddMethod(PyObject* self, PyObject* args, PyObject* kwargs) { + return Add(reinterpret_cast(self), args, kwargs); +} + // --------------------------------------------------------------------- // extend() @@ -226,6 +230,10 @@ PyObject* Extend(RepeatedCompositeContainer* self, PyObject* value) { Py_RETURN_NONE; } +static PyObject* ExtendMethod(PyObject* self, PyObject* value) { + return Extend(reinterpret_cast(self), value); +} + PyObject* MergeFrom(RepeatedCompositeContainer* self, PyObject* other) { if (UpdateChildMessages(self) < 0) { return NULL; @@ -233,6 +241,10 @@ PyObject* MergeFrom(RepeatedCompositeContainer* self, PyObject* other) { return Extend(self, other); } +static PyObject* MergeFromMethod(PyObject* self, PyObject* other) { + return MergeFrom(reinterpret_cast(self), other); +} + PyObject* Subscript(RepeatedCompositeContainer* self, PyObject* slice) { if (UpdateChildMessages(self) < 0) { return NULL; @@ -242,6 +254,10 @@ PyObject* Subscript(RepeatedCompositeContainer* self, PyObject* slice) { return PyObject_GetItem(self->child_messages, slice); } +static PyObject* SubscriptMethod(PyObject* self, PyObject* slice) { + return Subscript(reinterpret_cast(self), slice); +} + int AssignSubscript(RepeatedCompositeContainer* self, PyObject* slice, PyObject* value) { @@ -265,7 +281,7 @@ int AssignSubscript(RepeatedCompositeContainer* self, Py_ssize_t from; Py_ssize_t to; Py_ssize_t step; - Py_ssize_t length = Length(self); + Py_ssize_t length = Length(reinterpret_cast(self)); Py_ssize_t slicelength; if (PySlice_Check(slice)) { #if PY_MAJOR_VERSION >= 3 @@ -290,7 +306,16 @@ int AssignSubscript(RepeatedCompositeContainer* self, return 0; } -static PyObject* Remove(RepeatedCompositeContainer* self, PyObject* value) { +static int AssignSubscriptMethod(PyObject* self, PyObject* slice, + PyObject* value) { + return AssignSubscript(reinterpret_cast(self), + slice, value); +} + +static PyObject* Remove(PyObject* pself, PyObject* value) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + if (UpdateChildMessages(self) < 0) { return NULL; } @@ -305,9 +330,10 @@ static PyObject* Remove(RepeatedCompositeContainer* self, PyObject* value) { Py_RETURN_NONE; } -static PyObject* RichCompare(RepeatedCompositeContainer* self, - PyObject* other, - int opid) { +static PyObject* RichCompare(PyObject* pself, PyObject* other, int opid) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + if (UpdateChildMessages(self) < 0) { return NULL; } @@ -340,12 +366,13 @@ static PyObject* RichCompare(RepeatedCompositeContainer* self, } } -static PyObject* ToStr(RepeatedCompositeContainer* self) { +static PyObject* ToStr(PyObject* pself) { ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL)); if (full_slice == NULL) { return NULL; } - ScopedPyObjectPtr list(Subscript(self, full_slice.get())); + ScopedPyObjectPtr list(Subscript( + reinterpret_cast(pself), full_slice.get())); if (list == NULL) { return NULL; } @@ -359,7 +386,7 @@ static void ReorderAttached(RepeatedCompositeContainer* self) { Message* message = self->message; const Reflection* reflection = message->GetReflection(); const FieldDescriptor* descriptor = self->parent_field_descriptor; - const Py_ssize_t length = Length(self); + const Py_ssize_t length = Length(reinterpret_cast(self)); // Since Python protobuf objects are never arena-allocated, adding and // removing message pointers to the underlying array is just updating @@ -390,9 +417,10 @@ static int SortPythonMessages(RepeatedCompositeContainer* self, return 0; } -static PyObject* Sort(RepeatedCompositeContainer* self, - PyObject* args, - PyObject* kwds) { +static PyObject* Sort(PyObject* pself, PyObject* args, PyObject* kwds) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + // Support the old sort_function argument for backwards // compatibility. if (kwds != NULL) { @@ -416,11 +444,14 @@ static PyObject* Sort(RepeatedCompositeContainer* self, // --------------------------------------------------------------------- -static PyObject* Item(RepeatedCompositeContainer* self, Py_ssize_t index) { +static PyObject* Item(PyObject* pself, Py_ssize_t index) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + if (UpdateChildMessages(self) < 0) { return NULL; } - Py_ssize_t length = Length(self); + Py_ssize_t length = Length(pself); if (index < 0) { index = length + index; } @@ -432,17 +463,17 @@ static PyObject* Item(RepeatedCompositeContainer* self, Py_ssize_t index) { return item; } -static PyObject* Pop(RepeatedCompositeContainer* self, - PyObject* args) { +static PyObject* Pop(PyObject* pself, PyObject* args) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + Py_ssize_t index = -1; if (!PyArg_ParseTuple(args, "|n", &index)) { return NULL; } - PyObject* item = Item(self, index); + PyObject* item = Item(pself, index); if (item == NULL) { - PyErr_Format(PyExc_IndexError, - "list index (%zd) out of range", - index); + PyErr_Format(PyExc_IndexError, "list index (%zd) out of range", index); return NULL; } ScopedPyObjectPtr py_index(PyLong_FromSsize_t(index)); @@ -460,7 +491,7 @@ void ReleaseLastTo(CMessage* parent, GOOGLE_CHECK_NOTNULL(field); GOOGLE_CHECK_NOTNULL(target); - shared_ptr released_message( + CMessage::OwnerRef released_message( parent->message->GetReflection()->ReleaseLast(parent->message, field)); // TODO(tibell): Deal with proto1. @@ -503,7 +534,10 @@ int Release(RepeatedCompositeContainer* self) { return 0; } -PyObject* DeepCopy(RepeatedCompositeContainer* self, PyObject* arg) { +PyObject* DeepCopy(PyObject* pself, PyObject* arg) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + ScopedPyObjectPtr cloneObj( PyType_GenericAlloc(&RepeatedCompositeContainer_Type, 0)); if (cloneObj == NULL) { @@ -530,7 +564,7 @@ PyObject* DeepCopy(RepeatedCompositeContainer* self, PyObject* arg) { } int SetOwner(RepeatedCompositeContainer* self, - const shared_ptr& new_owner) { + const CMessage::OwnerRef& new_owner) { GOOGLE_CHECK_ATTACHED(self); self->owner = new_owner; @@ -571,43 +605,46 @@ PyObject *NewContainer( return reinterpret_cast(self); } -static void Dealloc(RepeatedCompositeContainer* self) { +static void Dealloc(PyObject* pself) { + RepeatedCompositeContainer* self = + reinterpret_cast(pself); + Py_CLEAR(self->child_messages); Py_CLEAR(self->child_message_class); // TODO(tibell): Do we need to call delete on these objects to make // sure their destructors are called? self->owner.reset(); - Py_TYPE(self)->tp_free(reinterpret_cast(self)); + Py_TYPE(self)->tp_free(pself); } static PySequenceMethods SqMethods = { - (lenfunc)Length, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - (ssizeargfunc)Item /* sq_item */ + Length, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + Item /* sq_item */ }; static PyMappingMethods MpMethods = { - (lenfunc)Length, /* mp_length */ - (binaryfunc)Subscript, /* mp_subscript */ - (objobjargproc)AssignSubscript,/* mp_ass_subscript */ + Length, /* mp_length */ + SubscriptMethod, /* mp_subscript */ + AssignSubscriptMethod, /* mp_ass_subscript */ }; static PyMethodDef Methods[] = { - { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS, + { "__deepcopy__", DeepCopy, METH_VARARGS, "Makes a deep copy of the class." }, - { "add", (PyCFunction) Add, METH_VARARGS | METH_KEYWORDS, + { "add", (PyCFunction)AddMethod, METH_VARARGS | METH_KEYWORDS, "Adds an object to the repeated container." }, - { "extend", (PyCFunction) Extend, METH_O, + { "extend", ExtendMethod, METH_O, "Adds objects to the repeated container." }, - { "pop", (PyCFunction)Pop, METH_VARARGS, + { "pop", Pop, METH_VARARGS, "Removes an object from the repeated container and returns it." }, - { "remove", (PyCFunction) Remove, METH_O, + { "remove", Remove, METH_O, "Removes an object from the repeated container." }, - { "sort", (PyCFunction) Sort, METH_VARARGS | METH_KEYWORDS, + { "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS, "Sorts the repeated container." }, - { "MergeFrom", (PyCFunction) MergeFrom, METH_O, + { "MergeFrom", MergeFromMethod, METH_O, "Adds objects to the repeated container." }, { NULL, NULL } }; @@ -619,12 +656,12 @@ PyTypeObject RepeatedCompositeContainer_Type = { FULL_MODULE_NAME ".RepeatedCompositeContainer", // tp_name sizeof(RepeatedCompositeContainer), // tp_basicsize 0, // tp_itemsize - (destructor)repeated_composite_container::Dealloc, // tp_dealloc + repeated_composite_container::Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare - (reprfunc)repeated_composite_container::ToStr, // tp_repr + repeated_composite_container::ToStr, // tp_repr 0, // tp_as_number &repeated_composite_container::SqMethods, // tp_as_sequence &repeated_composite_container::MpMethods, // tp_as_mapping @@ -638,7 +675,7 @@ PyTypeObject RepeatedCompositeContainer_Type = { "A Repeated scalar container", // tp_doc 0, // tp_traverse 0, // tp_clear - (richcmpfunc)repeated_composite_container::RichCompare, // tp_richcompare + repeated_composite_container::RichCompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext diff --git a/python/google/protobuf/pyext/repeated_composite_container.h b/python/google/protobuf/pyext/repeated_composite_container.h index a7b56b61b3..e5e946aaf0 100644 --- a/python/google/protobuf/pyext/repeated_composite_container.h +++ b/python/google/protobuf/pyext/repeated_composite_container.h @@ -37,27 +37,19 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include +#include + namespace google { namespace protobuf { class FieldDescriptor; class Message; -#ifdef _SHARED_PTR_H -using std::shared_ptr; -#else -using internal::shared_ptr; -#endif - namespace python { -struct CMessage; struct CMessageClass; // A RepeatedCompositeContainer can be in one of two states: attached @@ -77,7 +69,7 @@ typedef struct RepeatedCompositeContainer { // proto tree. Every Python RepeatedCompositeContainer holds a // reference to it in order to keep it alive as long as there's a // Python object that references any part of the tree. - shared_ptr owner; + CMessage::OwnerRef owner; // Weak reference to parent object. May be NULL. Used to make sure // the parent is writable before modifying the @@ -148,11 +140,6 @@ int AssignSubscript(RepeatedCompositeContainer* self, PyObject* slice, PyObject* value); -// Releases the messages in the container to the given message. -// -// Returns 0 on success, -1 on failure. -int ReleaseToMessage(RepeatedCompositeContainer* self, Message* new_message); - // Releases the messages in the container to a new message. // // Returns 0 on success, -1 on failure. @@ -160,7 +147,7 @@ int Release(RepeatedCompositeContainer* self); // Returns 0 on success, -1 on failure. int SetOwner(RepeatedCompositeContainer* self, - const shared_ptr& new_owner); + const CMessage::OwnerRef& new_owner); // Removes the last element of the repeated message field 'field' on // the Message 'parent', and transfers the ownership of the released diff --git a/python/google/protobuf/pyext/repeated_scalar_container.cc b/python/google/protobuf/pyext/repeated_scalar_container.cc index 5a7832cd11..1517e654ee 100644 --- a/python/google/protobuf/pyext/repeated_scalar_container.cc +++ b/python/google/protobuf/pyext/repeated_scalar_container.cc @@ -34,9 +34,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -77,15 +74,18 @@ static int InternalAssignRepeatedField( return 0; } -static Py_ssize_t Len(RepeatedScalarContainer* self) { +static Py_ssize_t Len(PyObject* pself) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); Message* message = self->message; return message->GetReflection()->FieldSize(*message, self->parent_field_descriptor); } -static int AssignItem(RepeatedScalarContainer* self, - Py_ssize_t index, - PyObject* arg) { +static int AssignItem(PyObject* pself, Py_ssize_t index, PyObject* arg) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + cmessage::AssureWritable(self->parent); Message* message = self->message; const FieldDescriptor* field_descriptor = self->parent_field_descriptor; @@ -188,7 +188,10 @@ static int AssignItem(RepeatedScalarContainer* self, return 0; } -static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) { +static PyObject* Item(PyObject* pself, Py_ssize_t index) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + Message* message = self->message; const FieldDescriptor* field_descriptor = self->parent_field_descriptor; const Reflection* reflection = message->GetReflection(); @@ -256,8 +259,9 @@ static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) { break; } case FieldDescriptor::CPPTYPE_STRING: { - string value = reflection->GetRepeatedString( - *message, field_descriptor, index); + string scratch; + const string& value = reflection->GetRepeatedStringReference( + *message, field_descriptor, index, &scratch); result = ToStringObject(field_descriptor, value); break; } @@ -271,7 +275,10 @@ static PyObject* Item(RepeatedScalarContainer* self, Py_ssize_t index) { return result; } -static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) { +static PyObject* Subscript(PyObject* pself, PyObject* slice) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + Py_ssize_t from; Py_ssize_t to; Py_ssize_t step; @@ -286,14 +293,13 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) { if (PyLong_Check(slice)) { from = to = PyLong_AsLong(slice); } else if (PySlice_Check(slice)) { - length = Len(self); + length = Len(pself); #if PY_MAJOR_VERSION >= 3 if (PySlice_GetIndicesEx(slice, length, &from, &to, &step, &slicelength) == -1) { #else if (PySlice_GetIndicesEx(reinterpret_cast(slice), length, &from, &to, &step, &slicelength) == -1) { - #endif return NULL; } @@ -304,7 +310,7 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) { } if (!return_list) { - return Item(self, from); + return Item(pself, from); } PyObject* list = PyList_New(0); @@ -319,7 +325,7 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) { if (index < 0 || index >= length) { break; } - ScopedPyObjectPtr s(Item(self, index)); + ScopedPyObjectPtr s(Item(pself, index)); PyList_Append(list, s.get()); } } else { @@ -330,7 +336,7 @@ static PyObject* Subscript(RepeatedScalarContainer* self, PyObject* slice) { if (index < 0 || index >= length) { break; } - ScopedPyObjectPtr s(Item(self, index)); + ScopedPyObjectPtr s(Item(pself, index)); PyList_Append(list, s.get()); } } @@ -417,9 +423,14 @@ PyObject* Append(RepeatedScalarContainer* self, PyObject* item) { Py_RETURN_NONE; } -static int AssSubscript(RepeatedScalarContainer* self, - PyObject* slice, - PyObject* value) { +static PyObject* AppendMethod(PyObject* self, PyObject* item) { + return Append(reinterpret_cast(self), item); +} + +static int AssSubscript(PyObject* pself, PyObject* slice, PyObject* value) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + Py_ssize_t from; Py_ssize_t to; Py_ssize_t step; @@ -435,7 +446,7 @@ static int AssSubscript(RepeatedScalarContainer* self, #if PY_MAJOR_VERSION < 3 if (PyInt_Check(slice)) { from = to = PyInt_AsLong(slice); - } else + } else // NOLINT #endif if (PyLong_Check(slice)) { from = to = PyLong_AsLong(slice); @@ -463,14 +474,14 @@ static int AssSubscript(RepeatedScalarContainer* self, } if (!create_list) { - return AssignItem(self, from, value); + return AssignItem(pself, from, value); } ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL)); if (full_slice == NULL) { return -1; } - ScopedPyObjectPtr new_list(Subscript(self, full_slice.get())); + ScopedPyObjectPtr new_list(Subscript(pself, full_slice.get())); if (new_list == NULL) { return -1; } @@ -509,14 +520,17 @@ PyObject* Extend(RepeatedScalarContainer* self, PyObject* value) { Py_RETURN_NONE; } -static PyObject* Insert(RepeatedScalarContainer* self, PyObject* args) { +static PyObject* Insert(PyObject* pself, PyObject* args) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + Py_ssize_t index; PyObject* value; if (!PyArg_ParseTuple(args, "lO", &index, &value)) { return NULL; } ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL)); - ScopedPyObjectPtr new_list(Subscript(self, full_slice.get())); + ScopedPyObjectPtr new_list(Subscript(pself, full_slice.get())); if (PyList_Insert(new_list.get(), index, value) < 0) { return NULL; } @@ -527,10 +541,13 @@ static PyObject* Insert(RepeatedScalarContainer* self, PyObject* args) { Py_RETURN_NONE; } -static PyObject* Remove(RepeatedScalarContainer* self, PyObject* value) { +static PyObject* Remove(PyObject* pself, PyObject* value) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + Py_ssize_t match_index = -1; - for (Py_ssize_t i = 0; i < Len(self); ++i) { - ScopedPyObjectPtr elem(Item(self, i)); + for (Py_ssize_t i = 0; i < Len(pself); ++i) { + ScopedPyObjectPtr elem(Item(pself, i)); if (PyObject_RichCompareBool(elem.get(), value, Py_EQ)) { match_index = i; break; @@ -540,15 +557,20 @@ static PyObject* Remove(RepeatedScalarContainer* self, PyObject* value) { PyErr_SetString(PyExc_ValueError, "remove(x): x not in container"); return NULL; } - if (AssignItem(self, match_index, NULL) < 0) { + if (AssignItem(pself, match_index, NULL) < 0) { return NULL; } Py_RETURN_NONE; } -static PyObject* RichCompare(RepeatedScalarContainer* self, - PyObject* other, - int opid) { +static PyObject* ExtendMethod(PyObject* self, PyObject* value) { + return Extend(reinterpret_cast(self), value); +} + +static PyObject* RichCompare(PyObject* pself, PyObject* other, int opid) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + if (opid != Py_EQ && opid != Py_NE) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; @@ -565,28 +587,25 @@ static PyObject* RichCompare(RepeatedScalarContainer* self, ScopedPyObjectPtr other_list_deleter; if (PyObject_TypeCheck(other, &RepeatedScalarContainer_Type)) { - other_list_deleter.reset(Subscript( - reinterpret_cast(other), full_slice.get())); + other_list_deleter.reset(Subscript(other, full_slice.get())); other = other_list_deleter.get(); } - ScopedPyObjectPtr list(Subscript(self, full_slice.get())); + ScopedPyObjectPtr list(Subscript(pself, full_slice.get())); if (list == NULL) { return NULL; } return PyObject_RichCompare(list.get(), other, opid); } -PyObject* Reduce(RepeatedScalarContainer* unused_self) { +PyObject* Reduce(PyObject* unused_self, PyObject* unused_other) { PyErr_Format( PickleError_class, "can't pickle repeated message fields, convert to list first"); return NULL; } -static PyObject* Sort(RepeatedScalarContainer* self, - PyObject* args, - PyObject* kwds) { +static PyObject* Sort(PyObject* pself, PyObject* args, PyObject* kwds) { // Support the old sort_function argument for backwards // compatibility. if (kwds != NULL) { @@ -605,7 +624,7 @@ static PyObject* Sort(RepeatedScalarContainer* self, if (full_slice == NULL) { return NULL; } - ScopedPyObjectPtr list(Subscript(self, full_slice.get())); + ScopedPyObjectPtr list(Subscript(pself, full_slice.get())); if (list == NULL) { return NULL; } @@ -617,38 +636,39 @@ static PyObject* Sort(RepeatedScalarContainer* self, if (res == NULL) { return NULL; } - int ret = InternalAssignRepeatedField(self, list.get()); + int ret = InternalAssignRepeatedField( + reinterpret_cast(pself), list.get()); if (ret < 0) { return NULL; } Py_RETURN_NONE; } -static PyObject* Pop(RepeatedScalarContainer* self, - PyObject* args) { +static PyObject* Pop(PyObject* pself, PyObject* args) { Py_ssize_t index = -1; if (!PyArg_ParseTuple(args, "|n", &index)) { return NULL; } - PyObject* item = Item(self, index); + PyObject* item = Item(pself, index); if (item == NULL) { - PyErr_Format(PyExc_IndexError, - "list index (%zd) out of range", - index); + PyErr_Format(PyExc_IndexError, "list index (%zd) out of range", index); return NULL; } - if (AssignItem(self, index, NULL) < 0) { + if (AssignItem(pself, index, NULL) < 0) { return NULL; } return item; } -static PyObject* ToStr(RepeatedScalarContainer* self) { +static PyObject* ToStr(PyObject* pself) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + ScopedPyObjectPtr full_slice(PySlice_New(NULL, NULL, NULL)); if (full_slice == NULL) { return NULL; } - ScopedPyObjectPtr list(Subscript(self, full_slice.get())); + ScopedPyObjectPtr list(Subscript(pself, full_slice.get())); if (list == NULL) { return NULL; } @@ -687,7 +707,8 @@ static int InitializeAndCopyToParentContainer( if (full_slice == NULL) { return -1; } - ScopedPyObjectPtr values(Subscript(from, full_slice.get())); + ScopedPyObjectPtr values( + Subscript(reinterpret_cast(from), full_slice.get())); if (values == NULL) { return -1; } @@ -706,7 +727,10 @@ int Release(RepeatedScalarContainer* self) { return InitializeAndCopyToParentContainer(self, self); } -PyObject* DeepCopy(RepeatedScalarContainer* self, PyObject* arg) { +PyObject* DeepCopy(PyObject* pself, PyObject* arg) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); + RepeatedScalarContainer* clone = reinterpret_cast( PyType_GenericAlloc(&RepeatedScalarContainer_Type, 0)); if (clone == NULL) { @@ -720,45 +744,47 @@ PyObject* DeepCopy(RepeatedScalarContainer* self, PyObject* arg) { return reinterpret_cast(clone); } -static void Dealloc(RepeatedScalarContainer* self) { +static void Dealloc(PyObject* pself) { + RepeatedScalarContainer* self = + reinterpret_cast(pself); self->owner.reset(); - Py_TYPE(self)->tp_free(reinterpret_cast(self)); + Py_TYPE(self)->tp_free(pself); } void SetOwner(RepeatedScalarContainer* self, - const shared_ptr& new_owner) { + const CMessage::OwnerRef& new_owner) { self->owner = new_owner; } static PySequenceMethods SqMethods = { - (lenfunc)Len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - (ssizeargfunc)Item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)AssignItem /* sq_ass_item */ + Len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + Item, /* sq_item */ + 0, /* sq_slice */ + AssignItem /* sq_ass_item */ }; static PyMappingMethods MpMethods = { - (lenfunc)Len, /* mp_length */ - (binaryfunc)Subscript, /* mp_subscript */ - (objobjargproc)AssSubscript, /* mp_ass_subscript */ + Len, /* mp_length */ + Subscript, /* mp_subscript */ + AssSubscript, /* mp_ass_subscript */ }; static PyMethodDef Methods[] = { - { "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS, + { "__deepcopy__", DeepCopy, METH_VARARGS, "Makes a deep copy of the class." }, - { "__reduce__", (PyCFunction)Reduce, METH_NOARGS, + { "__reduce__", Reduce, METH_NOARGS, "Outputs picklable representation of the repeated field." }, - { "append", (PyCFunction)Append, METH_O, + { "append", AppendMethod, METH_O, "Appends an object to the repeated container." }, - { "extend", (PyCFunction)Extend, METH_O, - "Appends objects to the repeated container." }, - { "insert", (PyCFunction)Insert, METH_VARARGS, + { "extend", ExtendMethod, METH_O, "Appends objects to the repeated container." }, - { "pop", (PyCFunction)Pop, METH_VARARGS, + { "insert", Insert, METH_VARARGS, + "Inserts an object at the specified position in the container." }, + { "pop", Pop, METH_VARARGS, "Removes an object from the repeated container and returns it." }, - { "remove", (PyCFunction)Remove, METH_O, + { "remove", Remove, METH_O, "Removes an object from the repeated container." }, { "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS, "Sorts the repeated container."}, @@ -772,12 +798,12 @@ PyTypeObject RepeatedScalarContainer_Type = { FULL_MODULE_NAME ".RepeatedScalarContainer", // tp_name sizeof(RepeatedScalarContainer), // tp_basicsize 0, // tp_itemsize - (destructor)repeated_scalar_container::Dealloc, // tp_dealloc + repeated_scalar_container::Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare - (reprfunc)repeated_scalar_container::ToStr, // tp_repr + repeated_scalar_container::ToStr, // tp_repr 0, // tp_as_number &repeated_scalar_container::SqMethods, // tp_as_sequence &repeated_scalar_container::MpMethods, // tp_as_mapping @@ -791,7 +817,7 @@ PyTypeObject RepeatedScalarContainer_Type = { "A Repeated scalar container", // tp_doc 0, // tp_traverse 0, // tp_clear - (richcmpfunc)repeated_scalar_container::RichCompare, // tp_richcompare + repeated_scalar_container::RichCompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext diff --git a/python/google/protobuf/pyext/repeated_scalar_container.h b/python/google/protobuf/pyext/repeated_scalar_container.h index 555e621c9b..559dec980b 100644 --- a/python/google/protobuf/pyext/repeated_scalar_container.h +++ b/python/google/protobuf/pyext/repeated_scalar_container.h @@ -37,27 +37,14 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include +#include namespace google { namespace protobuf { - -class Message; - -#ifdef _SHARED_PTR_H -using std::shared_ptr; -#else -using internal::shared_ptr; -#endif - namespace python { -struct CMessage; - typedef struct RepeatedScalarContainer { PyObject_HEAD; @@ -65,7 +52,7 @@ typedef struct RepeatedScalarContainer { // proto tree. Every Python RepeatedScalarContainer holds a // reference to it in order to keep it alive as long as there's a // Python object that references any part of the tree. - shared_ptr owner; + CMessage::OwnerRef owner; // Pointer to the C++ Message that contains this container. The // RepeatedScalarContainer does not own this pointer. @@ -112,7 +99,7 @@ PyObject* Extend(RepeatedScalarContainer* self, PyObject* value); // Set the owner field of self and any children of self. void SetOwner(RepeatedScalarContainer* self, - const shared_ptr& new_owner); + const CMessage::OwnerRef& new_owner); } // namespace repeated_scalar_container } // namespace python diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py index 36ddd1b7c6..2cbd21bc25 100755 --- a/python/google/protobuf/text_format.py +++ b/python/google/protobuf/text_format.py @@ -141,9 +141,11 @@ def MessageToString(message, as_one_line: Don't introduce newlines between fields. pointy_brackets: If True, use angle brackets instead of curly braces for nesting. - use_index_order: If True, print fields of a proto message using the order - defined in source code instead of the field number. By default, use the - field number order. + use_index_order: If True, fields of a proto message will be printed using + the order defined in source code instead of the field number, extensions + will be printed at the end of the message and their relative order is + determined by the extension number. By default, use the field number + order. float_format: If set, use this to specify floating point number formatting (per the "Format Specification Mini-Language"); otherwise, str() is used. use_field_number: If True, print field numbers instead of names. @@ -336,11 +338,12 @@ class _Printer(object): return fields = message.ListFields() if self.use_index_order: - fields.sort(key=lambda x: x[0].index) + fields.sort( + key=lambda x: x[0].number if x[0].is_extension else x[0].index) for field, value in fields: if _IsMapEntry(field): for key in sorted(value): - # This is slow for maps with submessage entires because it copies the + # This is slow for maps with submessage entries because it copies the # entire tree. Unfortunately this would take significant refactoring # of this file to work around. # @@ -645,6 +648,30 @@ class _Parser(object): ParseError: In case of text parsing problems. """ message_descriptor = message.DESCRIPTOR + if (message_descriptor.full_name == _ANY_FULL_TYPE_NAME and + tokenizer.TryConsume('[')): + type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer) + tokenizer.Consume(']') + tokenizer.TryConsume(':') + if tokenizer.TryConsume('<'): + expanded_any_end_token = '>' + else: + tokenizer.Consume('{') + expanded_any_end_token = '}' + expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name, + self.descriptor_pool) + if not expanded_any_sub_message: + raise ParseError('Type %s not found in descriptor pool' % + packed_type_name) + while not tokenizer.TryConsume(expanded_any_end_token): + if tokenizer.AtEnd(): + raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % + (expanded_any_end_token,)) + self._MergeField(tokenizer, expanded_any_sub_message) + message.Pack(expanded_any_sub_message, + type_url_prefix=type_url_prefix) + return + if tokenizer.TryConsume('['): name = [tokenizer.ConsumeIdentifier()] while tokenizer.TryConsume('.'): @@ -725,11 +752,12 @@ class _Parser(object): if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED and tokenizer.TryConsume('[')): # Short repeated format, e.g. "foo: [1, 2, 3]" - while True: - merger(tokenizer, message, field) - if tokenizer.TryConsume(']'): - break - tokenizer.Consume(',') + if not tokenizer.TryConsume(']'): + while True: + merger(tokenizer, message, field) + if tokenizer.TryConsume(']'): + break + tokenizer.Consume(',') else: merger(tokenizer, message, field) @@ -777,33 +805,7 @@ class _Parser(object): tokenizer.Consume('{') end_token = '}' - if (field.message_type.full_name == _ANY_FULL_TYPE_NAME and - tokenizer.TryConsume('[')): - type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer) - tokenizer.Consume(']') - tokenizer.TryConsume(':') - if tokenizer.TryConsume('<'): - expanded_any_end_token = '>' - else: - tokenizer.Consume('{') - expanded_any_end_token = '}' - expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name, - self.descriptor_pool) - if not expanded_any_sub_message: - raise ParseError('Type %s not found in descriptor pool' % - packed_type_name) - while not tokenizer.TryConsume(expanded_any_end_token): - if tokenizer.AtEnd(): - raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % - (expanded_any_end_token,)) - self._MergeField(tokenizer, expanded_any_sub_message) - if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: - any_message = getattr(message, field.name).add() - else: - any_message = getattr(message, field.name) - any_message.Pack(expanded_any_sub_message, - type_url_prefix=type_url_prefix) - elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: if field.is_extension: sub_message = message.Extensions[field].add() elif is_map_entry: @@ -812,8 +814,20 @@ class _Parser(object): sub_message = getattr(message, field.name).add() else: if field.is_extension: + if (not self._allow_multiple_scalars and + message.HasExtension(field)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" extensions.' % + (message.DESCRIPTOR.full_name, field.full_name)) sub_message = message.Extensions[field] else: + # Also apply _allow_multiple_scalars to message field. + # TODO(jieluo): Change to _allow_singular_overwrites. + if (not self._allow_multiple_scalars and + message.HasField(field.name)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" fields.' % + (message.DESCRIPTOR.full_name, field.name)) sub_message = getattr(message, field.name) sub_message.SetInParent() diff --git a/src/Makefile.am b/src/Makefile.am index af2db52f2d..a3e69057fa 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -64,20 +64,6 @@ MAINTAINERCLEANFILES = \ Makefile.in nobase_include_HEADERS = \ - google/protobuf/stubs/atomic_sequence_num.h \ - google/protobuf/stubs/atomicops.h \ - google/protobuf/stubs/atomicops_internals_power.h \ - google/protobuf/stubs/atomicops_internals_ppc_gcc.h \ - google/protobuf/stubs/atomicops_internals_arm64_gcc.h \ - google/protobuf/stubs/atomicops_internals_arm_gcc.h \ - google/protobuf/stubs/atomicops_internals_arm_qnx.h \ - google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h \ - google/protobuf/stubs/atomicops_internals_generic_gcc.h \ - google/protobuf/stubs/atomicops_internals_mips_gcc.h \ - google/protobuf/stubs/atomicops_internals_solaris.h \ - google/protobuf/stubs/atomicops_internals_tsan.h \ - google/protobuf/stubs/atomicops_internals_x86_gcc.h \ - google/protobuf/stubs/atomicops_internals_x86_msvc.h \ google/protobuf/stubs/callback.h \ google/protobuf/stubs/bytestream.h \ google/protobuf/stubs/casts.h \ @@ -90,8 +76,6 @@ nobase_include_HEADERS = \ google/protobuf/stubs/once.h \ google/protobuf/stubs/platform_macros.h \ google/protobuf/stubs/port.h \ - google/protobuf/stubs/scoped_ptr.h \ - google/protobuf/stubs/shared_ptr.h \ google/protobuf/stubs/singleton.h \ google/protobuf/stubs/status.h \ google/protobuf/stubs/stl_util.h \ @@ -189,8 +173,6 @@ libprotobuf_lite_la_LDFLAGS += -Wl,--version-script=$(srcdir)/libprotobuf-lite.m EXTRA_libprotobuf_lite_la_DEPENDENCIES = libprotobuf-lite.map endif libprotobuf_lite_la_SOURCES = \ - google/protobuf/stubs/atomicops_internals_x86_gcc.cc \ - google/protobuf/stubs/atomicops_internals_x86_msvc.cc \ google/protobuf/stubs/bytestream.cc \ google/protobuf/stubs/bytestream.h \ google/protobuf/stubs/common.cc \ @@ -201,8 +183,6 @@ libprotobuf_lite_la_SOURCES = \ google/protobuf/stubs/io_win32.h \ google/protobuf/stubs/map_util.h \ google/protobuf/stubs/mathutil.h \ - google/protobuf/stubs/once.cc \ - google/protobuf/stubs/shared_ptr.h \ google/protobuf/stubs/status.cc \ google/protobuf/stubs/status.h \ google/protobuf/stubs/status_macros.h \ @@ -772,7 +752,6 @@ protobuf_test_SOURCES = \ google/protobuf/stubs/common_unittest.cc \ google/protobuf/stubs/int128_unittest.cc \ google/protobuf/stubs/io_win32_unittest.cc \ - google/protobuf/stubs/once_unittest.cc \ google/protobuf/stubs/statusor_test.cc \ google/protobuf/stubs/status_test.cc \ google/protobuf/stubs/stringpiece_unittest.cc \ @@ -796,8 +775,8 @@ protobuf_test_SOURCES = \ google/protobuf/message_unittest.cc \ google/protobuf/no_field_presence_test.cc \ google/protobuf/preserve_unknown_enum_test.cc \ - google/protobuf/proto3_arena_unittest.cc \ google/protobuf/proto3_arena_lite_unittest.cc \ + google/protobuf/proto3_arena_unittest.cc \ google/protobuf/proto3_lite_unittest.cc \ google/protobuf/reflection_ops_unittest.cc \ google/protobuf/repeated_field_reflection_unittest.cc \ @@ -928,9 +907,7 @@ endif no_warning_test.cc: echo "// Generated from Makefile.am" > no_warning_test.cc for FILE in $(nobase_include_HEADERS); do \ - if ! echo $${FILE} | grep "atomicops"; then \ - echo "#include <$${FILE}>" >> no_warning_test.cc; \ - fi \ + echo "#include <$${FILE}>" >> no_warning_test.cc; \ done echo "int main(int, char**) { return 0; }" >> no_warning_test.cc diff --git a/src/google/protobuf/any.cc b/src/google/protobuf/any.cc index 83edba5788..b94529e685 100644 --- a/src/google/protobuf/any.cc +++ b/src/google/protobuf/any.cc @@ -32,6 +32,7 @@ #include + namespace google { namespace protobuf { namespace internal { @@ -84,15 +85,23 @@ bool AnyMetadata::InternalIs(const Descriptor* descriptor) const { return full_name == descriptor->full_name(); } -bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) { +bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, + string* full_type_name) { size_t pos = type_url.find_last_of("/"); if (pos == string::npos || pos + 1 == type_url.size()) { return false; } + if (url_prefix) { + *url_prefix = type_url.substr(0, pos + 1); + } *full_type_name = type_url.substr(pos + 1); return true; } +bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) { + return ParseAnyTypeUrl(type_url, NULL, full_type_name); +} + bool GetAnyFieldDescriptors(const Message& message, const FieldDescriptor** type_url_field, diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h index c2c27ec333..a34e5f8eca 100644 --- a/src/google/protobuf/any.h +++ b/src/google/protobuf/any.h @@ -92,8 +92,19 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". // "type.googleapis.com/rpc.QueryOrigin" will return "rpc.QueryOrigin" in // *full_type_name. Returns false if the type_url does not have a "/" // in the type url separating the full type name. +// +// NOTE: this function is available publicly as: +// google::protobuf::Any() // static method on the generated message type. bool ParseAnyTypeUrl(const string& type_url, string* full_type_name); +// Get the proto type name and prefix from Any::type_url value. For example, +// passing "type.googleapis.com/rpc.QueryOrigin" will return +// "type.googleapis.com/" in *url_prefix and "rpc.QueryOrigin" in +// *full_type_name. Returns false if the type_url does not have a "/" in the +// type url separating the full type name. +bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, + string* full_type_name); + // See if message is of type google.protobuf.Any, if so, return the descriptors // for "type_url" and "value" fields. bool GetAnyFieldDescriptors(const Message& message, diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc index 4335e467a0..9d632efeef 100644 --- a/src/google/protobuf/any.pb.cc +++ b/src/google/protobuf/any.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class AnyDefaultTypeInternal { @@ -29,14 +29,9 @@ class AnyDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fany_2eproto { -void InitDefaultsAnyImpl() { +static void InitDefaultsAny() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Any_default_instance_; new (ptr) ::google::protobuf::Any(); @@ -45,9 +40,11 @@ void InitDefaultsAnyImpl() { ::google::protobuf::Any::InitAsDefaultInstance(); } -void InitDefaultsAny() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAnyImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Any.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -71,15 +68,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -134,6 +130,11 @@ void Any::PackFrom(const ::google::protobuf::Message& message, bool Any::UnpackTo(::google::protobuf::Message* message) const { return _any_metadata_.UnpackTo(message); } +bool Any::ParseAnyTypeUrl(const string& type_url, + string* full_type_name) { + return ::google::protobuf::internal::ParseAnyTypeUrl(type_url, + full_type_name); +} #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Any::kTypeUrlFieldNumber; @@ -142,16 +143,14 @@ const int Any::kValueFieldNumber; Any::Any() : ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Any) } Any::Any(const Any& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _cached_size_(0), _any_metadata_(&type_url_, &value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -168,7 +167,6 @@ Any::Any(const Any& from) void Any::SharedCtor() { type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } Any::~Any() { @@ -182,9 +180,7 @@ void Any::SharedDtor() { } void Any::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Any::descriptor() { ::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce(); @@ -192,7 +188,7 @@ const ::google::protobuf::Descriptor* Any::descriptor() { } const Any& Any::default_instance() { - ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); return *internal_default_instance(); } @@ -214,7 +210,7 @@ bool Any::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Any) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -352,9 +348,7 @@ size_t Any::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -414,10 +408,11 @@ void Any::Swap(Any* other) { } void Any::InternalSwap(Any* other) { using std::swap; - type_url_.Swap(&other->type_url_); - value_.Swap(&other->value_); + type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Any::GetMetadata() const { @@ -431,7 +426,7 @@ void Any::InternalSwap(Any* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::Create< ::google::protobuf::Any >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Any >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index 14c21a8f11..bc53799957 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto -#ifndef PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto #include @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: export @@ -31,6 +32,7 @@ #include #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fany_2eproto { // Internal implementation detail -- do not use these members. @@ -43,11 +45,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsAnyImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsAny(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsAny(); -} } // namespace protobuf_google_2fprotobuf_2fany_2eproto namespace google { namespace protobuf { @@ -58,7 +55,7 @@ LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::Create< ::google::protobuf::Any>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -100,7 +97,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in return reinterpret_cast( &_Any_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; // implements Any ----------------------------------------------- @@ -112,6 +109,8 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in template bool Is() const { return _any_metadata_.Is(); } + static bool ParseAnyTypeUrl(const string& type_url, + string* full_type_name); void Swap(Any* other); friend void swap(Any& a, Any& b) { @@ -120,32 +119,33 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // implements Message ---------------------------------------------- - inline Any* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline Any* New() const final { + return CreateMaybeMessage(NULL); } - Any* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + Any* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Any& from); void MergeFrom(const Any& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Any* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -156,7 +156,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -196,10 +196,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr type_url_; ::google::protobuf::internal::ArenaStringPtr value_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::AnyMetadata _any_metadata_; friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAnyImpl(); }; // =================================================================== @@ -329,4 +328,4 @@ inline void Any::set_allocated_value(::std::string* value) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fany_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc index b03545512f..e0a249d041 100644 --- a/src/google/protobuf/api.pb.cc +++ b/src/google/protobuf/api.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,17 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fapi_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Method; +} // namespace protobuf_google_2fprotobuf_2fapi_2eproto +namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext; +} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto +namespace protobuf_google_2fprotobuf_2ftype_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option; +} // namespace protobuf_google_2fprotobuf_2ftype_2eproto namespace google { namespace protobuf { class ApiDefaultTypeInternal { @@ -39,18 +49,9 @@ class MixinDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fapi_2eproto { -void InitDefaultsApiImpl() { +static void InitDefaultsApi() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod(); - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); - protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin(); { void* ptr = &::google::protobuf::_Api_default_instance_; new (ptr) ::google::protobuf::Api(); @@ -59,20 +60,16 @@ void InitDefaultsApiImpl() { ::google::protobuf::Api::InitAsDefaultInstance(); } -void InitDefaultsApi() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsApiImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi}, { + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base, + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base, + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base,}}; -void InitDefaultsMethodImpl() { +static void InitDefaultsMethod() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); { void* ptr = &::google::protobuf::_Method_default_instance_; new (ptr) ::google::protobuf::Method(); @@ -81,19 +78,13 @@ void InitDefaultsMethodImpl() { ::google::protobuf::Method::InitAsDefaultInstance(); } -void InitDefaultsMethod() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; -void InitDefaultsMixinImpl() { +static void InitDefaultsMixin() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Mixin_default_instance_; new (ptr) ::google::protobuf::Mixin(); @@ -102,9 +93,13 @@ void InitDefaultsMixinImpl() { ::google::protobuf::Mixin::InitAsDefaultInstance(); } -void InitDefaultsMixin() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMixinImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Api.base); + ::google::protobuf::internal::InitSCC(&scc_info_Method.base); + ::google::protobuf::internal::InitSCC(&scc_info_Mixin.base); } ::google::protobuf::Metadata file_level_metadata[3]; @@ -156,15 +151,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -205,8 +199,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -245,9 +239,8 @@ const int Api::kSyntaxFieldNumber; Api::Api() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Api) } @@ -256,8 +249,7 @@ Api::Api(const Api& from) _internal_metadata_(NULL), methods_(from.methods_), options_(from.options_), - mixins_(from.mixins_), - _cached_size_(0) { + mixins_(from.mixins_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -282,7 +274,6 @@ void Api::SharedCtor() { ::memset(&source_context_, 0, static_cast( reinterpret_cast(&syntax_) - reinterpret_cast(&source_context_)) + sizeof(syntax_)); - _cached_size_ = 0; } Api::~Api() { @@ -297,9 +288,7 @@ void Api::SharedDtor() { } void Api::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Api::descriptor() { ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); @@ -307,7 +296,7 @@ const ::google::protobuf::Descriptor* Api::descriptor() { } const Api& Api::default_instance() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); return *internal_default_instance(); } @@ -337,7 +326,7 @@ bool Api::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Api) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -503,7 +492,7 @@ void Api::SerializeWithCachedSizes( // .google.protobuf.SourceContext source_context = 5; if (this->has_source_context()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *source_context_, output); + 5, this->_internal_source_context(), output); } // repeated .google.protobuf.Mixin mixins = 6; @@ -577,7 +566,7 @@ void Api::SerializeWithCachedSizes( if (this->has_source_context()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, *source_context_, deterministic, target); + 5, this->_internal_source_context(), deterministic, target); } // repeated .google.protobuf.Mixin mixins = 6; @@ -672,9 +661,7 @@ size_t Api::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -746,12 +733,13 @@ void Api::InternalSwap(Api* other) { CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_)); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_)); - name_.Swap(&other->name_); - version_.Swap(&other->version_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + version_.Swap(&other->version_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(source_context_, other->source_context_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Api::GetMetadata() const { @@ -779,17 +767,15 @@ const int Method::kSyntaxFieldNumber; Method::Method() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Method) } Method::Method(const Method& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -816,7 +802,6 @@ void Method::SharedCtor() { ::memset(&request_streaming_, 0, static_cast( reinterpret_cast(&syntax_) - reinterpret_cast(&request_streaming_)) + sizeof(syntax_)); - _cached_size_ = 0; } Method::~Method() { @@ -831,9 +816,7 @@ void Method::SharedDtor() { } void Method::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Method::descriptor() { ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); @@ -841,7 +824,7 @@ const ::google::protobuf::Descriptor* Method::descriptor() { } const Method& Method::default_instance() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); return *internal_default_instance(); } @@ -868,7 +851,7 @@ bool Method::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Method) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1193,9 +1176,7 @@ size_t Method::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1270,14 +1251,16 @@ void Method::Swap(Method* other) { void Method::InternalSwap(Method* other) { using std::swap; CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); - request_type_url_.Swap(&other->request_type_url_); - response_type_url_.Swap(&other->response_type_url_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + request_type_url_.Swap(&other->request_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + response_type_url_.Swap(&other->response_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(request_streaming_, other->request_streaming_); swap(response_streaming_, other->response_streaming_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Method::GetMetadata() const { @@ -1297,16 +1280,14 @@ const int Mixin::kRootFieldNumber; Mixin::Mixin() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Mixin) } Mixin::Mixin(const Mixin& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -1322,7 +1303,6 @@ Mixin::Mixin(const Mixin& from) void Mixin::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } Mixin::~Mixin() { @@ -1336,9 +1316,7 @@ void Mixin::SharedDtor() { } void Mixin::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Mixin::descriptor() { ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1346,7 +1324,7 @@ const ::google::protobuf::Descriptor* Mixin::descriptor() { } const Mixin& Mixin::default_instance() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); return *internal_default_instance(); } @@ -1368,7 +1346,7 @@ bool Mixin::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Mixin) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1518,9 +1496,7 @@ size_t Mixin::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1580,10 +1556,11 @@ void Mixin::Swap(Mixin* other) { } void Mixin::InternalSwap(Mixin* other) { using std::swap; - name_.Swap(&other->name_); - root_.Swap(&other->root_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Mixin::GetMetadata() const { @@ -1597,13 +1574,13 @@ void Mixin::InternalSwap(Mixin* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::Create< ::google::protobuf::Api >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Api >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::Create< ::google::protobuf::Method >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Method >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::Create< ::google::protobuf::Mixin >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::Mixin >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index 648aa308d2..5a720cce8c 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto -#ifndef PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto #include @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: export @@ -32,6 +33,7 @@ #include #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fapi_2eproto { // Internal implementation detail -- do not use these members. @@ -44,17 +46,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsApiImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsApi(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMethod(); -void LIBPROTOBUF_EXPORT InitDefaultsMixinImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMixin(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsApi(); - InitDefaultsMethod(); - InitDefaultsMixin(); -} } // namespace protobuf_google_2fprotobuf_2fapi_2eproto namespace google { namespace protobuf { @@ -71,9 +62,9 @@ LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::Create< ::google::protobuf::Api>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::Create< ::google::protobuf::Method>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::Create< ::google::protobuf::Mixin>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -115,7 +106,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in return reinterpret_cast( &_Api_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(Api* other); @@ -125,32 +116,33 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in // implements Message ---------------------------------------------- - inline Api* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline Api* New() const final { + return CreateMaybeMessage(NULL); } - Api* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + Api* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Api& from); void MergeFrom(const Api& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Api* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -161,7 +153,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -235,6 +227,9 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in bool has_source_context() const; void clear_source_context(); static const int kSourceContextFieldNumber = 5; + private: + const ::google::protobuf::SourceContext& _internal_source_context() const; + public: const ::google::protobuf::SourceContext& source_context() const; ::google::protobuf::SourceContext* release_source_context(); ::google::protobuf::SourceContext* mutable_source_context(); @@ -257,9 +252,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in ::google::protobuf::internal::ArenaStringPtr version_; ::google::protobuf::SourceContext* source_context_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApiImpl(); }; // ------------------------------------------------------------------- @@ -297,7 +291,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc return reinterpret_cast( &_Method_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void Swap(Method* other); @@ -307,32 +301,33 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- - inline Method* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline Method* New() const final { + return CreateMaybeMessage(NULL); } - Method* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + Method* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Method& from); void MergeFrom(const Method& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Method* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -343,7 +338,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -432,9 +427,8 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc bool request_streaming_; bool response_streaming_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethodImpl(); }; // ------------------------------------------------------------------- @@ -472,7 +466,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast( &_Mixin_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void Swap(Mixin* other); @@ -482,32 +476,33 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Mixin* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline Mixin* New() const final { + return CreateMaybeMessage(NULL); } - Mixin* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + Mixin* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Mixin& from); void MergeFrom(const Mixin& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Mixin* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -518,7 +513,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -558,9 +553,8 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr root_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixinImpl(); }; // =================================================================== @@ -740,6 +734,9 @@ inline void Api::set_allocated_version(::std::string* version) { inline bool Api::has_source_context() const { return this != internal_default_instance() && source_context_ != NULL; } +inline const ::google::protobuf::SourceContext& Api::_internal_source_context() const { + return *source_context_; +} inline const ::google::protobuf::SourceContext& Api::source_context() const { const ::google::protobuf::SourceContext* p = source_context_; // @@protoc_insertion_point(field_get:google.protobuf.Api.source_context) @@ -756,8 +753,8 @@ inline ::google::protobuf::SourceContext* Api::release_source_context() { inline ::google::protobuf::SourceContext* Api::mutable_source_context() { if (source_context_ == NULL) { - source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual()); + source_context_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context) return source_context_; @@ -1182,4 +1179,4 @@ inline void Mixin::set_allocated_root(::std::string* root) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fapi_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc index e53d72191c..c117c9e528 100755 --- a/src/google/protobuf/arena.cc +++ b/src/google/protobuf/arena.cc @@ -48,7 +48,7 @@ namespace protobuf { namespace internal { -google::protobuf::internal::SequenceNumber ArenaImpl::lifecycle_id_generator_; +std::atomic ArenaImpl::lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) ArenaImpl::ThreadCache& ArenaImpl::thread_cache() { static internal::ThreadLocalStorage* thread_cache_ = @@ -65,9 +65,10 @@ GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL} #endif void ArenaImpl::Init() { - lifecycle_id_ = lifecycle_id_generator_.GetNext(); - google::protobuf::internal::NoBarrier_Store(&hint_, 0); - google::protobuf::internal::NoBarrier_Store(&threads_, 0); + lifecycle_id_ = + lifecycle_id_generator_.fetch_add(1, std::memory_order_relaxed); + hint_.store(nullptr, std::memory_order_relaxed); + threads_.store(nullptr, std::memory_order_relaxed); if (initial_block_) { // Thread which calls Init() owns the first block. This allows the @@ -77,13 +78,12 @@ void ArenaImpl::Init() { SerialArena* serial = SerialArena::New(initial_block_, &thread_cache(), this); serial->set_next(NULL); - google::protobuf::internal::NoBarrier_Store(&threads_, - reinterpret_cast(serial)); - google::protobuf::internal::NoBarrier_Store(&space_allocated_, - options_.initial_block_size); + threads_.store(serial, std::memory_order_relaxed); + space_allocated_.store(options_.initial_block_size, + std::memory_order_relaxed); CacheSerialArena(serial); } else { - google::protobuf::internal::NoBarrier_Store(&space_allocated_, 0); + space_allocated_.store(0, std::memory_order_relaxed); } } @@ -118,7 +118,7 @@ ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) { void* mem = options_.block_alloc(size); Block* b = new (mem) Block(size, last_block); - google::protobuf::internal::NoBarrier_AtomicIncrement(&space_allocated_, size); + space_allocated_.fetch_add(size, std::memory_order_relaxed); return b; } @@ -142,6 +142,7 @@ void ArenaImpl::SerialArena::AddCleanupFallback(void* elem, AddCleanup(elem, cleanup); } +GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32) void* ArenaImpl::AllocateAligned(size_t n) { SerialArena* arena; if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { @@ -199,8 +200,7 @@ bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { // Check whether we own the last accessed SerialArena on this arena. This // fast path optimizes the case where a single thread uses multiple arenas. - SerialArena* serial = - reinterpret_cast(google::protobuf::internal::Acquire_Load(&hint_)); + SerialArena* serial = hint_.load(std::memory_order_acquire); if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { *arena = serial; return true; @@ -235,12 +235,11 @@ void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) { } uint64 ArenaImpl::SpaceAllocated() const { - return google::protobuf::internal::NoBarrier_Load(&space_allocated_); + return space_allocated_.load(std::memory_order_relaxed); } uint64 ArenaImpl::SpaceUsed() const { - SerialArena* serial = - reinterpret_cast(google::protobuf::internal::Acquire_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_acquire); uint64 space_used = 0; for ( ; serial; serial = serial->next()) { space_used += serial->SpaceUsed(); @@ -264,8 +263,7 @@ uint64 ArenaImpl::FreeBlocks() { uint64 space_allocated = 0; // By omitting an Acquire barrier we ensure that any user code that doesn't // properly synchronize Reset() or the destructor will throw a TSAN warning. - SerialArena* serial = - reinterpret_cast(google::protobuf::internal::NoBarrier_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_relaxed); while (serial) { // This is inside a block we are freeing, so we need to read it now. @@ -311,8 +309,7 @@ uint64 ArenaImpl::SerialArena::Free(ArenaImpl::SerialArena* serial, void ArenaImpl::CleanupList() { // By omitting an Acquire barrier we ensure that any user code that doesn't // properly synchronize Reset() or the destructor will throw a TSAN warning. - SerialArena* serial = - reinterpret_cast(google::protobuf::internal::NoBarrier_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_relaxed); for ( ; serial; serial = serial->next()) { serial->CleanupList(); @@ -368,8 +365,7 @@ ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner, GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) { // Look for this SerialArena in our linked list. - SerialArena* serial = - reinterpret_cast(google::protobuf::internal::Acquire_Load(&threads_)); + SerialArena* serial = threads_.load(std::memory_order_acquire); for ( ; serial; serial = serial->next()) { if (serial->owner() == me) { break; @@ -382,12 +378,11 @@ ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) { Block* b = NewBlock(NULL, kSerialArenaSize); serial = SerialArena::New(b, me, this); - google::protobuf::internal::AtomicWord head; + SerialArena* head = threads_.load(std::memory_order_relaxed); do { - head = google::protobuf::internal::NoBarrier_Load(&threads_); - serial->set_next(reinterpret_cast(head)); - } while (google::protobuf::internal::Release_CompareAndSwap( - &threads_, head, reinterpret_cast(serial)) != head); + serial->set_next(head); + } while (!threads_.compare_exchange_weak( + head, serial, std::memory_order_release, std::memory_order_relaxed)); } CacheSerialArena(serial); diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h index f3cdedac3f..53b7def5cd 100644 --- a/src/google/protobuf/arena.h +++ b/src/google/protobuf/arena.h @@ -37,9 +37,6 @@ #ifdef max #undef max // Visual Studio defines this macro #endif -#if LANG_CXX11 -#include -#endif #if defined(_MSC_VER) && !_HAS_EXCEPTIONS // Work around bugs in MSVC header when _HAS_EXCEPTIONS=0. #include @@ -53,10 +50,13 @@ using type_info = ::type_info; #include #include +#include namespace google { namespace protobuf { -struct ArenaOptions; + +struct ArenaOptions; // defined below + } // namespace protobuf namespace quality_webanswers { @@ -66,27 +66,32 @@ void TempPrivateWorkAround(::google::protobuf::ArenaOptions* arena_options); } // namespace quality_webanswers namespace protobuf { + +class Arena; // defined below +class Message; // defined in message.h +class MessageLite; + namespace arena_metrics { void EnableArenaMetrics(::google::protobuf::ArenaOptions* options); } // namespace arena_metrics -class Arena; // defined below -class Message; // message.h - namespace internal { -struct ArenaStringPtr; // arenastring.h -class LazyField; // lazy_field.h -template -class GenericTypeHandler; // repeated_field.h +struct ArenaStringPtr; // defined in arenastring.h +class LazyField; // defined in lazy_field.h + +template +class GenericTypeHandler; // defined in repeated_field.h // Templated cleanup methods. -template void arena_destruct_object(void* object) { +template +void arena_destruct_object(void* object) { reinterpret_cast(object)->~T(); } -template void arena_delete_object(void* object) { +template +void arena_delete_object(void* object) { delete reinterpret_cast(object); } inline void arena_free(void* object, size_t size) { @@ -165,12 +170,12 @@ struct ArenaOptions { // intentionally want to avoid monitoring an allocation. (i.e. internal // allocations for managing the arena) void (*on_arena_allocation)(const std::type_info* allocated_type, - uint64 alloc_size, void* cookie); + uint64 alloc_size, void* cookie); // Constants define default starting block size and max block size for // arena allocator behavior -- see descriptions above. static const size_t kDefaultStartBlockSize = 256; - static const size_t kDefaultMaxBlockSize = 8192; + static const size_t kDefaultMaxBlockSize = 8192; friend void ::google::protobuf::arena_metrics::EnableArenaMetrics(ArenaOptions*); friend void quality_webanswers::TempPrivateWorkAround(ArenaOptions*); @@ -285,70 +290,16 @@ class LIBPROTOBUF_EXPORT Arena { // // This function also accepts any type T that satisfies the arena message // allocation protocol, documented above. -#if LANG_CXX11 template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage( - ::google::protobuf::Arena* arena, Args&&... args) { - static_assert( - InternalHelper::is_arena_constructable::value, - "CreateMessage can only construct types that are ArenaConstructable"); - if (arena == NULL) { - return new T(NULL, std::forward(args)...); - } else { - return arena->CreateMessageInternal(std::forward(args)...); - } - } -#endif - - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessage(::google::protobuf::Arena* arena) { -#if LANG_CXX11 - static_assert( - InternalHelper::is_arena_constructable::value, - "CreateMessage can only construct types that are ArenaConstructable"); -#endif - if (arena == NULL) { - return new T; - } else { - return arena->CreateMessageInternal(); - } - } - - // One-argument form of CreateMessage. This is useful for constructing objects - // that implement the arena message construction protocol described above but - // take additional constructor arguments. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessage(::google::protobuf::Arena* arena, const Arg& arg) { -#if LANG_CXX11 - static_assert( - InternalHelper::is_arena_constructable::value, - "CreateMessage can only construct types that are ArenaConstructable"); -#endif - if (arena == NULL) { - return new T(NULL, arg); - } else { - return arena->CreateMessageInternal(arg); - } - } - - // Two-argument form of CreateMessage. This is useful for constructing objects - // that implement the arena message construction protocol described above but - // take additional constructor arguments. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessage(::google::protobuf::Arena* arena, - const Arg1& arg1, - const Arg2& arg2) { -#if LANG_CXX11 + Arena* arena, Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); -#endif - if (arena == NULL) { - return new T(NULL, arg1, arg2); - } else { - return arena->CreateMessageInternal(arg1, arg2); - } + // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal() + // because protobuf generated classes specialize CreateMaybeMessage() and we + // need to use that specialization for code size reasons. + return Arena::CreateMaybeMessage(arena, std::forward(args)...); } // API to create any objects on the arena. Note that only the object will @@ -366,153 +317,11 @@ class LIBPROTOBUF_EXPORT Arena { // (unless the destructor is trivial). Hence, from T's point of view, it is as // if the object were allocated on the heap (except that the underlying memory // is obtained from the arena). -#if LANG_CXX11 template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, Args&&... args) { - if (arena == NULL) { - return new T(std::forward(args)...); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - std::forward(args)...); - } - } -#endif - - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena) { - if (arena == NULL) { - return new T(); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value); - } - } - - // Version of the above with one constructor argument for the created object. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, const Arg& arg) { - if (arena == NULL) { - return new T(arg); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - arg); - } - } - - // Version of the above with two constructor arguments for the created object. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, const Arg1& arg1, const Arg2& arg2) { - if (arena == NULL) { - return new T(arg1, arg2); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - arg1, arg2); - } - } - - // Version of the above with three constructor arguments for the created - // object. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3) { - if (arena == NULL) { - return new T(arg1, arg2, arg3); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - arg1, arg2, arg3); - } - } - - // Version of the above with four constructor arguments for the created - // object. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - arg1, arg2, arg3, arg4); - } - } - - // Version of the above with five constructor arguments for the created - // object. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - arg1, arg2, arg3, arg4, arg5); - } - } - - // Version of the above with six constructor arguments for the created - // object. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5, const Arg6& arg6) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5, arg6); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - arg1, arg2, arg3, arg4, arg5, arg6); - } - } - - // Version of the above with seven constructor arguments for the created - // object. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5, const Arg6& arg6, - const Arg7& arg7) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value, - arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } - } - - // Version of the above with eight constructor arguments for the created - // object. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* Create(::google::protobuf::Arena* arena, - const Arg1& arg1, const Arg2& arg2, - const Arg3& arg3, const Arg4& arg4, - const Arg5& arg5, const Arg6& arg6, - const Arg7& arg7, const Arg8& arg8) { - if (arena == NULL) { - return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } else { - return arena->CreateInternal( - google::protobuf::internal::has_trivial_destructor::value, - arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena, + Args&&... args) { + return CreateNoMessage(arena, is_arena_constructable(), + std::forward(args)...); } // Create an array of object type T on the arena *without* invoking the @@ -521,10 +330,14 @@ class LIBPROTOBUF_EXPORT Arena { // To ensure safe uses, this function checks at compile time // (when compiled as C++11) that T is trivially default-constructible and // trivially destructible. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateArray(::google::protobuf::Arena* arena, size_t num_elements) { - GOOGLE_CHECK_LE(num_elements, - std::numeric_limits::max() / sizeof(T)) + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray( + Arena* arena, size_t num_elements) { + static_assert(std::is_trivially_default_constructible::value, + "CreateArray requires a trivially constructible type"); + static_assert(std::is_trivially_destructible::value, + "CreateArray requires a trivially destructible type"); + GOOGLE_CHECK_LE(num_elements, std::numeric_limits::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; if (arena == NULL) { return static_cast(::operator new[](num_elements * sizeof(T))); @@ -566,9 +379,9 @@ class LIBPROTOBUF_EXPORT Arena { // Adds |object| to a list of heap-allocated objects to be freed with |delete| // when the arena is destroyed or reset. - template GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void Own(T* object) { - OwnInternal(object, google::protobuf::internal::is_convertible()); + template + GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) { + OwnInternal(object, std::is_convertible()); } // Adds |object| to a list of objects whose destructors will be manually @@ -576,8 +389,8 @@ class LIBPROTOBUF_EXPORT Arena { // that it does not free the underlying memory with |delete|; hence, it is // normally only used for objects that are placement-newed into // arena-allocated memory. - template GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void OwnDestructor(T* object) { + template + GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_destruct_object); } @@ -596,8 +409,9 @@ class LIBPROTOBUF_EXPORT Arena { // message, or NULL otherwise. This differs from value->GetArena() in that the // latter is a virtual call, while this method is a templated call that // resolves at compile-time. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static ::google::protobuf::Arena* GetArena(const T* value) { + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena( + const T* value) { return GetArenaInternal(value, is_arena_constructable()); } @@ -608,80 +422,89 @@ class LIBPROTOBUF_EXPORT Arena { template static double DestructorSkippable(...); - typedef google::protobuf::internal::integral_constant< + typedef std::integral_constant< bool, sizeof(DestructorSkippable(static_cast(0))) == sizeof(char) || - google::protobuf::internal::has_trivial_destructor::value> + std::is_trivially_destructible::value> is_destructor_skippable; - template + template static char ArenaConstructable( const typename U::InternalArenaConstructable_*); - template + template static double ArenaConstructable(...); - typedef google::protobuf::internal::integral_constant( - static_cast(0))) == - sizeof(char)> + typedef std::integral_constant( + static_cast(0))) == + sizeof(char)> is_arena_constructable; -#if LANG_CXX11 template static T* Construct(void* ptr, Args&&... args) { return new (ptr) T(std::forward(args)...); } -#else - template - static T* Construct(void* ptr, const Arg1& arg1) { - return new (ptr) T(arg1); - } - template - static T* Construct(void* ptr, const Arg1& arg1, const Arg2& arg2) { - return new (ptr) T(arg1, arg2); - } - template - static T* Construct(void* ptr, const Arg1& arg1, - const Arg2& arg2, const Arg3& arg3) { - return new (ptr) T(arg1, arg2, arg3); - } -#endif // LANG_CXX11 static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); } friend class Arena; }; - // Helper typetrait that indicates support for arenas in a type T at compile + // Helper typetraits that indicates support for arenas in a type T at compile // time. This is public only to allow construction of higher-level templated - // utilities. is_arena_constructable::value is true if the message type T - // has arena support enabled, and false otherwise. + // utilities. + // + // is_arena_constructable::value is true if the message type T has arena + // support enabled, and false otherwise. + // + // is_destructor_skippable::value is true if the message type T has told + // the arena that it is safe to skip the destructor, and false otherwise. // // This is inside Arena because only Arena has the friend relationships // necessary to see the underlying generated code traits. template struct is_arena_constructable : InternalHelper::is_arena_constructable {}; + template + struct is_destructor_skippable : InternalHelper::is_destructor_skippable { + }; private: - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMessageInternal(::google::protobuf::Arena* arena) { -#if LANG_CXX11 + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( + Arena* arena, Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); -#endif if (arena == NULL) { - return new T; + return new T(nullptr, std::forward(args)...); } else { - return arena->CreateMessageInternal(); + return arena->DoCreateMessage(std::forward(args)...); } } - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateInternal(::google::protobuf::Arena* arena) { + // This specialization for no arguments is necessary, because its behavior is + // slightly different. When the arena pointer is nullptr, it calls T() + // instead of T(nullptr). + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( + Arena* arena) { + static_assert( + InternalHelper::is_arena_constructable::value, + "CreateMessage can only construct types that are ArenaConstructable"); if (arena == NULL) { return new T(); } else { - return arena->CreateInternal(google::protobuf::internal::has_trivial_destructor::value); + return arena->DoCreateMessage(); + } + } + + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal( + Arena* arena, Args&&... args) { + if (arena == NULL) { + return new T(std::forward(args)...); + } else { + return arena->DoCreate(std::is_trivially_destructible::value, + std::forward(args)...); } } @@ -696,8 +519,9 @@ class LIBPROTOBUF_EXPORT Arena { // Allocate and also optionally call on_arena_allocation callback with the // allocated type info when the hooks are in place in ArenaOptions and // the cookie is not null. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - void* AllocateInternal(bool skip_explicit_ownership) { + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* AllocateInternal( + bool skip_explicit_ownership) { const size_t n = internal::AlignUpTo8(sizeof(T)); AllocHook(RTTI_TYPE_ID(T), n); // Monitor allocation if needed. @@ -714,27 +538,49 @@ class LIBPROTOBUF_EXPORT Arena { // as it can cause confusing API usages, and end up having double free in // user code. These are used only internally from LazyField and Repeated // fields, since they are designed to work in all mode combinations. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static Msg* CreateMaybeMessage(Arena* arena, google::protobuf::internal::true_type) { - return CreateMessageInternal(arena); + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage( + Arena* arena, std::true_type, Args&&... args) { + return CreateMessageInternal(arena, std::forward(args)...); } - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMaybeMessage(Arena* arena, google::protobuf::internal::false_type) { - return CreateInternal(arena); + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage( + Arena* arena, std::false_type, Args&&... args) { + return CreateInternal(arena, std::forward(args)...); } - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static T* CreateMaybeMessage(Arena* arena) { - return CreateMaybeMessage(arena, is_arena_constructable()); + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage( + Arena* arena, Args&&... args) { + return DoCreateMaybeMessage(arena, is_arena_constructable(), + std::forward(args)...); + } + + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( + Arena* arena, std::true_type, Args&&... args) { + // User is constructing with Create() despite the fact that T supports arena + // construction. In this case we have to delegate to CreateInternal(), and + // we can't use any CreateMaybeMessage() specialization that may be defined. + return CreateInternal(arena, std::forward(args)...); + } + + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( + Arena* arena, std::false_type, Args&&... args) { + // User is constructing with Create() and the type does not support arena + // construction. In this case we can delegate to CreateMaybeMessage() and + // use any specialization that may be available for that. + return CreateMaybeMessage(arena, std::forward(args)...); } // Just allocate the required size for the given type assuming the // type has a trivial constructor. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternalRawArray(size_t num_elements) { - GOOGLE_CHECK_LE(num_elements, - std::numeric_limits::max() / sizeof(T)) + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray( + size_t num_elements) { + GOOGLE_CHECK_LE(num_elements, std::numeric_limits::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements); // Monitor allocation if needed. @@ -742,143 +588,18 @@ class LIBPROTOBUF_EXPORT Arena { return static_cast(impl_.AllocateAligned(n)); } -#if LANG_CXX11 template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, Args&&... args) { + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate( + bool skip_explicit_ownership, Args&&... args) { return new (AllocateInternal(skip_explicit_ownership)) T(std::forward(args)...); } -#else - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership) { - return new (AllocateInternal(skip_explicit_ownership)) T(); - } - - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, const Arg& arg) { - return new (AllocateInternal(skip_explicit_ownership)) T(arg); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2) { - return new (AllocateInternal(skip_explicit_ownership)) T(arg1, arg2); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3) { - return new (AllocateInternal(skip_explicit_ownership)) - T(arg1, arg2, arg3); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4) { - return new (AllocateInternal(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5) { - return new (AllocateInternal(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5, - const Arg6& arg6) { - return new (AllocateInternal(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5, arg6); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5, - const Arg6& arg6, - const Arg7& arg7) { - return new (AllocateInternal(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateInternal(bool skip_explicit_ownership, - const Arg1& arg1, - const Arg2& arg2, - const Arg3& arg3, - const Arg4& arg4, - const Arg5& arg5, - const Arg6& arg6, - const Arg7& arg7, - const Arg8& arg8) { - return new (AllocateInternal(skip_explicit_ownership)) - T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } -#endif -#if LANG_CXX11 template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal( - Args&&... args) { + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { return InternalHelper::Construct( AllocateInternal(InternalHelper::is_destructor_skippable::value), this, std::forward(args)...); } -#endif - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal() { - return InternalHelper::Construct( - AllocateInternal(InternalHelper::is_destructor_skippable::value), - this); - } - - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateMessageInternal(const Arg& arg) { - return InternalHelper::Construct( - AllocateInternal(InternalHelper::is_destructor_skippable::value), - this, arg); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - T* CreateMessageInternal(const Arg1& arg1, const Arg2& arg2) { - return InternalHelper::Construct( - AllocateInternal(InternalHelper::is_destructor_skippable::value), - this, arg1, arg2); - } // CreateInArenaStorage is used to implement map field. Without it, // google::protobuf::Map need to call generated message's protected arena constructor, @@ -893,22 +614,22 @@ class LIBPROTOBUF_EXPORT Arena { } template - static void CreateInArenaStorageInternal( - T* ptr, Arena* arena, google::protobuf::internal::true_type) { + static void CreateInArenaStorageInternal(T* ptr, Arena* arena, + std::true_type) { InternalHelper::Construct(ptr, arena); } template - static void CreateInArenaStorageInternal( - T* ptr, Arena* /* arena */, google::protobuf::internal::false_type) { + static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */, + std::false_type) { new (ptr) T(); } template - static void RegisterDestructorInternal( - T* /* ptr */, Arena* /* arena */, google::protobuf::internal::true_type) {} + static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */, + std::true_type) {} template - static void RegisterDestructorInternal( - T* ptr, Arena* arena, google::protobuf::internal::false_type) { + static void RegisterDestructorInternal(T* ptr, Arena* arena, + std::false_type) { arena->OwnDestructor(ptr); } @@ -917,15 +638,16 @@ class LIBPROTOBUF_EXPORT Arena { // is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing // all template instantiations to one for generic Message reduces code size, // using the virtual destructor instead. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - void OwnInternal(T* object, google::protobuf::internal::true_type) { + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, + std::true_type) { if (object != NULL) { - impl_.AddCleanup(object, - &internal::arena_delete_object< ::google::protobuf::Message>); + impl_.AddCleanup(object, &internal::arena_delete_object); } } - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - void OwnInternal(T* object, google::protobuf::internal::false_type) { + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, + std::false_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object); } @@ -934,16 +656,15 @@ class LIBPROTOBUF_EXPORT Arena { // Implementation for GetArena(). Only message objects with // InternalArenaConstructable_ tags can be associated with an arena, and such // objects must implement a GetArenaNoVirtual() method. - template GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static ::google::protobuf::Arena* GetArenaInternal( - const T* value, google::protobuf::internal::true_type) { + template + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( + const T* value, std::true_type) { return InternalHelper::GetArena(value); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE - static ::google::protobuf::Arena* GetArenaInternal( - const T* /* value */, google::protobuf::internal::false_type) { + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( + const T* /* value */, std::false_type) { return NULL; } @@ -965,9 +686,10 @@ class LIBPROTOBUF_EXPORT Arena { void* hooks_cookie_; template - friend class ::google::protobuf::internal::GenericTypeHandler; + friend class internal::GenericTypeHandler; friend struct internal::ArenaStringPtr; // For AllocateAligned. - friend class internal::LazyField; // For CreateMaybeMessage. + friend class internal::LazyField; // For CreateMaybeMessage. + friend class MessageLite; template friend class Map; }; diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h index 439b096988..f648f16621 100644 --- a/src/google/protobuf/arena_impl.h +++ b/src/google/protobuf/arena_impl.h @@ -33,13 +33,11 @@ #ifndef GOOGLE_PROTOBUF_ARENA_IMPL_H__ #define GOOGLE_PROTOBUF_ARENA_IMPL_H__ +#include #include -#include -#include #include #include -#include #include @@ -248,7 +246,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl { int64 last_lifecycle_id_seen; SerialArena* last_serial_arena; }; - static google::protobuf::internal::SequenceNumber lifecycle_id_generator_; + static std::atomic lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread // local storage class we implemented. @@ -277,12 +275,15 @@ class LIBPROTOBUF_EXPORT ArenaImpl { // TODO(haberman): evaluate whether we would gain efficiency by getting rid // of hint_. It's the only write we do to ArenaImpl in the allocation path, // which will dirty the cache line. - google::protobuf::internal::Release_Store(&hint_, reinterpret_cast(serial)); + + hint_.store(serial, std::memory_order_release); } - google::protobuf::internal::AtomicWord threads_; // Pointer to a linked list of SerialArena. - google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access - google::protobuf::internal::AtomicWord space_allocated_; // Sum of sizes of all allocated blocks. + + std::atomic + threads_; // Pointer to a linked list of SerialArena. + std::atomic hint_; // Fast thread-local block access + std::atomic space_allocated_; // Total size of all allocated blocks. Block *initial_block_; // If non-NULL, points to the block that came from // user data. @@ -297,18 +298,20 @@ class LIBPROTOBUF_EXPORT ArenaImpl { Options options_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl); + // All protos have pointers back to the arena hence Arena must have + // pointer stability. + ArenaImpl(ArenaImpl&&) = delete; + ArenaImpl& operator=(ArenaImpl&&) = delete; public: // kBlockHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8 // to protect the invariant that pos is always at a multiple of 8. static const size_t kBlockHeaderSize = (sizeof(Block) + 7) & -8; static const size_t kSerialArenaSize = (sizeof(SerialArena) + 7) & -8; -#if LANG_CXX11 static_assert(kBlockHeaderSize % 8 == 0, "kBlockHeaderSize must be a multiple of 8."); static_assert(kSerialArenaSize % 8 == 0, "kSerialArenaSize must be a multiple of 8."); -#endif }; } // namespace internal diff --git a/src/google/protobuf/arena_test_util.h b/src/google/protobuf/arena_test_util.h index 8c9f7698c5..df56ece8d4 100644 --- a/src/google/protobuf/arena_test_util.h +++ b/src/google/protobuf/arena_test_util.h @@ -50,7 +50,7 @@ void TestParseCorruptedString(const T& message) { s[i] ^= c; google::protobuf::Arena arena; T* message = - google::protobuf::Arena::CreateMessage(use_arena ? &arena : NULL); + google::protobuf::Arena::CreateMessage(use_arena ? &arena : nullptr); if (message->ParseFromString(s)) { ++success_count; } diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc index 71e28b0c4e..eaaffce25a 100644 --- a/src/google/protobuf/arena_unittest.cc +++ b/src/google/protobuf/arena_unittest.cc @@ -33,10 +33,8 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include +#include #include #include @@ -153,9 +151,19 @@ class MustBeConstructedWithOneThroughEight { TEST(ArenaTest, ArenaConstructable) { EXPECT_TRUE(Arena::is_arena_constructable::type::value); EXPECT_TRUE(Arena::is_arena_constructable::type::value); + EXPECT_FALSE(Arena::is_arena_constructable< + protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); EXPECT_FALSE(Arena::is_arena_constructable::type::value); } +TEST(ArenaTest, DestructorSkippable) { + EXPECT_TRUE(Arena::is_destructor_skippable::type::value); + EXPECT_TRUE(Arena::is_destructor_skippable::type::value); + EXPECT_FALSE(Arena::is_destructor_skippable< + protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); + EXPECT_FALSE(Arena::is_destructor_skippable::type::value); +} + TEST(ArenaTest, BasicCreate) { Arena arena; EXPECT_TRUE(Arena::Create(&arena) != NULL); @@ -197,7 +205,6 @@ TEST(ArenaTest, CreateAndNonConstCopy) { EXPECT_EQ("foo", *s_copy); } -#if LANG_CXX11 TEST(ArenaTest, CreateAndMove) { Arena arena; string s("foo"); @@ -206,7 +213,6 @@ TEST(ArenaTest, CreateAndMove) { EXPECT_TRUE(s.empty()); // NOLINT EXPECT_EQ("foo", *s_move); } -#endif TEST(ArenaTest, CreateWithFourConstructorArguments) { Arena arena; @@ -242,7 +248,6 @@ TEST(ArenaTest, CreateWithEightConstructorArguments) { ASSERT_EQ("8", new_object->eight_); } -#if LANG_CXX11 class PleaseMoveMe { public: explicit PleaseMoveMe(const string& value) : value_(value) {} @@ -263,7 +268,6 @@ TEST(ArenaTest, CreateWithMoveArguments) { EXPECT_TRUE(new_object); ASSERT_EQ("1", new_object->value()); } -#endif TEST(ArenaTest, InitialBlockTooSmall) { // Construct a small (64 byte) initial block of memory to be used by the @@ -442,7 +446,7 @@ TEST(ArenaTest, ReflectionSwapFields) { TestUtil::SetAllFields(arena1_message); reflection->SwapFields(arena1_message, &message, fields); EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(NULL, message.GetArena()); + EXPECT_EQ(nullptr, message.GetArena()); arena1_message->SerializeToString(&output); EXPECT_EQ(0, output.size()); TestUtil::ExpectAllFieldsSet(message); @@ -468,7 +472,7 @@ TEST(ArenaTest, ReleaseMessage) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); arena_message->mutable_optional_nested_message()->set_bb(118); - google::protobuf::scoped_ptr nested( + std::unique_ptr nested( arena_message->release_optional_nested_message()); EXPECT_EQ(118, nested->bb()); @@ -489,7 +493,7 @@ TEST(ArenaTest, ReleaseString) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); arena_message->set_optional_string("hello"); - google::protobuf::scoped_ptr released_str( + std::unique_ptr released_str( arena_message->release_optional_string()); EXPECT_EQ("hello", *released_str); @@ -600,25 +604,6 @@ TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) { } #endif // !GOOGLE_PROTOBUF_NO_RTTI -TEST(ArenaTest, UnsafeArenaReleaseDoesNotMakeCopy) { - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - TestAllTypes::NestedMessage* nested_msg = NULL; - TestAllTypes::NestedMessage* orig_nested_msg = NULL; - string* nested_string = NULL; - string* orig_nested_string = NULL; - arena_message->mutable_optional_nested_message()->set_bb(42); - *arena_message->mutable_optional_string() = "Hello"; - orig_nested_msg = arena_message->mutable_optional_nested_message(); - orig_nested_string = arena_message->mutable_optional_string(); - nested_msg = arena_message->unsafe_arena_release_optional_nested_message(); - nested_string = arena_message->unsafe_arena_release_optional_string(); - - EXPECT_EQ(orig_nested_msg, nested_msg); - EXPECT_EQ(orig_nested_string, nested_string); - // Released pointers still on arena; no 'delete' calls needed here. -} - TEST(ArenaTest, SetAllocatedAcrossArenas) { Arena arena1; TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); @@ -898,17 +883,18 @@ TEST(ArenaTest, ReleaseLastRepeatedField) { TEST(ArenaTest, UnsafeArenaReleaseAdd) { // Use unsafe_arena_release() and unsafe_arena_set_allocated() to transfer an // arena-allocated string from one message to another. + const char kContent[] = "Test content"; + Arena arena; TestAllTypes* message1 = Arena::CreateMessage(&arena); TestAllTypes* message2 = Arena::CreateMessage(&arena); string* arena_string = Arena::Create(&arena); - *arena_string = "Test content"; + *arena_string = kContent; message1->unsafe_arena_set_allocated_optional_string(arena_string); - EXPECT_EQ(arena_string, message1->mutable_optional_string()); message2->unsafe_arena_set_allocated_optional_string( message1->unsafe_arena_release_optional_string()); - EXPECT_EQ(arena_string, message2->mutable_optional_string()); + EXPECT_EQ(kContent, message2->optional_string()); } TEST(ArenaTest, UnsafeArenaAddAllocated) { @@ -1432,7 +1418,7 @@ TEST(ArenaTest, ArenaHooksSanity) { EXPECT_EQ(1, ArenaHooksTestUtil::num_init); EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations); ::google::protobuf::Arena::Create(&arena); - if (google::protobuf::internal::has_trivial_destructor::value) { + if (std::is_trivially_destructible::value) { EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations); } else { EXPECT_EQ(2, ArenaHooksTestUtil::num_allocations); diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h index 2b108616ad..168fc972b8 100755 --- a/src/google/protobuf/arenastring.h +++ b/src/google/protobuf/arenastring.h @@ -99,6 +99,13 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { if (ptr_ == default_value) { return NULL; } + return ReleaseNonDefault(default_value, arena); + } + + // Similar to Release, but ptr_ cannot be the default_value. + inline ::std::string* ReleaseNonDefault( + const ::std::string* default_value, ::google::protobuf::Arena* arena) { + GOOGLE_DCHECK(!IsDefault(default_value)); ::std::string* released = NULL; if (arena != NULL) { // ptr_ is owned by the arena. @@ -164,6 +171,29 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) { std::swap(ptr_, other->ptr_); } + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap( + ArenaStringPtr* other, const ::std::string* default_value, Arena* arena) { +#ifndef NDEBUG + // For debug builds, we swap the contents of the string, rather than the + // string instances themselves. This invalidates previously taken const + // references that are (per our documentation) invalidated by calling Swap() + // on the message. + // + // If both strings are the default_value, swapping is uninteresting. + // Otherwise, we use ArenaStringPtr::Mutable() to access the string, to + // ensure that we do not try to mutate default_value itself. + if (IsDefault(default_value) && other->IsDefault(default_value)) { + return; + } + + ::std::string* this_ptr = Mutable(default_value, arena); + ::std::string* other_ptr = other->Mutable(default_value, arena); + + this_ptr->swap(*other_ptr); +#else + std::swap(ptr_, other->ptr_); +#endif + } // Frees storage (if not on an arena). inline void Destroy(const ::std::string* default_value, @@ -186,6 +216,15 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { } } + // Clears content, assuming that the current value is not the empty string + // default. + inline void ClearNonDefaultToEmpty() { + ptr_->clear(); + } + inline void ClearNonDefaultToEmptyNoArena() { + ptr_->clear(); + } + // Clears content, but keeps allocated string if arena != NULL, to avoid the // overhead of heap operations. After this returns, the content (as seen by // the user) will always be equal to |default_value|. @@ -253,12 +292,19 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr { if (ptr_ == default_value) { return NULL; } else { - ::std::string* released = ptr_; - ptr_ = const_cast< ::std::string* >(default_value); - return released; + return ReleaseNonDefaultNoArena(default_value); } } + inline ::std::string* ReleaseNonDefaultNoArena( + const ::std::string* default_value) { + GOOGLE_DCHECK(!IsDefault(default_value)); + ::std::string* released = ptr_; + ptr_ = const_cast< ::std::string* >(default_value); + return released; + } + + inline void SetAllocatedNoArena(const ::std::string* default_value, ::std::string* value) { if (ptr_ != default_value) { diff --git a/src/google/protobuf/arenastring_unittest.cc b/src/google/protobuf/arenastring_unittest.cc index d5d995a6af..adc44fe25c 100644 --- a/src/google/protobuf/arenastring_unittest.cc +++ b/src/google/protobuf/arenastring_unittest.cc @@ -35,9 +35,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include diff --git a/src/google/protobuf/compiler/annotation_test_util.cc b/src/google/protobuf/compiler/annotation_test_util.cc index cc8534cc57..a0530b9a69 100644 --- a/src/google/protobuf/compiler/annotation_test_util.cc +++ b/src/google/protobuf/compiler/annotation_test_util.cc @@ -31,9 +31,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include diff --git a/src/google/protobuf/compiler/code_generator.cc b/src/google/protobuf/compiler/code_generator.cc index 11d0f33432..aaabd9142d 100644 --- a/src/google/protobuf/compiler/code_generator.cc +++ b/src/google/protobuf/compiler/code_generator.cc @@ -34,9 +34,9 @@ #include -#include #include #include +#include #include #include diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc index 7c45fe75fa..8380367fa8 100644 --- a/src/google/protobuf/compiler/command_line_interface.cc +++ b/src/google/protobuf/compiler/command_line_interface.cc @@ -58,9 +58,6 @@ #include //For PATH_MAX #include -#ifndef _SHARED_PTR_H -#include -#endif #ifdef __APPLE__ #include @@ -171,8 +168,7 @@ bool VerifyDirectoryExists(const string& path) { // directories listed in |filename|. bool TryCreateParentDirectory(const string& prefix, const string& filename) { // Recursively create parent directories to the output file. - std::vector parts = - Split(filename, "/", true); + std::vector parts = Split(filename, "/", true); string path_so_far = prefix; for (int i = 0; i < parts.size() - 1; i++) { path_so_far += parts[i]; @@ -440,7 +436,7 @@ class CommandLineInterface::MemoryOutputStream bool append_mode_; // StringOutputStream writing to data_. - google::protobuf::scoped_ptr inner_; + std::unique_ptr inner_; }; // ------------------------------------------------------------------- @@ -835,10 +831,10 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { std::vector parsed_files; // null unless descriptor_set_in_names_.empty() - google::protobuf::scoped_ptr disk_source_tree; - google::protobuf::scoped_ptr error_collector; - google::protobuf::scoped_ptr descriptor_pool; - google::protobuf::scoped_ptr descriptor_database; + std::unique_ptr disk_source_tree; + std::unique_ptr error_collector; + std::unique_ptr descriptor_pool; + std::unique_ptr descriptor_database; if (descriptor_set_in_names_.empty()) { disk_source_tree.reset(new DiskSourceTree()); if (!InitializeDiskSourceTree(disk_source_tree.get())) { @@ -1395,8 +1391,7 @@ CommandLineInterface::InterpretArgument(const string& name, // with colons. Let's accept that syntax too just to make things more // intuitive. std::vector parts = Split( - value, - CommandLineInterface::kPathSeparator, + value, CommandLineInterface::kPathSeparator, true); for (int i = 0; i < parts.size(); i++) { @@ -1421,7 +1416,7 @@ CommandLineInterface::InterpretArgument(const string& name, // Make sure disk path exists, warn otherwise. if (access(disk_path.c_str(), F_OK) < 0) { - // Try the original path; it may have just happed to have a '=' in it. + // Try the original path; it may have just happened to have a '=' in it. if (access(parts[i].c_str(), F_OK) < 0) { std::cerr << disk_path << ": warning: directory does not exist." << std::endl; @@ -1447,8 +1442,7 @@ CommandLineInterface::InterpretArgument(const string& name, } direct_dependencies_explicitly_set_ = true; - std::vector direct = Split( - value, ":", true); + std::vector direct = Split(value, ":", true); GOOGLE_DCHECK(direct_dependencies_.empty()); direct_dependencies_.insert(direct.begin(), direct.end()); @@ -1481,9 +1475,8 @@ CommandLineInterface::InterpretArgument(const string& name, } descriptor_set_in_names_ = Split( - value, - CommandLineInterface::kPathSeparator, - true); + value, CommandLineInterface::kPathSeparator, + true); } else if (name == "-o" || name == "--descriptor_set_out") { if (!descriptor_set_out_name_.empty()) { @@ -1629,7 +1622,6 @@ CommandLineInterface::InterpretArgument(const string& name, } mode_ = MODE_PRINT; print_mode_ = PRINT_FREE_FIELDS; - } else if (name == "--profile_path") { } else { // Some other flag. Look it up in the generators list. const GeneratorInfo* generator_info = @@ -1908,10 +1900,12 @@ bool CommandLineInterface::GeneratePluginOutput( string* error) { CodeGeneratorRequest request; CodeGeneratorResponse response; + string processed_parameter = parameter; + // Build the request. - if (!parameter.empty()) { - request.set_parameter(parameter); + if (!processed_parameter.empty()) { + request.set_parameter(processed_parameter); } @@ -1948,17 +1942,18 @@ bool CommandLineInterface::GeneratePluginOutput( // Write the files. We do this even if there was a generator error in order // to match the behavior of a compiled-in generator. - google::protobuf::scoped_ptr current_output; + std::unique_ptr current_output; for (int i = 0; i < response.file_size(); i++) { const CodeGeneratorResponse::File& output_file = response.file(i); if (!output_file.insertion_point().empty()) { + string filename = output_file.name(); // Open a file for insert. // We reset current_output to NULL first so that the old file is closed // before the new one is opened. current_output.reset(); current_output.reset(generator_context->OpenForInsert( - output_file.name(), output_file.insertion_point())); + filename, output_file.insertion_point())); } else if (!output_file.name().empty()) { // Starting a new file. Open it. // We reset current_output to NULL first so that the old file is closed @@ -1997,7 +1992,7 @@ bool CommandLineInterface::EncodeOrDecode(const DescriptorPool* pool) { } DynamicMessageFactory dynamic_factory(pool); - google::protobuf::scoped_ptr message(dynamic_factory.GetPrototype(type)->New()); + std::unique_ptr message(dynamic_factory.GetPrototype(type)->New()); if (mode_ == MODE_ENCODE) { SetFdToTextMode(STDIN_FILENO); diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h index d5d85f2da3..7d3037a9f7 100644 --- a/src/google/protobuf/compiler/command_line_interface.h +++ b/src/google/protobuf/compiler/command_line_interface.h @@ -413,11 +413,6 @@ class LIBPROTOC_EXPORT CommandLineInterface { // dependency file will be written. Otherwise, empty. string dependency_out_name_; - // Path to a file that contains serialized AccessInfo which provides - // relative hotness of fields per message. This helps protoc to generate - // better code. - string profile_path_; - // True if --include_imports was given, meaning that we should // write all transitive dependencies to the DescriptorSet. Otherwise, only // the .proto files listed on the command-line are added. diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc index ef7579a26c..41eb244a2d 100644 --- a/src/google/protobuf/compiler/command_line_interface_unittest.cc +++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc @@ -40,9 +40,6 @@ #include #endif #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -344,7 +341,7 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector args) { } } - google::protobuf::scoped_array argv(new const char* [args.size()]); + std::unique_ptr argv(new const char* [args.size()]); for (int i = 0; i < args.size(); i++) { args[i] = StringReplace(args[i], "$tmpdir", temp_directory_, true); @@ -2298,7 +2295,7 @@ class EncodeDecodeTest : public testing::TestWithParam { ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam(); } - google::protobuf::scoped_array argv(new const char* [args.size()]); + std::unique_ptr argv(new const char* [args.size()]); for (int i = 0; i < args.size(); i++) { argv[i] = args[i].c_str(); } diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc index f99159f5e9..4e150fe3d6 100644 --- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc @@ -44,6 +44,7 @@ #include +#include #include #include #include @@ -97,9 +98,10 @@ class MockGeneratorContext : public GeneratorContext { File::GetContents(TestSourceDir() + "/" + physical_filename, &actual_contents, true)); EXPECT_TRUE(actual_contents == *expected_contents) - << physical_filename << " needs to be regenerated. Please run " - "generate_descriptor_proto.sh. Then add this file " - "to your CL."; + << physical_filename + << " needs to be regenerated. Please run " + "generate_descriptor_proto.sh. " + "Then add this file to your CL."; } // implements GeneratorContext -------------------------------------- @@ -116,37 +118,50 @@ class MockGeneratorContext : public GeneratorContext { std::map files_; }; -TEST(BootstrapTest, GeneratedDescriptorMatches) { - MockErrorCollector error_collector; +const char kDescriptorParameter[] = "dllexport_decl=LIBPROTOBUF_EXPORT"; +const char kPluginParameter[] = "dllexport_decl=LIBPROTOC_EXPORT"; +const char kNormalParameter[] = ""; + +const char* test_protos[][2] = { + {"google/protobuf/descriptor", kDescriptorParameter}, + {"google/protobuf/compiler/plugin", kPluginParameter}, +}; + +TEST(BootstrapTest, GeneratedFilesMatch) { + // We need a mapping from the actual file to virtual and actual path + // of the data to compare to. + std::map vpath_map; + std::map rpath_map; + rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto2"] = + "net/proto2/z_generated_example/test_messages_proto2"; + rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto3"] = + "net/proto2/z_generated_example/test_messages_proto3"; + rpath_map["google/protobuf/proto2_weak"] = + "net/proto2/z_generated_example/proto2_weak"; + DiskSourceTree source_tree; source_tree.MapPath("", TestSourceDir()); - Importer importer(&source_tree, &error_collector); - const FileDescriptor* proto_file = - importer.Import("google/protobuf/descriptor.proto"); - const FileDescriptor* plugin_proto_file = - importer.Import("google/protobuf/compiler/plugin.proto"); - EXPECT_EQ("", error_collector.text_); - ASSERT_TRUE(proto_file != NULL); - ASSERT_TRUE(plugin_proto_file != NULL); - - CppGenerator generator; - MockGeneratorContext context; - string error; - string parameter = "dllexport_decl=LIBPROTOBUF_EXPORT"; - ASSERT_TRUE(generator.Generate(proto_file, parameter, - &context, &error)); - parameter = "dllexport_decl=LIBPROTOC_EXPORT"; - ASSERT_TRUE(generator.Generate(plugin_proto_file, parameter, - &context, &error)); - - context.ExpectFileMatches("google/protobuf/descriptor.pb.h", - "google/protobuf/descriptor.pb.h"); - context.ExpectFileMatches("google/protobuf/descriptor.pb.cc", - "google/protobuf/descriptor.pb.cc"); - context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.h", - "google/protobuf/compiler/plugin.pb.h"); - context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.cc", - "google/protobuf/compiler/plugin.pb.cc"); + + for (auto file_parameter : test_protos) { + MockErrorCollector error_collector; + Importer importer(&source_tree, &error_collector); + const FileDescriptor* file = + importer.Import(file_parameter[0] + string(".proto")); + ASSERT_TRUE(file != nullptr) + << "Can't import file " << file_parameter[0] + string(".proto") << "\n"; + EXPECT_EQ("", error_collector.text_); + CppGenerator generator; + MockGeneratorContext context; + string error; + ASSERT_TRUE(generator.Generate(file, file_parameter[1], &context, &error)); + + string vpath = + FindWithDefault(vpath_map, file_parameter[0], file_parameter[0]); + string rpath = + FindWithDefault(rpath_map, file_parameter[0], file_parameter[0]); + context.ExpectFileMatches(vpath + ".pb.cc", rpath + ".pb.cc"); + context.ExpectFileMatches(vpath + ".pb.h", rpath + ".pb.h"); + } } } // namespace diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.cc b/src/google/protobuf/compiler/cpp/cpp_enum.cc index 8adee0f5b5..0d6a9e2443 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum.cc +++ b/src/google/protobuf/compiler/cpp/cpp_enum.cc @@ -179,7 +179,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) { void EnumGenerator:: GenerateGetEnumDescriptorSpecializations(io::Printer* printer) { printer->Print( - "template <> struct is_proto_enum< $classname$> : ::google::protobuf::internal::true_type " + "template <> struct is_proto_enum< $classname$> : ::std::true_type " "{};\n", "classname", ClassName(descriptor_, true)); if (HasDescriptorMethods(descriptor_->file(), options_)) { diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc index 0a4e0bb949..c416ba1077 100644 --- a/src/google/protobuf/compiler/cpp/cpp_extension.cc +++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc @@ -35,8 +35,8 @@ #include #include #include -#include #include +#include #include @@ -120,7 +120,6 @@ void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) { " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n" " $name$;\n" ); - } void ExtensionGenerator::GenerateDefinition(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/cpp/cpp_field.cc b/src/google/protobuf/compiler/cpp/cpp_field.cc index 0cf25b33fd..33ffe574c3 100644 --- a/src/google/protobuf/compiler/cpp/cpp_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_field.cc @@ -34,21 +34,18 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include +#include +#include #include #include #include #include -#include #include -#include -#include +#include #include namespace google { @@ -116,26 +113,30 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { } FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, - const Options& options) + const Options& options, + SCCAnalyzer* scc_analyzer) : descriptor_(descriptor), options_(options), field_generators_( - new google::protobuf::scoped_ptr[descriptor->field_count()]) { + new std::unique_ptr[descriptor->field_count()]) { // Construct all the FieldGenerators. for (int i = 0; i < descriptor->field_count(); i++) { - field_generators_[i].reset(MakeGenerator(descriptor->field(i), options)); + field_generators_[i].reset( + MakeGenerator(descriptor->field(i), options, scc_analyzer)); } } FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, - const Options& options) { + const Options& options, + SCCAnalyzer* scc_analyzer) { if (field->is_repeated()) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: if (field->is_map()) { return new MapFieldGenerator(field, options); } else { - return new RepeatedMessageFieldGenerator(field, options); + return new RepeatedMessageFieldGenerator(field, options, + scc_analyzer); } case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { @@ -151,7 +152,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, } else if (field->containing_oneof()) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: - return new MessageOneofFieldGenerator(field, options); + return new MessageOneofFieldGenerator(field, options, scc_analyzer); case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // StringOneofFieldGenerator handles unknown ctypes. @@ -166,7 +167,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, } else { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_MESSAGE: - return new MessageFieldGenerator(field, options); + return new MessageFieldGenerator(field, options, scc_analyzer); case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: // StringFieldGenerator handles unknown ctypes. diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/cpp_field.h index bccfcb9a55..6cb466a87a 100644 --- a/src/google/protobuf/compiler/cpp/cpp_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_field.h @@ -37,13 +37,11 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include -#include +#include #include +#include namespace google { namespace protobuf { @@ -82,38 +80,12 @@ class FieldGenerator { // implementation is empty. virtual void GenerateStaticMembers(io::Printer* /*printer*/) const {} - // Generate prototypes for accessors that will manipulate imported - // messages inline. These are for .proto.h headers. - // - // In .proto.h mode, the headers of imports are not #included. However, - // functions that manipulate the imported message types need access to - // the class definition of the imported message, meaning that the headers - // must be #included. To get around this, functions that manipulate - // imported message objects are defined as dependent functions in a base - // template class. By making them dependent template functions, the - // function templates will not be instantiated until they are called, so - // we can defer to those translation units to #include the necessary - // generated headers. - // - // See: - // http://en.cppreference.com/w/cpp/language/class_template#Implicit_instantiation - // - // Most field types don't need this, so the default implementation is empty. - virtual void GenerateDependentAccessorDeclarations( - io::Printer* printer) const {} - // Generate prototypes for all of the accessor functions related to this // field. These are placed inside the class definition. virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0; - // Generate inline definitions of depenent accessor functions for this field. - // These are placed inside the header after all class definitions. - virtual void GenerateDependentInlineAccessorDefinitions( - io::Printer* printer) const {} - // Generate inline definitions of accessor functions for this field. // These are placed inside the header after all class definitions. - // In non-.proto.h mode, this generates dependent accessor functions as well. virtual void GenerateInlineAccessorDefinitions( io::Printer* printer) const = 0; @@ -207,6 +179,11 @@ class FieldGenerator { // are placed in the message's ByteSize() method. virtual void GenerateByteSize(io::Printer* printer) const = 0; + // Any tags about field layout decisions (such as inlining) to embed in the + // offset. + virtual uint32 CalculateFieldTag() const { return 0; } + virtual bool IsInlined() const { return false; } + protected: const Options& options_; @@ -217,7 +194,8 @@ class FieldGenerator { // Convenience class which constructs FieldGenerators for a Descriptor. class FieldGeneratorMap { public: - FieldGeneratorMap(const Descriptor* descriptor, const Options& options); + FieldGeneratorMap(const Descriptor* descriptor, const Options& options, + SCCAnalyzer* scc_analyzer); ~FieldGeneratorMap(); const FieldGenerator& get(const FieldDescriptor* field) const; @@ -225,10 +203,11 @@ class FieldGeneratorMap { private: const Descriptor* descriptor_; const Options& options_; - google::protobuf::scoped_array > field_generators_; + std::unique_ptr []> field_generators_; static FieldGenerator* MakeGenerator(const FieldDescriptor* field, - const Options& options); + const Options& options, + SCCAnalyzer* scc_analyzer); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc index a922ee977e..42525687d5 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.cc +++ b/src/google/protobuf/compiler/cpp/cpp_file.cc @@ -35,20 +35,17 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include -#include #include +#include #include #include -#include -#include +#include #include +#include #include namespace google { @@ -61,11 +58,11 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options) options_(options), scc_analyzer_(options), enum_generators_owner_( - new google::protobuf::scoped_ptr[file->enum_type_count()]), + new std::unique_ptr[file->enum_type_count()]), service_generators_owner_( - new google::protobuf::scoped_ptr[file->service_count()]), + new std::unique_ptr[file->service_count()]), extension_generators_owner_( - new google::protobuf::scoped_ptr[file->extension_count()]) { + new std::unique_ptr[file->extension_count()]) { std::vector msgs = FlattenMessagesInFile(file); for (int i = 0; i < msgs.size(); i++) { // Deleted in destructor @@ -141,6 +138,9 @@ void FileGenerator::GenerateHeader(io::Printer* printer) { printer->Print( "// @@protoc_insertion_point(includes)\n"); + printer->Print("#define PROTOBUF_INTERNAL_EXPORT_$filename$ $export$\n", + "filename", FileLevelNamespace(file_), + "export", options_.dllexport_decl); GenerateMacroUndefs(printer); GenerateGlobalStateFunctionDeclarations(printer); @@ -223,8 +223,9 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer, GenerateTopHeaderGuard(printer, filename_identifier); if (options_.proto_h) { + string target_basename = StripProto(file_->name()); printer->Print("#include \"$basename$.proto.h\" // IWYU pragma: export\n", - "basename", StripProto(file_->name())); + "basename", target_basename); } else { GenerateLibraryIncludes(printer); } @@ -256,9 +257,10 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer, } void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { + string target_basename = StripProto(file_->name()); const bool use_system_include = IsWellKnownMessage(file_); - string header = - StripProto(file_->name()) + (options_.proto_h ? ".proto.h" : ".pb.h"); + + string header = target_basename + (options_.proto_h ? ".proto.h" : ".pb.h"); printer->Print( "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" @@ -269,7 +271,6 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { "\n" "#include \n" "#include \n" - "#include \n" "#include \n" "#include \n", "filename", file_->name(), @@ -296,7 +297,8 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { for (int i = 0; i < file_->dependency_count(); i++) { const FileDescriptor* dep = file_->dependency(i); const char* extension = ".proto.h"; - string dependency = StripProto(dep->name()) + extension; + string basename = StripProto(dep->name()); + string dependency = basename + extension; printer->Print( "#include \"$dependency$\"\n", "dependency", dependency); @@ -338,33 +340,34 @@ namespace { // Generates weak symbol declarations for types that are to be considered weakly // referenced. -void GenerateWeakDeclarations( - const FileDescriptor* file, const Options& options, - SCCAnalyzer* scc_analyzer, - io::Printer* printer) { - std::vector fields; - ListAllFields(file, &fields); - +void GenerateInternalForwardDeclarations( + const std::vector& fields, const Options& options, + SCCAnalyzer* scc_analyzer, io::Printer* printer) { // To ensure determinism and minimize the number of namespace statements, // we output the forward declarations sorted on namespace and type / function // name. std::set > messages; + std::set > sccs; std::set > inits; for (int i = 0; i < fields.size(); ++i) { const FieldDescriptor* field = fields[i]; - bool is_weak = IsImplicitWeakField(field, options); + const Descriptor* msg = field->message_type(); + if (msg == nullptr) continue; + bool is_weak = IsImplicitWeakField(field, options, scc_analyzer); + string flns = FileLevelNamespace(msg); + auto scc = scc_analyzer->GetSCC(msg); + string repr = ClassName(scc->GetRepresentative()); + string weak_attr; if (is_weak) { - const Descriptor* msg = field->message_type(); - string flns = FileLevelNamespace(msg); - string repr = ClassName(scc_analyzer->GetSCC(msg)->GetRepresentative()); - inits.insert(std::make_pair(flns, "InitDefaults" + repr)); inits.insert(std::make_pair(flns, "AddDescriptors")); messages.insert(std::make_pair(Namespace(msg), ClassName(msg))); + weak_attr = " __attribute__((weak))"; } - } - - if (messages.empty()) { - return; + string dllexport = "PROTOBUF_INTERNAL_EXPORT_" + FileLevelNamespace(msg); + sccs.insert(std::make_pair(flns, "extern " + dllexport + weak_attr + + " ::google::protobuf::internal::SCCInfo<" + + SimpleItoa(scc->children.size()) + + "> scc_info_" + repr + ";\n")); } printer->Print("\n"); @@ -384,13 +387,33 @@ void GenerateWeakDeclarations( printer->Print("void $name$() __attribute__((weak));\n", "name", it->second); } + for (const auto& p : sccs) { + ns.ChangeTo(p.first); + printer->Print(p.second.c_str()); + } } } // namespace void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { GenerateSourceIncludes(printer); - GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer); + + // Generate weak declarations. We do this for the whole strongly-connected + // component (SCC), because we have a single InitDefaults* function for the + // SCC. + std::vector fields; + for (const Descriptor* message : + scc_analyzer_.GetSCC(message_generators_[idx]->descriptor_) + ->descriptors) { + ListAllFields(message, &fields); + } + GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, + printer); + + if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) { + NamespaceOpener ns(FileLevelNamespace(file_), printer); + GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer); + } { // package namespace NamespaceOpener ns(Namespace(file_), printer); @@ -411,12 +434,6 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { "// @@protoc_insertion_point(namespace_scope)\n"); } // end package namespace - if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) { - NamespaceOpener ns(FileLevelNamespace(file_), printer); - GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer); - } - - printer->Print( "namespace google {\nnamespace protobuf {\n"); message_generators_[idx]->GenerateSourceInProto2Namespace(printer); @@ -430,15 +447,16 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { void FileGenerator::GenerateGlobalSource(io::Printer* printer) { GenerateSourceIncludes(printer); - GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer); - // TODO(gerbens) Generate tables here - - // Define the code to initialize reflection. This code uses a global - // constructor to register reflection data with the runtime pre-main. - if (HasDescriptorMethods(file_, options_)) { + { NamespaceOpener ns(FileLevelNamespace(file_), printer); - GenerateReflectionInitializationCode(printer); + GenerateTables(printer); + + // Define the code to initialize reflection. This code uses a global + // constructor to register reflection data with the runtime pre-main. + if (HasDescriptorMethods(file_, options_)) { + GenerateReflectionInitializationCode(printer); + } } NamespaceOpener ns(Namespace(file_), printer); @@ -466,7 +484,10 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) { void FileGenerator::GenerateSource(io::Printer* printer) { GenerateSourceIncludes(printer); - GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer); + std::vector fields; + ListAllFields(file_, &fields); + GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, + printer); { NamespaceOpener ns(Namespace(file_), printer); @@ -483,9 +504,25 @@ void FileGenerator::GenerateSource(io::Printer* printer) { { NamespaceOpener ns(FileLevelNamespace(file_), printer); - // Define the initialization code to initialize the default instances. - // This code doesn't use a global constructor. - GenerateInitializationCode(printer); + GenerateTables(printer); + + // Now generate the InitDefaults for each SCC. + for (int i = 0; i < message_generators_.size(); i++) { + if (IsSCCRepresentative(message_generators_[i]->descriptor_)) { + GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), + printer); + } + } + + printer->Print("void InitDefaults() {\n"); + for (int i = 0; i < message_generators_.size(); i++) { + if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; + string scc_name = ClassName(message_generators_[i]->descriptor_); + printer->Print( + " ::google::protobuf::internal::InitSCC(&scc_info_$scc_name$.base);\n", + "scc_name", scc_name); + } + printer->Print("}\n\n"); // Define the code to initialize reflection. This code uses a global // constructor to register reflection data with the runtime pre-main. @@ -560,7 +597,7 @@ class FileGenerator::ForwardDeclarations { ForwardDeclarations* AddOrGetNamespace(const string& ns_name) { ForwardDeclarations*& ns = namespaces_[ns_name]; - if (ns == NULL) { + if (ns == nullptr) { ns = new ForwardDeclarations; } return ns; @@ -648,17 +685,12 @@ class FileGenerator::ForwardDeclarations { end = classes_.end(); it != end; ++it) { const Descriptor* d = it->second; - string extra_class_qualifier; - // "class" is to disambiguate in case there is also a function with this - // name. There is code out there that does this! printer->Print( "template<> " "$dllexport_decl$" - "$class$$classname$* Arena::$func$< $class$$classname$>(Arena*);\n", - "classname", QualifiedClassName(d), - "func", MessageCreateFunction(d), - "class", extra_class_qualifier, - "dllexport_decl", + "$classname$* Arena::CreateMaybeMessage<$classname$>" + "(Arena*);\n", + "classname", QualifiedClassName(d), "dllexport_decl", options.dllexport_decl.empty() ? "" : options.dllexport_decl + " "); } printer->Print( @@ -758,7 +790,6 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { // protobuf_AssignDescriptorsOnce(): The first time it is called, calls // AssignDescriptors(). All later times, waits for the first call to // complete and then returns. - string message_factory = "NULL"; printer->Print( "void protobuf_AssignDescriptors() {\n" // Make sure the file has found its way into the pool. If a descriptor @@ -766,10 +797,9 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { // been called yet, so we call it manually. Note that it's fine if // AddDescriptors() is called multiple times. " AddDescriptors();\n" - " ::google::protobuf::MessageFactory* factory = $factory$;\n" " AssignDescriptors(\n" " \"$filename$\", schemas, file_default_instances, " - "TableStruct::offsets, factory,\n" + "TableStruct::offsets,\n" " $metadata$, $enum_descriptors$, $service_descriptors$);\n", "filename", file_->name(), "metadata", !message_generators_.empty() ? "file_level_metadata" : "NULL", @@ -778,14 +808,13 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { "service_descriptors", HasGenericServices(file_, options_) && file_->service_count() > 0 ? "file_level_service_descriptors" - : "NULL", - "factory", message_factory); + : "NULL"); printer->Print( "}\n" "\n" "void protobuf_AssignDescriptorsOnce() {\n" - " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n" - " ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);\n" + " static ::google::protobuf::internal::once_flag once;\n" + " ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);\n" "}\n" "\n", "filename", file_->name(), "metadata", @@ -795,8 +824,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { "service_descriptors", HasGenericServices(file_, options_) && file_->service_count() > 0 ? "file_level_service_descriptors" - : "NULL", - "factory", message_factory); + : "NULL"); // Only here because of useless string reference that we don't want in // protobuf_AssignDescriptorsOnce, because that is called from all the @@ -891,8 +919,8 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { "}\n" "\n" "void AddDescriptors() {\n" - " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n" - " ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);\n" + " static ::google::protobuf::internal::once_flag once;\n" + " ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);\n" "}\n"); printer->Print( @@ -907,47 +935,16 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { const string scc_name = ClassName(scc->GetRepresentative()); + // We use static and not anonymous namespace because symbol names are + // substantially shorter. printer->Print( - "void InitDefaults$scc_name$Impl() {\n" + "static void InitDefaults$scc_name$() {\n" " GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n" - "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n" - " ::google::protobuf::internal::InitProtobufDefaultsForceUnique();\n" - "#else\n" - " ::google::protobuf::internal::InitProtobufDefaults();\n" - "#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n", - // Force initialization of primitive values we depend on. + , // awkward comma due to macro "scc_name", scc_name); printer->Indent(); - // Call the InitDefaults() methods for all of our dependencies, to make - // sure they get added first. - for (int i = 0; i < scc->children.size(); i++) { - const SCC* child_scc = scc->children[i]; - const FileDescriptor* dependency = child_scc->GetRepresentative()->file(); - // Print the namespace prefix for the dependency. - string file_namespace = FileLevelNamespace(dependency); - std::map variables; - variables["file_namespace"] = file_namespace; - variables["scc_name"] = ClassName(child_scc->GetRepresentative(), false); - bool using_weak_fields = UsingImplicitWeakFields(file_, options_); - if (using_weak_fields) { - // We're building for lite with implicit weak fields, so we need to handle - // the possibility that this InitDefaults function is not linked into the - // binary. Some of these might actually be guaranteed to be non-null since - // we might have a strong reference to the dependency (via a required - // field, for example), but it's simplest to just assume that any of them - // could be null. - printer->Print( - variables, - "if (&$file_namespace$::InitDefaults$scc_name$ != NULL) {\n" - " $file_namespace$::InitDefaults$scc_name$();\n" - "}\n"); - } else { - printer->Print(variables, - "$file_namespace$::InitDefaults$scc_name$();\n"); - } - } // First construct all the necessary default instances. for (int i = 0; i < message_generators_.size(); i++) { @@ -982,23 +979,24 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { } printer->Outdent(); printer->Print("}\n\n"); + printer->Print( - "void InitDefaults$scc_name$() {\n" - " static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n" - " ::google::protobuf::GoogleOnceInit(&once, " - "&InitDefaults$scc_name$Impl);\n" - "}\n\n", - "scc_name", scc_name); + "$dllexport_decl$::google::protobuf::internal::SCCInfo<$size$> " + "scc_info_$scc_name$ =\n" + " {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), " + "$size$, InitDefaults$scc_name$}, {", + "size", SimpleItoa(scc->children.size()), "scc_name", + ClassName(scc->GetRepresentative()), "dllexport_decl", + options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); + for (const SCC* child : scc->children) { + auto repr = child->GetRepresentative(); + printer->Print("\n &$ns$::scc_info_$child$.base,", "ns", + FileLevelNamespace(repr), "child", ClassName(repr)); + } + printer->Print("}};\n\n"); } -void FileGenerator::GenerateInitializationCode(io::Printer* printer) { - // Messages depend on the existence of a default instance, which has to - // initialized properly. The default instances are allocated in the data - // segment, but we can't quite allocate the type directly. The destructors - // cannot run at program exit as this could lead to segfaults in a threaded - // environment. Hence these instances must be inplace constructed at first - // use. - +void FileGenerator::GenerateTables(io::Printer* printer) { if (options_.table_driven_parsing) { // TODO(ckennelly): Gate this with the same options flag to enable // table-driven parsing. @@ -1105,16 +1103,6 @@ void FileGenerator::GenerateInitializationCode(io::Printer* printer) { "};\n" "\n"); } - - // ----------------------------------------------------------------- - // All functionality that need private access. - - // Now generate the InitDefaults for each SCC. - for (int i = 0; i < message_generators_.size(); i++) { - if (IsSCCRepresentative(message_generators_[i]->descriptor_)) { - GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), printer); - } - } } void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) { @@ -1145,8 +1133,8 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" "\n" - "#ifndef PROTOBUF_$filename_identifier$_INCLUDED\n" - "#define PROTOBUF_$filename_identifier$_INCLUDED\n" + "#ifndef PROTOBUF_INCLUDED_$filename_identifier$\n" + "#define PROTOBUF_INCLUDED_$filename_identifier$\n" "\n" "#include \n", "filename", file_->name(), "filename_identifier", filename_identifier); @@ -1156,7 +1144,7 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, void FileGenerator::GenerateBottomHeaderGuard( io::Printer* printer, const string& filename_identifier) { printer->Print( - "#endif // PROTOBUF_$filename_identifier$_INCLUDED\n", + "#endif // PROTOBUF_INCLUDED_$filename_identifier$\n", "filename_identifier", filename_identifier); } @@ -1193,7 +1181,9 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) { "#include \n" "#include \n" "#include \n" - "#include \n"); + "#include \n" + "#include \n"); + if (HasDescriptorMethods(file_, options_)) { printer->Print( @@ -1280,11 +1270,12 @@ void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) { const bool use_system_include = IsWellKnownMessage(file_->dependency(i)); const string& name = file_->dependency(i)->name(); bool public_import = (public_import_names.count(name) != 0); + string basename = StripProto(name); printer->Print( "#include $left$$dependency$.pb.h$right$$iwyu$\n", - "dependency", StripProto(name), + "dependency", basename, "iwyu", (public_import) ? " // IWYU pragma: export" : "", "left", use_system_include ? "<" : "\"", "right", use_system_include ? ">" : "\""); @@ -1318,28 +1309,6 @@ void FileGenerator::GenerateGlobalStateFunctionDeclarations( "void $dllexport_decl$AddDescriptors();\n", "dllexport_decl", options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); } - for (int i = 0; i < message_generators_.size(); i++) { - if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; - string scc_name = ClassName(message_generators_[i]->descriptor_); - // TODO(gerbens) Remove the Impl from header. This is solely because - // it currently still needs to be a friend of the protos. - printer->Print( - "void $dllexport_decl$InitDefaults$scc_name$Impl();\n" - "void $dllexport_decl$InitDefaults$scc_name$();\n", - "scc_name", scc_name, "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); - } - // TODO(gerbens) This is for proto1 interoperability. Remove when proto1 - // is gone. - printer->Print( - "inline void $dllexport_decl$InitDefaults() {\n", "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); - for (int i = 0; i < message_generators_.size(); i++) { - if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; - string scc_name = ClassName(message_generators_[i]->descriptor_); - printer->Print(" InitDefaults$scc_name$();\n", "scc_name", scc_name); - } - printer->Print("}\n"); printer->Print( "} // namespace $file_namespace$\n", "file_namespace", FileLevelNamespace(file_)); @@ -1416,8 +1385,6 @@ void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) { printer->Print(kThinSeparator); printer->Print("\n"); } - // Methods of the dependent base class must always be inline in the header. - message_generators_[i]->GenerateDependentInlineMethods(printer); } } diff --git a/src/google/protobuf/compiler/cpp/cpp_file.h b/src/google/protobuf/compiler/cpp/cpp_file.h index 7e61cbad37..94da9a1456 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.h +++ b/src/google/protobuf/compiler/cpp/cpp_file.h @@ -37,9 +37,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -97,7 +94,7 @@ class FileGenerator { void GenerateSourceDefaultInstance(int idx, io::Printer* printer); void GenerateInitForSCC(const SCC* scc, io::Printer* printer); - void GenerateInitializationCode(io::Printer* printer); + void GenerateTables(io::Printer* printer); void GenerateReflectionInitializationCode(io::Printer* printer); // For other imports, generates their forward-declarations. @@ -176,10 +173,10 @@ class FileGenerator { // These members are just for owning (and thus proper deleting). // Nested (enum/extension)_generators are owned by child messages. - google::protobuf::scoped_array > enum_generators_owner_; - google::protobuf::scoped_array > + std::unique_ptr []> enum_generators_owner_; + std::unique_ptr []> service_generators_owner_; - google::protobuf::scoped_array > + std::unique_ptr []> extension_generators_owner_; // E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}. diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/cpp_generator.cc index 5d8ea30090..20bb8a1a7e 100644 --- a/src/google/protobuf/compiler/cpp/cpp_generator.cc +++ b/src/google/protobuf/compiler/cpp/cpp_generator.cc @@ -36,17 +36,15 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include #include +#include #include #include -#include + namespace google { namespace protobuf { @@ -66,12 +64,6 @@ bool CppGenerator::Generate(const FileDescriptor* file, // ----------------------------------------------------------------- // parse generator options - // TODO(kenton): If we ever have more options, we may want to create a - // class that encapsulates them which we can pass down to all the - // generator classes. Currently we pass dllexport_decl down to all of - // them via the constructors, but we don't want to have to add another - // constructor parameter for every option. - // If the dllexport_decl option is passed to the compiler, we need to write // it in front of every symbol that should be exported if this .proto is // compiled into a Windows DLL. E.g., if the user invokes the protocol @@ -127,11 +119,12 @@ bool CppGenerator::Generate(const FileDescriptor* file, string basename = StripProto(file->name()); + FileGenerator file_generator(file, file_options); // Generate header(s). if (file_options.proto_h) { - google::protobuf::scoped_ptr output( + std::unique_ptr output( generator_context->Open(basename + ".proto.h")); GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( @@ -143,14 +136,14 @@ bool CppGenerator::Generate(const FileDescriptor* file, file_generator.GenerateProtoHeader( &printer, file_options.annotate_headers ? info_path : ""); if (file_options.annotate_headers) { - google::protobuf::scoped_ptr info_output( + std::unique_ptr info_output( generator_context->Open(info_path)); annotations.SerializeToZeroCopyStream(info_output.get()); } } { - google::protobuf::scoped_ptr output( + std::unique_ptr output( generator_context->Open(basename + ".pb.h")); GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( @@ -162,7 +155,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, file_generator.GeneratePBHeader( &printer, file_options.annotate_headers ? info_path : ""); if (file_options.annotate_headers) { - google::protobuf::scoped_ptr info_output( + std::unique_ptr info_output( generator_context->Open(info_path)); annotations.SerializeToZeroCopyStream(info_output.get()); } @@ -172,7 +165,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, if (UsingImplicitWeakFields(file, file_options)) { { // This is the global .cc file, containing enum/services/tables/reflection - google::protobuf::scoped_ptr output( + std::unique_ptr output( generator_context->Open(basename + ".pb.cc")); io::Printer printer(output.get(), '$'); file_generator.GenerateGlobalSource(&printer); @@ -191,7 +184,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, } for (int i = 0; i < num_cc_files; i++) { // TODO(gerbens) Agree on naming scheme. - google::protobuf::scoped_ptr output( + std::unique_ptr output( generator_context->Open(basename + "." + SimpleItoa(i) + ".cc")); io::Printer printer(output.get(), '$'); if (i < file_generator.NumMessages()) { @@ -199,7 +192,7 @@ bool CppGenerator::Generate(const FileDescriptor* file, } } } else { - google::protobuf::scoped_ptr output( + std::unique_ptr output( generator_context->Open(basename + ".pb.cc")); io::Printer printer(output.get(), '$'); file_generator.GenerateSource(&printer); diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc index 172aceddba..163dac0aa0 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc +++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc @@ -42,6 +42,7 @@ #include #include #include +#include #include #include @@ -73,7 +74,7 @@ const char* const kKeywordList[] = { "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", - "mutable", "namespace", "new", "noexcept", "not", "not_eq", "NULL", + "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", @@ -219,24 +220,12 @@ string ReferenceFunctionName(const Descriptor* descriptor) { return QualifiedClassName(descriptor) + "_ReferenceStrong"; } -string DependentBaseClassTemplateName(const Descriptor* descriptor) { - return ClassName(descriptor, false) + "_InternalBase"; -} - string SuperClassName(const Descriptor* descriptor, const Options& options) { return HasDescriptorMethods(descriptor->file(), options) ? "::google::protobuf::Message" : "::google::protobuf::MessageLite"; } -string DependentBaseDownCast() { - return "reinterpret_cast(this)->"; -} - -string DependentBaseConstDownCast() { - return "reinterpret_cast(this)->"; -} - string FieldName(const FieldDescriptor* field) { string result = field->name(); LowerString(&result); @@ -294,60 +283,6 @@ string FieldConstantName(const FieldDescriptor *field) { return result; } -bool IsFieldDependent(const FieldDescriptor* field) { - if (field->containing_oneof() != NULL && - field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - return true; - } - if (field->is_map()) { - const Descriptor* map_descriptor = field->message_type(); - for (int i = 0; i < map_descriptor->field_count(); i++) { - if (IsFieldDependent(map_descriptor->field(i))) { - return true; - } - } - return false; - } - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - return false; - } - if (field->containing_oneof() != NULL) { - // Oneof fields will always be dependent. - // - // This is a unique case for field codegen. Field generators are - // responsible for generating all the field-specific accessor - // functions, except for the clear_*() function; instead, field - // generators produce inline clearing code. - // - // For non-oneof fields, the Message class uses the inline clearing - // code to define the field's clear_*() function, as well as in the - // destructor. For oneof fields, the Message class generates a much - // more complicated clear_*() function, which clears only the oneof - // member that is set, in addition to clearing methods for each of the - // oneof members individually. - // - // Since oneofs do not have their own generator class, the Message code - // generation logic would be significantly complicated in order to - // split dependent and non-dependent manipulation logic based on - // whether the oneof truly needs to be dependent; so, for oneof fields, - // we just assume it (and its constituents) should be manipulated by a - // dependent base class function. - // - // This is less precise than how dependent message-typed fields are - // handled, but the cost is limited to only the generated code for the - // oneof field, which seems like an acceptable tradeoff. - return true; - } - if (field->file() == field->message_type()->file()) { - return false; - } - return true; -} - -string DependentTypeName(const FieldDescriptor* field) { - return "InternalBase_" + field->name() + "_T"; -} - string FieldMessageTypeName(const FieldDescriptor* field) { // Note: The Google-internal version of Protocol Buffers uses this function // as a hook point for hacks to support legacy code. @@ -748,12 +683,17 @@ bool UsingImplicitWeakFields(const FileDescriptor* file, GetOptimizeFor(file, options) == FileOptions::LITE_RUNTIME; } - -bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options) { +bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, + SCCAnalyzer* scc_analyzer) { return UsingImplicitWeakFields(field->file(), options) && field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_required() && !field->is_map() && - field->containing_oneof() == NULL; + field->containing_oneof() == NULL && + !IsWellKnownMessage(field->message_type()->file()) && + // We do not support implicit weak fields between messages in the same + // strongly-connected component. + scc_analyzer->GetSCC(field->containing_type()) != + scc_analyzer->GetSCC(field->message_type()); } struct CompareDescriptors { @@ -920,6 +860,7 @@ void ListAllTypesForServices(const FileDescriptor* fd, } } + } // namespace cpp } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h index 4026d0ed06..eac6512452 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.h +++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h @@ -38,8 +38,9 @@ #include #include #include -#include +#include #include +#include #include #include @@ -53,6 +54,7 @@ namespace cpp { extern const char kThickSeparator[]; extern const char kThinSeparator[]; + // Name space of the proto file. This namespace is such that the string // "::some_name" is the correct fully qualified namespace. // This means if the package is empty the namespace is "", and otherwise @@ -102,19 +104,9 @@ string DefaultInstanceName(const Descriptor* descriptor); // fields. string ReferenceFunctionName(const Descriptor* descriptor); -// Name of the CRTP class template (for use with proto_h). -// This is a class name, like "ProtoName_InternalBase". -string DependentBaseClassTemplateName(const Descriptor* descriptor); - -// Name of the base class: either the dependent base class (for use with -// proto_h) or google::protobuf::Message. +// Name of the base class: google::protobuf::Message or google::protobuf::MessageLite. string SuperClassName(const Descriptor* descriptor, const Options& options); -// Returns a string that down-casts from the dependent base class to the -// derived class. -string DependentBaseDownCast(); -string DependentBaseConstDownCast(); - // Get the (unqualified) name that should be used for this field in C++ code. // The name is coerced to lower-case to emulate proto1 behavior. People // should be using lowercase-with-underscores style for proto field names @@ -141,20 +133,6 @@ inline const Descriptor* FieldScope(const FieldDescriptor* field) { field->extension_scope() : field->containing_type(); } -// Returns true if the given 'field_descriptor' has a message type that is -// a dependency of the file where the field is defined (i.e., the field -// type is defined in a different file than the message holding the field). -// -// This only applies to Message-typed fields. Enum-typed fields may refer -// to an enum in a dependency; however, enums are specified and -// forward-declared with an enum-base, so the definition is not required to -// manipulate the field value. -bool IsFieldDependent(const FieldDescriptor* field_descriptor); - -// Returns the name that should be used for forcing dependent lookup from a -// dependent base class. -string DependentTypeName(const FieldDescriptor* field); - // Returns the fully-qualified type name field->message_type(). Usually this // is just ClassName(field->message_type(), true); string FieldMessageTypeName(const FieldDescriptor* field); @@ -314,6 +292,11 @@ inline string MessageCreateFunction(const Descriptor* d) { return SupportsArenas(d) ? "CreateMessage" : "Create"; } +inline string MakeDefaultName(const FieldDescriptor* field) { + return "_i_give_permission_to_break_this_code_default_" + FieldName(field) + + "_"; +} + bool IsAnyMessage(const FileDescriptor* descriptor); bool IsAnyMessage(const Descriptor* descriptor); @@ -350,13 +333,6 @@ inline std::vector FlattenMessagesInFile( bool HasWeakFields(const Descriptor* desc); bool HasWeakFields(const FileDescriptor* desc); -// Indicates whether we should use implicit weak fields for this file. -bool UsingImplicitWeakFields(const FileDescriptor* file, - const Options& options); - -// Indicates whether to treat this field as implicitly weak. -bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options); - // Returns true if the "required" restriction check should be ignored for the // given field. inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field, @@ -462,11 +438,21 @@ class LIBPROTOC_EXPORT SCCAnalyzer { void AddChildren(SCC* scc); }; +void ListAllFields(const Descriptor* d, + std::vector* fields); void ListAllFields(const FileDescriptor* d, std::vector* fields); void ListAllTypesForServices(const FileDescriptor* fd, std::vector* types); +// Indicates whether we should use implicit weak fields for this file. +bool UsingImplicitWeakFields(const FileDescriptor* file, + const Options& options); + +// Indicates whether to treat this field as implicitly weak. +bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, + SCCAnalyzer* scc_analyzer); + } // namespace cpp } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc index b22c075461..0e485cacbc 100644 --- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc @@ -104,9 +104,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor, MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), - descriptor_(descriptor), - dependent_field_(options.proto_h && IsFieldDependent(descriptor)) { + : FieldGenerator(options), descriptor_(descriptor) { SetMessageVariables(descriptor, &variables_, options); } @@ -202,7 +200,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const { key = "entry->key()"; value = "entry->value()"; printer->Print(variables_, - "::google::protobuf::scoped_ptr<$map_classname$> entry($name$_.NewEntry());\n"); + "::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n"); printer->Print(variables_, "{\n" " ::std::string data;\n" @@ -258,7 +256,7 @@ static void GenerateSerializationLoop(io::Printer* printer, const string& ptr, bool loop_via_iterators) { printer->Print(variables, - StrCat("::google::protobuf::scoped_ptr<$map_classname$> entry;\n", + StrCat("::std::unique_ptr<$map_classname$> entry;\n", loop_header, " {\n").c_str()); printer->Indent(); @@ -365,7 +363,7 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes( "\n" "if ($deterministic$ &&\n" " this->$name$().size() > 1) {\n" - " ::google::protobuf::scoped_array items(\n" + " ::std::unique_ptr items(\n" " new SortItem[this->$name$().size()]);\n" " typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::size_type size_type;\n" " size_type n = 0;\n" @@ -402,7 +400,7 @@ GenerateByteSize(io::Printer* printer) const { "total_size += $tag_size$ *\n" " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" "{\n" - " ::google::protobuf::scoped_ptr<$map_classname$> entry;\n" + " ::std::unique_ptr<$map_classname$> entry;\n" " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" " it = this->$name$().begin();\n" " it != this->$name$().end(); ++it) {\n"); diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.h b/src/google/protobuf/compiler/cpp/cpp_map_field.h index 88e3b464e0..0d54f0ea47 100644 --- a/src/google/protobuf/compiler/cpp/cpp_map_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_map_field.h @@ -66,7 +66,6 @@ class MapFieldGenerator : public FieldGenerator { io::Printer* printer, const std::map& variables) const; const FieldDescriptor* descriptor_; - const bool dependent_field_; std::map variables_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc index 9b2f090e1a..8c2336af1b 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.cc +++ b/src/google/protobuf/compiler/cpp/cpp_message.cc @@ -38,9 +38,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -49,9 +46,9 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -60,6 +57,7 @@ #include + namespace google { namespace protobuf { namespace compiler { @@ -440,13 +438,12 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor, index_in_file_messages_(index_in_file_messages), classname_(ClassName(descriptor, false)), options_(options), - field_generators_(descriptor, options), + field_generators_(descriptor, options, scc_analyzer), max_has_bit_index_(0), enum_generators_( - new google::protobuf::scoped_ptr[descriptor->enum_type_count()]), - extension_generators_(new google::protobuf::scoped_ptr< + new std::unique_ptr[descriptor->enum_type_count()]), + extension_generators_(new std::unique_ptr< ExtensionGenerator>[descriptor->extension_count()]), - use_dependent_base_(false), num_weak_fields_(0), message_layout_helper_(new PaddingOptimizer()), scc_analyzer_(scc_analyzer) { @@ -492,13 +489,6 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor, if (descriptor->field(i)->is_required()) { ++num_required_fields_; } - if (options.proto_h && IsFieldDependent(descriptor->field(i))) { - use_dependent_base_ = true; - } - } - if (options.proto_h && descriptor->oneof_decl_count() > 0) { - // Always make oneofs dependent. - use_dependent_base_ = true; } table_driven_ = TableDrivenParsingEnabled(descriptor_, options_); @@ -538,22 +528,6 @@ void MessageGenerator::FillMessageForwardDeclarations( (*class_names)[classname_] = descriptor_; } -void MessageGenerator:: -GenerateDependentFieldAccessorDeclarations(io::Printer* printer) { - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - PrintFieldComment(printer, field); - - std::map vars; - SetCommonFieldVariables(field, &vars, options_); - - // Generate type-specific accessor declarations. - field_generators_.get(field).GenerateDependentAccessorDeclarations(printer); - printer->Print("\n"); - } -} - void MessageGenerator:: GenerateFieldAccessorDeclarations(io::Printer* printer) { // optimized_fields_ does not contain fields where @@ -585,21 +559,6 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) { SetCommonFieldVariables(field, &vars, options_); vars["constant_name"] = FieldConstantName(field); - bool dependent_field = use_dependent_base_ && IsFieldDependent(field); - if (dependent_field && - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !field->is_map()) { - // If this field is dependent, the dependent base class determines - // the message type from the derived class (which is a template - // parameter). This typedef is for that: - printer->Print( - "private:\n" - "typedef $field_type$ $dependent_type$;\n" - "public:\n", - "field_type", FieldMessageTypeName(field), - "dependent_type", DependentTypeName(field)); - } - if (field->is_repeated()) { printer->Print(vars, "$deprecated_attr$int ${$$name$_size$}$() const;\n"); printer->Annotate("{", "}", field); @@ -637,6 +596,7 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) { for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { printer->Print( + "void clear_$oneof_name$();\n" "$camel_oneof_name$Case $oneof_name$_case() const;\n", "camel_oneof_name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true), @@ -644,32 +604,6 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) { } } -void MessageGenerator:: -GenerateDependentFieldAccessorDefinitions(io::Printer* printer) { - if (!use_dependent_base_) return; - - printer->Print("// $classname$\n\n", "classname", - DependentBaseClassTemplateName(descriptor_)); - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - if (field->options().weak()) continue; - - PrintFieldComment(printer, field); - // Generate type-specific accessors. - field_generators_.get(field) - .GenerateDependentInlineAccessorDefinitions(printer); - - printer->Print("\n"); - } - - // Generate has_$name$() and clear_has_$name$() functions for oneofs - // Similar to other has-bits, these must always be in the header if we - // are using a dependent base class. - GenerateOneofHasBits(printer); -} - void MessageGenerator:: GenerateSingularFieldHasBits(const FieldDescriptor* field, std::map vars, @@ -812,18 +746,6 @@ GenerateFieldAccessorDefinitions(io::Printer* printer) { std::map vars; SetCommonFieldVariables(field, &vars, options_); - if (use_dependent_base_ && IsFieldDependent(field)) { - vars["tmpl"] = "template\n"; - vars["dependent_classname"] = - DependentBaseClassTemplateName(descriptor_) + ""; - vars["this_message"] = "reinterpret_cast(this)->"; - vars["this_const_message"] = "reinterpret_cast(this)->"; - } else { - vars["tmpl"] = ""; - vars["dependent_classname"] = vars["classname"]; - vars["this_message"] = ""; - vars["this_const_message"] = ""; - } // Generate has_$name$() or $name$_size(). if (field->is_repeated()) { @@ -851,42 +773,8 @@ GenerateFieldAccessorDefinitions(io::Printer* printer) { printer->Print("\n"); } - if (!use_dependent_base_) { - // Generate has_$name$() and clear_has_$name$() functions for oneofs - // If we aren't using a dependent base, they can be with the other functions - // that are #ifdef-guarded. - GenerateOneofHasBits(printer); - } -} - -void MessageGenerator:: -GenerateDependentBaseClassDefinition(io::Printer* printer) { - if (!use_dependent_base_) { - return; - } - - std::map vars; - vars["classname"] = DependentBaseClassTemplateName(descriptor_); - vars["full_name"] = descriptor_->full_name(); - vars["superclass"] = SuperClassName(descriptor_, options_); - - printer->Print(vars, - "template \n" - "class $classname$ : public $superclass$ " - "/* @@protoc_insertion_point(dep_base_class_definition:$full_name$) */ {\n" - " public:\n"); - printer->Indent(); - - printer->Print(vars, - "$classname$() {}\n" - "virtual ~$classname$() {}\n" - "\n"); - - // Generate dependent accessor methods for all fields. - GenerateDependentFieldAccessorDeclarations(printer); - - printer->Outdent(); - printer->Print("};\n"); + // Generate has_$name$() and clear_has_$name$() functions for oneofs. + GenerateOneofHasBits(printer); } void MessageGenerator:: @@ -919,7 +807,7 @@ GenerateClassDefinition(io::Printer* printer) { "$classname$*>(&_$classname$_default_instance_); }\n"); if (HasDescriptorMethods(descriptor_->file(), options_)) { printer->Print( - " void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL;\n" + " void MergeFrom(const ::google::protobuf::Message& other) final;\n" " ::google::protobuf::Metadata GetMetadata() const;\n" "};\n"); } else { @@ -927,10 +815,6 @@ GenerateClassDefinition(io::Printer* printer) { } return; } - if (use_dependent_base_) { - GenerateDependentBaseClassDefinition(printer); - printer->Print("\n"); - } std::map vars; vars["classname"] = classname_; @@ -942,20 +826,12 @@ GenerateClassDefinition(io::Printer* printer) { } else { vars["dllexport"] = options_.dllexport_decl + " "; } - if (use_dependent_base_) { - vars["superclass"] = - DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">"; - } else { - vars["superclass"] = SuperClassName(descriptor_, options_); - } + vars["superclass"] = SuperClassName(descriptor_, options_); printer->Print(vars, "class $dllexport$$classname$ : public $superclass$ " "/* @@protoc_insertion_point(class_definition:$full_name$) */ " "{\n"); printer->Annotate("classname", descriptor_); - if (use_dependent_base_) { - printer->Print(vars, " friend class $superclass$;\n"); - } printer->Print(" public:\n"); printer->Indent(); @@ -1016,10 +892,10 @@ GenerateClassDefinition(io::Printer* printer) { // virtual method version of GetArenaNoVirtual(), required for generic dispatch given a // MessageLite* (e.g., in RepeatedField::AddAllocated()). printer->Print( - "inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {\n" + "inline ::google::protobuf::Arena* GetArena() const final {\n" " return GetArenaNoVirtual();\n" "}\n" - "inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {\n" + "inline void* GetMaybeArenaPointer() const final {\n" " return MaybeArenaPtr();\n" "}\n"); } @@ -1071,7 +947,7 @@ GenerateClassDefinition(io::Printer* printer) { " return reinterpret_cast(\n" " &_$classname$_default_instance_);\n" "}\n" - "static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =\n" + "static constexpr int kIndexInFileMessages =\n" " $message_index$;\n" "\n"); @@ -1091,12 +967,13 @@ GenerateClassDefinition(io::Printer* printer) { "template bool Is() const {\n" " return _any_metadata_.Is();\n" "}\n" + "static bool ParseAnyTypeUrl(const string& type_url,\n" + " string* full_type_name);\n" "\n"); } - vars["new_final"] = " PROTOBUF_FINAL"; + vars["new_final"] = " final"; - vars["create_func"] = MessageCreateFunction(descriptor_); printer->Print(vars, "void Swap($classname$* other);\n" "friend void swap($classname$& a, $classname$& b) {\n" @@ -1106,32 +983,32 @@ GenerateClassDefinition(io::Printer* printer) { "// implements Message ----------------------------------------------\n" "\n" "inline $classname$* New() const$new_final$ {\n" - " return ::google::protobuf::Arena::$create_func$<$classname$>(NULL);\n" + " return CreateMaybeMessage<$classname$>(NULL);\n" "}\n" "\n" "$classname$* New(::google::protobuf::Arena* arena) const$new_final$ {\n" - " return ::google::protobuf::Arena::$create_func$<$classname$>(arena);\n" + " return CreateMaybeMessage<$classname$>(arena);\n" "}\n"); // For instances that derive from Message (rather than MessageLite), some // methods are virtual and should be marked as final. string use_final = HasDescriptorMethods(descriptor_->file(), options_) ? - " PROTOBUF_FINAL" : ""; + " final" : ""; if (HasGeneratedMethods(descriptor_->file(), options_)) { if (HasDescriptorMethods(descriptor_->file(), options_)) { printer->Print(vars, - "void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;\n" - "void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;\n"); + "void CopyFrom(const ::google::protobuf::Message& from) final;\n" + "void MergeFrom(const ::google::protobuf::Message& from) final;\n"); } else { printer->Print(vars, "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)\n" - " PROTOBUF_FINAL;\n"); + " final;\n"); } - vars["clear_final"] = " PROTOBUF_FINAL"; - vars["is_initialized_final"] = " PROTOBUF_FINAL"; - vars["merge_partial_final"] = " PROTOBUF_FINAL"; + vars["clear_final"] = " final"; + vars["is_initialized_final"] = " final"; + vars["merge_partial_final"] = " final"; printer->Print( vars, @@ -1140,7 +1017,7 @@ GenerateClassDefinition(io::Printer* printer) { "void Clear()$clear_final$;\n" "bool IsInitialized() const$is_initialized_final$;\n" "\n" - "size_t ByteSizeLong() const PROTOBUF_FINAL;\n" + "size_t ByteSizeLong() const final;\n" "bool MergePartialFromCodedStream(\n" " ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n"); if (!options_.table_driven_serialization || @@ -1148,7 +1025,7 @@ GenerateClassDefinition(io::Printer* printer) { printer->Print( "void SerializeWithCachedSizes(\n" " ::google::protobuf::io::CodedOutputStream* output) const " - "PROTOBUF_FINAL;\n"); + "final;\n"); } // DiscardUnknownFields() is implemented in message.cc using reflections. We // need to implement this function in generated code for messages. @@ -1160,19 +1037,18 @@ GenerateClassDefinition(io::Printer* printer) { if (HasFastArraySerialization(descriptor_->file(), options_)) { printer->Print( "::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;\n"); + " bool deterministic, ::google::protobuf::uint8* target) const final;\n"); } } printer->Print( - "int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }\n" - "private:\n" - "void SharedCtor();\n" - "void SharedDtor();\n" - "void SetCachedSize(int size) const$final$;\n" - "void InternalSwap($classname$* other);\n", - "classname", classname_, - "final", use_final); + "int GetCachedSize() const final { return _cached_size_.Get(); }" + "\n\nprivate:\n" + "void SharedCtor();\n" + "void SharedDtor();\n" + "void SetCachedSize(int size) const$final$;\n" + "void InternalSwap($classname$* other);\n", + "classname", classname_, "final", use_final); if (SupportsArenas(descriptor_)) { printer->Print( // TODO(gerbens) Make this private! Currently people are deriving from @@ -1212,11 +1088,11 @@ GenerateClassDefinition(io::Printer* printer) { if (HasDescriptorMethods(descriptor_->file(), options_)) { printer->Print( - "::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;\n" + "::google::protobuf::Metadata GetMetadata() const final;\n" "\n"); } else { printer->Print( - "::std::string GetTypeName() const PROTOBUF_FINAL;\n" + "::std::string GetTypeName() const final;\n" "\n"); } @@ -1295,7 +1171,6 @@ GenerateClassDefinition(io::Printer* printer) { for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { printer->Print( "inline bool has_$oneof_name$() const;\n" - "void clear_$oneof_name$();\n" "inline void clear_has_$oneof_name$();\n\n", "oneof_name", descriptor_->oneof_decl(i)->name()); } @@ -1313,7 +1188,8 @@ GenerateClassDefinition(io::Printer* printer) { bool need_to_emit_cached_size = true; // TODO(kenton): Make _cached_size_ an atomic when C++ supports it. - const string cached_size_decl = "mutable int _cached_size_;\n"; + const string cached_size_decl = + "mutable ::google::protobuf::internal::CachedSize _cached_size_;\n"; const size_t sizeof_has_bits = HasBitsSize(); const string has_bits_decl = sizeof_has_bits == 0 ? "" : @@ -1423,31 +1299,16 @@ GenerateClassDefinition(io::Printer* printer) { // The TableStruct struct needs access to the private parts, in order to // construct the offsets of all members. - // TODO(gerbens) Remove the friend for InitDefaults. - printer->Print( - "friend struct ::$file_namespace$::TableStruct;\n" - "friend void ::$file_namespace$::InitDefaults$scc_name$Impl();\n", - // Vars. - "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); + printer->Print("friend struct ::$file_namespace$::TableStruct;\n", + // Vars. + "scc_name", scc_name_, "file_namespace", + FileLevelNamespace(descriptor_)); printer->Outdent(); printer->Print("};"); GOOGLE_DCHECK(!need_to_emit_cached_size); } -void MessageGenerator:: -GenerateDependentInlineMethods(io::Printer* printer) { - if (IsMapEntryMessage(descriptor_)) return; - for (int i = 0; i < descriptor_->field_count(); i++) { - if (descriptor_->field(i)->options().weak()) { - field_generators_.get(descriptor_->field(i)) - .GenerateDependentInlineAccessorDefinitions(printer); - } - } - GenerateDependentFieldAccessorDefinitions(printer); -} - void MessageGenerator:: GenerateInlineMethods(io::Printer* printer) { if (IsMapEntryMessage(descriptor_)) return; @@ -1603,7 +1464,8 @@ uint32 CalculateType(uint32 type, uint32 type_class) { return (type - 1) + type_class * 20; } -uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) { +uint32 CalcFieldNum(const FieldGenerator&, const FieldDescriptor* field, + const Options& options) { bool is_a_map = IsMapEntryMessage(field->containing_type()); int type = field->type(); if (field->containing_oneof()) { @@ -1624,9 +1486,16 @@ uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) { #else // We need to calculate for each field what function the table driven code // should use to serialize it. This returns the index in a lookup table. -uint32 CalcFieldNum(const FieldDescriptor* field, const Options& options) { +uint32 CalcFieldNum(const FieldGenerator& generator, + const FieldDescriptor* field, const Options& options) { bool is_a_map = IsMapEntryMessage(field->containing_type()); int type = field->type(); + if (type == FieldDescriptor::TYPE_STRING || + type == FieldDescriptor::TYPE_BYTES) { + if (generator.IsInlined()) { + type = internal::FieldMetadata::kInlinedType; + } + } if (field->containing_oneof()) { return internal::FieldMetadata::CalculateType( type, internal::FieldMetadata::kOneOf); @@ -1668,6 +1537,8 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { if (IsMapEntryMessage(descriptor_)) { for (int i = 0; i < 2; i++) { const FieldDescriptor* field = sorted[i]; + const FieldGenerator& generator = field_generators_.get(field); + uint32 tag = internal::WireFormatLite::MakeTag( field->number(), WireFormat::WireTypeForFieldType(field->type())); @@ -1676,7 +1547,7 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { vars["field_name"] = FieldName(field); vars["tag"] = SimpleItoa(tag); vars["hasbit"] = SimpleItoa(i); - vars["type"] = SimpleItoa(CalcFieldNum(field, options_)); + vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); vars["ptr"] = "NULL"; if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { GOOGLE_CHECK(!IsMapEntryMessage(field->message_type())); @@ -1765,7 +1636,9 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { SimpleItoa(FindMessageIndexInFile(field->message_type())); } } - vars["type"] = SimpleItoa(CalcFieldNum(field, options_)); + + const FieldGenerator& generator = field_generators_.get(field); + vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); if (field->options().weak()) { @@ -1912,6 +1785,11 @@ GenerateClassMethods(io::Printer* printer) { "bool $classname$::UnpackTo(::google::protobuf::Message* message) const {\n" " return _any_metadata_.UnpackTo(message);\n" "}\n" + "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n" + " string* full_type_name) {\n" + " return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,\n" + " full_type_name);\n" + "}\n" "\n", "classname", classname_); } @@ -2049,16 +1927,26 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { } processing_type = static_cast(field->type()); + const FieldGenerator& generator = field_generators_.get(field); if (field->type() == FieldDescriptor::TYPE_STRING) { switch (EffectiveStringCType(field)) { case FieldOptions::STRING: - default: + default: { + if (generator.IsInlined()) { + processing_type = internal::TYPE_STRING_INLINED; + break; + } break; + } } } else if (field->type() == FieldDescriptor::TYPE_BYTES) { switch (EffectiveStringCType(field)) { case FieldOptions::STRING: default: + if (generator.IsInlined()) { + processing_type = internal::TYPE_BYTES_INLINED; + break; + } break; } } @@ -2093,7 +1981,7 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { "{\n" " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" " $classname$, $name$_),\n" - " static_cast< ::google::protobuf::uint32>($presence$),\n" + " static_cast<::google::protobuf::uint32>($presence$),\n" " $nwtype$, $pwtype$, $ptype$, $tag_size$\n" "},\n"); } @@ -2150,20 +2038,7 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { printer->Print( vars, "{::google::protobuf::internal::AuxillaryParseTableField::message_aux{\n" - " &$ns$::_$classname$_default_instance_,\n"); - - bool dont_emit_table = - !TableDrivenParsingEnabled(field->message_type(), options_); - - if (dont_emit_table) { - printer->Print(" NULL,\n"); - } else { - printer->Print(vars, - " ::$file_namespace$::TableStruct::schema +\n" - " $ns$::$classname$::kIndexInFileMessages,\n"); - } - - printer->Print("}},\n"); + " &$ns$::_$classname$_default_instance_}},\n"); last_field_number++; break; } @@ -2174,7 +2049,7 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { field->default_value_string().empty() ? "&::google::protobuf::internal::fixed_address_empty_string" : "&" + Namespace(field) + " ::" + classname_ + - "::_default_" + FieldName(field) + "_"; + "::" + MakeDefaultName(field); break; case FieldOptions::CORD: case FieldOptions::STRING_PIECE: @@ -2245,14 +2120,20 @@ std::pair MessageGenerator::GenerateOffsets( for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); if (field->containing_oneof() || field->options().weak()) { - printer->Print("offsetof($classname$DefaultTypeInternal, $name$_),\n", + printer->Print("offsetof($classname$DefaultTypeInternal, $name$_)", "classname", full_classname, "name", FieldName(field)); } else { printer->Print( - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "$name$_),\n", + "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_)", "classname", full_classname, "name", FieldName(field)); } + + uint32 tag = field_generators_.get(field).CalculateFieldTag(); + if (tag != 0) { + printer->Print(" | $tag$", "tag", SimpleItoa(tag)); + } + + printer->Print(",\n"); } for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { @@ -2286,15 +2167,6 @@ GenerateSharedConstructorCode(io::Printer* printer) { "classname", classname_); printer->Indent(); - bool need_to_clear_cached_size = true; - // We reproduce the logic used for laying out _cached_sized_ in the class - // definition, as to initialize it in-order. - if (HasFieldPresence(descriptor_->file()) && - (HasBitsSize() % 8) != 0) { - printer->Print("_cached_size_ = 0;\n"); - need_to_clear_cached_size = false; - } - std::vector processed(optimized_order_.size(), false); GenerateConstructorBody(printer, processed, false); @@ -2304,10 +2176,6 @@ GenerateSharedConstructorCode(io::Printer* printer) { "oneof_name", descriptor_->oneof_decl(i)->name()); } - if (need_to_clear_cached_size) { - printer->Print("_cached_size_ = 0;\n"); - } - printer->Outdent(); printer->Print("}\n\n"); } @@ -2491,12 +2359,7 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer, void MessageGenerator:: GenerateStructors(io::Printer* printer) { string superclass; - if (use_dependent_base_) { - superclass = - DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">"; - } else { - superclass = SuperClassName(descriptor_, options_); - } + superclass = SuperClassName(descriptor_, options_); string initializer_with_arena = superclass + "()"; if (descriptor_->extension_range_count() > 0) { @@ -2528,15 +2391,14 @@ GenerateStructors(io::Printer* printer) { initializer_null += ", _any_metadata_(&type_url_, &value_)"; } if (num_weak_fields_ > 0) { - initializer_null += ", _weak_field_map_(NULL)"; + initializer_null += ", _weak_field_map_(nullptr)"; } printer->Print( "$classname$::$classname$()\n" " : $initializer$ {\n" - " if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {\n" - " ::$file_namespace$::InitDefaults$scc_name$();\n" - " }\n" + " ::google::protobuf::internal::InitSCC(\n" + " &$file_namespace$::scc_info_$scc_name$.base);\n" " SharedCtor();\n" " // @@protoc_insertion_point(constructor:$full_name$)\n" "}\n", @@ -2548,7 +2410,9 @@ GenerateStructors(io::Printer* printer) { printer->Print( "$classname$::$classname$(::google::protobuf::Arena* arena)\n" " : $initializer$ {\n" - " ::$file_namespace$::InitDefaults$scc_name$();\n" + " " + "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$." + "base);\n" " SharedCtor();\n" " RegisterArenaDtor(arena);\n" " // @@protoc_insertion_point(arena_constructor:$full_name$)\n" @@ -2589,16 +2453,6 @@ GenerateStructors(io::Printer* printer) { printer->Print(",\n_has_bits_(from._has_bits_)"); } - bool need_to_emit_cached_size = true; - const string cached_size_decl = ",\n_cached_size_(0)"; - // We reproduce the logic used for laying out _cached_sized_ in the class - // definition, as to initialize it in-order. - if (HasFieldPresence(descriptor_->file()) && - (HasBitsSize() % 8) != 0) { - printer->Print(cached_size_decl.c_str()); - need_to_emit_cached_size = false; - } - std::vector processed(optimized_order_.size(), false); for (int i = 0; i < optimized_order_.size(); ++i) { const FieldDescriptor* field = optimized_order_[i]; @@ -2613,11 +2467,6 @@ GenerateStructors(io::Printer* printer) { "name", FieldName(field)); } - if (need_to_emit_cached_size) { - printer->Print(cached_size_decl.c_str()); - need_to_emit_cached_size = false; - } - if (IsAnyMessage(descriptor_)) { printer->Print(",\n_any_metadata_(&type_url_, &value_)"); } @@ -2702,12 +2551,10 @@ GenerateStructors(io::Printer* printer) { // Generate SetCachedSize. printer->Print( - "void $classname$::SetCachedSize(int size) const {\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - " _cached_size_ = size;\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "}\n", - "classname", classname_); + "void $classname$::SetCachedSize(int size) const {\n" + " _cached_size_.Set(size);\n" + "}\n", + "classname", classname_); // Only generate this member if it's not disabled. if (HasDescriptorMethods(descriptor_->file(), options_) && @@ -2726,7 +2573,9 @@ GenerateStructors(io::Printer* printer) { printer->Print( "const $classname$& $classname$::default_instance() {\n" - " ::$file_namespace$::InitDefaults$scc_name$();\n" + " " + "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$.base)" + ";\n" " return *internal_default_instance();\n" "}\n\n", "classname", classname_, "scc_name", scc_name_, "file_namespace", @@ -2737,7 +2586,7 @@ void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) { printer->Print( "template<> " "GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE " - "$classname$* Arena::$create_func$< $classname$ >(Arena* arena) {\n" + "$classname$* Arena::CreateMaybeMessage< $classname$ >(Arena* arena) {\n" " return Arena::$create_func$Internal< $classname$ >(arena);\n" "}\n", "classname", QualifiedClassName(descriptor_), @@ -2823,10 +2672,10 @@ GenerateClear(io::Printer* printer) { chunks.push_back(chunks_frag[i]); const FieldDescriptor* field = chunks_frag[i].front(); const FieldDescriptor* next_field = - (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : NULL; + (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : nullptr; if (CanInitializeByZeroing(field) && (chunks_frag[i].size() == 1 || unconditional_budget < 0) && - next_field != NULL && + next_field != nullptr && has_bit_indices_[field->index()] / 8 == has_bit_indices_[next_field->index()] / 8) { GOOGLE_CHECK(!CanInitializeByZeroing(next_field)); @@ -3111,7 +2960,6 @@ GenerateSwap(io::Printer* printer) { printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\n"); - printer->Print("swap(_cached_size_, other->_cached_size_);\n"); if (descriptor_->extension_range_count() > 0) { printer->Print("_extensions_.Swap(&other->_extensions_);\n"); } @@ -3492,8 +3340,12 @@ GenerateMergeFromCodedStream(io::Printer* printer) { printer->Print("for (;;) {\n"); printer->Indent(); - uint32 maxtag = descriptor_->field_count() == 0 ? 0 : - WireFormat::MakeTag(ordered_fields[descriptor_->field_count() - 1]); + // To calculate the maximum tag to expect, we look at the highest-numbered + // field. We need to be prepared to handle more than one wire type if that + // field is a packable repeated field, so to simplify things we assume the + // highest possible wire type of 5. + uint32 maxtag = + ordered_fields.empty() ? 0 : ordered_fields.back()->number() * 8 + 5; const int kCutoff0 = 127; // fits in 1-byte varint const int kCutoff1 = (127 << 7) + 127; // fits in 2-byte varint @@ -3511,6 +3363,15 @@ GenerateMergeFromCodedStream(io::Printer* printer) { break; } } + + for (int i = 0; i < parent->extension_count(); i++) { + const FieldDescriptor* field = parent->extension(i); + if (field->type() == FieldDescriptor::TYPE_GROUP && + field->message_type() == descriptor_) { + capture_last_tag = true; + break; + } + } } for (int i = 0; i < descriptor_->file()->extension_count(); i++) { @@ -3522,7 +3383,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) { } } - printer->Print("::std::pair< ::google::protobuf::uint32, bool> p = " + printer->Print("::std::pair<::google::protobuf::uint32, bool> p = " "input->ReadTagWithCutoffNoLastTag($max$u);\n" "tag = p.first;\n" "if (!p.second) goto handle_unusual;\n", @@ -3621,7 +3482,6 @@ GenerateMergeFromCodedStream(io::Printer* printer) { printer->Outdent(); printer->Print("}\n\n"); } - printer->Print("default: {\n"); printer->Indent(); } @@ -4012,7 +3872,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { // Merge the fields and the extension ranges, both sorted by field number. { LazySerializerEmitter e(this, printer, to_array); - const FieldDescriptor* last_weak_field = NULL; + const FieldDescriptor* last_weak_field = nullptr; int i, j; for (i = 0, j = 0; i < ordered_fields.size() || j < sorted_extensions.size();) { @@ -4024,16 +3884,16 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { last_weak_field = field; PrintFieldComment(printer, field); } else { - if (last_weak_field != NULL) { + if (last_weak_field != nullptr) { e.Emit(last_weak_field); - last_weak_field = NULL; + last_weak_field = nullptr; } e.Emit(field); } } else { - if (last_weak_field != NULL) { + if (last_weak_field != nullptr) { e.Emit(last_weak_field); - last_weak_field = NULL; + last_weak_field = nullptr; } e.Flush(); GenerateSerializeOneExtensionRange(printer, @@ -4041,7 +3901,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { to_array); } } - if (last_weak_field != NULL) { + if (last_weak_field != nullptr) { e.Emit(last_weak_field); } } @@ -4103,8 +3963,9 @@ static string ConditionalToCheckBitmasks(const std::vector& masks) { } GOOGLE_CHECK(!parts.empty()); // If we have multiple parts, each expected to be 0, then bitwise-or them. - string result = parts.size() == 1 ? parts[0] : - StrCat("(", Join(parts, "\n | "), ")"); + string result = parts.size() == 1 + ? parts[0] + : StrCat("(", Join(parts, "\n | "), ")"); return result + " == 0"; } @@ -4117,20 +3978,19 @@ GenerateByteSize(io::Printer* printer) { SetUnknkownFieldsVariable(descriptor_, options_, &vars); vars["classname"] = classname_; vars["full_name"] = descriptor_->full_name(); - printer->Print(vars, - "size_t $classname$::ByteSizeLong() const {\n" - "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n" - " size_t total_size = _extensions_.MessageSetByteSize();\n" - " if ($have_unknown_fields$) {\n" - " total_size += ::google::protobuf::internal::WireFormat::\n" - " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n" - " }\n" - " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - " _cached_size_ = cached_size;\n" - " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - " return total_size;\n" - "}\n"); + printer->Print( + vars, + "size_t $classname$::ByteSizeLong() const {\n" + "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n" + " size_t total_size = _extensions_.MessageSetByteSize();\n" + " if ($have_unknown_fields$) {\n" + " total_size += ::google::protobuf::internal::WireFormat::\n" + " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n" + " }\n" + " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" + " SetCachedSize(cached_size);\n" + " return total_size;\n" + "}\n"); return; } @@ -4362,17 +4222,18 @@ GenerateByteSize(io::Printer* printer) { printer->Print("total_size += _weak_field_map_.ByteSizeLong();\n"); } - // We update _cached_size_ even though this is a const method. In theory, - // this is not thread-compatible, because concurrent writes have undefined - // results. In practice, since any concurrent writes will be writing the - // exact same value, it works on all common processors. In a future version - // of C++, _cached_size_ should be made into an atomic. + // We update _cached_size_ even though this is a const method. Because + // const methods might be called concurrently this needs to be atomic + // operations or the program is undefined. In practice, since any concurrent + // writes will be writing the exact same value, normal writes will work on + // all common processors. We use a dedicated wrapper class to abstract away + // the underlying atomic. This makes it easier on platforms where even relaxed + // memory order might have perf impact to replace it with ordinary loads and + // stores. printer->Print( - "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - "_cached_size_ = cached_size;\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "return total_size;\n"); + "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" + "SetCachedSize(cached_size);\n" + "return total_size;\n"); printer->Outdent(); printer->Print("}\n"); @@ -4421,7 +4282,7 @@ GenerateIsInitialized(io::Printer* printer) { !ShouldIgnoreRequiredFieldCheck(field, options_) && scc_analyzer_->HasRequiredFields(field->message_type())) { if (field->is_repeated()) { - if (IsImplicitWeakField(field, options_)) { + if (IsImplicitWeakField(field, options_, scc_analyzer_)) { printer->Print( "if (!::google::protobuf::internal::AllAreInitializedWeak(this->$name$_))" " return false;\n", diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h index 06e2030b51..ca2ca2c90a 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.h +++ b/src/google/protobuf/compiler/cpp/cpp_message.h @@ -36,9 +36,6 @@ #define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -87,9 +84,6 @@ class MessageGenerator { // file). void GenerateInlineMethods(io::Printer* printer); - // Dependent methods are always inline. - void GenerateDependentInlineMethods(io::Printer* printer); - // Source file stuff. // Generate extra fields @@ -111,10 +105,7 @@ class MessageGenerator { private: // Generate declarations and definitions of accessors for fields. - void GenerateDependentBaseClassDefinition(io::Printer* printer); - void GenerateDependentFieldAccessorDeclarations(io::Printer* printer); void GenerateFieldAccessorDeclarations(io::Printer* printer); - void GenerateDependentFieldAccessorDefinitions(io::Printer* printer); void GenerateFieldAccessorDefinitions(io::Printer* printer); // Generate the table-driven parsing array. Returns the number of entries @@ -222,15 +213,14 @@ class MessageGenerator { std::vector optimized_order_; std::vector has_bit_indices_; int max_has_bit_index_; - google::protobuf::scoped_array > enum_generators_; - google::protobuf::scoped_array > extension_generators_; + std::unique_ptr []> enum_generators_; + std::unique_ptr []> extension_generators_; int num_required_fields_; - bool use_dependent_base_; int num_weak_fields_; // table_driven_ indicates the generated message uses table-driven parsing. bool table_driven_; - google::protobuf::scoped_ptr message_layout_helper_; + std::unique_ptr message_layout_helper_; SCCAnalyzer* scc_analyzer_; string scc_name_; diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/cpp_message_field.cc index 530a6392ea..c1e15c5232 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc @@ -70,17 +70,16 @@ string ReinterpretCast(const string& type, const string& expression, } void SetMessageVariables(const FieldDescriptor* descriptor, - std::map* variables, - const Options& options) { + const Options& options, bool implicit_weak, + std::map* variables) { SetCommonFieldVariables(descriptor, variables, options); (*variables)["type"] = FieldMessageTypeName(descriptor); - (*variables)["casted_member"] = - ReinterpretCast((*variables)["type"] + "*", (*variables)["name"] + "_", - IsImplicitWeakField(descriptor, options)); + (*variables)["casted_member"] = ReinterpretCast( + (*variables)["type"] + "*", (*variables)["name"] + "_", implicit_weak); (*variables)["type_default_instance"] = DefaultInstanceName(descriptor->message_type()); (*variables)["type_reference_function"] = - IsImplicitWeakField(descriptor, options) + implicit_weak ? (" " + ReferenceFunctionName(descriptor->message_type()) + "();\n") : ""; (*variables)["stream_writer"] = @@ -94,8 +93,6 @@ void SetMessageVariables(const FieldDescriptor* descriptor, SafeFunctionName(descriptor->containing_type(), descriptor, "release_"); (*variables)["full_name"] = descriptor->full_name(); - (*variables)["create_func"] = - MessageCreateFunction(descriptor->message_type()); } } // namespace @@ -103,11 +100,13 @@ void SetMessageVariables(const FieldDescriptor* descriptor, // =================================================================== MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) + const Options& options, + SCCAnalyzer* scc_analyzer) : FieldGenerator(options), descriptor_(descriptor), - implicit_weak_field_(IsImplicitWeakField(descriptor, options)) { - SetMessageVariables(descriptor, &variables_, options); + implicit_weak_field_( + IsImplicitWeakField(descriptor, options, scc_analyzer)) { + SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); } MessageFieldGenerator::~MessageFieldGenerator() {} @@ -115,7 +114,7 @@ MessageFieldGenerator::~MessageFieldGenerator() {} void MessageFieldGenerator:: GeneratePrivateMembers(io::Printer* printer) const { if (implicit_weak_field_) { - printer->Print(variables_, "google::protobuf::MessageLite* $name$_;\n"); + printer->Print(variables_, "::google::protobuf::MessageLite* $name$_;\n"); } else { printer->Print(variables_, "$type$* $name$_;\n"); } @@ -129,8 +128,16 @@ GenerateAccessorDeclarations(io::Printer* printer) const { // the field without creating a strong dependency on the message type. printer->Print(variables_, "private:\n" - "const google::protobuf::MessageLite& _internal_$name$() const;\n" - "google::protobuf::MessageLite* _internal_mutable_$name$();\n" + "const ::google::protobuf::MessageLite& _internal_$name$() const;\n" + "::google::protobuf::MessageLite* _internal_mutable_$name$();\n" + "public:\n"); + } else { + // This inline accessor directly returns member field and is used in + // Serialize such that AFDO profile correctly captures access information to + // message fields under serialize. + printer->Print(variables_, + "private:\n" + "const $type$& _internal_$name$() const;\n" "public:\n"); } printer->Print(variables_, @@ -162,22 +169,22 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( io::Printer* printer) const { if (implicit_weak_field_) { printer->Print(variables_, - "const google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n" + "const ::google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n" " if ($name$_ != NULL) {\n" " return *$name$_;\n" " } else if (&$type_default_instance$ != NULL) {\n" - " return *reinterpret_cast(\n" + " return *reinterpret_cast(\n" " &$type_default_instance$);\n" " } else {\n" - " return *reinterpret_cast(\n" - " &::google::protobuf::internal::implicit_weak_message_default_instance);\n" + " return " + "*::google::protobuf::internal::ImplicitWeakMessage::default_instance();\n" " }\n" "}\n"); } if (SupportsArenas(descriptor_)) { if (implicit_weak_field_) { printer->Print(variables_, - "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" + "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" " $set_hasbit$\n" " if ($name$_ == NULL) {\n" " if (&$type_default_instance$ == NULL) {\n" @@ -185,7 +192,7 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( " ::google::protobuf::internal::ImplicitWeakMessage>(\n" " GetArenaNoVirtual());\n" " } else {\n" - " $name$_ = reinterpret_cast(\n" + " $name$_ = reinterpret_cast(\n" " &$type_default_instance$)->New(GetArenaNoVirtual());\n" " }\n" " }\n" @@ -212,13 +219,13 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( "}\n"); } else if (implicit_weak_field_) { printer->Print(variables_, - "google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" + "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" " $set_hasbit$\n" " if ($name$_ == NULL) {\n" " if (&$type_default_instance$ == NULL) {\n" " $name$_ = new ::google::protobuf::internal::ImplicitWeakMessage;\n" " } else {\n" - " $name$_ = reinterpret_cast(\n" + " $name$_ = reinterpret_cast(\n" " &$type_default_instance$)->New();\n" " }\n" " }\n" @@ -229,9 +236,14 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( void MessageFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { + if (!implicit_weak_field_) { + printer->Print(variables_, + "inline const $type$& $classname$::_internal_$name$() const {\n" + " return *$field_member$;\n" + "}\n"); + } printer->Print(variables_, "inline const $type$& $classname$::$name$() const {\n" - "$type_reference_function$" " const $type$* p = $casted_member$;\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" " return p != NULL ? *p : *reinterpret_cast(\n" @@ -247,7 +259,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { if (SupportsArenas(descriptor_)) { printer->Print(variables_, " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n" + " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" " }\n"); } printer->Print(variables_, @@ -269,16 +281,15 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, "inline $type$* $classname$::mutable_$name$() {\n" - "$type_reference_function$" " $set_hasbit$\n" - " if ($name$_ == NULL) {\n"); + " if ($name$_ == NULL) {\n" + " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n"); if (implicit_weak_field_) { printer->Print(variables_, - " _internal_mutable_$name$();\n"); + " $name$_ = reinterpret_cast<::google::protobuf::MessageLite*>(p);\n"); } else { printer->Print(variables_, - " $name$_ = ::google::protobuf::Arena::$create_func$< $type$ >(\n" - " GetArenaNoVirtual());\n"); + " $name$_ = p;\n"); } printer->Print(variables_, " }\n" @@ -309,7 +320,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { // isn't defined in this file. printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n"); + " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); } else if (!SupportsArenas(descriptor_->message_type())) { printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena = NULL;\n"); @@ -436,7 +447,7 @@ void MessageFieldGenerator:: GenerateSerializeWithCachedSizes(io::Printer* printer) const { printer->Print(variables_, "::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n" - " $number$, *$field_member$, output);\n"); + " $number$, this->_internal_$name$(), output);\n"); } void MessageFieldGenerator:: @@ -444,7 +455,7 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { printer->Print(variables_, "target = ::google::protobuf::internal::WireFormatLite::\n" " InternalWrite$declared_type$ToArray(\n" - " $number$, *$field_member$, deterministic, target);\n"); + " $number$, this->_internal_$name$(), deterministic, target);\n"); } void MessageFieldGenerator:: @@ -457,11 +468,10 @@ GenerateByteSize(io::Printer* printer) const { // =================================================================== -MessageOneofFieldGenerator:: -MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : MessageFieldGenerator(descriptor, options), - dependent_base_(options.proto_h) { +MessageOneofFieldGenerator::MessageOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options, + SCCAnalyzer* scc_analyzer) + : MessageFieldGenerator(descriptor, options, scc_analyzer) { SetCommonOneofFieldVariables(descriptor, &variables_); } @@ -480,7 +490,7 @@ void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions( // isn't defined in this file. printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast< ::google::protobuf::MessageLite*>($name$)->GetArena();\n"); + " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); } else if (!SupportsArenas(descriptor_->message_type())) { printer->Print(variables_, " ::google::protobuf::Arena* submessage_arena = NULL;\n"); @@ -503,6 +513,12 @@ void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions( void MessageOneofFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { + if (!implicit_weak_field_) { + printer->Print(variables_, + "inline const $type$& $classname$::_internal_$name$() const {\n" + " return *$field_member$;\n" + "}\n"); + } printer->Print(variables_, "inline $type$* $classname$::$release_name$() {\n" " // @@protoc_insertion_point(field_release:$full_name$)\n" @@ -512,7 +528,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { if (SupportsArenas(descriptor_)) { printer->Print(variables_, " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL);\n" + " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" " }\n"); } printer->Print(variables_, @@ -565,7 +581,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " if (!has_$name$()) {\n" " clear_$oneof_name$();\n" " set_has_$name$();\n" - " $field_member$ = ::google::protobuf::Arena::$create_func$< $type$ >(\n" + " $field_member$ = CreateMaybeMessage< $type$ >(\n" " GetArenaNoVirtual());\n" " }\n" " // @@protoc_insertion_point(field_mutable:$full_name$)\n" @@ -611,12 +627,13 @@ GenerateConstructorCode(io::Printer* printer) const { // =================================================================== RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) + const FieldDescriptor* descriptor, const Options& options, + SCCAnalyzer* scc_analyzer) : FieldGenerator(options), descriptor_(descriptor), - dependent_field_(options.proto_h && IsFieldDependent(descriptor)), - implicit_weak_field_(IsImplicitWeakField(descriptor, options)) { - SetMessageVariables(descriptor, &variables_, options); + implicit_weak_field_( + IsImplicitWeakField(descriptor, options, scc_analyzer)) { + SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); } RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {} @@ -627,19 +644,6 @@ GeneratePrivateMembers(io::Printer* printer) const { "::google::protobuf::RepeatedPtrField< $type$ > $name$_;\n"); } -void RepeatedMessageFieldGenerator:: -InternalGenerateTypeDependentAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedMessageFieldGenerator:: -GenerateDependentAccessorDeclarations(io::Printer* printer) const { - if (dependent_field_) { - InternalGenerateTypeDependentAccessorDeclarations(printer); - } -} - void RepeatedMessageFieldGenerator:: GenerateAccessorDeclarations(io::Printer* printer) const { printer->Print(variables_, @@ -653,38 +657,14 @@ GenerateAccessorDeclarations(io::Printer* printer) const { printer->Print(variables_, "$deprecated_attr$const $type$& $name$(int index) const;\n"); printer->Annotate("name", descriptor_); - if (!dependent_field_) { - InternalGenerateTypeDependentAccessorDeclarations(printer); - } + printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); printer->Print(variables_, "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n" " $name$() const;\n"); printer->Annotate("name", descriptor_); } -void RepeatedMessageFieldGenerator:: -GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const { - if (!dependent_field_) { - return; - } - std::map variables(variables_); - // For the CRTP base class, all mutation methods are dependent, and so - // they must be in the header. - variables["dependent_classname"] = - DependentBaseClassTemplateName(descriptor_->containing_type()) + ""; - variables["this_message"] = DependentBaseDownCast(); - variables["this_const_message"] = DependentBaseConstDownCast(); - - // Generate per-element accessors: - printer->Print(variables, - "template \n" - "inline $type$* $dependent_classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "$type_reference_function$" - " return $this_message$$name$_.Add();\n" - "}\n"); -} - void RepeatedMessageFieldGenerator:: GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, @@ -705,7 +685,6 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { printer->Print(variables_, "inline const $type$& $classname$::$name$(int index) const {\n" " // @@protoc_insertion_point(field_get:$full_name$)\n" - "$type_reference_function$" " return $name$_.InternalCheckedGet(index,\n" " *reinterpret_cast(&$type_default_instance$));\n" "}\n"); @@ -718,14 +697,11 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { "}\n"); } - if (!dependent_field_) { - printer->Print(variables_, - "inline $type$* $classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "$type_reference_function$" - " return $name$_.Add();\n" - "}\n"); - } + printer->Print(variables_, + "inline $type$* $classname$::add_$name$() {\n" + " // @@protoc_insertion_point(field_add:$full_name$)\n" + " return $name$_.Add();\n" + "}\n"); printer->Print(variables_, "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n" diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.h b/src/google/protobuf/compiler/cpp/cpp_message_field.h index e165404f1a..6879539c7d 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_message_field.h @@ -38,18 +38,17 @@ #include #include #include +#include namespace google { namespace protobuf { namespace compiler { namespace cpp { -bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options); - class MessageFieldGenerator : public FieldGenerator { public: MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); + const Options& options, SCCAnalyzer* scc_analyzer); ~MessageFieldGenerator(); // implements FieldGenerator --------------------------------------- @@ -81,7 +80,7 @@ class MessageFieldGenerator : public FieldGenerator { class MessageOneofFieldGenerator : public MessageFieldGenerator { public: MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); + const Options& options, SCCAnalyzer* scc_analyzer); ~MessageOneofFieldGenerator(); // implements FieldGenerator --------------------------------------- @@ -97,21 +96,19 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator { void GenerateConstructorCode(io::Printer* printer) const; private: - const bool dependent_base_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator); }; class RepeatedMessageFieldGenerator : public FieldGenerator { public: RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); + const Options& options, + SCCAnalyzer* scc_analyzer); ~RepeatedMessageFieldGenerator(); // implements FieldGenerator --------------------------------------- void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateDependentAccessorDeclarations(io::Printer* printer) const; void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const; void GenerateInlineAccessorDefinitions(io::Printer* printer) const; void GenerateClearingCode(io::Printer* printer) const; void GenerateMergingCode(io::Printer* printer) const; @@ -124,11 +121,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator { void GenerateByteSize(io::Printer* printer) const; private: - void InternalGenerateTypeDependentAccessorDeclarations( - io::Printer* printer) const; - const FieldDescriptor* descriptor_; - const bool dependent_field_; const bool implicit_weak_field_; std::map variables_; diff --git a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc index f72a7d6014..eb7cd1c775 100644 --- a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc @@ -34,7 +34,7 @@ #include #if LANG_CXX11 -#include +#include #endif namespace google { diff --git a/src/google/protobuf/compiler/cpp/cpp_options.h b/src/google/protobuf/compiler/cpp/cpp_options.h index b0dd883642..f09885bebe 100644 --- a/src/google/protobuf/compiler/cpp/cpp_options.h +++ b/src/google/protobuf/compiler/cpp/cpp_options.h @@ -54,6 +54,7 @@ struct Options { table_driven_parsing(false), table_driven_serialization(false), lite_implicit_weak_fields(false), + bootstrap(false), num_cc_files(0), access_info_map(NULL) {} @@ -66,6 +67,7 @@ struct Options { bool table_driven_parsing; bool table_driven_serialization; bool lite_implicit_weak_fields; + bool bootstrap; int num_cc_files; string annotation_pragma_name; string annotation_guard_name; diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h index 9641ba407c..42a3b5cdf8 100644 --- a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h +++ b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h @@ -50,10 +50,10 @@ namespace cpp { class PaddingOptimizer : public MessageLayoutHelper { public: PaddingOptimizer() {} - ~PaddingOptimizer() {} + ~PaddingOptimizer() override {} void OptimizeLayout(std::vector* fields, - const Options& options); + const Options& options) override; }; } // namespace cpp diff --git a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc index ceb2270e6e..ff6ba0f819 100644 --- a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc @@ -35,9 +35,6 @@ // worth. #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -172,7 +169,7 @@ class TestGenerator : public CodeGenerator { void TryInsert(const string& filename, const string& insertion_point, GeneratorContext* context) const { - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); io::Printer printer(output.get(), '$'); printer.Print("// inserted $name$\n", "name", insertion_point); diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc index c9901e8489..cf6c4b33af 100644 --- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc +++ b/src/google/protobuf/compiler/cpp/cpp_string_field.cc @@ -34,8 +34,8 @@ #include #include -#include #include +#include #include @@ -53,7 +53,7 @@ void SetStringVariables(const FieldDescriptor* descriptor, (*variables)["default"] = DefaultValue(descriptor); (*variables)["default_length"] = SimpleItoa(descriptor->default_value_string().length()); - string default_variable_string = "_default_" + FieldName(descriptor) + "_"; + string default_variable_string = MakeDefaultName(descriptor); (*variables)["default_variable_name"] = default_variable_string; (*variables)["default_variable"] = descriptor->default_value_string().empty() @@ -82,8 +82,24 @@ void SetStringVariables(const FieldDescriptor* descriptor, StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor), - lite_(!HasDescriptorMethods(descriptor->file(), options)) { + : FieldGenerator(options), + descriptor_(descriptor), + lite_(!HasDescriptorMethods(descriptor->file(), options)), + inlined_(false) { + + // TODO(ckennelly): Handle inlining for any.proto. + if (IsAnyMessage(descriptor_->containing_type())) { + inlined_ = false; + } + if (descriptor_->containing_type()->options().map_entry()) { + inlined_ = false; + } + + // Limit to proto2, as we rely on has bits to distinguish field presence for + // release_$name$. On proto3, we cannot use the address of the string + // instance when the field has been inlined. + inlined_ = inlined_ && HasFieldPresence(descriptor_->file()); + SetStringVariables(descriptor, &variables_, options); } @@ -91,27 +107,36 @@ StringFieldGenerator::~StringFieldGenerator() {} void StringFieldGenerator:: GeneratePrivateMembers(io::Printer* printer) const { - // N.B. that we continue to use |ArenaStringPtr| instead of |string*| for - // string fields, even when SupportArenas(descriptor_) == false. Why? - // The simple answer is to avoid unmaintainable complexity. The reflection - // code assumes ArenaStringPtrs. These are *almost* in-memory-compatible with - // string*, except for the pointer tags and related ownership semantics. We - // could modify the runtime code to use string* for the not-supporting-arenas - // case, but this would require a way to detect which type of class was - // generated (adding overhead and complexity to GeneratedMessageReflection) - // and littering the runtime code paths with conditionals. It's simpler to - // stick with this but use lightweight accessors that assume arena == NULL. - // There should be very little overhead anyway because it's just a tagged - // pointer in-memory. - printer->Print(variables_, "::google::protobuf::internal::ArenaStringPtr $name$_;\n"); + if (inlined_) { + printer->Print(variables_, + "::google::protobuf::internal::InlinedStringField $name$_;\n"); + } else { + // N.B. that we continue to use |ArenaStringPtr| instead of |string*| for + // string fields, even when SupportArenas(descriptor_) == false. Why? The + // simple answer is to avoid unmaintainable complexity. The reflection code + // assumes ArenaStringPtrs. These are *almost* in-memory-compatible with + // string*, except for the pointer tags and related ownership semantics. We + // could modify the runtime code to use string* for the + // not-supporting-arenas case, but this would require a way to detect which + // type of class was generated (adding overhead and complexity to + // GeneratedMessageReflection) and littering the runtime code paths with + // conditionals. It's simpler to stick with this but use lightweight + // accessors that assume arena == NULL. There should be very little + // overhead anyway because it's just a tagged pointer in-memory. + printer->Print(variables_, "::google::protobuf::internal::ArenaStringPtr $name$_;\n"); + } } void StringFieldGenerator:: GenerateStaticMembers(io::Printer* printer) const { if (!descriptor_->default_value_string().empty()) { + // We make the default instance public, so it can be initialized by + // non-friend code. printer->Print(variables_, + "public:\n" "static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string>" - " $default_variable_name$;\n"); + " $default_variable_name$;\n" + "private:\n"); } } @@ -246,9 +271,23 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n" "}\n" "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" + " // @@protoc_insertion_point(field_release:$full_name$)\n"); + + if (HasFieldPresence(descriptor_->file())) { + printer->Print(variables_, + " if (!has_$name$()) {\n" + " return NULL;\n" + " }\n" + " $clear_hasbit$\n" + " return $name$_.ReleaseNonDefault(" + "$default_variable$, GetArenaNoVirtual());\n"); + } else { + printer->Print(variables_, " $clear_hasbit$\n" - " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n" + " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"); + } + + printer->Print(variables_, "}\n" "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" " if ($name$ != NULL) {\n" @@ -322,9 +361,22 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const { " return $name$_.MutableNoArena($default_variable$);\n" "}\n" "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" + " // @@protoc_insertion_point(field_release:$full_name$)\n"); + + if (HasFieldPresence(descriptor_->file())) { + printer->Print(variables_, + " if (!has_$name$()) {\n" + " return NULL;\n" + " }\n" " $clear_hasbit$\n" - " return $name$_.ReleaseNoArena($default_variable$);\n" + " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n"); + } else { + printer->Print(variables_, + " $clear_hasbit$\n" + " return $name$_.ReleaseNoArena($default_variable$);\n"); + } + + printer->Print(variables_, "}\n" "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" " if ($name$ != NULL) {\n" @@ -343,7 +395,7 @@ GenerateNonInlineAccessorDefinitions(io::Printer* printer) const { if (!descriptor_->default_value_string().empty()) { // Initialized in GenerateDefaultInstanceAllocator. printer->Print(variables_, - "::google::protobuf::internal::ExplicitlyConstructed< ::std::string> " + "::google::protobuf::internal::ExplicitlyConstructed<::std::string> " "$classname$::$default_variable_name$;\n"); } } @@ -383,18 +435,34 @@ GenerateMessageClearingCode(io::Printer* printer) const { // If we have field presence, then the Clear() method of the protocol buffer // will have checked that this field is set. If so, we can avoid redundant // checks against default_variable. - const bool must_be_present = HasFieldPresence(descriptor_->file()); - - if (must_be_present) { + const bool must_be_present = + HasFieldPresence(descriptor_->file()); + + if (inlined_ && must_be_present) { + // Calling mutable_$name$() gives us a string reference and sets the has bit + // for $name$ (in proto2). We may get here when the string field is inlined + // but the string's contents have not been changed by the user, so we cannot + // make an assertion about the contents of the string and could never make + // an assertion about the string instance. + // + // For non-inlined strings, we distinguish from non-default by comparing + // instances, rather than contents. printer->Print(variables_, "GOOGLE_DCHECK(!$name$_.IsDefault($default_variable$));\n"); } if (SupportsArenas(descriptor_)) { if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); + if (must_be_present) { + printer->Print(variables_, + "$name$_.ClearNonDefaultToEmpty();\n"); + } else { + printer->Print(variables_, + "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); + } } else { + // Clear to a non-empty default is more involved, as we try to use the + // Arena if one is present and may need to reallocate the string. printer->Print(variables_, "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); } @@ -402,7 +470,7 @@ GenerateMessageClearingCode(io::Printer* printer) const { // When Arenas are disabled and field presence has been checked, we can // safely treat the ArenaStringPtr as a string*. if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, "$name$_.UnsafeMutablePointer()->clear();\n"); + printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n"); } else { printer->Print( variables_, @@ -433,13 +501,29 @@ GenerateMergingCode(io::Printer* printer) const { void StringFieldGenerator:: GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n"); + if (inlined_) { + printer->Print( + variables_, + "$name$_.Swap(&other->$name$_);\n"); + } else { + printer->Print( + variables_, + "$name$_.Swap(&other->$name$_, $default_variable$,\n" + " GetArenaNoVirtual());\n"); + } } void StringFieldGenerator:: GenerateConstructorCode(io::Printer* printer) const { + // TODO(ckennelly): Construct non-empty strings as part of the initializer + // list. + if (inlined_ && descriptor_->default_value_string().empty()) { + // Automatic initialization will construct the string. + return; + } + printer->Print(variables_, - "$name$_.UnsafeSetDefault($default_variable$);\n"); + "$name$_.UnsafeSetDefault($default_variable$);\n"); } void StringFieldGenerator:: @@ -472,8 +556,23 @@ GenerateCopyConstructorCode(io::Printer* printer) const { void StringFieldGenerator:: GenerateDestructorCode(io::Printer* printer) const { + if (inlined_) { + // The destructor is automatically invoked. + return; + } + + printer->Print(variables_, "$name$_.DestroyNoArena($default_variable$);\n"); +} + +bool StringFieldGenerator::GenerateArenaDestructorCode( + io::Printer* printer) const { + if (!inlined_) { + return false; + } + printer->Print(variables_, - "$name$_.DestroyNoArena($default_variable$);\n"); + "_this->$name$_.DestroyNoArena($default_variable$);\n"); + return true; } void StringFieldGenerator:: @@ -544,13 +643,17 @@ GenerateByteSize(io::Printer* printer) const { " this->$name$());\n"); } +uint32 StringFieldGenerator::CalculateFieldTag() const { + return inlined_ ? 1 : 0; +} + // =================================================================== -StringOneofFieldGenerator:: -StringOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : StringFieldGenerator(descriptor, options), - dependent_field_(options.proto_h) { +StringOneofFieldGenerator::StringOneofFieldGenerator( + const FieldDescriptor* descriptor, const Options& options) + : StringFieldGenerator(descriptor, options) { + inlined_ = false; + SetCommonOneofFieldVariables(descriptor, &variables_); } diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h index 0c6e9ced66..6cbf722fc1 100644 --- a/src/google/protobuf/compiler/cpp/cpp_string_field.h +++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h @@ -63,11 +63,14 @@ class StringFieldGenerator : public FieldGenerator { void GenerateConstructorCode(io::Printer* printer) const; void GenerateCopyConstructorCode(io::Printer* printer) const; void GenerateDestructorCode(io::Printer* printer) const; + bool GenerateArenaDestructorCode(io::Printer* printer) const; void GenerateDefaultInstanceAllocator(io::Printer* printer) const; void GenerateMergeFromCodedStream(io::Printer* printer) const; void GenerateSerializeWithCachedSizes(io::Printer* printer) const; void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; void GenerateByteSize(io::Printer* printer) const; + uint32 CalculateFieldTag() const; + bool IsInlined() const { return inlined_; } bool MergeFromCodedStreamNeedsArena() const; @@ -75,6 +78,7 @@ class StringFieldGenerator : public FieldGenerator { const FieldDescriptor* descriptor_; std::map variables_; const bool lite_; + bool inlined_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator); @@ -99,7 +103,6 @@ class StringOneofFieldGenerator : public StringFieldGenerator { void GenerateMergeFromCodedStream(io::Printer* printer) const; private: - const bool dependent_field_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator); }; diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_unittest.cc index 2ad7ea4e66..22b759a923 100644 --- a/src/google/protobuf/compiler/cpp/cpp_unittest.cc +++ b/src/google/protobuf/compiler/cpp/cpp_unittest.cc @@ -46,40 +46,26 @@ #include -#include -#ifndef _SHARED_PTR_H -#include -#endif -#include - #include -#include #include #include -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) -// We exclude this large proto from cmake build because it's too large for -// visual studio to compile (report internal errors). -#include -#endif -#include + #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#define MESSAGE_TEST_NAME MessageTest +#define GENERATED_DESCRIPTOR_TEST_NAME GeneratedDescriptorTest +#define GENERATED_MESSAGE_TEST_NAME GeneratedMessageTest +#define GENERATED_ENUM_TEST_NAME GeneratedEnumTest +#define GENERATED_SERVICE_TEST_NAME GeneratedServiceTest +#define HELPERS_TEST_NAME HelpersTest +#define DESCRIPTOR_INIT_TEST_NAME DescriptorInitializationTest + +#define UNITTEST_PROTO_PATH "google/protobuf/unittest.proto" +#define UNITTEST ::protobuf_unittest +#define UNITTEST_IMPORT ::protobuf_unittest_import + +// Must include after the above macros. +#include namespace google { namespace protobuf { @@ -91,848 +77,14 @@ namespace cpp_unittest { namespace protobuf_unittest = ::protobuf_unittest; - -class MockErrorCollector : public MultiFileErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); - } -}; - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -// Test that generated code has proper descriptors: -// Parse a descriptor directly (using google::protobuf::compiler::Importer) and -// compare it to the one that was produced by generated code. -TEST(GeneratedDescriptorTest, IdenticalDescriptors) { - const FileDescriptor* generated_descriptor = - unittest::TestAllTypes::descriptor()->file(); - - // Set up the Importer. - MockErrorCollector error_collector; - DiskSourceTree source_tree; - source_tree.MapPath("", TestSourceDir()); - Importer importer(&source_tree, &error_collector); - - // Import (parse) unittest.proto. - const FileDescriptor* parsed_descriptor = - importer.Import("google/protobuf/unittest.proto"); - EXPECT_EQ("", error_collector.text_); - ASSERT_TRUE(parsed_descriptor != NULL); - - // Test that descriptors are generated correctly by converting them to - // FileDescriptorProtos and comparing. - FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto; - generated_descriptor->CopyTo(&generated_descriptor_proto); - parsed_descriptor->CopyTo(&parsed_descriptor_proto); - - EXPECT_EQ(parsed_descriptor_proto.DebugString(), - generated_descriptor_proto.DebugString()); -} - -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) -// Test that generated code has proper descriptors: -// Touch a descriptor generated from an enormous message to validate special -// handling for descriptors exceeding the C++ standard's recommended minimum -// limit for string literal size -TEST(GeneratedDescriptorTest, EnormousDescriptor) { - const Descriptor* generated_descriptor = - TestEnormousDescriptor::descriptor(); - - EXPECT_TRUE(generated_descriptor != NULL); -} -#endif - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -TEST(GeneratedMessageTest, Defaults) { - // Check that all default values are set correctly in the initial message. - unittest::TestAllTypes message; - - TestUtil::ExpectClear(message); - - // Messages should return pointers to default instances until first use. - // (This is not checked by ExpectClear() since it is not actually true after - // the fields have been set and then cleared.) - EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_EQ(&unittest::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_EQ(&unittest_import::ImportMessage::default_instance(), - &message.optional_import_message()); -} - -#ifndef PROTOBUF_USE_DLLS -TEST(GeneratedMessageTest, Int32StringConversion) { - EXPECT_EQ("971", Int32ToString(971)); - EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min)); - EXPECT_EQ("2147483647", Int32ToString(kint32max)); -} - -TEST(GeneratedMessageTest, Int64StringConversion) { - EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971)); - EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min)); - EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min)); - EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max)); -} -#endif // !PROTOBUF_USE_DLLS - -TEST(GeneratedMessageTest, FloatingPointDefaults) { - const unittest::TestExtremeDefaultValues& extreme_default = - unittest::TestExtremeDefaultValues::default_instance(); - - EXPECT_EQ(0.0f, extreme_default.zero_float()); - EXPECT_EQ(1.0f, extreme_default.one_float()); - EXPECT_EQ(1.5f, extreme_default.small_float()); - EXPECT_EQ(-1.0f, extreme_default.negative_one_float()); - EXPECT_EQ(-1.5f, extreme_default.negative_float()); - EXPECT_EQ(2.0e8f, extreme_default.large_float()); - EXPECT_EQ(-8e-28f, extreme_default.small_negative_float()); - EXPECT_EQ(std::numeric_limits::infinity(), - extreme_default.inf_double()); - EXPECT_EQ(-std::numeric_limits::infinity(), - extreme_default.neg_inf_double()); - EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double()); - EXPECT_EQ(std::numeric_limits::infinity(), - extreme_default.inf_float()); - EXPECT_EQ(-std::numeric_limits::infinity(), - extreme_default.neg_inf_float()); - EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float()); -} - -TEST(GeneratedMessageTest, Trigraph) { - const unittest::TestExtremeDefaultValues& extreme_default = - unittest::TestExtremeDefaultValues::default_instance(); - - EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph()); -} - -TEST(GeneratedMessageTest, ExtremeSmallIntegerDefault) { - const unittest::TestExtremeDefaultValues& extreme_default = - unittest::TestExtremeDefaultValues::default_instance(); - EXPECT_EQ(~0x7fffffff, kint32min); - EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min); - EXPECT_EQ(kint32min, extreme_default.really_small_int32()); - EXPECT_EQ(kint64min, extreme_default.really_small_int64()); -} - -TEST(GeneratedMessageTest, Accessors) { - // Set every field to a unique value then go back and check all those - // values. - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - TestUtil::ExpectAllFieldsSet(message); - - TestUtil::ModifyRepeatedFields(&message); - TestUtil::ExpectRepeatedFieldsModified(message); -} - -TEST(GeneratedMessageTest, MutableStringDefault) { - // mutable_foo() for a string should return a string initialized to its - // default value. - unittest::TestAllTypes message; - - EXPECT_EQ("hello", *message.mutable_default_string()); - - // Note that the first time we call mutable_foo(), we get a newly-allocated - // string, but if we clear it and call it again, we get the same object again. - // We should verify that it has its default value in both cases. - message.set_default_string("blah"); - message.Clear(); - - EXPECT_EQ("hello", *message.mutable_default_string()); -} - -TEST(GeneratedMessageTest, StringDefaults) { - unittest::TestExtremeDefaultValues message; - // Check if '\000' can be used in default string value. - EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero()); - EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero()); -} - -TEST(GeneratedMessageTest, ReleaseString) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestAllTypes message; - - EXPECT_EQ(NULL, message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - EXPECT_EQ("hello", message.default_string()); - - message.set_default_string("blah"); - EXPECT_TRUE(message.has_default_string()); - google::protobuf::scoped_ptr str(message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - ASSERT_TRUE(str != NULL); - EXPECT_EQ("blah", *str); - - EXPECT_EQ(NULL, message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - EXPECT_EQ("hello", message.default_string()); -} - -TEST(GeneratedMessageTest, ReleaseMessage) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestAllTypes message; - - EXPECT_EQ(NULL, message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - google::protobuf::scoped_ptr nest( - message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); - ASSERT_TRUE(nest != NULL); - EXPECT_EQ(1, nest->bb()); - - EXPECT_EQ(NULL, message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); -} - -TEST(GeneratedMessageTest, SetAllocatedString) { - // Check that set_allocated_foo() works for strings. - unittest::TestAllTypes message; - - EXPECT_FALSE(message.has_optional_string()); - const string kHello("hello"); - message.set_optional_string(kHello); - EXPECT_TRUE(message.has_optional_string()); - - message.set_allocated_optional_string(NULL); - EXPECT_FALSE(message.has_optional_string()); - EXPECT_EQ("", message.optional_string()); - - message.set_allocated_optional_string(new string(kHello)); - EXPECT_TRUE(message.has_optional_string()); - EXPECT_EQ(kHello, message.optional_string()); -} - -TEST(GeneratedMessageTest, SetAllocatedMessage) { - // Check that set_allocated_foo() can be called in all cases. - unittest::TestAllTypes message; - - EXPECT_FALSE(message.has_optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - EXPECT_TRUE(message.has_optional_nested_message()); - - message.set_allocated_optional_nested_message(NULL); - EXPECT_FALSE(message.has_optional_nested_message()); - EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - unittest::TestAllTypes::NestedMessage* nest = - message.release_optional_nested_message(); - ASSERT_TRUE(nest != NULL); - EXPECT_FALSE(message.has_optional_nested_message()); - - message.set_allocated_optional_nested_message(nest); - EXPECT_TRUE(message.has_optional_nested_message()); - EXPECT_EQ(1, message.optional_nested_message().bb()); -} - -TEST(GeneratedMessageTest, Clear) { - // Set every field to a unique value, clear the message, then check that - // it is cleared. - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - message.Clear(); - TestUtil::ExpectClear(message); - - // Unlike with the defaults test, we do NOT expect that requesting embedded - // messages will return a pointer to the default instance. Instead, they - // should return the objects that were created when mutable_blah() was - // called. - EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &message.optional_import_message()); -} - -TEST(GeneratedMessageTest, EmbeddedNullsInBytesCharStar) { - unittest::TestAllTypes message; - - const char* value = "\0lalala\0\0"; - message.set_optional_bytes(value, 9); - ASSERT_EQ(9, message.optional_bytes().size()); - EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9)); - - message.add_repeated_bytes(value, 9); - ASSERT_EQ(9, message.repeated_bytes(0).size()); - EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9)); -} - -TEST(GeneratedMessageTest, ClearOneField) { - // Set every field to a unique value, then clear one value and insure that - // only that one value is cleared. - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - int64 original_value = message.optional_int64(); - - // Clear the field and make sure it shows up as cleared. - message.clear_optional_int64(); - EXPECT_FALSE(message.has_optional_int64()); - EXPECT_EQ(0, message.optional_int64()); - - // Other adjacent fields should not be cleared. - EXPECT_TRUE(message.has_optional_int32()); - EXPECT_TRUE(message.has_optional_uint32()); - - // Make sure if we set it again, then all fields are set. - message.set_optional_int64(original_value); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(GeneratedMessageTest, StringCharStarLength) { - // Verify that we can use a char*,length to set one of the string fields. - unittest::TestAllTypes message; - message.set_optional_string("abcdef", 3); - EXPECT_EQ("abc", message.optional_string()); - - // Verify that we can use a char*,length to add to a repeated string field. - message.add_repeated_string("abcdef", 3); - EXPECT_EQ(1, message.repeated_string_size()); - EXPECT_EQ("abc", message.repeated_string(0)); - - // Verify that we can use a char*,length to set a repeated string field. - message.set_repeated_string(0, "wxyz", 2); - EXPECT_EQ("wx", message.repeated_string(0)); -} - -#if LANG_CXX11 -TEST(GeneratedMessageTest, StringMove) { - // Verify that we trigger the move behavior on a scalar setter. - protobuf_unittest_no_arena::TestAllTypes message; - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.set_optional_string(std::move(tmp)); - const char* new_data = message.optional_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.optional_string()); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_optional_string(std::move(tmp2)); - new_data = message.optional_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.optional_string()); - } - - // Verify that we trigger the move behavior on a oneof setter. - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.set_oneof_string(std::move(tmp)); - const char* new_data = message.oneof_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.oneof_string()); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_oneof_string(std::move(tmp2)); - new_data = message.oneof_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.oneof_string()); - } - - // Verify that we trigger the move behavior on a repeated setter. - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.add_repeated_string(std::move(tmp)); - const char* new_data = message.repeated_string(0).data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.repeated_string(0)); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_repeated_string(0, std::move(tmp2)); - new_data = message.repeated_string(0).data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.repeated_string(0)); - } -} -#endif - - -TEST(GeneratedMessageTest, CopyFrom) { - unittest::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - message2.CopyFrom(message1); - TestUtil::ExpectAllFieldsSet(message2); - - // Copying from self should be a no-op. - message2.CopyFrom(message2); - TestUtil::ExpectAllFieldsSet(message2); -} - - -TEST(GeneratedMessageTest, SwapWithEmpty) { - unittest::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - - TestUtil::ExpectAllFieldsSet(message1); - TestUtil::ExpectClear(message2); - message1.Swap(&message2); - TestUtil::ExpectAllFieldsSet(message2); - TestUtil::ExpectClear(message1); -} - -TEST(GeneratedMessageTest, SwapWithSelf) { - unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - TestUtil::ExpectAllFieldsSet(message); - message.Swap(&message); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(GeneratedMessageTest, SwapWithOther) { - unittest::TestAllTypes message1, message2; - - message1.set_optional_int32(123); - message1.set_optional_string("abc"); - message1.mutable_optional_nested_message()->set_bb(1); - message1.set_optional_nested_enum(unittest::TestAllTypes::FOO); - message1.add_repeated_int32(1); - message1.add_repeated_int32(2); - message1.add_repeated_string("a"); - message1.add_repeated_string("b"); - message1.add_repeated_nested_message()->set_bb(7); - message1.add_repeated_nested_message()->set_bb(8); - message1.add_repeated_nested_enum(unittest::TestAllTypes::FOO); - message1.add_repeated_nested_enum(unittest::TestAllTypes::BAR); - - message2.set_optional_int32(456); - message2.set_optional_string("def"); - message2.mutable_optional_nested_message()->set_bb(2); - message2.set_optional_nested_enum(unittest::TestAllTypes::BAR); - message2.add_repeated_int32(3); - message2.add_repeated_string("c"); - message2.add_repeated_nested_message()->set_bb(9); - message2.add_repeated_nested_enum(unittest::TestAllTypes::BAZ); - - message1.Swap(&message2); - - EXPECT_EQ(456, message1.optional_int32()); - EXPECT_EQ("def", message1.optional_string()); - EXPECT_EQ(2, message1.optional_nested_message().bb()); - EXPECT_EQ(unittest::TestAllTypes::BAR, message1.optional_nested_enum()); - ASSERT_EQ(1, message1.repeated_int32_size()); - EXPECT_EQ(3, message1.repeated_int32(0)); - ASSERT_EQ(1, message1.repeated_string_size()); - EXPECT_EQ("c", message1.repeated_string(0)); - ASSERT_EQ(1, message1.repeated_nested_message_size()); - EXPECT_EQ(9, message1.repeated_nested_message(0).bb()); - ASSERT_EQ(1, message1.repeated_nested_enum_size()); - EXPECT_EQ(unittest::TestAllTypes::BAZ, message1.repeated_nested_enum(0)); - - EXPECT_EQ(123, message2.optional_int32()); - EXPECT_EQ("abc", message2.optional_string()); - EXPECT_EQ(1, message2.optional_nested_message().bb()); - EXPECT_EQ(unittest::TestAllTypes::FOO, message2.optional_nested_enum()); - ASSERT_EQ(2, message2.repeated_int32_size()); - EXPECT_EQ(1, message2.repeated_int32(0)); - EXPECT_EQ(2, message2.repeated_int32(1)); - ASSERT_EQ(2, message2.repeated_string_size()); - EXPECT_EQ("a", message2.repeated_string(0)); - EXPECT_EQ("b", message2.repeated_string(1)); - ASSERT_EQ(2, message2.repeated_nested_message_size()); - EXPECT_EQ(7, message2.repeated_nested_message(0).bb()); - EXPECT_EQ(8, message2.repeated_nested_message(1).bb()); - ASSERT_EQ(2, message2.repeated_nested_enum_size()); - EXPECT_EQ(unittest::TestAllTypes::FOO, message2.repeated_nested_enum(0)); - EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1)); -} - -TEST(GeneratedMessageTest, ADLSwap) { - unittest::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - - // Note the address of one of the repeated fields, to verify it was swapped - // rather than copied. - const int32* addr = &message1.repeated_int32().Get(0); - - using std::swap; - swap(message1, message2); - - TestUtil::ExpectAllFieldsSet(message2); - TestUtil::ExpectClear(message1); - - EXPECT_EQ(addr, &message2.repeated_int32().Get(0)); -} - -TEST(GeneratedMessageTest, CopyConstructor) { - // All set. - { - unittest::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - - unittest::TestAllTypes message2(message1); - TestUtil::ExpectAllFieldsSet(message2); - } - - // None set. - { - unittest::TestAllTypes message1; - unittest::TestAllTypes message2(message1); - - EXPECT_FALSE(message1.has_optional_string()); - EXPECT_FALSE(message2.has_optional_string()); - EXPECT_EQ(&message1.optional_string(), - &message2.optional_string()); - - EXPECT_FALSE(message1.has_optional_bytes()); - EXPECT_FALSE(message2.has_optional_bytes()); - EXPECT_EQ(&message1.optional_bytes(), - &message2.optional_bytes()); - - EXPECT_FALSE(message1.has_optional_nested_message()); - EXPECT_FALSE(message2.has_optional_nested_message()); - EXPECT_EQ(&message1.optional_nested_message(), - &message2.optional_nested_message()); - - EXPECT_FALSE(message1.has_optional_foreign_message()); - EXPECT_FALSE(message2.has_optional_foreign_message()); - EXPECT_EQ(&message1.optional_foreign_message(), - &message2.optional_foreign_message()); - - EXPECT_FALSE(message1.has_optional_import_message()); - EXPECT_FALSE(message2.has_optional_import_message()); - EXPECT_EQ(&message1.optional_import_message(), - &message2.optional_import_message()); - - EXPECT_FALSE(message1.has_optional_public_import_message()); - EXPECT_FALSE(message2.has_optional_public_import_message()); - EXPECT_EQ(&message1.optional_public_import_message(), - &message2.optional_public_import_message()); - - EXPECT_FALSE(message1.has_optional_lazy_message()); - EXPECT_FALSE(message2.has_optional_lazy_message()); - EXPECT_EQ(&message1.optional_lazy_message(), - &message2.optional_lazy_message()); - } -} - -TEST(GeneratedMessageTest, CopyConstructorWithArenas) { - Arena arena; - unittest::TestAllTypes* message1 = - Arena::CreateMessage(&arena); - TestUtil::SetAllFields(message1); - - unittest::TestAllTypes message2_stack(*message1); - TestUtil::ExpectAllFieldsSet(message2_stack); - - google::protobuf::scoped_ptr message2_heap( - new unittest::TestAllTypes(*message1)); - TestUtil::ExpectAllFieldsSet(*message2_heap); - - arena.Reset(); - - // Verify that the copies are still intact. - TestUtil::ExpectAllFieldsSet(message2_stack); - TestUtil::ExpectAllFieldsSet(*message2_heap); -} - -TEST(GeneratedMessageTest, CopyAssignmentOperator) { - unittest::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - - unittest::TestAllTypes message2; - message2 = message1; - TestUtil::ExpectAllFieldsSet(message2); - - // Make sure that self-assignment does something sane. - message2.operator=(message2); - TestUtil::ExpectAllFieldsSet(message2); -} - -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \ - !defined(GOOGLE_PROTOBUF_NO_RTTI) -TEST(GeneratedMessageTest, UpcastCopyFrom) { - // Test the CopyFrom method that takes in the generic const Message& - // parameter. - unittest::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - - const Message* source = implicit_cast(&message1); - message2.CopyFrom(*source); - - TestUtil::ExpectAllFieldsSet(message2); -} -#endif - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedMessageTest, DynamicMessageCopyFrom) { - // Test copying from a DynamicMessage, which must fall back to using - // reflection. - unittest::TestAllTypes message2; - - // Construct a new version of the dynamic message via the factory. - DynamicMessageFactory factory; - google::protobuf::scoped_ptr message1; - message1.reset(factory.GetPrototype( - unittest::TestAllTypes::descriptor())->New()); - - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - reflection_tester.SetAllFieldsViaReflection(message1.get()); - - message2.CopyFrom(*message1); - - TestUtil::ExpectAllFieldsSet(message2); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedMessageTest, NonEmptyMergeFrom) { - // Test merging with a non-empty message. Code is a modified form - // of that found in google/protobuf/reflection_ops_unittest.cc. - unittest::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - - // This field will test merging into an empty spot. - message2.set_optional_int32(message1.optional_int32()); - message1.clear_optional_int32(); - - // This tests overwriting. - message2.set_optional_string(message1.optional_string()); - message1.set_optional_string("something else"); - - // This tests concatenating. - message2.add_repeated_int32(message1.repeated_int32(1)); - int32 i = message1.repeated_int32(0); - message1.clear_repeated_int32(); - message1.add_repeated_int32(i); - - message1.MergeFrom(message2); - - TestUtil::ExpectAllFieldsSet(message1); -} - - -// Test the generated SerializeWithCachedSizesToArray(), -TEST(GeneratedMessageTest, SerializationToArray) { - unittest::TestAllTypes message1, message2; - string data; - TestUtil::SetAllFields(&message1); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message2); - -} - -TEST(GeneratedMessageTest, PackedFieldsSerializationToArray) { - unittest::TestPackedTypes packed_message1, packed_message2; - string packed_data; - TestUtil::SetPackedFields(&packed_message1); - int packed_size = packed_message1.ByteSize(); - packed_data.resize(packed_size); - uint8* start = reinterpret_cast(string_as_array(&packed_data)); - uint8* end = packed_message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(packed_size, end - start); - EXPECT_TRUE(packed_message2.ParseFromString(packed_data)); - TestUtil::ExpectPackedFieldsSet(packed_message2); -} - -// Test the generated SerializeWithCachedSizes() by forcing the buffer to write -// one byte at a time. -TEST(GeneratedMessageTest, SerializationToStream) { - unittest::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - int size = message1.ByteSize(); - string data; - data.resize(size); - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - TestUtil::ExpectAllFieldsSet(message2); - -} - -TEST(GeneratedMessageTest, PackedFieldsSerializationToStream) { - unittest::TestPackedTypes message1, message2; - TestUtil::SetPackedFields(&message1); - int size = message1.ByteSize(); - string data; - data.resize(size); - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - TestUtil::ExpectPackedFieldsSet(message2); -} - - -TEST(GeneratedMessageTest, Required) { - // Test that IsInitialized() returns false if required fields are missing. - unittest::TestRequired message; - - EXPECT_FALSE(message.IsInitialized()); - message.set_a(1); - EXPECT_FALSE(message.IsInitialized()); - message.set_b(2); - EXPECT_FALSE(message.IsInitialized()); - message.set_c(3); - EXPECT_TRUE(message.IsInitialized()); -} - -TEST(GeneratedMessageTest, RequiredForeign) { - // Test that IsInitialized() returns false if required fields in nested - // messages are missing. - unittest::TestRequiredForeign message; - - EXPECT_TRUE(message.IsInitialized()); - - message.mutable_optional_message(); - EXPECT_FALSE(message.IsInitialized()); - - message.mutable_optional_message()->set_a(1); - message.mutable_optional_message()->set_b(2); - message.mutable_optional_message()->set_c(3); - EXPECT_TRUE(message.IsInitialized()); - - message.add_repeated_message(); - EXPECT_FALSE(message.IsInitialized()); - - message.mutable_repeated_message(0)->set_a(1); - message.mutable_repeated_message(0)->set_b(2); - message.mutable_repeated_message(0)->set_c(3); - EXPECT_TRUE(message.IsInitialized()); -} - -TEST(GeneratedMessageTest, ForeignNested) { - // Test that TestAllTypes::NestedMessage can be embedded directly into - // another message. - unittest::TestForeignNested message; - - // If this compiles and runs without crashing, it must work. We have - // nothing more to test. - unittest::TestAllTypes::NestedMessage* nested = - message.mutable_foreign_nested(); - nested->set_bb(1); -} - -TEST(GeneratedMessageTest, ReallyLargeTagNumber) { - // Test that really large tag numbers don't break anything. - unittest::TestReallyLargeTagNumber message1, message2; - string data; - - // For the most part, if this compiles and runs then we're probably good. - // (The most likely cause for failure would be if something were attempting - // to allocate a lookup table of some sort using tag numbers as the index.) - // We'll try serializing just for fun. - message1.set_a(1234); - message1.set_bb(5678); - message1.SerializeToString(&data); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(1234, message2.a()); - EXPECT_EQ(5678, message2.bb()); -} - -TEST(GeneratedMessageTest, MutualRecursion) { - // Test that mutually-recursive message types work. - unittest::TestMutualRecursionA message; - unittest::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a(); - unittest::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a(); - - // Again, if the above compiles and runs, that's all we really have to - // test, but just for run we'll check that the system didn't somehow come - // up with a pointer loop... - EXPECT_NE(&message, nested); - EXPECT_NE(&message, nested2); - EXPECT_NE(nested, nested2); -} - -TEST(GeneratedMessageTest, CamelCaseFieldNames) { - // This test is mainly checking that the following compiles, which verifies - // that the field names were coerced to lower-case. - // - // Protocol buffers standard style is to use lowercase-with-underscores for - // field names. Some old proto1 .protos unfortunately used camel-case field - // names. In proto1, these names were forced to lower-case. So, we do the - // same thing in proto2. - - unittest::TestCamelCaseFieldNames message; - - message.set_primitivefield(2); - message.set_stringfield("foo"); - message.set_enumfield(unittest::FOREIGN_FOO); - message.mutable_messagefield()->set_c(6); - - message.add_repeatedprimitivefield(8); - message.add_repeatedstringfield("qux"); - message.add_repeatedenumfield(unittest::FOREIGN_BAR); - message.add_repeatedmessagefield()->set_c(15); - - EXPECT_EQ(2, message.primitivefield()); - EXPECT_EQ("foo", message.stringfield()); - EXPECT_EQ(unittest::FOREIGN_FOO, message.enumfield()); - EXPECT_EQ(6, message.messagefield().c()); - - EXPECT_EQ(8, message.repeatedprimitivefield(0)); - EXPECT_EQ("qux", message.repeatedstringfield(0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.repeatedenumfield(0)); - EXPECT_EQ(15, message.repeatedmessagefield(0).c()); -} - -TEST(GeneratedMessageTest, TestConflictingSymbolNames) { +TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingSymbolNames) { // test_bad_identifiers.proto successfully compiled, then it works. The // following is just a token usage to insure that the code is, in fact, // being compiled and linked. protobuf_unittest::TestConflictingSymbolNames message; message.set_uint32(1); - EXPECT_EQ(3, message.ByteSize()); + EXPECT_EQ(3, message.ByteSizeLong()); message.set_friend_(5); EXPECT_EQ(5, message.friend_()); @@ -948,7 +100,7 @@ TEST(GeneratedMessageTest, TestConflictingSymbolNames) { message.GetExtension(ExtensionMessage::repeated_int32_ext, 0)); } -TEST(GeneratedMessageTest, TestConflictingEnumNames) { +TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingEnumNames) { protobuf_unittest::TestConflictingEnumNames message; message.set_conflicting_enum(protobuf_unittest::TestConflictingEnumNames_NestedConflictingEnum_and_); EXPECT_EQ(1, message.conflicting_enum()); @@ -963,1366 +115,7 @@ TEST(GeneratedMessageTest, TestConflictingEnumNames) { EXPECT_EQ(3, conflicting_enum); } -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedMessageTest, TestOptimizedForSize) { - // We rely on the tests in reflection_ops_unittest and wire_format_unittest - // to really test that reflection-based methods work. Here we are mostly - // just making sure that TestOptimizedForSize actually builds and seems to - // function. - - protobuf_unittest::TestOptimizedForSize message, message2; - message.set_i(1); - message.mutable_msg()->set_c(2); - message2.CopyFrom(message); - EXPECT_EQ(1, message2.i()); - EXPECT_EQ(2, message2.msg().c()); -} - -TEST(GeneratedMessageTest, TestEmbedOptimizedForSize) { - // Verifies that something optimized for speed can contain something optimized - // for size. - - protobuf_unittest::TestEmbedOptimizedForSize message, message2; - message.mutable_optional_message()->set_i(1); - message.add_repeated_message()->mutable_msg()->set_c(2); - string data; - message.SerializeToString(&data); - ASSERT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(1, message2.optional_message().i()); - EXPECT_EQ(2, message2.repeated_message(0).msg().c()); -} - -TEST(GeneratedMessageTest, TestSpaceUsed) { - unittest::TestAllTypes message1; - // sizeof provides a lower bound on SpaceUsedLong(). - EXPECT_LE(sizeof(unittest::TestAllTypes), message1.SpaceUsedLong()); - const size_t empty_message_size = message1.SpaceUsedLong(); - - // Setting primitive types shouldn't affect the space used. - message1.set_optional_int32(123); - message1.set_optional_int64(12345); - message1.set_optional_uint32(123); - message1.set_optional_uint64(12345); - EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); - - // On some STL implementations, setting the string to a small value should - // only increase SpaceUsedLong() by the size of a string object, though this - // is not true everywhere. - message1.set_optional_string("abc"); - EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); - - // Setting a string to a value larger than the string object itself should - // increase SpaceUsedLong(), because it cannot store the value internally. - message1.set_optional_string(string(sizeof(string) + 1, 'x')); - int min_expected_increase = message1.optional_string().capacity() + - sizeof(string); - EXPECT_LE(empty_message_size + min_expected_increase, - message1.SpaceUsedLong()); - - size_t previous_size = message1.SpaceUsedLong(); - // Adding an optional message should increase the size by the size of the - // nested message type. NestedMessage is simple enough (1 int field) that it - // is equal to sizeof(NestedMessage) - message1.mutable_optional_nested_message(); - ASSERT_EQ(sizeof(unittest::TestAllTypes::NestedMessage), - message1.optional_nested_message().SpaceUsedLong()); - EXPECT_EQ(previous_size + - sizeof(unittest::TestAllTypes::NestedMessage), - message1.SpaceUsedLong()); -} - -TEST(GeneratedMessageTest, TestOneofSpaceUsed) { - unittest::TestOneof2 message1; - EXPECT_LE(sizeof(unittest::TestOneof2), message1.SpaceUsedLong()); - - const size_t empty_message_size = message1.SpaceUsedLong(); - // Setting primitive types shouldn't affect the space used. - message1.set_foo_int(123); - message1.set_bar_int(12345); - EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); - - // Setting a string in oneof to a small value should only increase - // SpaceUsedLong() by the size of a string object. - message1.set_foo_string("abc"); - EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); - - // Setting a string in oneof to a value larger than the string object itself - // should increase SpaceUsedLong(), because it cannot store the value - // internally. - message1.set_foo_string(string(sizeof(string) + 1, 'x')); - int min_expected_increase = message1.foo_string().capacity() + - sizeof(string); - EXPECT_LE(empty_message_size + min_expected_increase, - message1.SpaceUsedLong()); - - // Setting a message in oneof should delete the other fields and increase the - // size by the size of the nested message type. NestedMessage is simple enough - // that it is equal to sizeof(NestedMessage) - message1.mutable_foo_message(); - ASSERT_EQ(sizeof(unittest::TestOneof2::NestedMessage), - message1.foo_message().SpaceUsedLong()); - EXPECT_EQ(empty_message_size + - sizeof(unittest::TestOneof2::NestedMessage), - message1.SpaceUsedLong()); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - - -TEST(GeneratedMessageTest, FieldConstantValues) { - unittest::TestRequired message; - EXPECT_EQ(unittest::TestAllTypes_NestedMessage::kBbFieldNumber, 1); - EXPECT_EQ(unittest::TestAllTypes::kOptionalInt32FieldNumber, 1); - EXPECT_EQ(unittest::TestAllTypes::kOptionalgroupFieldNumber, 16); - EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedMessageFieldNumber, 18); - EXPECT_EQ(unittest::TestAllTypes::kOptionalNestedEnumFieldNumber, 21); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedInt32FieldNumber, 31); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedgroupFieldNumber, 46); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48); - EXPECT_EQ(unittest::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51); -} - -TEST(GeneratedMessageTest, ExtensionConstantValues) { - EXPECT_EQ(unittest::TestRequired::kSingleFieldNumber, 1000); - EXPECT_EQ(unittest::TestRequired::kMultiFieldNumber, 1001); - EXPECT_EQ(unittest::kOptionalInt32ExtensionFieldNumber, 1); - EXPECT_EQ(unittest::kOptionalgroupExtensionFieldNumber, 16); - EXPECT_EQ(unittest::kOptionalNestedMessageExtensionFieldNumber, 18); - EXPECT_EQ(unittest::kOptionalNestedEnumExtensionFieldNumber, 21); - EXPECT_EQ(unittest::kRepeatedInt32ExtensionFieldNumber, 31); - EXPECT_EQ(unittest::kRepeatedgroupExtensionFieldNumber, 46); - EXPECT_EQ(unittest::kRepeatedNestedMessageExtensionFieldNumber, 48); - EXPECT_EQ(unittest::kRepeatedNestedEnumExtensionFieldNumber, 51); -} - -TEST(GeneratedMessageTest, ParseFromTruncated) { - const string long_string = string(128, 'q'); - FileDescriptorProto p; - p.add_extension()->set_name(long_string); - const string msg = p.SerializeAsString(); - int successful_count = 0; - for (int i = 0; i <= msg.size(); i++) { - if (p.ParseFromArray(msg.c_str(), i)) { - ++successful_count; - } - } - // We don't really care about how often we succeeded. - // As long as we didn't crash, we're happy. - EXPECT_GE(successful_count, 1); -} - -// =================================================================== - -TEST(GeneratedEnumTest, EnumValuesAsSwitchCases) { - // Test that our nested enum values can be used as switch cases. This test - // doesn't actually do anything, the proof that it works is that it - // compiles. - int i =0; - unittest::TestAllTypes::NestedEnum a = unittest::TestAllTypes::BAR; - switch (a) { - case unittest::TestAllTypes::FOO: - i = 1; - break; - case unittest::TestAllTypes::BAR: - i = 2; - break; - case unittest::TestAllTypes::BAZ: - i = 3; - break; - case unittest::TestAllTypes::NEG: - i = -1; - break; - // no default case: We want to make sure the compiler recognizes that - // all cases are covered. (GCC warns if you do not cover all cases of - // an enum in a switch.) - } - - // Token check just for fun. - EXPECT_EQ(2, i); -} - -TEST(GeneratedEnumTest, IsValidValue) { - // Test enum IsValidValue. - EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(1)); - EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(2)); - EXPECT_TRUE(unittest::TestAllTypes::NestedEnum_IsValid(3)); - - EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(0)); - EXPECT_FALSE(unittest::TestAllTypes::NestedEnum_IsValid(4)); - - // Make sure it also works when there are dups. - EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(1)); - EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(2)); - EXPECT_TRUE(unittest::TestEnumWithDupValue_IsValid(3)); - - EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(0)); - EXPECT_FALSE(unittest::TestEnumWithDupValue_IsValid(4)); -} - -TEST(GeneratedEnumTest, MinAndMax) { - EXPECT_EQ(unittest::TestAllTypes::NEG, - unittest::TestAllTypes::NestedEnum_MIN); - EXPECT_EQ(unittest::TestAllTypes::BAZ, - unittest::TestAllTypes::NestedEnum_MAX); - EXPECT_EQ(4, unittest::TestAllTypes::NestedEnum_ARRAYSIZE); - - EXPECT_EQ(unittest::FOREIGN_FOO, unittest::ForeignEnum_MIN); - EXPECT_EQ(unittest::FOREIGN_BAZ, unittest::ForeignEnum_MAX); - EXPECT_EQ(7, unittest::ForeignEnum_ARRAYSIZE); - - EXPECT_EQ(1, unittest::TestEnumWithDupValue_MIN); - EXPECT_EQ(3, unittest::TestEnumWithDupValue_MAX); - EXPECT_EQ(4, unittest::TestEnumWithDupValue_ARRAYSIZE); - - EXPECT_EQ(unittest::SPARSE_E, unittest::TestSparseEnum_MIN); - EXPECT_EQ(unittest::SPARSE_C, unittest::TestSparseEnum_MAX); - EXPECT_EQ(12589235, unittest::TestSparseEnum_ARRAYSIZE); - - // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE. - void* null_pointer = 0; // NULL may be integer-type, not pointer-type. - EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MIN); - EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_MAX); - EXPECT_NE(null_pointer, &unittest::TestAllTypes::NestedEnum_ARRAYSIZE); - - EXPECT_NE(null_pointer, &unittest::ForeignEnum_MIN); - EXPECT_NE(null_pointer, &unittest::ForeignEnum_MAX); - EXPECT_NE(null_pointer, &unittest::ForeignEnum_ARRAYSIZE); - - // Make sure we can use _MIN and _MAX as switch cases. - switch (unittest::SPARSE_A) { - case unittest::TestSparseEnum_MIN: - case unittest::TestSparseEnum_MAX: - break; - default: - break; - } -} - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GeneratedEnumTest, Name) { - // "Names" in the presence of dup values are a bit arbitrary. - EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO1)); - EXPECT_EQ("FOO1", unittest::TestEnumWithDupValue_Name(unittest::FOO2)); - - EXPECT_EQ("SPARSE_A", unittest::TestSparseEnum_Name(unittest::SPARSE_A)); - EXPECT_EQ("SPARSE_B", unittest::TestSparseEnum_Name(unittest::SPARSE_B)); - EXPECT_EQ("SPARSE_C", unittest::TestSparseEnum_Name(unittest::SPARSE_C)); - EXPECT_EQ("SPARSE_D", unittest::TestSparseEnum_Name(unittest::SPARSE_D)); - EXPECT_EQ("SPARSE_E", unittest::TestSparseEnum_Name(unittest::SPARSE_E)); - EXPECT_EQ("SPARSE_F", unittest::TestSparseEnum_Name(unittest::SPARSE_F)); - EXPECT_EQ("SPARSE_G", unittest::TestSparseEnum_Name(unittest::SPARSE_G)); -} - -TEST(GeneratedEnumTest, Parse) { - unittest::TestEnumWithDupValue dup_value = unittest::FOO1; - EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO1", &dup_value)); - EXPECT_EQ(unittest::FOO1, dup_value); - EXPECT_TRUE(unittest::TestEnumWithDupValue_Parse("FOO2", &dup_value)); - EXPECT_EQ(unittest::FOO2, dup_value); - EXPECT_FALSE(unittest::TestEnumWithDupValue_Parse("FOO", &dup_value)); -} - -TEST(GeneratedEnumTest, GetEnumDescriptor) { - EXPECT_EQ(unittest::TestAllTypes::NestedEnum_descriptor(), - GetEnumDescriptor()); - EXPECT_EQ(unittest::ForeignEnum_descriptor(), - GetEnumDescriptor()); - EXPECT_EQ(unittest::TestEnumWithDupValue_descriptor(), - GetEnumDescriptor()); - EXPECT_EQ(unittest::TestSparseEnum_descriptor(), - GetEnumDescriptor()); -} - -enum NonProtoEnum { - kFoo = 1, -}; - -TEST(GeneratedEnumTest, IsProtoEnumTypeTrait) { - EXPECT_TRUE(is_proto_enum::value); - EXPECT_TRUE(is_proto_enum::value); - EXPECT_TRUE(is_proto_enum::value); - EXPECT_TRUE(is_proto_enum::value); - - EXPECT_FALSE(is_proto_enum::value); - EXPECT_FALSE(is_proto_enum::value); -} - -#endif // PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -// Support code for testing services. -class GeneratedServiceTest : public testing::Test { - protected: - class MockTestService : public unittest::TestService { - public: - MockTestService() - : called_(false), - method_(""), - controller_(NULL), - request_(NULL), - response_(NULL), - done_(NULL) {} - - ~MockTestService() {} - - void Reset() { called_ = false; } - - // implements TestService ---------------------------------------- - - void Foo(RpcController* controller, - const unittest::FooRequest* request, - unittest::FooResponse* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = "Foo"; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - void Bar(RpcController* controller, - const unittest::BarRequest* request, - unittest::BarResponse* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = "Bar"; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - // --------------------------------------------------------------- - - bool called_; - string method_; - RpcController* controller_; - const Message* request_; - Message* response_; - Closure* done_; - }; - - class MockRpcChannel : public RpcChannel { - public: - MockRpcChannel() - : called_(false), - method_(NULL), - controller_(NULL), - request_(NULL), - response_(NULL), - done_(NULL), - destroyed_(NULL) {} - - ~MockRpcChannel() { - if (destroyed_ != NULL) *destroyed_ = true; - } - - void Reset() { called_ = false; } - - // implements TestService ---------------------------------------- - - void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = method; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - // --------------------------------------------------------------- - - bool called_; - const MethodDescriptor* method_; - RpcController* controller_; - const Message* request_; - Message* response_; - Closure* done_; - bool* destroyed_; - }; - - class MockController : public RpcController { - public: - void Reset() { - ADD_FAILURE() << "Reset() not expected during this test."; - } - bool Failed() const { - ADD_FAILURE() << "Failed() not expected during this test."; - return false; - } - string ErrorText() const { - ADD_FAILURE() << "ErrorText() not expected during this test."; - return ""; - } - void StartCancel() { - ADD_FAILURE() << "StartCancel() not expected during this test."; - } - void SetFailed(const string& reason) { - ADD_FAILURE() << "SetFailed() not expected during this test."; - } - bool IsCanceled() const { - ADD_FAILURE() << "IsCanceled() not expected during this test."; - return false; - } - void NotifyOnCancel(Closure* callback) { - ADD_FAILURE() << "NotifyOnCancel() not expected during this test."; - } - }; - - GeneratedServiceTest() - : descriptor_(unittest::TestService::descriptor()), - foo_(descriptor_->FindMethodByName("Foo")), - bar_(descriptor_->FindMethodByName("Bar")), - stub_(&mock_channel_), - done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {} - - virtual void SetUp() { - ASSERT_TRUE(foo_ != NULL); - ASSERT_TRUE(bar_ != NULL); - } - - const ServiceDescriptor* descriptor_; - const MethodDescriptor* foo_; - const MethodDescriptor* bar_; - - MockTestService mock_service_; - MockController mock_controller_; - - MockRpcChannel mock_channel_; - unittest::TestService::Stub stub_; - - // Just so we don't have to re-define these with every test. - unittest::FooRequest foo_request_; - unittest::FooResponse foo_response_; - unittest::BarRequest bar_request_; - unittest::BarResponse bar_response_; - google::protobuf::scoped_ptr done_; -}; - -TEST_F(GeneratedServiceTest, GetDescriptor) { - // Test that GetDescriptor() works. - - EXPECT_EQ(descriptor_, mock_service_.GetDescriptor()); -} - -TEST_F(GeneratedServiceTest, GetChannel) { - EXPECT_EQ(&mock_channel_, stub_.channel()); -} - -TEST_F(GeneratedServiceTest, OwnsChannel) { - MockRpcChannel* channel = new MockRpcChannel; - bool destroyed = false; - channel->destroyed_ = &destroyed; - - { - unittest::TestService::Stub owning_stub(channel, - Service::STUB_OWNS_CHANNEL); - EXPECT_FALSE(destroyed); - } - - EXPECT_TRUE(destroyed); -} - -TEST_F(GeneratedServiceTest, CallMethod) { - // Test that CallMethod() works. - - // Call Foo() via CallMethod(). - mock_service_.CallMethod(foo_, &mock_controller_, - &foo_request_, &foo_response_, done_.get()); - - ASSERT_TRUE(mock_service_.called_); - - EXPECT_EQ("Foo" , mock_service_.method_ ); - EXPECT_EQ(&mock_controller_, mock_service_.controller_); - EXPECT_EQ(&foo_request_ , mock_service_.request_ ); - EXPECT_EQ(&foo_response_ , mock_service_.response_ ); - EXPECT_EQ(done_.get() , mock_service_.done_ ); - - // Try again, but call Bar() instead. - mock_service_.Reset(); - mock_service_.CallMethod(bar_, &mock_controller_, - &bar_request_, &bar_response_, done_.get()); - - ASSERT_TRUE(mock_service_.called_); - EXPECT_EQ("Bar", mock_service_.method_); -} - -TEST_F(GeneratedServiceTest, CallMethodTypeFailure) { - // Verify death if we call Foo() with Bar's message types. - -#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet - EXPECT_DEBUG_DEATH( - mock_service_.CallMethod(foo_, &mock_controller_, - &foo_request_, &bar_response_, done_.get()), - "dynamic_cast"); - - mock_service_.Reset(); - EXPECT_DEBUG_DEATH( - mock_service_.CallMethod(foo_, &mock_controller_, - &bar_request_, &foo_response_, done_.get()), - "dynamic_cast"); -#endif // PROTOBUF_HAS_DEATH_TEST -} - -TEST_F(GeneratedServiceTest, GetPrototypes) { - // Test Get{Request,Response}Prototype() methods. - - EXPECT_EQ(&unittest::FooRequest::default_instance(), - &mock_service_.GetRequestPrototype(foo_)); - EXPECT_EQ(&unittest::BarRequest::default_instance(), - &mock_service_.GetRequestPrototype(bar_)); - - EXPECT_EQ(&unittest::FooResponse::default_instance(), - &mock_service_.GetResponsePrototype(foo_)); - EXPECT_EQ(&unittest::BarResponse::default_instance(), - &mock_service_.GetResponsePrototype(bar_)); -} - -TEST_F(GeneratedServiceTest, Stub) { - // Test that the stub class works. - - // Call Foo() via the stub. - stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get()); - - ASSERT_TRUE(mock_channel_.called_); - - EXPECT_EQ(foo_ , mock_channel_.method_ ); - EXPECT_EQ(&mock_controller_, mock_channel_.controller_); - EXPECT_EQ(&foo_request_ , mock_channel_.request_ ); - EXPECT_EQ(&foo_response_ , mock_channel_.response_ ); - EXPECT_EQ(done_.get() , mock_channel_.done_ ); - - // Call Bar() via the stub. - mock_channel_.Reset(); - stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get()); - - ASSERT_TRUE(mock_channel_.called_); - EXPECT_EQ(bar_, mock_channel_.method_); -} - -TEST_F(GeneratedServiceTest, NotImplemented) { - // Test that failing to implement a method of a service causes it to fail - // with a "not implemented" error message. - - // A service which doesn't implement any methods. - class UnimplementedService : public unittest::TestService { - public: - UnimplementedService() {} - }; - - UnimplementedService unimplemented_service; - - // And a controller which expects to get a "not implemented" error. - class ExpectUnimplementedController : public MockController { - public: - ExpectUnimplementedController() : called_(false) {} - - void SetFailed(const string& reason) { - EXPECT_FALSE(called_); - called_ = true; - EXPECT_EQ("Method Foo() not implemented.", reason); - } - - bool called_; - }; - - ExpectUnimplementedController controller; - - // Call Foo. - unimplemented_service.Foo(&controller, &foo_request_, &foo_response_, - done_.get()); - - EXPECT_TRUE(controller.called_); -} - -// =================================================================== - -class OneofTest : public testing::Test { - protected: - virtual void SetUp() { - } - - void ExpectEnumCasesWork(const unittest::TestOneof2 &message) { - switch (message.foo_case()) { - case unittest::TestOneof2::kFooInt: - EXPECT_TRUE(message.has_foo_int()); - break; - case unittest::TestOneof2::kFooString: - EXPECT_TRUE(message.has_foo_string()); - break; - case unittest::TestOneof2::kFooCord: - EXPECT_TRUE(message.has_foo_cord()); - break; - case unittest::TestOneof2::kFooStringPiece: - EXPECT_TRUE(message.has_foo_string_piece()); - break; - case unittest::TestOneof2::kFooBytes: - EXPECT_TRUE(message.has_foo_bytes()); - break; - case unittest::TestOneof2::kFooEnum: - EXPECT_TRUE(message.has_foo_enum()); - break; - case unittest::TestOneof2::kFooMessage: - EXPECT_TRUE(message.has_foo_message()); - break; - case unittest::TestOneof2::kFoogroup: - EXPECT_TRUE(message.has_foogroup()); - break; - case unittest::TestOneof2::kFooLazyMessage: - EXPECT_TRUE(message.has_foo_lazy_message()); - break; - case unittest::TestOneof2::FOO_NOT_SET: - break; - } - } -}; - -TEST_F(OneofTest, SettingOneFieldClearsOthers) { - unittest::TestOneof2 message; - - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.set_foo_string("foo"); - EXPECT_TRUE(message.has_foo_string()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - - message.set_foo_bytes("qux"); - EXPECT_TRUE(message.has_foo_bytes()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.set_foo_enum(unittest::TestOneof2::FOO); - EXPECT_TRUE(message.has_foo_enum()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.mutable_foo_message()->set_qux_int(234); - EXPECT_TRUE(message.has_foo_message()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.mutable_foogroup()->set_a(345); - EXPECT_TRUE(message.has_foogroup()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - - // we repeat this because we didn't test if this properly clears other fields - // at the beginning. - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); -} - -TEST_F(OneofTest, EnumCases) { - unittest::TestOneof2 message; - - message.set_foo_int(123); - ExpectEnumCasesWork(message); - message.set_foo_string("foo"); - ExpectEnumCasesWork(message); - message.set_foo_bytes("qux"); - ExpectEnumCasesWork(message); - message.set_foo_enum(unittest::TestOneof2::FOO); - ExpectEnumCasesWork(message); - message.mutable_foo_message()->set_qux_int(234); - ExpectEnumCasesWork(message); - message.mutable_foogroup()->set_a(345); - ExpectEnumCasesWork(message); -} - -TEST_F(OneofTest, PrimitiveType) { - unittest::TestOneof2 message; - // Unset field returns default value - EXPECT_EQ(message.foo_int(), 0); - - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - EXPECT_EQ(message.foo_int(), 123); - message.clear_foo_int(); - EXPECT_FALSE(message.has_foo_int()); -} - -TEST_F(OneofTest, EnumType) { - unittest::TestOneof2 message; - // Unset field returns default value - EXPECT_EQ(message.foo_enum(), 1); - - message.set_foo_enum(unittest::TestOneof2::FOO); - EXPECT_TRUE(message.has_foo_enum()); - EXPECT_EQ(message.foo_enum(), unittest::TestOneof2::FOO); - message.clear_foo_enum(); - EXPECT_FALSE(message.has_foo_enum()); -} - -TEST_F(OneofTest, SetString) { - // Check that setting a string field in various ways works - unittest::TestOneof2 message; - - // Unset field returns default value - EXPECT_EQ(message.foo_string(), ""); - - message.set_foo_string("foo"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "foo"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string(string("bar")); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "bar"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - - message.set_foo_string("qux", 3); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "qux"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.mutable_foo_string()->assign("quux"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "quux"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string("corge"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "corge"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); -} - -TEST_F(OneofTest, ReleaseString) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestOneof2 message; - - EXPECT_EQ(NULL, message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string("blah"); - EXPECT_TRUE(message.has_foo_string()); - google::protobuf::scoped_ptr str(message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); - ASSERT_TRUE(str != NULL); - EXPECT_EQ("blah", *str); - - EXPECT_EQ(NULL, message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); -} - -TEST_F(OneofTest, SetAllocatedString) { - // Check that set_allocated_foo() works for strings. - unittest::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_string()); - const string kHello("hello"); - message.set_foo_string(kHello); - EXPECT_TRUE(message.has_foo_string()); - - message.set_allocated_foo_string(NULL); - EXPECT_FALSE(message.has_foo_string()); - EXPECT_EQ("", message.foo_string()); - - message.set_allocated_foo_string(new string(kHello)); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(kHello, message.foo_string()); -} - - -TEST_F(OneofTest, SetMessage) { - // Check that setting a message field works - unittest::TestOneof2 message; - - // Unset field returns default instance - EXPECT_EQ(&message.foo_message(), - &unittest::TestOneof2_NestedMessage::default_instance()); - EXPECT_EQ(message.foo_message().qux_int(), 0); - - message.mutable_foo_message()->set_qux_int(234); - EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 234); - message.clear_foo_message(); - EXPECT_FALSE(message.has_foo_message()); -} - -TEST_F(OneofTest, ReleaseMessage) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - unittest::TestOneof2 message; - - EXPECT_EQ(NULL, message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); - - message.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message.has_foo_message()); - google::protobuf::scoped_ptr mes( - message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); - ASSERT_TRUE(mes != NULL); - EXPECT_EQ(1, mes->qux_int()); - - EXPECT_EQ(NULL, message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); -} - -TEST_F(OneofTest, SetAllocatedMessage) { - // Check that set_allocated_foo() works for messages. - unittest::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_message()); - - message.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message.has_foo_message()); - - message.set_allocated_foo_message(NULL); - EXPECT_FALSE(message.has_foo_message()); - EXPECT_EQ(&message.foo_message(), - &unittest::TestOneof2_NestedMessage::default_instance()); - - message.mutable_foo_message()->set_qux_int(1); - unittest::TestOneof2_NestedMessage* mes = message.release_foo_message(); - ASSERT_TRUE(mes != NULL); - EXPECT_FALSE(message.has_foo_message()); - - message.set_allocated_foo_message(mes); - EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(1, message.foo_message().qux_int()); -} - - -TEST_F(OneofTest, Clear) { - unittest::TestOneof2 message; - - message.set_foo_int(1); - EXPECT_TRUE(message.has_foo_int()); - message.clear_foo_int(); - EXPECT_FALSE(message.has_foo_int()); -} - -TEST_F(OneofTest, Defaults) { - unittest::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_int()); - EXPECT_EQ(message.foo_int(), 0); - - EXPECT_FALSE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), ""); - - - EXPECT_FALSE(message.has_foo_bytes()); - EXPECT_EQ(message.foo_bytes(), ""); - - EXPECT_FALSE(message.has_foo_enum()); - EXPECT_EQ(message.foo_enum(), 1); - - EXPECT_FALSE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 0); - - EXPECT_FALSE(message.has_foogroup()); - EXPECT_EQ(message.foogroup().a(), 0); - - - EXPECT_FALSE(message.has_bar_int()); - EXPECT_EQ(message.bar_int(), 5); - - EXPECT_FALSE(message.has_bar_string()); - EXPECT_EQ(message.bar_string(), "STRING"); - - - EXPECT_FALSE(message.has_bar_bytes()); - EXPECT_EQ(message.bar_bytes(), "BYTES"); - - EXPECT_FALSE(message.has_bar_enum()); - EXPECT_EQ(message.bar_enum(), 2); -} - -TEST_F(OneofTest, SwapWithEmpty) { - unittest::TestOneof2 message1, message2; - message1.set_foo_string("FOO"); - EXPECT_TRUE(message1.has_foo_string()); - message1.Swap(&message2); - EXPECT_FALSE(message1.has_foo_string()); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "FOO"); -} - -TEST_F(OneofTest, SwapWithSelf) { - unittest::TestOneof2 message; - message.set_foo_string("FOO"); - EXPECT_TRUE(message.has_foo_string()); - message.Swap(&message); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "FOO"); -} - -TEST_F(OneofTest, SwapBothHasFields) { - unittest::TestOneof2 message1, message2; - - message1.set_foo_string("FOO"); - EXPECT_TRUE(message1.has_foo_string()); - message2.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message2.has_foo_message()); - - message1.Swap(&message2); - EXPECT_FALSE(message1.has_foo_string()); - EXPECT_FALSE(message2.has_foo_message()); - EXPECT_TRUE(message1.has_foo_message()); - EXPECT_EQ(message1.foo_message().qux_int(), 1); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "FOO"); -} - -TEST_F(OneofTest, CopyConstructor) { - unittest::TestOneof2 message1; - message1.set_foo_bytes("FOO"); - - unittest::TestOneof2 message2(message1); - EXPECT_TRUE(message2.has_foo_bytes()); - EXPECT_EQ(message2.foo_bytes(), "FOO"); -} - -TEST_F(OneofTest, CopyFrom) { - unittest::TestOneof2 message1, message2; - message1.set_foo_enum(unittest::TestOneof2::BAR); - EXPECT_TRUE(message1.has_foo_enum()); - - message2.CopyFrom(message1); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR); - - // Copying from self should be a no-op. - message2.CopyFrom(message2); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::BAR); -} - -TEST_F(OneofTest, CopyAssignmentOperator) { - unittest::TestOneof2 message1; - message1.mutable_foo_message()->set_qux_int(123); - EXPECT_TRUE(message1.has_foo_message()); - - unittest::TestOneof2 message2; - message2 = message1; - EXPECT_EQ(message2.foo_message().qux_int(), 123); - - // Make sure that self-assignment does something sane. - message2 = message2; - EXPECT_EQ(message2.foo_message().qux_int(), 123); -} - -TEST_F(OneofTest, UpcastCopyFrom) { - // Test the CopyFrom method that takes in the generic const Message& - // parameter. - unittest::TestOneof2 message1, message2; - message1.mutable_foogroup()->set_a(123); - EXPECT_TRUE(message1.has_foogroup()); - - const Message* source = implicit_cast(&message1); - message2.CopyFrom(*source); - - EXPECT_TRUE(message2.has_foogroup()); - EXPECT_EQ(message2.foogroup().a(), 123); -} - -// Test the generated SerializeWithCachedSizesToArray(), -// This indirectly tests MergePartialFromCodedStream() -// We have to test each field type separately because we cannot set them at the -// same time -TEST_F(OneofTest, SerializationToArray) { - // Primitive type - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_int(), 123); - } - - // String - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_string("foo"); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_string(), "foo"); - } - - - // Bytes - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_bytes("qux"); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_bytes(), "qux"); - } - - // Enum - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_enum(unittest::TestOneof2::FOO); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO); - } - - // Message - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foo_message()->set_qux_int(234); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - } - - // Group - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foogroup()->set_a(345); - int size = message1.ByteSize(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foogroup().a(), 345); - } - -} - -// Test the generated SerializeWithCachedSizes() by forcing the buffer to write -// one byte at a time. -// This indirectly tests MergePartialFromCodedStream() -// We have to test each field type separately because we cannot set them at the -// same time -TEST_F(OneofTest, SerializationToStream) { - // Primitive type - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - EXPECT_EQ(message2.foo_int(), 123); - } - - // String - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_string("foo"); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - EXPECT_EQ(message2.foo_string(), "foo"); - } - - - // Bytes - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_bytes("qux"); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - EXPECT_EQ(message2.foo_bytes(), "qux"); - } - - // Enum - { - unittest::TestOneof2 message1, message2; - string data; - message1.set_foo_enum(unittest::TestOneof2::FOO); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO); - } - - // Message - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foo_message()->set_qux_int(234); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - } - - // Group - { - unittest::TestOneof2 message1, message2; - string data; - message1.mutable_foogroup()->set_a(345); - int size = message1.ByteSize(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - 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)); - EXPECT_EQ(message2.foogroup().a(), 345); - } - -} - -TEST_F(OneofTest, MergeFrom) { - unittest::TestOneof2 message1, message2; - - message1.set_foo_int(123); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_int()); - EXPECT_EQ(message2.foo_int(), 123); - - message1.set_foo_string("foo"); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "foo"); - - - message1.set_foo_bytes("qux"); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_bytes()); - EXPECT_EQ(message2.foo_bytes(), "qux"); - - message1.set_foo_enum(unittest::TestOneof2::FOO); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), unittest::TestOneof2::FOO); - - message1.mutable_foo_message()->set_qux_int(234); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_message()); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - - message1.mutable_foogroup()->set_a(345); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foogroup()); - EXPECT_EQ(message2.foogroup().a(), 345); - -} - -TEST(HelpersTest, TestSCC) { - protobuf_unittest::TestMutualRecursionA a; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor()); - std::vector names; - for (int i = 0; i < scc->descriptors.size(); i++) { - names.push_back(scc->descriptors[i]->full_name()); - } - ASSERT_EQ(names.size(), 4); - std::sort(names.begin(), names.end()); - EXPECT_EQ(names[0], "protobuf_unittest.TestMutualRecursionA"); - EXPECT_EQ(names[1], "protobuf_unittest.TestMutualRecursionA.SubGroup"); - EXPECT_EQ(names[2], "protobuf_unittest.TestMutualRecursionA.SubMessage"); - EXPECT_EQ(names[3], "protobuf_unittest.TestMutualRecursionB"); - - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, true); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, true); // TestAllTypes - EXPECT_EQ(result.contains_extension, false); // TestAllTypes -} - -TEST(HelpersTest, TestSCCAnalysis) { - { - protobuf_unittest::TestRecursiveMessage msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, true); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, false); - } - { - protobuf_unittest::TestAllExtensions msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, false); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, true); - } - { - protobuf_unittest::TestRequired msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, false); - EXPECT_EQ(result.contains_required, true); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, false); - } -} - -} // namespace cpp_unittest -} // namespace cpp -} // namespace compiler - -namespace no_generic_services_test { - // Verify that no class called "TestService" was defined in - // unittest_no_generic_services.pb.h by defining a different type by the same - // name. If such a service was generated, this will not compile. - struct TestService { - int i; - }; -} - -namespace compiler { -namespace cpp { -namespace cpp_unittest { - -TEST_F(GeneratedServiceTest, NoGenericServices) { - // Verify that non-services in unittest_no_generic_services.proto were - // generated. - no_generic_services_test::TestMessage message; - message.set_a(1); - message.SetExtension(no_generic_services_test::test_extension, 123); - no_generic_services_test::TestEnum e = no_generic_services_test::FOO; - EXPECT_EQ(e, 1); - - // Verify that a ServiceDescriptor is generated for the service even if the - // class itself is not. - const FileDescriptor* file = - no_generic_services_test::TestMessage::descriptor()->file(); - - ASSERT_EQ(1, file->service_count()); - EXPECT_EQ("TestService", file->service(0)->name()); - ASSERT_EQ(1, file->service(0)->method_count()); - EXPECT_EQ("Foo", file->service(0)->method(0)->name()); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -// This test must run last. It verifies that descriptors were or were not -// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined. -// When this is defined, we skip all tests which are expected to trigger -// descriptor initialization. This verifies that everything else still works -// if descriptors are not initialized. -TEST(DescriptorInitializationTest, Initialized) { -#ifdef PROTOBUF_TEST_NO_DESCRIPTORS - bool should_have_descriptors = false; -#else - bool should_have_descriptors = true; -#endif - - EXPECT_EQ(should_have_descriptors, - DescriptorPool::generated_pool()->InternalIsFileLoaded( - "google/protobuf/unittest.proto")); -} - } // namespace cpp_unittest - } // namespace cpp } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/cpp_unittest.inc new file mode 100644 index 0000000000..ff6354f815 --- /dev/null +++ b/src/google/protobuf/compiler/cpp/cpp_unittest.inc @@ -0,0 +1,2281 @@ +// 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) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// To test the code generator, we actually use it to generate code for +// google/protobuf/unittest.proto, then test that. This means that we +// are actually testing the parser and other parts of the system at the same +// time, and that problems in the generator may show up as compile-time errors +// rather than unittest failures, which may be surprising. However, testing +// the output of the C++ generator directly would be very hard. We can't very +// well just check it against golden files since those files would have to be +// updated for any small change; such a test would be very brittle and probably +// not very helpful. What we really want to test is that the code compiles +// correctly and produces the interfaces we expect, which is why this test +// is written this way. + +#include + +#include +#include + +#include +#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) +// We exclude this large proto from cmake build because it's too large for +// visual studio to compile (report internal errors). +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. +namespace cpp_unittest { + + +class MockErrorCollector : public MultiFileErrorCollector { + public: + MockErrorCollector() {} + ~MockErrorCollector() {} + + string text_; + + // implements ErrorCollector --------------------------------------- + void AddError(const string& filename, int line, int column, + const string& message) { + strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", + filename, line, column, message); + } +}; + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +// Test that generated code has proper descriptors: +// Parse a descriptor directly (using google::protobuf::compiler::Importer) and +// compare it to the one that was produced by generated code. +TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) { + const FileDescriptor* generated_descriptor = + UNITTEST::TestAllTypes::descriptor()->file(); + + // Set up the Importer. + MockErrorCollector error_collector; + DiskSourceTree source_tree; + source_tree.MapPath("", TestSourceDir()); + Importer importer(&source_tree, &error_collector); + + // Import (parse) unittest.proto. + const FileDescriptor* parsed_descriptor = + importer.Import(UNITTEST_PROTO_PATH); + EXPECT_EQ("", error_collector.text_); + ASSERT_TRUE(parsed_descriptor != NULL); + + // Test that descriptors are generated correctly by converting them to + // FileDescriptorProtos and comparing. + FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto; + generated_descriptor->CopyTo(&generated_descriptor_proto); + parsed_descriptor->CopyTo(&parsed_descriptor_proto); + + EXPECT_EQ(parsed_descriptor_proto.DebugString(), + generated_descriptor_proto.DebugString()); +} + +#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) +// Test that generated code has proper descriptors: +// Touch a descriptor generated from an enormous message to validate special +// handling for descriptors exceeding the C++ standard's recommended minimum +// limit for string literal size +TEST(GENERATED_DESCRIPTOR_TEST_NAME, EnormousDescriptor) { + const Descriptor* generated_descriptor = + TestEnormousDescriptor::descriptor(); + + EXPECT_TRUE(generated_descriptor != NULL); +} +#endif + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + +// =================================================================== + +TEST(GENERATED_MESSAGE_TEST_NAME, Defaults) { + // Check that all default values are set correctly in the initial message. + UNITTEST::TestAllTypes message; + + TestUtil::ExpectClear(message); + + // Messages should return pointers to default instances until first use. + // (This is not checked by ExpectClear() since it is not actually true after + // the fields have been set and then cleared.) + EXPECT_EQ(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(), + &message.optionalgroup()); + EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), + &message.optional_nested_message()); + EXPECT_EQ(&UNITTEST::ForeignMessage::default_instance(), + &message.optional_foreign_message()); + EXPECT_EQ(&UNITTEST_IMPORT::ImportMessage::default_instance(), + &message.optional_import_message()); +} + +#ifndef PROTOBUF_USE_DLLS +TEST(GENERATED_MESSAGE_TEST_NAME, Int32StringConversion) { + EXPECT_EQ("971", Int32ToString(971)); + EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min)); + EXPECT_EQ("2147483647", Int32ToString(kint32max)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Int64StringConversion) { + EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971)); + EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min)); + EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min)); + EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max)); +} +#endif // !PROTOBUF_USE_DLLS + +TEST(GENERATED_MESSAGE_TEST_NAME, FloatingPointDefaults) { + const UNITTEST::TestExtremeDefaultValues& extreme_default = + UNITTEST::TestExtremeDefaultValues::default_instance(); + + EXPECT_EQ(0.0f, extreme_default.zero_float()); + EXPECT_EQ(1.0f, extreme_default.one_float()); + EXPECT_EQ(1.5f, extreme_default.small_float()); + EXPECT_EQ(-1.0f, extreme_default.negative_one_float()); + EXPECT_EQ(-1.5f, extreme_default.negative_float()); + EXPECT_EQ(2.0e8f, extreme_default.large_float()); + EXPECT_EQ(-8e-28f, extreme_default.small_negative_float()); + EXPECT_EQ(std::numeric_limits::infinity(), + extreme_default.inf_double()); + EXPECT_EQ(-std::numeric_limits::infinity(), + extreme_default.neg_inf_double()); + EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double()); + EXPECT_EQ(std::numeric_limits::infinity(), + extreme_default.inf_float()); + EXPECT_EQ(-std::numeric_limits::infinity(), + extreme_default.neg_inf_float()); + EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Trigraph) { + const UNITTEST::TestExtremeDefaultValues& extreme_default = + UNITTEST::TestExtremeDefaultValues::default_instance(); + + EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ExtremeSmallIntegerDefault) { + const UNITTEST::TestExtremeDefaultValues& extreme_default = + UNITTEST::TestExtremeDefaultValues::default_instance(); + EXPECT_EQ(~0x7fffffff, kint32min); + EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min); + EXPECT_EQ(kint32min, extreme_default.really_small_int32()); + EXPECT_EQ(kint64min, extreme_default.really_small_int64()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Accessors) { + // Set every field to a unique value then go back and check all those + // values. + UNITTEST::TestAllTypes message; + + TestUtil::SetAllFields(&message); + TestUtil::ExpectAllFieldsSet(message); + + TestUtil::ModifyRepeatedFields(&message); + TestUtil::ExpectRepeatedFieldsModified(message); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, MutableStringDefault) { + // mutable_foo() for a string should return a string initialized to its + // default value. + UNITTEST::TestAllTypes message; + + EXPECT_EQ("hello", *message.mutable_default_string()); + + // Note that the first time we call mutable_foo(), we get a newly-allocated + // string, but if we clear it and call it again, we get the same object again. + // We should verify that it has its default value in both cases. + message.set_default_string("blah"); + message.Clear(); + + EXPECT_EQ("hello", *message.mutable_default_string()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, StringDefaults) { + UNITTEST::TestExtremeDefaultValues message; + // Check if '\000' can be used in default string value. + EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero()); + EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestAllTypes message; + + EXPECT_EQ(NULL, message.release_default_string()); + EXPECT_FALSE(message.has_default_string()); + EXPECT_EQ("hello", message.default_string()); + + message.set_default_string("blah"); + EXPECT_TRUE(message.has_default_string()); + std::unique_ptr str(message.release_default_string()); + EXPECT_FALSE(message.has_default_string()); + ASSERT_TRUE(str != NULL); + EXPECT_EQ("blah", *str); + + EXPECT_EQ(NULL, message.release_default_string()); + EXPECT_FALSE(message.has_default_string()); + EXPECT_EQ("hello", message.default_string()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseMessage) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestAllTypes message; + + EXPECT_EQ(NULL, message.release_optional_nested_message()); + EXPECT_FALSE(message.has_optional_nested_message()); + + message.mutable_optional_nested_message()->set_bb(1); + std::unique_ptr nest( + message.release_optional_nested_message()); + EXPECT_FALSE(message.has_optional_nested_message()); + ASSERT_TRUE(nest != NULL); + EXPECT_EQ(1, nest->bb()); + + EXPECT_EQ(NULL, message.release_optional_nested_message()); + EXPECT_FALSE(message.has_optional_nested_message()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) { + // Check that set_allocated_foo() works for strings. + UNITTEST::TestAllTypes message; + + EXPECT_FALSE(message.has_optional_string()); + const string kHello("hello"); + message.set_optional_string(kHello); + EXPECT_TRUE(message.has_optional_string()); + + message.set_allocated_optional_string(NULL); + EXPECT_FALSE(message.has_optional_string()); + EXPECT_EQ("", message.optional_string()); + + message.set_allocated_optional_string(new string(kHello)); + EXPECT_TRUE(message.has_optional_string()); + EXPECT_EQ(kHello, message.optional_string()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedMessage) { + // Check that set_allocated_foo() can be called in all cases. + UNITTEST::TestAllTypes message; + + EXPECT_FALSE(message.has_optional_nested_message()); + + message.mutable_optional_nested_message()->set_bb(1); + EXPECT_TRUE(message.has_optional_nested_message()); + + message.set_allocated_optional_nested_message(NULL); + EXPECT_FALSE(message.has_optional_nested_message()); + EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), + &message.optional_nested_message()); + + message.mutable_optional_nested_message()->set_bb(1); + UNITTEST::TestAllTypes::NestedMessage* nest = + message.release_optional_nested_message(); + ASSERT_TRUE(nest != NULL); + EXPECT_FALSE(message.has_optional_nested_message()); + + message.set_allocated_optional_nested_message(nest); + EXPECT_TRUE(message.has_optional_nested_message()); + EXPECT_EQ(1, message.optional_nested_message().bb()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, Clear) { + // Set every field to a unique value, clear the message, then check that + // it is cleared. + UNITTEST::TestAllTypes message; + + TestUtil::SetAllFields(&message); + message.Clear(); + TestUtil::ExpectClear(message); + + // Unlike with the defaults test, we do NOT expect that requesting embedded + // messages will return a pointer to the default instance. Instead, they + // should return the objects that were created when mutable_blah() was + // called. + EXPECT_NE(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(), + &message.optionalgroup()); + EXPECT_NE(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), + &message.optional_nested_message()); + EXPECT_NE(&UNITTEST::ForeignMessage::default_instance(), + &message.optional_foreign_message()); + EXPECT_NE(&UNITTEST_IMPORT::ImportMessage::default_instance(), + &message.optional_import_message()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, EmbeddedNullsInBytesCharStar) { + UNITTEST::TestAllTypes message; + + const char* value = "\0lalala\0\0"; + message.set_optional_bytes(value, 9); + ASSERT_EQ(9, message.optional_bytes().size()); + EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9)); + + message.add_repeated_bytes(value, 9); + ASSERT_EQ(9, message.repeated_bytes(0).size()); + EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ClearOneField) { + // Set every field to a unique value, then clear one value and insure that + // only that one value is cleared. + UNITTEST::TestAllTypes message; + + TestUtil::SetAllFields(&message); + int64 original_value = message.optional_int64(); + + // Clear the field and make sure it shows up as cleared. + message.clear_optional_int64(); + EXPECT_FALSE(message.has_optional_int64()); + EXPECT_EQ(0, message.optional_int64()); + + // Other adjacent fields should not be cleared. + EXPECT_TRUE(message.has_optional_int32()); + EXPECT_TRUE(message.has_optional_uint32()); + + // Make sure if we set it again, then all fields are set. + message.set_optional_int64(original_value); + TestUtil::ExpectAllFieldsSet(message); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, StringCharStarLength) { + // Verify that we can use a char*,length to set one of the string fields. + UNITTEST::TestAllTypes message; + message.set_optional_string("abcdef", 3); + EXPECT_EQ("abc", message.optional_string()); + + // Verify that we can use a char*,length to add to a repeated string field. + message.add_repeated_string("abcdef", 3); + EXPECT_EQ(1, message.repeated_string_size()); + EXPECT_EQ("abc", message.repeated_string(0)); + + // Verify that we can use a char*,length to set a repeated string field. + message.set_repeated_string(0, "wxyz", 2); + EXPECT_EQ("wx", message.repeated_string(0)); +} + +#if LANG_CXX11 +TEST(GENERATED_MESSAGE_TEST_NAME, StringMove) { + // Verify that we trigger the move behavior on a scalar setter. + protobuf_unittest_no_arena::TestAllTypes message; + { + string tmp(32, 'a'); + + const char* old_data = tmp.data(); + message.set_optional_string(std::move(tmp)); + const char* new_data = message.optional_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'a'), message.optional_string()); + + string tmp2(32, 'b'); + old_data = tmp2.data(); + message.set_optional_string(std::move(tmp2)); + new_data = message.optional_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'b'), message.optional_string()); + } + + // Verify that we trigger the move behavior on a oneof setter. + { + string tmp(32, 'a'); + + const char* old_data = tmp.data(); + message.set_oneof_string(std::move(tmp)); + const char* new_data = message.oneof_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'a'), message.oneof_string()); + + string tmp2(32, 'b'); + old_data = tmp2.data(); + message.set_oneof_string(std::move(tmp2)); + new_data = message.oneof_string().data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'b'), message.oneof_string()); + } + + // Verify that we trigger the move behavior on a repeated setter. + { + string tmp(32, 'a'); + + const char* old_data = tmp.data(); + message.add_repeated_string(std::move(tmp)); + const char* new_data = message.repeated_string(0).data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'a'), message.repeated_string(0)); + + string tmp2(32, 'b'); + old_data = tmp2.data(); + message.set_repeated_string(0, std::move(tmp2)); + new_data = message.repeated_string(0).data(); + + EXPECT_EQ(old_data, new_data); + EXPECT_EQ(string(32, 'b'), message.repeated_string(0)); + } +} +#endif + + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) { + UNITTEST::TestAllTypes message1, message2; + + TestUtil::SetAllFields(&message1); + message2.CopyFrom(message1); + TestUtil::ExpectAllFieldsSet(message2); + + // Copying from self should be a no-op. + message2.CopyFrom(message2); + TestUtil::ExpectAllFieldsSet(message2); +} + + +TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithEmpty) { + UNITTEST::TestAllTypes message1, message2; + TestUtil::SetAllFields(&message1); + + TestUtil::ExpectAllFieldsSet(message1); + TestUtil::ExpectClear(message2); + message1.Swap(&message2); + TestUtil::ExpectAllFieldsSet(message2); + TestUtil::ExpectClear(message1); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithSelf) { + UNITTEST::TestAllTypes message; + TestUtil::SetAllFields(&message); + TestUtil::ExpectAllFieldsSet(message); + message.Swap(&message); + TestUtil::ExpectAllFieldsSet(message); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithOther) { + UNITTEST::TestAllTypes message1, message2; + + message1.set_optional_int32(123); + message1.set_optional_string("abc"); + message1.mutable_optional_nested_message()->set_bb(1); + message1.set_optional_nested_enum(UNITTEST::TestAllTypes::FOO); + message1.add_repeated_int32(1); + message1.add_repeated_int32(2); + message1.add_repeated_string("a"); + message1.add_repeated_string("b"); + message1.add_repeated_nested_message()->set_bb(7); + message1.add_repeated_nested_message()->set_bb(8); + message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::FOO); + message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR); + + message2.set_optional_int32(456); + message2.set_optional_string("def"); + message2.mutable_optional_nested_message()->set_bb(2); + message2.set_optional_nested_enum(UNITTEST::TestAllTypes::BAR); + message2.add_repeated_int32(3); + message2.add_repeated_string("c"); + message2.add_repeated_nested_message()->set_bb(9); + message2.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ); + + message1.Swap(&message2); + + EXPECT_EQ(456, message1.optional_int32()); + EXPECT_EQ("def", message1.optional_string()); + EXPECT_EQ(2, message1.optional_nested_message().bb()); + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message1.optional_nested_enum()); + ASSERT_EQ(1, message1.repeated_int32_size()); + EXPECT_EQ(3, message1.repeated_int32(0)); + ASSERT_EQ(1, message1.repeated_string_size()); + EXPECT_EQ("c", message1.repeated_string(0)); + ASSERT_EQ(1, message1.repeated_nested_message_size()); + EXPECT_EQ(9, message1.repeated_nested_message(0).bb()); + ASSERT_EQ(1, message1.repeated_nested_enum_size()); + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message1.repeated_nested_enum(0)); + + EXPECT_EQ(123, message2.optional_int32()); + EXPECT_EQ("abc", message2.optional_string()); + EXPECT_EQ(1, message2.optional_nested_message().bb()); + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.optional_nested_enum()); + ASSERT_EQ(2, message2.repeated_int32_size()); + EXPECT_EQ(1, message2.repeated_int32(0)); + EXPECT_EQ(2, message2.repeated_int32(1)); + ASSERT_EQ(2, message2.repeated_string_size()); + EXPECT_EQ("a", message2.repeated_string(0)); + EXPECT_EQ("b", message2.repeated_string(1)); + ASSERT_EQ(2, message2.repeated_nested_message_size()); + EXPECT_EQ(7, message2.repeated_nested_message(0).bb()); + EXPECT_EQ(8, message2.repeated_nested_message(1).bb()); + ASSERT_EQ(2, message2.repeated_nested_enum_size()); + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message2.repeated_nested_enum(1)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ADLSwap) { + UNITTEST::TestAllTypes message1, message2; + TestUtil::SetAllFields(&message1); + + // Note the address of one of the repeated fields, to verify it was swapped + // rather than copied. + const int32* addr = &message1.repeated_int32().Get(0); + + using std::swap; + swap(message1, message2); + + TestUtil::ExpectAllFieldsSet(message2); + TestUtil::ExpectClear(message1); + + EXPECT_EQ(addr, &message2.repeated_int32().Get(0)); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructor) { + // All set. + { + UNITTEST::TestAllTypes message1; + TestUtil::SetAllFields(&message1); + + UNITTEST::TestAllTypes message2(message1); + TestUtil::ExpectAllFieldsSet(message2); + } + + // None set. + { + UNITTEST::TestAllTypes message1; + UNITTEST::TestAllTypes message2(message1); + + EXPECT_FALSE(message1.has_optional_string()); + EXPECT_FALSE(message2.has_optional_string()); + EXPECT_EQ(message1.optional_string(), message2.optional_string()); + + EXPECT_FALSE(message1.has_optional_bytes()); + EXPECT_FALSE(message2.has_optional_bytes()); + EXPECT_EQ(message1.optional_bytes(), message2.optional_bytes()); + + EXPECT_FALSE(message1.has_optional_nested_message()); + EXPECT_FALSE(message2.has_optional_nested_message()); + EXPECT_EQ(&message1.optional_nested_message(), + &message2.optional_nested_message()); + + EXPECT_FALSE(message1.has_optional_foreign_message()); + EXPECT_FALSE(message2.has_optional_foreign_message()); + EXPECT_EQ(&message1.optional_foreign_message(), + &message2.optional_foreign_message()); + + EXPECT_FALSE(message1.has_optional_import_message()); + EXPECT_FALSE(message2.has_optional_import_message()); + EXPECT_EQ(&message1.optional_import_message(), + &message2.optional_import_message()); + + EXPECT_FALSE(message1.has_optional_public_import_message()); + EXPECT_FALSE(message2.has_optional_public_import_message()); + EXPECT_EQ(&message1.optional_public_import_message(), + &message2.optional_public_import_message()); + + EXPECT_FALSE(message1.has_optional_lazy_message()); + EXPECT_FALSE(message2.has_optional_lazy_message()); + EXPECT_EQ(&message1.optional_lazy_message(), + &message2.optional_lazy_message()); + } +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructorWithArenas) { + Arena arena; + UNITTEST::TestAllTypes* message1 = + Arena::CreateMessage(&arena); + TestUtil::SetAllFields(message1); + + UNITTEST::TestAllTypes message2_stack(*message1); + TestUtil::ExpectAllFieldsSet(message2_stack); + + std::unique_ptr message2_heap( + new UNITTEST::TestAllTypes(*message1)); + TestUtil::ExpectAllFieldsSet(*message2_heap); + + arena.Reset(); + + // Verify that the copies are still intact. + TestUtil::ExpectAllFieldsSet(message2_stack); + TestUtil::ExpectAllFieldsSet(*message2_heap); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) { + UNITTEST::TestAllTypes message1; + TestUtil::SetAllFields(&message1); + + UNITTEST::TestAllTypes message2; + message2 = message1; + TestUtil::ExpectAllFieldsSet(message2); + + // Make sure that self-assignment does something sane. + message2.operator=(message2); + TestUtil::ExpectAllFieldsSet(message2); +} + +#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \ + !defined(GOOGLE_PROTOBUF_NO_RTTI) +TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) { + // Test the CopyFrom method that takes in the generic const Message& + // parameter. + UNITTEST::TestAllTypes message1, message2; + + TestUtil::SetAllFields(&message1); + + const Message* source = implicit_cast(&message1); + message2.CopyFrom(*source); + + TestUtil::ExpectAllFieldsSet(message2); +} +#endif + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) { + // Test copying from a DynamicMessage, which must fall back to using + // reflection. + UNITTEST::TestAllTypes message2; + + // Construct a new version of the dynamic message via the factory. + DynamicMessageFactory factory; + std::unique_ptr message1; + message1.reset(factory.GetPrototype( + UNITTEST::TestAllTypes::descriptor())->New()); + + TestUtil::ReflectionTester reflection_tester( + UNITTEST::TestAllTypes::descriptor()); + reflection_tester.SetAllFieldsViaReflection(message1.get()); + + message2.CopyFrom(*message1); + + TestUtil::ExpectAllFieldsSet(message2); +} + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) { + // Test merging with a non-empty message. Code is a modified form + // of that found in google/protobuf/reflection_ops_unittest.cc. + UNITTEST::TestAllTypes message1, message2; + + TestUtil::SetAllFields(&message1); + + // This field will test merging into an empty spot. + message2.set_optional_int32(message1.optional_int32()); + message1.clear_optional_int32(); + + // This tests overwriting. + message2.set_optional_string(message1.optional_string()); + message1.set_optional_string("something else"); + + // This tests concatenating. + message2.add_repeated_int32(message1.repeated_int32(1)); + int32 i = message1.repeated_int32(0); + message1.clear_repeated_int32(); + message1.add_repeated_int32(i); + + message1.MergeFrom(message2); + + TestUtil::ExpectAllFieldsSet(message1); +} + + +// Test the generated SerializeWithCachedSizesToArray(), +TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) { + UNITTEST::TestAllTypes message1, message2; + string data; + TestUtil::SetAllFields(&message1); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + TestUtil::ExpectAllFieldsSet(message2); + +} + +TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) { + UNITTEST::TestPackedTypes packed_message1, packed_message2; + string packed_data; + TestUtil::SetPackedFields(&packed_message1); + int packed_size = packed_message1.ByteSizeLong(); + packed_data.resize(packed_size); + uint8* start = reinterpret_cast(string_as_array(&packed_data)); + uint8* end = packed_message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(packed_size, end - start); + EXPECT_TRUE(packed_message2.ParseFromString(packed_data)); + TestUtil::ExpectPackedFieldsSet(packed_message2); +} + +// Test the generated SerializeWithCachedSizes() by forcing the buffer to write +// one byte at a time. +TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) { + UNITTEST::TestAllTypes message1, message2; + TestUtil::SetAllFields(&message1); + int size = message1.ByteSizeLong(); + string data; + data.resize(size); + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + TestUtil::ExpectAllFieldsSet(message2); + +} + +TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) { + UNITTEST::TestPackedTypes message1, message2; + TestUtil::SetPackedFields(&message1); + int size = message1.ByteSizeLong(); + string data; + data.resize(size); + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + TestUtil::ExpectPackedFieldsSet(message2); +} + + +TEST(GENERATED_MESSAGE_TEST_NAME, Required) { + // Test that IsInitialized() returns false if required fields are missing. + UNITTEST::TestRequired message; + + EXPECT_FALSE(message.IsInitialized()); + message.set_a(1); + EXPECT_FALSE(message.IsInitialized()); + message.set_b(2); + EXPECT_FALSE(message.IsInitialized()); + message.set_c(3); + EXPECT_TRUE(message.IsInitialized()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, RequiredForeign) { + // Test that IsInitialized() returns false if required fields in nested + // messages are missing. + UNITTEST::TestRequiredForeign message; + + EXPECT_TRUE(message.IsInitialized()); + + message.mutable_optional_message(); + EXPECT_FALSE(message.IsInitialized()); + + message.mutable_optional_message()->set_a(1); + message.mutable_optional_message()->set_b(2); + message.mutable_optional_message()->set_c(3); + EXPECT_TRUE(message.IsInitialized()); + + message.add_repeated_message(); + EXPECT_FALSE(message.IsInitialized()); + + message.mutable_repeated_message(0)->set_a(1); + message.mutable_repeated_message(0)->set_b(2); + message.mutable_repeated_message(0)->set_c(3); + EXPECT_TRUE(message.IsInitialized()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ForeignNested) { + // Test that TestAllTypes::NestedMessage can be embedded directly into + // another message. + UNITTEST::TestForeignNested message; + + // If this compiles and runs without crashing, it must work. We have + // nothing more to test. + UNITTEST::TestAllTypes::NestedMessage* nested = + message.mutable_foreign_nested(); + nested->set_bb(1); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ReallyLargeTagNumber) { + // Test that really large tag numbers don't break anything. + UNITTEST::TestReallyLargeTagNumber message1, message2; + string data; + + // For the most part, if this compiles and runs then we're probably good. + // (The most likely cause for failure would be if something were attempting + // to allocate a lookup table of some sort using tag numbers as the index.) + // We'll try serializing just for fun. + message1.set_a(1234); + message1.set_bb(5678); + message1.SerializeToString(&data); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(1234, message2.a()); + EXPECT_EQ(5678, message2.bb()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, MutualRecursion) { + // Test that mutually-recursive message types work. + UNITTEST::TestMutualRecursionA message; + UNITTEST::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a(); + UNITTEST::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a(); + + // Again, if the above compiles and runs, that's all we really have to + // test, but just for run we'll check that the system didn't somehow come + // up with a pointer loop... + EXPECT_NE(&message, nested); + EXPECT_NE(&message, nested2); + EXPECT_NE(nested, nested2); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, CamelCaseFieldNames) { + // This test is mainly checking that the following compiles, which verifies + // that the field names were coerced to lower-case. + // + // Protocol buffers standard style is to use lowercase-with-underscores for + // field names. Some old proto1 .protos unfortunately used camel-case field + // names. In proto1, these names were forced to lower-case. So, we do the + // same thing in proto2. + + UNITTEST::TestCamelCaseFieldNames message; + + message.set_primitivefield(2); + message.set_stringfield("foo"); + message.set_enumfield(UNITTEST::FOREIGN_FOO); + message.mutable_messagefield()->set_c(6); + + message.add_repeatedprimitivefield(8); + message.add_repeatedstringfield("qux"); + message.add_repeatedenumfield(UNITTEST::FOREIGN_BAR); + message.add_repeatedmessagefield()->set_c(15); + + EXPECT_EQ(2, message.primitivefield()); + EXPECT_EQ("foo", message.stringfield()); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.enumfield()); + EXPECT_EQ(6, message.messagefield().c()); + + EXPECT_EQ(8, message.repeatedprimitivefield(0)); + EXPECT_EQ("qux", message.repeatedstringfield(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeatedenumfield(0)); + EXPECT_EQ(15, message.repeatedmessagefield(0).c()); +} + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_MESSAGE_TEST_NAME, TestOptimizedForSize) { + // We rely on the tests in reflection_ops_unittest and wire_format_unittest + // to really test that reflection-based methods work. Here we are mostly + // just making sure that TestOptimizedForSize actually builds and seems to + // function. + + UNITTEST::TestOptimizedForSize message, message2; + message.set_i(1); + message.mutable_msg()->set_c(2); + message2.CopyFrom(message); + EXPECT_EQ(1, message2.i()); + EXPECT_EQ(2, message2.msg().c()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, TestEmbedOptimizedForSize) { + // Verifies that something optimized for speed can contain something optimized + // for size. + + UNITTEST::TestEmbedOptimizedForSize message, message2; + message.mutable_optional_message()->set_i(1); + message.add_repeated_message()->mutable_msg()->set_c(2); + string data; + message.SerializeToString(&data); + ASSERT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(1, message2.optional_message().i()); + EXPECT_EQ(2, message2.repeated_message(0).msg().c()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, TestSpaceUsed) { + UNITTEST::TestAllTypes message1; + // sizeof provides a lower bound on SpaceUsedLong(). + EXPECT_LE(sizeof(UNITTEST::TestAllTypes), message1.SpaceUsedLong()); + const size_t empty_message_size = message1.SpaceUsedLong(); + + // Setting primitive types shouldn't affect the space used. + message1.set_optional_int32(123); + message1.set_optional_int64(12345); + message1.set_optional_uint32(123); + message1.set_optional_uint64(12345); + EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); + + // On some STL implementations, setting the string to a small value should + // only increase SpaceUsedLong() by the size of a string object, though this + // is not true everywhere. + message1.set_optional_string("abc"); + EXPECT_LE(empty_message_size + message1.optional_string().size(), + message1.SpaceUsedLong()); + + // Setting a string to a value larger than the string object itself should + // increase SpaceUsedLong(), because it cannot store the value internally. + message1.set_optional_string(string(sizeof(string) + 1, 'x')); + int min_expected_increase = message1.optional_string().capacity(); + EXPECT_LE(empty_message_size + min_expected_increase, + message1.SpaceUsedLong()); + + size_t previous_size = message1.SpaceUsedLong(); + // Adding an optional message should increase the size by the size of the + // nested message type. NestedMessage is simple enough (1 int field) that it + // is equal to sizeof(NestedMessage) + message1.mutable_optional_nested_message(); + ASSERT_EQ(sizeof(UNITTEST::TestAllTypes::NestedMessage), + message1.optional_nested_message().SpaceUsedLong()); + EXPECT_EQ(previous_size + + sizeof(UNITTEST::TestAllTypes::NestedMessage), + message1.SpaceUsedLong()); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, TestOneofSpaceUsed) { + UNITTEST::TestOneof2 message1; + EXPECT_LE(sizeof(UNITTEST::TestOneof2), message1.SpaceUsedLong()); + + const size_t empty_message_size = message1.SpaceUsedLong(); + // Setting primitive types shouldn't affect the space used. + message1.set_foo_int(123); + message1.set_bar_int(12345); + EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); + + // Setting a string in oneof to a small value should only increase + // SpaceUsedLong() by the size of a string object. + message1.set_foo_string("abc"); + EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); + + // Setting a string in oneof to a value larger than the string object itself + // should increase SpaceUsedLong(), because it cannot store the value + // internally. + message1.set_foo_string(string(sizeof(string) + 1, 'x')); + int min_expected_increase = message1.foo_string().capacity() + + sizeof(string); + EXPECT_LE(empty_message_size + min_expected_increase, + message1.SpaceUsedLong()); + + // Setting a message in oneof should delete the other fields and increase the + // size by the size of the nested message type. NestedMessage is simple enough + // that it is equal to sizeof(NestedMessage) + message1.mutable_foo_message(); + ASSERT_EQ(sizeof(UNITTEST::TestOneof2::NestedMessage), + message1.foo_message().SpaceUsedLong()); + EXPECT_EQ(empty_message_size + + sizeof(UNITTEST::TestOneof2::NestedMessage), + message1.SpaceUsedLong()); +} + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + + +TEST(GENERATED_MESSAGE_TEST_NAME, FieldConstantValues) { + UNITTEST::TestRequired message; + EXPECT_EQ(UNITTEST::TestAllTypes_NestedMessage::kBbFieldNumber, 1); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalInt32FieldNumber, 1); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalgroupFieldNumber, 16); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedMessageFieldNumber, 18); + EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedEnumFieldNumber, 21); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedInt32FieldNumber, 31); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedgroupFieldNumber, 46); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48); + EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ExtensionConstantValues) { + EXPECT_EQ(UNITTEST::TestRequired::kSingleFieldNumber, 1000); + EXPECT_EQ(UNITTEST::TestRequired::kMultiFieldNumber, 1001); + EXPECT_EQ(UNITTEST::kOptionalInt32ExtensionFieldNumber, 1); + EXPECT_EQ(UNITTEST::kOptionalgroupExtensionFieldNumber, 16); + EXPECT_EQ(UNITTEST::kOptionalNestedMessageExtensionFieldNumber, 18); + EXPECT_EQ(UNITTEST::kOptionalNestedEnumExtensionFieldNumber, 21); + EXPECT_EQ(UNITTEST::kRepeatedInt32ExtensionFieldNumber, 31); + EXPECT_EQ(UNITTEST::kRepeatedgroupExtensionFieldNumber, 46); + EXPECT_EQ(UNITTEST::kRepeatedNestedMessageExtensionFieldNumber, 48); + EXPECT_EQ(UNITTEST::kRepeatedNestedEnumExtensionFieldNumber, 51); +} + +TEST(GENERATED_MESSAGE_TEST_NAME, ParseFromTruncated) { + const string long_string = string(128, 'q'); + FileDescriptorProto p; + p.add_extension()->set_name(long_string); + const string msg = p.SerializeAsString(); + int successful_count = 0; + for (int i = 0; i <= msg.size(); i++) { + if (p.ParseFromArray(msg.c_str(), i)) { + ++successful_count; + } + } + // We don't really care about how often we succeeded. + // As long as we didn't crash, we're happy. + EXPECT_GE(successful_count, 1); +} + +// =================================================================== + +TEST(GENERATED_ENUM_TEST_NAME, EnumValuesAsSwitchCases) { + // Test that our nested enum values can be used as switch cases. This test + // doesn't actually do anything, the proof that it works is that it + // compiles. + int i =0; + UNITTEST::TestAllTypes::NestedEnum a = UNITTEST::TestAllTypes::BAR; + switch (a) { + case UNITTEST::TestAllTypes::FOO: + i = 1; + break; + case UNITTEST::TestAllTypes::BAR: + i = 2; + break; + case UNITTEST::TestAllTypes::BAZ: + i = 3; + break; + case UNITTEST::TestAllTypes::NEG: + i = -1; + break; + // no default case: We want to make sure the compiler recognizes that + // all cases are covered. (GCC warns if you do not cover all cases of + // an enum in a switch.) + } + + // Token check just for fun. + EXPECT_EQ(2, i); +} + +TEST(GENERATED_ENUM_TEST_NAME, IsValidValue) { + // Test enum IsValidValue. + EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(1)); + EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(2)); + EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(3)); + + EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(0)); + EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(4)); + + // Make sure it also works when there are dups. + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(1)); + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(2)); + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(3)); + + EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(0)); + EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(4)); +} + +TEST(GENERATED_ENUM_TEST_NAME, MinAndMax) { + EXPECT_EQ(UNITTEST::TestAllTypes::NEG, + UNITTEST::TestAllTypes::NestedEnum_MIN); + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + UNITTEST::TestAllTypes::NestedEnum_MAX); + EXPECT_EQ(4, UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE); + + EXPECT_EQ(UNITTEST::FOREIGN_FOO, UNITTEST::ForeignEnum_MIN); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, UNITTEST::ForeignEnum_MAX); + EXPECT_EQ(7, UNITTEST::ForeignEnum_ARRAYSIZE); + + EXPECT_EQ(1, UNITTEST::TestEnumWithDupValue_MIN); + EXPECT_EQ(3, UNITTEST::TestEnumWithDupValue_MAX); + EXPECT_EQ(4, UNITTEST::TestEnumWithDupValue_ARRAYSIZE); + + EXPECT_EQ(UNITTEST::SPARSE_E, UNITTEST::TestSparseEnum_MIN); + EXPECT_EQ(UNITTEST::SPARSE_C, UNITTEST::TestSparseEnum_MAX); + EXPECT_EQ(12589235, UNITTEST::TestSparseEnum_ARRAYSIZE); + + // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE. + void* null_pointer = 0; // NULL may be integer-type, not pointer-type. + EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MIN); + EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MAX); + EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE); + + EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MIN); + EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MAX); + EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_ARRAYSIZE); + + // Make sure we can use _MIN and _MAX as switch cases. + switch (UNITTEST::SPARSE_A) { + case UNITTEST::TestSparseEnum_MIN: + case UNITTEST::TestSparseEnum_MAX: + break; + default: + break; + } +} + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +TEST(GENERATED_ENUM_TEST_NAME, Name) { + // "Names" in the presence of dup values are a bit arbitrary. + EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO1)); + EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO2)); + + EXPECT_EQ("SPARSE_A", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_A)); + EXPECT_EQ("SPARSE_B", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_B)); + EXPECT_EQ("SPARSE_C", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_C)); + EXPECT_EQ("SPARSE_D", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_D)); + EXPECT_EQ("SPARSE_E", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_E)); + EXPECT_EQ("SPARSE_F", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_F)); + EXPECT_EQ("SPARSE_G", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_G)); +} + +TEST(GENERATED_ENUM_TEST_NAME, Parse) { + UNITTEST::TestEnumWithDupValue dup_value = UNITTEST::FOO1; + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO1", &dup_value)); + EXPECT_EQ(UNITTEST::FOO1, dup_value); + EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO2", &dup_value)); + EXPECT_EQ(UNITTEST::FOO2, dup_value); + EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_Parse("FOO", &dup_value)); +} + +TEST(GENERATED_ENUM_TEST_NAME, GetEnumDescriptor) { + EXPECT_EQ(UNITTEST::TestAllTypes::NestedEnum_descriptor(), + GetEnumDescriptor()); + EXPECT_EQ(UNITTEST::ForeignEnum_descriptor(), + GetEnumDescriptor()); + EXPECT_EQ(UNITTEST::TestEnumWithDupValue_descriptor(), + GetEnumDescriptor()); + EXPECT_EQ(UNITTEST::TestSparseEnum_descriptor(), + GetEnumDescriptor()); +} + +enum NonProtoEnum { + kFoo = 1, +}; + +TEST(GENERATED_ENUM_TEST_NAME, IsProtoEnumTypeTrait) { + EXPECT_TRUE(is_proto_enum::value); + EXPECT_TRUE(is_proto_enum::value); + EXPECT_TRUE(is_proto_enum::value); + EXPECT_TRUE(is_proto_enum::value); + + EXPECT_FALSE(is_proto_enum::value); + EXPECT_FALSE(is_proto_enum::value); +} + +#endif // PROTOBUF_TEST_NO_DESCRIPTORS + +// =================================================================== + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + +// Support code for testing services. +class GENERATED_SERVICE_TEST_NAME : public testing::Test { + protected: + class MockTestService : public UNITTEST::TestService { + public: + MockTestService() + : called_(false), + method_(""), + controller_(NULL), + request_(NULL), + response_(NULL), + done_(NULL) {} + + ~MockTestService() {} + + void Reset() { called_ = false; } + + // implements TestService ---------------------------------------- + + void Foo(RpcController* controller, + const UNITTEST::FooRequest* request, + UNITTEST::FooResponse* response, + Closure* done) { + ASSERT_FALSE(called_); + called_ = true; + method_ = "Foo"; + controller_ = controller; + request_ = request; + response_ = response; + done_ = done; + } + + void Bar(RpcController* controller, + const UNITTEST::BarRequest* request, + UNITTEST::BarResponse* response, + Closure* done) { + ASSERT_FALSE(called_); + called_ = true; + method_ = "Bar"; + controller_ = controller; + request_ = request; + response_ = response; + done_ = done; + } + + // --------------------------------------------------------------- + + bool called_; + string method_; + RpcController* controller_; + const Message* request_; + Message* response_; + Closure* done_; + }; + + class MockRpcChannel : public RpcChannel { + public: + MockRpcChannel() + : called_(false), + method_(NULL), + controller_(NULL), + request_(NULL), + response_(NULL), + done_(NULL), + destroyed_(NULL) {} + + ~MockRpcChannel() { + if (destroyed_ != NULL) *destroyed_ = true; + } + + void Reset() { called_ = false; } + + // implements TestService ---------------------------------------- + + void CallMethod(const MethodDescriptor* method, + RpcController* controller, + const Message* request, + Message* response, + Closure* done) { + ASSERT_FALSE(called_); + called_ = true; + method_ = method; + controller_ = controller; + request_ = request; + response_ = response; + done_ = done; + } + + // --------------------------------------------------------------- + + bool called_; + const MethodDescriptor* method_; + RpcController* controller_; + const Message* request_; + Message* response_; + Closure* done_; + bool* destroyed_; + }; + + class MockController : public RpcController { + public: + void Reset() { + ADD_FAILURE() << "Reset() not expected during this test."; + } + bool Failed() const { + ADD_FAILURE() << "Failed() not expected during this test."; + return false; + } + string ErrorText() const { + ADD_FAILURE() << "ErrorText() not expected during this test."; + return ""; + } + void StartCancel() { + ADD_FAILURE() << "StartCancel() not expected during this test."; + } + void SetFailed(const string& reason) { + ADD_FAILURE() << "SetFailed() not expected during this test."; + } + bool IsCanceled() const { + ADD_FAILURE() << "IsCanceled() not expected during this test."; + return false; + } + void NotifyOnCancel(Closure* callback) { + ADD_FAILURE() << "NotifyOnCancel() not expected during this test."; + } + }; + + GENERATED_SERVICE_TEST_NAME() + : descriptor_(UNITTEST::TestService::descriptor()), + foo_(descriptor_->FindMethodByName("Foo")), + bar_(descriptor_->FindMethodByName("Bar")), + stub_(&mock_channel_), + done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {} + + virtual void SetUp() { + ASSERT_TRUE(foo_ != NULL); + ASSERT_TRUE(bar_ != NULL); + } + + const ServiceDescriptor* descriptor_; + const MethodDescriptor* foo_; + const MethodDescriptor* bar_; + + MockTestService mock_service_; + MockController mock_controller_; + + MockRpcChannel mock_channel_; + UNITTEST::TestService::Stub stub_; + + // Just so we don't have to re-define these with every test. + UNITTEST::FooRequest foo_request_; + UNITTEST::FooResponse foo_response_; + UNITTEST::BarRequest bar_request_; + UNITTEST::BarResponse bar_response_; + std::unique_ptr done_; +}; + +TEST_F(GENERATED_SERVICE_TEST_NAME, GetDescriptor) { + // Test that GetDescriptor() works. + + EXPECT_EQ(descriptor_, mock_service_.GetDescriptor()); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, GetChannel) { + EXPECT_EQ(&mock_channel_, stub_.channel()); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, OwnsChannel) { + MockRpcChannel* channel = new MockRpcChannel; + bool destroyed = false; + channel->destroyed_ = &destroyed; + + { + UNITTEST::TestService::Stub owning_stub(channel, + Service::STUB_OWNS_CHANNEL); + EXPECT_FALSE(destroyed); + } + + EXPECT_TRUE(destroyed); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethod) { + // Test that CallMethod() works. + + // Call Foo() via CallMethod(). + mock_service_.CallMethod(foo_, &mock_controller_, + &foo_request_, &foo_response_, done_.get()); + + ASSERT_TRUE(mock_service_.called_); + + EXPECT_EQ("Foo" , mock_service_.method_ ); + EXPECT_EQ(&mock_controller_, mock_service_.controller_); + EXPECT_EQ(&foo_request_ , mock_service_.request_ ); + EXPECT_EQ(&foo_response_ , mock_service_.response_ ); + EXPECT_EQ(done_.get() , mock_service_.done_ ); + + // Try again, but call Bar() instead. + mock_service_.Reset(); + mock_service_.CallMethod(bar_, &mock_controller_, + &bar_request_, &bar_response_, done_.get()); + + ASSERT_TRUE(mock_service_.called_); + EXPECT_EQ("Bar", mock_service_.method_); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethodTypeFailure) { + // Verify death if we call Foo() with Bar's message types. + +#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet + EXPECT_DEBUG_DEATH( + mock_service_.CallMethod(foo_, &mock_controller_, + &foo_request_, &bar_response_, done_.get()), + "dynamic_cast"); + + mock_service_.Reset(); + EXPECT_DEBUG_DEATH( + mock_service_.CallMethod(foo_, &mock_controller_, + &bar_request_, &foo_response_, done_.get()), + "dynamic_cast"); +#endif // PROTOBUF_HAS_DEATH_TEST +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, GetPrototypes) { + // Test Get{Request,Response}Prototype() methods. + + EXPECT_EQ(&UNITTEST::FooRequest::default_instance(), + &mock_service_.GetRequestPrototype(foo_)); + EXPECT_EQ(&UNITTEST::BarRequest::default_instance(), + &mock_service_.GetRequestPrototype(bar_)); + + EXPECT_EQ(&UNITTEST::FooResponse::default_instance(), + &mock_service_.GetResponsePrototype(foo_)); + EXPECT_EQ(&UNITTEST::BarResponse::default_instance(), + &mock_service_.GetResponsePrototype(bar_)); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, Stub) { + // Test that the stub class works. + + // Call Foo() via the stub. + stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get()); + + ASSERT_TRUE(mock_channel_.called_); + + EXPECT_EQ(foo_ , mock_channel_.method_ ); + EXPECT_EQ(&mock_controller_, mock_channel_.controller_); + EXPECT_EQ(&foo_request_ , mock_channel_.request_ ); + EXPECT_EQ(&foo_response_ , mock_channel_.response_ ); + EXPECT_EQ(done_.get() , mock_channel_.done_ ); + + // Call Bar() via the stub. + mock_channel_.Reset(); + stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get()); + + ASSERT_TRUE(mock_channel_.called_); + EXPECT_EQ(bar_, mock_channel_.method_); +} + +TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) { + // Test that failing to implement a method of a service causes it to fail + // with a "not implemented" error message. + + // A service which doesn't implement any methods. + class UnimplementedService : public UNITTEST::TestService { + public: + UnimplementedService() {} + }; + + UnimplementedService unimplemented_service; + + // And a controller which expects to get a "not implemented" error. + class ExpectUnimplementedController : public MockController { + public: + ExpectUnimplementedController() : called_(false) {} + + void SetFailed(const string& reason) { + EXPECT_FALSE(called_); + called_ = true; + EXPECT_EQ("Method Foo() not implemented.", reason); + } + + bool called_; + }; + + ExpectUnimplementedController controller; + + // Call Foo. + unimplemented_service.Foo(&controller, &foo_request_, &foo_response_, + done_.get()); + + EXPECT_TRUE(controller.called_); +} + +// =================================================================== + +class OneofTest : public testing::Test { + protected: + virtual void SetUp() { + } + + void ExpectEnumCasesWork(const UNITTEST::TestOneof2 &message) { + switch (message.foo_case()) { + case UNITTEST::TestOneof2::kFooInt: + EXPECT_TRUE(message.has_foo_int()); + break; + case UNITTEST::TestOneof2::kFooString: + EXPECT_TRUE(message.has_foo_string()); + break; + case UNITTEST::TestOneof2::kFooCord: + EXPECT_TRUE(message.has_foo_cord()); + break; + case UNITTEST::TestOneof2::kFooStringPiece: + EXPECT_TRUE(message.has_foo_string_piece()); + break; + case UNITTEST::TestOneof2::kFooBytes: + EXPECT_TRUE(message.has_foo_bytes()); + break; + case UNITTEST::TestOneof2::kFooEnum: + EXPECT_TRUE(message.has_foo_enum()); + break; + case UNITTEST::TestOneof2::kFooMessage: + EXPECT_TRUE(message.has_foo_message()); + break; + case UNITTEST::TestOneof2::kFoogroup: + EXPECT_TRUE(message.has_foogroup()); + break; + case UNITTEST::TestOneof2::kFooLazyMessage: + EXPECT_TRUE(message.has_foo_lazy_message()); + break; + case UNITTEST::TestOneof2::FOO_NOT_SET: + break; + } + } +}; + +TEST_F(OneofTest, SettingOneFieldClearsOthers) { + UNITTEST::TestOneof2 message; + + message.set_foo_int(123); + EXPECT_TRUE(message.has_foo_int()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.set_foo_string("foo"); + EXPECT_TRUE(message.has_foo_string()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + + message.set_foo_bytes("qux"); + EXPECT_TRUE(message.has_foo_bytes()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.set_foo_enum(UNITTEST::TestOneof2::FOO); + EXPECT_TRUE(message.has_foo_enum()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.mutable_foo_message()->set_qux_int(234); + EXPECT_TRUE(message.has_foo_message()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + message.mutable_foogroup()->set_a(345); + EXPECT_TRUE(message.has_foogroup()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); + + + // we repeat this because we didn't test if this properly clears other fields + // at the beginning. + message.set_foo_int(123); + EXPECT_TRUE(message.has_foo_int()); + TestUtil::ExpectAtMostOneFieldSetInOneof(message); +} + +TEST_F(OneofTest, EnumCases) { + UNITTEST::TestOneof2 message; + + message.set_foo_int(123); + ExpectEnumCasesWork(message); + message.set_foo_string("foo"); + ExpectEnumCasesWork(message); + message.set_foo_bytes("qux"); + ExpectEnumCasesWork(message); + message.set_foo_enum(UNITTEST::TestOneof2::FOO); + ExpectEnumCasesWork(message); + message.mutable_foo_message()->set_qux_int(234); + ExpectEnumCasesWork(message); + message.mutable_foogroup()->set_a(345); + ExpectEnumCasesWork(message); +} + +TEST_F(OneofTest, PrimitiveType) { + UNITTEST::TestOneof2 message; + // Unset field returns default value + EXPECT_EQ(message.foo_int(), 0); + + message.set_foo_int(123); + EXPECT_TRUE(message.has_foo_int()); + EXPECT_EQ(message.foo_int(), 123); + message.clear_foo_int(); + EXPECT_FALSE(message.has_foo_int()); +} + +TEST_F(OneofTest, EnumType) { + UNITTEST::TestOneof2 message; + // Unset field returns default value + EXPECT_EQ(message.foo_enum(), 1); + + message.set_foo_enum(UNITTEST::TestOneof2::FOO); + EXPECT_TRUE(message.has_foo_enum()); + EXPECT_EQ(message.foo_enum(), UNITTEST::TestOneof2::FOO); + message.clear_foo_enum(); + EXPECT_FALSE(message.has_foo_enum()); +} + +TEST_F(OneofTest, SetString) { + // Check that setting a string field in various ways works + UNITTEST::TestOneof2 message; + + // Unset field returns default value + EXPECT_EQ(message.foo_string(), ""); + + message.set_foo_string("foo"); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "foo"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + message.set_foo_string(string("bar")); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "bar"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + + message.set_foo_string("qux", 3); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "qux"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + message.mutable_foo_string()->assign("quux"); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "quux"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); + + message.set_foo_string("corge"); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "corge"); + message.clear_foo_string(); + EXPECT_FALSE(message.has_foo_string()); +} + +TEST_F(OneofTest, ReleaseString) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestOneof2 message; + + EXPECT_EQ(NULL, message.release_foo_string()); + EXPECT_FALSE(message.has_foo_string()); + + message.set_foo_string("blah"); + EXPECT_TRUE(message.has_foo_string()); + std::unique_ptr str(message.release_foo_string()); + EXPECT_FALSE(message.has_foo_string()); + ASSERT_TRUE(str != NULL); + EXPECT_EQ("blah", *str); + + EXPECT_EQ(NULL, message.release_foo_string()); + EXPECT_FALSE(message.has_foo_string()); +} + +TEST_F(OneofTest, SetAllocatedString) { + // Check that set_allocated_foo() works for strings. + UNITTEST::TestOneof2 message; + + EXPECT_FALSE(message.has_foo_string()); + const string kHello("hello"); + message.set_foo_string(kHello); + EXPECT_TRUE(message.has_foo_string()); + + message.set_allocated_foo_string(NULL); + EXPECT_FALSE(message.has_foo_string()); + EXPECT_EQ("", message.foo_string()); + + message.set_allocated_foo_string(new string(kHello)); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(kHello, message.foo_string()); +} + + +TEST_F(OneofTest, SetMessage) { + // Check that setting a message field works + UNITTEST::TestOneof2 message; + + // Unset field returns default instance + EXPECT_EQ(&message.foo_message(), + &UNITTEST::TestOneof2_NestedMessage::default_instance()); + EXPECT_EQ(message.foo_message().qux_int(), 0); + + message.mutable_foo_message()->set_qux_int(234); + EXPECT_TRUE(message.has_foo_message()); + EXPECT_EQ(message.foo_message().qux_int(), 234); + message.clear_foo_message(); + EXPECT_FALSE(message.has_foo_message()); +} + +TEST_F(OneofTest, ReleaseMessage) { + // Check that release_foo() starts out NULL, and gives us a value + // that we can delete after it's been set. + UNITTEST::TestOneof2 message; + + EXPECT_EQ(NULL, message.release_foo_message()); + EXPECT_FALSE(message.has_foo_message()); + + message.mutable_foo_message()->set_qux_int(1); + EXPECT_TRUE(message.has_foo_message()); + std::unique_ptr mes( + message.release_foo_message()); + EXPECT_FALSE(message.has_foo_message()); + ASSERT_TRUE(mes != NULL); + EXPECT_EQ(1, mes->qux_int()); + + EXPECT_EQ(NULL, message.release_foo_message()); + EXPECT_FALSE(message.has_foo_message()); +} + +TEST_F(OneofTest, SetAllocatedMessage) { + // Check that set_allocated_foo() works for messages. + UNITTEST::TestOneof2 message; + + EXPECT_FALSE(message.has_foo_message()); + + message.mutable_foo_message()->set_qux_int(1); + EXPECT_TRUE(message.has_foo_message()); + + message.set_allocated_foo_message(NULL); + EXPECT_FALSE(message.has_foo_message()); + EXPECT_EQ(&message.foo_message(), + &UNITTEST::TestOneof2_NestedMessage::default_instance()); + + message.mutable_foo_message()->set_qux_int(1); + UNITTEST::TestOneof2_NestedMessage* mes = message.release_foo_message(); + ASSERT_TRUE(mes != NULL); + EXPECT_FALSE(message.has_foo_message()); + + message.set_allocated_foo_message(mes); + EXPECT_TRUE(message.has_foo_message()); + EXPECT_EQ(1, message.foo_message().qux_int()); +} + + +TEST_F(OneofTest, Clear) { + UNITTEST::TestOneof2 message; + + message.set_foo_int(1); + EXPECT_TRUE(message.has_foo_int()); + message.clear_foo_int(); + EXPECT_FALSE(message.has_foo_int()); +} + +TEST_F(OneofTest, Defaults) { + UNITTEST::TestOneof2 message; + + EXPECT_FALSE(message.has_foo_int()); + EXPECT_EQ(message.foo_int(), 0); + + EXPECT_FALSE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), ""); + + + EXPECT_FALSE(message.has_foo_bytes()); + EXPECT_EQ(message.foo_bytes(), ""); + + EXPECT_FALSE(message.has_foo_enum()); + EXPECT_EQ(message.foo_enum(), 1); + + EXPECT_FALSE(message.has_foo_message()); + EXPECT_EQ(message.foo_message().qux_int(), 0); + + EXPECT_FALSE(message.has_foogroup()); + EXPECT_EQ(message.foogroup().a(), 0); + + + EXPECT_FALSE(message.has_bar_int()); + EXPECT_EQ(message.bar_int(), 5); + + EXPECT_FALSE(message.has_bar_string()); + EXPECT_EQ(message.bar_string(), "STRING"); + + + EXPECT_FALSE(message.has_bar_bytes()); + EXPECT_EQ(message.bar_bytes(), "BYTES"); + + EXPECT_FALSE(message.has_bar_enum()); + EXPECT_EQ(message.bar_enum(), 2); +} + +TEST_F(OneofTest, SwapWithEmpty) { + UNITTEST::TestOneof2 message1, message2; + message1.set_foo_string("FOO"); + EXPECT_TRUE(message1.has_foo_string()); + message1.Swap(&message2); + EXPECT_FALSE(message1.has_foo_string()); + EXPECT_TRUE(message2.has_foo_string()); + EXPECT_EQ(message2.foo_string(), "FOO"); +} + +TEST_F(OneofTest, SwapWithSelf) { + UNITTEST::TestOneof2 message; + message.set_foo_string("FOO"); + EXPECT_TRUE(message.has_foo_string()); + message.Swap(&message); + EXPECT_TRUE(message.has_foo_string()); + EXPECT_EQ(message.foo_string(), "FOO"); +} + +TEST_F(OneofTest, SwapBothHasFields) { + UNITTEST::TestOneof2 message1, message2; + + message1.set_foo_string("FOO"); + EXPECT_TRUE(message1.has_foo_string()); + message2.mutable_foo_message()->set_qux_int(1); + EXPECT_TRUE(message2.has_foo_message()); + + message1.Swap(&message2); + EXPECT_FALSE(message1.has_foo_string()); + EXPECT_FALSE(message2.has_foo_message()); + EXPECT_TRUE(message1.has_foo_message()); + EXPECT_EQ(message1.foo_message().qux_int(), 1); + EXPECT_TRUE(message2.has_foo_string()); + EXPECT_EQ(message2.foo_string(), "FOO"); +} + +TEST_F(OneofTest, CopyConstructor) { + UNITTEST::TestOneof2 message1; + message1.set_foo_bytes("FOO"); + + UNITTEST::TestOneof2 message2(message1); + EXPECT_TRUE(message2.has_foo_bytes()); + EXPECT_EQ(message2.foo_bytes(), "FOO"); +} + +TEST_F(OneofTest, CopyFrom) { + UNITTEST::TestOneof2 message1, message2; + message1.set_foo_enum(UNITTEST::TestOneof2::BAR); + EXPECT_TRUE(message1.has_foo_enum()); + + message2.CopyFrom(message1); + EXPECT_TRUE(message2.has_foo_enum()); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR); + + // Copying from self should be a no-op. + message2.CopyFrom(message2); + EXPECT_TRUE(message2.has_foo_enum()); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR); +} + +TEST_F(OneofTest, CopyAssignmentOperator) { + UNITTEST::TestOneof2 message1; + message1.mutable_foo_message()->set_qux_int(123); + EXPECT_TRUE(message1.has_foo_message()); + + UNITTEST::TestOneof2 message2; + message2 = message1; + EXPECT_EQ(message2.foo_message().qux_int(), 123); + + // Make sure that self-assignment does something sane. + message2 = message2; + EXPECT_EQ(message2.foo_message().qux_int(), 123); +} + +TEST_F(OneofTest, UpcastCopyFrom) { + // Test the CopyFrom method that takes in the generic const Message& + // parameter. + UNITTEST::TestOneof2 message1, message2; + message1.mutable_foogroup()->set_a(123); + EXPECT_TRUE(message1.has_foogroup()); + + const Message* source = implicit_cast(&message1); + message2.CopyFrom(*source); + + EXPECT_TRUE(message2.has_foogroup()); + EXPECT_EQ(message2.foogroup().a(), 123); +} + +// Test the generated SerializeWithCachedSizesToArray(), +// This indirectly tests MergePartialFromCodedStream() +// We have to test each field type separately because we cannot set them at the +// same time +TEST_F(OneofTest, SerializationToArray) { + // Primitive type + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_int(123); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_int(), 123); + } + + // String + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_string("foo"); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_string(), "foo"); + } + + + // Bytes + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_bytes("qux"); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_bytes(), "qux"); + } + + // Enum + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_enum(UNITTEST::TestOneof2::FOO); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); + } + + // Message + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foo_message()->set_qux_int(234); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foo_message().qux_int(), 234); + } + + // Group + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foogroup()->set_a(345); + int size = message1.ByteSizeLong(); + data.resize(size); + uint8* start = reinterpret_cast(string_as_array(&data)); + uint8* end = message1.SerializeWithCachedSizesToArray(start); + EXPECT_EQ(size, end - start); + EXPECT_TRUE(message2.ParseFromString(data)); + EXPECT_EQ(message2.foogroup().a(), 345); + } + +} + +// Test the generated SerializeWithCachedSizes() by forcing the buffer to write +// one byte at a time. +// This indirectly tests MergePartialFromCodedStream() +// We have to test each field type separately because we cannot set them at the +// same time +TEST_F(OneofTest, SerializationToStream) { + // Primitive type + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_int(123); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + EXPECT_EQ(message2.foo_int(), 123); + } + + // String + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_string("foo"); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + EXPECT_EQ(message2.foo_string(), "foo"); + } + + + // Bytes + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_bytes("qux"); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + EXPECT_EQ(message2.foo_bytes(), "qux"); + } + + // Enum + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.set_foo_enum(UNITTEST::TestOneof2::FOO); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); + } + + // Message + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foo_message()->set_qux_int(234); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + EXPECT_EQ(message2.foo_message().qux_int(), 234); + } + + // Group + { + UNITTEST::TestOneof2 message1, message2; + string data; + message1.mutable_foogroup()->set_a(345); + int size = message1.ByteSizeLong(); + data.resize(size); + + { + // Allow the output stream to buffer only one byte at a time. + io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); + 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)); + EXPECT_EQ(message2.foogroup().a(), 345); + } + +} + +TEST_F(OneofTest, MergeFrom) { + UNITTEST::TestOneof2 message1, message2; + + message1.set_foo_int(123); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_int()); + EXPECT_EQ(message2.foo_int(), 123); + + message1.set_foo_string("foo"); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_string()); + EXPECT_EQ(message2.foo_string(), "foo"); + + + message1.set_foo_bytes("qux"); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_bytes()); + EXPECT_EQ(message2.foo_bytes(), "qux"); + + message1.set_foo_enum(UNITTEST::TestOneof2::FOO); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_enum()); + EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); + + message1.mutable_foo_message()->set_qux_int(234); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foo_message()); + EXPECT_EQ(message2.foo_message().qux_int(), 234); + + message1.mutable_foogroup()->set_a(345); + message2.MergeFrom(message1); + TestUtil::ExpectAtMostOneFieldSetInOneof(message2); + EXPECT_TRUE(message2.has_foogroup()); + EXPECT_EQ(message2.foogroup().a(), 345); + +} + +TEST(HELPERS_TEST_NAME, TestSCC) { + UNITTEST::TestMutualRecursionA a; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor()); + std::vector names; + for (int i = 0; i < scc->descriptors.size(); i++) { + names.push_back(scc->descriptors[i]->full_name()); + } + string package = a.GetDescriptor()->file()->package(); + ASSERT_EQ(names.size(), 4); + std::sort(names.begin(), names.end()); + EXPECT_EQ(names[0], package + ".TestMutualRecursionA"); + EXPECT_EQ(names[1], package + ".TestMutualRecursionA.SubGroup"); + EXPECT_EQ(names[2], package + ".TestMutualRecursionA.SubMessage"); + EXPECT_EQ(names[3], package + ".TestMutualRecursionB"); + + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, true); + EXPECT_EQ(result.contains_required, false); + EXPECT_EQ(result.contains_cord, true); // TestAllTypes + EXPECT_EQ(result.contains_extension, false); // TestAllTypes +} + +TEST(HELPERS_TEST_NAME, TestSCCAnalysis) { + { + UNITTEST::TestRecursiveMessage msg; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, true); + EXPECT_EQ(result.contains_required, false); + EXPECT_EQ(result.contains_cord, false); + EXPECT_EQ(result.contains_extension, false); + } + { + UNITTEST::TestAllExtensions msg; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, false); + EXPECT_EQ(result.contains_required, false); + EXPECT_EQ(result.contains_cord, false); + EXPECT_EQ(result.contains_extension, true); + } + { + UNITTEST::TestRequired msg; + SCCAnalyzer scc_analyzer((Options())); + const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); + MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); + EXPECT_EQ(result.is_recursive, false); + EXPECT_EQ(result.contains_required, true); + EXPECT_EQ(result.contains_cord, false); + EXPECT_EQ(result.contains_extension, false); + } +} + +} // namespace cpp_unittest +} // namespace cpp +} // namespace compiler + +namespace no_generic_services_test { + // Verify that no class called "TestService" was defined in + // unittest_no_generic_services.pb.h by defining a different type by the same + // name. If such a service was generated, this will not compile. + struct TestService { + int i; + }; +} + +namespace compiler { +namespace cpp { +namespace cpp_unittest { + +TEST_F(GENERATED_SERVICE_TEST_NAME, NoGenericServices) { + // Verify that non-services in unittest_no_generic_services.proto were + // generated. + no_generic_services_test::TestMessage message; + message.set_a(1); + message.SetExtension(no_generic_services_test::test_extension, 123); + no_generic_services_test::TestEnum e = no_generic_services_test::FOO; + EXPECT_EQ(e, 1); + + // Verify that a ServiceDescriptor is generated for the service even if the + // class itself is not. + const FileDescriptor* file = + no_generic_services_test::TestMessage::descriptor()->file(); + + ASSERT_EQ(1, file->service_count()); + EXPECT_EQ("TestService", file->service(0)->name()); + ASSERT_EQ(1, file->service(0)->method_count()); + EXPECT_EQ("Foo", file->service(0)->method(0)->name()); +} + +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS + +// =================================================================== + +// This test must run last. It verifies that descriptors were or were not +// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined. +// When this is defined, we skip all tests which are expected to trigger +// descriptor initialization. This verifies that everything else still works +// if descriptors are not initialized. +TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) { +#ifdef PROTOBUF_TEST_NO_DESCRIPTORS + bool should_have_descriptors = false; +#else + bool should_have_descriptors = true; +#endif + + EXPECT_EQ(should_have_descriptors, + DescriptorPool::generated_pool()->InternalIsFileLoaded( + UNITTEST_PROTO_PATH)); +} + +} // namespace cpp_unittest + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/src/google/protobuf/compiler/cpp/metadata_test.cc b/src/google/protobuf/compiler/cpp/metadata_test.cc index 456784c6e8..2ad4edd248 100644 --- a/src/google/protobuf/compiler/cpp/metadata_test.cc +++ b/src/google/protobuf/compiler/cpp/metadata_test.cc @@ -29,9 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc index a5341e0dd0..c3831e72a6 100644 --- a/src/google/protobuf/compiler/importer.cc +++ b/src/google/protobuf/compiler/importer.cc @@ -32,7 +32,6 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. - #ifdef _MSC_VER #include #else @@ -45,9 +44,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include @@ -55,6 +51,8 @@ #include #include #include + + #include #ifdef _WIN32 @@ -131,7 +129,7 @@ SourceTreeDescriptorDatabase::~SourceTreeDescriptorDatabase() {} bool SourceTreeDescriptorDatabase::FindFileByName( const string& filename, FileDescriptorProto* output) { - google::protobuf::scoped_ptr input(source_tree_->Open(filename)); + std::unique_ptr input(source_tree_->Open(filename)); if (input == NULL) { if (error_collector_ != NULL) { error_collector_->AddError(filename, -1, 0, @@ -420,7 +418,7 @@ DiskSourceTree::DiskFileToVirtualFile( // Verify that we can open the file. Note that this also has the side-effect // of verifying that we are not canonicalizing away any non-existent // directories. - google::protobuf::scoped_ptr stream(OpenDiskFile(disk_file)); + std::unique_ptr stream(OpenDiskFile(disk_file)); if (stream == NULL) { return CANNOT_OPEN; } @@ -430,7 +428,7 @@ DiskSourceTree::DiskFileToVirtualFile( bool DiskSourceTree::VirtualFileToDiskFile(const string& virtual_file, string* disk_file) { - google::protobuf::scoped_ptr stream( + std::unique_ptr stream( OpenVirtualFile(virtual_file, disk_file)); return stream != NULL; } diff --git a/src/google/protobuf/compiler/importer_unittest.cc b/src/google/protobuf/compiler/importer_unittest.cc index a96ac85339..73bef3f4b0 100644 --- a/src/google/protobuf/compiler/importer_unittest.cc +++ b/src/google/protobuf/compiler/importer_unittest.cc @@ -36,9 +36,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -268,7 +265,7 @@ class DiskSourceTreeTest : public testing::Test { void ExpectFileContents(const string& filename, const char* expected_contents) { - google::protobuf::scoped_ptr input(source_tree_.Open(filename)); + std::unique_ptr input(source_tree_.Open(filename)); ASSERT_FALSE(input == NULL); @@ -285,7 +282,7 @@ class DiskSourceTreeTest : public testing::Test { void ExpectCannotOpenFile(const string& filename, const string& error_message) { - google::protobuf::scoped_ptr input(source_tree_.Open(filename)); + std::unique_ptr input(source_tree_.Open(filename)); EXPECT_TRUE(input == NULL); EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage()); } diff --git a/src/google/protobuf/compiler/java/java_context.cc b/src/google/protobuf/compiler/java/java_context.cc index 0771d5e19c..2528c2d13f 100644 --- a/src/google/protobuf/compiler/java/java_context.cc +++ b/src/google/protobuf/compiler/java/java_context.cc @@ -69,14 +69,14 @@ bool IsConflicting(const FieldDescriptor* field1, const string& name1, // field1 is repeated, and field2 is not. if (name1 + "Count" == name2) { *info = "both repeated field \"" + field1->name() + "\" and singular " + - "field \"" + field2->name() + "\" generates the method \"" + - "get" + name1 + "Count()\""; + "field \"" + field2->name() + "\" generate the method \"" + + "get" + name1 + "Count()\""; return true; } if (name1 + "List" == name2) { *info = "both repeated field \"" + field1->name() + "\" and singular " + - "field \"" + field2->name() + "\" generates the method \"" + - "get" + name1 + "List()\""; + "field \"" + field2->name() + "\" generate the method \"" + + "get" + name1 + "List()\""; return true; } // Well, there are obviously many more conflicting cases, but it probably diff --git a/src/google/protobuf/compiler/java/java_context.h b/src/google/protobuf/compiler/java/java_context.h index 9a74c4303d..9de7415ad2 100644 --- a/src/google/protobuf/compiler/java/java_context.h +++ b/src/google/protobuf/compiler/java/java_context.h @@ -33,9 +33,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -97,7 +94,7 @@ class Context { void InitializeFieldGeneratorInfoForFields( const std::vector& fields); - google::protobuf::scoped_ptr name_resolver_; + std::unique_ptr name_resolver_; std::map field_generator_info_map_; std::map diff --git a/src/google/protobuf/compiler/java/java_enum.cc b/src/google/protobuf/compiler/java/java_enum.cc index d125ebe52c..bef69f1a10 100644 --- a/src/google/protobuf/compiler/java/java_enum.cc +++ b/src/google/protobuf/compiler/java/java_enum.cc @@ -36,12 +36,12 @@ #include #include -#include #include +#include #include #include -#include #include +#include #include namespace google { diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/java_enum_field.cc index 642cdd3636..0686ea0f66 100644 --- a/src/google/protobuf/compiler/java/java_enum_field.cc +++ b/src/google/protobuf/compiler/java/java_enum_field.cc @@ -674,8 +674,7 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); } - if (descriptor_->is_packed() && - context_->HasGeneratedMethods(descriptor_->containing_type())) { + if (descriptor_->is_packed()) { printer->Print(variables_, "private int $name$MemoizedSerializedSize;\n"); } diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/src/google/protobuf/compiler/java/java_enum_field_lite.cc index a4de1e2334..f1fe71b044 100644 --- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_enum_field_lite.cc @@ -165,6 +165,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); @@ -173,6 +174,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " return $name$_;\n" "}\n"); @@ -180,6 +182,7 @@ GenerateMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " $type$ result = $type$.forNumber($name$_);\n" " return result == null ? $unknown$ : result;\n" @@ -217,6 +220,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -225,6 +229,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " return instance.get$capitalized_name$Value();\n" "}\n"); @@ -241,6 +246,7 @@ GenerateBuilderMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -378,6 +384,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); @@ -386,6 +393,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " if ($has_oneof_case_message$) {\n" " return (java.lang.Integer) $oneof_name$_;\n" @@ -396,6 +404,7 @@ GenerateMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " if ($has_oneof_case_message$) {\n" " $type$ result = $type$.forNumber((java.lang.Integer) $oneof_name$_);\n" @@ -439,6 +448,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -447,6 +457,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" " return instance.get$capitalized_name$Value();\n" "}\n"); @@ -463,6 +474,7 @@ GenerateBuilderMembers(io::Printer* printer) const { } WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -611,6 +623,7 @@ GenerateMembers(io::Printer* printer) const { " java.lang.Integer, $type$> $name$_converter_ =\n" " new com.google.protobuf.Internal.ListAdapter.Converter<\n" " java.lang.Integer, $type$>() {\n" + " @java.lang.Override\n" " public $type$ convert(java.lang.Integer from) {\n" " $type$ result = $type$.forNumber(from);\n" " return result == null ? $unknown$ : result;\n" @@ -619,6 +632,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return new com.google.protobuf.Internal.ListAdapter<\n" @@ -627,12 +641,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return $name$_converter_.convert($name$_.getInt(index));\n" "}\n"); @@ -640,6 +656,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List\n" "${$get$capitalized_name$ValueList$}$() {\n" " return $name$_;\n" @@ -647,6 +664,7 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" " return $name$_.getInt(index);\n" "}\n"); @@ -732,6 +750,7 @@ void RepeatedImmutableEnumFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return instance.get$capitalized_name$List();\n" @@ -739,12 +758,14 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" "}\n"); @@ -787,6 +808,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List\n" "${$get$capitalized_name$ValueList$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -795,6 +817,7 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" " return instance.get$capitalized_name$Value(index);\n" "}\n"); diff --git a/src/google/protobuf/compiler/java/java_enum_lite.cc b/src/google/protobuf/compiler/java/java_enum_lite.cc index ab3b332345..806008ee13 100644 --- a/src/google/protobuf/compiler/java/java_enum_lite.cc +++ b/src/google/protobuf/compiler/java/java_enum_lite.cc @@ -36,12 +36,12 @@ #include #include -#include #include +#include #include #include -#include #include +#include #include namespace google { @@ -135,6 +135,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) { printer->Print( "\n" + "@java.lang.Override\n" "public final int getNumber() {\n"); if (SupportUnknownEnumValue(descriptor_->file())) { printer->Print( @@ -182,6 +183,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) { "private static final com.google.protobuf.Internal.EnumLiteMap<\n" " $classname$> internalValueMap =\n" " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" + " @java.lang.Override\n" " public $classname$ findValueByNumber(int number) {\n" " return $classname$.forNumber(number);\n" " }\n" diff --git a/src/google/protobuf/compiler/java/java_extension.cc b/src/google/protobuf/compiler/java/java_extension.cc index 9b9be55b42..3eb1370dd8 100644 --- a/src/google/protobuf/compiler/java/java_extension.cc +++ b/src/google/protobuf/compiler/java/java_extension.cc @@ -141,6 +141,7 @@ void ImmutableExtensionGenerator::Generate(io::Printer* printer) { " $singular_type$.class,\n" " $prototype$);\n"); } + printer->Annotate("name", descriptor_); } int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode( diff --git a/src/google/protobuf/compiler/java/java_extension_lite.cc b/src/google/protobuf/compiler/java/java_extension_lite.cc index c48c92e9fc..70ce8e7d1f 100644 --- a/src/google/protobuf/compiler/java/java_extension_lite.cc +++ b/src/google/protobuf/compiler/java/java_extension_lite.cc @@ -96,6 +96,7 @@ void ImmutableExtensionLiteGenerator::Generate(io::Printer* printer) { " com.google.protobuf.WireFormat.FieldType.$type_constant$,\n" " $singular_type$.class);\n"); } + printer->Annotate("name", descriptor_); } int ImmutableExtensionLiteGenerator::GenerateNonNestedInitializationCode( diff --git a/src/google/protobuf/compiler/java/java_field.cc b/src/google/protobuf/compiler/java/java_field.cc index 1ab1862953..d731968166 100644 --- a/src/google/protobuf/compiler/java/java_field.cc +++ b/src/google/protobuf/compiler/java/java_field.cc @@ -35,9 +35,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -214,7 +211,7 @@ template <> FieldGeneratorMap::FieldGeneratorMap( const Descriptor* descriptor, Context* context) : descriptor_(descriptor), - field_generators_(new google::protobuf::scoped_ptr< + field_generators_(new std::unique_ptr< ImmutableFieldGenerator>[descriptor->field_count()]) { // Construct all the FieldGenerators and assign them bit indices for their @@ -237,7 +234,7 @@ template <> FieldGeneratorMap::FieldGeneratorMap( const Descriptor* descriptor, Context* context) : descriptor_(descriptor), - field_generators_(new google::protobuf::scoped_ptr< + field_generators_(new std::unique_ptr< ImmutableFieldLiteGenerator>[descriptor->field_count()]) { // Construct all the FieldGenerators and assign them bit indices for their // bit fields. diff --git a/src/google/protobuf/compiler/java/java_field.h b/src/google/protobuf/compiler/java/java_field.h index cc1d83d981..04bbe24aa4 100644 --- a/src/google/protobuf/compiler/java/java_field.h +++ b/src/google/protobuf/compiler/java/java_field.h @@ -37,9 +37,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -141,7 +138,7 @@ class FieldGeneratorMap { const Descriptor* descriptor_; Context* context_; ClassNameResolver* name_resolver_; - google::protobuf::scoped_array > field_generators_; + std::unique_ptr []> field_generators_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; @@ -163,6 +160,14 @@ template<> FieldGeneratorMap::~FieldGeneratorMap(); +template <> +FieldGeneratorMap::FieldGeneratorMap( + const Descriptor* descriptor, Context* context); + +template <> +FieldGeneratorMap::~FieldGeneratorMap(); + + // Field information used in FieldGeneartors. struct FieldGeneratorInfo { string name; diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc index 21133a1512..5ee04e5a2d 100644 --- a/src/google/protobuf/compiler/java/java_file.cc +++ b/src/google/protobuf/compiler/java/java_file.cc @@ -35,9 +35,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -51,9 +48,9 @@ #include #include #include +#include #include #include -#include #include #include @@ -136,7 +133,7 @@ void CollectExtensions(const FileDescriptorProto& file_proto, "descriptor.proto is not in the transitive dependencies. " "This normally should not happen. Please report a bug."; DynamicMessageFactory factory; - google::protobuf::scoped_ptr dynamic_file_proto( + std::unique_ptr dynamic_file_proto( factory.GetPrototype(file_proto_desc)->New()); GOOGLE_CHECK(dynamic_file_proto.get() != NULL); GOOGLE_CHECK(dynamic_file_proto->ParseFromString(file_data)); @@ -190,9 +187,9 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options, : file_(file), java_package_(FileJavaPackage(file, immutable_api)), message_generators_( - new google::protobuf::scoped_ptr[file->message_type_count()]), + new std::unique_ptr[file->message_type_count()]), extension_generators_( - new google::protobuf::scoped_ptr[file->extension_count()]), + new std::unique_ptr[file->extension_count()]), context_(new Context(file, options)), name_resolver_(context_->GetNameResolver()), options_(options), @@ -309,7 +306,7 @@ void FileGenerator::Generate(io::Printer* printer) { } if (HasGenericServices(file_, context_->EnforceLite())) { for (int i = 0; i < file_->service_count(); i++) { - google::protobuf::scoped_ptr generator( + std::unique_ptr generator( generator_factory_->NewServiceGenerator(file_->service(i))); generator->Generate(printer); } @@ -435,7 +432,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( " com.google.protobuf.ExtensionRegistry.newInstance();\n"); FieldDescriptorSet::iterator it; for (it = extensions.begin(); it != extensions.end(); it++) { - google::protobuf::scoped_ptr generator( + std::unique_ptr generator( generator_factory_->NewExtensionGenerator(*it)); bytecode_estimate += generator->GenerateRegistrationCode(printer); MaybeRestartJavaMethod( @@ -588,7 +585,7 @@ static void GenerateSibling(const string& package_dir, io::AnnotationProtoCollector annotation_collector( &annotations); - google::protobuf::scoped_ptr output(context->Open(filename)); + std::unique_ptr output(context->Open(filename)); io::Printer printer(output.get(), '$', annotate_code ? &annotation_collector : NULL); @@ -607,7 +604,7 @@ static void GenerateSibling(const string& package_dir, (generator->*pfn)(&printer); if (annotate_code) { - google::protobuf::scoped_ptr info_output( + std::unique_ptr info_output( context->Open(info_full_path)); annotations.SerializeToZeroCopyStream(info_output.get()); annotation_list->push_back(info_full_path); @@ -650,7 +647,7 @@ void FileGenerator::GenerateSiblings(const string& package_dir, } if (HasGenericServices(file_, context_->EnforceLite())) { for (int i = 0; i < file_->service_count(); i++) { - google::protobuf::scoped_ptr generator( + std::unique_ptr generator( generator_factory_->NewServiceGenerator(file_->service(i))); GenerateSibling( package_dir, java_package_, file_->service(i), context, file_list, diff --git a/src/google/protobuf/compiler/java/java_file.h b/src/google/protobuf/compiler/java/java_file.h index e95aef0912..9ad7937c81 100644 --- a/src/google/protobuf/compiler/java/java_file.h +++ b/src/google/protobuf/compiler/java/java_file.h @@ -36,9 +36,6 @@ #define GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__ #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -101,10 +98,10 @@ class FileGenerator { string java_package_; string classname_; - google::protobuf::scoped_array > message_generators_; - google::protobuf::scoped_array > extension_generators_; - google::protobuf::scoped_ptr generator_factory_; - google::protobuf::scoped_ptr context_; + std::unique_ptr []> message_generators_; + std::unique_ptr []> extension_generators_; + std::unique_ptr generator_factory_; + std::unique_ptr context_; ClassNameResolver* name_resolver_; const Options options_; bool immutable_api_; diff --git a/src/google/protobuf/compiler/java/java_generator.cc b/src/google/protobuf/compiler/java/java_generator.cc index 84a3b90d6c..a5b2e78412 100644 --- a/src/google/protobuf/compiler/java/java_generator.cc +++ b/src/google/protobuf/compiler/java/java_generator.cc @@ -35,9 +35,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -45,9 +42,9 @@ #include #include #include +#include #include #include -#include #include @@ -144,7 +141,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, } // Generate main java file. - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->Open(java_filename)); GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( @@ -160,7 +157,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, &all_annotations); if (file_options.annotate_code) { - google::protobuf::scoped_ptr info_output( + std::unique_ptr info_output( context->Open(info_full_path)); annotations.SerializeToZeroCopyStream(info_output.get()); } @@ -175,7 +172,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, if (!file_options.output_list_file.empty()) { // Generate output list. This is just a simple text file placed in a // deterministic location which lists the .java files being generated. - google::protobuf::scoped_ptr srclist_raw_output( + std::unique_ptr srclist_raw_output( context->Open(file_options.output_list_file)); io::Printer srclist_printer(srclist_raw_output.get(), '$'); for (int i = 0; i < all_files.size(); i++) { @@ -186,7 +183,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file, if (!file_options.annotation_list_file.empty()) { // Generate output list. This is just a simple text file placed in a // deterministic location which lists the .java files being generated. - google::protobuf::scoped_ptr annotation_list_raw_output( + std::unique_ptr annotation_list_raw_output( context->Open(file_options.annotation_list_file)); io::Printer annotation_list_printer(annotation_list_raw_output.get(), '$'); for (int i = 0; i < all_annotations.size(); i++) { diff --git a/src/google/protobuf/compiler/java/java_helpers.cc b/src/google/protobuf/compiler/java/java_helpers.cc index dbb86b87fe..957076cb4a 100644 --- a/src/google/protobuf/compiler/java/java_helpers.cc +++ b/src/google/protobuf/compiler/java/java_helpers.cc @@ -75,6 +75,8 @@ const char* kForbiddenWordList[] = { "class", }; +const int kDefaultLookUpStartFieldNumber = 40; + bool IsForbidden(const string& field_name) { for (int i = 0; i < GOOGLE_ARRAYSIZE(kForbiddenWordList); ++i) { if (field_name == kForbiddenWordList[i]) { @@ -103,6 +105,20 @@ string FieldName(const FieldDescriptor* field) { } +// Judge whether should use table or use look up. +// Copied from com.google.protobuf.SchemaUtil.shouldUseTableSwitch +bool ShouldUseTable(int lo, int hi, int number_of_fields) { + if (hi < kDefaultLookUpStartFieldNumber) { + return true; + } + int64 table_space_cost = (static_cast(hi) - lo + 1); // words + int64 table_time_cost = 3; // comparisons + int64 lookup_space_cost = 3 + 2 * static_cast(number_of_fields); + int64 lookup_time_cost = 3 + number_of_fields; + return table_space_cost + 3 * table_time_cost <= + lookup_space_cost + 3 * lookup_time_cost; +} + } // namespace void PrintGeneratedAnnotation(io::Printer* printer, char delimiter, @@ -915,6 +931,23 @@ void EscapeUtf16ToString(uint16 code, string* output) { output->append(StringPrintf("\\u%04x", code)); } } + +std::pair GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( + const FieldDescriptor** fields, int count) { + GOOGLE_CHECK_GT(count, 0); + int table_driven_number_of_entries = count; + int look_up_start_field_number = 0; + for (int i = 0; i < count; i++) { + const int field_number = fields[i]->number(); + if (ShouldUseTable(fields[0]->number(), field_number, i + 1)) { + table_driven_number_of_entries = + field_number - fields[0]->number() + 1 + count - i - 1; + look_up_start_field_number = field_number + 1; + } + } + return std::make_pair( + table_driven_number_of_entries, look_up_start_field_number); +} } // namespace java } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/java/java_helpers.h b/src/google/protobuf/compiler/java/java_helpers.h index 00d683db56..dd9b65b816 100644 --- a/src/google/protobuf/compiler/java/java_helpers.h +++ b/src/google/protobuf/compiler/java/java_helpers.h @@ -37,8 +37,8 @@ #include #include -#include #include +#include #include namespace google { @@ -414,6 +414,11 @@ void EscapeUtf16ToString(uint16 code, string* output); // bit 3: whether the field is a map field with proto2 enum value. // bits 4-7: unused int GetExperimentalJavaFieldType(const FieldDescriptor* field); + +// To get the total number of entries need to be built for experimental runtime +// and the first field number that are not in the table part +std::pair GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( + const FieldDescriptor** fields, int count); } // namespace java } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.cc b/src/google/protobuf/compiler/java/java_map_field_lite.cc index f19ec271e0..e2e68076c7 100644 --- a/src/google/protobuf/compiler/java/java_map_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc @@ -301,6 +301,7 @@ GenerateMembers(io::Printer* printer) const { "}\n"); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public int ${$get$capitalized_name$Count$}$() {\n" " return internalGet$capitalized_name$().size();\n" @@ -309,6 +310,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public boolean ${$contains$capitalized_name$$}$(\n" " $key_type$ key) {\n" @@ -339,6 +341,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" "${$get$capitalized_name$Map$}$() {\n" @@ -352,6 +355,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -367,6 +371,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" @@ -385,6 +390,7 @@ GenerateMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$Value$}$() {\n" @@ -394,6 +400,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$ValueMap$}$() {\n" @@ -404,6 +411,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" " $key_type$ key,\n" @@ -417,6 +425,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" " $key_type$ key) {\n" @@ -436,6 +445,7 @@ GenerateMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$Map()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$$}$() {\n" @@ -445,6 +455,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$Map$}$() {\n" @@ -455,6 +466,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -468,6 +480,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" @@ -519,6 +532,7 @@ void ImmutableMapFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Map().size();\n" @@ -527,6 +541,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public boolean ${$contains$capitalized_name$$}$(\n" " $key_type$ key) {\n" @@ -570,6 +585,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" "${$get$capitalized_name$Map$}$() {\n" @@ -580,6 +596,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -595,6 +612,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" @@ -636,6 +654,7 @@ GenerateBuilderMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$Value$}$() {\n" @@ -645,6 +664,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" "${$get$capitalized_name$ValueMap$}$() {\n" @@ -655,6 +675,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" " $key_type$ key,\n" @@ -668,6 +689,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" " $key_type$ key) {\n" @@ -709,6 +731,7 @@ GenerateBuilderMembers(io::Printer* printer) const { "/**\n" " * Use {@link #get$capitalized_name$Map()} instead.\n" " */\n" + "@java.lang.Override\n" "@java.lang.Deprecated\n" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$$}$() {\n" @@ -718,6 +741,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$" "public java.util.Map<$type_parameters$> " "${$get$capitalized_name$Map$}$() {\n" @@ -728,6 +752,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n" " $key_type$ key,\n" @@ -741,6 +766,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, + "@java.lang.Override\n" "$deprecation$\n" "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" " $key_type$ key) {\n" diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc index 8964f632d5..209c0b2a2a 100644 --- a/src/google/protobuf/compiler/java/java_message.cc +++ b/src/google/protobuf/compiler/java/java_message.cc @@ -38,9 +38,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -52,9 +49,9 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -438,7 +435,8 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); printer->Print( "$deprecation$$field_name$($field_number$),\n", - "deprecation", field->options().deprecated() ? "@java.lang.Deprecated " : "", + "deprecation", + field->options().deprecated() ? "@java.lang.Deprecated " : "", "field_name", ToUpper(field->name()), "field_number", SimpleItoa(field->number())); } @@ -578,7 +576,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { void ImmutableMessageGenerator:: GenerateMessageSerializationMethods(io::Printer* printer) { - google::protobuf::scoped_array sorted_fields( + std::unique_ptr sorted_fields( SortFieldsByNumber(descriptor_)); std::vector sorted_extensions; @@ -1216,7 +1214,7 @@ GenerateExtensionRegistrationCode(io::Printer* printer) { // =================================================================== void ImmutableMessageGenerator:: GenerateParsingConstructor(io::Printer* printer) { - google::protobuf::scoped_array sorted_fields( + std::unique_ptr sorted_fields( SortFieldsByNumber(descriptor_)); printer->Print( diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc index 43c39b4aae..4c67e8066f 100644 --- a/src/google/protobuf/compiler/java/java_message_builder.cc +++ b/src/google/protobuf/compiler/java/java_message_builder.cc @@ -38,9 +38,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -50,9 +47,9 @@ #include #include #include +#include #include #include -#include #include #include #include diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.cc b/src/google/protobuf/compiler/java/java_message_builder_lite.cc index 1ad58c09ce..f04d394e7b 100644 --- a/src/google/protobuf/compiler/java/java_message_builder_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_builder_lite.cc @@ -38,9 +38,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -50,12 +47,12 @@ #include #include #include +#include #include #include -#include #include -#include #include +#include namespace google { namespace protobuf { @@ -109,6 +106,7 @@ Generate(io::Printer* printer) { // oneofCase() and clearOneof() printer->Print(vars, + "@java.lang.Override\n" "public $oneof_capitalized_name$Case\n" " get$oneof_capitalized_name$Case() {\n" " return instance.get$oneof_capitalized_name$Case();\n" diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.cc b/src/google/protobuf/compiler/java/java_message_field_lite.cc index df3e80d4e0..9cf6f36364 100644 --- a/src/google/protobuf/compiler/java/java_message_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc @@ -147,12 +147,14 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" "}\n"); @@ -160,12 +162,14 @@ GenerateMembers(io::Printer* printer) const { } else { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $name$_ != null;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" "}\n"); @@ -195,7 +199,11 @@ GenerateMembers(io::Printer* printer) const { // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.SuppressWarnings({\"ReferenceEquality\"})\n" "private void merge$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" " if ($name$_ != null &&\n" " $name$_ != $type$.getDefaultInstance()) {\n" " $name$_ =\n" @@ -223,6 +231,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -231,6 +240,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // Field getField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -396,12 +406,14 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " if ($has_oneof_case_message$) {\n" " return ($type$) $oneof_name$_;\n" @@ -434,6 +446,9 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "private void merge$capitalized_name$($type$ value) {\n" + " if (value == null) {\n" + " throw new NullPointerException();\n" + " }\n" " if ($has_oneof_case_message$ &&\n" " $oneof_name$_ != $type$.getDefaultInstance()) {\n" " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" @@ -464,6 +479,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -472,6 +488,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // Field getField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -624,6 +641,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return $name$_;\n" // note: unmodifiable list @@ -638,12 +656,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return $name$_.get(index);\n" "}\n"); @@ -761,6 +781,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // List getRepeatedFieldList() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$type$> " "${$get$capitalized_name$List$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -771,6 +792,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // int getRepeatedFieldCount() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}"); @@ -779,6 +801,7 @@ GenerateBuilderMembers(io::Printer* printer) const { // Field getRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" "}\n"); diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc index 108504c7ab..3a512e8dda 100644 --- a/src/google/protobuf/compiler/java/java_message_lite.cc +++ b/src/google/protobuf/compiler/java/java_message_lite.cc @@ -38,9 +38,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -52,9 +49,9 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -310,6 +307,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { " default: return null;\n" " }\n" "}\n" + "@java.lang.Override\n" "public int getNumber() {\n" " return this.value;\n" "}\n", @@ -318,6 +316,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Print("};\n\n"); // oneofCase() printer->Print(vars, + "@java.lang.Override\n" "public $oneof_capitalized_name$Case\n" "get$oneof_capitalized_name$Case() {\n" " return $oneof_capitalized_name$Case.forNumber(\n" @@ -356,6 +355,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { } printer->Print( + "@java.lang.Override\n" "@java.lang.SuppressWarnings({\"unchecked\", \"fallthrough\"})\n" "protected final java.lang.Object dynamicMethod(\n" " com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n" @@ -369,22 +369,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Indent(); printer->Indent(); - printer->Print("case IS_INITIALIZED: {\n"); - printer->Indent(); - GenerateDynamicMethodIsInitialized(printer); - printer->Outdent(); - - printer->Print("}\n"); - printer->Print( - "case MAKE_IMMUTABLE: {\n"); - - printer->Indent(); - GenerateDynamicMethodMakeImmutable(printer); - printer->Outdent(); - - printer->Print( - "}\n" "case NEW_BUILDER: {\n"); printer->Indent(); @@ -392,6 +377,22 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Outdent(); if (!EnableExperimentalRuntimeForLite()) { + printer->Print( + "}\n" + "case IS_INITIALIZED: {\n"); + printer->Indent(); + GenerateDynamicMethodIsInitialized(printer); + printer->Outdent(); + + printer->Print("}\n"); + + printer->Print( + "case MAKE_IMMUTABLE: {\n"); + + printer->Indent(); + GenerateDynamicMethodMakeImmutable(printer); + printer->Outdent(); + printer->Print( "}\n" "case VISIT: {\n"); @@ -399,15 +400,16 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Indent(); GenerateDynamicMethodVisit(printer); printer->Outdent(); - } - printer->Print( - "}\n" - "case MERGE_FROM_STREAM: {\n"); + printer->Print( + "}\n" + "case MERGE_FROM_STREAM: {\n"); + + printer->Indent(); + GenerateDynamicMethodMergeFromStream(printer); + printer->Outdent(); + } - printer->Indent(); - GenerateDynamicMethodMergeFromStream(printer); - printer->Outdent(); printer->Print( "}\n" @@ -420,14 +422,20 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { // manipulating static fields but that has exceptional cost on Android as // it will generate an extra class for every message. Instead, use the // double-check locking pattern which works just as well. - " if (PARSER == null) {" + // + // The "parser" temporary mirrors the "PARSER" field to eliminate a read + // at the final return statement. + " com.google.protobuf.Parser<$classname$> parser = PARSER;\n" + " if (parser == null) {\n" " synchronized ($classname$.class) {\n" - " if (PARSER == null) {\n" - " PARSER = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n" + " parser = PARSER;\n" + " if (parser == null) {\n" + " parser = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n" + " PARSER = parser;\n" " }\n" " }\n" " }\n" - " return PARSER;\n", + " return parser;\n", "classname", name_resolver_->GetImmutableClassName(descriptor_)); printer->Outdent(); @@ -475,8 +483,9 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Print( "static {\n" + " // New instances are implicitly immutable so no need to make\n" + " // immutable.\n" " DEFAULT_INSTANCE = new $classname$();\n" - " DEFAULT_INSTANCE.makeImmutable();\n" "}\n" "\n", "classname", descriptor_->name()); @@ -491,6 +500,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { "}\n", "classname", descriptor_->name()); } + printer->Print( "public static $classname$ getDefaultInstance() {\n" " return DEFAULT_INSTANCE;\n" @@ -519,6 +529,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { .Generate(printer); } + printer->Outdent(); printer->Print("}\n\n"); } @@ -528,7 +539,11 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { void ImmutableMessageLiteGenerator:: GenerateMessageSerializationMethods(io::Printer* printer) { - google::protobuf::scoped_array sorted_fields( + if (EnableExperimentalRuntimeForLite()) { + return; + } + + std::unique_ptr sorted_fields( SortFieldsByNumber(descriptor_)); std::vector sorted_extensions; @@ -539,6 +554,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) { ExtensionRangeOrdering()); printer->Print( + "@java.lang.Override\n" "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" " throws java.io.IOException {\n"); printer->Indent(); @@ -594,6 +610,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) { printer->Print( "}\n" "\n" + "@java.lang.Override\n" "public int getSerializedSize() {\n" " int size = memoizedSerializedSize;\n" " if (size != -1) return size;\n" @@ -1005,7 +1022,7 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream( " done = true;\n" " break;\n"); - google::protobuf::scoped_array sorted_fields( + std::unique_ptr sorted_fields( SortFieldsByNumber(descriptor_)); for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = sorted_fields[i]; diff --git a/src/google/protobuf/compiler/java/java_plugin_unittest.cc b/src/google/protobuf/compiler/java/java_plugin_unittest.cc index 3e4910c88a..87f687da18 100644 --- a/src/google/protobuf/compiler/java/java_plugin_unittest.cc +++ b/src/google/protobuf/compiler/java/java_plugin_unittest.cc @@ -35,9 +35,6 @@ // worth. #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -76,7 +73,7 @@ class TestGenerator : public CodeGenerator { void TryInsert(const string& filename, const string& insertion_point, GeneratorContext* context) const { - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); io::Printer printer(output.get(), '$'); printer.Print("// inserted $name$\n", "name", insertion_point); diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/java_primitive_field.cc index 074a6be867..71ee0992b1 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field.cc +++ b/src/google/protobuf/compiler/java/java_primitive_field.cc @@ -633,8 +633,7 @@ GenerateMembers(io::Printer* printer) const { "}\n"); printer->Annotate("{", "}", descriptor_); - if (descriptor_->is_packed() && - context_->HasGeneratedMethods(descriptor_->containing_type())) { + if (descriptor_->is_packed()) { printer->Print(variables_, "private int $name$MemoizedSerializedSize = -1;\n"); } diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc index f92931711f..d2ebc56741 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc @@ -222,6 +222,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); @@ -230,6 +231,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return $name$_;\n" "}\n"); @@ -266,6 +268,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -274,6 +277,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -488,6 +492,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); @@ -496,6 +501,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " if ($has_oneof_case_message$) {\n" " return ($boxed_type$) $oneof_name$_;\n" @@ -528,6 +534,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -536,6 +543,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -645,6 +653,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$boxed_type$>\n" " ${$get$capitalized_name$List$}$() {\n" " return $name$_;\n" // note: unmodifiable list @@ -652,12 +661,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return $repeated_get$(index);\n" "}\n"); @@ -711,6 +722,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List<$boxed_type$>\n" " ${$get$capitalized_name$List$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -719,12 +731,14 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" "}\n"); diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.cc b/src/google/protobuf/compiler/java/java_shared_code_generator.cc index 9a42aba9f4..0cec20b97b 100644 --- a/src/google/protobuf/compiler/java/java_shared_code_generator.cc +++ b/src/google/protobuf/compiler/java/java_shared_code_generator.cc @@ -33,16 +33,13 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include +#include #include #include -#include #include #include @@ -69,11 +66,11 @@ void SharedCodeGenerator::Generate(GeneratorContext* context, string classname = name_resolver_->GetDescriptorClassName(file_); string filename = package_dir + classname + ".java"; file_list->push_back(filename); - google::protobuf::scoped_ptr output(context->Open(filename)); + std::unique_ptr output(context->Open(filename)); GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( &annotations); - google::protobuf::scoped_ptr printer( + std::unique_ptr printer( new io::Printer(output.get(), '$', options_.annotate_code ? &annotation_collector : NULL)); string info_relative_path = classname + ".java.pb.meta"; @@ -108,7 +105,7 @@ void SharedCodeGenerator::Generate(GeneratorContext* context, "}\n"); if (options_.annotate_code) { - google::protobuf::scoped_ptr info_output( + std::unique_ptr info_output( context->Open(info_full_path)); annotations.SerializeToZeroCopyStream(info_output.get()); annotation_file_list->push_back(info_full_path); diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.h b/src/google/protobuf/compiler/java/java_shared_code_generator.h index 40502270ac..58a31f5d7c 100644 --- a/src/google/protobuf/compiler/java/java_shared_code_generator.h +++ b/src/google/protobuf/compiler/java/java_shared_code_generator.h @@ -36,9 +36,6 @@ #define GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__ #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -77,7 +74,7 @@ class SharedCodeGenerator { void GenerateDescriptors(io::Printer* printer); private: - google::protobuf::scoped_ptr name_resolver_; + std::unique_ptr name_resolver_; const FileDescriptor* file_; const Options options_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SharedCodeGenerator); diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.cc b/src/google/protobuf/compiler/java/java_string_field_lite.cc index adda307cf9..a238c67d9e 100644 --- a/src/google/protobuf/compiler/java/java_string_field_lite.cc +++ b/src/google/protobuf/compiler/java/java_string_field_lite.cc @@ -192,6 +192,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); @@ -200,12 +201,14 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " return $name$_;\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n" @@ -249,6 +252,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -257,6 +261,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -264,6 +269,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " return instance.get$capitalized_name$Bytes();\n" @@ -419,6 +425,7 @@ GenerateMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return $has_oneof_case_message$;\n" "}\n"); @@ -427,6 +434,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " java.lang.String ref $default_init$;\n" " if ($has_oneof_case_message$) {\n" @@ -438,6 +446,7 @@ GenerateMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " java.lang.String ref $default_init$;\n" @@ -489,6 +498,7 @@ GenerateBuilderMembers(io::Printer* printer) const { if (SupportFieldPresence(descriptor_->file())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" " return instance.has$capitalized_name$();\n" "}\n"); @@ -497,6 +507,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" " return instance.get$capitalized_name$();\n" "}\n"); @@ -504,6 +515,7 @@ GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$() {\n" " return instance.get$capitalized_name$Bytes();\n" @@ -641,6 +653,7 @@ GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List " "${$get$capitalized_name$List$}$() {\n" " return $name$_;\n" // note: unmodifiable list @@ -648,12 +661,14 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return $name$_.size();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String " "${$get$capitalized_name$$}$(int index) {\n" " return $name$_.get(index);\n" @@ -661,6 +676,7 @@ GenerateMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$(int index) {\n" " return com.google.protobuf.ByteString.copyFromUtf8(\n" @@ -725,6 +741,7 @@ void RepeatedImmutableStringFieldLiteGenerator:: GenerateBuilderMembers(io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.util.List\n" " ${$get$capitalized_name$List$}$() {\n" " return java.util.Collections.unmodifiableList(\n" @@ -733,12 +750,14 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" " return instance.get$capitalized_name$Count();\n" "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public java.lang.String " "${$get$capitalized_name$$}$(int index) {\n" " return instance.get$capitalized_name$(index);\n" @@ -746,6 +765,7 @@ GenerateBuilderMembers(io::Printer* printer) const { printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, + "@java.lang.Override\n" "$deprecation$public com.google.protobuf.ByteString\n" " ${$get$capitalized_name$Bytes$}$(int index) {\n" " return instance.get$capitalized_name$Bytes(index);\n" diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc index fd2d3dfdad..d8282e4094 100755 --- a/src/google/protobuf/compiler/js/js_generator.cc +++ b/src/google/protobuf/compiler/js/js_generator.cc @@ -35,9 +35,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -52,6 +49,7 @@ #include #include + namespace google { namespace protobuf { namespace compiler { @@ -2062,6 +2060,7 @@ void Generator::GenerateOneofCaseDefinition( " $upcase$: $number$", "upcase", ToEnumCase(oneof->field(i)->name()), "number", JSFieldIndex(oneof->field(i))); + printer->Annotate("upcase", oneof->field(i)); } printer->Print( @@ -2768,28 +2767,33 @@ void Generator::GenerateClassField(const GeneratorOptions& options, void Generator::GenerateRepeatedPrimitiveHelperMethods( const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field, bool untyped) const { + // clang-format off printer->Print( "/**\n" " * @param {!$optionaltype$} value\n" - " * @param {number=} opt_index\n" + " * @param {number=} opt_index$returndoc$\n" " */\n" "$class$.prototype.$addername$ = function(value, opt_index) {\n" " jspb.Message.addToRepeatedField(this, $index$", "class", GetMessagePath(options, field->containing_type()), "addername", "add" + JSGetterName(options, field, BYTES_DEFAULT, /* drop_list = */ true), - "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "index", - JSFieldIndex(field)); + "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), + "index", JSFieldIndex(field), + "returndoc", JSReturnDoc(options, field)); printer->Annotate("addername", field); printer->Print( - "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, opt_index);\n" + "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, " + "opt_index);$returnvalue$\n" "};\n" "\n" "\n", "type", untyped ? "/** @type{string|number|boolean|!Uint8Array} */(" : "", "typeclose", untyped ? ")" : "", "oneofgroup", (field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""), - "rptvalueinit", ""); + "rptvalueinit", "", + "returnvalue", JSReturnClause(field)); + // clang-format on } void Generator::GenerateRepeatedMessageHelperMethods( @@ -3206,21 +3210,24 @@ void Generator::GenerateExtension(const GeneratorOptions& options, ? GetMessagePath(options, field->extension_scope()) : GetFilePath(options, field->file())); + const string extension_object_name = JSObjectFieldName(options, field); printer->Print( "\n" "/**\n" " * A tuple of {field number, class constructor} for the extension\n" - " * field named `$name$`.\n" + " * field named `$nameInComment$`.\n" " * @type {!jspb.ExtensionFieldInfo<$extensionType$>}\n" " */\n" "$class$.$name$ = new jspb.ExtensionFieldInfo(\n", - "name", JSObjectFieldName(options, field), + "nameInComment", extension_object_name, + "name", extension_object_name, "class", extension_scope, "extensionType", JSFieldTypeAnnotation( options, field, /* is_setter_argument = */ false, /* force_present = */ true, /* singular_if_not_packed = */ false)); + printer->Annotate("name", field); printer->Print( " $index$,\n" " {$name$: 0},\n" @@ -3230,7 +3237,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options, " $toObject$),\n" " $repeated$);\n", "index", SimpleItoa(field->number()), - "name", JSObjectFieldName(options, field), + "name", extension_object_name, "ctor", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? SubmessageTypeRef(options, field) : string("null")), "toObject", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? @@ -3249,7 +3256,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options, "extendName", JSExtensionsObjectName(options, field->file(), field->containing_type()), "index", SimpleItoa(field->number()), "class", extension_scope, "name", - JSObjectFieldName(options, field), "binaryReaderFn", + extension_object_name, "binaryReaderFn", JSBinaryReaderMethodName(options, field), "binaryWriterFn", JSBinaryWriterMethodName(options, field), "binaryMessageSerializeFn", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) @@ -3272,7 +3279,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options, field->containing_type()), "index", SimpleItoa(field->number()), "class", extension_scope, - "name", JSObjectFieldName(options, field)); + "name", extension_object_name); } bool GeneratorOptions::ParseFromOptions( @@ -3500,7 +3507,7 @@ bool Generator::GenerateAll(const std::vector& files, // All output should go in a single file. string filename = options.output_dir + "/" + options.library + options.GetFileNameExtension(); - google::protobuf::scoped_ptr output(context->Open(filename)); + std::unique_ptr output(context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3549,7 +3556,7 @@ bool Generator::GenerateAll(const std::vector& files, } string filename = GetMessageFileName(options, desc); - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3575,7 +3582,7 @@ bool Generator::GenerateAll(const std::vector& files, } string filename = GetEnumFileName(options, enumdesc); - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3598,7 +3605,7 @@ bool Generator::GenerateAll(const std::vector& files, if (allowed_set.count(file) == 1) { string filename = GetExtensionFileName(options, file); - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); @@ -3634,7 +3641,7 @@ bool Generator::GenerateAll(const std::vector& files, string filename = options.output_dir + "/" + GetJSFilename(options, file->name()); - google::protobuf::scoped_ptr output(context->Open(filename)); + std::unique_ptr output(context->Open(filename)); GOOGLE_CHECK(output.get()); GeneratedCodeInfo annotations; io::AnnotationProtoCollector annotation_collector( diff --git a/src/google/protobuf/compiler/mock_code_generator.cc b/src/google/protobuf/compiler/mock_code_generator.cc index 7719ec3d69..e150f97d49 100644 --- a/src/google/protobuf/compiler/mock_code_generator.cc +++ b/src/google/protobuf/compiler/mock_code_generator.cc @@ -35,9 +35,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include @@ -103,8 +100,7 @@ void MockCodeGenerator::ExpectGenerated( File::GetContents(output_directory + "/" + GetOutputFileName(name, file), &content, true)); - std::vector lines = - Split(content, "\n", true); + std::vector lines = Split(content, "\n", true); while (!lines.empty() && lines.back().empty()) { lines.pop_back(); @@ -232,7 +228,7 @@ bool MockCodeGenerator::Generate( for (size_t i = 0; i < insert_into.size(); i++) { { - google::protobuf::scoped_ptr output(context->OpenForInsert( + std::unique_ptr output(context->OpenForInsert( GetOutputFileName(insert_into[i], file), kFirstInsertionPointName)); io::Printer printer(output.get(), '$'); printer.PrintRaw(GetOutputFileContent(name_, "first_insert", @@ -244,7 +240,7 @@ bool MockCodeGenerator::Generate( } { - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->OpenForInsert(GetOutputFileName(insert_into[i], file), kSecondInsertionPointName)); io::Printer printer(output.get(), '$'); @@ -257,7 +253,7 @@ bool MockCodeGenerator::Generate( } } } else { - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->Open(GetOutputFileName(name_, file))); GeneratedCodeInfo annotations; @@ -287,7 +283,7 @@ bool MockCodeGenerator::Generate( return false; } if (annotate) { - google::protobuf::scoped_ptr meta_output( + std::unique_ptr meta_output( context->Open(GetOutputFileName(name_, file) + ".meta")); if (!TextFormat::Print(annotations, meta_output.get())) { *error = "MockCodeGenerator couldn't write .meta"; diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index 03d05ad4af..df81e55f92 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -39,13 +39,14 @@ #include +#include +#include +#include #include -#include #include -#include #include -#include -#include +#include +#include #include #include @@ -1650,10 +1651,6 @@ bool Parser::ParseReservedNumbers(EnumDescriptorProto* message, if (TryConsume("max")) { // This is in the enum descriptor path, which doesn't have the message // set duality to fix up, so it doesn't integrate with the sentinel. - - // Evaluate 'max' to INT_MAX - 1 so that incrementing to create the - // exclusive range end doesn't cause an overflow. - // Note, this prevents reserving the actual INT_MAX enum value. end = INT_MAX; } else { DO(ConsumeSignedInteger(&end, "Expected integer.")); diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index 33b4c7009a..01d8a66ba2 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -40,10 +40,10 @@ #include #include #include -#include #include -#include #include +#include +#include namespace google { namespace protobuf { class Message; } diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 9b59842e6a..0725a68228 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -33,9 +33,6 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -50,6 +47,7 @@ #include #include #include + #include #include @@ -177,9 +175,9 @@ class ParserTest : public testing::Test { MockErrorCollector error_collector_; DescriptorPool pool_; - google::protobuf::scoped_ptr raw_input_; - google::protobuf::scoped_ptr input_; - google::protobuf::scoped_ptr parser_; + std::unique_ptr raw_input_; + std::unique_ptr input_; + std::unique_ptr parser_; bool require_syntax_identifier_; }; diff --git a/src/google/protobuf/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc index bde3d79829..9c1c757c99 100644 --- a/src/google/protobuf/compiler/plugin.cc +++ b/src/google/protobuf/compiler/plugin.cc @@ -45,8 +45,8 @@ #include #include #include -#include #include +#include #include diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc index d13ad2b34b..ef52def36c 100644 --- a/src/google/protobuf/compiler/plugin.pb.cc +++ b/src/google/protobuf/compiler/plugin.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,14 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Version; +} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto +namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto; +} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto namespace google { namespace protobuf { namespace compiler { @@ -46,14 +53,9 @@ class CodeGeneratorResponseDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { -void InitDefaultsVersionImpl() { +static void InitDefaultsVersion() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::compiler::_Version_default_instance_; new (ptr) ::google::protobuf::compiler::Version(); @@ -62,21 +64,12 @@ void InitDefaultsVersionImpl() { ::google::protobuf::compiler::Version::InitAsDefaultInstance(); } -void InitDefaultsVersion() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsVersionImpl); -} +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion}, {}}; -void InitDefaultsCodeGeneratorRequestImpl() { +static void InitDefaultsCodeGeneratorRequest() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion(); { void* ptr = &::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_; new (ptr) ::google::protobuf::compiler::CodeGeneratorRequest(); @@ -85,19 +78,14 @@ void InitDefaultsCodeGeneratorRequestImpl() { ::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance(); } -void InitDefaultsCodeGeneratorRequest() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorRequestImpl); -} +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCodeGeneratorRequest}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base, + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base,}}; -void InitDefaultsCodeGeneratorResponse_FileImpl() { +static void InitDefaultsCodeGeneratorResponse_File() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_; new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse_File(); @@ -106,20 +94,12 @@ void InitDefaultsCodeGeneratorResponse_FileImpl() { ::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance(); } -void InitDefaultsCodeGeneratorResponse_File() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponse_FileImpl); -} +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File}, {}}; -void InitDefaultsCodeGeneratorResponseImpl() { +static void InitDefaultsCodeGeneratorResponse() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File(); { void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_; new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse(); @@ -128,9 +108,15 @@ void InitDefaultsCodeGeneratorResponseImpl() { ::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance(); } -void InitDefaultsCodeGeneratorResponse() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsCodeGeneratorResponseImpl); +LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCodeGeneratorResponse}, { + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base,}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Version.base); + ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorRequest.base); + ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse_File.base); + ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse.base); } ::google::protobuf::Metadata file_level_metadata[4]; @@ -199,15 +185,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -244,8 +229,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -271,17 +256,15 @@ const int Version::kSuffixFieldNumber; Version::Version() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.Version) } Version::Version(const Version& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_suffix()) { @@ -294,7 +277,6 @@ Version::Version(const Version& from) } void Version::SharedCtor() { - _cached_size_ = 0; suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&major_, 0, static_cast( reinterpret_cast(&patch_) - @@ -311,9 +293,7 @@ void Version::SharedDtor() { } void Version::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Version::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -321,7 +301,7 @@ const ::google::protobuf::Descriptor* Version::descriptor() { } const Version& Version::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersion(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); return *internal_default_instance(); } @@ -334,8 +314,7 @@ void Version::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!suffix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - suffix_.UnsafeMutablePointer()->clear(); + suffix_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 14u) { ::memset(&major_, 0, static_cast( @@ -352,7 +331,7 @@ bool Version::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.Version) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -555,9 +534,7 @@ size_t Version::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -626,13 +603,13 @@ void Version::Swap(Version* other) { } void Version::InternalSwap(Version* other) { using std::swap; - suffix_.Swap(&other->suffix_); + suffix_.Swap(&other->suffix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(major_, other->major_); swap(minor_, other->minor_); swap(patch_, other->patch_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Version::GetMetadata() const { @@ -659,9 +636,8 @@ const int CodeGeneratorRequest::kCompilerVersionFieldNumber; CodeGeneratorRequest::CodeGeneratorRequest() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest) } @@ -669,7 +645,6 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), file_to_generate_(from.file_to_generate_), proto_file_(from.proto_file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); @@ -686,7 +661,6 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) } void CodeGeneratorRequest::SharedCtor() { - _cached_size_ = 0; parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); compiler_version_ = NULL; } @@ -702,9 +676,7 @@ void CodeGeneratorRequest::SharedDtor() { } void CodeGeneratorRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -712,7 +684,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() { } const CodeGeneratorRequest& CodeGeneratorRequest::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequest(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); return *internal_default_instance(); } @@ -728,8 +700,7 @@ void CodeGeneratorRequest::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!parameter_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - parameter_.UnsafeMutablePointer()->clear(); + parameter_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(compiler_version_ != NULL); @@ -746,7 +717,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorRequest) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -857,7 +828,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes( // optional .google.protobuf.compiler.Version compiler_version = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *compiler_version_, output); + 3, this->_internal_compiler_version(), output); } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; @@ -909,7 +880,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *compiler_version_, deterministic, target); + 3, this->_internal_compiler_version(), deterministic, target); } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; @@ -973,9 +944,7 @@ size_t CodeGeneratorRequest::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1042,11 +1011,11 @@ void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) { using std::swap; file_to_generate_.InternalSwap(CastToBase(&other->file_to_generate_)); CastToBase(&proto_file_)->InternalSwap(CastToBase(&other->proto_file_)); - parameter_.Swap(&other->parameter_); + parameter_.Swap(&other->parameter_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(compiler_version_, other->compiler_version_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const { @@ -1067,17 +1036,15 @@ const int CodeGeneratorResponse_File::kContentFieldNumber; CodeGeneratorResponse_File::CodeGeneratorResponse_File() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File) } CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -1095,7 +1062,6 @@ CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorRespon } void CodeGeneratorResponse_File::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -1113,9 +1079,7 @@ void CodeGeneratorResponse_File::SharedDtor() { } void CodeGeneratorResponse_File::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1123,7 +1087,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() { } const CodeGeneratorResponse_File& CodeGeneratorResponse_File::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_File(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); return *internal_default_instance(); } @@ -1137,16 +1101,13 @@ void CodeGeneratorResponse_File::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.UnsafeMutablePointer()->clear(); + name_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!insertion_point_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - insertion_point_.UnsafeMutablePointer()->clear(); + insertion_point_.ClearNonDefaultToEmptyNoArena(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!content_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - content_.UnsafeMutablePointer()->clear(); + content_.ClearNonDefaultToEmptyNoArena(); } } _has_bits_.Clear(); @@ -1159,7 +1120,7 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse.File) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1357,9 +1318,7 @@ size_t CodeGeneratorResponse_File::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1426,12 +1385,14 @@ void CodeGeneratorResponse_File::Swap(CodeGeneratorResponse_File* other) { } void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) { using std::swap; - name_.Swap(&other->name_); - insertion_point_.Swap(&other->insertion_point_); - content_.Swap(&other->content_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + insertion_point_.Swap(&other->insertion_point_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + content_.Swap(&other->content_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata CodeGeneratorResponse_File::GetMetadata() const { @@ -1451,9 +1412,8 @@ const int CodeGeneratorResponse::kFileFieldNumber; CodeGeneratorResponse::CodeGeneratorResponse() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse) } @@ -1461,7 +1421,6 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), file_(from.file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -1472,7 +1431,6 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) } void CodeGeneratorResponse::SharedCtor() { - _cached_size_ = 0; error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } @@ -1486,9 +1444,7 @@ void CodeGeneratorResponse::SharedDtor() { } void CodeGeneratorResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() { ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1496,7 +1452,7 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() { } const CodeGeneratorResponse& CodeGeneratorResponse::default_instance() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); return *internal_default_instance(); } @@ -1510,8 +1466,7 @@ void CodeGeneratorResponse::Clear() { file_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!error_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - error_.UnsafeMutablePointer()->clear(); + error_.ClearNonDefaultToEmptyNoArena(); } _has_bits_.Clear(); _internal_metadata_.Clear(); @@ -1523,7 +1478,7 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1671,9 +1626,7 @@ size_t CodeGeneratorResponse::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1731,10 +1684,10 @@ void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) { void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) { using std::swap; CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); - error_.Swap(&other->error_); + error_.Swap(&other->error_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const { @@ -1749,16 +1702,16 @@ void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::Create< ::google::protobuf::compiler::Version >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::Version >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::Create< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorRequest >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse_File >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index a6c1300e81..5ad6b4d322 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/compiler/plugin.proto -#ifndef PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto #include @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: export @@ -31,6 +32,7 @@ #include #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto LIBPROTOC_EXPORT #ifdef major #undef major #endif @@ -49,20 +51,6 @@ struct LIBPROTOC_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOC_EXPORT AddDescriptors(); -void LIBPROTOC_EXPORT InitDefaultsVersionImpl(); -void LIBPROTOC_EXPORT InitDefaultsVersion(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequestImpl(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorRequest(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_FileImpl(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse_File(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponseImpl(); -void LIBPROTOC_EXPORT InitDefaultsCodeGeneratorResponse(); -inline void LIBPROTOC_EXPORT InitDefaults() { - InitDefaultsVersion(); - InitDefaultsCodeGeneratorRequest(); - InitDefaultsCodeGeneratorResponse_File(); - InitDefaultsCodeGeneratorResponse(); -} } // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto namespace google { namespace protobuf { @@ -84,10 +72,10 @@ LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::Create< ::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::Create< ::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::Create< ::google::protobuf::compiler::Version>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); +template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -137,7 +125,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast( &_Version_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(Version* other); @@ -147,32 +135,33 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Version* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline Version* New() const final { + return CreateMaybeMessage(NULL); } - Version* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + Version* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Version& from); void MergeFrom(const Version& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Version* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -183,7 +172,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -238,13 +227,12 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr suffix_; ::google::protobuf::int32 major_; ::google::protobuf::int32 minor_; ::google::protobuf::int32 patch_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsVersionImpl(); }; // ------------------------------------------------------------------- @@ -289,7 +277,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message return reinterpret_cast( &_CodeGeneratorRequest_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void Swap(CodeGeneratorRequest* other); @@ -299,32 +287,33 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message // implements Message ---------------------------------------------- - inline CodeGeneratorRequest* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline CodeGeneratorRequest* New() const final { + return CreateMaybeMessage(NULL); } - CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CodeGeneratorRequest& from); void MergeFrom(const CodeGeneratorRequest& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorRequest* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -335,7 +324,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -394,6 +383,9 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message bool has_compiler_version() const; void clear_compiler_version(); static const int kCompilerVersionFieldNumber = 3; + private: + const ::google::protobuf::compiler::Version& _internal_compiler_version() const; + public: const ::google::protobuf::compiler::Version& compiler_version() const; ::google::protobuf::compiler::Version* release_compiler_version(); ::google::protobuf::compiler::Version* mutable_compiler_version(); @@ -408,13 +400,12 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::std::string> file_to_generate_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_; ::google::protobuf::internal::ArenaStringPtr parameter_; ::google::protobuf::compiler::Version* compiler_version_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorRequestImpl(); }; // ------------------------------------------------------------------- @@ -459,7 +450,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M return reinterpret_cast( &_CodeGeneratorResponse_File_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void Swap(CodeGeneratorResponse_File* other); @@ -469,32 +460,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M // implements Message ---------------------------------------------- - inline CodeGeneratorResponse_File* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline CodeGeneratorResponse_File* New() const final { + return CreateMaybeMessage(NULL); } - CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CodeGeneratorResponse_File& from); void MergeFrom(const CodeGeneratorResponse_File& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse_File* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -505,7 +497,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -567,12 +559,11 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr insertion_point_; ::google::protobuf::internal::ArenaStringPtr content_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponse_FileImpl(); }; // ------------------------------------------------------------------- @@ -617,7 +608,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag return reinterpret_cast( &_CodeGeneratorResponse_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void Swap(CodeGeneratorResponse* other); @@ -627,32 +618,33 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline CodeGeneratorResponse* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline CodeGeneratorResponse* New() const final { + return CreateMaybeMessage(NULL); } - CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const CodeGeneratorResponse& from); void MergeFrom(const CodeGeneratorResponse& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -663,7 +655,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -705,11 +697,10 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File > file_; ::google::protobuf::internal::ArenaStringPtr error_; friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::InitDefaultsCodeGeneratorResponseImpl(); }; // =================================================================== @@ -844,8 +835,11 @@ inline ::std::string* Version::mutable_suffix() { } inline ::std::string* Version::release_suffix() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix) + if (!has_suffix()) { + return NULL; + } clear_has_suffix(); - return suffix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return suffix_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void Version::set_allocated_suffix(::std::string* suffix) { if (suffix != NULL) { @@ -980,8 +974,11 @@ inline ::std::string* CodeGeneratorRequest::mutable_parameter() { } inline ::std::string* CodeGeneratorRequest::release_parameter() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter) + if (!has_parameter()) { + return NULL; + } clear_has_parameter(); - return parameter_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return parameter_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) { if (parameter != NULL) { @@ -1034,6 +1031,9 @@ inline void CodeGeneratorRequest::clear_compiler_version() { if (compiler_version_ != NULL) compiler_version_->Clear(); clear_has_compiler_version(); } +inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::_internal_compiler_version() const { + return *compiler_version_; +} inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const { const ::google::protobuf::compiler::Version* p = compiler_version_; // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) @@ -1050,8 +1050,8 @@ inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_comp inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() { set_has_compiler_version(); if (compiler_version_ == NULL) { - compiler_version_ = ::google::protobuf::Arena::Create< ::google::protobuf::compiler::Version >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::compiler::Version>(GetArenaNoVirtual()); + compiler_version_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) return compiler_version_; @@ -1129,8 +1129,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_name() { } inline ::std::string* CodeGeneratorResponse_File::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return name_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -1192,8 +1195,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_insertion_point() { } inline ::std::string* CodeGeneratorResponse_File::release_insertion_point() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) + if (!has_insertion_point()) { + return NULL; + } clear_has_insertion_point(); - return insertion_point_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return insertion_point_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) { if (insertion_point != NULL) { @@ -1255,8 +1261,11 @@ inline ::std::string* CodeGeneratorResponse_File::mutable_content() { } inline ::std::string* CodeGeneratorResponse_File::release_content() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content) + if (!has_content()) { + return NULL; + } clear_has_content(); - return content_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return content_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) { if (content != NULL) { @@ -1322,8 +1331,11 @@ inline ::std::string* CodeGeneratorResponse::mutable_error() { } inline ::std::string* CodeGeneratorResponse::release_error() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error) + if (!has_error()) { + return NULL; + } clear_has_error(); - return error_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return error_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void CodeGeneratorResponse::set_allocated_error(::std::string* error) { if (error != NULL) { @@ -1383,4 +1395,4 @@ CodeGeneratorResponse::file() const { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fcompiler_2fplugin_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto diff --git a/src/google/protobuf/compiler/python/python_generator.cc b/src/google/protobuf/compiler/python/python_generator.cc index 5ca6b4ee3f..01f28b3724 100644 --- a/src/google/protobuf/compiler/python/python_generator.cc +++ b/src/google/protobuf/compiler/python/python_generator.cc @@ -49,9 +49,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -202,11 +199,6 @@ void PrintTopBoilerplate( "from google.protobuf import service_reflection\n"); } - // Avoid circular imports if this module is descriptor_pb2. - if (!descriptor_proto) { - printer->Print( - "from google.protobuf import descriptor_pb2\n"); - } printer->Print( "# @@protoc_insertion_point(imports)\n\n" "_sym_db = _symbol_database.Default()\n"); @@ -338,7 +330,7 @@ bool Generator::Generate(const FileDescriptor* file, fdp.SerializeToString(&file_descriptor_serialized_); - google::protobuf::scoped_ptr output(context->Open(filename)); + std::unique_ptr output(context->Open(filename)); GOOGLE_CHECK(output.get()); io::Printer printer(output.get(), '$'); printer_ = &printer; @@ -422,11 +414,13 @@ void Generator::PrintFileDescriptor() const { m["name"] = file_->name(); m["package"] = file_->package(); m["syntax"] = StringifySyntax(file_->syntax()); + m["options"] = OptionsValue(file_->options().SerializeAsString()); const char file_descriptor_template[] = "$descriptor_name$ = _descriptor.FileDescriptor(\n" " name='$name$',\n" " package='$package$',\n" - " syntax='$syntax$',\n"; + " syntax='$syntax$',\n" + " serialized_options=$options$,\n"; printer_->Print(m, file_descriptor_template); printer_->Indent(); printer_->Print( @@ -526,9 +520,9 @@ void Generator::PrintEnum(const EnumDescriptor& enum_descriptor) const { printer_->Outdent(); printer_->Print("],\n"); printer_->Print("containing_type=None,\n"); - printer_->Print("options=$options_value$,\n", + printer_->Print("serialized_options=$options_value$,\n", "options_value", - OptionsValue("EnumOptions", options_string)); + OptionsValue(options_string)); EnumDescriptorProto edp; PrintSerializedPbInterval(enum_descriptor, edp); printer_->Outdent(); @@ -606,13 +600,13 @@ void Generator::PrintServiceDescriptor( m["full_name"] = descriptor.full_name(); m["file"] = kDescriptorKey; m["index"] = SimpleItoa(descriptor.index()); - m["options_value"] = OptionsValue("ServiceOptions", options_string); + m["options_value"] = OptionsValue(options_string); const char required_function_arguments[] = "name='$name$',\n" "full_name='$full_name$',\n" "file=$file$,\n" "index=$index$,\n" - "options=$options_value$,\n"; + "serialized_options=$options_value$,\n"; printer_->Print(m, required_function_arguments); ServiceDescriptorProto sdp; @@ -630,7 +624,7 @@ void Generator::PrintServiceDescriptor( m["serialized_options"] = CEscape(options_string); m["input_type"] = ModuleLevelDescriptorName(*(method->input_type())); m["output_type"] = ModuleLevelDescriptorName(*(method->output_type())); - m["options_value"] = OptionsValue("MethodOptions", options_string); + m["options_value"] = OptionsValue(options_string); printer_->Print("_descriptor.MethodDescriptor(\n"); printer_->Indent(); printer_->Print( @@ -641,7 +635,7 @@ void Generator::PrintServiceDescriptor( "containing_service=None,\n" "input_type=$input_type$,\n" "output_type=$output_type$,\n" - "options=$options_value$,\n"); + "serialized_options=$options_value$,\n"); printer_->Outdent(); printer_->Print("),\n"); } @@ -737,10 +731,10 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { string options_string; message_descriptor.options().SerializeToString(&options_string); printer_->Print( - "options=$options_value$,\n" + "serialized_options=$options_value$,\n" "is_extendable=$extendable$,\n" "syntax='$syntax$'", - "options_value", OptionsValue("MessageOptions", options_string), + "options_value", OptionsValue(options_string), "extendable", message_descriptor.extension_range_count() > 0 ? "True" : "False", "syntax", StringifySyntax(message_descriptor.file()->syntax())); @@ -765,17 +759,18 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { m["full_name"] = desc->full_name(); m["index"] = SimpleItoa(desc->index()); string options_string = - OptionsValue("OneofOptions", desc->options().SerializeAsString()); + OptionsValue(desc->options().SerializeAsString()); if (options_string == "None") { - m["options"] = ""; + m["serialized_options"] = ""; } else { - m["options"] = ", options=" + options_string; + m["serialized_options"] = ", serialized_options=" + options_string; } printer_->Print( m, "_descriptor.OneofDescriptor(\n" " name='$name$', full_name='$full_name$',\n" - " index=$index$, containing_type=None, fields=[]$options$),\n"); + " index=$index$, containing_type=None, " + "fields=[]$serialized_options$),\n"); } printer_->Outdent(); printer_->Print("],\n"); @@ -1098,27 +1093,22 @@ void Generator::PrintEnumValueDescriptor( m["name"] = descriptor.name(); m["index"] = SimpleItoa(descriptor.index()); m["number"] = SimpleItoa(descriptor.number()); - m["options"] = OptionsValue("EnumValueOptions", options_string); + m["options"] = OptionsValue(options_string); printer_->Print( m, "_descriptor.EnumValueDescriptor(\n" " name='$name$', index=$index$, number=$number$,\n" - " options=$options$,\n" + " serialized_options=$options$,\n" " type=None)"); } -// Returns a Python expression that calls descriptor._ParseOptions using -// the given descriptor class name and serialized options protobuf string. -string Generator::OptionsValue( - const string& class_name, const string& serialized_options) const { +// Returns a CEscaped string of serialized_options. +string Generator::OptionsValue(const string& serialized_options) const { if (serialized_options.length() == 0 || GeneratingDescriptorProto()) { return "None"; } else { - string full_class_name = "descriptor_pb2." + class_name; -//##!PY25 return "_descriptor._ParseOptions(" + full_class_name + "(), b'" -//##!PY25 + CEscape(serialized_options)+ "')"; - return "_descriptor._ParseOptions(" + full_class_name + "(), _b('" //##PY25 - + CEscape(serialized_options)+ "'))"; //##PY25 +//##!PY25 return "b'('" + CEscape(serialized_options)+ "')"; + return "_b('"+ CEscape(serialized_options) + "')"; //##PY25 } } @@ -1138,7 +1128,7 @@ void Generator::PrintFieldDescriptor( m["has_default_value"] = field.has_default_value() ? "True" : "False"; m["default_value"] = StringifyDefaultValue(field); m["is_extension"] = is_extension ? "True" : "False"; - m["options"] = OptionsValue("FieldOptions", options_string); + m["serialized_options"] = OptionsValue(options_string); m["json_name"] = field.has_json_name() ? ", json_name='" + field.json_name() + "'": ""; // We always set message_type and enum_type to None at this point, and then @@ -1151,7 +1141,7 @@ void Generator::PrintFieldDescriptor( " has_default_value=$has_default_value$, default_value=$default_value$,\n" " message_type=None, enum_type=None, containing_type=None,\n" " is_extension=$is_extension$, extension_scope=None,\n" - " options=$options$$json_name$, file=DESCRIPTOR)"; + " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR)"; printer_->Print(m, field_descriptor_decl); } @@ -1280,23 +1270,18 @@ namespace { void PrintDescriptorOptionsFixingCode(const string& descriptor, const string& options, io::Printer* printer) { - // TODO(xiaofeng): I have added a method _SetOptions() to DescriptorBase - // in proto2 python runtime but it couldn't be used here because appengine - // uses a snapshot version of the library in which the new method is not - // yet present. After appengine has synced their runtime library, the code - // below should be cleaned up to use _SetOptions(). + // Reset the _options to None thus DescriptorBase.GetOptions() can + // parse _options again after extensions are registered. printer->Print( - "$descriptor$.has_options = True\n" - "$descriptor$._options = $options$\n", - "descriptor", descriptor, "options", options); + "$descriptor$._options = None\n", + "descriptor", descriptor); } } // namespace // Prints expressions that set the options field of all descriptors. void Generator::FixAllDescriptorOptions() const { // Prints an expression that sets the file descriptor's options. - string file_options = OptionsValue( - "FileOptions", file_->options().SerializeAsString()); + string file_options = OptionsValue(file_->options().SerializeAsString()); if (file_options != "None") { PrintDescriptorOptionsFixingCode(kDescriptorKey, file_options, printer_); } @@ -1318,8 +1303,7 @@ void Generator::FixAllDescriptorOptions() const { } void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const { - string oneof_options = OptionsValue( - "OneofOptions", oneof.options().SerializeAsString()); + string oneof_options = OptionsValue(oneof.options().SerializeAsString()); if (oneof_options != "None") { string oneof_name = strings::Substitute( "$0.$1['$2']", @@ -1334,14 +1318,14 @@ void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const { void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { string descriptor_name = ModuleLevelDescriptorName(enum_descriptor); string enum_options = OptionsValue( - "EnumOptions", enum_descriptor.options().SerializeAsString()); + enum_descriptor.options().SerializeAsString()); if (enum_options != "None") { PrintDescriptorOptionsFixingCode(descriptor_name, enum_options, printer_); } for (int i = 0; i < enum_descriptor.value_count(); ++i) { const EnumValueDescriptor& value_descriptor = *enum_descriptor.value(i); string value_options = OptionsValue( - "EnumValueOptions", value_descriptor.options().SerializeAsString()); + value_descriptor.options().SerializeAsString()); if (value_options != "None") { PrintDescriptorOptionsFixingCode( StringPrintf("%s.values_by_name[\"%s\"]", descriptor_name.c_str(), @@ -1355,8 +1339,7 @@ void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { // extensions). void Generator::FixOptionsForField( const FieldDescriptor& field) const { - string field_options = OptionsValue( - "FieldOptions", field.options().SerializeAsString()); + string field_options = OptionsValue(field.options().SerializeAsString()); if (field_options != "None") { string field_name; if (field.is_extension()) { @@ -1402,7 +1385,7 @@ void Generator::FixOptionsForMessage(const Descriptor& descriptor) const { } // Message option for this message. string message_options = OptionsValue( - "MessageOptions", descriptor.options().SerializeAsString()); + descriptor.options().SerializeAsString()); if (message_options != "None") { string descriptor_name = ModuleLevelDescriptorName(descriptor); PrintDescriptorOptionsFixingCode(descriptor_name, diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/python_generator.h index 2b5a028b3f..8e4050de8c 100644 --- a/src/google/protobuf/compiler/python/python_generator.h +++ b/src/google/protobuf/compiler/python/python_generator.h @@ -135,8 +135,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const ServiceDescriptor& descriptor) const; void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const; - string OptionsValue(const string& class_name, - const string& serialized_options) const; + string OptionsValue(const string& serialized_options) const; bool GeneratingDescriptorProto() const; template diff --git a/src/google/protobuf/compiler/python/python_plugin_unittest.cc b/src/google/protobuf/compiler/python/python_plugin_unittest.cc index 34f857fddb..2f096808a5 100644 --- a/src/google/protobuf/compiler/python/python_plugin_unittest.cc +++ b/src/google/protobuf/compiler/python/python_plugin_unittest.cc @@ -35,9 +35,6 @@ // worth. #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -74,7 +71,7 @@ class TestGenerator : public CodeGenerator { void TryInsert(const string& filename, const string& insertion_point, GeneratorContext* context) const { - google::protobuf::scoped_ptr output( + std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); io::Printer printer(output.get(), '$'); printer.Print("// inserted $name$\n", "name", insertion_point); diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 9d48bfba6e..bd08581d1c 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -38,24 +38,22 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include +#include #include #include #include #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -65,6 +63,7 @@ #include #include + #include #include @@ -347,14 +346,14 @@ class PrefixRemover { } if (ascii_tolower(str[i]) != prefix_[j++]) { - return str.as_string(); + return string(str); } } // If we didn't make it through the prefix, we've failed to strip the // prefix. if (j < prefix_.size()) { - return str.as_string(); + return string(str); } // Skip underscores between prefix and further characters. @@ -364,12 +363,12 @@ class PrefixRemover { // Enum label can't be the empty string. if (i == str.size()) { - return str.as_string(); + return string(str); } // We successfully stripped the prefix. str.remove_prefix(i); - return str.as_string(); + return string(str); } private: @@ -1802,6 +1801,15 @@ FileDescriptor::FindExtensionByCamelcaseName(const string& key) const { } } +void Descriptor::ExtensionRange::CopyTo( + DescriptorProto_ExtensionRange* proto) const { + proto->set_start(this->start); + proto->set_end(this->end); + if (options_ != &google::protobuf::ExtensionRangeOptions::default_instance()) { + *proto->mutable_options() = *options_; + } +} + const Descriptor::ExtensionRange* Descriptor::FindExtensionRangeContainingNumber(int number) const { // Linear search should be fine because we don't expect a message to have @@ -2069,13 +2077,7 @@ void Descriptor::CopyTo(DescriptorProto* proto) const { enum_type(i)->CopyTo(proto->add_enum_type()); } for (int i = 0; i < extension_range_count(); i++) { - DescriptorProto::ExtensionRange* range = proto->add_extension_range(); - range->set_start(extension_range(i)->start); - range->set_end(extension_range(i)->end); - const ExtensionRangeOptions* options = extension_range(i)->options_; - if (options != &ExtensionRangeOptions::default_instance()) { - range->mutable_options()->CopyFrom(*options); - } + extension_range(i)->CopyTo(proto->add_extension_range()); } for (int i = 0; i < extension_count(); i++) { extension(i)->CopyTo(proto->add_extension()); @@ -2306,7 +2308,7 @@ bool RetrieveOptions(int depth, const Message& options, return RetrieveOptionsAssumingRightPool(depth, options, option_entries); } DynamicMessageFactory factory; - google::protobuf::scoped_ptr dynamic_options( + std::unique_ptr dynamic_options( factory.GetPrototype(option_descriptor)->New()); if (dynamic_options->ParseFromString(options.SerializeAsString())) { return RetrieveOptionsAssumingRightPool(depth, *dynamic_options, @@ -5132,13 +5134,13 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, for (int j = i + 1; j < proto.reserved_range_size(); j++) { const EnumDescriptorProto_EnumReservedRange& range2 = proto.reserved_range(j); - if (range1.end() > range2.start() && range2.end() > range1.start()) { + if (range1.end() >= range2.start() && range2.end() >= range1.start()) { AddError(result->full_name(), proto.reserved_range(i), DescriptorPool::ErrorCollector::NUMBER, strings::Substitute("Reserved range $0 to $1 overlaps with " "already-defined range $2 to $3.", - range2.start(), range2.end() - 1, - range1.start(), range1.end() - 1)); + range2.start(), range2.end(), + range1.start(), range1.end())); } } } @@ -5661,13 +5663,15 @@ void DescriptorBuilder::CrossLinkField( if (!tables_->AddExtension(field)) { const FieldDescriptor* conflicting_field = tables_->FindExtension(field->containing_type(), field->number()); + string containing_type_name = + field->containing_type() == NULL + ? "unknown" + : field->containing_type()->full_name(); string error_msg = strings::Substitute( "Extension number $0 has already been used in \"$1\" by extension " "\"$2\" defined in $3.", - field->number(), - field->containing_type()->full_name(), - conflicting_field->full_name(), - conflicting_field->file()->name()); + field->number(), containing_type_name, + conflicting_field->full_name(), conflicting_field->file()->name()); // Conflicting extension numbers should be an error. However, before // turning this into an error we need to fix all existing broken // protos first. @@ -6456,7 +6460,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( // First set the value on the UnknownFieldSet corresponding to the // innermost message. - google::protobuf::scoped_ptr unknown_fields(new UnknownFieldSet()); + std::unique_ptr unknown_fields(new UnknownFieldSet()); if (!SetOptionValue(field, unknown_fields.get())) { return false; // SetOptionValue() already added the error. } @@ -6466,7 +6470,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( for (std::vector::reverse_iterator iter = intermediate_fields.rbegin(); iter != intermediate_fields.rend(); ++iter) { - google::protobuf::scoped_ptr parent_unknown_fields( + std::unique_ptr parent_unknown_fields( new UnknownFieldSet()); switch ((*iter)->type()) { case FieldDescriptor::TYPE_MESSAGE: { @@ -6854,7 +6858,7 @@ bool DescriptorBuilder::OptionInterpreter::SetAggregateOption( } const Descriptor* type = option_field->message_type(); - google::protobuf::scoped_ptr dynamic(dynamic_factory_.GetPrototype(type)->New()); + std::unique_ptr dynamic(dynamic_factory_.GetPrototype(type)->New()); GOOGLE_CHECK(dynamic.get() != NULL) << "Could not create an instance of " << option_field->DebugString(); diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h index 5f5159a8ad..115d4ddc26 100644 --- a/src/google/protobuf/descriptor.h +++ b/src/google/protobuf/descriptor.h @@ -55,9 +55,6 @@ #define GOOGLE_PROTOBUF_DESCRIPTOR_H__ #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -87,6 +84,7 @@ class DescriptorPool; // Defined in descriptor.proto class DescriptorProto; +class DescriptorProto_ExtensionRange; class FieldDescriptorProto; class OneofDescriptorProto; class EnumDescriptorProto; @@ -340,6 +338,9 @@ class LIBPROTOBUF_EXPORT Descriptor { struct ExtensionRange { typedef ExtensionRangeOptions OptionsType; + // See Descriptor::CopyTo(). + void CopyTo(DescriptorProto_ExtensionRange* proto) const; + int start; // inclusive int end; // exclusive @@ -1802,7 +1803,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // This class contains a lot of hash maps with complicated types that // we'd like to keep out of the header. class Tables; - google::protobuf::scoped_ptr tables_; + std::unique_ptr tables_; bool enforce_dependencies_; bool lazily_build_dependencies_; diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc index c8362376f8..9927bc4a80 100644 --- a/src/google/protobuf/descriptor.pb.cc +++ b/src/google/protobuf/descriptor.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,34 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto; +} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto namespace google { namespace protobuf { class FileDescriptorSetDefaultTypeInternal { @@ -159,15 +186,9 @@ class GeneratedCodeInfoDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { -void InitDefaultsFileDescriptorSetImpl() { +static void InitDefaultsFileDescriptorSet() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); { void* ptr = &::google::protobuf::_FileDescriptorSet_default_instance_; new (ptr) ::google::protobuf::FileDescriptorSet(); @@ -176,25 +197,13 @@ void InitDefaultsFileDescriptorSetImpl() { ::google::protobuf::FileDescriptorSet::InitAsDefaultInstance(); } -void InitDefaultsFileDescriptorSet() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorSetImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileDescriptorSet = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileDescriptorSet}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base,}}; -void InitDefaultsFileDescriptorProtoImpl() { +static void InitDefaultsFileDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); { void* ptr = &::google::protobuf::_FileDescriptorProto_default_instance_; new (ptr) ::google::protobuf::FileDescriptorProto(); @@ -203,20 +212,18 @@ void InitDefaultsFileDescriptorProtoImpl() { ::google::protobuf::FileDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsFileDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsFileDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base,}}; -void InitDefaultsDescriptorProto_ExtensionRangeImpl() { +static void InitDefaultsDescriptorProto_ExtensionRange() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); { void* ptr = &::google::protobuf::_DescriptorProto_ExtensionRange_default_instance_; new (ptr) ::google::protobuf::DescriptorProto_ExtensionRange(); @@ -225,19 +232,13 @@ void InitDefaultsDescriptorProto_ExtensionRangeImpl() { ::google::protobuf::DescriptorProto_ExtensionRange::InitAsDefaultInstance(); } -void InitDefaultsDescriptorProto_ExtensionRange() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ExtensionRangeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDescriptorProto_ExtensionRange}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base,}}; -void InitDefaultsDescriptorProto_ReservedRangeImpl() { +static void InitDefaultsDescriptorProto_ReservedRange() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_DescriptorProto_ReservedRange_default_instance_; new (ptr) ::google::protobuf::DescriptorProto_ReservedRange(); @@ -246,25 +247,12 @@ void InitDefaultsDescriptorProto_ReservedRangeImpl() { ::google::protobuf::DescriptorProto_ReservedRange::InitAsDefaultInstance(); } -void InitDefaultsDescriptorProto_ReservedRange() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProto_ReservedRangeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDescriptorProto_ReservedRange}, {}}; -void InitDefaultsDescriptorProtoImpl() { +static void InitDefaultsDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); { void* ptr = &::google::protobuf::_DescriptorProto_default_instance_; new (ptr) ::google::protobuf::DescriptorProto(); @@ -273,20 +261,18 @@ void InitDefaultsDescriptorProtoImpl() { ::google::protobuf::DescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base,}}; -void InitDefaultsExtensionRangeOptionsImpl() { +static void InitDefaultsExtensionRangeOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_ExtensionRangeOptions_default_instance_; new (ptr) ::google::protobuf::ExtensionRangeOptions(); @@ -295,20 +281,13 @@ void InitDefaultsExtensionRangeOptionsImpl() { ::google::protobuf::ExtensionRangeOptions::InitAsDefaultInstance(); } -void InitDefaultsExtensionRangeOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsExtensionRangeOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsExtensionRangeOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsFieldDescriptorProtoImpl() { +static void InitDefaultsFieldDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); { void* ptr = &::google::protobuf::_FieldDescriptorProto_default_instance_; new (ptr) ::google::protobuf::FieldDescriptorProto(); @@ -317,20 +296,13 @@ void InitDefaultsFieldDescriptorProtoImpl() { ::google::protobuf::FieldDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsFieldDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base,}}; -void InitDefaultsOneofDescriptorProtoImpl() { +static void InitDefaultsOneofDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); { void* ptr = &::google::protobuf::_OneofDescriptorProto_default_instance_; new (ptr) ::google::protobuf::OneofDescriptorProto(); @@ -339,19 +311,13 @@ void InitDefaultsOneofDescriptorProtoImpl() { ::google::protobuf::OneofDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsOneofDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base,}}; -void InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl() { +static void InitDefaultsEnumDescriptorProto_EnumReservedRange() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_EnumDescriptorProto_EnumReservedRange_default_instance_; new (ptr) ::google::protobuf::EnumDescriptorProto_EnumReservedRange(); @@ -360,22 +326,12 @@ void InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl() { ::google::protobuf::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance(); } -void InitDefaultsEnumDescriptorProto_EnumReservedRange() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEnumDescriptorProto_EnumReservedRange}, {}}; -void InitDefaultsEnumDescriptorProtoImpl() { +static void InitDefaultsEnumDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); { void* ptr = &::google::protobuf::_EnumDescriptorProto_default_instance_; new (ptr) ::google::protobuf::EnumDescriptorProto(); @@ -384,20 +340,15 @@ void InitDefaultsEnumDescriptorProtoImpl() { ::google::protobuf::EnumDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsEnumDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnumDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base,}}; -void InitDefaultsEnumValueDescriptorProtoImpl() { +static void InitDefaultsEnumValueDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); { void* ptr = &::google::protobuf::_EnumValueDescriptorProto_default_instance_; new (ptr) ::google::protobuf::EnumValueDescriptorProto(); @@ -406,21 +357,13 @@ void InitDefaultsEnumValueDescriptorProtoImpl() { ::google::protobuf::EnumValueDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsEnumValueDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base,}}; -void InitDefaultsServiceDescriptorProtoImpl() { +static void InitDefaultsServiceDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); { void* ptr = &::google::protobuf::_ServiceDescriptorProto_default_instance_; new (ptr) ::google::protobuf::ServiceDescriptorProto(); @@ -429,20 +372,14 @@ void InitDefaultsServiceDescriptorProtoImpl() { ::google::protobuf::ServiceDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsServiceDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsServiceDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base, + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base,}}; -void InitDefaultsMethodDescriptorProtoImpl() { +static void InitDefaultsMethodDescriptorProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); { void* ptr = &::google::protobuf::_MethodDescriptorProto_default_instance_; new (ptr) ::google::protobuf::MethodDescriptorProto(); @@ -451,20 +388,13 @@ void InitDefaultsMethodDescriptorProtoImpl() { ::google::protobuf::MethodDescriptorProto::InitAsDefaultInstance(); } -void InitDefaultsMethodDescriptorProto() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodDescriptorProtoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodDescriptorProto}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base,}}; -void InitDefaultsFileOptionsImpl() { +static void InitDefaultsFileOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_FileOptions_default_instance_; new (ptr) ::google::protobuf::FileOptions(); @@ -473,20 +403,13 @@ void InitDefaultsFileOptionsImpl() { ::google::protobuf::FileOptions::InitAsDefaultInstance(); } -void InitDefaultsFileOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFileOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsMessageOptionsImpl() { +static void InitDefaultsMessageOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_MessageOptions_default_instance_; new (ptr) ::google::protobuf::MessageOptions(); @@ -495,20 +418,13 @@ void InitDefaultsMessageOptionsImpl() { ::google::protobuf::MessageOptions::InitAsDefaultInstance(); } -void InitDefaultsMessageOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMessageOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMessageOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsFieldOptionsImpl() { +static void InitDefaultsFieldOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_FieldOptions_default_instance_; new (ptr) ::google::protobuf::FieldOptions(); @@ -517,20 +433,13 @@ void InitDefaultsFieldOptionsImpl() { ::google::protobuf::FieldOptions::InitAsDefaultInstance(); } -void InitDefaultsFieldOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsOneofOptionsImpl() { +static void InitDefaultsOneofOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_OneofOptions_default_instance_; new (ptr) ::google::protobuf::OneofOptions(); @@ -539,20 +448,13 @@ void InitDefaultsOneofOptionsImpl() { ::google::protobuf::OneofOptions::InitAsDefaultInstance(); } -void InitDefaultsOneofOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOneofOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsEnumOptionsImpl() { +static void InitDefaultsEnumOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_EnumOptions_default_instance_; new (ptr) ::google::protobuf::EnumOptions(); @@ -561,20 +463,13 @@ void InitDefaultsEnumOptionsImpl() { ::google::protobuf::EnumOptions::InitAsDefaultInstance(); } -void InitDefaultsEnumOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsEnumValueOptionsImpl() { +static void InitDefaultsEnumValueOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_EnumValueOptions_default_instance_; new (ptr) ::google::protobuf::EnumValueOptions(); @@ -583,20 +478,13 @@ void InitDefaultsEnumValueOptionsImpl() { ::google::protobuf::EnumValueOptions::InitAsDefaultInstance(); } -void InitDefaultsEnumValueOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsServiceOptionsImpl() { +static void InitDefaultsServiceOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_ServiceOptions_default_instance_; new (ptr) ::google::protobuf::ServiceOptions(); @@ -605,20 +493,13 @@ void InitDefaultsServiceOptionsImpl() { ::google::protobuf::ServiceOptions::InitAsDefaultInstance(); } -void InitDefaultsServiceOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsServiceOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsServiceOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsMethodOptionsImpl() { +static void InitDefaultsMethodOptions() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); { void* ptr = &::google::protobuf::_MethodOptions_default_instance_; new (ptr) ::google::protobuf::MethodOptions(); @@ -627,19 +508,13 @@ void InitDefaultsMethodOptionsImpl() { ::google::protobuf::MethodOptions::InitAsDefaultInstance(); } -void InitDefaultsMethodOptions() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodOptionsImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodOptions}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}}; -void InitDefaultsUninterpretedOption_NamePartImpl() { +static void InitDefaultsUninterpretedOption_NamePart() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_UninterpretedOption_NamePart_default_instance_; new (ptr) ::google::protobuf::UninterpretedOption_NamePart(); @@ -648,20 +523,12 @@ void InitDefaultsUninterpretedOption_NamePartImpl() { ::google::protobuf::UninterpretedOption_NamePart::InitAsDefaultInstance(); } -void InitDefaultsUninterpretedOption_NamePart() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOption_NamePartImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUninterpretedOption_NamePart}, {}}; -void InitDefaultsUninterpretedOptionImpl() { +static void InitDefaultsUninterpretedOption() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); { void* ptr = &::google::protobuf::_UninterpretedOption_default_instance_; new (ptr) ::google::protobuf::UninterpretedOption(); @@ -670,19 +537,13 @@ void InitDefaultsUninterpretedOptionImpl() { ::google::protobuf::UninterpretedOption::InitAsDefaultInstance(); } -void InitDefaultsUninterpretedOption() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsUninterpretedOptionImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsUninterpretedOption}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base,}}; -void InitDefaultsSourceCodeInfo_LocationImpl() { +static void InitDefaultsSourceCodeInfo_Location() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_SourceCodeInfo_Location_default_instance_; new (ptr) ::google::protobuf::SourceCodeInfo_Location(); @@ -691,20 +552,12 @@ void InitDefaultsSourceCodeInfo_LocationImpl() { ::google::protobuf::SourceCodeInfo_Location::InitAsDefaultInstance(); } -void InitDefaultsSourceCodeInfo_Location() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfo_LocationImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceCodeInfo_Location}, {}}; -void InitDefaultsSourceCodeInfoImpl() { +static void InitDefaultsSourceCodeInfo() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); { void* ptr = &::google::protobuf::_SourceCodeInfo_default_instance_; new (ptr) ::google::protobuf::SourceCodeInfo(); @@ -713,19 +566,13 @@ void InitDefaultsSourceCodeInfoImpl() { ::google::protobuf::SourceCodeInfo::InitAsDefaultInstance(); } -void InitDefaultsSourceCodeInfo() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceCodeInfoImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsSourceCodeInfo}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base,}}; -void InitDefaultsGeneratedCodeInfo_AnnotationImpl() { +static void InitDefaultsGeneratedCodeInfo_Annotation() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_GeneratedCodeInfo_Annotation_default_instance_; new (ptr) ::google::protobuf::GeneratedCodeInfo_Annotation(); @@ -734,20 +581,12 @@ void InitDefaultsGeneratedCodeInfo_AnnotationImpl() { ::google::protobuf::GeneratedCodeInfo_Annotation::InitAsDefaultInstance(); } -void InitDefaultsGeneratedCodeInfo_Annotation() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfo_AnnotationImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsGeneratedCodeInfo_Annotation}, {}}; -void InitDefaultsGeneratedCodeInfoImpl() { +static void InitDefaultsGeneratedCodeInfo() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); { void* ptr = &::google::protobuf::_GeneratedCodeInfo_default_instance_; new (ptr) ::google::protobuf::GeneratedCodeInfo(); @@ -756,9 +595,38 @@ void InitDefaultsGeneratedCodeInfoImpl() { ::google::protobuf::GeneratedCodeInfo::InitAsDefaultInstance(); } -void InitDefaultsGeneratedCodeInfo() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsGeneratedCodeInfoImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_GeneratedCodeInfo = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsGeneratedCodeInfo}, { + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base,}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorSet.base); + ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ExtensionRange.base); + ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ReservedRange.base); + ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_ExtensionRangeOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_FieldDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_OneofDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto_EnumReservedRange.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumValueDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_ServiceDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_MethodDescriptorProto.base); + ::google::protobuf::internal::InitSCC(&scc_info_FileOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_MessageOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_FieldOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_OneofOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumValueOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_ServiceOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_MethodOptions.base); + ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption_NamePart.base); + ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption.base); + ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo_Location.base); + ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo.base); + ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo_Annotation.base); + ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo.base); } ::google::protobuf::Metadata file_level_metadata[27]; @@ -1207,15 +1075,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -1385,8 +1252,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -1576,9 +1443,8 @@ const int FileDescriptorSet::kFileFieldNumber; FileDescriptorSet::FileDescriptorSet() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet) } @@ -1586,7 +1452,7 @@ FileDescriptorSet::FileDescriptorSet(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), file_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorSet) @@ -1595,14 +1461,12 @@ FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), file_(from.file_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorSet) } void FileDescriptorSet::SharedCtor() { - _cached_size_ = 0; } FileDescriptorSet::~FileDescriptorSet() { @@ -1621,9 +1485,7 @@ void FileDescriptorSet::ArenaDtor(void* object) { void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FileDescriptorSet::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1631,7 +1493,7 @@ const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() { } const FileDescriptorSet& FileDescriptorSet::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSet(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base); return *internal_default_instance(); } @@ -1653,7 +1515,7 @@ bool FileDescriptorSet::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorSet) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1755,9 +1617,7 @@ size_t FileDescriptorSet::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1829,7 +1689,6 @@ void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) { CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FileDescriptorSet::GetMetadata() const { @@ -1889,9 +1748,8 @@ const int FileDescriptorProto::kSyntaxFieldNumber; FileDescriptorProto::FileDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto) } @@ -1905,7 +1763,7 @@ FileDescriptorProto::FileDescriptorProto(::google::protobuf::Arena* arena) extension_(arena), public_dependency_(arena), weak_dependency_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorProto) @@ -1914,7 +1772,6 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), dependency_(from.dependency_), message_type_(from.message_type_), enum_type_(from.enum_type_), @@ -1952,7 +1809,6 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) } void FileDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -1982,9 +1838,7 @@ void FileDescriptorProto::ArenaDtor(void* object) { void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FileDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1992,7 +1846,7 @@ const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() { } const FileDescriptorProto& FileDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base); return *internal_default_instance(); } @@ -2013,16 +1867,13 @@ void FileDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 31u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!syntax_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - syntax_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + syntax_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { GOOGLE_DCHECK(options_ != NULL); @@ -2043,7 +1894,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2318,13 +2169,13 @@ void FileDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.FileOptions options = 8; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, *options_, output); + 8, this->_internal_options(), output); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 9, *source_code_info_, output); + 9, this->_internal_source_code_info(), output); } // repeated int32 public_dependency = 10; @@ -2432,14 +2283,14 @@ void FileDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 8, *options_, deterministic, target); + 8, this->_internal_options(), deterministic, target); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 9, *source_code_info_, deterministic, target); + 9, this->_internal_source_code_info(), deterministic, target); } // repeated int32 public_dependency = 10; @@ -2586,9 +2437,7 @@ size_t FileDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2694,14 +2543,16 @@ void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) { CastToBase(&extension_)->InternalSwap(CastToBase(&other->extension_)); public_dependency_.InternalSwap(&other->public_dependency_); weak_dependency_.InternalSwap(&other->weak_dependency_); - name_.Swap(&other->name_); - package_.Swap(&other->package_); - syntax_.Swap(&other->syntax_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + package_.Swap(&other->package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + syntax_.Swap(&other->syntax_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(source_code_info_, other->source_code_info_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FileDescriptorProto::GetMetadata() const { @@ -2737,16 +2588,15 @@ const int DescriptorProto_ExtensionRange::kOptionsFieldNumber; DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ExtensionRange) } DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ExtensionRange) @@ -2754,8 +2604,7 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobu DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_options()) { options_ = new ::google::protobuf::ExtensionRangeOptions(*from.options_); @@ -2769,7 +2618,6 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorP } void DescriptorProto_ExtensionRange::SharedCtor() { - _cached_size_ = 0; ::memset(&options_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&options_)) + sizeof(end_)); @@ -2792,9 +2640,7 @@ void DescriptorProto_ExtensionRange::ArenaDtor(void* object) { void DescriptorProto_ExtensionRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void DescriptorProto_ExtensionRange::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2802,7 +2648,7 @@ const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor } const DescriptorProto_ExtensionRange& DescriptorProto_ExtensionRange::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base); return *internal_default_instance(); } @@ -2833,7 +2679,7 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ExtensionRange) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2917,7 +2763,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes( // optional .google.protobuf.ExtensionRangeOptions options = 3; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -2949,7 +2795,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes( if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -2993,9 +2839,7 @@ size_t DescriptorProto_ExtensionRange::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -3083,7 +2927,6 @@ void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DescriptorProto_ExtensionRange::GetMetadata() const { @@ -3103,16 +2946,15 @@ const int DescriptorProto_ReservedRange::kEndFieldNumber; DescriptorProto_ReservedRange::DescriptorProto_ReservedRange() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ReservedRange) } DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ReservedRange) @@ -3120,8 +2962,7 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf: DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&start_, &from.start_, static_cast(reinterpret_cast(&end_) - @@ -3130,7 +2971,6 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorPro } void DescriptorProto_ReservedRange::SharedCtor() { - _cached_size_ = 0; ::memset(&start_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&start_)) + sizeof(end_)); @@ -3152,9 +2992,7 @@ void DescriptorProto_ReservedRange::ArenaDtor(void* object) { void DescriptorProto_ReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void DescriptorProto_ReservedRange::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -3162,7 +3000,7 @@ const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor( } const DescriptorProto_ReservedRange& DescriptorProto_ReservedRange::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base); return *internal_default_instance(); } @@ -3189,7 +3027,7 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ReservedRange) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -3317,9 +3155,7 @@ size_t DescriptorProto_ReservedRange::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -3400,7 +3236,6 @@ void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange* swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DescriptorProto_ReservedRange::GetMetadata() const { @@ -3443,9 +3278,8 @@ const int DescriptorProto::kReservedNameFieldNumber; DescriptorProto::DescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto) } @@ -3460,7 +3294,7 @@ DescriptorProto::DescriptorProto(::google::protobuf::Arena* arena) oneof_decl_(arena), reserved_range_(arena), reserved_name_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto) @@ -3469,7 +3303,6 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), field_(from.field_), nested_type_(from.nested_type_), enum_type_(from.enum_type_), @@ -3493,7 +3326,6 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from) } void DescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -3516,9 +3348,7 @@ void DescriptorProto::ArenaDtor(void* object) { void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void DescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* DescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -3526,7 +3356,7 @@ const ::google::protobuf::Descriptor* DescriptorProto::descriptor() { } const DescriptorProto& DescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base); return *internal_default_instance(); } @@ -3548,8 +3378,7 @@ void DescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -3566,7 +3395,7 @@ bool DescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -3784,7 +3613,7 @@ void DescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.MessageOptions options = 7; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 7, *options_, output); + 7, this->_internal_options(), output); } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; @@ -3885,7 +3714,7 @@ void DescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 7, *options_, deterministic, target); + 7, this->_internal_options(), deterministic, target); } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; @@ -4033,9 +3862,7 @@ size_t DescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -4136,11 +3963,11 @@ void DescriptorProto::InternalSwap(DescriptorProto* other) { CastToBase(&oneof_decl_)->InternalSwap(CastToBase(&other->oneof_decl_)); CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_)); reserved_name_.InternalSwap(CastToBase(&other->reserved_name_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DescriptorProto::GetMetadata() const { @@ -4159,9 +3986,8 @@ const int ExtensionRangeOptions::kUninterpretedOptionFieldNumber; ExtensionRangeOptions::ExtensionRangeOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ExtensionRangeOptions) } @@ -4170,7 +3996,7 @@ ExtensionRangeOptions::ExtensionRangeOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ExtensionRangeOptions) @@ -4179,7 +4005,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -4187,7 +4012,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) } void ExtensionRangeOptions::SharedCtor() { - _cached_size_ = 0; } ExtensionRangeOptions::~ExtensionRangeOptions() { @@ -4206,9 +4030,7 @@ void ExtensionRangeOptions::ArenaDtor(void* object) { void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void ExtensionRangeOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -4216,7 +4038,7 @@ const ::google::protobuf::Descriptor* ExtensionRangeOptions::descriptor() { } const ExtensionRangeOptions& ExtensionRangeOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base); return *internal_default_instance(); } @@ -4239,7 +4061,7 @@ bool ExtensionRangeOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ExtensionRangeOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -4357,9 +4179,7 @@ size_t ExtensionRangeOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -4436,7 +4256,6 @@ void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) { CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -4480,16 +4299,15 @@ const int FieldDescriptorProto::kOptionsFieldNumber; FieldDescriptorProto::FieldDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldDescriptorProto) } FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto) @@ -4497,8 +4315,7 @@ FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena) FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -4537,7 +4354,6 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) } void FieldDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -4572,9 +4388,7 @@ void FieldDescriptorProto::ArenaDtor(void* object) { void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FieldDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -4582,7 +4396,7 @@ const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() { } const FieldDescriptorProto& FieldDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base); return *internal_default_instance(); } @@ -4596,24 +4410,19 @@ void FieldDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 63u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!extendee_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - extendee_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + extendee_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!type_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - type_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + type_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(!default_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + default_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { - GOOGLE_DCHECK(!json_name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + json_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { GOOGLE_DCHECK(options_ != NULL); @@ -4639,7 +4448,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -4890,7 +4699,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.FieldOptions options = 8; if (cached_has_bits & 0x00000020u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, *options_, output); + 8, this->_internal_options(), output); } // optional int32 oneof_index = 9; @@ -4988,7 +4797,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000020u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 8, *options_, deterministic, target); + 8, this->_internal_options(), deterministic, target); } // optional int32 oneof_index = 9; @@ -5097,9 +4906,7 @@ size_t FieldDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -5206,11 +5013,16 @@ void FieldDescriptorProto::UnsafeArenaSwap(FieldDescriptorProto* other) { } void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); - extendee_.Swap(&other->extendee_); - type_name_.Swap(&other->type_name_); - default_value_.Swap(&other->default_value_); - json_name_.Swap(&other->json_name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + extendee_.Swap(&other->extendee_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + type_name_.Swap(&other->type_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + default_value_.Swap(&other->default_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + json_name_.Swap(&other->json_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(number_, other->number_); swap(oneof_index_, other->oneof_index_); @@ -5218,7 +5030,6 @@ void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) { swap(type_, other->type_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FieldDescriptorProto::GetMetadata() const { @@ -5253,16 +5064,15 @@ const int OneofDescriptorProto::kOptionsFieldNumber; OneofDescriptorProto::OneofDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.OneofDescriptorProto) } OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto) @@ -5270,8 +5080,7 @@ OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena) OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -5287,7 +5096,6 @@ OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from) } void OneofDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -5310,9 +5118,7 @@ void OneofDescriptorProto::ArenaDtor(void* object) { void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void OneofDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -5320,7 +5126,7 @@ const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() { } const OneofDescriptorProto& OneofDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base); return *internal_default_instance(); } @@ -5334,8 +5140,7 @@ void OneofDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -5352,7 +5157,7 @@ bool OneofDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -5424,7 +5229,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.OneofOptions options = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, *options_, output); + 2, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -5457,7 +5262,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, *options_, deterministic, target); + 2, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -5494,9 +5299,7 @@ size_t OneofDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -5575,11 +5378,11 @@ void OneofDescriptorProto::UnsafeArenaSwap(OneofDescriptorProto* other) { } void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata OneofDescriptorProto::GetMetadata() const { @@ -5599,16 +5402,15 @@ const int EnumDescriptorProto_EnumReservedRange::kEndFieldNumber; EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) } EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) @@ -5616,8 +5418,7 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::g EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&start_, &from.start_, static_cast(reinterpret_cast(&end_) - @@ -5626,7 +5427,6 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(con } void EnumDescriptorProto_EnumReservedRange::SharedCtor() { - _cached_size_ = 0; ::memset(&start_, 0, static_cast( reinterpret_cast(&end_) - reinterpret_cast(&start_)) + sizeof(end_)); @@ -5648,9 +5448,7 @@ void EnumDescriptorProto_EnumReservedRange::ArenaDtor(void* object) { void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void EnumDescriptorProto_EnumReservedRange::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -5658,7 +5456,7 @@ const ::google::protobuf::Descriptor* EnumDescriptorProto_EnumReservedRange::des } const EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto_EnumReservedRange::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRange(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base); return *internal_default_instance(); } @@ -5685,7 +5483,7 @@ bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto.EnumReservedRange) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -5813,9 +5611,7 @@ size_t EnumDescriptorProto_EnumReservedRange::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -5896,7 +5692,6 @@ void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_Enu swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const { @@ -5934,9 +5729,8 @@ const int EnumDescriptorProto::kReservedNameFieldNumber; EnumDescriptorProto::EnumDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto) } @@ -5946,7 +5740,7 @@ EnumDescriptorProto::EnumDescriptorProto(::google::protobuf::Arena* arena) value_(arena), reserved_range_(arena), reserved_name_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto) @@ -5955,7 +5749,6 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), value_(from.value_), reserved_range_(from.reserved_range_), reserved_name_(from.reserved_name_) { @@ -5974,7 +5767,6 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) } void EnumDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -5997,9 +5789,7 @@ void EnumDescriptorProto::ArenaDtor(void* object) { void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void EnumDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -6007,7 +5797,7 @@ const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() { } const EnumDescriptorProto& EnumDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base); return *internal_default_instance(); } @@ -6024,8 +5814,7 @@ void EnumDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -6042,7 +5831,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -6164,7 +5953,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.EnumOptions options = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; @@ -6224,7 +6013,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; @@ -6309,9 +6098,7 @@ size_t EnumDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -6397,11 +6184,11 @@ void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) { CastToBase(&value_)->InternalSwap(CastToBase(&other->value_)); CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_)); reserved_name_.InternalSwap(CastToBase(&other->reserved_name_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const { @@ -6437,16 +6224,15 @@ const int EnumValueDescriptorProto::kOptionsFieldNumber; EnumValueDescriptorProto::EnumValueDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValueDescriptorProto) } EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto) @@ -6454,8 +6240,7 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* ar EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -6472,7 +6257,6 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProt } void EnumValueDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&options_, 0, static_cast( reinterpret_cast(&number_) - @@ -6497,9 +6281,7 @@ void EnumValueDescriptorProto::ArenaDtor(void* object) { void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void EnumValueDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -6507,7 +6289,7 @@ const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() { } const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base); return *internal_default_instance(); } @@ -6521,8 +6303,7 @@ void EnumValueDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -6540,7 +6321,7 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -6631,7 +6412,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.EnumValueOptions options = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -6669,7 +6450,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -6713,9 +6494,7 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -6798,12 +6577,12 @@ void EnumValueDescriptorProto::UnsafeArenaSwap(EnumValueDescriptorProto* other) } void EnumValueDescriptorProto::InternalSwap(EnumValueDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(number_, other->number_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumValueDescriptorProto::GetMetadata() const { @@ -6839,9 +6618,8 @@ const int ServiceDescriptorProto::kOptionsFieldNumber; ServiceDescriptorProto::ServiceDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto) } @@ -6849,7 +6627,7 @@ ServiceDescriptorProto::ServiceDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), method_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceDescriptorProto) @@ -6858,7 +6636,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), method_(from.method_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -6875,7 +6652,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro } void ServiceDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); options_ = NULL; } @@ -6898,9 +6674,7 @@ void ServiceDescriptorProto::ArenaDtor(void* object) { void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void ServiceDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -6908,7 +6682,7 @@ const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() { } const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base); return *internal_default_instance(); } @@ -6923,8 +6697,7 @@ void ServiceDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(options_ != NULL); @@ -6941,7 +6714,7 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -7034,7 +6807,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.ServiceOptions options = 3; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, *options_, output); + 3, this->_internal_options(), output); } if (_internal_metadata_.have_unknown_fields()) { @@ -7075,7 +6848,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 3, *options_, deterministic, target); + 3, this->_internal_options(), deterministic, target); } if (_internal_metadata_.have_unknown_fields()) { @@ -7123,9 +6896,7 @@ size_t ServiceDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -7207,11 +6978,11 @@ void ServiceDescriptorProto::UnsafeArenaSwap(ServiceDescriptorProto* other) { void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) { using std::swap; CastToBase(&method_)->InternalSwap(CastToBase(&other->method_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const { @@ -7250,16 +7021,15 @@ const int MethodDescriptorProto::kServerStreamingFieldNumber; MethodDescriptorProto::MethodDescriptorProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MethodDescriptorProto) } MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto) @@ -7267,8 +7037,7 @@ MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena) MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name()) { @@ -7297,7 +7066,6 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) } void MethodDescriptorProto::SharedCtor() { - _cached_size_ = 0; name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -7326,9 +7094,7 @@ void MethodDescriptorProto::ArenaDtor(void* object) { void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void MethodDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -7336,7 +7102,7 @@ const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() { } const MethodDescriptorProto& MethodDescriptorProto::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProto(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base); return *internal_default_instance(); } @@ -7350,16 +7116,13 @@ void MethodDescriptorProto::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 15u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!input_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - input_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + input_type_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!output_type_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - output_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + output_type_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { GOOGLE_DCHECK(options_ != NULL); @@ -7379,7 +7142,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodDescriptorProto) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -7531,7 +7294,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes( // optional .google.protobuf.MethodOptions options = 4; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, *options_, output); + 4, this->_internal_options(), output); } // optional bool client_streaming = 5 [default = false]; @@ -7596,7 +7359,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes( if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, *options_, deterministic, target); + 4, this->_internal_options(), deterministic, target); } // optional bool client_streaming = 5 [default = false]; @@ -7667,9 +7430,7 @@ size_t MethodDescriptorProto::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -7761,15 +7522,17 @@ void MethodDescriptorProto::UnsafeArenaSwap(MethodDescriptorProto* other) { } void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) { using std::swap; - name_.Swap(&other->name_); - input_type_.Swap(&other->input_type_); - output_type_.Swap(&other->output_type_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + input_type_.Swap(&other->input_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + output_type_.Swap(&other->output_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(options_, other->options_); swap(client_streaming_, other->client_streaming_); swap(server_streaming_, other->server_streaming_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata MethodDescriptorProto::GetMetadata() const { @@ -7806,9 +7569,8 @@ const int FileOptions::kUninterpretedOptionFieldNumber; FileOptions::FileOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FileOptions) } @@ -7817,7 +7579,7 @@ FileOptions::FileOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileOptions) @@ -7826,7 +7588,6 @@ FileOptions::FileOptions(const FileOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -7877,7 +7638,6 @@ FileOptions::FileOptions(const FileOptions& from) } void FileOptions::SharedCtor() { - _cached_size_ = 0; java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -7916,9 +7676,7 @@ void FileOptions::ArenaDtor(void* object) { void FileOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FileOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FileOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -7926,7 +7684,7 @@ const ::google::protobuf::Descriptor* FileOptions::descriptor() { } const FileOptions& FileOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base); return *internal_default_instance(); } @@ -7942,36 +7700,28 @@ void FileOptions::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 255u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!java_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - java_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + java_package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!java_outer_classname_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - java_outer_classname_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + java_outer_classname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!go_package_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - go_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + go_package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(!objc_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - objc_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + objc_class_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { - GOOGLE_DCHECK(!csharp_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - csharp_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + csharp_namespace_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { - GOOGLE_DCHECK(!swift_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - swift_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + swift_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000040u) { - GOOGLE_DCHECK(!php_class_prefix_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - php_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + php_class_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000080u) { - GOOGLE_DCHECK(!php_namespace_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - php_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + php_namespace_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 65280u) { @@ -7993,7 +7743,7 @@ bool FileOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FileOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -8770,9 +8520,7 @@ size_t FileOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -8910,14 +8658,22 @@ void FileOptions::UnsafeArenaSwap(FileOptions* other) { void FileOptions::InternalSwap(FileOptions* other) { using std::swap; CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); - java_package_.Swap(&other->java_package_); - java_outer_classname_.Swap(&other->java_outer_classname_); - go_package_.Swap(&other->go_package_); - objc_class_prefix_.Swap(&other->objc_class_prefix_); - csharp_namespace_.Swap(&other->csharp_namespace_); - swift_prefix_.Swap(&other->swift_prefix_); - php_class_prefix_.Swap(&other->php_class_prefix_); - php_namespace_.Swap(&other->php_namespace_); + java_package_.Swap(&other->java_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + java_outer_classname_.Swap(&other->java_outer_classname_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + go_package_.Swap(&other->go_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + objc_class_prefix_.Swap(&other->objc_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + csharp_namespace_.Swap(&other->csharp_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + swift_prefix_.Swap(&other->swift_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + php_class_prefix_.Swap(&other->php_class_prefix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + php_namespace_.Swap(&other->php_namespace_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(cc_enable_arenas_, other->cc_enable_arenas_); swap(java_multiple_files_, other->java_multiple_files_); swap(java_generate_equals_and_hash_, other->java_generate_equals_and_hash_); @@ -8930,7 +8686,6 @@ void FileOptions::InternalSwap(FileOptions* other) { swap(optimize_for_, other->optimize_for_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -8954,9 +8709,8 @@ const int MessageOptions::kUninterpretedOptionFieldNumber; MessageOptions::MessageOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MessageOptions) } @@ -8965,7 +8719,7 @@ MessageOptions::MessageOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MessageOptions) @@ -8974,7 +8728,6 @@ MessageOptions::MessageOptions(const MessageOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -8985,7 +8738,6 @@ MessageOptions::MessageOptions(const MessageOptions& from) } void MessageOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&message_set_wire_format_, 0, static_cast( reinterpret_cast(&map_entry_) - reinterpret_cast(&message_set_wire_format_)) + sizeof(map_entry_)); @@ -9007,9 +8759,7 @@ void MessageOptions::ArenaDtor(void* object) { void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void MessageOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* MessageOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -9017,7 +8767,7 @@ const ::google::protobuf::Descriptor* MessageOptions::descriptor() { } const MessageOptions& MessageOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base); return *internal_default_instance(); } @@ -9043,7 +8793,7 @@ bool MessageOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MessageOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -9281,9 +9031,7 @@ size_t MessageOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -9380,7 +9128,6 @@ void MessageOptions::InternalSwap(MessageOptions* other) { swap(map_entry_, other->map_entry_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -9406,9 +9153,8 @@ const int FieldOptions::kUninterpretedOptionFieldNumber; FieldOptions::FieldOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldOptions) } @@ -9417,7 +9163,7 @@ FieldOptions::FieldOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldOptions) @@ -9426,7 +9172,6 @@ FieldOptions::FieldOptions(const FieldOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -9437,7 +9182,6 @@ FieldOptions::FieldOptions(const FieldOptions& from) } void FieldOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&ctype_, 0, static_cast( reinterpret_cast(&jstype_) - reinterpret_cast(&ctype_)) + sizeof(jstype_)); @@ -9459,9 +9203,7 @@ void FieldOptions::ArenaDtor(void* object) { void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FieldOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FieldOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -9469,7 +9211,7 @@ const ::google::protobuf::Descriptor* FieldOptions::descriptor() { } const FieldOptions& FieldOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base); return *internal_default_instance(); } @@ -9498,7 +9240,7 @@ bool FieldOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -9812,9 +9554,7 @@ size_t FieldOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -9919,7 +9659,6 @@ void FieldOptions::InternalSwap(FieldOptions* other) { swap(jstype_, other->jstype_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -9939,9 +9678,8 @@ const int OneofOptions::kUninterpretedOptionFieldNumber; OneofOptions::OneofOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.OneofOptions) } @@ -9950,7 +9688,7 @@ OneofOptions::OneofOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofOptions) @@ -9959,7 +9697,6 @@ OneofOptions::OneofOptions(const OneofOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -9967,7 +9704,6 @@ OneofOptions::OneofOptions(const OneofOptions& from) } void OneofOptions::SharedCtor() { - _cached_size_ = 0; } OneofOptions::~OneofOptions() { @@ -9986,9 +9722,7 @@ void OneofOptions::ArenaDtor(void* object) { void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void OneofOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* OneofOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -9996,7 +9730,7 @@ const ::google::protobuf::Descriptor* OneofOptions::descriptor() { } const OneofOptions& OneofOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base); return *internal_default_instance(); } @@ -10019,7 +9753,7 @@ bool OneofOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.OneofOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -10137,9 +9871,7 @@ size_t OneofOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -10216,7 +9948,6 @@ void OneofOptions::InternalSwap(OneofOptions* other) { CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -10238,9 +9969,8 @@ const int EnumOptions::kUninterpretedOptionFieldNumber; EnumOptions::EnumOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumOptions) } @@ -10249,7 +9979,7 @@ EnumOptions::EnumOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumOptions) @@ -10258,7 +9988,6 @@ EnumOptions::EnumOptions(const EnumOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -10269,7 +9998,6 @@ EnumOptions::EnumOptions(const EnumOptions& from) } void EnumOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&allow_alias_, 0, static_cast( reinterpret_cast(&deprecated_) - reinterpret_cast(&allow_alias_)) + sizeof(deprecated_)); @@ -10291,9 +10019,7 @@ void EnumOptions::ArenaDtor(void* object) { void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void EnumOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -10301,7 +10027,7 @@ const ::google::protobuf::Descriptor* EnumOptions::descriptor() { } const EnumOptions& EnumOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base); return *internal_default_instance(); } @@ -10327,7 +10053,7 @@ bool EnumOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -10507,9 +10233,7 @@ size_t EnumOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -10598,7 +10322,6 @@ void EnumOptions::InternalSwap(EnumOptions* other) { swap(deprecated_, other->deprecated_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -10619,9 +10342,8 @@ const int EnumValueOptions::kUninterpretedOptionFieldNumber; EnumValueOptions::EnumValueOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions) } @@ -10630,7 +10352,7 @@ EnumValueOptions::EnumValueOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueOptions) @@ -10639,7 +10361,6 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -10648,7 +10369,6 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) } void EnumValueOptions::SharedCtor() { - _cached_size_ = 0; deprecated_ = false; } @@ -10668,9 +10388,7 @@ void EnumValueOptions::ArenaDtor(void* object) { void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void EnumValueOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -10678,7 +10396,7 @@ const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() { } const EnumValueOptions& EnumValueOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base); return *internal_default_instance(); } @@ -10702,7 +10420,7 @@ bool EnumValueOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValueOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -10851,9 +10569,7 @@ size_t EnumValueOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -10934,7 +10650,6 @@ void EnumValueOptions::InternalSwap(EnumValueOptions* other) { swap(deprecated_, other->deprecated_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -10955,9 +10670,8 @@ const int ServiceOptions::kUninterpretedOptionFieldNumber; ServiceOptions::ServiceOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions) } @@ -10966,7 +10680,7 @@ ServiceOptions::ServiceOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceOptions) @@ -10975,7 +10689,6 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -10984,7 +10697,6 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from) } void ServiceOptions::SharedCtor() { - _cached_size_ = 0; deprecated_ = false; } @@ -11004,9 +10716,7 @@ void ServiceOptions::ArenaDtor(void* object) { void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void ServiceOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ServiceOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -11014,7 +10724,7 @@ const ::google::protobuf::Descriptor* ServiceOptions::descriptor() { } const ServiceOptions& ServiceOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base); return *internal_default_instance(); } @@ -11038,7 +10748,7 @@ bool ServiceOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ServiceOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -11187,9 +10897,7 @@ size_t ServiceOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -11270,7 +10978,6 @@ void ServiceOptions::InternalSwap(ServiceOptions* other) { swap(deprecated_, other->deprecated_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -11292,9 +10999,8 @@ const int MethodOptions::kUninterpretedOptionFieldNumber; MethodOptions::MethodOptions() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.MethodOptions) } @@ -11303,7 +11009,7 @@ MethodOptions::MethodOptions(::google::protobuf::Arena* arena) _extensions_(arena), _internal_metadata_(arena), uninterpreted_option_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodOptions) @@ -11312,7 +11018,6 @@ MethodOptions::MethodOptions(const MethodOptions& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), uninterpreted_option_(from.uninterpreted_option_) { _internal_metadata_.MergeFrom(from._internal_metadata_); _extensions_.MergeFrom(from._extensions_); @@ -11323,7 +11028,6 @@ MethodOptions::MethodOptions(const MethodOptions& from) } void MethodOptions::SharedCtor() { - _cached_size_ = 0; ::memset(&deprecated_, 0, static_cast( reinterpret_cast(&idempotency_level_) - reinterpret_cast(&deprecated_)) + sizeof(idempotency_level_)); @@ -11345,9 +11049,7 @@ void MethodOptions::ArenaDtor(void* object) { void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void MethodOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* MethodOptions::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -11355,7 +11057,7 @@ const ::google::protobuf::Descriptor* MethodOptions::descriptor() { } const MethodOptions& MethodOptions::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptions(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base); return *internal_default_instance(); } @@ -11384,7 +11086,7 @@ bool MethodOptions::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.MethodOptions) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -11573,9 +11275,7 @@ size_t MethodOptions::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -11664,7 +11364,6 @@ void MethodOptions::InternalSwap(MethodOptions* other) { swap(idempotency_level_, other->idempotency_level_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); _extensions_.Swap(&other->_extensions_); } @@ -11685,16 +11384,15 @@ const int UninterpretedOption_NamePart::kIsExtensionFieldNumber; UninterpretedOption_NamePart::UninterpretedOption_NamePart() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption.NamePart) } UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption.NamePart) @@ -11702,8 +11400,7 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::A UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - _cached_size_(0) { + _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.has_name_part()) { @@ -11715,7 +11412,6 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp } void UninterpretedOption_NamePart::SharedCtor() { - _cached_size_ = 0; name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); is_extension_ = false; } @@ -11737,9 +11433,7 @@ void UninterpretedOption_NamePart::ArenaDtor(void* object) { void UninterpretedOption_NamePart::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void UninterpretedOption_NamePart::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -11747,7 +11441,7 @@ const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() } const UninterpretedOption_NamePart& UninterpretedOption_NamePart::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePart(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base); return *internal_default_instance(); } @@ -11760,8 +11454,7 @@ void UninterpretedOption_NamePart::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!name_part_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - name_part_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + name_part_.ClearNonDefaultToEmpty(); } is_extension_ = false; _has_bits_.Clear(); @@ -11774,7 +11467,7 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption.NamePart) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -11929,9 +11622,7 @@ size_t UninterpretedOption_NamePart::ByteSizeLong() const { total_size += RequiredFieldsByteSizeFallback(); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -12009,11 +11700,11 @@ void UninterpretedOption_NamePart::UnsafeArenaSwap(UninterpretedOption_NamePart* } void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* other) { using std::swap; - name_part_.Swap(&other->name_part_); + name_part_.Swap(&other->name_part_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(is_extension_, other->is_extension_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata UninterpretedOption_NamePart::GetMetadata() const { @@ -12038,9 +11729,8 @@ const int UninterpretedOption::kAggregateValueFieldNumber; UninterpretedOption::UninterpretedOption() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption) } @@ -12048,7 +11738,7 @@ UninterpretedOption::UninterpretedOption(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), name_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption) @@ -12057,7 +11747,6 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), name_(from.name_) { _internal_metadata_.MergeFrom(from._internal_metadata_); identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -12082,7 +11771,6 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) } void UninterpretedOption::SharedCtor() { - _cached_size_ = 0; identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -12110,9 +11798,7 @@ void UninterpretedOption::ArenaDtor(void* object) { void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void UninterpretedOption::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -12120,7 +11806,7 @@ const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() { } const UninterpretedOption& UninterpretedOption::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base); return *internal_default_instance(); } @@ -12135,16 +11821,13 @@ void UninterpretedOption::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!identifier_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - identifier_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + identifier_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!string_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - string_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + string_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - GOOGLE_DCHECK(!aggregate_value_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - aggregate_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + aggregate_value_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 56u) { @@ -12162,7 +11845,7 @@ bool UninterpretedOption::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -12479,9 +12162,7 @@ size_t UninterpretedOption::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -12573,15 +12254,17 @@ void UninterpretedOption::UnsafeArenaSwap(UninterpretedOption* other) { void UninterpretedOption::InternalSwap(UninterpretedOption* other) { using std::swap; CastToBase(&name_)->InternalSwap(CastToBase(&other->name_)); - identifier_value_.Swap(&other->identifier_value_); - string_value_.Swap(&other->string_value_); - aggregate_value_.Swap(&other->aggregate_value_); + identifier_value_.Swap(&other->identifier_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + string_value_.Swap(&other->string_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + aggregate_value_.Swap(&other->aggregate_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(positive_int_value_, other->positive_int_value_); swap(negative_int_value_, other->negative_int_value_); swap(double_value_, other->double_value_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata UninterpretedOption::GetMetadata() const { @@ -12604,9 +12287,8 @@ const int SourceCodeInfo_Location::kLeadingDetachedCommentsFieldNumber; SourceCodeInfo_Location::SourceCodeInfo_Location() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location) } @@ -12616,7 +12298,7 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(::google::protobuf::Arena* aren path_(arena), span_(arena), leading_detached_comments_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo.Location) @@ -12625,7 +12307,6 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), path_(from.path_), span_(from.span_), leading_detached_comments_(from.leading_detached_comments_) { @@ -12644,7 +12325,6 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& } void SourceCodeInfo_Location::SharedCtor() { - _cached_size_ = 0; leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } @@ -12667,9 +12347,7 @@ void SourceCodeInfo_Location::ArenaDtor(void* object) { void SourceCodeInfo_Location::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void SourceCodeInfo_Location::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -12677,7 +12355,7 @@ const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() { } const SourceCodeInfo_Location& SourceCodeInfo_Location::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_Location(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base); return *internal_default_instance(); } @@ -12694,12 +12372,10 @@ void SourceCodeInfo_Location::Clear() { cached_has_bits = _has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!leading_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - leading_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + leading_comments_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(!trailing_comments_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - trailing_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + trailing_comments_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); @@ -12712,7 +12388,7 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo.Location) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -13029,9 +12705,7 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -13113,11 +12787,12 @@ void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) { path_.InternalSwap(&other->path_); span_.InternalSwap(&other->span_); leading_detached_comments_.InternalSwap(CastToBase(&other->leading_detached_comments_)); - leading_comments_.Swap(&other->leading_comments_); - trailing_comments_.Swap(&other->trailing_comments_); + leading_comments_.Swap(&other->leading_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + trailing_comments_.Swap(&other->trailing_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SourceCodeInfo_Location::GetMetadata() const { @@ -13136,9 +12811,8 @@ const int SourceCodeInfo::kLocationFieldNumber; SourceCodeInfo::SourceCodeInfo() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo) } @@ -13146,7 +12820,7 @@ SourceCodeInfo::SourceCodeInfo(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), location_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo) @@ -13155,14 +12829,12 @@ SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), location_(from.location_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo) } void SourceCodeInfo::SharedCtor() { - _cached_size_ = 0; } SourceCodeInfo::~SourceCodeInfo() { @@ -13181,9 +12853,7 @@ void SourceCodeInfo::ArenaDtor(void* object) { void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void SourceCodeInfo::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -13191,7 +12861,7 @@ const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() { } const SourceCodeInfo& SourceCodeInfo::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base); return *internal_default_instance(); } @@ -13213,7 +12883,7 @@ bool SourceCodeInfo::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -13315,9 +12985,7 @@ size_t SourceCodeInfo::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -13388,7 +13056,6 @@ void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) { CastToBase(&location_)->InternalSwap(CastToBase(&other->location_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SourceCodeInfo::GetMetadata() const { @@ -13410,9 +13077,8 @@ const int GeneratedCodeInfo_Annotation::kEndFieldNumber; GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation) } @@ -13420,7 +13086,7 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::google::protobuf::A : ::google::protobuf::Message(), _internal_metadata_(arena), path_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo.Annotation) @@ -13429,7 +13095,6 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), path_(from.path_) { _internal_metadata_.MergeFrom(from._internal_metadata_); source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); @@ -13444,7 +13109,6 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn } void GeneratedCodeInfo_Annotation::SharedCtor() { - _cached_size_ = 0; source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&begin_, 0, static_cast( reinterpret_cast(&end_) - @@ -13468,9 +13132,7 @@ void GeneratedCodeInfo_Annotation::ArenaDtor(void* object) { void GeneratedCodeInfo_Annotation::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -13478,7 +13140,7 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor() } const GeneratedCodeInfo_Annotation& GeneratedCodeInfo_Annotation::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_Annotation(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base); return *internal_default_instance(); } @@ -13492,8 +13154,7 @@ void GeneratedCodeInfo_Annotation::Clear() { path_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(!source_file_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited())); - source_file_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + source_file_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 6u) { ::memset(&begin_, 0, static_cast( @@ -13510,7 +13171,7 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo.Annotation) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -13741,9 +13402,7 @@ size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -13825,12 +13484,12 @@ void GeneratedCodeInfo_Annotation::UnsafeArenaSwap(GeneratedCodeInfo_Annotation* void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* other) { using std::swap; path_.InternalSwap(&other->path_); - source_file_.Swap(&other->source_file_); + source_file_.Swap(&other->source_file_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(begin_, other->begin_); swap(end_, other->end_); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const { @@ -13849,9 +13508,8 @@ const int GeneratedCodeInfo::kAnnotationFieldNumber; GeneratedCodeInfo::GeneratedCodeInfo() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo) } @@ -13859,7 +13517,7 @@ GeneratedCodeInfo::GeneratedCodeInfo(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), annotation_(arena) { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo) @@ -13868,14 +13526,12 @@ GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), - _cached_size_(0), annotation_(from.annotation_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo) } void GeneratedCodeInfo::SharedCtor() { - _cached_size_ = 0; } GeneratedCodeInfo::~GeneratedCodeInfo() { @@ -13894,9 +13550,7 @@ void GeneratedCodeInfo::ArenaDtor(void* object) { void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void GeneratedCodeInfo::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() { ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce(); @@ -13904,7 +13558,7 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() { } const GeneratedCodeInfo& GeneratedCodeInfo::default_instance() { - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base); return *internal_default_instance(); } @@ -13926,7 +13580,7 @@ bool GeneratedCodeInfo::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -14028,9 +13682,7 @@ size_t GeneratedCodeInfo::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -14101,7 +13753,6 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) { CastToBase(&annotation_)->InternalSwap(CastToBase(&other->annotation_)); swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GeneratedCodeInfo::GetMetadata() const { @@ -14115,85 +13766,85 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorSet >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ExtensionRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMessage< ::google::protobuf::DescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ExtensionRangeOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FieldDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::OneofDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValueDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ServiceDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MethodDescriptorProto >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMessage< ::google::protobuf::FileOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMaybeMessage< ::google::protobuf::FileOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FileOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMessage< ::google::protobuf::MessageOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MessageOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMessage< ::google::protobuf::FieldOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::FieldOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMessage< ::google::protobuf::OneofOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage< ::google::protobuf::OneofOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::OneofOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMessage< ::google::protobuf::EnumOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValueOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMessage< ::google::protobuf::ServiceOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage< ::google::protobuf::ServiceOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ServiceOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMessage< ::google::protobuf::MethodOptions >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::MethodOptions >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption_NamePart >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo_Location >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo_Annotation >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 4ec0a5b4bd..07a3c2f0ae 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/descriptor.proto -#ifndef PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto #include @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: export @@ -31,6 +32,7 @@ #include #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { // Internal implementation detail -- do not use these members. @@ -43,89 +45,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSetImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorSet(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFileDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRangeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ExtensionRange(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRangeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto_ReservedRange(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsExtensionRangeOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto_EnumReservedRange(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProtoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodDescriptorProto(); -void LIBPROTOBUF_EXPORT InitDefaultsFileOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFileOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsMessageOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMessageOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsOneofOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsServiceOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodOptionsImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsMethodOptions(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePartImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption_NamePart(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOptionImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsUninterpretedOption(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_LocationImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo_Location(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceCodeInfo(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_AnnotationImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo_Annotation(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfoImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsGeneratedCodeInfo(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsFileDescriptorSet(); - InitDefaultsFileDescriptorProto(); - InitDefaultsDescriptorProto_ExtensionRange(); - InitDefaultsDescriptorProto_ReservedRange(); - InitDefaultsDescriptorProto(); - InitDefaultsExtensionRangeOptions(); - InitDefaultsFieldDescriptorProto(); - InitDefaultsOneofDescriptorProto(); - InitDefaultsEnumDescriptorProto_EnumReservedRange(); - InitDefaultsEnumDescriptorProto(); - InitDefaultsEnumValueDescriptorProto(); - InitDefaultsServiceDescriptorProto(); - InitDefaultsMethodDescriptorProto(); - InitDefaultsFileOptions(); - InitDefaultsMessageOptions(); - InitDefaultsFieldOptions(); - InitDefaultsOneofOptions(); - InitDefaultsEnumOptions(); - InitDefaultsEnumValueOptions(); - InitDefaultsServiceOptions(); - InitDefaultsMethodOptions(); - InitDefaultsUninterpretedOption_NamePart(); - InitDefaultsUninterpretedOption(); - InitDefaultsSourceCodeInfo_Location(); - InitDefaultsSourceCodeInfo(); - InitDefaultsGeneratedCodeInfo_Annotation(); - InitDefaultsGeneratedCodeInfo(); -} } // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto namespace google { namespace protobuf { @@ -214,33 +133,33 @@ LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _Unint } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMessage< ::google::protobuf::DescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ExtensionRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMessage< ::google::protobuf::DescriptorProto_ReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMessage< ::google::protobuf::EnumOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMessage< ::google::protobuf::EnumValueDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMessage< ::google::protobuf::EnumValueOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMessage< ::google::protobuf::FieldDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMessage< ::google::protobuf::FieldOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMessage< ::google::protobuf::FileDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMessage< ::google::protobuf::FileDescriptorSet>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMessage< ::google::protobuf::FileOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMessage< ::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMessage< ::google::protobuf::MessageOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMessage< ::google::protobuf::MethodDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMessage< ::google::protobuf::MethodOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMessage< ::google::protobuf::OneofDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMessage< ::google::protobuf::OneofOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMessage< ::google::protobuf::ServiceDescriptorProto>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMessage< ::google::protobuf::ServiceOptions>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMessage< ::google::protobuf::SourceCodeInfo_Location>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMessage< ::google::protobuf::UninterpretedOption>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMessage< ::google::protobuf::UninterpretedOption_NamePart>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -416,10 +335,10 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -430,7 +349,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message return reinterpret_cast( &_FileDescriptorSet_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(FileDescriptorSet* other); @@ -441,32 +360,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message // implements Message ---------------------------------------------- - inline FileDescriptorSet* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline FileDescriptorSet* New() const final { + return CreateMaybeMessage(NULL); } - FileDescriptorSet* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + FileDescriptorSet* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FileDescriptorSet& from); void MergeFrom(const FileDescriptorSet& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorSet* other); protected: explicit FileDescriptorSet(::google::protobuf::Arena* arena); @@ -482,7 +402,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -508,10 +428,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorSetImpl(); }; // ------------------------------------------------------------------- @@ -548,10 +467,10 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -562,7 +481,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag return reinterpret_cast( &_FileDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void UnsafeArenaSwap(FileDescriptorProto* other); @@ -573,32 +492,33 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline FileDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline FileDescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - FileDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + FileDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FileDescriptorProto& from); void MergeFrom(const FileDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorProto* other); protected: explicit FileDescriptorProto(::google::protobuf::Arena* arena); @@ -614,7 +534,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -790,6 +710,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 8; + private: + const ::google::protobuf::FileOptions& _internal_options() const; + public: const ::google::protobuf::FileOptions& options() const; ::google::protobuf::FileOptions* release_options(); ::google::protobuf::FileOptions* mutable_options(); @@ -802,6 +725,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag bool has_source_code_info() const; void clear_source_code_info(); static const int kSourceCodeInfoFieldNumber = 9; + private: + const ::google::protobuf::SourceCodeInfo& _internal_source_code_info() const; + public: const ::google::protobuf::SourceCodeInfo& source_code_info() const; ::google::protobuf::SourceCodeInfo* release_source_code_info(); ::google::protobuf::SourceCodeInfo* mutable_source_code_info(); @@ -828,7 +754,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::std::string> dependency_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > message_type_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; @@ -842,7 +768,6 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag ::google::protobuf::FileOptions* options_; ::google::protobuf::SourceCodeInfo* source_code_info_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -879,10 +804,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -893,7 +818,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto return reinterpret_cast( &_DescriptorProto_ExtensionRange_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void UnsafeArenaSwap(DescriptorProto_ExtensionRange* other); @@ -904,32 +829,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto // implements Message ---------------------------------------------- - inline DescriptorProto_ExtensionRange* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline DescriptorProto_ExtensionRange* New() const final { + return CreateMaybeMessage(NULL); } - DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + DescriptorProto_ExtensionRange* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DescriptorProto_ExtensionRange& from); void MergeFrom(const DescriptorProto_ExtensionRange& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ExtensionRange* other); protected: explicit DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena); @@ -945,7 +871,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -955,6 +881,9 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::ExtensionRangeOptions& _internal_options() const; + public: const ::google::protobuf::ExtensionRangeOptions& options() const; ::google::protobuf::ExtensionRangeOptions* release_options(); ::google::protobuf::ExtensionRangeOptions* mutable_options(); @@ -991,12 +920,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::ExtensionRangeOptions* options_; ::google::protobuf::int32 start_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ExtensionRangeImpl(); }; // ------------------------------------------------------------------- @@ -1033,10 +961,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1047,7 +975,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob return reinterpret_cast( &_DescriptorProto_ReservedRange_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void UnsafeArenaSwap(DescriptorProto_ReservedRange* other); @@ -1058,32 +986,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob // implements Message ---------------------------------------------- - inline DescriptorProto_ReservedRange* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline DescriptorProto_ReservedRange* New() const final { + return CreateMaybeMessage(NULL); } - DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + DescriptorProto_ReservedRange* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DescriptorProto_ReservedRange& from); void MergeFrom(const DescriptorProto_ReservedRange& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ReservedRange* other); protected: explicit DescriptorProto_ReservedRange(::google::protobuf::Arena* arena); @@ -1099,7 +1028,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1131,11 +1060,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::int32 start_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProto_ReservedRangeImpl(); }; // ------------------------------------------------------------------- @@ -1172,10 +1100,10 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1186,7 +1114,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* return reinterpret_cast( &_DescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 4; void UnsafeArenaSwap(DescriptorProto* other); @@ -1197,32 +1125,33 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline DescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline DescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - DescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + DescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const DescriptorProto& from); void MergeFrom(const DescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto* other); protected: explicit DescriptorProto(::google::protobuf::Arena* arena); @@ -1238,7 +1167,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1381,6 +1310,9 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 7; + private: + const ::google::protobuf::MessageOptions& _internal_options() const; + public: const ::google::protobuf::MessageOptions& options() const; ::google::protobuf::MessageOptions* release_options(); ::google::protobuf::MessageOptions* mutable_options(); @@ -1401,7 +1333,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > nested_type_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; @@ -1413,7 +1345,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::MessageOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -1450,10 +1381,10 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1464,7 +1395,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess return reinterpret_cast( &_ExtensionRangeOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 5; void UnsafeArenaSwap(ExtensionRangeOptions* other); @@ -1475,32 +1406,33 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess // implements Message ---------------------------------------------- - inline ExtensionRangeOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline ExtensionRangeOptions* New() const final { + return CreateMaybeMessage(NULL); } - ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + ExtensionRangeOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ExtensionRangeOptions& from); void MergeFrom(const ExtensionRangeOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ExtensionRangeOptions* other); protected: explicit ExtensionRangeOptions(::google::protobuf::Arena* arena); @@ -1516,7 +1448,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1545,10 +1477,9 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsExtensionRangeOptionsImpl(); }; // ------------------------------------------------------------------- @@ -1585,10 +1516,10 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1599,7 +1530,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa return reinterpret_cast( &_FieldDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 6; void UnsafeArenaSwap(FieldDescriptorProto* other); @@ -1610,32 +1541,33 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa // implements Message ---------------------------------------------- - inline FieldDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline FieldDescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - FieldDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + FieldDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FieldDescriptorProto& from); void MergeFrom(const FieldDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FieldDescriptorProto* other); protected: explicit FieldDescriptorProto(::google::protobuf::Arena* arena); @@ -1651,7 +1583,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1867,6 +1799,9 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 8; + private: + const ::google::protobuf::FieldOptions& _internal_options() const; + public: const ::google::protobuf::FieldOptions& options() const; ::google::protobuf::FieldOptions* release_options(); ::google::protobuf::FieldOptions* mutable_options(); @@ -1931,7 +1866,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr extendee_; ::google::protobuf::internal::ArenaStringPtr type_name_; @@ -1943,7 +1878,6 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa int label_; int type_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -1980,10 +1914,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1994,7 +1928,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa return reinterpret_cast( &_OneofDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 7; void UnsafeArenaSwap(OneofDescriptorProto* other); @@ -2005,32 +1939,33 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa // implements Message ---------------------------------------------- - inline OneofDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline OneofDescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - OneofDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + OneofDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const OneofDescriptorProto& from); void MergeFrom(const OneofDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(OneofDescriptorProto* other); protected: explicit OneofDescriptorProto(::google::protobuf::Arena* arena); @@ -2046,7 +1981,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2080,6 +2015,9 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 2; + private: + const ::google::protobuf::OneofOptions& _internal_options() const; + public: const ::google::protobuf::OneofOptions& options() const; ::google::protobuf::OneofOptions* release_options(); ::google::protobuf::OneofOptions* mutable_options(); @@ -2100,11 +2038,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::OneofOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2141,10 +2078,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2155,7 +2092,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google return reinterpret_cast( &_EnumDescriptorProto_EnumReservedRange_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 8; void UnsafeArenaSwap(EnumDescriptorProto_EnumReservedRange* other); @@ -2166,32 +2103,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google // implements Message ---------------------------------------------- - inline EnumDescriptorProto_EnumReservedRange* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline EnumDescriptorProto_EnumReservedRange* New() const final { + return CreateMaybeMessage(NULL); } - EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + EnumDescriptorProto_EnumReservedRange* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumDescriptorProto_EnumReservedRange& from); void MergeFrom(const EnumDescriptorProto_EnumReservedRange& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto_EnumReservedRange* other); protected: explicit EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena); @@ -2207,7 +2145,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2239,11 +2177,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::int32 start_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProto_EnumReservedRangeImpl(); }; // ------------------------------------------------------------------- @@ -2280,10 +2217,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2294,7 +2231,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag return reinterpret_cast( &_EnumDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 9; void UnsafeArenaSwap(EnumDescriptorProto* other); @@ -2305,32 +2242,33 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline EnumDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline EnumDescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - EnumDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + EnumDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumDescriptorProto& from); void MergeFrom(const EnumDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto* other); protected: explicit EnumDescriptorProto(::google::protobuf::Arena* arena); @@ -2346,7 +2284,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2428,6 +2366,9 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::EnumOptions& _internal_options() const; + public: const ::google::protobuf::EnumOptions& options() const; ::google::protobuf::EnumOptions* release_options(); ::google::protobuf::EnumOptions* mutable_options(); @@ -2448,14 +2389,13 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto > value_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto_EnumReservedRange > reserved_range_; ::google::protobuf::RepeatedPtrField< ::std::string> reserved_name_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::EnumOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2492,10 +2432,10 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2506,7 +2446,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M return reinterpret_cast( &_EnumValueDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 10; void UnsafeArenaSwap(EnumValueDescriptorProto* other); @@ -2517,32 +2457,33 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M // implements Message ---------------------------------------------- - inline EnumValueDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline EnumValueDescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + EnumValueDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumValueDescriptorProto& from); void MergeFrom(const EnumValueDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumValueDescriptorProto* other); protected: explicit EnumValueDescriptorProto(::google::protobuf::Arena* arena); @@ -2558,7 +2499,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2592,6 +2533,9 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::EnumValueOptions& _internal_options() const; + public: const ::google::protobuf::EnumValueOptions& options() const; ::google::protobuf::EnumValueOptions* release_options(); ::google::protobuf::EnumValueOptions* mutable_options(); @@ -2621,12 +2565,11 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::EnumValueOptions* options_; ::google::protobuf::int32 number_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2663,10 +2606,10 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2677,7 +2620,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes return reinterpret_cast( &_ServiceDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 11; void UnsafeArenaSwap(ServiceDescriptorProto* other); @@ -2688,32 +2631,33 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes // implements Message ---------------------------------------------- - inline ServiceDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline ServiceDescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + ServiceDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ServiceDescriptorProto& from); void MergeFrom(const ServiceDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ServiceDescriptorProto* other); protected: explicit ServiceDescriptorProto(::google::protobuf::Arena* arena); @@ -2729,7 +2673,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2775,6 +2719,9 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 3; + private: + const ::google::protobuf::ServiceOptions& _internal_options() const; + public: const ::google::protobuf::ServiceOptions& options() const; ::google::protobuf::ServiceOptions* release_options(); ::google::protobuf::ServiceOptions* mutable_options(); @@ -2795,12 +2742,11 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto > method_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::ServiceOptions* options_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -2837,10 +2783,10 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -2851,7 +2797,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess return reinterpret_cast( &_MethodDescriptorProto_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 12; void UnsafeArenaSwap(MethodDescriptorProto* other); @@ -2862,32 +2808,33 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess // implements Message ---------------------------------------------- - inline MethodDescriptorProto* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline MethodDescriptorProto* New() const final { + return CreateMaybeMessage(NULL); } - MethodDescriptorProto* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + MethodDescriptorProto* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MethodDescriptorProto& from); void MergeFrom(const MethodDescriptorProto& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(MethodDescriptorProto* other); protected: explicit MethodDescriptorProto(::google::protobuf::Arena* arena); @@ -2903,7 +2850,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -2985,6 +2932,9 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess bool has_options() const; void clear_options(); static const int kOptionsFieldNumber = 4; + private: + const ::google::protobuf::MethodOptions& _internal_options() const; + public: const ::google::protobuf::MethodOptions& options() const; ::google::protobuf::MethodOptions* release_options(); ::google::protobuf::MethodOptions* mutable_options(); @@ -3027,7 +2977,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::internal::ArenaStringPtr input_type_; ::google::protobuf::internal::ArenaStringPtr output_type_; @@ -3035,7 +2985,6 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess bool client_streaming_; bool server_streaming_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodDescriptorProtoImpl(); }; // ------------------------------------------------------------------- @@ -3072,10 +3021,10 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3086,7 +3035,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p return reinterpret_cast( &_FileOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 13; void UnsafeArenaSwap(FileOptions* other); @@ -3097,32 +3046,33 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline FileOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline FileOptions* New() const final { + return CreateMaybeMessage(NULL); } - FileOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + FileOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FileOptions& from); void MergeFrom(const FileOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FileOptions* other); protected: explicit FileOptions(::google::protobuf::Arena* arena); @@ -3138,7 +3088,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -3493,7 +3443,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; ::google::protobuf::internal::ArenaStringPtr java_package_; ::google::protobuf::internal::ArenaStringPtr java_outer_classname_; @@ -3514,7 +3464,6 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p bool deprecated_; int optimize_for_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFileOptionsImpl(); }; // ------------------------------------------------------------------- @@ -3551,10 +3500,10 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3565,7 +3514,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* return reinterpret_cast( &_MessageOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 14; void UnsafeArenaSwap(MessageOptions* other); @@ -3576,32 +3525,33 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline MessageOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline MessageOptions* New() const final { + return CreateMaybeMessage(NULL); } - MessageOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + MessageOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MessageOptions& from); void MergeFrom(const MessageOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(MessageOptions* other); protected: explicit MessageOptions(::google::protobuf::Arena* arena); @@ -3617,7 +3567,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -3682,14 +3632,13 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool message_set_wire_format_; bool no_standard_descriptor_accessor_; bool deprecated_; bool map_entry_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMessageOptionsImpl(); }; // ------------------------------------------------------------------- @@ -3726,10 +3675,10 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3740,7 +3689,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ return reinterpret_cast( &_FieldOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 15; void UnsafeArenaSwap(FieldOptions* other); @@ -3751,32 +3700,33 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ // implements Message ---------------------------------------------- - inline FieldOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline FieldOptions* New() const final { + return CreateMaybeMessage(NULL); } - FieldOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + FieldOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FieldOptions& from); void MergeFrom(const FieldOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FieldOptions* other); protected: explicit FieldOptions(::google::protobuf::Arena* arena); @@ -3792,7 +3742,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -3931,7 +3881,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; int ctype_; bool packed_; @@ -3940,7 +3890,6 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@ bool weak_; int jstype_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsFieldOptionsImpl(); }; // ------------------------------------------------------------------- @@ -3977,10 +3926,10 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -3991,7 +3940,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ return reinterpret_cast( &_OneofOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 16; void UnsafeArenaSwap(OneofOptions* other); @@ -4002,32 +3951,33 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ // implements Message ---------------------------------------------- - inline OneofOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline OneofOptions* New() const final { + return CreateMaybeMessage(NULL); } - OneofOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + OneofOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const OneofOptions& from); void MergeFrom(const OneofOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(OneofOptions* other); protected: explicit OneofOptions(::google::protobuf::Arena* arena); @@ -4043,7 +3993,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4072,10 +4022,9 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@ typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsOneofOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4112,10 +4061,10 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4126,7 +4075,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p return reinterpret_cast( &_EnumOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 17; void UnsafeArenaSwap(EnumOptions* other); @@ -4137,32 +4086,33 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p // implements Message ---------------------------------------------- - inline EnumOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline EnumOptions* New() const final { + return CreateMaybeMessage(NULL); } - EnumOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + EnumOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumOptions& from); void MergeFrom(const EnumOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumOptions* other); protected: explicit EnumOptions(::google::protobuf::Arena* arena); @@ -4178,7 +4128,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4225,12 +4175,11 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool allow_alias_; bool deprecated_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4267,10 +4216,10 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4281,7 +4230,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / return reinterpret_cast( &_EnumValueOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 18; void UnsafeArenaSwap(EnumValueOptions* other); @@ -4292,32 +4241,33 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / // implements Message ---------------------------------------------- - inline EnumValueOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline EnumValueOptions* New() const final { + return CreateMaybeMessage(NULL); } - EnumValueOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + EnumValueOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumValueOptions& from); void MergeFrom(const EnumValueOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumValueOptions* other); protected: explicit EnumValueOptions(::google::protobuf::Arena* arena); @@ -4333,7 +4283,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4371,11 +4321,10 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message / typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool deprecated_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsEnumValueOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4412,10 +4361,10 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4426,7 +4375,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* return reinterpret_cast( &_ServiceOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 19; void UnsafeArenaSwap(ServiceOptions* other); @@ -4437,32 +4386,33 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline ServiceOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline ServiceOptions* New() const final { + return CreateMaybeMessage(NULL); } - ServiceOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + ServiceOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ServiceOptions& from); void MergeFrom(const ServiceOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ServiceOptions* other); protected: explicit ServiceOptions(::google::protobuf::Arena* arena); @@ -4478,7 +4428,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4516,11 +4466,10 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool deprecated_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsServiceOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4557,10 +4506,10 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4571,7 +4520,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ return reinterpret_cast( &_MethodOptions_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 20; void UnsafeArenaSwap(MethodOptions* other); @@ -4582,32 +4531,33 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ // implements Message ---------------------------------------------- - inline MethodOptions* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline MethodOptions* New() const final { + return CreateMaybeMessage(NULL); } - MethodOptions* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + MethodOptions* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const MethodOptions& from); void MergeFrom(const MethodOptions& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(MethodOptions* other); protected: explicit MethodOptions(::google::protobuf::Arena* arena); @@ -4623,7 +4573,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4698,12 +4648,11 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @ typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; bool deprecated_; int idempotency_level_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsMethodOptionsImpl(); }; // ------------------------------------------------------------------- @@ -4740,10 +4689,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4754,7 +4703,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu return reinterpret_cast( &_UninterpretedOption_NamePart_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 21; void UnsafeArenaSwap(UninterpretedOption_NamePart* other); @@ -4765,32 +4714,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu // implements Message ---------------------------------------------- - inline UninterpretedOption_NamePart* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline UninterpretedOption_NamePart* New() const final { + return CreateMaybeMessage(NULL); } - UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + UninterpretedOption_NamePart* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const UninterpretedOption_NamePart& from); void MergeFrom(const UninterpretedOption_NamePart& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption_NamePart* other); protected: explicit UninterpretedOption_NamePart(::google::protobuf::Arena* arena); @@ -4806,7 +4756,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -4858,11 +4808,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr name_part_; bool is_extension_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOption_NamePartImpl(); }; // ------------------------------------------------------------------- @@ -4899,10 +4848,10 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -4913,7 +4862,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag return reinterpret_cast( &_UninterpretedOption_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 22; void UnsafeArenaSwap(UninterpretedOption* other); @@ -4924,32 +4873,33 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag // implements Message ---------------------------------------------- - inline UninterpretedOption* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline UninterpretedOption* New() const final { + return CreateMaybeMessage(NULL); } - UninterpretedOption* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + UninterpretedOption* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const UninterpretedOption& from); void MergeFrom(const UninterpretedOption& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption* other); protected: explicit UninterpretedOption(::google::protobuf::Arena* arena); @@ -4965,7 +4915,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5098,7 +5048,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart > name_; ::google::protobuf::internal::ArenaStringPtr identifier_value_; ::google::protobuf::internal::ArenaStringPtr string_value_; @@ -5107,7 +5057,6 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag ::google::protobuf::int64 negative_int_value_; double double_value_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsUninterpretedOptionImpl(); }; // ------------------------------------------------------------------- @@ -5144,10 +5093,10 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5158,7 +5107,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me return reinterpret_cast( &_SourceCodeInfo_Location_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 23; void UnsafeArenaSwap(SourceCodeInfo_Location* other); @@ -5169,32 +5118,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me // implements Message ---------------------------------------------- - inline SourceCodeInfo_Location* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline SourceCodeInfo_Location* New() const final { + return CreateMaybeMessage(NULL); } - SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + SourceCodeInfo_Location* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const SourceCodeInfo_Location& from); void MergeFrom(const SourceCodeInfo_Location& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo_Location* other); protected: explicit SourceCodeInfo_Location(::google::protobuf::Arena* arena); @@ -5210,7 +5160,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5322,7 +5272,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_; mutable int _path_cached_byte_size_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > span_; @@ -5331,7 +5281,6 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me ::google::protobuf::internal::ArenaStringPtr leading_comments_; ::google::protobuf::internal::ArenaStringPtr trailing_comments_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfo_LocationImpl(); }; // ------------------------------------------------------------------- @@ -5368,10 +5317,10 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5382,7 +5331,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* return reinterpret_cast( &_SourceCodeInfo_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 24; void UnsafeArenaSwap(SourceCodeInfo* other); @@ -5393,32 +5342,33 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* // implements Message ---------------------------------------------- - inline SourceCodeInfo* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline SourceCodeInfo* New() const final { + return CreateMaybeMessage(NULL); } - SourceCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + SourceCodeInfo* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const SourceCodeInfo& from); void MergeFrom(const SourceCodeInfo& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo* other); protected: explicit SourceCodeInfo(::google::protobuf::Arena* arena); @@ -5434,7 +5384,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5462,10 +5412,9 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location > location_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsSourceCodeInfoImpl(); }; // ------------------------------------------------------------------- @@ -5502,10 +5451,10 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5516,7 +5465,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu return reinterpret_cast( &_GeneratedCodeInfo_Annotation_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 25; void UnsafeArenaSwap(GeneratedCodeInfo_Annotation* other); @@ -5527,32 +5476,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu // implements Message ---------------------------------------------- - inline GeneratedCodeInfo_Annotation* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline GeneratedCodeInfo_Annotation* New() const final { + return CreateMaybeMessage(NULL); } - GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + GeneratedCodeInfo_Annotation* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const GeneratedCodeInfo_Annotation& from); void MergeFrom(const GeneratedCodeInfo_Annotation& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo_Annotation* other); protected: explicit GeneratedCodeInfo_Annotation(::google::protobuf::Arena* arena); @@ -5568,7 +5518,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5638,14 +5588,13 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_; mutable int _path_cached_byte_size_; ::google::protobuf::internal::ArenaStringPtr source_file_; ::google::protobuf::int32 begin_; ::google::protobuf::int32 end_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfo_AnnotationImpl(); }; // ------------------------------------------------------------------- @@ -5682,10 +5631,10 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message return _internal_metadata_.mutable_unknown_fields(); } - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -5696,7 +5645,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message return reinterpret_cast( &_GeneratedCodeInfo_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 26; void UnsafeArenaSwap(GeneratedCodeInfo* other); @@ -5707,32 +5656,33 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message // implements Message ---------------------------------------------- - inline GeneratedCodeInfo* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline GeneratedCodeInfo* New() const final { + return CreateMaybeMessage(NULL); } - GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + GeneratedCodeInfo* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const GeneratedCodeInfo& from); void MergeFrom(const GeneratedCodeInfo& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo* other); protected: explicit GeneratedCodeInfo(::google::protobuf::Arena* arena); @@ -5748,7 +5698,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -5776,10 +5726,9 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation > annotation_; friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::InitDefaultsGeneratedCodeInfoImpl(); }; // =================================================================== @@ -5878,8 +5827,11 @@ inline ::std::string* FileDescriptorProto::mutable_name() { } inline ::std::string* FileDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -5963,8 +5915,11 @@ inline ::std::string* FileDescriptorProto::mutable_package() { } inline ::std::string* FileDescriptorProto::release_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package) + if (!has_package()) { + return NULL; + } clear_has_package(); - return package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::set_allocated_package(::std::string* package) { if (package != NULL) { @@ -6259,6 +6214,9 @@ inline void FileDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::FileOptions& FileDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const { const ::google::protobuf::FileOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options) @@ -6270,7 +6228,7 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::release_options() { clear_has_options(); ::google::protobuf::FileOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -6285,8 +6243,8 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::unsafe_arena_releas inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FileOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::FileOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.options) return options_; @@ -6325,6 +6283,9 @@ inline void FileDescriptorProto::clear_source_code_info() { if (source_code_info_ != NULL) source_code_info_->Clear(); clear_has_source_code_info(); } +inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::_internal_source_code_info() const { + return *source_code_info_; +} inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const { const ::google::protobuf::SourceCodeInfo* p = source_code_info_; // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info) @@ -6336,7 +6297,7 @@ inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::release_source_c clear_has_source_code_info(); ::google::protobuf::SourceCodeInfo* temp = source_code_info_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } source_code_info_ = NULL; return temp; @@ -6351,8 +6312,8 @@ inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::unsafe_arena_rel inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() { set_has_source_code_info(); if (source_code_info_ == NULL) { - source_code_info_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::SourceCodeInfo >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(GetArenaNoVirtual()); + source_code_info_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.source_code_info) return source_code_info_; @@ -6429,8 +6390,11 @@ inline ::std::string* FileDescriptorProto::mutable_syntax() { } inline ::std::string* FileDescriptorProto::release_syntax() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax) + if (!has_syntax()) { + return NULL; + } clear_has_syntax(); - return syntax_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return syntax_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) { if (syntax != NULL) { @@ -6528,6 +6492,9 @@ inline void DescriptorProto_ExtensionRange::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::_internal_options() const { + return *options_; +} inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::options() const { const ::google::protobuf::ExtensionRangeOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.options) @@ -6539,7 +6506,7 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange clear_has_options(); ::google::protobuf::ExtensionRangeOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -6554,8 +6521,8 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ExtensionRangeOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.ExtensionRange.options) return options_; @@ -6688,8 +6655,11 @@ inline ::std::string* DescriptorProto::mutable_name() { } inline ::std::string* DescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void DescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -6915,6 +6885,9 @@ inline void DescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::MessageOptions& DescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const { const ::google::protobuf::MessageOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options) @@ -6926,7 +6899,7 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::release_options() { clear_has_options(); ::google::protobuf::MessageOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -6941,8 +6914,8 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::unsafe_arena_release inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MessageOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::MessageOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.options) return options_; @@ -7156,8 +7129,11 @@ inline ::std::string* FieldDescriptorProto::mutable_name() { } inline ::std::string* FieldDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -7315,8 +7291,11 @@ inline ::std::string* FieldDescriptorProto::mutable_type_name() { } inline ::std::string* FieldDescriptorProto::release_type_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name) + if (!has_type_name()) { + return NULL; + } clear_has_type_name(); - return type_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return type_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) { if (type_name != NULL) { @@ -7400,8 +7379,11 @@ inline ::std::string* FieldDescriptorProto::mutable_extendee() { } inline ::std::string* FieldDescriptorProto::release_extendee() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee) + if (!has_extendee()) { + return NULL; + } clear_has_extendee(); - return extendee_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return extendee_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) { if (extendee != NULL) { @@ -7485,8 +7467,11 @@ inline ::std::string* FieldDescriptorProto::mutable_default_value() { } inline ::std::string* FieldDescriptorProto::release_default_value() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value) + if (!has_default_value()) { + return NULL; + } clear_has_default_value(); - return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return default_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) { if (default_value != NULL) { @@ -7594,8 +7579,11 @@ inline ::std::string* FieldDescriptorProto::mutable_json_name() { } inline ::std::string* FieldDescriptorProto::release_json_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name) + if (!has_json_name()) { + return NULL; + } clear_has_json_name(); - return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return json_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) { if (json_name != NULL) { @@ -7641,6 +7629,9 @@ inline void FieldDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const { const ::google::protobuf::FieldOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options) @@ -7652,7 +7643,7 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::release_options() clear_has_options(); ::google::protobuf::FieldOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -7667,8 +7658,8 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::unsafe_arena_rele inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::FieldOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::FieldOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.options) return options_; @@ -7749,8 +7740,11 @@ inline ::std::string* OneofDescriptorProto::mutable_name() { } inline ::std::string* OneofDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void OneofDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -7796,6 +7790,9 @@ inline void OneofDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const { const ::google::protobuf::OneofOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options) @@ -7807,7 +7804,7 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::release_options() clear_has_options(); ::google::protobuf::OneofOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -7822,8 +7819,8 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::unsafe_arena_rele inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::OneofOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::OneofOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.options) return options_; @@ -7956,8 +7953,11 @@ inline ::std::string* EnumDescriptorProto::mutable_name() { } inline ::std::string* EnumDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void EnumDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8033,6 +8033,9 @@ inline void EnumDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const { const ::google::protobuf::EnumOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options) @@ -8044,7 +8047,7 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() { clear_has_options(); ::google::protobuf::EnumOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8059,8 +8062,8 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::unsafe_arena_releas inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::EnumOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.options) return options_; @@ -8240,8 +8243,11 @@ inline ::std::string* EnumValueDescriptorProto::mutable_name() { } inline ::std::string* EnumValueDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void EnumValueDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8311,6 +8317,9 @@ inline void EnumValueDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const { const ::google::protobuf::EnumValueOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options) @@ -8322,7 +8331,7 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_o clear_has_options(); ::google::protobuf::EnumValueOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8337,8 +8346,8 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::unsafe_ar inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::EnumValueOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::EnumValueOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.options) return options_; @@ -8419,8 +8428,11 @@ inline ::std::string* ServiceDescriptorProto::mutable_name() { } inline ::std::string* ServiceDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void ServiceDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8496,6 +8508,9 @@ inline void ServiceDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const { const ::google::protobuf::ServiceOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options) @@ -8507,7 +8522,7 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_optio clear_has_options(); ::google::protobuf::ServiceOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8522,8 +8537,8 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::unsafe_arena_ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ServiceOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::ServiceOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.options) return options_; @@ -8604,8 +8619,11 @@ inline ::std::string* MethodDescriptorProto::mutable_name() { } inline ::std::string* MethodDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name) + if (!has_name()) { + return NULL; + } clear_has_name(); - return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::set_allocated_name(::std::string* name) { if (name != NULL) { @@ -8689,8 +8707,11 @@ inline ::std::string* MethodDescriptorProto::mutable_input_type() { } inline ::std::string* MethodDescriptorProto::release_input_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type) + if (!has_input_type()) { + return NULL; + } clear_has_input_type(); - return input_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return input_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) { if (input_type != NULL) { @@ -8774,8 +8795,11 @@ inline ::std::string* MethodDescriptorProto::mutable_output_type() { } inline ::std::string* MethodDescriptorProto::release_output_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type) + if (!has_output_type()) { + return NULL; + } clear_has_output_type(); - return output_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return output_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) { if (output_type != NULL) { @@ -8821,6 +8845,9 @@ inline void MethodDescriptorProto::clear_options() { if (options_ != NULL) options_->Clear(); clear_has_options(); } +inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::_internal_options() const { + return *options_; +} inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const { const ::google::protobuf::MethodOptions* p = options_; // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options) @@ -8832,7 +8859,7 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::release_options clear_has_options(); ::google::protobuf::MethodOptions* temp = options_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } options_ = NULL; return temp; @@ -8847,8 +8874,8 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::unsafe_arena_re inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() { set_has_options(); if (options_ == NULL) { - options_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::MethodOptions >( - GetArenaNoVirtual()); + auto* p = CreateMaybeMessage<::google::protobuf::MethodOptions>(GetArenaNoVirtual()); + options_ = p; } // @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.options) return options_; @@ -8977,8 +9004,11 @@ inline ::std::string* FileOptions::mutable_java_package() { } inline ::std::string* FileOptions::release_java_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package) + if (!has_java_package()) { + return NULL; + } clear_has_java_package(); - return java_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return java_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_java_package(::std::string* java_package) { if (java_package != NULL) { @@ -9062,8 +9092,11 @@ inline ::std::string* FileOptions::mutable_java_outer_classname() { } inline ::std::string* FileOptions::release_java_outer_classname() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname) + if (!has_java_outer_classname()) { + return NULL; + } clear_has_java_outer_classname(); - return java_outer_classname_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return java_outer_classname_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) { if (java_outer_classname != NULL) { @@ -9244,8 +9277,11 @@ inline ::std::string* FileOptions::mutable_go_package() { } inline ::std::string* FileOptions::release_go_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package) + if (!has_go_package()) { + return NULL; + } clear_has_go_package(); - return go_package_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return go_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_go_package(::std::string* go_package) { if (go_package != NULL) { @@ -9473,8 +9509,11 @@ inline ::std::string* FileOptions::mutable_objc_class_prefix() { } inline ::std::string* FileOptions::release_objc_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix) + if (!has_objc_class_prefix()) { + return NULL; + } clear_has_objc_class_prefix(); - return objc_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return objc_class_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) { if (objc_class_prefix != NULL) { @@ -9558,8 +9597,11 @@ inline ::std::string* FileOptions::mutable_csharp_namespace() { } inline ::std::string* FileOptions::release_csharp_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace) + if (!has_csharp_namespace()) { + return NULL; + } clear_has_csharp_namespace(); - return csharp_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return csharp_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) { if (csharp_namespace != NULL) { @@ -9643,8 +9685,11 @@ inline ::std::string* FileOptions::mutable_swift_prefix() { } inline ::std::string* FileOptions::release_swift_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix) + if (!has_swift_prefix()) { + return NULL; + } clear_has_swift_prefix(); - return swift_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return swift_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix) { if (swift_prefix != NULL) { @@ -9728,8 +9773,11 @@ inline ::std::string* FileOptions::mutable_php_class_prefix() { } inline ::std::string* FileOptions::release_php_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_class_prefix) + if (!has_php_class_prefix()) { + return NULL; + } clear_has_php_class_prefix(); - return php_class_prefix_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return php_class_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_php_class_prefix(::std::string* php_class_prefix) { if (php_class_prefix != NULL) { @@ -9813,8 +9861,11 @@ inline ::std::string* FileOptions::mutable_php_namespace() { } inline ::std::string* FileOptions::release_php_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_namespace) + if (!has_php_namespace()) { + return NULL; + } clear_has_php_namespace(); - return php_namespace_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return php_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void FileOptions::set_allocated_php_namespace(::std::string* php_namespace) { if (php_namespace != NULL) { @@ -10557,8 +10608,11 @@ inline ::std::string* UninterpretedOption_NamePart::mutable_name_part() { } inline ::std::string* UninterpretedOption_NamePart::release_name_part() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part) + if (!has_name_part()) { + return NULL; + } clear_has_name_part(); - return name_part_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return name_part_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) { if (name_part != NULL) { @@ -10700,8 +10754,11 @@ inline ::std::string* UninterpretedOption::mutable_identifier_value() { } inline ::std::string* UninterpretedOption::release_identifier_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value) + if (!has_identifier_value()) { + return NULL; + } clear_has_identifier_value(); - return identifier_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return identifier_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) { if (identifier_value != NULL) { @@ -10857,8 +10914,11 @@ inline ::std::string* UninterpretedOption::mutable_string_value() { } inline ::std::string* UninterpretedOption::release_string_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value) + if (!has_string_value()) { + return NULL; + } clear_has_string_value(); - return string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return string_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::set_allocated_string_value(::std::string* string_value) { if (string_value != NULL) { @@ -10942,8 +11002,11 @@ inline ::std::string* UninterpretedOption::mutable_aggregate_value() { } inline ::std::string* UninterpretedOption::release_aggregate_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value) + if (!has_aggregate_value()) { + return NULL; + } clear_has_aggregate_value(); - return aggregate_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return aggregate_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) { if (aggregate_value != NULL) { @@ -11091,8 +11154,11 @@ inline ::std::string* SourceCodeInfo_Location::mutable_leading_comments() { } inline ::std::string* SourceCodeInfo_Location::release_leading_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments) + if (!has_leading_comments()) { + return NULL; + } clear_has_leading_comments(); - return leading_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return leading_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) { if (leading_comments != NULL) { @@ -11176,8 +11242,11 @@ inline ::std::string* SourceCodeInfo_Location::mutable_trailing_comments() { } inline ::std::string* SourceCodeInfo_Location::release_trailing_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments) + if (!has_trailing_comments()) { + return NULL; + } clear_has_trailing_comments(); - return trailing_comments_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return trailing_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) { if (trailing_comments != NULL) { @@ -11398,8 +11467,11 @@ inline ::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() { } inline ::std::string* GeneratedCodeInfo_Annotation::release_source_file() { // @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file) + if (!has_source_file()) { + return NULL; + } clear_has_source_file(); - return source_file_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); + return source_file_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) { if (source_file != NULL) { @@ -11577,32 +11649,32 @@ GeneratedCodeInfo::annotation() const { namespace google { namespace protobuf { -template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Type> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Type> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Type>() { return ::google::protobuf::FieldDescriptorProto_Type_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Label> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldDescriptorProto_Label> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Label>() { return ::google::protobuf::FieldDescriptorProto_Label_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FileOptions_OptimizeMode> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FileOptions_OptimizeMode> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FileOptions_OptimizeMode>() { return ::google::protobuf::FileOptions_OptimizeMode_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldOptions_CType> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldOptions_CType> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_CType>() { return ::google::protobuf::FieldOptions_CType_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::FieldOptions_JSType> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::FieldOptions_JSType> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_JSType>() { return ::google::protobuf::FieldOptions_JSType_descriptor(); } -template <> struct is_proto_enum< ::google::protobuf::MethodOptions_IdempotencyLevel> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::MethodOptions_IdempotencyLevel> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOptions_IdempotencyLevel>() { return ::google::protobuf::MethodOptions_IdempotencyLevel_descriptor(); @@ -11613,4 +11685,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOption // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h index 28f8af7a2d..d61f2a6a42 100644 --- a/src/google/protobuf/descriptor_database.h +++ b/src/google/protobuf/descriptor_database.h @@ -214,7 +214,7 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { // will find it. Proof: // 1) Define the "search key" to be the key we are looking for, the "found // key" to be the key found in step (1), and the "match key" to be the - // key which actually matches the serach key (i.e. the key we're trying + // key which actually matches the search key (i.e. the key we're trying // to find). // 2) The found key must be less than or equal to the search key by // definition. diff --git a/src/google/protobuf/descriptor_database_unittest.cc b/src/google/protobuf/descriptor_database_unittest.cc index 9d71088601..083ef8f294 100644 --- a/src/google/protobuf/descriptor_database_unittest.cc +++ b/src/google/protobuf/descriptor_database_unittest.cc @@ -36,13 +36,10 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif -#include -#include #include +#include +#include #include #include @@ -179,7 +176,7 @@ class DescriptorDatabaseTest EXPECT_FALSE(test_case_->AddToDatabase(file_proto)); } - google::protobuf::scoped_ptr test_case_; + std::unique_ptr test_case_; DescriptorDatabase* database_; }; diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index b0337035dc..5f8d445c83 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -36,9 +36,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -2252,7 +2249,7 @@ class MiscTest : public testing::Test { return field != NULL ? field->enum_type() : NULL; } - google::protobuf::scoped_ptr pool_; + std::unique_ptr pool_; }; TEST_F(MiscTest, TypeNames) { @@ -2682,7 +2679,7 @@ class AllowUnknownDependenciesTest const FieldDescriptor* qux_field_; SimpleDescriptorDatabase db_; // used if in FALLBACK_DATABASE mode. - google::protobuf::scoped_ptr pool_; + std::unique_ptr pool_; }; TEST_P(AllowUnknownDependenciesTest, PlaceholderFile) { @@ -3952,8 +3949,22 @@ TEST_F(ValidationErrorTest, EnumReservedRangeOverlap) { " reserved_range { start: 5 end: 15 }" "}", - "foo.proto: Foo: NUMBER: Reserved range 5 to 14" - " overlaps with already-defined range 10 to 19.\n"); + "foo.proto: Foo: NUMBER: Reserved range 5 to 15" + " overlaps with already-defined range 10 to 20.\n"); +} + +TEST_F(ValidationErrorTest, EnumReservedRangeOverlapByOne) { + BuildFileWithErrors( + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:0 }" + " reserved_range { start: 10 end: 20 }" + " reserved_range { start: 5 end: 10 }" + "}", + + "foo.proto: Foo: NUMBER: Reserved range 5 to 10" + " overlaps with already-defined range 10 to 20.\n"); } TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) { @@ -3966,8 +3977,8 @@ TEST_F(ValidationErrorTest, EnumNegativeReservedRangeOverlap) { " reserved_range { start: -15 end: -5 }" "}", - "foo.proto: Foo: NUMBER: Reserved range -15 to -6" - " overlaps with already-defined range -20 to -11.\n"); + "foo.proto: Foo: NUMBER: Reserved range -15 to -5" + " overlaps with already-defined range -20 to -10.\n"); } TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) { @@ -3980,8 +3991,22 @@ TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap) { " reserved_range { start: -15 end: 5 }" "}", - "foo.proto: Foo: NUMBER: Reserved range -15 to 4" - " overlaps with already-defined range -20 to 9.\n"); + "foo.proto: Foo: NUMBER: Reserved range -15 to 5" + " overlaps with already-defined range -20 to 10.\n"); +} + +TEST_F(ValidationErrorTest, EnumMixedReservedRangeOverlap2) { + BuildFileWithErrors( + "name: \"foo.proto\" " + "enum_type {" + " name: \"Foo\"" + " value { name:\"BAR\" number:20 }" + " reserved_range { start: -20 end: 10 }" + " reserved_range { start: 10 end: 10 }" + "}", + + "foo.proto: Foo: NUMBER: Reserved range 10 to 10" + " overlaps with already-defined range -20 to 10.\n"); } TEST_F(ValidationErrorTest, EnumReservedRangeStartGreaterThanEnd) { diff --git a/src/google/protobuf/drop_unknown_fields_test.cc b/src/google/protobuf/drop_unknown_fields_test.cc index f2f2f749e0..437a04e773 100644 --- a/src/google/protobuf/drop_unknown_fields_test.cc +++ b/src/google/protobuf/drop_unknown_fields_test.cc @@ -29,9 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -94,7 +91,7 @@ TEST(DropUnknownFieldsTest, DynamicMessageDefaultDrop) { foo_with_extra_fields.set_extra_int32_value(2); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr foo( + std::unique_ptr foo( factory.GetPrototype(Foo::descriptor())->New()); ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_TRUE(foo->GetReflection()->GetUnknownFields(*foo).empty()); @@ -114,7 +111,7 @@ TEST(DropUnknownFieldsTest, DynamicMessageDefaultPreserve) { foo_with_extra_fields.set_extra_int32_value(2); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr foo( + std::unique_ptr foo( factory.GetPrototype(Foo::descriptor())->New()); ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_FALSE(foo->GetReflection()->GetUnknownFields(*foo).empty()); diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc index b4d5eb5fcc..ddc063db12 100644 --- a/src/google/protobuf/duration.pb.cc +++ b/src/google/protobuf/duration.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class DurationDefaultTypeInternal { @@ -29,14 +29,9 @@ class DurationDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fduration_2eproto { -void InitDefaultsDurationImpl() { +static void InitDefaultsDuration() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Duration_default_instance_; new (ptr) ::google::protobuf::Duration(); @@ -45,9 +40,11 @@ void InitDefaultsDurationImpl() { ::google::protobuf::Duration::InitAsDefaultInstance(); } -void InitDefaultsDuration() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsDurationImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDuration}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Duration.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -71,15 +68,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -129,24 +125,22 @@ const int Duration::kNanosFieldNumber; Duration::Duration() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Duration) } Duration::Duration(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Duration) } Duration::Duration(const Duration& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&seconds_, &from.seconds_, static_cast(reinterpret_cast(&nanos_) - @@ -158,7 +152,6 @@ void Duration::SharedCtor() { ::memset(&seconds_, 0, static_cast( reinterpret_cast(&nanos_) - reinterpret_cast(&seconds_)) + sizeof(nanos_)); - _cached_size_ = 0; } Duration::~Duration() { @@ -177,9 +170,7 @@ void Duration::ArenaDtor(void* object) { void Duration::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Duration::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Duration::descriptor() { ::protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce(); @@ -187,7 +178,7 @@ const ::google::protobuf::Descriptor* Duration::descriptor() { } const Duration& Duration::default_instance() { - ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDuration(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base); return *internal_default_instance(); } @@ -210,7 +201,7 @@ bool Duration::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Duration) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -334,9 +325,7 @@ size_t Duration::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -412,7 +401,6 @@ void Duration::InternalSwap(Duration* other) { swap(seconds_, other->seconds_); swap(nanos_, other->nanos_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Duration::GetMetadata() const { @@ -426,7 +414,7 @@ void Duration::InternalSwap(Duration* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMessage< ::google::protobuf::Duration >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Duration >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h index 7fe0748d1a..3d0889d1b6 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto -#ifndef PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto #include @@ -24,12 +24,14 @@ #include #include #include +#include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fduration_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fduration_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsDurationImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsDuration(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsDuration(); -} } // namespace protobuf_google_2fprotobuf_2fduration_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMessage< ::google::protobuf::Duration>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot return reinterpret_cast( &_Duration_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Duration* other); @@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot // implements Message ---------------------------------------------- - inline Duration* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Duration* New() const final { + return CreateMaybeMessage(NULL); } - Duration* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Duration* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Duration& from); void MergeFrom(const Duration& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Duration* other); protected: explicit Duration(::google::protobuf::Arena* arena); @@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -184,9 +182,8 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot typedef void DestructorSkippable_; ::google::protobuf::int64 seconds_; ::google::protobuf::int32 nanos_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fduration_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fduration_2eproto::InitDefaultsDurationImpl(); }; // =================================================================== @@ -238,4 +235,4 @@ inline void Duration::set_nanos(::google::protobuf::int32 value) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fduration_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc index 48d6aad81c..44bdd85ddb 100644 --- a/src/google/protobuf/dynamic_message.cc +++ b/src/google/protobuf/dynamic_message.cc @@ -65,9 +65,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include @@ -232,9 +229,9 @@ class DynamicMessage : public Message { // Warning: The order in which the following pointers are defined is // important (the prototype must be deleted *before* the offsets). - google::protobuf::scoped_array offsets; - google::protobuf::scoped_array has_bits_indices; - google::protobuf::scoped_ptr reflection; + std::unique_ptr offsets; + std::unique_ptr has_bits_indices; + std::unique_ptr reflection; // Don't use a scoped_ptr to hold the prototype: the destructor for // DynamicMessage needs to know whether it is the prototype, and does so by // looking back at this field. This would assume details about the diff --git a/src/google/protobuf/dynamic_message.h b/src/google/protobuf/dynamic_message.h index e29b148d6a..d84cc8af47 100644 --- a/src/google/protobuf/dynamic_message.h +++ b/src/google/protobuf/dynamic_message.h @@ -40,9 +40,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -130,7 +127,7 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { // public header (for good reason), but dynamic_message.h is, and public // headers may only #include other public headers. struct PrototypeMap; - google::protobuf::scoped_ptr prototypes_; + std::unique_ptr prototypes_; mutable Mutex prototypes_mutex_; friend class DynamicMessage; diff --git a/src/google/protobuf/dynamic_message_unittest.cc b/src/google/protobuf/dynamic_message_unittest.cc index 34f3641be0..94446b08f7 100644 --- a/src/google/protobuf/dynamic_message_unittest.cc +++ b/src/google/protobuf/dynamic_message_unittest.cc @@ -41,16 +41,13 @@ // DynamicMessage. #include -#ifndef _SHARED_PTR_H -#include -#endif -#include -#include -#include #include #include #include +#include +#include +#include #include #include diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc index ffff80b923..9b53c54672 100644 --- a/src/google/protobuf/empty.pb.cc +++ b/src/google/protobuf/empty.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class EmptyDefaultTypeInternal { @@ -29,14 +29,9 @@ class EmptyDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fempty_2eproto { -void InitDefaultsEmptyImpl() { +static void InitDefaultsEmpty() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Empty_default_instance_; new (ptr) ::google::protobuf::Empty(); @@ -45,9 +40,11 @@ void InitDefaultsEmptyImpl() { ::google::protobuf::Empty::InitAsDefaultInstance(); } -void InitDefaultsEmpty() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEmptyImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEmpty}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Empty.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -69,15 +66,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -102,8 +98,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -124,30 +120,27 @@ void Empty::InitAsDefaultInstance() { Empty::Empty() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Empty) } Empty::Empty(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Empty) } Empty::Empty(const Empty& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.Empty) } void Empty::SharedCtor() { - _cached_size_ = 0; } Empty::~Empty() { @@ -166,9 +159,7 @@ void Empty::ArenaDtor(void* object) { void Empty::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Empty::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Empty::descriptor() { ::protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce(); @@ -176,7 +167,7 @@ const ::google::protobuf::Descriptor* Empty::descriptor() { } const Empty& Empty::default_instance() { - ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmpty(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base); return *internal_default_instance(); } @@ -196,7 +187,7 @@ bool Empty::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Empty) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; handle_unusual: @@ -253,9 +244,7 @@ size_t Empty::ByteSizeLong() const { (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -323,7 +312,6 @@ void Empty::UnsafeArenaSwap(Empty* other) { void Empty::InternalSwap(Empty* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Empty::GetMetadata() const { @@ -337,7 +325,7 @@ void Empty::InternalSwap(Empty* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMessage< ::google::protobuf::Empty >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Empty >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index 2fef9a4310..53857e5fe9 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto -#ifndef PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto #include @@ -24,12 +24,14 @@ #include #include #include +#include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fempty_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fempty_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsEmptyImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEmpty(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsEmpty(); -} } // namespace protobuf_google_2fprotobuf_2fempty_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMessage< ::google::protobuf::Empty>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast( &_Empty_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Empty* other); @@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Empty* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Empty* New() const final { + return CreateMaybeMessage(NULL); } - Empty* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Empty* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Empty& from); void MergeFrom(const Empty& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Empty* other); protected: explicit Empty(::google::protobuf::Arena* arena); @@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -170,9 +168,8 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ template friend class ::google::protobuf::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fempty_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fempty_2eproto::InitDefaultsEmptyImpl(); }; // =================================================================== @@ -196,4 +193,4 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_ // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fempty_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc index 8f1048005f..b587b38f16 100644 --- a/src/google/protobuf/extension_set.cc +++ b/src/google/protobuf/extension_set.cc @@ -33,6 +33,7 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include +#include #include #include #include @@ -179,20 +180,29 @@ void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type, // Constructors and basic methods. ExtensionSet::ExtensionSet(::google::protobuf::Arena* arena) - : arena_(arena) { - if (arena_ != NULL) { - arena_->OwnDestructor(&extensions_); - } -} - -ExtensionSet::ExtensionSet() : arena_(NULL) {} + : arena_(arena), + flat_capacity_(0), + flat_size_(0), + map_{flat_capacity_ == 0 ? NULL + : ::google::protobuf::Arena::CreateArray( + arena_, flat_capacity_)} {} + +ExtensionSet::ExtensionSet() + : arena_(NULL), + flat_capacity_(0), + flat_size_(0), + map_{flat_capacity_ == 0 ? NULL + : ::google::protobuf::Arena::CreateArray( + arena_, flat_capacity_)} {} ExtensionSet::~ExtensionSet() { // Deletes all allocated extensions. if (arena_ == NULL) { - for (ExtensionMap::iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.Free(); + ForEach([](int /* number */, Extension& ext) { ext.Free(); }); + if (GOOGLE_PREDICT_FALSE(is_large())) { + delete map_.large; + } else { + delete[] map_.flat; } } } @@ -203,45 +213,43 @@ ExtensionSet::~ExtensionSet() { // vector* output) const bool ExtensionSet::Has(int number) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return false; - GOOGLE_DCHECK(!iter->second.is_repeated); - return !iter->second.is_cleared; + const Extension* ext = FindOrNull(number); + if (ext == NULL) return false; + GOOGLE_DCHECK(!ext->is_repeated); + return !ext->is_cleared; } int ExtensionSet::NumExtensions() const { int result = 0; - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - if (!iter->second.is_cleared) { + ForEach([&result](int /* number */, const Extension& ext) { + if (!ext.is_cleared) { ++result; } - } + }); return result; } int ExtensionSet::ExtensionSize(int number) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return 0; - return iter->second.GetSize(); + const Extension* ext = FindOrNull(number); + return ext == NULL ? 0 : ext->GetSize(); } FieldType ExtensionSet::ExtensionType(int number) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + const Extension* ext = FindOrNull(number); + if (ext == NULL) { GOOGLE_LOG(DFATAL) << "Don't lookup extension types if they aren't present (1). "; return 0; } - if (iter->second.is_cleared) { + if (ext->is_cleared) { GOOGLE_LOG(DFATAL) << "Don't lookup extension types if they aren't present (2). "; } - return iter->second.type; + return ext->type; } void ExtensionSet::ClearExtension(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return; - iter->second.Clear(); + Extension* ext = FindOrNull(number); + if (ext == NULL) return; + ext->Clear(); } // =================================================================== @@ -267,12 +275,12 @@ enum Cardinality { \ LOWERCASE ExtensionSet::Get##CAMELCASE(int number, \ LOWERCASE default_value) const { \ - ExtensionMap::const_iterator iter = extensions_.find(number); \ - if (iter == extensions_.end() || iter->second.is_cleared) { \ + const Extension* extension = FindOrNull(number); \ + if (extension == NULL || extension->is_cleared) { \ return default_value; \ } else { \ - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, UPPERCASE); \ - return iter->second.LOWERCASE##_value; \ + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, UPPERCASE); \ + return extension->LOWERCASE##_value; \ } \ } \ \ @@ -292,18 +300,18 @@ void ExtensionSet::Set##CAMELCASE(int number, FieldType type, \ } \ \ LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) const { \ - ExtensionMap::const_iterator iter = extensions_.find(number); \ - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \ - return iter->second.repeated_##LOWERCASE##_value->Get(index); \ + const Extension* extension = FindOrNull(number); \ + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ + return extension->repeated_##LOWERCASE##_value->Get(index); \ } \ \ void ExtensionSet::SetRepeated##CAMELCASE( \ int number, int index, LOWERCASE value) { \ - ExtensionMap::iterator iter = extensions_.find(number); \ - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \ - iter->second.repeated_##LOWERCASE##_value->Set(index, value); \ + Extension* extension = FindOrNull(number); \ + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; \ + GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ + extension->repeated_##LOWERCASE##_value->Set(index, value); \ } \ \ void ExtensionSet::Add##CAMELCASE(int number, FieldType type, \ @@ -336,13 +344,13 @@ PRIMITIVE_ACCESSORS( BOOL, bool, Bool) const void* ExtensionSet::GetRawRepeatedField(int number, const void* default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + const Extension* extension = FindOrNull(number); + if (extension == NULL) { return default_value; } // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. - return iter->second.repeated_int32_value; + return extension->repeated_int32_value; } void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, @@ -393,7 +401,7 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, break; case WireFormatLite::CPPTYPE_STRING: extension->repeated_string_value = - Arena::CreateMessage >(arena_); + Arena::CreateMessage >(arena_); break; case WireFormatLite::CPPTYPE_MESSAGE: extension->repeated_message_value = @@ -410,11 +418,11 @@ void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, // Compatible version using old call signature. Does not create extensions when // the don't already exist; instead, just GOOGLE_CHECK-fails. void* ExtensionSet::MutableRawRepeatedField(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter == extensions_.end()) << "Extension not found."; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Extension not found."; // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. - return iter->second.repeated_int32_value; + return extension->repeated_int32_value; } @@ -422,13 +430,13 @@ void* ExtensionSet::MutableRawRepeatedField(int number) { // Enums int ExtensionSet::GetEnum(int number, int default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { + const Extension* extension = FindOrNull(number); + if (extension == NULL || extension->is_cleared) { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, ENUM); - return iter->second.enum_value; + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, ENUM); + return extension->enum_value; } } @@ -447,17 +455,17 @@ void ExtensionSet::SetEnum(int number, FieldType type, int value, } int ExtensionSet::GetRepeatedEnum(int number, int index) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); - return iter->second.repeated_enum_value->Get(index); + const Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); + return extension->repeated_enum_value->Get(index); } void ExtensionSet::SetRepeatedEnum(int number, int index, int value) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); - iter->second.repeated_enum_value->Set(index, value); + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); + extension->repeated_enum_value->Set(index, value); } void ExtensionSet::AddEnum(int number, FieldType type, @@ -483,13 +491,13 @@ void ExtensionSet::AddEnum(int number, FieldType type, const string& ExtensionSet::GetString(int number, const string& default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { + const Extension* extension = FindOrNull(number); + if (extension == NULL || extension->is_cleared) { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, STRING); - return *iter->second.string_value; + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, STRING); + return *extension->string_value; } } @@ -509,17 +517,17 @@ string* ExtensionSet::MutableString(int number, FieldType type, } const string& ExtensionSet::GetRepeatedString(int number, int index) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); - return iter->second.repeated_string_value->Get(index); + const Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); + return extension->repeated_string_value->Get(index); } string* ExtensionSet::MutableRepeatedString(int number, int index) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); - return iter->second.repeated_string_value->Mutable(index); + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); + return extension->repeated_string_value->Mutable(index); } string* ExtensionSet::AddString(int number, FieldType type, @@ -543,16 +551,16 @@ string* ExtensionSet::AddString(int number, FieldType type, const MessageLite& ExtensionSet::GetMessage( int number, const MessageLite& default_value) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + const Extension* extension = FindOrNull(number); + if (extension == NULL) { // Not present. Return the default value. return default_value; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); - if (iter->second.is_lazy) { - return iter->second.lazymessage_value->GetMessage(default_value); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + if (extension->is_lazy) { + return extension->lazymessage_value->GetMessage(default_value); } else { - return *iter->second.message_value; + return *extension->message_value; } } } @@ -663,55 +671,53 @@ void ExtensionSet::UnsafeArenaSetAllocatedMessage( extension->is_cleared = false; } - MessageLite* ExtensionSet::ReleaseMessage(int number, const MessageLite& prototype) { - ExtensionMap::iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(number); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = iter->second.lazymessage_value->ReleaseMessage(prototype); + if (extension->is_lazy) { + ret = extension->lazymessage_value->ReleaseMessage(prototype); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { if (arena_ == NULL) { - ret = iter->second.message_value; + ret = extension->message_value; } else { // ReleaseMessage() always returns a heap-allocated message, and we are // on an arena, so we need to make a copy of this message to return. - ret = (iter->second.message_value)->New(); - ret->CheckTypeAndMergeFrom(*iter->second.message_value); + ret = extension->message_value->New(); + ret->CheckTypeAndMergeFrom(*extension->message_value); } } - extensions_.erase(number); + Erase(number); return ret; } } MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( int number, const MessageLite& prototype) { - ExtensionMap::iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(number); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = - iter->second.lazymessage_value->UnsafeArenaReleaseMessage(prototype); + if (extension->is_lazy) { + ret = extension->lazymessage_value->UnsafeArenaReleaseMessage(prototype); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { - ret = iter->second.message_value; + ret = extension->message_value; } - extensions_.erase(number); + Erase(number); return ret; } } @@ -722,17 +728,17 @@ MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( const MessageLite& ExtensionSet::GetRepeatedMessage( int number, int index) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); - return iter->second.repeated_message_value->Get(index); + const Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); + return extension->repeated_message_value->Get(index); } MessageLite* ExtensionSet::MutableRepeatedMessage(int number, int index) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); - return iter->second.repeated_message_value->Mutable(index); + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; + GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); + return extension->repeated_message_value->Mutable(index); } MessageLite* ExtensionSet::AddMessage(int number, FieldType type, @@ -752,7 +758,7 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type, // RepeatedPtrField does not know how to Add() since it cannot // allocate an abstract object, so we have to be tricky. MessageLite* result = - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( extension->repeated_message_value) ->AddFromCleared >(); if (result == NULL) { @@ -770,10 +776,8 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type, #undef GOOGLE_DCHECK_TYPE void ExtensionSet::RemoveLast(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); switch(cpp_type(extension->type)) { @@ -811,20 +815,16 @@ void ExtensionSet::RemoveLast(int number) { } MessageLite* ExtensionSet::ReleaseLast(int number) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); GOOGLE_DCHECK(cpp_type(extension->type) == WireFormatLite::CPPTYPE_MESSAGE); return extension->repeated_message_value->ReleaseLast(); } void ExtensionSet::SwapElements(int number, int index1, int index2) { - ExtensionMap::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; + Extension* extension = FindOrNull(number); + GOOGLE_CHECK(extension != NULL) << "Index out-of-bounds (field is empty)."; GOOGLE_DCHECK(extension->is_repeated); switch(cpp_type(extension->type)) { @@ -864,18 +864,45 @@ void ExtensionSet::SwapElements(int number, int index1, int index2) { // =================================================================== void ExtensionSet::Clear() { - for (ExtensionMap::iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.Clear(); + ForEach([](int /* number */, Extension& ext) { ext.Clear(); }); +} + +namespace { +// Computes the size of a std::set_union without constructing the union. +template +size_t SizeOfUnion(ItX it_xs, ItX end_xs, ItY it_ys, ItY end_ys) { + size_t result = 0; + while (it_xs != end_xs && it_ys != end_ys) { + ++result; + if (it_xs->first < it_ys->first) { + ++it_xs; + } else if (it_xs->first == it_ys->first) { + ++it_xs; + ++it_ys; + } else { + ++it_ys; + } } + result += std::distance(it_xs, end_xs); + result += std::distance(it_ys, end_ys); + return result; } +} // namespace void ExtensionSet::MergeFrom(const ExtensionSet& other) { - for (ExtensionMap::const_iterator iter = other.extensions_.begin(); - iter != other.extensions_.end(); ++iter) { - const Extension& other_extension = iter->second; - InternalExtensionMergeFrom(iter->first, other_extension); + if (GOOGLE_PREDICT_TRUE(!is_large())) { + if (GOOGLE_PREDICT_TRUE(!other.is_large())) { + GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), other.flat_begin(), + other.flat_end())); + } else { + GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), + other.map_.large->begin(), + other.map_.large->end())); + } } + other.ForEach([this](int number, const Extension& ext) { + this->InternalExtensionMergeFrom(number, ext); + }); } void ExtensionSet::InternalExtensionMergeFrom( @@ -929,7 +956,7 @@ void ExtensionSet::InternalExtensionMergeFrom( for (int i = 0; i < other_repeated_message->size(); i++) { const MessageLite& other_message = other_repeated_message->Get(i); MessageLite* target = - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( extension->repeated_message_value) ->AddFromCleared >(); if (target == NULL) { @@ -1020,7 +1047,10 @@ void ExtensionSet::InternalExtensionMergeFrom( void ExtensionSet::Swap(ExtensionSet* x) { if (GetArenaNoVirtual() == x->GetArenaNoVirtual()) { - extensions_.swap(x->extensions_); + using std::swap; + swap(flat_capacity_, x->flat_capacity_); + swap(flat_size_, x->flat_size_); + swap(map_, x->map_); } else { // TODO(cfallin, rohananil): We maybe able to optimize a case where we are // swapping from heap to arena-allocated extension set, by just Own()'ing @@ -1037,19 +1067,17 @@ void ExtensionSet::Swap(ExtensionSet* x) { void ExtensionSet::SwapExtension(ExtensionSet* other, int number) { if (this == other) return; - ExtensionMap::iterator this_iter = extensions_.find(number); - ExtensionMap::iterator other_iter = other->extensions_.find(number); + Extension* this_ext = FindOrNull(number); + Extension* other_ext = other->FindOrNull(number); - if (this_iter == extensions_.end() && - other_iter == other->extensions_.end()) { + if (this_ext == NULL && other_ext == NULL) { return; } - if (this_iter != extensions_.end() && - other_iter != other->extensions_.end()) { + if (this_ext != NULL && other_ext != NULL) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { using std::swap; - swap(this_iter->second, other_iter->second); + swap(*this_ext, *other_ext); } else { // TODO(cfallin, rohananil): We could further optimize these cases, // especially avoid creation of ExtensionSet, and move MergeFrom logic @@ -1057,33 +1085,33 @@ void ExtensionSet::SwapExtension(ExtensionSet* other, // We do it this way to reuse the copy-across-arenas logic already // implemented in ExtensionSet's MergeFrom. ExtensionSet temp; - temp.InternalExtensionMergeFrom(number, other_iter->second); - ExtensionMap::iterator temp_iter = temp.extensions_.find(number); - other_iter->second.Clear(); - other->InternalExtensionMergeFrom(number, this_iter->second); - this_iter->second.Clear(); - InternalExtensionMergeFrom(number, temp_iter->second); + temp.InternalExtensionMergeFrom(number, *other_ext); + Extension* temp_ext = temp.FindOrNull(number); + other_ext->Clear(); + other->InternalExtensionMergeFrom(number, *this_ext); + this_ext->Clear(); + InternalExtensionMergeFrom(number, *temp_ext); } return; } - if (this_iter == extensions_.end()) { + if (this_ext == NULL) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { - extensions_.insert(std::make_pair(number, other_iter->second)); + *Insert(number).first = *other_ext; } else { - InternalExtensionMergeFrom(number, other_iter->second); + InternalExtensionMergeFrom(number, *other_ext); } - other->extensions_.erase(number); + other->Erase(number); return; } - if (other_iter == other->extensions_.end()) { + if (other_ext == NULL) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { - other->extensions_.insert(std::make_pair(number, this_iter->second)); + *other->Insert(number).first = *this_ext; } else { - other->InternalExtensionMergeFrom(number, this_iter->second); + other->InternalExtensionMergeFrom(number, *this_ext); } - extensions_.erase(number); + Erase(number); return; } } @@ -1091,28 +1119,15 @@ void ExtensionSet::SwapExtension(ExtensionSet* other, bool ExtensionSet::IsInitialized() const { // Extensions are never required. However, we need to check that all // embedded messages are initialized. - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - const Extension& extension = iter->second; - if (cpp_type(extension.type) == WireFormatLite::CPPTYPE_MESSAGE) { - if (extension.is_repeated) { - for (int i = 0; i < extension.repeated_message_value->size(); i++) { - if (!extension.repeated_message_value->Get(i).IsInitialized()) { - return false; - } - } - } else { - if (!extension.is_cleared) { - if (extension.is_lazy) { - if (!extension.lazymessage_value->IsInitialized()) return false; - } else { - if (!extension.message_value->IsInitialized()) return false; - } - } - } + if (GOOGLE_PREDICT_FALSE(is_large())) { + for (const auto& kv : *map_.large) { + if (!kv.second.IsInitialized()) return false; } + return true; + } + for (const KeyValue* it = flat_begin(); it != flat_end(); ++it) { + if (!it->second.IsInitialized()) return false; } - return true; } @@ -1351,22 +1366,27 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, void ExtensionSet::SerializeWithCachedSizes( int start_field_number, int end_field_number, io::CodedOutputStream* output) const { - ExtensionMap::const_iterator iter; - for (iter = extensions_.lower_bound(start_field_number); - iter != extensions_.end() && iter->first < end_field_number; - ++iter) { - iter->second.SerializeFieldWithCachedSizes(iter->first, output); + if (GOOGLE_PREDICT_FALSE(is_large())) { + const auto& end = map_.large->end(); + for (auto it = map_.large->lower_bound(start_field_number); + it != end && it->first < end_field_number; ++it) { + it->second.SerializeFieldWithCachedSizes(it->first, output); + } + return; + } + const KeyValue* end = flat_end(); + for (const KeyValue* it = std::lower_bound( + flat_begin(), end, start_field_number, KeyValue::FirstComparator()); + it != end && it->first < end_field_number; ++it) { + it->second.SerializeFieldWithCachedSizes(it->first, output); } } size_t ExtensionSet::ByteSize() const { size_t total_size = 0; - - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - total_size += iter->second.ByteSize(iter->first); - } - + ForEach([&total_size](int number, const Extension& ext) { + total_size += ext.ByteSize(number); + }); return total_size; } @@ -1376,11 +1396,10 @@ size_t ExtensionSet::ByteSize() const { bool ExtensionSet::MaybeNewExtension(int number, const FieldDescriptor* descriptor, Extension** result) { - std::pair insert_result = - extensions_.insert(std::make_pair(number, Extension())); - *result = &insert_result.first->second; + bool extension_is_new = false; + std::tie(*result, extension_is_new) = Insert(number); (*result)->descriptor = descriptor; - return insert_result.second; + return extension_is_new; } // =================================================================== @@ -1752,9 +1771,143 @@ void ExtensionSet::Extension::Free() { // Defined in extension_set_heavy.cc. // int ExtensionSet::Extension::SpaceUsedExcludingSelf() const +bool ExtensionSet::Extension::IsInitialized() const { + if (cpp_type(type) == WireFormatLite::CPPTYPE_MESSAGE) { + if (is_repeated) { + for (int i = 0; i < repeated_message_value->size(); i++) { + if (!repeated_message_value->Get(i).IsInitialized()) { + return false; + } + } + } else { + if (!is_cleared) { + if (is_lazy) { + if (!lazymessage_value->IsInitialized()) return false; + } else { + if (!message_value->IsInitialized()) return false; + } + } + } + } + return true; +} + // Dummy key method to avoid weak vtable. void ExtensionSet::LazyMessageExtension::UnusedKeyMethod() {} +const ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) const { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return FindOrNullInLargeMap(key); + } + const KeyValue* end = flat_end(); + const KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + return &it->second; + } + return NULL; +} + +const ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap( + int key) const { + assert(is_large()); + LargeMap::const_iterator it = map_.large->find(key); + if (it != map_.large->end()) { + return &it->second; + } + return NULL; +} + +ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return FindOrNullInLargeMap(key); + } + KeyValue* end = flat_end(); + KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + return &it->second; + } + return NULL; +} + +ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(int key) { + assert(is_large()); + LargeMap::iterator it = map_.large->find(key); + if (it != map_.large->end()) { + return &it->second; + } + return NULL; +} + +std::pair ExtensionSet::Insert(int key) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + auto maybe = map_.large->insert({key, Extension()}); + return {&maybe.first->second, maybe.second}; + } + KeyValue* end = flat_end(); + KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + return {&it->second, false}; + } + if (flat_size_ < flat_capacity_) { + std::copy_backward(it, end, end + 1); + ++flat_size_; + it->first = key; + it->second = Extension(); + return {&it->second, true}; + } + GrowCapacity(flat_size_ + 1); + return Insert(key); +} + +void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return; // LargeMap does not have a "reserve" method. + } + if (flat_capacity_ >= minimum_new_capacity) { + return; + } + + do { + flat_capacity_ = flat_capacity_ == 0 ? 1 : flat_capacity_ * 4; + } while (flat_capacity_ < minimum_new_capacity); + + const KeyValue* begin = flat_begin(); + const KeyValue* end = flat_end(); + if (flat_capacity_ > kMaximumFlatCapacity) { + // Switch to LargeMap + map_.large = ::google::protobuf::Arena::Create(arena_); + LargeMap::iterator hint = map_.large->begin(); + for (const KeyValue* it = begin; it != end; ++it) { + hint = map_.large->insert(hint, {it->first, it->second}); + } + flat_size_ = 0; + } else { + map_.flat = ::google::protobuf::Arena::CreateArray(arena_, flat_capacity_); + std::copy(begin, end, map_.flat); + } + if (arena_ == NULL) delete[] begin; +} + +// static +constexpr uint16 ExtensionSet::kMaximumFlatCapacity; + +void ExtensionSet::Erase(int key) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + map_.large->erase(key); + return; + } + KeyValue* end = flat_end(); + KeyValue* it = + std::lower_bound(flat_begin(), end, key, KeyValue::FirstComparator()); + if (it != end && it->first == key) { + std::copy(it + 1, end, it); + --flat_size_; + } +} + // ================================================================== // Default repeated field instances for iterator-compatible accessors diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h index b0f3b8ddec..c4796629a9 100644 --- a/src/google/protobuf/extension_set.h +++ b/src/google/protobuf/extension_set.h @@ -38,16 +38,16 @@ #ifndef GOOGLE_PROTOBUF_EXTENSION_SET_H__ #define GOOGLE_PROTOBUF_EXTENSION_SET_H__ -#include +#include +#include #include -#include #include - +#include +#include #include #include #include - #include namespace google { @@ -464,7 +464,12 @@ class LIBPROTOBUF_EXPORT ExtensionSet { const MessageLite& prototype) = 0; virtual bool IsInitialized() const = 0; - virtual int ByteSize() const = 0; + + PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead") + virtual int ByteSize() const { + return internal::ToIntSize(ByteSizeLong()); + } + virtual size_t ByteSizeLong() const = 0; virtual size_t SpaceUsedLong() const = 0; virtual void MergeFrom(const LazyMessageExtension& other) = 0; @@ -567,9 +572,89 @@ class LIBPROTOBUF_EXPORT ExtensionSet { int GetSize() const; void Free(); size_t SpaceUsedExcludingSelfLong() const; + bool IsInitialized() const; }; - typedef std::map ExtensionMap; + // The Extension struct is small enough to be passed by value, so we use it + // directly as the value type in mappings rather than use pointers. We use + // sorted maps rather than hash-maps because we expect most ExtensionSets will + // only contain a small number of extension. Also, we want AppendToList and + // deterministic serialization to order fields by field number. + + struct KeyValue { + int first; + Extension second; + + struct FirstComparator { + bool operator()(const KeyValue& lhs, const KeyValue& rhs) const { + return lhs.first < rhs.first; + } + bool operator()(const KeyValue& lhs, int key) const { + return lhs.first < key; + } + bool operator()(int key, const KeyValue& rhs) const { + return key < rhs.first; + } + }; + }; + + typedef std::map LargeMap; + + // Wrapper API that switches between flat-map and LargeMap. + + // Finds a key (if present) in the ExtensionSet. + const Extension* FindOrNull(int key) const; + Extension* FindOrNull(int key); + + // Helper-functions that only inspect the LargeMap. + const Extension* FindOrNullInLargeMap(int key) const; + Extension* FindOrNullInLargeMap(int key); + + // Inserts a new (key, Extension) into the ExtensionSet (and returns true), or + // finds the already-existing Extension for that key (returns false). + // The Extension* will point to the new-or-found Extension. + std::pair Insert(int key); + + // Grows the flat_capacity_. + // If flat_capacity_ > kMaximumFlatCapacity, converts to LargeMap. + void GrowCapacity(size_t minimum_new_capacity); + static constexpr uint16 kMaximumFlatCapacity = 256; + bool is_large() const { return flat_capacity_ > kMaximumFlatCapacity; } + + // Removes a key from the ExtensionSet. + void Erase(int key); + + size_t Size() const { + return GOOGLE_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_; + } + + // Similar to std::for_each. + // Each Iterator is decomposed into ->first and ->second fields, so + // that the KeyValueFunctor can be agnostic vis-a-vis KeyValue-vs-std::pair. + template + static KeyValueFunctor ForEach(Iterator begin, Iterator end, + KeyValueFunctor func) { + for (Iterator it = begin; it != end; ++it) func(it->first, it->second); + return std::move(func); + } + + // Applies a functor to the pairs in sorted order. + template + KeyValueFunctor ForEach(KeyValueFunctor func) { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); + } + return ForEach(flat_begin(), flat_end(), std::move(func)); + } + + // Applies a functor to the pairs in sorted order. + template + KeyValueFunctor ForEach(KeyValueFunctor func) const { + if (GOOGLE_PREDICT_FALSE(is_large())) { + return ForEach(map_.large->begin(), map_.large->end(), std::move(func)); + } + return ForEach(flat_begin(), flat_end(), std::move(func)); + } // Merges existing Extension from other_extension void InternalExtensionMergeFrom(int number, const Extension& other_extension); @@ -633,14 +718,38 @@ class LIBPROTOBUF_EXPORT ExtensionSet { static inline size_t RepeatedMessage_SpaceUsedExcludingSelfLong( RepeatedPtrFieldBase* field); - // The Extension struct is small enough to be passed by value, so we use it - // directly as the value type in the map rather than use pointers. We use - // a map rather than hash_map here because we expect most ExtensionSets will - // only contain a small number of extensions whereas hash_map is optimized - // for 100 elements or more. Also, we want AppendToList() to order fields - // by field number. - ExtensionMap extensions_; + KeyValue* flat_begin() { + assert(!is_large()); + return map_.flat; + } + const KeyValue* flat_begin() const { + assert(!is_large()); + return map_.flat; + } + KeyValue* flat_end() { + assert(!is_large()); + return map_.flat + flat_size_; + } + const KeyValue* flat_end() const { + assert(!is_large()); + return map_.flat + flat_size_; + } + ::google::protobuf::Arena* arena_; + + // Manual memory-management: + // map_.flat is an allocated array of flat_capacity_ elements. + // [map_.flat, map_.flat + flat_size_) is the currently-in-use prefix. + uint16 flat_capacity_; + uint16 flat_size_; + union AllocatedData { + KeyValue* flat; + + // If flat_capacity_ > kMaximumFlatCapacity, switch to LargeMap, + // which guarantees O(n lg n) CPU but larger constant factors. + LargeMap* large; + } map_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet); }; @@ -1127,7 +1236,7 @@ LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_message_generic_type_traits_ // message-type repeated field extensions. class LIBPROTOBUF_EXPORT RepeatedMessageGenericTypeTraits { public: - typedef RepeatedPtrField< ::google::protobuf::MessageLite*> RepeatedFieldType; + typedef RepeatedPtrField<::google::protobuf::MessageLite*> RepeatedFieldType; private: template friend class RepeatedMessageTypeTraits; static void InitializeDefaultRepeatedFields(); diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc index 432c0fd7f4..a3c841671f 100644 --- a/src/google/protobuf/extension_set_heavy.cc +++ b/src/google/protobuf/extension_set_heavy.cc @@ -35,9 +35,10 @@ // Contains methods defined in extension_set.h which cannot be part of the // lite library because they use descriptors or reflection. +#include +#include #include #include -#include #include #include #include @@ -95,16 +96,14 @@ class DescriptorPoolExtensionFinder : public ExtensionFinder { }; void ExtensionSet::AppendToList( - const Descriptor* containing_type, - const DescriptorPool* pool, + const Descriptor* containing_type, const DescriptorPool* pool, std::vector* output) const { - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { + ForEach([containing_type, pool, &output](int number, const Extension& ext) { bool has = false; - if (iter->second.is_repeated) { - has = iter->second.GetSize() > 0; + if (ext.is_repeated) { + has = ext.GetSize() > 0; } else { - has = !iter->second.is_cleared; + has = !ext.is_cleared; } if (has) { @@ -113,14 +112,13 @@ void ExtensionSet::AppendToList( // initialized, so they might not even be constructed until // AppendToList() is called. - if (iter->second.descriptor == NULL) { - output->push_back(pool->FindExtensionByNumber( - containing_type, iter->first)); + if (ext.descriptor == NULL) { + output->push_back(pool->FindExtensionByNumber(containing_type, number)); } else { - output->push_back(iter->second.descriptor); + output->push_back(ext.descriptor); } } - } + }); } inline FieldDescriptor::Type real_type(FieldType type) { @@ -147,17 +145,17 @@ inline WireFormatLite::FieldType field_type(FieldType type) { const MessageLite& ExtensionSet::GetMessage(int number, const Descriptor* message_type, MessageFactory* factory) const { - ExtensionMap::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { + const Extension* extension = FindOrNull(number); + if (extension == NULL || extension->is_cleared) { // Not present. Return the default value. return *factory->GetPrototype(message_type); } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); - if (iter->second.is_lazy) { - return iter->second.lazymessage_value->GetMessage( + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); + if (extension->is_lazy) { + return extension->lazymessage_value->GetMessage( *factory->GetPrototype(message_type)); } else { - return *iter->second.message_value; + return *extension->message_value; } } } @@ -190,51 +188,51 @@ MessageLite* ExtensionSet::MutableMessage(const FieldDescriptor* descriptor, MessageLite* ExtensionSet::ReleaseMessage(const FieldDescriptor* descriptor, MessageFactory* factory) { - ExtensionMap::iterator iter = extensions_.find(descriptor->number()); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(descriptor->number()); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = iter->second.lazymessage_value->ReleaseMessage( + if (extension->is_lazy) { + ret = extension->lazymessage_value->ReleaseMessage( *factory->GetPrototype(descriptor->message_type())); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { if (arena_ != NULL) { - ret = (iter->second.message_value)->New(); - ret->CheckTypeAndMergeFrom(*(iter->second.message_value)); + ret = extension->message_value->New(); + ret->CheckTypeAndMergeFrom(*extension->message_value); } else { - ret = iter->second.message_value; + ret = extension->message_value; } } - extensions_.erase(descriptor->number()); + Erase(descriptor->number()); return ret; } } MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( const FieldDescriptor* descriptor, MessageFactory* factory) { - ExtensionMap::iterator iter = extensions_.find(descriptor->number()); - if (iter == extensions_.end()) { + Extension* extension = FindOrNull(descriptor->number()); + if (extension == NULL) { // Not present. Return NULL. return NULL; } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); + GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); MessageLite* ret = NULL; - if (iter->second.is_lazy) { - ret = iter->second.lazymessage_value->UnsafeArenaReleaseMessage( + if (extension->is_lazy) { + ret = extension->lazymessage_value->UnsafeArenaReleaseMessage( *factory->GetPrototype(descriptor->message_type())); if (arena_ == NULL) { - delete iter->second.lazymessage_value; + delete extension->lazymessage_value; } } else { - ret = iter->second.message_value; + ret = extension->message_value; } - extensions_.erase(descriptor->number()); + Erase(descriptor->number()); return ret; } } @@ -260,7 +258,7 @@ MessageLite* ExtensionSet::AddMessage(const FieldDescriptor* descriptor, // RepeatedPtrField does not know how to Add() since it cannot // allocate an abstract object, so we have to be tricky. MessageLite* result = - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( extension->repeated_message_value) ->AddFromCleared >(); if (result == NULL) { @@ -349,14 +347,10 @@ int ExtensionSet::SpaceUsedExcludingSelf() const { } size_t ExtensionSet::SpaceUsedExcludingSelfLong() const { - size_t total_size = - extensions_.size() * sizeof(ExtensionMap::value_type); - for (ExtensionMap::const_iterator iter = extensions_.begin(), - end = extensions_.end(); - iter != end; - ++iter) { - total_size += iter->second.SpaceUsedExcludingSelfLong(); - } + size_t total_size = Size() * sizeof(KeyValue); + ForEach([&total_size](int /* number */, const Extension& ext) { + total_size += ext.SpaceUsedExcludingSelfLong(); + }); return total_size; } @@ -394,7 +388,7 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const { total_size += sizeof(*repeated_message_value) + RepeatedMessage_SpaceUsedExcludingSelfLong( - reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( repeated_message_value)); break; } @@ -438,25 +432,33 @@ uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray( } uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray( - int start_field_number, int end_field_number, - bool deterministic, uint8* target) const { - ExtensionMap::const_iterator iter; - for (iter = extensions_.lower_bound(start_field_number); - iter != extensions_.end() && iter->first < end_field_number; - ++iter) { - target = iter->second.InternalSerializeFieldWithCachedSizesToArray( - iter->first, deterministic, target); + int start_field_number, int end_field_number, bool deterministic, + uint8* target) const { + if (GOOGLE_PREDICT_FALSE(is_large())) { + const auto& end = map_.large->end(); + for (auto it = map_.large->lower_bound(start_field_number); + it != end && it->first < end_field_number; ++it) { + target = it->second.InternalSerializeFieldWithCachedSizesToArray( + it->first, deterministic, target); + } + return target; + } + const KeyValue* end = flat_end(); + for (const KeyValue* it = std::lower_bound( + flat_begin(), end, start_field_number, KeyValue::FirstComparator()); + it != end && it->first < end_field_number; ++it) { + target = it->second.InternalSerializeFieldWithCachedSizesToArray( + it->first, deterministic, target); } return target; } uint8* ExtensionSet::InternalSerializeMessageSetWithCachedSizesToArray( bool deterministic, uint8* target) const { - ExtensionMap::const_iterator iter; - for (iter = extensions_.begin(); iter != extensions_.end(); ++iter) { - target = iter->second.InternalSerializeMessageSetItemWithCachedSizesToArray( - iter->first, deterministic, target); - } + ForEach([deterministic, &target](int number, const Extension& ext) { + target = ext.InternalSerializeMessageSetItemWithCachedSizesToArray( + number, deterministic, target); + }); return target; } @@ -783,9 +785,9 @@ size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { // message size_t message_size = 0; if (is_lazy) { - message_size = lazymessage_value->ByteSize(); + message_size = lazymessage_value->ByteSizeLong(); } else { - message_size = message_value->ByteSize(); + message_size = message_value->ByteSizeLong(); } our_size += io::CodedOutputStream::VarintSize32(message_size); @@ -796,20 +798,16 @@ size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const { void ExtensionSet::SerializeMessageSetWithCachedSizes( io::CodedOutputStream* output) const { - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.SerializeMessageSetItemWithCachedSizes(iter->first, output); - } + ForEach([output](int number, const Extension& ext) { + ext.SerializeMessageSetItemWithCachedSizes(number, output); + }); } size_t ExtensionSet::MessageSetByteSize() const { size_t total_size = 0; - - for (ExtensionMap::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - total_size += iter->second.MessageSetItemByteSize(iter->first); - } - + ForEach([&total_size](int number, const Extension& ext) { + total_size += ext.MessageSetItemByteSize(number); + }); return total_size; } diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc index b8b6e42868..bc65d29506 100644 --- a/src/google/protobuf/extension_set_unittest.cc +++ b/src/google/protobuf/extension_set_unittest.cc @@ -32,19 +32,20 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. +#include #include -#include +#include #include #include -#include +#include +#include #include #include #include #include +#include #include -#include -#include #include #include @@ -285,7 +286,7 @@ TEST(ExtensionSetTest, CopyFrom) { TestUtil::ExpectAllExtensionsSet(message2); } -TEST(ExtensioSetTest, CopyFromPacked) { +TEST(ExtensionSetTest, CopyFromPacked) { unittest::TestPackedExtensions message1, message2; TestUtil::SetPackedExtensions(&message1); @@ -444,7 +445,7 @@ TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) { TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) { ::google::protobuf::Arena arena1; - google::protobuf::scoped_ptr arena2(new ::google::protobuf::Arena()); + std::unique_ptr arena2(new ::google::protobuf::Arena()); unittest::TestAllExtensions* message1 = Arena::CreateMessage(&arena1); @@ -601,6 +602,26 @@ TEST(ExtensionSetTest, PackedSerializationToStream) { TestUtil::ExpectPackedFieldsSet(destination); } +TEST(ExtensionSetTest, NestedExtensionGroup) { + // Serialize as TestGroup and parse as TestGroupExtension. + unittest::TestGroup source; + unittest::TestGroupExtension destination; + string data; + + source.mutable_optionalgroup()->set_a(117); + source.set_optional_foreign_enum(unittest::FOREIGN_BAZ); + source.SerializeToString(&data); + EXPECT_TRUE(destination.ParseFromString(data)); + EXPECT_TRUE(destination.GetExtension( + unittest::TestNestedExtension::optionalgroup_extension).has_a()); + EXPECT_EQ(117, destination.GetExtension( + unittest::TestNestedExtension::optionalgroup_extension).a()); + EXPECT_TRUE(destination.HasExtension( + unittest::TestNestedExtension::optional_foreign_enum_extension)); + EXPECT_EQ(unittest::FOREIGN_BAZ, destination.GetExtension( + unittest::TestNestedExtension::optional_foreign_enum_extension)); +} + TEST(ExtensionSetTest, Parsing) { // Serialize as TestAllTypes and parse as TestAllExtensions. unittest::TestAllTypes source; @@ -998,8 +1019,8 @@ TEST(ExtensionSetTest, RepeatedFields) { ASSERT_EQ(110, SumAllExtensions( message, unittest::repeated_double_extension, 0)); - RepeatedPtrField< ::std::string>::iterator string_iter; - RepeatedPtrField< ::std::string>::iterator string_end; + RepeatedPtrField<::std::string>::iterator string_iter; + RepeatedPtrField<::std::string>::iterator string_end; for (string_iter = message.MutableRepeatedExtension( unittest::repeated_string_extension)->begin(), string_end = message.MutableRepeatedExtension( @@ -1007,8 +1028,8 @@ TEST(ExtensionSetTest, RepeatedFields) { string_iter != string_end; ++string_iter) { *string_iter += "test"; } - RepeatedPtrField< ::std::string>::const_iterator string_const_iter; - RepeatedPtrField< ::std::string>::const_iterator string_const_end; + RepeatedPtrField<::std::string>::const_iterator string_const_iter; + RepeatedPtrField<::std::string>::const_iterator string_const_end; for (string_const_iter = message.GetRepeatedExtension( unittest::repeated_string_extension).begin(), string_const_end = message.GetRepeatedExtension( diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc index abee4fe7fb..000fa8d33a 100644 --- a/src/google/protobuf/field_mask.pb.cc +++ b/src/google/protobuf/field_mask.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class FieldMaskDefaultTypeInternal { @@ -29,14 +29,9 @@ class FieldMaskDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto { -void InitDefaultsFieldMaskImpl() { +static void InitDefaultsFieldMask() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_FieldMask_default_instance_; new (ptr) ::google::protobuf::FieldMask(); @@ -45,9 +40,11 @@ void InitDefaultsFieldMaskImpl() { ::google::protobuf::FieldMask::InitAsDefaultInstance(); } -void InitDefaultsFieldMask() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldMaskImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldMask}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_FieldMask.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -70,15 +67,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -104,8 +100,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -127,23 +123,20 @@ const int FieldMask::kPathsFieldNumber; FieldMask::FieldMask() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.FieldMask) } FieldMask::FieldMask(const FieldMask& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - paths_(from.paths_), - _cached_size_(0) { + paths_(from.paths_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask) } void FieldMask::SharedCtor() { - _cached_size_ = 0; } FieldMask::~FieldMask() { @@ -155,9 +148,7 @@ void FieldMask::SharedDtor() { } void FieldMask::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FieldMask::descriptor() { ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce(); @@ -165,7 +156,7 @@ const ::google::protobuf::Descriptor* FieldMask::descriptor() { } const FieldMask& FieldMask::default_instance() { - ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMask(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base); return *internal_default_instance(); } @@ -186,7 +177,7 @@ bool FieldMask::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.FieldMask) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -293,9 +284,7 @@ size_t FieldMask::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -350,7 +339,6 @@ void FieldMask::InternalSwap(FieldMask* other) { using std::swap; paths_.InternalSwap(CastToBase(&other->paths_)); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata FieldMask::GetMetadata() const { @@ -364,7 +352,7 @@ void FieldMask::InternalSwap(FieldMask* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::Create< ::google::protobuf::FieldMask >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::FieldMask >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index 2d75967e84..144b41fae0 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto -#ifndef PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto #include @@ -24,12 +24,14 @@ #include #include #include +#include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ffield_5fmask_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldMaskImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldMask(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsFieldMask(); -} } // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instan } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::Create< ::google::protobuf::FieldMask>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -99,7 +96,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro return reinterpret_cast( &_FieldMask_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(FieldMask* other); @@ -109,32 +106,33 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline FieldMask* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline FieldMask* New() const final { + return CreateMaybeMessage(NULL); } - FieldMask* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + FieldMask* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const FieldMask& from); void MergeFrom(const FieldMask& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(FieldMask* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -145,7 +143,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -178,9 +176,8 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::std::string> paths_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::InitDefaultsFieldMaskImpl(); }; // =================================================================== @@ -273,4 +270,4 @@ FieldMask::mutable_paths() { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2ffield_5fmask_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto diff --git a/src/google/protobuf/field_mask.proto b/src/google/protobuf/field_mask.proto index eb96ba00a1..76e09f391d 100644 --- a/src/google/protobuf/field_mask.proto +++ b/src/google/protobuf/field_mask.proto @@ -243,8 +243,8 @@ option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask"; // // ## Field Mask Verification // -// The implementation of the all the API methods, which have any FieldMask type -// field in the request, should verify the included field paths, and return +// The implementation of any API method which has a FieldMask type field in the +// request should verify the included field paths, and return an // `INVALID_ARGUMENT` error if any path is duplicated or unmappable. message FieldMask { // The set of field mask paths. diff --git a/src/google/protobuf/generated_enum_util.h b/src/google/protobuf/generated_enum_util.h index 4f5ded5bb7..96b03cc916 100644 --- a/src/google/protobuf/generated_enum_util.h +++ b/src/google/protobuf/generated_enum_util.h @@ -31,14 +31,14 @@ #ifndef GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__ #define GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__ -#include +#include namespace google { namespace protobuf { // This type trait can be used to cause templates to only match proto2 enum // types. -template struct is_proto_enum : ::google::protobuf::internal::false_type {}; +template struct is_proto_enum : ::std::false_type {}; } // namespace protobuf diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc index b0c975b4cb..247f772c04 100644 --- a/src/google/protobuf/generated_message_reflection.cc +++ b/src/google/protobuf/generated_message_reflection.cc @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -290,6 +291,13 @@ size_t GeneratedMessageReflection::SpaceUsedLong(const Message& message) const { switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + const string* ptr = + &GetField(message, field).GetNoArena(); + total_size += StringSpaceUsedExcludingSelfLong(*ptr); + break; + } + // Initially, the string points to the default value stored in // the prototype. Only count the string if it has been changed // from the default value. @@ -424,15 +432,25 @@ void GeneratedMessageReflection::SwapField( { Arena* arena1 = GetArena(message1); Arena* arena2 = GetArena(message2); + + if (IsInlined(field)) { + InlinedStringField* string1 = + MutableRaw(message1, field); + InlinedStringField* string2 = + MutableRaw(message2, field); + string1->Swap(string2); + break; + } + ArenaStringPtr* string1 = MutableRaw(message1, field); ArenaStringPtr* string2 = MutableRaw(message2, field); + const string* default_ptr = + &DefaultRaw(field).Get(); if (arena1 == arena2) { - string1->Swap(string2); + string1->Swap(string2, default_ptr, arena1); } else { - const string* default_ptr = - &DefaultRaw(field).Get(); const string temp = string1->Get(); string1->Set(default_ptr, string2->Get(), arena1); string2->Set(default_ptr, temp, arena2); @@ -738,7 +756,15 @@ int GeneratedMessageReflection::FieldSize(const Message& message, case FieldDescriptor::CPPTYPE_STRING: case FieldDescriptor::CPPTYPE_MESSAGE: if (IsMapFieldInApi(field)) { - return GetRaw(message, field).GetRepeatedField().size(); + const internal::MapFieldBase& map = + GetRaw(message, field); + if (map.IsRepeatedFieldValid()) { + return map.GetRepeatedField().size(); + } else { + // No need to materialize the repeated field if it is out of sync: + // its size will be the same as the map's size. + return map.size(); + } } else { return GetRaw(message, field).size(); } @@ -789,6 +815,14 @@ void GeneratedMessageReflection::ClearField( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + const string* default_ptr = + &DefaultRaw(field).GetNoArena(); + MutableRaw(message, field)->SetNoArena( + default_ptr, *default_ptr); + break; + } + const string* default_ptr = &DefaultRaw(field).Get(); MutableRaw(message, field)->SetAllocated( @@ -1121,6 +1155,10 @@ string GeneratedMessageReflection::GetString( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + return GetField(message, field).GetNoArena(); + } + return GetField(message, field).Get(); } } @@ -1138,6 +1176,10 @@ const string& GeneratedMessageReflection::GetStringReference( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + return GetField(message, field).GetNoArena(); + } + return GetField(message, field).Get(); } } @@ -1156,6 +1198,12 @@ void GeneratedMessageReflection::SetString( switch (field->options().ctype()) { default: // TODO(kenton): Support other string reps. case FieldOptions::STRING: { + if (IsInlined(field)) { + MutableField(message, field)->SetNoArena( + NULL, value); + break; + } + const string* default_ptr = &DefaultRaw(field).Get(); if (field->containing_oneof() && !HasOneofField(*message, field)) { ClearOneof(message, field->containing_oneof()); @@ -1868,6 +1916,10 @@ const Type& GeneratedMessageReflection::GetRaw( return GetConstRefAtOffset(message, schema_.GetFieldOffset(field)); } +bool GeneratedMessageReflection::IsInlined(const FieldDescriptor* field) const { + return schema_.IsFieldInlined(field); +} + template Type* GeneratedMessageReflection::MutableRaw(Message* message, const FieldDescriptor* field) const { @@ -1963,6 +2015,10 @@ inline bool GeneratedMessageReflection::HasBit( case FieldDescriptor::CPPTYPE_STRING: switch (field->options().ctype()) { default: { + if (IsInlined(field)) { + return !GetField(message, field) + .GetNoArena().empty(); + } return GetField(message, field).Get().size() > 0; } } @@ -2307,7 +2363,6 @@ struct MetadataOwner { void AssignDescriptors( const string& filename, const MigrationSchema* schemas, const Message* const* default_instances_, const uint32* offsets, - MessageFactory* factory, // update the following descriptor arrays. Metadata* file_level_metadata, const EnumDescriptor** file_level_enum_descriptors, @@ -2316,7 +2371,7 @@ void AssignDescriptors( ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(filename); GOOGLE_CHECK(file != NULL); - if (!factory) factory = MessageFactory::generated_factory(); + MessageFactory* factory = MessageFactory::generated_factory(); AssignDescriptorsHelper helper(factory, file_level_metadata, file_level_enum_descriptors, schemas, diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h index 3c6701cfef..31f249b6b4 100644 --- a/src/google/protobuf/generated_message_reflection.h +++ b/src/google/protobuf/generated_message_reflection.h @@ -94,7 +94,7 @@ class WeakFieldMap; // weak_field_map.h // For each oneof or weak field, the offset is relative to the // default_instance. These can be computed at compile time // using the -// GOOGLE_PROTOBUF_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET() +// PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET() // macro. For each none oneof field, the offset is related to // the start of the message object. These can be computed at // compile time using the @@ -134,7 +134,7 @@ struct ReflectionSchema { // efficient when we know statically that it is not a oneof field. uint32 GetFieldOffsetNonOneof(const FieldDescriptor* field) const { GOOGLE_DCHECK(!field->containing_oneof()); - return offsets_[field->index()]; + return OffsetValue(offsets_[field->index()], field->type()); } // Offset of any field. @@ -143,12 +143,23 @@ struct ReflectionSchema { size_t offset = static_cast(field->containing_type()->field_count() + field->containing_oneof()->index()); - return offsets_[offset]; + return OffsetValue(offsets_[offset], field->type()); } else { return GetFieldOffsetNonOneof(field); } } + bool IsFieldInlined(const FieldDescriptor* field) const { + if (field->containing_oneof()) { + size_t offset = + static_cast(field->containing_type()->field_count() + + field->containing_oneof()->index()); + return Inlined(offsets_[offset], field->type()); + } else { + return Inlined(offsets_[field->index()], field->type()); + } + } + uint32 GetOneofCaseOffset(const OneofDescriptor* oneof_descriptor) const { return static_cast(oneof_case_offset_) + static_cast( @@ -198,7 +209,7 @@ struct ReflectionSchema { // of the underlying data depends on the field's type. const void *GetFieldDefault(const FieldDescriptor* field) const { return reinterpret_cast(default_instance_) + - offsets_[field->index()]; + OffsetValue(offsets_[field->index()], field->type()); } @@ -219,6 +230,27 @@ struct ReflectionSchema { int oneof_case_offset_; int object_size_; int weak_field_map_offset_; + + // We tag offset values to provide additional data about fields (such as + // inlined). + static uint32 OffsetValue(uint32 v, FieldDescriptor::Type type) { + if (type == FieldDescriptor::TYPE_STRING || + type == FieldDescriptor::TYPE_BYTES) { + return v & ~1u; + } else { + return v; + } + } + + static bool Inlined(uint32 v, FieldDescriptor::Type type) { + if (type == FieldDescriptor::TYPE_STRING || + type == FieldDescriptor::TYPE_BYTES) { + return v & 1u; + } else { + // Non string/byte fields are not inlined. + return false; + } + } }; // Structs that the code generator emits directly to describe a message. @@ -257,7 +289,7 @@ struct MigrationSchema { // of whatever type the individual field would be. Strings and // Messages use RepeatedPtrFields while everything else uses // RepeatedFields. -class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Reflection { +class GeneratedMessageReflection final : public Reflection { public: // Constructs a GeneratedMessageReflection. // Parameters: @@ -543,6 +575,8 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection PROTOBUF_FINAL : public Refl inline InternalMetadataWithArena* MutableInternalMetadataWithArena(Message* message) const; + inline bool IsInlined(const FieldDescriptor* field) const; + inline bool HasBit(const Message& message, const FieldDescriptor* field) const; inline void SetBit(Message* message, @@ -704,7 +738,6 @@ T* DynamicCastToGenerated(Message* from) { LIBPROTOBUF_EXPORT void AssignDescriptors( const string& filename, const MigrationSchema* schemas, const Message* const* default_instances_, const uint32* offsets, - MessageFactory* factory, // update the following descriptor arrays. Metadata* file_level_metadata, const EnumDescriptor** file_level_enum_descriptors, diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc index 242cc4a1b7..61eb6603ca 100644 --- a/src/google/protobuf/generated_message_reflection_unittest.cc +++ b/src/google/protobuf/generated_message_reflection_unittest.cc @@ -44,9 +44,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -360,7 +357,7 @@ TEST(GeneratedMessageReflectionTest, ReleaseLast) { ASSERT_EQ(2, message.repeated_foreign_message_size()); const protobuf_unittest::ForeignMessage* expected = message.mutable_repeated_foreign_message(1); - google::protobuf::scoped_ptr released(message.GetReflection()->ReleaseLast( + std::unique_ptr released(message.GetReflection()->ReleaseLast( &message, descriptor->FindFieldByName("repeated_foreign_message"))); EXPECT_EQ(expected, released.get()); } @@ -383,7 +380,7 @@ TEST(GeneratedMessageReflectionTest, ReleaseLastExtensions) { unittest::repeated_foreign_message_extension)); const protobuf_unittest::ForeignMessage* expected = message.MutableExtension( unittest::repeated_foreign_message_extension, 1); - google::protobuf::scoped_ptr released(message.GetReflection()->ReleaseLast( + std::unique_ptr released(message.GetReflection()->ReleaseLast( &message, descriptor->file()->FindExtensionByName( "repeated_foreign_message_extension"))); EXPECT_EQ(expected, released.get()); @@ -746,6 +743,10 @@ TEST(GeneratedMessageReflectionTest, Oneof) { "change_spiece"); EXPECT_EQ("change_spiece", reflection->GetString( message, descriptor->FindFieldByName("bar_string_piece"))); + + message.clear_foo(); + message.clear_bar(); + TestUtil::ExpectOneofClear(message); } TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) { diff --git a/src/google/protobuf/generated_message_table_driven.cc b/src/google/protobuf/generated_message_table_driven.cc index 29af1ef692..d4450a6cd5 100644 --- a/src/google/protobuf/generated_message_table_driven.cc +++ b/src/google/protobuf/generated_message_table_driven.cc @@ -30,8 +30,9 @@ #include -#include +#include +#include #include #include #include diff --git a/src/google/protobuf/generated_message_table_driven.h b/src/google/protobuf/generated_message_table_driven.h index 6f3fe66609..10ca3aaa36 100644 --- a/src/google/protobuf/generated_message_table_driven.h +++ b/src/google/protobuf/generated_message_table_driven.h @@ -38,9 +38,6 @@ #include #include -#if LANG_CXX11 -#define PROTOBUF_CONSTEXPR constexpr - // We require C++11 and Clang to use constexpr for variables, as GCC 4.8 // requires constexpr to be consistent between declarations of variables // unnecessarily (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58541). @@ -51,37 +48,28 @@ #define PROTOBUF_CONSTEXPR_VAR #endif // !_clang -#else -#define PROTOBUF_CONSTEXPR -#define PROTOBUF_CONSTEXPR_VAR -#endif - namespace google { namespace protobuf { namespace internal { // Processing-type masks. -static PROTOBUF_CONSTEXPR const unsigned char kOneofMask = 0x40; -static PROTOBUF_CONSTEXPR const unsigned char kRepeatedMask = 0x20; +static constexpr const unsigned char kOneofMask = 0x40; +static constexpr const unsigned char kRepeatedMask = 0x20; // Mask for the raw type: either a WireFormatLite::FieldType or one of the // ProcessingTypes below, without the oneof or repeated flag. -static PROTOBUF_CONSTEXPR const unsigned char kTypeMask = 0x1f; +static constexpr const unsigned char kTypeMask = 0x1f; // Wire type masks. -static PROTOBUF_CONSTEXPR const unsigned char kNotPackedMask = 0x10; -static PROTOBUF_CONSTEXPR const unsigned char kInvalidMask = 0x20; +static constexpr const unsigned char kNotPackedMask = 0x10; +static constexpr const unsigned char kInvalidMask = 0x20; enum ProcessingTypes { - TYPE_STRING_CORD = 19, - TYPE_STRING_STRING_PIECE = 20, - TYPE_BYTES_CORD = 21, - TYPE_BYTES_STRING_PIECE = 22, - TYPE_MAP = 23, + TYPE_STRING_INLINED = 23, + TYPE_BYTES_INLINED = 24, + TYPE_MAP = 25, }; -#if LANG_CXX11 static_assert(TYPE_MAP < kRepeatedMask, "Invalid enum"); -#endif // TODO(ckennelly): Add a static assertion to ensure that these masks do not // conflict with wiretypes. @@ -124,7 +112,6 @@ union AuxillaryParseTableField { const MessageLite* default_message() const { return static_cast(default_message_void); } - const ParseTable* parse_table; }; message_aux messages; // Strings @@ -139,19 +126,14 @@ union AuxillaryParseTableField { }; map_aux maps; -#if LANG_CXX11 AuxillaryParseTableField() = default; -#else - AuxillaryParseTableField() { } -#endif - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::enum_aux e) : enums(e) {} - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::message_aux m) : messages(m) {} - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::string_aux s) : strings(s) {} - PROTOBUF_CONSTEXPR AuxillaryParseTableField( - AuxillaryParseTableField::map_aux m) + constexpr AuxillaryParseTableField(AuxillaryParseTableField::enum_aux e) + : enums(e) {} + constexpr AuxillaryParseTableField(AuxillaryParseTableField::message_aux m) + : messages(m) {} + constexpr AuxillaryParseTableField(AuxillaryParseTableField::string_aux s) + : strings(s) {} + constexpr AuxillaryParseTableField(AuxillaryParseTableField::map_aux m) : maps(m) {} }; @@ -178,18 +160,17 @@ struct ParseTable { bool unknown_field_set; }; -// TODO(jhen): Remove the __NVCC__ check when we get a version of nvcc that -// supports these checks. -#if LANG_CXX11 && !defined(__NVCC__) static_assert(sizeof(ParseTableField) <= 16, "ParseTableField is too large"); // The tables must be composed of POD components to ensure link-time // initialization. static_assert(std::is_pod::value, ""); -static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); static_assert(std::is_pod::value, ""); + +#ifndef __NVCC__ // This assertion currently fails under NVCC. +static_assert(std::is_pod::value, ""); #endif // TODO(ckennelly): Consolidate these implementations into a single one, using diff --git a/src/google/protobuf/generated_message_table_driven_lite.cc b/src/google/protobuf/generated_message_table_driven_lite.cc index 90a5050553..961329f367 100644 --- a/src/google/protobuf/generated_message_table_driven_lite.cc +++ b/src/google/protobuf/generated_message_table_driven_lite.cc @@ -30,7 +30,7 @@ #include -#include +#include #include #include diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h index 4dfbf678f7..b2c6096891 100644 --- a/src/google/protobuf/generated_message_table_driven_lite.h +++ b/src/google/protobuf/generated_message_table_driven_lite.h @@ -33,14 +33,15 @@ #include -#include - #include #include +#include +#include #include #include #include #include +#include namespace google { @@ -50,8 +51,7 @@ namespace internal { enum StringType { StringType_STRING = 0, - StringType_CORD = 1, - StringType_STRING_PIECE = 2 + StringType_INLINED = 3 }; // Logically a superset of StringType, consisting of all field types that @@ -60,7 +60,8 @@ enum ProcessingType { ProcessingType_STRING = 0, ProcessingType_CORD = 1, ProcessingType_STRING_PIECE = 2, - ProcessingType_MESSAGE = 3 + ProcessingType_INLINED = 3, + ProcessingType_MESSAGE = 4, }; enum Cardinality { @@ -99,10 +100,9 @@ inline ExtensionSet* GetExtensionSet(MessageLite* msg, int64 extension_offset) { template inline Type* AddField(MessageLite* msg, int64 offset) { -#if LANG_CXX11 - static_assert(has_trivial_copy::value, + static_assert(std::is_trivially_copy_assignable::value || + std::is_same::value, "Do not assign"); -#endif google::protobuf::RepeatedField* repeated = Raw >(msg, offset); @@ -119,15 +119,13 @@ inline string* AddField(MessageLite* msg, int64 offset) { template inline void AddField(MessageLite* msg, int64 offset, Type value) { -#if LANG_CXX11 - static_assert(has_trivial_copy::value, + static_assert(std::is_trivially_copy_assignable::value, "Do not assign"); -#endif *AddField(msg, offset) = value; } inline void SetBit(uint32* has_bits, uint32 has_bit_index) { - GOOGLE_DCHECK(has_bits != NULL); + GOOGLE_DCHECK(has_bits != nullptr); uint32 mask = static_cast(1u) << (has_bit_index % 32); has_bits[has_bit_index / 32u] |= mask; @@ -143,10 +141,8 @@ inline Type* MutableField(MessageLite* msg, uint32* has_bits, template inline void SetField(MessageLite* msg, uint32* has_bits, uint32 has_bit_index, int64 offset, Type value) { -#if LANG_CXX11 - static_assert(has_trivial_copy::value, + static_assert(std::is_trivially_copy_assignable::value, "Do not assign"); -#endif *MutableField(msg, has_bits, has_bit_index, offset) = value; } @@ -175,6 +171,11 @@ inline void ClearOneofField(const ParseTableField& field, Arena* arena, ->Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena); break; + case TYPE_STRING_INLINED: + case TYPE_BYTES_INLINED: + Raw(msg, field.offset)->DestroyNoArena(NULL); + break; + default: // No cleanup needed. break; @@ -207,6 +208,10 @@ inline void ResetOneofField(const ParseTable& table, int field_number, Raw(msg, offset) ->UnsafeSetDefault(static_cast(default_ptr)); break; + case ProcessingType_INLINED: + new (Raw(msg, offset)) + InlinedStringField(*static_cast(default_ptr)); + break; case ProcessingType_MESSAGE: MessageLite** submessage = Raw(msg, offset); const MessageLite* prototype = @@ -227,32 +232,65 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg, size_t size; #endif - string* value; - switch (cardinality) { - case Cardinality_SINGULAR: - // TODO(ckennelly): Is this optimal? - value = - MutableField(msg, has_bits, has_bit_index, offset) - ->Mutable(static_cast(default_ptr), arena); - break; - case Cardinality_REPEATED: - value = AddField(msg, offset); - break; - case Cardinality_ONEOF: - value = Raw(msg, offset) - ->Mutable(static_cast(default_ptr), arena); - break; - } - GOOGLE_DCHECK(value != NULL); + switch (ctype) { + case StringType_INLINED: { + InlinedStringField* s; + switch (cardinality) { + case Cardinality_SINGULAR: + // TODO(ckennelly): Is this optimal? + s = MutableField( + msg, has_bits, has_bit_index, offset); + break; + case Cardinality_REPEATED: + s = AddField(msg, offset); + break; + case Cardinality_ONEOF: + s = Raw(msg, offset); + break; + } + GOOGLE_DCHECK(s != nullptr); + ::std::string* value = s->MutableNoArena(NULL); + + if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { + return false; + } - if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { - return false; +#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED + sdata = value->data(); + size = value->size(); +#endif + break; } + case StringType_STRING: { + string* value; + switch (cardinality) { + case Cardinality_SINGULAR: + // TODO(ckennelly): Is this optimal? + value = + MutableField(msg, has_bits, has_bit_index, offset) + ->Mutable(static_cast(default_ptr), arena); + break; + case Cardinality_REPEATED: + value = AddField(msg, offset); + break; + case Cardinality_ONEOF: + value = Raw(msg, offset) + ->Mutable(static_cast(default_ptr), arena); + break; + } + GOOGLE_DCHECK(value != nullptr); + + if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) { + return false; + } #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - sdata = value->data(); - size = value->size(); + sdata = value->data(); + size = value->size(); #endif + break; + } + } #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED if (validate) { @@ -323,44 +361,6 @@ class RepeatedMessageTypeHandler { } }; -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 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, @@ -490,6 +490,23 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } break; } + case TYPE_BYTES_INLINED: +#ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED + case TYPE_STRING_INLINED: +#endif + { + Arena* const arena = + GetArena(msg, table.arena_offset); + const void* default_ptr = table.aux[field_number].strings.default_ptr; + + if (GOOGLE_PREDICT_FALSE((!HandleString( + 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: @@ -513,8 +530,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, break; } case (WireFormatLite::TYPE_BYTES) | kRepeatedMask: + case TYPE_BYTES_INLINED | kRepeatedMask: #ifndef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case (WireFormatLite::TYPE_STRING) | kRepeatedMask: + case TYPE_STRING_INLINED | kRepeatedMask: #endif { Arena* const arena = @@ -545,6 +564,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, } break; } + case TYPE_STRING_INLINED | kRepeatedMask: case (WireFormatLite::TYPE_STRING) | kRepeatedMask: { Arena* const arena = GetArena(msg, table.arena_offset); @@ -657,6 +677,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, GetArena(msg, table.arena_offset); const MessageLite* prototype = table.aux[field_number].messages.default_message(); + if (prototype == NULL) { + prototype = + ::google::protobuf::internal::ImplicitWeakMessage::default_instance(); + } submsg = prototype->New(arena); *submsg_holder = submsg; } @@ -673,7 +697,10 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, RepeatedPtrFieldBase* field = Raw(msg, offset); const MessageLite* prototype = table.aux[field_number].messages.default_message(); - GOOGLE_DCHECK(prototype != NULL); + if (prototype == NULL) { + prototype = + ::google::protobuf::internal::ImplicitWeakMessage::default_instance(); + } MessageLite* submsg = MergePartialFromCodedStreamHelper::Add(field, prototype); @@ -700,6 +727,22 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, break; } +#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED + case TYPE_STRING_INLINED: { + Arena* const arena = + GetArena(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( + input, msg, arena, has_bits, presence_index, offset, + default_ptr, field_name)))) { + return false; + } + break; + } +#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED case TYPE_MAP: { if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)( input, Raw(msg, offset)))) { @@ -721,7 +764,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table, GOOGLE_DCHECK_NE(processing_type, kRepeatedMask); GOOGLE_DCHECK_EQ(0, processing_type & kOneofMask); - + GOOGLE_DCHECK_NE(TYPE_BYTES_INLINED | kRepeatedMask, processing_type); + GOOGLE_DCHECK_NE(TYPE_STRING_INLINED | kRepeatedMask, processing_type); // TODO(ckennelly): Use a computed goto on GCC/LLVM. // diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc index 15d842226c..dac8ca909a 100644 --- a/src/google/protobuf/generated_message_util.cc +++ b/src/google/protobuf/generated_message_util.cc @@ -35,6 +35,9 @@ #include #include +// We're only using this as a standard way for getting the thread id. +// We're not using any thread functionality. +#include // NOLINT #include #include @@ -43,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -61,7 +65,7 @@ double NaN() { return std::numeric_limits::quiet_NaN(); } -ExplicitlyConstructed< ::std::string> fixed_address_empty_string; +ExplicitlyConstructed<::std::string> fixed_address_empty_string; GOOGLE_PROTOBUF_DECLARE_ONCE(empty_string_once_init_); void DeleteEmptyString() { fixed_address_empty_string.Destruct(); } @@ -251,6 +255,10 @@ struct PrimitiveTypeHelper : PrimitiveTypeHelper {}; +template <> +struct PrimitiveTypeHelper + : PrimitiveTypeHelper {}; + // We want to serialize to both CodedOutputStream and directly into byte arrays // without duplicating the code. In fact we might want extra output channels in // the future. @@ -274,7 +282,7 @@ void WriteLengthTo(uint32 length, O* output) { // Specialization for coded output stream template -struct OutputHelper< ::google::protobuf::io::CodedOutputStream, type> { +struct OutputHelper<::google::protobuf::io::CodedOutputStream, type> { static void Serialize(const void* ptr, ::google::protobuf::io::CodedOutputStream* output) { PrimitiveTypeHelper::Serialize(ptr, output); @@ -416,6 +424,15 @@ struct SingularFieldHelper { } }; +template <> +struct SingularFieldHelper { + template + static void Serialize(const void* field, const FieldMetadata& md, O* output) { + WriteTagTo(md.tag, output); + SerializeTo(&Get<::std::string>(field), output); + } +}; + template struct RepeatedFieldHelper { template @@ -488,6 +505,10 @@ struct RepeatedFieldHelper { }; +template <> +struct RepeatedFieldHelper + : RepeatedFieldHelper {}; + template struct PackedFieldHelper { template @@ -523,6 +544,9 @@ struct PackedFieldHelper template <> struct PackedFieldHelper : PackedFieldHelper {}; +template <> +struct PackedFieldHelper + : PackedFieldHelper {}; template struct OneOfFieldHelper { @@ -533,6 +557,15 @@ struct OneOfFieldHelper { }; +template <> +struct OneOfFieldHelper { + template + static void Serialize(const void* field, const FieldMetadata& md, O* output) { + SingularFieldHelper::Serialize( + Get(field), md, output); + } +}; + void SerializeNotImplemented(int field) { GOOGLE_LOG(FATAL) << "Not implemented field number " << field; } @@ -573,6 +606,11 @@ bool IsNull(const void* ptr) { } +template <> +bool IsNull(const void* ptr) { + return static_cast(ptr)->empty(); +} + #define SERIALIZERS_FOR_TYPE(type) \ case SERIALIZE_TABLE_OP(type, FieldMetadata::kPresence): \ if (!IsPresent(base, field_metadata.has_offset)) continue; \ @@ -620,6 +658,7 @@ void SerializeInternal(const uint8* base, SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64); + SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType); // Special cases case FieldMetadata::kSpecial: @@ -663,6 +702,7 @@ uint8* SerializeInternalToArray(const uint8* base, SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SFIXED64); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT32); SERIALIZERS_FOR_TYPE(WireFormatLite::TYPE_SINT64); + SERIALIZERS_FOR_TYPE(FieldMetadata::kInlinedType); // Special cases case FieldMetadata::kSpecial: { io::ArrayOutputStream array_stream(array_output.ptr, INT_MAX); @@ -698,9 +738,9 @@ void UnknownFieldSerializerLite(const uint8* ptr, uint32 offset, uint32 tag, ->unknown_fields()); } -MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena) { +MessageLite* DuplicateIfNonNullInternal(MessageLite* message) { if (message) { - MessageLite* ret = message->New(arena); + MessageLite* ret = message->New(); ret->CheckTypeAndMergeFrom(*message); return ret; } else { @@ -725,6 +765,49 @@ MessageLite* GetOwnedMessageInternal(Arena* message_arena, } } +namespace { + +void InitSCC_DFS(SCCInfoBase* scc) { + if (scc->visit_status.load(std::memory_order_relaxed) != + SCCInfoBase::kUninitialized) return; + scc->visit_status.store(SCCInfoBase::kRunning, std::memory_order_relaxed); + // Each base is followed by an array of pointers to deps + auto deps = reinterpret_cast(scc + 1); + for (int i = 0; i < scc->num_deps; i++) { + if (deps[i]) InitSCC_DFS(deps[i]); + } + scc->init_func(); + // Mark done (note we use memory order release here), other threads could + // now see this as initialized and thus the initialization must have happened + // before. + scc->visit_status.store(SCCInfoBase::kInitialized, std::memory_order_release); +} + +} // namespace + +void InitSCCImpl(SCCInfoBase* scc) { + static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED}; + // Either the default in case no initialization is running or the id of the + // thread that is currently initializing. + static std::atomic runner; + auto me = std::this_thread::get_id(); + // This will only happen because the constructor will call InitSCC while + // constructing the default instance. + if (runner.load(std::memory_order_relaxed) == me) { + // Because we're in the process of constructing the default instance. + // We can be assured that we're already exploring this SCC. + GOOGLE_CHECK_EQ(scc->visit_status.load(std::memory_order_relaxed), + SCCInfoBase::kRunning); + return; + } + InitProtobufDefaults(); + mu.Lock(); + runner.store(me, std::memory_order_relaxed); + InitSCC_DFS(scc); + runner.store(std::thread::id{}, std::memory_order_relaxed); + mu.Unlock(); +} + } // namespace internal } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h index cd74b45e32..c0e41bf70e 100644 --- a/src/google/protobuf/generated_message_util.h +++ b/src/google/protobuf/generated_message_util.h @@ -39,13 +39,14 @@ #define GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__ #include +#include #include #include #include #include #include -#include +#include // Add direct dep on port for pb.cc #include #include #include @@ -128,7 +129,7 @@ template bool AllAreInitializedWeak(const ::google::protobuf::RepeatedPtrField& t) { for (int i = t.size(); --i >= 0;) { if (!reinterpret_cast(t) - .Get< ::google::protobuf::internal::ImplicitWeakTypeHandler >(i) + .Get<::google::protobuf::internal::ImplicitWeakTypeHandler >(i) .IsInitialized()) { return false; } @@ -164,7 +165,8 @@ struct LIBPROTOBUF_EXPORT FieldMetadata { enum { kCordType = 19, kStringPieceType = 20, - kNumTypes = 20, + kInlinedType = 21, + kNumTypes = 21, kSpecial = kNumTypes * kNumTypeClasses, }; @@ -290,17 +292,17 @@ void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag, } } -LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message, Arena* arena); +LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message); LIBPROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena, MessageLite* submessage, Arena* submessage_arena); template -T* DuplicateIfNonNull(T* message, Arena* arena) { +T* DuplicateIfNonNull(T* message) { // The casts must be reinterpret_cast<> because T might be a forward-declared // type that the compiler doesn't know is related to MessageLite. - return reinterpret_cast(DuplicateIfNonNullInternal( - reinterpret_cast(message), arena)); + return reinterpret_cast( + DuplicateIfNonNullInternal(reinterpret_cast(message))); } template @@ -313,20 +315,48 @@ T* GetOwnedMessage(Arena* message_arena, T* submessage, submessage_arena)); } -// Returns a message owned by this Arena. This may require Own()ing or -// duplicating the message. -template -T* GetOwnedMessage(T* message, Arena* arena) { - GOOGLE_DCHECK(message); - Arena* message_arena = google::protobuf::Arena::GetArena(message); - if (message_arena == arena) { - return message; - } else if (arena != NULL && message_arena == NULL) { - arena->Own(message); - return message; - } else { - return DuplicateIfNonNull(message, arena); - } +// Hide atomic from the public header and allow easy change to regular int +// on platforms where the atomic might have a perf impact. +class LIBPROTOBUF_EXPORT CachedSize { + public: + int Get() const { return size_.load(std::memory_order_relaxed); } + void Set(int size) { size_.store(size, std::memory_order_relaxed); } + private: + std::atomic size_{0}; +}; + +// SCCInfo represents information of a strongly connected component of +// mutual dependent messages. +struct LIBPROTOBUF_EXPORT SCCInfoBase { + // We use 0 for the Initialized state, because test eax,eax, jnz is smaller + // and is subject to macro fusion. + enum { + kInitialized = 0, // final state + kRunning = 1, + kUninitialized = -1, // initial state + }; + std::atomic visit_status; + int num_deps; + void (*init_func)(); + // This is followed by an array of num_deps + // const SCCInfoBase* deps[]; +}; + +template +struct SCCInfo { + SCCInfoBase base; + // Semantically this is const SCCInfo* which is is a templated type. + // The obvious inheriting from SCCInfoBase mucks with struct initialization. + // Attempts showed the compiler was generating dynamic initialization code. + // Zero length arrays produce warnings with MSVC. + SCCInfoBase* deps[N ? N : 1]; +}; + +LIBPROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc); + +inline void InitSCC(SCCInfoBase* scc) { + auto status = scc->visit_status.load(std::memory_order_acquire); + if (GOOGLE_PREDICT_FALSE(status != SCCInfoBase::kInitialized)) InitSCCImpl(scc); } } // namespace internal diff --git a/src/google/protobuf/implicit_weak_message.cc b/src/google/protobuf/implicit_weak_message.cc index 0dd126befc..7a1d4446bf 100644 --- a/src/google/protobuf/implicit_weak_message.cc +++ b/src/google/protobuf/implicit_weak_message.cc @@ -30,6 +30,7 @@ #include +#include #include #include @@ -37,15 +38,26 @@ namespace google { namespace protobuf { namespace internal { -::google::protobuf::internal::ExplicitlyConstructed - implicit_weak_message_default_instance; - bool ImplicitWeakMessage::MergePartialFromCodedStream(io::CodedInputStream* input) { io::StringOutputStream string_stream(&data_); io::CodedOutputStream coded_stream(&string_stream, false); return WireFormatLite::SkipMessage(input, &coded_stream); } +::google::protobuf::internal::ExplicitlyConstructed + implicit_weak_message_default_instance; +GOOGLE_PROTOBUF_DECLARE_ONCE(implicit_weak_message_once_init_); + +void InitImplicitWeakMessageDefaultInstance() { + implicit_weak_message_default_instance.DefaultConstruct(); +} + +const ImplicitWeakMessage* ImplicitWeakMessage::default_instance() { + ::google::protobuf::GoogleOnceInit(&implicit_weak_message_once_init_, + &InitImplicitWeakMessageDefaultInstance); + return &implicit_weak_message_default_instance.get(); +} + } // namespace internal } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h index a822172e0f..3279bd1777 100644 --- a/src/google/protobuf/implicit_weak_message.h +++ b/src/google/protobuf/implicit_weak_message.h @@ -50,6 +50,8 @@ class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite { ImplicitWeakMessage() : arena_(NULL) {} explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {} + static const ImplicitWeakMessage* default_instance(); + string GetTypeName() const { return ""; } MessageLite* New() const { return new ImplicitWeakMessage; } @@ -91,9 +93,7 @@ class ImplicitWeakTypeHandler { public: typedef ImplicitWeakType Type; typedef ::google::protobuf::MessageLite WeakType; -#if LANG_CXX11 static const bool Moveable = false; -#endif // With implicit weak fields, we need separate NewFromPrototype and // NewFromPrototypeWeak functions. The former is used when we want to create a @@ -128,9 +128,6 @@ class ImplicitWeakTypeHandler { } }; -extern ::google::protobuf::internal::ExplicitlyConstructed - implicit_weak_message_default_instance; - } // namespace internal } // namespace protobuf diff --git a/src/google/protobuf/inlined_string_field.h b/src/google/protobuf/inlined_string_field.h new file mode 100644 index 0000000000..95d4687be3 --- /dev/null +++ b/src/google/protobuf/inlined_string_field.h @@ -0,0 +1,271 @@ +// 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_INLINED_STRING_FIELD_H__ +#define GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ + +#include + +#include +#include + +namespace google { +namespace protobuf { + +class Arena; + +namespace internal { + +// InlinedStringField wraps a ::std::string instance and exposes an API similar to +// ArenaStringPtr's wrapping of a ::std::string* instance. As ::std::string is never +// allocated on the Arena, we expose only the *NoArena methods of +// ArenaStringPtr. +// +// default_value parameters are taken for consistency with ArenaStringPtr, but +// are not used for most methods. With inlining, these should be removed from +// the generated binary. +class LIBPROTOBUF_EXPORT InlinedStringField { + public: + InlinedStringField() + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + explicit InlinedStringField(const ::std::string& default_value); + + void AssignWithDefault(const ::std::string* default_value, + const InlinedStringField& from) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void ClearToEmpty(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearToEmptyNoArena(default_value); + } + void ClearNonDefaultToEmpty() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearNonDefaultToEmptyNoArena(); + } + void ClearToEmptyNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearNonDefaultToEmptyNoArena(); + } + void ClearNonDefaultToEmptyNoArena() + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void ClearToDefault(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + ClearToDefaultNoArena(default_value); + } + void ClearToDefaultNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void Destroy(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + DestroyNoArena(default_value); + } + void DestroyNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + const ::std::string& Get() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + return GetNoArena(); + } + const ::std::string& GetNoArena() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + ::std::string* Mutable(const ::std::string* default_value, Arena* arena) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + return MutableNoArena(default_value); + } + ::std::string* MutableNoArena(const ::std::string* default_value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + ::std::string* Release(const ::std::string* default_value, Arena* arena) { + return ReleaseNoArena(default_value); + } + ::std::string* ReleaseNonDefault(const ::std::string* default_value, Arena* arena) { + return ReleaseNonDefaultNoArena(default_value); + } + ::std::string* ReleaseNoArena(const ::std::string* default_value) { + return ReleaseNonDefaultNoArena(default_value); + } + ::std::string* ReleaseNonDefaultNoArena(const ::std::string* default_value); + + void Set(const ::std::string* default_value, + StringPiece value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetLite(const ::std::string* default_value, + StringPiece value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetNoArena(const ::std::string* default_value, + StringPiece value) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + + void Set(const ::std::string* default_value, + const ::std::string& value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetLite(const ::std::string* default_value, + const ::std::string& value, + Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { + SetNoArena(default_value, value); + } + void SetNoArena(const ::std::string* default_value, + const ::std::string& value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + +#if LANG_CXX11 + void SetNoArena(const ::std::string* default_value, + ::std::string&& value) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; +#endif + void SetAllocated(const ::std::string* default_value, + ::std::string* value, + Arena* arena) { + SetAllocatedNoArena(default_value, value); + } + void SetAllocatedNoArena(const ::std::string* default_value, + ::std::string* value); + void Swap(InlinedStringField* from) + GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE; + ::std::string* UnsafeMutablePointer(); + void UnsafeSetDefault(const ::std::string* default_value); + ::std::string* UnsafeArenaRelease(const ::std::string* default_value, Arena* arena); + void UnsafeArenaSetAllocated( + const ::std::string* default_value, ::std::string* value, Arena* arena); + + bool IsDefault(const ::std::string* default_value) { + return false; + } + private: + ::std::string value_; +}; + +inline InlinedStringField::InlinedStringField() {} + +inline InlinedStringField::InlinedStringField(const ::std::string& default_value) : + value_(default_value) {} + +inline void InlinedStringField::AssignWithDefault( + const ::std::string* default_value, const InlinedStringField& from) { + value_ = from.value_; +} + +inline const ::std::string& InlinedStringField::GetNoArena() const { + return value_; +} + +inline ::std::string* InlinedStringField::MutableNoArena(const ::std::string*) { + return &value_; +} + +inline void InlinedStringField::SetAllocatedNoArena( + const ::std::string* default_value, ::std::string* value) { + if (value == NULL) { + value_.assign(*default_value); + } else { +#if LANG_CXX11 + value_.assign(std::move(*value)); +#else + value_.swap(*value); +#endif + delete value; + } +} + +inline void InlinedStringField::DestroyNoArena(const ::std::string*) { + // This is invoked from the generated message's ArenaDtor, which is used to + // clean up objects not allocated on the Arena. + this->~InlinedStringField(); +} + +inline void InlinedStringField::ClearNonDefaultToEmptyNoArena() { + value_.clear(); +} + +inline void InlinedStringField::ClearToDefaultNoArena( + const ::std::string* default_value) { + value_.assign(*default_value); +} + +inline ::std::string* InlinedStringField::ReleaseNonDefaultNoArena( + const ::std::string* default_value) { + ::std::string* released = new ::std::string(*default_value); + value_.swap(*released); + return released; +} + +inline void InlinedStringField::SetNoArena( + const ::std::string* default_value, StringPiece value) { + value_.assign(value.data(), value.length()); +} + +inline void InlinedStringField::SetNoArena( + const ::std::string* default_value, const ::std::string& value) { + value_.assign(value); +} + +#if LANG_CXX11 +inline void InlinedStringField::SetNoArena( + const ::std::string* default_value, ::std::string&& value) { + value_.assign(std::move(value)); +} +#endif + +inline void InlinedStringField::Swap(InlinedStringField* from) { + value_.swap(from->value_); +} + +inline ::std::string* InlinedStringField::UnsafeMutablePointer() { + return &value_; +} + +inline void InlinedStringField::UnsafeSetDefault( + const ::std::string* default_value) { + value_.assign(*default_value); +} + +inline ::std::string* InlinedStringField::UnsafeArenaRelease( + const ::std::string* default_value, Arena* arena) { + return ReleaseNoArena(default_value); +} + +inline void InlinedStringField::UnsafeArenaSetAllocated( + const ::std::string* default_value, ::std::string* value, Arena* arena) { + if (value == NULL) { + value_.assign(*default_value); + } else { + value_.assign(*value); + } +} + +} // namespace internal +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__ diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc index d3bc7c6dc8..0851ff0cb6 100644 --- a/src/google/protobuf/io/coded_stream.cc +++ b/src/google/protobuf/io/coded_stream.cc @@ -217,8 +217,12 @@ bool CodedInputStream::SkipFallback(int count, int original_buffer_size) { return false; } + if (!input_->Skip(count)) { + total_bytes_read_ = input_->ByteCount(); + return false; + } total_bytes_read_ += count; - return input_->Skip(count); + return true; } bool CodedInputStream::GetDirectBufferPointer(const void** data, int* size) { @@ -615,23 +619,11 @@ bool CodedInputStream::Refresh() { // CodedOutputStream ================================================= -google::protobuf::internal::AtomicWord CodedOutputStream::default_serialization_deterministic_ = 0; +std::atomic CodedOutputStream::default_serialization_deterministic_{ + false}; CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output) - : output_(output), - buffer_(NULL), - buffer_size_(0), - total_bytes_(0), - had_error_(false), - aliasing_enabled_(false), - serialization_deterministic_is_overridden_(false) { - // Eagerly Refresh() so buffer space is immediately available. - Refresh(); - // The Refresh() may have failed. If the client doesn't write any data, - // though, don't consider this an error. If the client does write data, then - // another Refresh() will be attempted and it will set the error once again. - had_error_ = false; -} + : CodedOutputStream(output, true) {} CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output, bool do_eager_refresh) @@ -641,7 +633,7 @@ CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output, total_bytes_(0), had_error_(false), aliasing_enabled_(false), - serialization_deterministic_is_overridden_(false) { + is_serialization_deterministic_(IsDefaultSerializationDeterministic()) { if (do_eager_refresh) { // Eagerly Refresh() so buffer space is immediately available. Refresh(); diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h index ec85147b62..9dad1c6139 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h @@ -110,6 +110,7 @@ #define GOOGLE_PROTOBUF_IO_CODED_STREAM_H__ #include +#include #include #include #include @@ -131,7 +132,6 @@ #define PROTOBUF_LITTLE_ENDIAN 1 #endif #endif -#include #include #include #include @@ -829,7 +829,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // canonicalization specification and implement the serializer using // reflection APIs rather than relying on this API. // - // If determinisitc serialization is requested, the serializer will + // If deterministic serialization is requested, the serializer will // sort map entries by keys in lexicographical order or numerical order. // (This is an implementation detail and may subject to change.) // @@ -840,21 +840,18 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // Otherwise, SetSerializationDeterministic has been called, and the last // value passed to it is all that matters. void SetSerializationDeterministic(bool value) { - serialization_deterministic_is_overridden_ = true; - serialization_deterministic_override_ = value; + is_serialization_deterministic_ = value; } // See above. Also, note that users of this CodedOutputStream may need to // call IsSerializationDeterministic() to serialize in the intended way. This // CodedOutputStream cannot enforce a desire for deterministic serialization // by itself. bool IsSerializationDeterministic() const { - return serialization_deterministic_is_overridden_ ? - serialization_deterministic_override_ : - IsDefaultSerializationDeterministic(); + return is_serialization_deterministic_; } static bool IsDefaultSerializationDeterministic() { - return google::protobuf::internal::NoBarrier_Load(&default_serialization_deterministic_); + return default_serialization_deterministic_.load(std::memory_order_relaxed); } private: @@ -866,12 +863,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { int total_bytes_; // Sum of sizes of all buffers seen so far. bool had_error_; // Whether an error occurred during output. bool aliasing_enabled_; // See EnableAliasing(). - // See SetSerializationDeterministic() regarding these three fields. - bool serialization_deterministic_is_overridden_; - bool serialization_deterministic_override_; - // Conceptually, default_serialization_deterministic_ is an atomic bool. - // TODO(haberman): replace with std::atomic when we move to C++11. - static google::protobuf::internal::AtomicWord default_serialization_deterministic_; + bool is_serialization_deterministic_; + static std::atomic default_serialization_deterministic_; // Advance the buffer by a given number of bytes. void Advance(int amount); @@ -898,7 +891,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream { // thread has done so. friend void ::google::protobuf::internal::MapTestForceDeterministic(); static void SetDefaultSerializationDeterministic() { - google::protobuf::internal::NoBarrier_Store(&default_serialization_deterministic_, 1); + default_serialization_deterministic_.store(true, std::memory_order_relaxed); } }; diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc index 96f91ae91c..1c8d327260 100644 --- a/src/google/protobuf/io/coded_stream_unittest.cc +++ b/src/google/protobuf/io/coded_stream_unittest.cc @@ -35,9 +35,6 @@ // This file contains tests and benchmarks. #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -737,7 +734,7 @@ TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnStack) { } TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnHeap) { - google::protobuf::scoped_array buffer(new uint8[8]); + std::unique_ptr buffer(new uint8[8]); CodedInputStream coded_input(buffer.get(), 8); string str; EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); diff --git a/src/google/protobuf/io/zero_copy_stream_impl_lite.h b/src/google/protobuf/io/zero_copy_stream_impl_lite.h index ab0fd5ac24..29f63bf04a 100644 --- a/src/google/protobuf/io/zero_copy_stream_impl_lite.h +++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.h @@ -45,9 +45,6 @@ #define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -239,7 +236,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream // Data is read into this buffer. It may be NULL if no buffer is currently // in use. Otherwise, it points to an array of size buffer_size_. - google::protobuf::scoped_array buffer_; + std::unique_ptr buffer_; const int buffer_size_; // Number of valid bytes currently in the buffer (i.e. the size last @@ -328,7 +325,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea // Data is written from this buffer. It may be NULL if no buffer is // currently in use. Otherwise, it points to an array of size buffer_size_. - google::protobuf::scoped_array buffer_; + std::unique_ptr buffer_; const int buffer_size_; // Number of valid bytes currently in the buffer (i.e. the size last diff --git a/src/google/protobuf/io/zero_copy_stream_unittest.cc b/src/google/protobuf/io/zero_copy_stream_unittest.cc index 91792f1808..08de8cb1ce 100644 --- a/src/google/protobuf/io/zero_copy_stream_unittest.cc +++ b/src/google/protobuf/io/zero_copy_stream_unittest.cc @@ -56,9 +56,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -206,7 +203,7 @@ void IoTest::WriteString(ZeroCopyOutputStream* output, const string& str) { } void IoTest::ReadString(ZeroCopyInputStream* input, const string& str) { - google::protobuf::scoped_array buffer(new char[str.size() + 1]); + std::unique_ptr buffer(new char[str.size() + 1]); buffer[str.size()] = '\0'; EXPECT_EQ(ReadFromInput(input, buffer.get(), str.size()), str.size()); EXPECT_STREQ(str.c_str(), buffer.get()); diff --git a/src/google/protobuf/lite_arena_unittest.cc b/src/google/protobuf/lite_arena_unittest.cc index dadaffb619..3e88314d61 100644 --- a/src/google/protobuf/lite_arena_unittest.cc +++ b/src/google/protobuf/lite_arena_unittest.cc @@ -30,7 +30,6 @@ #include #include -#include #include namespace google { @@ -49,7 +48,7 @@ class LiteArenaTest : public testing::Test { google::protobuf::Arena::CreateArray(arena_.get(), 1); } - google::protobuf::scoped_ptr arena_; + std::unique_ptr arena_; }; TEST_F(LiteArenaTest, MapNoHeapAllocation) { diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc index d66939630b..b42a7b1466 100644 --- a/src/google/protobuf/lite_unittest.cc +++ b/src/google/protobuf/lite_unittest.cc @@ -621,7 +621,7 @@ TEST(Lite, AllLite28) { 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* 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)); @@ -1003,3 +1003,34 @@ TEST(Lite, AllLite45) { EXPECT_EQ(serialized.substr(0, 2), data); EXPECT_EQ(serialized.substr(2), data); } + +// The following two tests check for wire compatibility between packed and +// unpacked repeated fields. There used to be a bug in the generated parsing +// code that caused us to calculate the highest possible tag number without +// taking into account that a repeated field might not be in the packed (or +// unpacked) state we expect. These tests specifically check for that issue by +// making sure we can parse repeated fields when the tag is higher than we would +// expect. +TEST(Lite, AllLite46) { + protobuf_unittest::PackedInt32 packed; + packed.add_repeated_int32(42); + string serialized; + ASSERT_TRUE(packed.SerializeToString(&serialized)); + + protobuf_unittest::NonPackedInt32 non_packed; + ASSERT_TRUE(non_packed.ParseFromString(serialized)); + ASSERT_EQ(1, non_packed.repeated_int32_size()); + EXPECT_EQ(42, non_packed.repeated_int32(0)); +} + +TEST(Lite, AllLite47) { + protobuf_unittest::NonPackedFixed32 non_packed; + non_packed.add_repeated_fixed32(42); + string serialized; + ASSERT_TRUE(non_packed.SerializeToString(&serialized)); + + protobuf_unittest::PackedFixed32 packed; + ASSERT_TRUE(packed.ParseFromString(serialized)); + ASSERT_EQ(1, packed.repeated_fixed32_size()); + EXPECT_EQ(42, packed.repeated_fixed32(0)); +} diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h index a75fb786e0..6463ac2e02 100644 --- a/src/google/protobuf/map.h +++ b/src/google/protobuf/map.h @@ -37,6 +37,7 @@ #ifndef GOOGLE_PROTOBUF_MAP_H__ #define GOOGLE_PROTOBUF_MAP_H__ +#include #include #include // To support Visual Studio 2008 #include @@ -48,10 +49,6 @@ #include #include -#if LANG_CXX11 -#include -#endif - namespace google { namespace protobuf { @@ -146,7 +143,6 @@ class Map { insert(other.begin(), other.end()); } -#if LANG_CXX11 Map(Map&& other) noexcept : Map() { if (other.arena_) { *this = other; @@ -164,7 +160,6 @@ class Map { } return *this; } -#endif template Map(const InputIt& first, const InputIt& last) @@ -1117,11 +1112,9 @@ class Map { } } } -#if LANG_CXX11 void insert(std::initializer_list values) { insert(values.begin(), values.end()); } -#endif // Erase and clear size_type erase(const key_type& key) { diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h index dc6ec9177e..aa8ff39016 100644 --- a/src/google/protobuf/map_entry_lite.h +++ b/src/google/protobuf/map_entry_lite.h @@ -33,6 +33,7 @@ #include +#include #include #include #include @@ -431,7 +432,7 @@ class MapEntryImpl : public Base { Value* value_ptr_; // On the fast path entry_ is not used. And, when entry_ is used, it's set // to mf_->NewEntry(), so in the arena case we must call entry_.release. - google::protobuf::scoped_ptr entry_; + std::unique_ptr entry_; }; protected: @@ -603,7 +604,7 @@ template <> struct FromHelper { static ArenaStringPtr From(const string& x) { ArenaStringPtr res; - TaggedPtr< ::std::string> ptr; + TaggedPtr<::std::string> ptr; ptr.Set(const_cast(&x)); res.UnsafeSetTaggedPointer(ptr); return res; @@ -613,7 +614,7 @@ template <> struct FromHelper { static ArenaStringPtr From(const string& x) { ArenaStringPtr res; - TaggedPtr< ::std::string> ptr; + TaggedPtr<::std::string> ptr; ptr.Set(const_cast(&x)); res.UnsafeSetTaggedPointer(ptr); return res; diff --git a/src/google/protobuf/map_field.cc b/src/google/protobuf/map_field.cc index ec4f83e1b2..ac29c7e952 100644 --- a/src/google/protobuf/map_field.cc +++ b/src/google/protobuf/map_field.cc @@ -43,14 +43,14 @@ MapFieldBase::~MapFieldBase() { const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const { SyncRepeatedFieldWithMap(); - return *reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + return *reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( repeated_field_); } RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() { SyncRepeatedFieldWithMap(); SetRepeatedDirty(); - return reinterpret_cast< ::google::protobuf::internal::RepeatedPtrFieldBase*>( + return reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>( repeated_field_); } @@ -72,29 +72,39 @@ size_t MapFieldBase::SpaceUsedExcludingSelfNoLock() const { bool MapFieldBase::IsMapValid() const { // "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get // executed before state_ is checked. - Atomic32 state = google::protobuf::internal::Acquire_Load(&state_); + int state = state_.load(std::memory_order_acquire); return state != STATE_MODIFIED_REPEATED; } -void MapFieldBase::SetMapDirty() { state_ = STATE_MODIFIED_MAP; } +bool MapFieldBase::IsRepeatedFieldValid() const { + int state = state_.load(std::memory_order_acquire); + return state != STATE_MODIFIED_MAP; +} + +void MapFieldBase::SetMapDirty() { + // These are called by (non-const) mutator functions. So by our API it's the + // callers responsibility to have these calls properly ordered. + state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed); +} -void MapFieldBase::SetRepeatedDirty() { state_ = STATE_MODIFIED_REPEATED; } +void MapFieldBase::SetRepeatedDirty() { + // These are called by (non-const) mutator functions. So by our API it's the + // callers responsibility to have these calls properly ordered. + state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed); +} void* MapFieldBase::MutableRepeatedPtrField() const { return repeated_field_; } void MapFieldBase::SyncRepeatedFieldWithMap() const { - // "Acquire" insures the operation after SyncRepeatedFieldWithMap won't get - // executed before state_ is checked. - Atomic32 state = google::protobuf::internal::Acquire_Load(&state_); - if (state == STATE_MODIFIED_MAP) { + // acquire here matches with release below to ensure that we can only see a + // value of CLEAN after all previous changes have been synced. + if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_MAP) { mutex_.Lock(); // Double check state, because another thread may have seen the same state // and done the synchronization before the current thread. - if (state_ == STATE_MODIFIED_MAP) { + if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_MAP) { SyncRepeatedFieldWithMapNoLock(); - // "Release" insures state_ can only be changed "after" - // SyncRepeatedFieldWithMapNoLock is finished. - google::protobuf::internal::Release_Store(&state_, CLEAN); + state_.store(CLEAN, std::memory_order_release); } mutex_.Unlock(); } @@ -107,18 +117,15 @@ void MapFieldBase::SyncRepeatedFieldWithMapNoLock() const { } void MapFieldBase::SyncMapWithRepeatedField() const { - // "Acquire" insures the operation after SyncMapWithRepeatedField won't get - // executed before state_ is checked. - Atomic32 state = google::protobuf::internal::Acquire_Load(&state_); - if (state == STATE_MODIFIED_REPEATED) { + // acquire here matches with release below to ensure that we can only see a + // value of CLEAN after all previous changes have been synced. + if (state_.load(std::memory_order_acquire) == STATE_MODIFIED_REPEATED) { mutex_.Lock(); // Double check state, because another thread may have seen the same state // and done the synchronization before the current thread. - if (state_ == STATE_MODIFIED_REPEATED) { + if (state_.load(std::memory_order_relaxed) == STATE_MODIFIED_REPEATED) { SyncMapWithRepeatedFieldNoLock(); - // "Release" insures state_ can only be changed "after" - // SyncRepeatedFieldWithMapNoLock is finished. - google::protobuf::internal::Release_Store(&state_, CLEAN); + state_.store(CLEAN, std::memory_order_release); } mutex_.Unlock(); } diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h index 6c75a6da40..494401e129 100644 --- a/src/google/protobuf/map_field.h +++ b/src/google/protobuf/map_field.h @@ -31,7 +31,8 @@ #ifndef GOOGLE_PROTOBUF_MAP_FIELD_H__ #define GOOGLE_PROTOBUF_MAP_FIELD_H__ -#include +#include + #include #include #include @@ -86,6 +87,8 @@ class LIBPROTOBUF_EXPORT MapFieldBase { virtual bool ContainsMapKey(const MapKey& map_key) const = 0; virtual bool InsertOrLookupMapValue( const MapKey& map_key, MapValueRef* val) = 0; + // Returns whether changes to the map are reflected in the repeated field. + bool IsRepeatedFieldValid() const; // Insures operations after won't get executed before calling this. bool IsMapValid() const; virtual bool DeleteMapValue(const MapKey& map_key) = 0; @@ -140,9 +143,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase { mutable Mutex mutex_; // The thread to synchronize map and repeated field // needs to get lock first; - mutable volatile Atomic32 state_; // 0: STATE_MODIFIED_MAP - // 1: STATE_MODIFIED_REPEATED - // 2: CLEAN + mutable std::atomic state_; private: friend class ContendedMapCleanTest; @@ -814,13 +815,13 @@ struct hash { case google::protobuf::FieldDescriptor::CPPTYPE_STRING: return hash()(map_key.GetStringValue()); case google::protobuf::FieldDescriptor::CPPTYPE_INT64: - return hash< ::google::protobuf::int64>()(map_key.GetInt64Value()); + return hash<::google::protobuf::int64>()(map_key.GetInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_INT32: - return hash< ::google::protobuf::int32>()(map_key.GetInt32Value()); + return hash<::google::protobuf::int32>()(map_key.GetInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: - return hash< ::google::protobuf::uint64>()(map_key.GetUInt64Value()); + return hash<::google::protobuf::uint64>()(map_key.GetUInt64Value()); case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: - return hash< ::google::protobuf::uint32>()(map_key.GetUInt32Value()); + return hash<::google::protobuf::uint32>()(map_key.GetUInt32Value()); case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: return hash()(map_key.GetBoolValue()); } diff --git a/src/google/protobuf/map_field_inl.h b/src/google/protobuf/map_field_inl.h index e317b5ed42..d0517792f0 100644 --- a/src/google/protobuf/map_field_inl.h +++ b/src/google/protobuf/map_field_inl.h @@ -32,10 +32,8 @@ #define GOOGLE_PROTOBUF_MAP_FIELD_INL_H__ #include -#ifndef _SHARED_PTR_H -#include -#endif +#include #include #include #include @@ -254,7 +252,11 @@ void MapField::Swap(MapField* other) { std::swap(this->MapFieldBase::repeated_field_, other->repeated_field_); impl_.Swap(&other->impl_); - std::swap(this->MapFieldBase::state_, other->state_); + // a relaxed swap of the atomic + auto other_state = other->state_.load(std::memory_order_relaxed); + auto this_state = this->MapFieldBase::state_.load(std::memory_order_relaxed); + other->state_.store(this_state, std::memory_order_relaxed); + this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed); } template #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -71,10 +68,18 @@ class MapFieldBaseStub : public MapFieldBase { RepeatedPtrField* InternalRepeatedField() { return repeated_field_; } - bool IsMapClean() { return state_ != 0; } - bool IsRepeatedClean() { return state_ != 1; } - void SetMapDirty() { state_ = 0; } - void SetRepeatedDirty() { state_ = 1; } + bool IsMapClean() { + return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_MAP; + } + bool IsRepeatedClean() { + return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_REPEATED; + } + void SetMapDirty() { + state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed); + } + void SetRepeatedDirty() { + state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed); + } bool ContainsMapKey(const MapKey& map_key) const { return false; } @@ -124,7 +129,7 @@ class MapFieldBasePrimitiveTest : public ::testing::Test { EXPECT_EQ(2, map_->size()); } - google::protobuf::scoped_ptr map_field_; + std::unique_ptr map_field_; MapFieldBase* map_field_base_; Map* map_; const Descriptor* map_descriptor_; @@ -291,7 +296,7 @@ class MapFieldStateTest } } - google::protobuf::scoped_ptr map_field_; + std::unique_ptr map_field_; MapFieldBase* map_field_base_; State state_; }; diff --git a/src/google/protobuf/map_test.cc b/src/google/protobuf/map_test.cc index d59f92d24c..829a60ff73 100644 --- a/src/google/protobuf/map_test.cc +++ b/src/google/protobuf/map_test.cc @@ -40,9 +40,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include #include @@ -170,7 +167,7 @@ class MapImplTest : public ::testing::Test { EXPECT_EQ(value, const_it_copy->second); } - google::protobuf::scoped_ptr > map_ptr_; + std::unique_ptr > map_ptr_; Map& map_; const Map& const_map_; }; @@ -676,7 +673,6 @@ TEST_F(MapImplTest, InsertByIterator) { ExpectElements(map1); } -#if LANG_CXX11 TEST_F(MapImplTest, InsertByInitializerList) { map_.insert({{1, 100}, {2, 200}}); ExpectElements({{1, 100}, {2, 200}}); @@ -684,7 +680,6 @@ TEST_F(MapImplTest, InsertByInitializerList) { map_.insert({{2, 201}, {3, 301}}); ExpectElements({{1, 100}, {2, 200}, {3, 301}}); } -#endif TEST_F(MapImplTest, EraseSingleByKey) { int32 key = 0; @@ -1269,19 +1264,19 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) { &message, fd_map_int32_foreign_message); // Get entry default instances - google::protobuf::scoped_ptr entry_int32_int32( + std::unique_ptr entry_int32_int32( MessageFactory::generated_factory() ->GetPrototype(fd_map_int32_int32->message_type()) ->New()); - google::protobuf::scoped_ptr entry_int32_double( + std::unique_ptr entry_int32_double( MessageFactory::generated_factory() ->GetPrototype(fd_map_int32_double->message_type()) ->New()); - google::protobuf::scoped_ptr entry_string_string( + std::unique_ptr entry_string_string( MessageFactory::generated_factory() ->GetPrototype(fd_map_string_string->message_type()) ->New()); - google::protobuf::scoped_ptr entry_int32_foreign_message( + std::unique_ptr entry_int32_foreign_message( MessageFactory::generated_factory() ->GetPrototype(fd_map_int32_foreign_message->message_type()) ->New()); @@ -1819,7 +1814,7 @@ TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) { // Dynamic Message { DynamicMessageFactory factory; - google::protobuf::scoped_ptr message( + std::unique_ptr message( factory.GetPrototype(unittest::TestMap::descriptor())->New()); const Reflection* reflection = message->GetReflection(); const FieldDescriptor* field = @@ -1836,6 +1831,7 @@ TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) { EXPECT_EQ(2, reflection->FieldSize(*message, field)); EXPECT_EQ(1, MapSize(reflection, field, *message)); + EXPECT_EQ(2, reflection->FieldSize(*message, field)); } // Generated Message @@ -2004,7 +2000,7 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessage) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr message1; + std::unique_ptr message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); MapReflectionTester reflection_tester( @@ -2021,7 +2017,7 @@ TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr message1; + std::unique_ptr message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); MapReflectionTester reflection_tester( @@ -2040,7 +2036,7 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) { // Construct a new version of the dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr message1; + std::unique_ptr message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); @@ -2059,7 +2055,7 @@ TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) { // Construct a dynamic message via the factory. DynamicMessageFactory factory; - google::protobuf::scoped_ptr message1; + std::unique_ptr message1; message1.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); @@ -2073,7 +2069,7 @@ TEST(GeneratedMapFieldTest, SyncDynamicMapWithRepeatedField) { MapReflectionTester reflection_tester( unittest::TestMap::descriptor()); DynamicMessageFactory factory; - google::protobuf::scoped_ptr message; + std::unique_ptr message; message.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); reflection_tester.SetMapFieldsViaReflection(message.get()); @@ -2725,7 +2721,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) { // Check that all fields have independent offsets by setting each // one to a unique value then checking that they all still have those // unique values (i.e. they don't stomp each other). - google::protobuf::scoped_ptr message(map_prototype_->New()); + std::unique_ptr message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); reflection_tester.SetMapFieldsViaReflection(message.get()); @@ -2734,7 +2730,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) { TEST_F(MapFieldInDynamicMessageTest, DynamicMapReflection) { // Check that map fields work properly. - google::protobuf::scoped_ptr message(map_prototype_->New()); + std::unique_ptr message(map_prototype_->New()); // Check set functions. MapReflectionTester reflection_tester(map_descriptor_); @@ -2748,7 +2744,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) { // Since we share the implementation with generated messages, we don't need // to test very much here. Just make sure it appears to be working. - google::protobuf::scoped_ptr message(map_prototype_->New()); + std::unique_ptr message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); int initial_space_used = message->SpaceUsed(); @@ -2761,13 +2757,13 @@ TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) { TestRecursiveMapMessage from; (*from.mutable_a())[""]; string data = from.SerializeAsString(); - google::protobuf::scoped_ptr to( + std::unique_ptr to( factory_.GetPrototype(recursive_map_descriptor_)->New()); ASSERT_TRUE(to->ParseFromString(data)); } TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) { - google::protobuf::scoped_ptr message(map_prototype_->New()); + std::unique_ptr message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); reflection_tester.SetMapFieldsViaMapReflection(message.get()); @@ -2798,7 +2794,7 @@ TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) { } TEST_F(MapFieldInDynamicMessageTest, MapEntryReferernceValidAfterSerialize) { - google::protobuf::scoped_ptr message(map_prototype_->New()); + std::unique_ptr message(map_prototype_->New()); MapReflectionTester reflection_tester(map_descriptor_); reflection_tester.SetMapFieldsViaReflection(message.get()); @@ -2967,7 +2963,7 @@ TEST(WireFormatForMapFieldTest, SerializeMap) { TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) { DynamicMessageFactory factory; - google::protobuf::scoped_ptr dynamic_message; + std::unique_ptr dynamic_message; dynamic_message.reset( factory.GetPrototype(unittest::TestMap::descriptor())->New()); MapReflectionTester reflection_tester( @@ -3293,7 +3289,6 @@ TEST(ArenaTest, IsInitialized) { EXPECT_EQ(0, (*message->mutable_map_int32_int32())[0]); } -#if LANG_CXX11 TEST(MoveTest, MoveConstructorWorks) { Map original_map; original_map[42].mutable_optional_nested_message()->set_bb(42); @@ -3329,7 +3324,6 @@ TEST(MoveTest, MoveAssignmentWorks) { EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message()); EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message()); } -#endif } // namespace internal } // namespace protobuf diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc index 42ec033780..810db233ba 100644 --- a/src/google/protobuf/message.cc +++ b/src/google/protobuf/message.cc @@ -38,20 +38,22 @@ #include +#include #include #include #include #include +#include #include #include #include -#include #include #include #include #include #include #include + #include #include #include diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h index fc630b584b..f3d1a58a92 100644 --- a/src/google/protobuf/message.h +++ b/src/google/protobuf/message.h @@ -112,7 +112,7 @@ #include #include -#include +#include #include #include @@ -342,7 +342,7 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite { // // This method remains virtual in case a subclass does not implement // reflection and wants to override the default behavior. - virtual const Reflection* GetReflection() const PROTOBUF_FINAL { + virtual const Reflection* GetReflection() const final { return GetMetadata().reflection; } diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h index 0b2b24b2df..4cbec33081 100644 --- a/src/google/protobuf/message_lite.h +++ b/src/google/protobuf/message_lite.h @@ -43,11 +43,11 @@ #include #include #include +#include #include namespace google { namespace protobuf { -class Arena; template class RepeatedPtrField; namespace io { @@ -60,6 +60,7 @@ namespace internal { class RepeatedPtrFieldBase; class WireFormatLite; +class WeakFieldMap; #ifndef SWIG // We compute sizes as size_t but cache them as int. This function converts a @@ -113,13 +114,7 @@ class ExplicitlyConstructed { get_mutable()->~T(); } -#if LANG_CXX11 - constexpr -#endif - const T& - get() const { - return reinterpret_cast(union_); - } + constexpr const T& get() const { return reinterpret_cast(union_); } T* get_mutable() { return reinterpret_cast(&union_); } private: @@ -133,7 +128,7 @@ class ExplicitlyConstructed { // Default empty string object. Don't use this directly. Instead, call // GetEmptyString() to get the reference. -extern ExplicitlyConstructed< ::std::string> fixed_address_empty_string; +LIBPROTOBUF_EXPORT extern ExplicitlyConstructed<::std::string> fixed_address_empty_string; LIBPROTOBUF_EXPORT extern ProtobufOnceType empty_string_once_init_; LIBPROTOBUF_EXPORT void InitEmptyString(); @@ -274,7 +269,7 @@ class LIBPROTOBUF_EXPORT MessageLite { // Reads a protocol buffer from the stream and merges it into this - // Message. Singular fields read from the input overwrite what is + // Message. Singular fields read from the what is // already in the Message and repeated fields are appended to those // already present. // @@ -399,12 +394,18 @@ class LIBPROTOBUF_EXPORT MessageLite { return repeated; } + template + static T* CreateMaybeMessage(Arena* arena) { + return Arena::CreateMaybeMessage(arena); + } + private: // TODO(gerbens) make this a pure abstract function virtual const void* InternalGetTable() const { return NULL; } friend class internal::WireFormatLite; friend class Message; + friend class internal::WeakFieldMap; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite); }; diff --git a/src/google/protobuf/message_unittest.cc b/src/google/protobuf/message_unittest.cc index a27036e75f..45b46bee86 100644 --- a/src/google/protobuf/message_unittest.cc +++ b/src/google/protobuf/message_unittest.cc @@ -32,542 +32,20 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include - -#include -#include -#include -#ifndef _MSC_VER -#include -#endif -#include -#include - -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#define MESSAGE_TEST_NAME MessageTest +#define MESSAGE_FACTORY_TEST_NAME MessageFactoryTest +#define UNITTEST_PACKAGE_NAME "protobuf_unittest" +#define UNITTEST ::protobuf_unittest +#define UNITTEST_IMPORT ::protobuf_unittest_import + +// Must include after the above macros. +#include +#include +// Make extract script happy. namespace google { namespace protobuf { - -#if defined(_WIN32) -// DO NOT include , instead create functions in io_win32.{h,cc} and import -// them like we do below. -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::open; -#endif - -#ifndef O_BINARY -#ifdef _O_BINARY -#define O_BINARY _O_BINARY -#else -#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. -#endif -#endif - -TEST(MessageTest, SerializeHelpers) { - // TODO(kenton): Test more helpers? They're all two-liners so it seems - // like a waste of time. - - protobuf_unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - std::stringstream stream; - - string str1("foo"); - string str2("bar"); - - EXPECT_TRUE(message.SerializeToString(&str1)); - EXPECT_TRUE(message.AppendToString(&str2)); - EXPECT_TRUE(message.SerializeToOstream(&stream)); - - EXPECT_EQ(str1.size() + 3, str2.size()); - EXPECT_EQ("bar", str2.substr(0, 3)); - // Don't use EXPECT_EQ because we don't want to dump raw binary data to - // stdout. - EXPECT_TRUE(str2.substr(3) == str1); - - // GCC gives some sort of error if we try to just do stream.str() == str1. - string temp = stream.str(); - EXPECT_TRUE(temp == str1); - - EXPECT_TRUE(message.SerializeAsString() == str1); - -} - -TEST(MessageTest, SerializeToBrokenOstream) { - std::ofstream out; - protobuf_unittest::TestAllTypes message; - message.set_optional_int32(123); - - EXPECT_FALSE(message.SerializeToOstream(&out)); -} - -TEST(MessageTest, ParseFromFileDescriptor) { - string filename = TestSourceDir() + - "/google/protobuf/testdata/golden_message"; - int file = open(filename.c_str(), O_RDONLY | O_BINARY); - ASSERT_GE(file, 0); - - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromFileDescriptor(file)); - TestUtil::ExpectAllFieldsSet(message); - - EXPECT_GE(close(file), 0); -} - -TEST(MessageTest, ParsePackedFromFileDescriptor) { - string filename = - TestSourceDir() + - "/google/protobuf/testdata/golden_packed_fields_message"; - int file = open(filename.c_str(), O_RDONLY | O_BINARY); - ASSERT_GE(file, 0); - - protobuf_unittest::TestPackedTypes message; - EXPECT_TRUE(message.ParseFromFileDescriptor(file)); - TestUtil::ExpectPackedFieldsSet(message); - - EXPECT_GE(close(file), 0); -} - -TEST(MessageTest, ParseHelpers) { - // TODO(kenton): Test more helpers? They're all two-liners so it seems - // like a waste of time. - string data; - - { - // Set up. - protobuf_unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - message.SerializeToString(&data); - } - - { - // Test ParseFromString. - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test ParseFromIstream. - protobuf_unittest::TestAllTypes message; - std::stringstream stream(data); - EXPECT_TRUE(message.ParseFromIstream(&stream)); - EXPECT_TRUE(stream.eof()); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test ParseFromBoundedZeroCopyStream. - string data_with_junk(data); - data_with_junk.append("some junk on the end"); - io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size()); - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size())); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if - // EOF is reached before the expected number of bytes. - io::ArrayInputStream stream(data.data(), data.size()); - protobuf_unittest::TestAllTypes message; - EXPECT_FALSE( - message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1)); - } -} - -TEST(MessageTest, ParseFailsIfNotInitialized) { - unittest::TestRequired message; - std::vector errors; - - { - ScopedMemoryLog log; - EXPECT_FALSE(message.ParseFromString("")); - errors = log.GetMessages(ERROR); - } - - ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Can't parse message of type \"protobuf_unittest.TestRequired\" " - "because it is missing required fields: a, b, c", - errors[0]); -} - -TEST(MessageTest, BypassInitializationCheckOnParse) { - unittest::TestRequired message; - io::ArrayInputStream raw_input(NULL, 0); - io::CodedInputStream input(&raw_input); - EXPECT_TRUE(message.MergePartialFromCodedStream(&input)); -} - -TEST(MessageTest, InitializationErrorString) { - unittest::TestRequired message; - EXPECT_EQ("a, b, c", message.InitializationErrorString()); -} - -TEST(MessageTest, DynamicCastToGenerated) { - unittest::TestAllTypes test_all_types; - - google::protobuf::Message* test_all_types_pointer = &test_all_types; - EXPECT_EQ(&test_all_types, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer)); - EXPECT_EQ(NULL, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer)); - - const google::protobuf::Message* test_all_types_pointer_const = &test_all_types; - EXPECT_EQ( - &test_all_types, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer_const)); - EXPECT_EQ( - NULL, - google::protobuf::internal::DynamicCastToGenerated( - test_all_types_pointer_const)); -} - -#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet. - -TEST(MessageTest, SerializeFailsIfNotInitialized) { - unittest::TestRequired message; - string data; - EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)), - "Can't serialize message of type \"protobuf_unittest.TestRequired\" because " - "it is missing required fields: a, b, c"); -} - -TEST(MessageTest, CheckInitialized) { - unittest::TestRequired message; - EXPECT_DEATH(message.CheckInitialized(), - "Message of type \"protobuf_unittest.TestRequired\" is missing required " - "fields: a, b, c"); -} - -#endif // PROTOBUF_HAS_DEATH_TEST - -namespace { -// An input stream that repeats a string's content for a number of times. It -// helps us create a really large input without consuming too much memory. Used -// to test the parsing behavior when the input size exceeds 2G or close to it. -class RepeatedInputStream : public io::ZeroCopyInputStream { - public: - RepeatedInputStream(const string& data, size_t count) - : data_(data), count_(count), position_(0), total_byte_count_(0) {} - - virtual bool Next(const void** data, int* size) { - if (position_ == data_.size()) { - if (--count_ == 0) { - return false; - } - position_ = 0; - } - *data = &data_[position_]; - *size = static_cast(data_.size() - position_); - position_ = data_.size(); - total_byte_count_ += *size; - return true; - } - - virtual void BackUp(int count) { - position_ -= static_cast(count); - total_byte_count_ -= count; - } - - virtual bool Skip(int count) { - while (count > 0) { - const void* data; - int size; - if (!Next(&data, &size)) { - break; - } - if (size >= count) { - BackUp(size - count); - return true; - } else { - count -= size; - } - } - return false; - } - - virtual int64 ByteCount() const { return total_byte_count_; } - - private: - string data_; - size_t count_; // The number of strings that haven't been consuemd. - size_t position_; // Position in the string for the next read. - int64 total_byte_count_; -}; -} // namespace - -TEST(MessageTest, TestParseMessagesCloseTo2G) { - // Create a message with a large string field. - string value = string(64 * 1024 * 1024, 'x'); - protobuf_unittest::TestAllTypes message; - message.set_optional_string(value); - - // Repeat this message in the input stream to make the total input size - // close to 2G. - string data = message.SerializeAsString(); - size_t count = static_cast(kint32max) / data.size(); - RepeatedInputStream input(data, count); - - // The parsing should succeed. - protobuf_unittest::TestAllTypes result; - EXPECT_TRUE(result.ParseFromZeroCopyStream(&input)); - - // When there are multiple occurences of a singulr field, the last one - // should win. - EXPECT_EQ(value, result.optional_string()); -} - -TEST(MessageTest, TestParseMessagesOver2G) { - // Create a message with a large string field. - string value = string(64 * 1024 * 1024, 'x'); - protobuf_unittest::TestAllTypes message; - message.set_optional_string(value); - - // Repeat this message in the input stream to make the total input size - // larger than 2G. - string data = message.SerializeAsString(); - size_t count = static_cast(kint32max) / data.size() + 1; - RepeatedInputStream input(data, count); - - // The parsing should fail. - protobuf_unittest::TestAllTypes result; - EXPECT_FALSE(result.ParseFromZeroCopyStream(&input)); -} - -TEST(MessageTest, BypassInitializationCheckOnSerialize) { - unittest::TestRequired message; - io::ArrayOutputStream raw_output(NULL, 0); - io::CodedOutputStream output(&raw_output); - EXPECT_TRUE(message.SerializePartialToCodedStream(&output)); -} - -TEST(MessageTest, FindInitializationErrors) { - unittest::TestRequired message; - std::vector errors; - message.FindInitializationErrors(&errors); - ASSERT_EQ(3, errors.size()); - EXPECT_EQ("a", errors[0]); - EXPECT_EQ("b", errors[1]); - EXPECT_EQ("c", errors[2]); -} - -TEST(MessageTest, ParseFailsOnInvalidMessageEnd) { - unittest::TestAllTypes message; - - // Control case. - EXPECT_TRUE(message.ParseFromArray("", 0)); - - // The byte is a valid varint, but not a valid tag (zero). - EXPECT_FALSE(message.ParseFromArray("\0", 1)); - - // The byte is a malformed varint. - EXPECT_FALSE(message.ParseFromArray("\200", 1)); - - // The byte is an endgroup tag, but we aren't parsing a group. - EXPECT_FALSE(message.ParseFromArray("\014", 1)); -} - -// Regression test for b/23630858 -TEST(MessageTest, MessageIsStillValidAfterParseFails) { - unittest::TestAllTypes message; - - // 9 0xFFs for the "optional_uint64" field. - string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; - - EXPECT_FALSE(message.ParseFromString(invalid_data)); - message.Clear(); - EXPECT_EQ(0, message.optional_uint64()); - - // invalid data for field "optional_string". Length prefix is 1 but no - // payload. - string invalid_string_data = "\x72\x01"; - { - google::protobuf::Arena arena; - unittest::TestAllTypes* arena_message = - google::protobuf::Arena::CreateMessage(&arena); - EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data)); - arena_message->Clear(); - EXPECT_EQ("", arena_message->optional_string()); - } -} - - -namespace { - -void ExpectMessageMerged(const unittest::TestAllTypes& message) { - EXPECT_EQ(3, message.optional_int32()); - EXPECT_EQ(2, message.optional_int64()); - EXPECT_EQ("hello", message.optional_string()); -} - -void AssignParsingMergeMessages( - unittest::TestAllTypes* msg1, - unittest::TestAllTypes* msg2, - unittest::TestAllTypes* msg3) { - msg1->set_optional_int32(1); - msg2->set_optional_int64(2); - msg3->set_optional_int32(3); - msg3->set_optional_string("hello"); -} - -} // namespace - -// Test that if an optional or required message/group field appears multiple -// times in the input, they need to be merged. -TEST(MessageTest, ParsingMerge) { - unittest::TestParsingMerge::RepeatedFieldsGenerator generator; - unittest::TestAllTypes* msg1; - unittest::TestAllTypes* msg2; - unittest::TestAllTypes* 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); - unittest::TestParsingMerge 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(unittest::TestParsingMerge::optional_ext)); - - // Repeated fields should not be merged. - EXPECT_EQ(3, parsing_merge.repeated_all_types_size()); - EXPECT_EQ(3, parsing_merge.repeatedgroup_size()); - EXPECT_EQ(3, parsing_merge.ExtensionSize( - unittest::TestParsingMerge::repeated_ext)); -} - -TEST(MessageTest, MergeFrom) { - unittest::TestAllTypes source; - unittest::TestAllTypes dest; - - // Optional fields - source.set_optional_int32(1); // only source - source.set_optional_int64(2); // both source and dest - dest.set_optional_int64(3); - dest.set_optional_uint32(4); // only dest - - // Optional fields with defaults - source.set_default_int32(13); // only source - source.set_default_int64(14); // both source and dest - dest.set_default_int64(15); - dest.set_default_uint32(16); // only dest - - // Repeated fields - source.add_repeated_int32(5); // only source - source.add_repeated_int32(6); - source.add_repeated_int64(7); // both source and dest - source.add_repeated_int64(8); - dest.add_repeated_int64(9); - dest.add_repeated_int64(10); - dest.add_repeated_uint32(11); // only dest - dest.add_repeated_uint32(12); - - dest.MergeFrom(source); - - // Optional fields: source overwrites dest if source is specified - EXPECT_EQ(1, dest.optional_int32()); // only source: use source - EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source - EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest - EXPECT_EQ(0, dest.optional_uint64()); // neither: use default - - // Optional fields with defaults - EXPECT_EQ(13, dest.default_int32()); // only source: use source - EXPECT_EQ(14, dest.default_int64()); // source and dest: use source - EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest - EXPECT_EQ(44, dest.default_uint64()); // neither: use default - - // Repeated fields: concatenate source onto the end of dest - ASSERT_EQ(2, dest.repeated_int32_size()); - EXPECT_EQ(5, dest.repeated_int32(0)); - EXPECT_EQ(6, dest.repeated_int32(1)); - ASSERT_EQ(4, dest.repeated_int64_size()); - EXPECT_EQ(9, dest.repeated_int64(0)); - EXPECT_EQ(10, dest.repeated_int64(1)); - EXPECT_EQ(7, dest.repeated_int64(2)); - EXPECT_EQ(8, dest.repeated_int64(3)); - ASSERT_EQ(2, dest.repeated_uint32_size()); - EXPECT_EQ(11, dest.repeated_uint32(0)); - EXPECT_EQ(12, dest.repeated_uint32(1)); - ASSERT_EQ(0, dest.repeated_uint64_size()); -} - -TEST(MessageTest, IsInitialized) { - protobuf_unittest::TestIsInitialized msg; - EXPECT_TRUE(msg.IsInitialized()); - protobuf_unittest::TestIsInitialized::SubMessage* sub_message = msg.mutable_sub_message(); - EXPECT_TRUE(msg.IsInitialized()); - protobuf_unittest::TestIsInitialized::SubMessage::SubGroup* sub_group = sub_message->mutable_subgroup(); - EXPECT_FALSE(msg.IsInitialized()); - sub_group->set_i(1); - EXPECT_TRUE(msg.IsInitialized()); -} - -TEST(MessageFactoryTest, GeneratedFactoryLookup) { - EXPECT_EQ( - MessageFactory::generated_factory()->GetPrototype( - protobuf_unittest::TestAllTypes::descriptor()), - &protobuf_unittest::TestAllTypes::default_instance()); -} - -TEST(MessageFactoryTest, GeneratedFactoryUnknownType) { - // Construct a new descriptor. - DescriptorPool pool; - FileDescriptorProto file; - file.set_name("foo.proto"); - file.add_message_type()->set_name("Foo"); - const Descriptor* descriptor = pool.BuildFile(file)->message_type(0); - - // Trying to construct it should return NULL. - EXPECT_TRUE( - MessageFactory::generated_factory()->GetPrototype(descriptor) == NULL); -} - - } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/message_unittest.inc b/src/google/protobuf/message_unittest.inc new file mode 100644 index 0000000000..6ffdcce09a --- /dev/null +++ b/src/google/protobuf/message_unittest.inc @@ -0,0 +1,577 @@ +// 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) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// This file needs to be included as .inc as it depends on certain macros being +// defined prior to its inclusion. + +#include + +#include +#include +#include +#ifndef _MSC_VER +#include +#endif +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace google { +namespace protobuf { + +#if defined(_WIN32) +// DO NOT include , instead create functions in io_win32.{h,cc} and import +// them like we do below. +using google::protobuf::internal::win32::close; +using google::protobuf::internal::win32::open; +#endif + +#ifndef O_BINARY +#ifdef _O_BINARY +#define O_BINARY _O_BINARY +#else +#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. +#endif +#endif + +TEST(MESSAGE_TEST_NAME, SerializeHelpers) { + // TODO(kenton): Test more helpers? They're all two-liners so it seems + // like a waste of time. + + UNITTEST::TestAllTypes message; + TestUtil::SetAllFields(&message); + std::stringstream stream; + + string str1("foo"); + string str2("bar"); + + EXPECT_TRUE(message.SerializeToString(&str1)); + EXPECT_TRUE(message.AppendToString(&str2)); + EXPECT_TRUE(message.SerializeToOstream(&stream)); + + EXPECT_EQ(str1.size() + 3, str2.size()); + EXPECT_EQ("bar", str2.substr(0, 3)); + // Don't use EXPECT_EQ because we don't want to dump raw binary data to + // stdout. + EXPECT_TRUE(str2.substr(3) == str1); + + // GCC gives some sort of error if we try to just do stream.str() == str1. + string temp = stream.str(); + EXPECT_TRUE(temp == str1); + + EXPECT_TRUE(message.SerializeAsString() == str1); + +} + +TEST(MESSAGE_TEST_NAME, SerializeToBrokenOstream) { + std::ofstream out; + UNITTEST::TestAllTypes message; + message.set_optional_int32(123); + + EXPECT_FALSE(message.SerializeToOstream(&out)); +} + +TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) { + string filename = TestSourceDir() + + "/google/protobuf/testdata/golden_message"; + int file = open(filename.c_str(), O_RDONLY | O_BINARY); + ASSERT_GE(file, 0); + + UNITTEST::TestAllTypes message; + EXPECT_TRUE(message.ParseFromFileDescriptor(file)); + TestUtil::ExpectAllFieldsSet(message); + + EXPECT_GE(close(file), 0); +} + +TEST(MESSAGE_TEST_NAME, ParsePackedFromFileDescriptor) { + string filename = + TestSourceDir() + + "/google/protobuf/testdata/golden_packed_fields_message"; + int file = open(filename.c_str(), O_RDONLY | O_BINARY); + ASSERT_GE(file, 0); + + UNITTEST::TestPackedTypes message; + EXPECT_TRUE(message.ParseFromFileDescriptor(file)); + TestUtil::ExpectPackedFieldsSet(message); + + EXPECT_GE(close(file), 0); +} + +TEST(MESSAGE_TEST_NAME, ParseHelpers) { + // TODO(kenton): Test more helpers? They're all two-liners so it seems + // like a waste of time. + string data; + + { + // Set up. + UNITTEST::TestAllTypes message; + TestUtil::SetAllFields(&message); + message.SerializeToString(&data); + } + + { + // Test ParseFromString. + UNITTEST::TestAllTypes message; + EXPECT_TRUE(message.ParseFromString(data)); + TestUtil::ExpectAllFieldsSet(message); + } + + { + // Test ParseFromIstream. + UNITTEST::TestAllTypes message; + std::stringstream stream(data); + EXPECT_TRUE(message.ParseFromIstream(&stream)); + EXPECT_TRUE(stream.eof()); + TestUtil::ExpectAllFieldsSet(message); + } + + { + // Test ParseFromBoundedZeroCopyStream. + string data_with_junk(data); + data_with_junk.append("some junk on the end"); + io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size()); + UNITTEST::TestAllTypes message; + EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size())); + TestUtil::ExpectAllFieldsSet(message); + } + + { + // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if + // EOF is reached before the expected number of bytes. + io::ArrayInputStream stream(data.data(), data.size()); + UNITTEST::TestAllTypes message; + EXPECT_FALSE( + message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1)); + } +} + +TEST(MESSAGE_TEST_NAME, ParseFailsIfNotInitialized) { + UNITTEST::TestRequired message; + std::vector errors; + + { + ScopedMemoryLog log; + EXPECT_FALSE(message.ParseFromString("")); + errors = log.GetMessages(ERROR); + } + + ASSERT_EQ(1, errors.size()); + EXPECT_EQ( + "Can't parse message of type \"" + string(UNITTEST_PACKAGE_NAME) + + ".TestRequired\" because it is missing required fields: a, b, c", + errors[0]); +} + +TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnParse) { + UNITTEST::TestRequired message; + io::ArrayInputStream raw_input(nullptr, 0); + io::CodedInputStream input(&raw_input); + EXPECT_TRUE(message.MergePartialFromCodedStream(&input)); +} + +TEST(MESSAGE_TEST_NAME, InitializationErrorString) { + UNITTEST::TestRequired message; + EXPECT_EQ("a, b, c", message.InitializationErrorString()); +} + +TEST(MESSAGE_TEST_NAME, DynamicCastToGenerated) { + UNITTEST::TestAllTypes test_all_types; + + google::protobuf::Message* test_all_types_pointer = &test_all_types; + EXPECT_EQ(&test_all_types, + google::protobuf::internal::DynamicCastToGenerated( + test_all_types_pointer)); + EXPECT_EQ(nullptr, + google::protobuf::internal::DynamicCastToGenerated( + test_all_types_pointer)); + + const google::protobuf::Message* test_all_types_pointer_const = &test_all_types; + EXPECT_EQ( + &test_all_types, + google::protobuf::internal::DynamicCastToGenerated( + test_all_types_pointer_const)); + EXPECT_EQ( + nullptr, + google::protobuf::internal::DynamicCastToGenerated( + test_all_types_pointer_const)); +} + +#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet. + +TEST(MESSAGE_TEST_NAME, SerializeFailsIfNotInitialized) { + UNITTEST::TestRequired message; + string data; + EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)), + "Can't serialize message of type \"" + + string(UNITTEST_PACKAGE_NAME) + + ".TestRequired\" because " + "it is missing required fields: a, b, c"); +} + +TEST(MESSAGE_TEST_NAME, CheckInitialized) { + UNITTEST::TestRequired message; + EXPECT_DEATH(message.CheckInitialized(), + "Message of type \"" + + string(UNITTEST_PACKAGE_NAME) + + ".TestRequired\" is missing required " + "fields: a, b, c"); +} + +#endif // PROTOBUF_HAS_DEATH_TEST + +namespace { +// An input stream that repeats a string's content for a number of times. It +// helps us create a really large input without consuming too much memory. Used +// to test the parsing behavior when the input size exceeds 2G or close to it. +class RepeatedInputStream : public io::ZeroCopyInputStream { + public: + RepeatedInputStream(const string& data, size_t count) + : data_(data), count_(count), position_(0), total_byte_count_(0) {} + + virtual bool Next(const void** data, int* size) { + if (position_ == data_.size()) { + if (--count_ == 0) { + return false; + } + position_ = 0; + } + *data = &data_[position_]; + *size = static_cast(data_.size() - position_); + position_ = data_.size(); + total_byte_count_ += *size; + return true; + } + + virtual void BackUp(int count) { + position_ -= static_cast(count); + total_byte_count_ -= count; + } + + virtual bool Skip(int count) { + while (count > 0) { + const void* data; + int size; + if (!Next(&data, &size)) { + break; + } + if (size >= count) { + BackUp(size - count); + return true; + } else { + count -= size; + } + } + return false; + } + + virtual int64 ByteCount() const { return total_byte_count_; } + + private: + string data_; + size_t count_; // The number of strings that haven't been consuemd. + size_t position_; // Position in the string for the next read. + int64 total_byte_count_; +}; +} // namespace + +TEST(MESSAGE_TEST_NAME, TestParseMessagesCloseTo2G) { + // Create a message with a large string field. + string value = string(64 * 1024 * 1024, 'x'); + UNITTEST::TestAllTypes message; + message.set_optional_string(value); + + // Repeat this message in the input stream to make the total input size + // close to 2G. + string data = message.SerializeAsString(); + size_t count = static_cast(kint32max) / data.size(); + RepeatedInputStream input(data, count); + + // The parsing should succeed. + UNITTEST::TestAllTypes result; + EXPECT_TRUE(result.ParseFromZeroCopyStream(&input)); + + // When there are multiple occurences of a singulr field, the last one + // should win. + EXPECT_EQ(value, result.optional_string()); +} + +TEST(MESSAGE_TEST_NAME, TestParseMessagesOver2G) { + // Create a message with a large string field. + string value = string(64 * 1024 * 1024, 'x'); + UNITTEST::TestAllTypes message; + message.set_optional_string(value); + + // Repeat this message in the input stream to make the total input size + // larger than 2G. + string data = message.SerializeAsString(); + size_t count = static_cast(kint32max) / data.size() + 1; + RepeatedInputStream input(data, count); + + // The parsing should fail. + UNITTEST::TestAllTypes result; + EXPECT_FALSE(result.ParseFromZeroCopyStream(&input)); +} + +TEST(MESSAGE_TEST_NAME, BypassInitializationCheckOnSerialize) { + UNITTEST::TestRequired message; + io::ArrayOutputStream raw_output(nullptr, 0); + io::CodedOutputStream output(&raw_output); + EXPECT_TRUE(message.SerializePartialToCodedStream(&output)); +} + +TEST(MESSAGE_TEST_NAME, FindInitializationErrors) { + UNITTEST::TestRequired message; + std::vector errors; + message.FindInitializationErrors(&errors); + ASSERT_EQ(3, errors.size()); + EXPECT_EQ("a", errors[0]); + EXPECT_EQ("b", errors[1]); + EXPECT_EQ("c", errors[2]); +} + +TEST(MESSAGE_TEST_NAME, ParseFailsOnInvalidMessageEnd) { + UNITTEST::TestAllTypes message; + + // Control case. + EXPECT_TRUE(message.ParseFromArray("", 0)); + + // The byte is a valid varint, but not a valid tag (zero). + EXPECT_FALSE(message.ParseFromArray("\0", 1)); + + // The byte is a malformed varint. + EXPECT_FALSE(message.ParseFromArray("\200", 1)); + + // The byte is an endgroup tag, but we aren't parsing a group. + EXPECT_FALSE(message.ParseFromArray("\014", 1)); +} + +// Regression test for b/23630858 +TEST(MESSAGE_TEST_NAME, MessageIsStillValidAfterParseFails) { + UNITTEST::TestAllTypes message; + + // 9 0xFFs for the "optional_uint64" field. + string invalid_data = "\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"; + + EXPECT_FALSE(message.ParseFromString(invalid_data)); + message.Clear(); + EXPECT_EQ(0, message.optional_uint64()); + + // invalid data for field "optional_string". Length prefix is 1 but no + // payload. + string invalid_string_data = "\x72\x01"; + { + google::protobuf::Arena arena; + UNITTEST::TestAllTypes* arena_message = + google::protobuf::Arena::CreateMessage(&arena); + EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data)); + arena_message->Clear(); + EXPECT_EQ("", arena_message->optional_string()); + } +} + + +namespace { + +void ExpectMessageMerged(const UNITTEST::TestAllTypes& message) { + EXPECT_EQ(3, message.optional_int32()); + EXPECT_EQ(2, message.optional_int64()); + EXPECT_EQ("hello", message.optional_string()); +} + +void AssignParsingMergeMessages(UNITTEST::TestAllTypes* msg1, + UNITTEST::TestAllTypes* msg2, + UNITTEST::TestAllTypes* msg3) { + msg1->set_optional_int32(1); + msg2->set_optional_int64(2); + msg3->set_optional_int32(3); + msg3->set_optional_string("hello"); +} + +} // namespace + +// Test that if an optional or required message/group field appears multiple +// times in the input, they need to be merged. +TEST(MESSAGE_TEST_NAME, ParsingMerge) { + UNITTEST::TestParsingMerge::RepeatedFieldsGenerator generator; + UNITTEST::TestAllTypes* msg1; + UNITTEST::TestAllTypes* msg2; + UNITTEST::TestAllTypes* 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); + UNITTEST::TestParsingMerge 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(UNITTEST::TestParsingMerge::optional_ext)); + + // Repeated fields should not be merged. + EXPECT_EQ(3, parsing_merge.repeated_all_types_size()); + EXPECT_EQ(3, parsing_merge.repeatedgroup_size()); + EXPECT_EQ( + 3, parsing_merge.ExtensionSize(UNITTEST::TestParsingMerge::repeated_ext)); +} + +TEST(MESSAGE_TEST_NAME, MergeFrom) { + UNITTEST::TestAllTypes source, dest; + + // Optional fields + source.set_optional_int32(1); // only source + source.set_optional_int64(2); // both source and dest + dest.set_optional_int64(3); + dest.set_optional_uint32(4); // only dest + + // Optional fields with defaults + source.set_default_int32(13); // only source + source.set_default_int64(14); // both source and dest + dest.set_default_int64(15); + dest.set_default_uint32(16); // only dest + + // Repeated fields + source.add_repeated_int32(5); // only source + source.add_repeated_int32(6); + source.add_repeated_int64(7); // both source and dest + source.add_repeated_int64(8); + dest.add_repeated_int64(9); + dest.add_repeated_int64(10); + dest.add_repeated_uint32(11); // only dest + dest.add_repeated_uint32(12); + + dest.MergeFrom(source); + + // Optional fields: source overwrites dest if source is specified + EXPECT_EQ(1, dest.optional_int32()); // only source: use source + EXPECT_EQ(2, dest.optional_int64()); // source and dest: use source + EXPECT_EQ(4, dest.optional_uint32()); // only dest: use dest + EXPECT_EQ(0, dest.optional_uint64()); // neither: use default + + // Optional fields with defaults + EXPECT_EQ(13, dest.default_int32()); // only source: use source + EXPECT_EQ(14, dest.default_int64()); // source and dest: use source + EXPECT_EQ(16, dest.default_uint32()); // only dest: use dest + EXPECT_EQ(44, dest.default_uint64()); // neither: use default + + // Repeated fields: concatenate source onto the end of dest + ASSERT_EQ(2, dest.repeated_int32_size()); + EXPECT_EQ(5, dest.repeated_int32(0)); + EXPECT_EQ(6, dest.repeated_int32(1)); + ASSERT_EQ(4, dest.repeated_int64_size()); + EXPECT_EQ(9, dest.repeated_int64(0)); + EXPECT_EQ(10, dest.repeated_int64(1)); + EXPECT_EQ(7, dest.repeated_int64(2)); + EXPECT_EQ(8, dest.repeated_int64(3)); + ASSERT_EQ(2, dest.repeated_uint32_size()); + EXPECT_EQ(11, dest.repeated_uint32(0)); + EXPECT_EQ(12, dest.repeated_uint32(1)); + ASSERT_EQ(0, dest.repeated_uint64_size()); +} + +TEST(MESSAGE_TEST_NAME, IsInitialized) { + UNITTEST::TestIsInitialized msg; + EXPECT_TRUE(msg.IsInitialized()); + UNITTEST::TestIsInitialized::SubMessage* sub_message = + msg.mutable_sub_message(); + EXPECT_TRUE(msg.IsInitialized()); + UNITTEST::TestIsInitialized::SubMessage::SubGroup* sub_group = + sub_message->mutable_subgroup(); + EXPECT_FALSE(msg.IsInitialized()); + sub_group->set_i(1); + EXPECT_TRUE(msg.IsInitialized()); +} + +TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryLookup) { + EXPECT_EQ(MessageFactory::generated_factory()->GetPrototype( + UNITTEST::TestAllTypes::descriptor()), + &UNITTEST::TestAllTypes::default_instance()); +} + +TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryUnknownType) { + // Construct a new descriptor. + DescriptorPool pool; + FileDescriptorProto file; + file.set_name("foo.proto"); + file.add_message_type()->set_name("Foo"); + const Descriptor* descriptor = pool.BuildFile(file)->message_type(0); + + // Trying to construct it should return nullptr. + EXPECT_TRUE(MessageFactory::generated_factory()->GetPrototype(descriptor) == + nullptr); +} + + +} // namespace protobuf +} // namespace google diff --git a/src/google/protobuf/preserve_unknown_enum_test.cc b/src/google/protobuf/preserve_unknown_enum_test.cc index 1673e8afae..e292199e80 100644 --- a/src/google/protobuf/preserve_unknown_enum_test.cc +++ b/src/google/protobuf/preserve_unknown_enum_test.cc @@ -120,7 +120,7 @@ TEST(PreserveUnknownEnumTest, PreserveParseAndSerializeDynamicMessage) { string serialized = orig_message.SerializeAsString(); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr message(factory.GetPrototype( + std::unique_ptr message(factory.GetPrototype( proto3_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); message->DiscardUnknownFields(); @@ -161,7 +161,7 @@ TEST(PreserveUnknownEnumTest, DynamicProto2HidesUnknownValues) { orig_message.SerializeToString(&serialized); google::protobuf::DynamicMessageFactory factory; - google::protobuf::scoped_ptr message(factory.GetPrototype( + std::unique_ptr message(factory.GetPrototype( proto2_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); // The intermediate message has everything in its "unknown fields". diff --git a/src/google/protobuf/proto3_arena_lite_unittest.cc b/src/google/protobuf/proto3_arena_lite_unittest.cc index 0f18c027e8..2ac775d7d9 100644 --- a/src/google/protobuf/proto3_arena_lite_unittest.cc +++ b/src/google/protobuf/proto3_arena_lite_unittest.cc @@ -30,20 +30,15 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include -#include -#include -#include +#include #include #include #include namespace google { -using proto3_arena_lite_unittest::TestAllTypes; +using proto3_arena_unittest::TestAllTypes; namespace protobuf { namespace { @@ -56,9 +51,9 @@ void SetAllFields(TestAllTypes* m) { m->mutable_optional_nested_message()->set_bb(42); m->mutable_optional_foreign_message()->set_c(43); m->set_optional_nested_enum( - proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ); + proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); m->set_optional_foreign_enum( - proto3_arena_lite_unittest::FOREIGN_BAZ); + proto3_arena_unittest::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); m->add_repeated_int32(100); m->add_repeated_string("asdf"); @@ -66,9 +61,9 @@ void SetAllFields(TestAllTypes* m) { m->add_repeated_nested_message()->set_bb(46); m->add_repeated_foreign_message()->set_c(47); m->add_repeated_nested_enum( - proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ); + proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ); m->add_repeated_foreign_enum( - proto3_arena_lite_unittest::FOREIGN_BAZ); + proto3_arena_unittest::FOREIGN_BAZ); m->add_repeated_lazy_message()->set_bb(49); m->set_oneof_uint32(1); @@ -84,9 +79,9 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(42, m.optional_nested_message().bb()); EXPECT_EQ(true, m.has_optional_foreign_message()); EXPECT_EQ(43, m.optional_foreign_message().c()); - EXPECT_EQ(proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ, + EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.optional_nested_enum()); - EXPECT_EQ(proto3_arena_lite_unittest::FOREIGN_BAZ, + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.optional_foreign_enum()); EXPECT_EQ(true, m.has_optional_lazy_message()); EXPECT_EQ(45, m.optional_lazy_message().bb()); @@ -102,15 +97,15 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(1, m.repeated_foreign_message_size()); EXPECT_EQ(47, m.repeated_foreign_message(0).c()); EXPECT_EQ(1, m.repeated_nested_enum_size()); - EXPECT_EQ(proto3_arena_lite_unittest::TestAllTypes_NestedEnum_BAZ, + EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ, m.repeated_nested_enum(0)); EXPECT_EQ(1, m.repeated_foreign_enum_size()); - EXPECT_EQ(proto3_arena_lite_unittest::FOREIGN_BAZ, + EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.repeated_foreign_enum(0)); EXPECT_EQ(1, m.repeated_lazy_message_size()); EXPECT_EQ(49, m.repeated_lazy_message(0).bb()); - EXPECT_EQ(proto3_arena_lite_unittest::TestAllTypes::kOneofString, + EXPECT_EQ(proto3_arena_unittest::TestAllTypes::kOneofString, m.oneof_field_case()); EXPECT_EQ("test", m.oneof_string()); } @@ -154,7 +149,7 @@ TEST(Proto3ArenaLiteTest, ReleaseMessage) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); arena_message->mutable_optional_nested_message()->set_bb(118); - google::protobuf::scoped_ptr nested( + std::unique_ptr nested( arena_message->release_optional_nested_message()); EXPECT_EQ(118, nested->bb()); } diff --git a/src/google/protobuf/proto3_arena_unittest.cc b/src/google/protobuf/proto3_arena_unittest.cc index 3a0fb804be..dac7378162 100644 --- a/src/google/protobuf/proto3_arena_unittest.cc +++ b/src/google/protobuf/proto3_arena_unittest.cc @@ -30,9 +30,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -198,7 +195,7 @@ TEST(Proto3ArenaTest, ReleaseMessage) { Arena arena; TestAllTypes* arena_message = Arena::CreateMessage(&arena); arena_message->mutable_optional_nested_message()->set_bb(118); - google::protobuf::scoped_ptr nested( + std::unique_ptr nested( arena_message->release_optional_nested_message()); EXPECT_EQ(118, nested->bb()); } diff --git a/src/google/protobuf/proto3_lite_unittest.cc b/src/google/protobuf/proto3_lite_unittest.cc index 2e2beea909..f5c6084d8c 100644 --- a/src/google/protobuf/proto3_lite_unittest.cc +++ b/src/google/protobuf/proto3_lite_unittest.cc @@ -30,20 +30,15 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include -#include -#include -#include +#include #include #include #include namespace google { -using proto3_lite_unittest::TestAllTypes; +using proto3_unittest::TestAllTypes; namespace protobuf { namespace { @@ -56,9 +51,9 @@ void SetAllFields(TestAllTypes* m) { m->mutable_optional_nested_message()->set_bb(42); m->mutable_optional_foreign_message()->set_c(43); m->set_optional_nested_enum( - proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ); + proto3_unittest::TestAllTypes_NestedEnum_BAZ); m->set_optional_foreign_enum( - proto3_lite_unittest::FOREIGN_BAZ); + proto3_unittest::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); m->add_repeated_int32(100); m->add_repeated_string("asdf"); @@ -66,9 +61,9 @@ void SetAllFields(TestAllTypes* m) { m->add_repeated_nested_message()->set_bb(46); m->add_repeated_foreign_message()->set_c(47); m->add_repeated_nested_enum( - proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ); + proto3_unittest::TestAllTypes_NestedEnum_BAZ); m->add_repeated_foreign_enum( - proto3_lite_unittest::FOREIGN_BAZ); + proto3_unittest::FOREIGN_BAZ); m->add_repeated_lazy_message()->set_bb(49); m->set_oneof_uint32(1); @@ -84,9 +79,9 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(42, m.optional_nested_message().bb()); EXPECT_EQ(true, m.has_optional_foreign_message()); EXPECT_EQ(43, m.optional_foreign_message().c()); - EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ, + EXPECT_EQ(proto3_unittest::TestAllTypes_NestedEnum_BAZ, m.optional_nested_enum()); - EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ, + EXPECT_EQ(proto3_unittest::FOREIGN_BAZ, m.optional_foreign_enum()); EXPECT_EQ(true, m.has_optional_lazy_message()); EXPECT_EQ(45, m.optional_lazy_message().bb()); @@ -102,15 +97,15 @@ void ExpectAllFieldsSet(const TestAllTypes& m) { EXPECT_EQ(1, m.repeated_foreign_message_size()); EXPECT_EQ(47, m.repeated_foreign_message(0).c()); EXPECT_EQ(1, m.repeated_nested_enum_size()); - EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ, + EXPECT_EQ(proto3_unittest::TestAllTypes_NestedEnum_BAZ, m.repeated_nested_enum(0)); EXPECT_EQ(1, m.repeated_foreign_enum_size()); - EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ, + EXPECT_EQ(proto3_unittest::FOREIGN_BAZ, m.repeated_foreign_enum(0)); EXPECT_EQ(1, m.repeated_lazy_message_size()); EXPECT_EQ(49, m.repeated_lazy_message(0).bb()); - EXPECT_EQ(proto3_lite_unittest::TestAllTypes::kOneofString, + EXPECT_EQ(proto3_unittest::TestAllTypes::kOneofString, m.oneof_field_case()); EXPECT_EQ("test", m.oneof_string()); } diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h index fcb9a43559..5d0fc42b8e 100755 --- a/src/google/protobuf/reflection.h +++ b/src/google/protobuf/reflection.h @@ -34,9 +34,6 @@ #define GOOGLE_PROTOBUF_REFLECTION_H__ #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -63,7 +60,7 @@ MutableRepeatedFieldRef Reflection::GetMutableRepeatedFieldRef( // RepeatedFieldRef definition for non-message types. template class RepeatedFieldRef< - T, typename internal::enable_if::value>::type> { + T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::iterator IteratorType; typedef typename internal::RefTypeTraits::AccessorType AccessorType; @@ -112,7 +109,7 @@ class RepeatedFieldRef< // MutableRepeatedFieldRef definition for non-message types. template class MutableRepeatedFieldRef< - T, typename internal::enable_if::value>::type> { + T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::AccessorType AccessorType; public: @@ -177,7 +174,7 @@ class MutableRepeatedFieldRef< // RepeatedFieldRef definition for message types. template class RepeatedFieldRef< - T, typename internal::enable_if::value>::type> { + T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::iterator IteratorType; typedef typename internal::RefTypeTraits::AccessorType AccessorType; @@ -219,7 +216,7 @@ class RepeatedFieldRef< } iterator end() const { // The end iterator must not be dereferenced, no need for scratch space. - return iterator(data_, accessor_, false, NULL); + return iterator(data_, accessor_, false, nullptr); } private: @@ -245,7 +242,7 @@ class RepeatedFieldRef< // MutableRepeatedFieldRef definition for message types. template class MutableRepeatedFieldRef< - T, typename internal::enable_if::value>::type> { + T, typename std::enable_if::value>::type> { typedef typename internal::RefTypeTraits::AccessorType AccessorType; public: @@ -447,7 +444,7 @@ class RepeatedFieldRefIterator iterator_(begin ? accessor->BeginIterator(data) : accessor->EndIterator(data)), // The end iterator must not be dereferenced, no need for scratch space. - scratch_space_(begin ? new AccessorValueType : NULL) {} + scratch_space_(begin ? new AccessorValueType : nullptr) {} // Constructor for message fields. RepeatedFieldRefIterator(const void* data, const RepeatedFieldAccessor* accessor, @@ -508,7 +505,7 @@ class RepeatedFieldRefIterator const void* data_; const RepeatedFieldAccessor* accessor_; void* iterator_; - google::protobuf::scoped_ptr scratch_space_; + std::unique_ptr scratch_space_; }; // TypeTraits that maps the type parameter T of RepeatedFieldRef or @@ -535,7 +532,7 @@ DEFINE_PRIMITIVE(BOOL, bool) template struct RefTypeTraits< - T, typename internal::enable_if::is_primitive>::type> { + T, typename std::enable_if::is_primitive>::type> { typedef RepeatedFieldRefIterator iterator; typedef RepeatedFieldAccessor AccessorType; typedef T AccessorValueType; @@ -550,7 +547,7 @@ struct RefTypeTraits< template struct RefTypeTraits< - T, typename internal::enable_if::value>::type> { + T, typename std::enable_if::value>::type> { typedef RepeatedFieldRefIterator iterator; typedef RepeatedFieldAccessor AccessorType; // We use int32 for repeated enums in RepeatedFieldAccessor. @@ -566,7 +563,7 @@ struct RefTypeTraits< template struct RefTypeTraits< - T, typename internal::enable_if< ::google::protobuf::internal::is_same::value>::type> { + T, typename std::enable_if::value>::type> { typedef RepeatedFieldRefIterator iterator; typedef RepeatedFieldAccessor AccessorType; typedef string AccessorValueType; @@ -594,7 +591,7 @@ struct MessageDescriptorGetter { template struct RefTypeTraits< - T, typename internal::enable_if::value>::type> { + T, typename std::enable_if::value>::type> { typedef RepeatedFieldRefIterator iterator; typedef RepeatedFieldAccessor AccessorType; typedef Message AccessorValueType; diff --git a/src/google/protobuf/reflection_ops.cc b/src/google/protobuf/reflection_ops.cc index eb2a0e7a54..3cd503404d 100644 --- a/src/google/protobuf/reflection_ops.cc +++ b/src/google/protobuf/reflection_ops.cc @@ -50,10 +50,10 @@ namespace internal { static const Reflection* GetReflectionOrDie(const Message& m) { const Reflection* r = m.GetReflection(); - if (r == NULL) { + if (r == nullptr) { const Descriptor* d = m.GetDescriptor(); const string& mtype = d ? d->name() : "unknown"; - // RawMessage is one known type for which GetReflection() returns NULL. + // RawMessage is one known type for which GetReflection() returns nullptr. GOOGLE_LOG(FATAL) << "Message does not support reflection (type " << mtype << ")."; } return r; diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h index 5fc619f202..80820c7a09 100644 --- a/src/google/protobuf/repeated_field.h +++ b/src/google/protobuf/repeated_field.h @@ -61,6 +61,7 @@ #include #include #include +#include // Forward-declare these so that we can make them friends. @@ -108,7 +109,7 @@ inline int CalculateReserve(Iter begin, Iter end) { // not ever use a RepeatedField directly; they will use the get-by-index, // set-by-index, and add accessors that are generated for all repeated fields. template -class RepeatedField PROTOBUF_FINAL { +class RepeatedField final { public: RepeatedField(); explicit RepeatedField(Arena* arena); @@ -119,10 +120,8 @@ class RepeatedField PROTOBUF_FINAL { RepeatedField& operator=(const RepeatedField& other); -#if LANG_CXX11 RepeatedField(RepeatedField&& other) noexcept; RepeatedField& operator=(RepeatedField&& other) noexcept; -#endif bool empty() const; int size() const; @@ -352,7 +351,7 @@ namespace internal { // effectively. template ::value> + std::is_trivially_copy_constructible::value> struct ElementCopier { void operator()(Element* to, const Element* from, int array_size); }; @@ -386,8 +385,8 @@ struct TypeImplementsMergeBehaviorProbeForMergeFrom { CheckType*); template static HasNoMerge Check(...); - // Resolves to either google::protobuf::internal::true_type or google::protobuf::internal::false_type. - typedef google::protobuf::internal::integral_constant(0)) == sizeof(HasMerge))> type; }; @@ -398,7 +397,7 @@ struct TypeImplementsMergeBehavior : template <> struct TypeImplementsMergeBehavior< ::std::string> { - typedef google::protobuf::internal::true_type type; + typedef std::true_type type; }; // This is the common base class for RepeatedPtrFields. It deals only in void* @@ -465,11 +464,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { inline void InternalSwap(RepeatedPtrFieldBase* other); protected: -#if LANG_CXX11 template void Add(typename TypeHandler::Type&& value, - internal::enable_if* dummy = NULL); -#endif + std::enable_if* dummy = NULL); template void RemoveLast(); @@ -532,9 +529,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { typename TypeHandler::Type* ReleaseCleared(); template - void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::true_type); + void AddAllocatedInternal(typename TypeHandler::Type* value, std::true_type); template - void AddAllocatedInternal(typename TypeHandler::Type* value, google::protobuf::internal::false_type); + void AddAllocatedInternal(typename TypeHandler::Type* value, std::false_type); template GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void AddAllocatedSlowWithCopy(typename TypeHandler::Type* value, @@ -544,9 +541,9 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { void AddAllocatedSlowWithoutCopy(typename TypeHandler::Type* value); template - typename TypeHandler::Type* ReleaseLastInternal(google::protobuf::internal::true_type); + typename TypeHandler::Type* ReleaseLastInternal(std::true_type); template - typename TypeHandler::Type* ReleaseLastInternal(google::protobuf::internal::false_type); + typename TypeHandler::Type* ReleaseLastInternal(std::false_type); template GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void SwapFallback(RepeatedPtrFieldBase* other); @@ -640,9 +637,7 @@ class GenericTypeHandler { public: typedef GenericType Type; typedef GenericType WeakType; -#if LANG_CXX11 static const bool Moveable = false; -#endif static inline GenericType* New(Arena* arena) { return ::google::protobuf::Arena::CreateMaybeMessage(arena); @@ -732,20 +727,15 @@ class StringTypeHandler { public: typedef string Type; typedef string WeakType; -#if LANG_CXX11 - static const bool Moveable = - std::is_move_constructible::value && - std::is_move_assignable::value; -#endif + static const bool Moveable = std::is_move_constructible::value && + std::is_move_assignable::value; static inline string* New(Arena* arena) { return Arena::Create(arena); } -#if LANG_CXX11 static inline string* New(Arena* arena, string&& value) { return Arena::Create(arena, std::move(value)); } -#endif static inline string* NewFromPrototype(const string*, ::google::protobuf::Arena* arena) { return New(arena); @@ -773,7 +763,7 @@ class StringTypeHandler { // RepeatedPtrField is like RepeatedField, but used for repeated strings or // Messages. template -class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { +class RepeatedPtrField final : private internal::RepeatedPtrFieldBase { public: RepeatedPtrField(); explicit RepeatedPtrField(::google::protobuf::Arena* arena); @@ -785,10 +775,8 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { RepeatedPtrField& operator=(const RepeatedPtrField& other); -#if LANG_CXX11 RepeatedPtrField(RepeatedPtrField&& other) noexcept; RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept; -#endif bool empty() const; int size() const; @@ -796,9 +784,7 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { const Element& Get(int index) const; Element* Mutable(int index); Element* Add(); -#if LANG_CXX11 void Add(Element&& value); -#endif const Element& operator[](int index) const { return Get(index); } Element& operator[](int index) { return *Mutable(index); } @@ -928,7 +914,7 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { // RepeatedPtrField temp_field; // temp_field.AddAllocated(new T); // ... // Do something with temp_field - // temp_field.ExtractSubrange(0, temp_field.size(), NULL); + // temp_field.ExtractSubrange(0, temp_field.size(), nullptr); // If you put temp_field on the arena this fails, because the ownership // transfers to the arena at the "AddAllocated" call and is not released // anymore causing a double delete. UnsafeArenaAddAllocated prevents this. @@ -1027,9 +1013,9 @@ class RepeatedPtrField PROTOBUF_FINAL : private internal::RepeatedPtrFieldBase { // MergeFrom()), so we must resolve this at compile time. ExtractSubrange() // uses SFINAE to choose one of the below implementations. void ExtractSubrangeInternal(int start, int num, Element** elements, - google::protobuf::internal::true_type); + std::true_type); void ExtractSubrangeInternal(int start, int num, Element** elements, - google::protobuf::internal::false_type); + std::false_type); friend class Arena; friend class MessageLite; @@ -1100,8 +1086,6 @@ RepeatedField::operator=(const RepeatedField& other) { return *this; } -#if LANG_CXX11 - template inline RepeatedField::RepeatedField(RepeatedField&& other) noexcept : RepeatedField() { @@ -1129,8 +1113,6 @@ inline RepeatedField& RepeatedField::operator=( return *this; } -#endif // LANG_CXX11 - template inline bool RepeatedField::empty() const { return current_size_ == 0; @@ -1556,11 +1538,10 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add( return result; } -#if LANG_CXX11 template inline void RepeatedPtrFieldBase::Add( typename TypeHandler::Type&& value, - internal::enable_if*) { + std::enable_if*) { if (rep_ != NULL && current_size_ < rep_->allocated_size) { *cast(rep_->elements[current_size_++]) = std::move(value); return; @@ -1573,7 +1554,6 @@ inline void RepeatedPtrFieldBase::Add( TypeHandler::New(arena_, std::move(value)); rep_->elements[current_size_++] = result; } -#endif template inline void RepeatedPtrFieldBase::RemoveLast() { @@ -1716,7 +1696,7 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() { template void RepeatedPtrFieldBase::AddAllocatedInternal( typename TypeHandler::Type* value, - google::protobuf::internal::true_type) { + std::true_type) { Arena* element_arena = reinterpret_cast( TypeHandler::GetMaybeArenaPointer(value)); Arena* arena = GetArenaNoVirtual(); @@ -1766,7 +1746,7 @@ void RepeatedPtrFieldBase::AddAllocatedSlowWithCopy( template void RepeatedPtrFieldBase::AddAllocatedInternal( typename TypeHandler::Type* value, - google::protobuf::internal::false_type) { + std::false_type) { if (rep_ && rep_->allocated_size < total_size_) { // Fast path: underlying arena representation (tagged pointer) is equal to // our arena pointer, and we can add to array without resizing it (at least @@ -1816,7 +1796,7 @@ void RepeatedPtrFieldBase::UnsafeArenaAddAllocated( // ReleaseLast() for types that implement merge/copy behavior. template inline typename TypeHandler::Type* -RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::true_type) { +RepeatedPtrFieldBase::ReleaseLastInternal(std::true_type) { // First, release an element. typename TypeHandler::Type* result = UnsafeArenaReleaseLast(); // Now perform a copy if we're on an arena. @@ -1837,7 +1817,7 @@ RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::true_type) // case. template inline typename TypeHandler::Type* -RepeatedPtrFieldBase::ReleaseLastInternal(google::protobuf::internal::false_type) { +RepeatedPtrFieldBase::ReleaseLastInternal(std::false_type) { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL) << "ReleaseLast() called on a RepeatedPtrField that is on an arena, " << "with a type that does not implement MergeFrom. This is unsafe; " @@ -1943,8 +1923,6 @@ inline RepeatedPtrField& RepeatedPtrField::operator=( return *this; } -#if LANG_CXX11 - template inline RepeatedPtrField::RepeatedPtrField( RepeatedPtrField&& other) noexcept @@ -1973,8 +1951,6 @@ inline RepeatedPtrField& RepeatedPtrField::operator=( return *this; } -#endif // LANG_CXX11 - template inline bool RepeatedPtrField::empty() const { return RepeatedPtrFieldBase::empty(); @@ -2001,12 +1977,10 @@ inline Element* RepeatedPtrField::Add() { return RepeatedPtrFieldBase::Add(); } -#if LANG_CXX11 template inline void RepeatedPtrField::Add(Element&& value) { RepeatedPtrFieldBase::Add(std::move(value)); } -#endif template inline void RepeatedPtrField::RemoveLast() { @@ -2036,7 +2010,7 @@ inline void RepeatedPtrField::ExtractSubrange( // behavior. template inline void RepeatedPtrField::ExtractSubrangeInternal( - int start, int num, Element** elements, google::protobuf::internal::true_type) { + int start, int num, Element** elements, std::true_type) { GOOGLE_DCHECK_GE(start, 0); GOOGLE_DCHECK_GE(num, 0); GOOGLE_DCHECK_LE(start + num, size()); @@ -2069,7 +2043,7 @@ inline void RepeatedPtrField::ExtractSubrangeInternal( // behavior. template inline void RepeatedPtrField::ExtractSubrangeInternal( - int start, int num, Element** elements, google::protobuf::internal::false_type) { + int start, int num, Element** elements, std::false_type) { // This case is identical to UnsafeArenaExtractSubrange(). However, since // ExtractSubrange() must return heap-allocated objects by contract, and we // cannot fulfill this contract if we are an on arena, we must GOOGLE_DCHECK() that @@ -2241,7 +2215,7 @@ class RepeatedPtrIterator // Shadow the value_type in std::iterator<> because const_iterator::value_type // needs to be T, not const T. - typedef typename remove_const::type value_type; + typedef typename std::remove_const::type value_type; // Let the compiler know that these are type names, so we don't have to // write "typename" in front of them everywhere. @@ -2259,7 +2233,7 @@ class RepeatedPtrIterator : it_(other.it_) { // Force a compiler error if the other type is not convertible to ours. if (false) { - implicit_cast(static_cast(NULL)); + implicit_cast(static_cast(nullptr)); } } @@ -2335,7 +2309,7 @@ class RepeatedPtrOverPtrsIterator // Shadow the value_type in std::iterator<> because const_iterator::value_type // needs to be T, not const T. - typedef typename remove_const::type value_type; + typedef typename std::remove_const::type value_type; // Let the compiler know that these are type names, so we don't have to // write "typename" in front of them everywhere. @@ -2520,12 +2494,10 @@ template class RepeatedPtrFieldBackInsertIterator *field_->Add() = *ptr_to_value; return *this; } -#if LANG_CXX11 RepeatedPtrFieldBackInsertIterator& operator=(T&& value) { *field_->Add() = std::move(value); return *this; } -#endif RepeatedPtrFieldBackInsertIterator& operator*() { return *this; } @@ -2640,7 +2612,7 @@ AllocatedRepeatedPtrFieldBackInserter( // RepeatedPtrField temp_field; // temp_field.AddAllocated(new T); // ... // Do something with temp_field -// temp_field.ExtractSubrange(0, temp_field.size(), NULL); +// temp_field.ExtractSubrange(0, temp_field.size(), nullptr); // If you put temp_field on the arena this fails, because the ownership // transfers to the arena at the "AddAllocated" call and is not released anymore // causing a double delete. Using UnsafeArenaAddAllocated prevents this. diff --git a/src/google/protobuf/repeated_field_reflection_unittest.cc b/src/google/protobuf/repeated_field_reflection_unittest.cc index fd46656540..74ec83b050 100644 --- a/src/google/protobuf/repeated_field_reflection_unittest.cc +++ b/src/google/protobuf/repeated_field_reflection_unittest.cc @@ -704,7 +704,7 @@ TEST(RepeatedFieldReflectionTest, RepeatedFieldRefDynamicMessage) { desc->FindFieldByName("repeated_int32"); DynamicMessageFactory factory; - google::protobuf::scoped_ptr dynamic_message(factory.GetPrototype(desc)->New()); + std::unique_ptr dynamic_message(factory.GetPrototype(desc)->New()); const Reflection* refl = dynamic_message->GetReflection(); MutableRepeatedFieldRef rf_int32 = diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc index 16919711a5..053a4d68f2 100644 --- a/src/google/protobuf/repeated_field_unittest.cc +++ b/src/google/protobuf/repeated_field_unittest.cc @@ -383,8 +383,6 @@ TEST(RepeatedField, SelfAssign) { EXPECT_EQ(8, source.Get(1)); } -#if LANG_CXX11 - TEST(RepeatedField, MoveConstruct) { { RepeatedField source; @@ -405,7 +403,7 @@ TEST(RepeatedField, MoveConstruct) { source->Add(1); source->Add(2); RepeatedField destination = std::move(*source); - EXPECT_EQ(NULL, destination.GetArena()); + EXPECT_EQ(nullptr, destination.GetArena()); EXPECT_THAT(destination, ElementsAre(1, 2)); // This property isn't guaranteed but it's useful to have a test that would // catch changes in this area. @@ -517,8 +515,6 @@ TEST(RepeatedField, MoveAssign) { } } -#endif // LANG_CXX11 - TEST(RepeatedField, MutableDataIsMutable) { RepeatedField field; field.Add(1); @@ -1045,8 +1041,6 @@ TEST(RepeatedPtrField, SelfAssign) { EXPECT_EQ("8", source.Get(1)); } -#if LANG_CXX11 - TEST(RepeatedPtrField, MoveConstruct) { { RepeatedPtrField source; @@ -1067,7 +1061,7 @@ TEST(RepeatedPtrField, MoveConstruct) { *source->Add() = "1"; *source->Add() = "2"; RepeatedPtrField destination = std::move(*source); - EXPECT_EQ(NULL, destination.GetArena()); + EXPECT_EQ(nullptr, destination.GetArena()); EXPECT_THAT(destination, ElementsAre("1", "2")); // This property isn't guaranteed but it's useful to have a test that would // catch changes in this area. @@ -1179,8 +1173,6 @@ TEST(RepeatedPtrField, MoveAssign) { } } -#endif // LANG_CXX11 - TEST(RepeatedPtrField, MutableDataIsMutable) { RepeatedPtrField field; *field.Add() = "1"; @@ -1844,7 +1836,6 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, EXPECT_EQ(testproto.DebugString(), goldenproto.DebugString()); } -#if LANG_CXX11 TEST_F(RepeatedFieldInsertionIteratorsTest, MoveStrings) { std::vector src = {"a", "b", "c", "d"}; std::vector copy = src; // copy since move leaves in undefined state @@ -1874,7 +1865,6 @@ TEST_F(RepeatedFieldInsertionIteratorsTest, MoveProtos) { testproto.repeated_nested_message(i).DebugString()); } } -#endif } // namespace diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc index b9d8f3cbc5..739172f844 100644 --- a/src/google/protobuf/source_context.pb.cc +++ b/src/google/protobuf/source_context.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class SourceContextDefaultTypeInternal { @@ -29,14 +29,9 @@ class SourceContextDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { -void InitDefaultsSourceContextImpl() { +static void InitDefaultsSourceContext() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_SourceContext_default_instance_; new (ptr) ::google::protobuf::SourceContext(); @@ -45,9 +40,11 @@ void InitDefaultsSourceContextImpl() { ::google::protobuf::SourceContext::InitAsDefaultInstance(); } -void InitDefaultsSourceContext() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsSourceContextImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceContext}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_SourceContext.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -70,15 +67,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -128,16 +124,14 @@ const int SourceContext::kFileNameFieldNumber; SourceContext::SourceContext() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.SourceContext) } SourceContext::SourceContext(const SourceContext& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.file_name().size() > 0) { @@ -148,7 +142,6 @@ SourceContext::SourceContext(const SourceContext& from) void SourceContext::SharedCtor() { file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; } SourceContext::~SourceContext() { @@ -161,9 +154,7 @@ void SourceContext::SharedDtor() { } void SourceContext::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* SourceContext::descriptor() { ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce(); @@ -171,7 +162,7 @@ const ::google::protobuf::Descriptor* SourceContext::descriptor() { } const SourceContext& SourceContext::default_instance() { - ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base); return *internal_default_instance(); } @@ -192,7 +183,7 @@ bool SourceContext::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.SourceContext) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -298,9 +289,7 @@ size_t SourceContext::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -356,9 +345,9 @@ void SourceContext::Swap(SourceContext* other) { } void SourceContext::InternalSwap(SourceContext* other) { using std::swap; - file_name_.Swap(&other->file_name_); + file_name_.Swap(&other->file_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SourceContext::GetMetadata() const { @@ -372,7 +361,7 @@ void SourceContext::InternalSwap(SourceContext* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::Create< ::google::protobuf::SourceContext >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::CreateMaybeMessage< ::google::protobuf::SourceContext >(Arena* arena) { return Arena::CreateInternal< ::google::protobuf::SourceContext >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h index 81893b1a11..16ed21ca61 100644 --- a/src/google/protobuf/source_context.pb.h +++ b/src/google/protobuf/source_context.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto -#ifndef PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto #include @@ -24,12 +24,14 @@ #include #include #include +#include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceContextImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsSourceContext(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsSourceContext(); -} } // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_defaul } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::Create< ::google::protobuf::SourceContext>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::CreateMaybeMessage<::google::protobuf::SourceContext>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -99,7 +96,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ return reinterpret_cast( &_SourceContext_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void Swap(SourceContext* other); @@ -109,32 +106,33 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ // implements Message ---------------------------------------------- - inline SourceContext* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(NULL); + inline SourceContext* New() const final { + return CreateMaybeMessage(NULL); } - SourceContext* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::Create(arena); + SourceContext* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const SourceContext& from); void MergeFrom(const SourceContext& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(SourceContext* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { @@ -145,7 +143,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -170,9 +168,8 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @ ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::ArenaStringPtr file_name_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContextImpl(); }; // =================================================================== @@ -249,4 +246,4 @@ inline void SourceContext::set_allocated_file_name(::std::string* file_name) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fsource_5fcontext_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc index 309a4d2df1..8f2d484818 100644 --- a/src/google/protobuf/struct.pb.cc +++ b/src/google/protobuf/struct.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,10 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fstruct_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue; +} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto namespace google { namespace protobuf { class Struct_FieldsEntry_DoNotUseDefaultTypeInternal { @@ -50,14 +53,9 @@ class ListValueDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2fstruct_2eproto { -void InitDefaultsListValueImpl() { +static void InitDefaultsListValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Struct_FieldsEntry_DoNotUse_default_instance_; new (ptr) ::google::protobuf::Struct_FieldsEntry_DoNotUse(); @@ -83,9 +81,11 @@ void InitDefaultsListValueImpl() { ::google::protobuf::ListValue::InitAsDefaultInstance(); } -void InitDefaultsListValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsListValueImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsListValue}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_ListValue.base); } ::google::protobuf::Metadata file_level_metadata[4]; @@ -142,15 +142,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -187,8 +186,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -240,9 +239,8 @@ const int Struct::kFieldsFieldNumber; Struct::Struct() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Struct) } @@ -250,22 +248,20 @@ Struct::Struct(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), fields_(arena) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Struct) } Struct::Struct(const Struct& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); fields_.MergeFrom(from.fields_); // @@protoc_insertion_point(copy_constructor:google.protobuf.Struct) } void Struct::SharedCtor() { - _cached_size_ = 0; } Struct::~Struct() { @@ -284,9 +280,7 @@ void Struct::ArenaDtor(void* object) { void Struct::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Struct::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Struct::descriptor() { ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); @@ -294,7 +288,7 @@ const ::google::protobuf::Descriptor* Struct::descriptor() { } const Struct& Struct::default_instance() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); return *internal_default_instance(); } @@ -315,7 +309,7 @@ bool Struct::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Struct) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -385,7 +379,7 @@ void Struct::SerializeWithCachedSizes( if (output->IsSerializationDeterministic() && this->fields().size() > 1) { - ::google::protobuf::scoped_array items( + ::std::unique_ptr items( new SortItem[this->fields().size()]); typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type; size_type n = 0; @@ -395,7 +389,7 @@ void Struct::SerializeWithCachedSizes( items[static_cast(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast(n)], Less()); - ::google::protobuf::scoped_ptr entry; + ::std::unique_ptr entry; for (size_type i = 0; i < n; i++) { entry.reset(fields_.NewEntryWrapper( items[static_cast(i)]->first, items[static_cast(i)]->second)); @@ -407,7 +401,7 @@ void Struct::SerializeWithCachedSizes( Utf8Check::Check(items[static_cast(i)]); } } else { - ::google::protobuf::scoped_ptr entry; + ::std::unique_ptr entry; for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { @@ -454,7 +448,7 @@ void Struct::SerializeWithCachedSizes( if (deterministic && this->fields().size() > 1) { - ::google::protobuf::scoped_array items( + ::std::unique_ptr items( new SortItem[this->fields().size()]); typedef ::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::size_type size_type; size_type n = 0; @@ -464,7 +458,7 @@ void Struct::SerializeWithCachedSizes( items[static_cast(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast(n)], Less()); - ::google::protobuf::scoped_ptr entry; + ::std::unique_ptr entry; for (size_type i = 0; i < n; i++) { entry.reset(fields_.NewEntryWrapper( items[static_cast(i)]->first, items[static_cast(i)]->second)); @@ -478,7 +472,7 @@ void Struct::SerializeWithCachedSizes( Utf8Check::Check(items[static_cast(i)]); } } else { - ::google::protobuf::scoped_ptr entry; + ::std::unique_ptr entry; for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { @@ -517,7 +511,7 @@ size_t Struct::ByteSizeLong() const { total_size += 1 * ::google::protobuf::internal::FromIntSize(this->fields_size()); { - ::google::protobuf::scoped_ptr entry; + ::std::unique_ptr entry; for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator it = this->fields().begin(); it != this->fields().end(); ++it) { @@ -534,9 +528,7 @@ size_t Struct::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -606,7 +598,6 @@ void Struct::InternalSwap(Struct* other) { using std::swap; fields_.Swap(&other->fields_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Struct::GetMetadata() const { @@ -669,24 +660,22 @@ const int Value::kListValueFieldNumber; Value::Value() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Value) } Value::Value(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Value) } Value::Value(const Value& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_kind(); switch (from.kind_case()) { @@ -723,7 +712,6 @@ Value::Value(const Value& from) void Value::SharedCtor() { clear_has_kind(); - _cached_size_ = 0; } Value::~Value() { @@ -745,9 +733,7 @@ void Value::ArenaDtor(void* object) { void Value::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Value::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Value::descriptor() { ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); @@ -755,7 +741,7 @@ const ::google::protobuf::Descriptor* Value::descriptor() { } const Value& Value::default_instance() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); return *internal_default_instance(); } @@ -816,7 +802,7 @@ bool Value::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Value) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -960,13 +946,13 @@ void Value::SerializeWithCachedSizes( // .google.protobuf.Struct struct_value = 5; if (has_struct_value()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *kind_.struct_value_, output); + 5, this->_internal_struct_value(), output); } // .google.protobuf.ListValue list_value = 6; if (has_list_value()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, *kind_.list_value_, output); + 6, this->_internal_list_value(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -1014,14 +1000,14 @@ void Value::SerializeWithCachedSizes( if (has_struct_value()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, *kind_.struct_value_, deterministic, target); + 5, this->_internal_struct_value(), deterministic, target); } // .google.protobuf.ListValue list_value = 6; if (has_list_value()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 6, *kind_.list_value_, deterministic, target); + 6, this->_internal_list_value(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -1084,9 +1070,7 @@ size_t Value::ByteSizeLong() const { } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1185,7 +1169,6 @@ void Value::InternalSwap(Value* other) { swap(kind_, other->kind_); swap(_oneof_case_[0], other->_oneof_case_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Value::GetMetadata() const { @@ -1204,9 +1187,8 @@ const int ListValue::kValuesFieldNumber; ListValue::ListValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.ListValue) } @@ -1214,7 +1196,7 @@ ListValue::ListValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), values_(arena) { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue) @@ -1222,14 +1204,12 @@ ListValue::ListValue(::google::protobuf::Arena* arena) ListValue::ListValue(const ListValue& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - values_(from.values_), - _cached_size_(0) { + values_(from.values_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue) } void ListValue::SharedCtor() { - _cached_size_ = 0; } ListValue::~ListValue() { @@ -1248,9 +1228,7 @@ void ListValue::ArenaDtor(void* object) { void ListValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void ListValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* ListValue::descriptor() { ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1258,7 +1236,7 @@ const ::google::protobuf::Descriptor* ListValue::descriptor() { } const ListValue& ListValue::default_instance() { - ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base); return *internal_default_instance(); } @@ -1279,7 +1257,7 @@ bool ListValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.ListValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1381,9 +1359,7 @@ size_t ListValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1453,7 +1429,6 @@ void ListValue::InternalSwap(ListValue* other) { using std::swap; CastToBase(&values_)->InternalSwap(CastToBase(&other->values_)); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata ListValue::GetMetadata() const { @@ -1467,16 +1442,16 @@ void ListValue::InternalSwap(ListValue* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct* Arena::CreateMessage< ::google::protobuf::Struct >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct* Arena::CreateMaybeMessage< ::google::protobuf::Struct >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Struct >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Value* Arena::CreateMessage< ::google::protobuf::Value >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Value* Arena::CreateMaybeMessage< ::google::protobuf::Value >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Value >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMessage< ::google::protobuf::ListValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMaybeMessage< ::google::protobuf::ListValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::ListValue >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h index 91aa3cf24c..75665ff264 100644 --- a/src/google/protobuf/struct.pb.h +++ b/src/google/protobuf/struct.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto -#ifndef PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto #include @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: export @@ -34,6 +35,7 @@ #include #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2fstruct_2eproto { // Internal implementation detail -- do not use these members. @@ -46,11 +48,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsListValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsListValue(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsListValue(); -} } // namespace protobuf_google_2fprotobuf_2fstruct_2eproto namespace google { namespace protobuf { @@ -70,10 +67,10 @@ LIBPROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMessage< ::google::protobuf::ListValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMessage< ::google::protobuf::Struct>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMessage< ::google::protobuf::Value>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMaybeMessage<::google::protobuf::ListValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMaybeMessage<::google::protobuf::Struct>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMaybeMessage<::google::protobuf::Value>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -116,7 +113,7 @@ public: Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena); void MergeFrom(const Struct_FieldsEntry_DoNotUse& other); static const Struct_FieldsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_Struct_FieldsEntry_DoNotUse_default_instance_); } - void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL; + void MergeFrom(const ::google::protobuf::Message& other) final; ::google::protobuf::Metadata GetMetadata() const; }; @@ -148,10 +145,10 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -162,7 +159,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc return reinterpret_cast( &_Struct_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void UnsafeArenaSwap(Struct* other); @@ -173,32 +170,33 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- - inline Struct* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Struct* New() const final { + return CreateMaybeMessage(NULL); } - Struct* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Struct* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Struct& from); void MergeFrom(const Struct& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Struct* other); protected: explicit Struct(::google::protobuf::Arena* arena); @@ -214,7 +212,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -243,9 +241,8 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > fields_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl(); }; // ------------------------------------------------------------------- @@ -275,10 +272,10 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -299,7 +296,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast( &_Value_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void UnsafeArenaSwap(Value* other); @@ -310,32 +307,33 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Value* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Value* New() const final { + return CreateMaybeMessage(NULL); } - Value* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Value* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Value& from); void MergeFrom(const Value& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Value* other); protected: explicit Value(::google::protobuf::Arena* arena); @@ -351,7 +349,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -414,6 +412,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ bool has_struct_value() const; void clear_struct_value(); static const int kStructValueFieldNumber = 5; + private: + const ::google::protobuf::Struct& _internal_struct_value() const; + public: const ::google::protobuf::Struct& struct_value() const; ::google::protobuf::Struct* release_struct_value(); ::google::protobuf::Struct* mutable_struct_value(); @@ -426,6 +427,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ bool has_list_value() const; void clear_list_value(); static const int kListValueFieldNumber = 6; + private: + const ::google::protobuf::ListValue& _internal_list_value() const; + public: const ::google::protobuf::ListValue& list_value() const; ::google::protobuf::ListValue* release_list_value(); ::google::protobuf::ListValue* mutable_list_value(); @@ -434,6 +438,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::ListValue* list_value); ::google::protobuf::ListValue* unsafe_arena_release_list_value(); + void clear_kind(); KindCase kind_case() const; // @@protoc_insertion_point(class_scope:google.protobuf.Value) private: @@ -445,7 +450,6 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ void set_has_list_value(); inline bool has_kind() const; - void clear_kind(); inline void clear_has_kind(); ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; @@ -461,11 +465,10 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::Struct* struct_value_; ::google::protobuf::ListValue* list_value_; } kind_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::uint32 _oneof_case_[1]; friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl(); }; // ------------------------------------------------------------------- @@ -495,10 +498,10 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -509,7 +512,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro return reinterpret_cast( &_ListValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void UnsafeArenaSwap(ListValue* other); @@ -520,32 +523,33 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline ListValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline ListValue* New() const final { + return CreateMaybeMessage(NULL); } - ListValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + ListValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const ListValue& from); void MergeFrom(const ListValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(ListValue* other); protected: explicit ListValue(::google::protobuf::Arena* arena); @@ -561,7 +565,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -587,9 +591,8 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Value > values_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2fstruct_2eproto::InitDefaultsListValueImpl(); }; // =================================================================== @@ -852,13 +855,16 @@ inline void Value::clear_struct_value() { clear_has_kind(); } } +inline const ::google::protobuf::Struct& Value::_internal_struct_value() const { + return *kind_.struct_value_; +} inline ::google::protobuf::Struct* Value::release_struct_value() { // @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value) if (has_struct_value()) { clear_has_kind(); ::google::protobuf::Struct* temp = kind_.struct_value_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } kind_.struct_value_ = NULL; return temp; @@ -895,7 +901,7 @@ inline ::google::protobuf::Struct* Value::mutable_struct_value() { if (!has_struct_value()) { clear_kind(); set_has_struct_value(); - kind_.struct_value_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >( + kind_.struct_value_ = CreateMaybeMessage< ::google::protobuf::Struct >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value) @@ -917,13 +923,16 @@ inline void Value::clear_list_value() { clear_has_kind(); } } +inline const ::google::protobuf::ListValue& Value::_internal_list_value() const { + return *kind_.list_value_; +} inline ::google::protobuf::ListValue* Value::release_list_value() { // @@protoc_insertion_point(field_release:google.protobuf.Value.list_value) if (has_list_value()) { clear_has_kind(); ::google::protobuf::ListValue* temp = kind_.list_value_; if (GetArenaNoVirtual() != NULL) { - temp = ::google::protobuf::internal::DuplicateIfNonNull(temp, NULL); + temp = ::google::protobuf::internal::DuplicateIfNonNull(temp); } kind_.list_value_ = NULL; return temp; @@ -960,7 +969,7 @@ inline ::google::protobuf::ListValue* Value::mutable_list_value() { if (!has_list_value()) { clear_kind(); set_has_list_value(); - kind_.list_value_ = ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >( + kind_.list_value_ = CreateMaybeMessage< ::google::protobuf::ListValue >( GetArenaNoVirtual()); } // @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value) @@ -1028,7 +1037,7 @@ ListValue::values() const { namespace google { namespace protobuf { -template <> struct is_proto_enum< ::google::protobuf::NullValue> : ::google::protobuf::internal::true_type {}; +template <> struct is_proto_enum< ::google::protobuf::NullValue> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>() { return ::google::protobuf::NullValue_descriptor(); @@ -1039,4 +1048,4 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>() // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2fstruct_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto diff --git a/src/google/protobuf/stubs/callback.h b/src/google/protobuf/stubs/callback.h index 9ec0497955..6888f136dd 100644 --- a/src/google/protobuf/stubs/callback.h +++ b/src/google/protobuf/stubs/callback.h @@ -1,8 +1,9 @@ #ifndef GOOGLE_PROTOBUF_STUBS_CALLBACK_H_ #define GOOGLE_PROTOBUF_STUBS_CALLBACK_H_ +#include + #include -#include // =================================================================== // emulates google3/base/callback.h @@ -342,7 +343,7 @@ class FunctionResultCallback_1_1 : public ResultCallback1 { template struct InternalConstRef { - typedef typename remove_reference::type base_type; + typedef typename std::remove_reference::type base_type; typedef const base_type& type; }; @@ -397,11 +398,11 @@ class MethodResultCallback_5_2 : public ResultCallback2 { T* object_; MethodType method_; bool self_deleting_; - typename remove_reference::type p1_; - typename remove_reference::type p2_; - typename remove_reference::type p3_; - typename remove_reference::type p4_; - typename remove_reference::type p5_; + typename std::remove_reference::type p1_; + typename std::remove_reference::type p2_; + typename std::remove_reference::type p3_; + typename std::remove_reference::type p4_; + typename std::remove_reference::type p5_; }; } // namespace internal diff --git a/src/google/protobuf/stubs/casts.h b/src/google/protobuf/stubs/casts.h index be652849ef..35e2dba058 100644 --- a/src/google/protobuf/stubs/casts.h +++ b/src/google/protobuf/stubs/casts.h @@ -31,8 +31,9 @@ #ifndef GOOGLE_PROTOBUF_CASTS_H__ #define GOOGLE_PROTOBUF_CASTS_H__ +#include + #include -#include namespace google { namespace protobuf { @@ -95,7 +96,7 @@ inline To down_cast(From* f) { // so we only accept pointers template // use like this: down_cast(foo); inline To down_cast(From& f) { - typedef typename remove_reference::type* ToAsPointer; + typedef typename std::remove_reference::type* ToAsPointer; // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away diff --git a/src/google/protobuf/stubs/common.cc b/src/google/protobuf/stubs/common.cc index 574c7405c6..33d24c57cb 100755 --- a/src/google/protobuf/stubs/common.cc +++ b/src/google/protobuf/stubs/common.cc @@ -313,86 +313,6 @@ namespace internal { FunctionClosure0::~FunctionClosure0() {} } void DoNothing() {} -// =================================================================== -// emulates google3/base/mutex.cc - -#ifdef _WIN32 - -struct Mutex::Internal { - CRITICAL_SECTION mutex; -#ifndef NDEBUG - // Used only to implement AssertHeld(). - DWORD thread_id; -#endif -}; - -Mutex::Mutex() - : mInternal(new Internal) { - InitializeCriticalSection(&mInternal->mutex); -} - -Mutex::~Mutex() { - DeleteCriticalSection(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - EnterCriticalSection(&mInternal->mutex); -#ifndef NDEBUG - mInternal->thread_id = GetCurrentThreadId(); -#endif -} - -void Mutex::Unlock() { -#ifndef NDEBUG - mInternal->thread_id = 0; -#endif - LeaveCriticalSection(&mInternal->mutex); -} - -void Mutex::AssertHeld() { -#ifndef NDEBUG - GOOGLE_DCHECK_EQ(mInternal->thread_id, GetCurrentThreadId()); -#endif -} - -#elif defined(HAVE_PTHREAD) - -struct Mutex::Internal { - pthread_mutex_t mutex; -}; - -Mutex::Mutex() - : mInternal(new Internal) { - pthread_mutex_init(&mInternal->mutex, NULL); -} - -Mutex::~Mutex() { - pthread_mutex_destroy(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - int result = pthread_mutex_lock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_lock: " << strerror(result); - } -} - -void Mutex::Unlock() { - int result = pthread_mutex_unlock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_unlock: " << strerror(result); - } -} - -void Mutex::AssertHeld() { - // pthreads dosn't provide a way to check which thread holds the mutex. - // TODO(kenton): Maybe keep track of locking thread ID like with WIN32? -} - -#endif - // =================================================================== // emulates google3/util/endian/endian.h // diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h index 04660b8163..2fe8a98bc1 100644 --- a/src/google/protobuf/stubs/common.h +++ b/src/google/protobuf/stubs/common.h @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -48,7 +49,6 @@ // TODO(liujisi): Remove the following includes after the include clean-up. #include -#include #include #include @@ -231,6 +231,18 @@ class FatalException : public std::exception { // in some versions of MSVC. using std::string; +// TODO(gerbens) remove once an extraction cycle has removed all references +namespace internal { +template +using scoped_ptr = std::unique_ptr; +template +using scoped_array = std::unique_ptr; +} // namespace internal +template +using scoped_ptr = std::unique_ptr; +template +using scoped_array = std::unique_ptr; + } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/io_win32.cc b/src/google/protobuf/stubs/io_win32.cc index 5ead98c811..4407facb40 100644 --- a/src/google/protobuf/stubs/io_win32.cc +++ b/src/google/protobuf/stubs/io_win32.cc @@ -52,13 +52,13 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include @@ -229,7 +229,7 @@ bool as_windows_path(const char* path, wstring* result) { if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { return false; } - scoped_array wcwd(new WCHAR[size]); + std::unique_ptr wcwd(new WCHAR[size]); ::GetCurrentDirectoryW(size, wcwd.get()); wpath = join_paths(wcwd.get(), wpath); } @@ -371,7 +371,7 @@ bool wcs_to_mbs(const WCHAR* s, string* out, bool outUtf8) { || usedDefaultChar) { return false; } - scoped_array astr(new CHAR[size]); + std::unique_ptr astr(new CHAR[size]); WideCharToMultiByte( outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, NULL, NULL); out->assign(astr.get()); @@ -390,7 +390,7 @@ bool mbs_to_wcs(const char* s, wstring* out, bool inUtf8) { if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) { return false; } - scoped_array wstr(new WCHAR[size]); + std::unique_ptr wstr(new WCHAR[size]); MultiByteToWideChar( inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, wstr.get(), size + 1); out->assign(wstr.get()); diff --git a/src/google/protobuf/stubs/io_win32_unittest.cc b/src/google/protobuf/stubs/io_win32_unittest.cc index b216aece34..c933757c77 100644 --- a/src/google/protobuf/stubs/io_win32_unittest.cc +++ b/src/google/protobuf/stubs/io_win32_unittest.cc @@ -48,7 +48,6 @@ #include #include -#include #include #include @@ -115,7 +114,7 @@ void StripTrailingSlashes(string* str) { bool GetEnvVarAsUtf8(const WCHAR* name, string* result) { DWORD size = ::GetEnvironmentVariableW(name, NULL, 0); if (size > 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) { - scoped_array wcs(new WCHAR[size]); + std::unique_ptr wcs(new WCHAR[size]); ::GetEnvironmentVariableW(name, wcs.get(), size); // GetEnvironmentVariableA retrieves an Active-Code-Page-encoded text which // we'd first need to convert to UTF-16 then to UTF-8, because there seems @@ -131,7 +130,7 @@ bool GetEnvVarAsUtf8(const WCHAR* name, string* result) { bool GetCwdAsUtf8(string* result) { DWORD size = ::GetCurrentDirectoryW(0, NULL); if (size > 0) { - scoped_array wcs(new WCHAR[size]); + std::unique_ptr wcs(new WCHAR[size]); ::GetCurrentDirectoryW(size, wcs.get()); // GetCurrentDirectoryA retrieves an Active-Code-Page-encoded text which // we'd first need to convert to UTF-16 then to UTF-8, because there seems @@ -402,7 +401,7 @@ TEST_F(IoWin32Test, ChdirTestNonAscii) { TEST_F(IoWin32Test, AsWindowsPathTest) { DWORD size = GetCurrentDirectoryW(0, NULL); - scoped_array cwd_str(new wchar_t[size]); + std::unique_ptr cwd_str(new wchar_t[size]); EXPECT_GT(GetCurrentDirectoryW(size, cwd_str.get()), 0); wstring cwd = wstring(L"\\\\?\\") + cwd_str.get(); diff --git a/src/google/protobuf/stubs/mutex.h b/src/google/protobuf/stubs/mutex.h index 174290f624..b9b7d2e1be 100644 --- a/src/google/protobuf/stubs/mutex.h +++ b/src/google/protobuf/stubs/mutex.h @@ -30,9 +30,7 @@ #ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_ #define GOOGLE_PROTOBUF_STUBS_MUTEX_H_ -#ifdef GOOGLE_PROTOBUF_NO_THREADLOCAL -#include -#endif +#include #include @@ -42,34 +40,26 @@ namespace google { namespace protobuf { namespace internal { -// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T -// may hold a mutex at a given time. If T attempts to Lock() the same Mutex -// while holding it, T will deadlock. -class LIBPROTOBUF_EXPORT Mutex { - public: - // Create a Mutex that is not held by anybody. - Mutex(); - - // Destructor - ~Mutex(); - - // Block if necessary until this Mutex is free, then acquire it exclusively. - void Lock(); - - // Release this Mutex. Caller must hold it exclusively. - void Unlock(); +#define GOOGLE_PROTOBUF_LINKER_INITIALIZED +// Mutex is a natural type to wrap. As both google and other organization have +// specialized mutexes. gRPC also provides an injection mechanism for custom +// mutexes. +class LIBPROTOBUF_EXPORT WrappedMutex { + public: + WrappedMutex() = default; + void Lock() { mu_.lock(); } + void Unlock() { mu_.unlock(); } // Crash if this Mutex is not held exclusively by this thread. // May fail to crash when it should; will never crash when it should not. - void AssertHeld(); + void AssertHeld() const {} private: - struct Internal; - Internal* mInternal; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex); + std::mutex mu_; }; +using Mutex = WrappedMutex; + // MutexLock(mu) acquires mu when constructed and releases it when destroyed. class LIBPROTOBUF_EXPORT MutexLock { public: diff --git a/src/google/protobuf/stubs/once.h b/src/google/protobuf/stubs/once.h index 1f082c37e9..f3835ccd04 100644 --- a/src/google/protobuf/stubs/once.h +++ b/src/google/protobuf/stubs/once.h @@ -78,88 +78,51 @@ #ifndef GOOGLE_PROTOBUF_STUBS_ONCE_H__ #define GOOGLE_PROTOBUF_STUBS_ONCE_H__ -#include -#include -#include +#include +#include namespace google { namespace protobuf { +namespace internal { -#ifdef GOOGLE_PROTOBUF_NO_THREAD_SAFETY - -typedef bool ProtobufOnceType; - -#define GOOGLE_PROTOBUF_ONCE_INIT false - -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - if (!*once) { - *once = true; - init_func(); - } +using once_flag = std::once_flag; +template +void call_once(Args&&... args ) { + std::call_once(std::forward(args)...); } -template -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg), - Arg arg) { - if (!*once) { - *once = true; - init_func(arg); - } -} +} // namespace internal -#else - -enum { - ONCE_STATE_UNINITIALIZED = 0, - ONCE_STATE_EXECUTING_CLOSURE = 1, - ONCE_STATE_DONE = 2 -}; - -typedef internal::AtomicWord ProtobufOnceType; - -#define GOOGLE_PROTOBUF_ONCE_INIT ::google::protobuf::ONCE_STATE_UNINITIALIZED - -LIBPROTOBUF_EXPORT -void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure); +// TODO(gerbens) remove this once third_party is fully extracted +using ProtobufOnceType = internal::once_flag; inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - if (internal::Acquire_Load(once) != ONCE_STATE_DONE) { - internal::FunctionClosure0 func(init_func, false); - GoogleOnceInitImpl(once, &func); - } + std::call_once(*once, init_func); } template -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)(Arg*), - Arg* arg) { - if (internal::Acquire_Load(once) != ONCE_STATE_DONE) { - internal::FunctionClosure1 func(init_func, false, arg); - GoogleOnceInitImpl(once, &func); - } +inline void GoogleOnceInitArg(ProtobufOnceType* once, void (*init_func)(Arg*), + Arg* arg) { + std::call_once(*once, init_func, arg); } -#endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY - class GoogleOnceDynamic { public: - GoogleOnceDynamic() : state_(GOOGLE_PROTOBUF_ONCE_INIT) { } - // If this->Init() has not been called before by any thread, // execute (*func_with_arg)(arg) then return. // Otherwise, wait until that prior invocation has finished // executing its function, then return. template void Init(void (*func_with_arg)(T*), T* arg) { - GoogleOnceInit(&this->state_, - func_with_arg, - arg); + GoogleOnceInitArg(&this->state_, func_with_arg, arg); } private: ProtobufOnceType state_; }; +#define GOOGLE_PROTOBUF_ONCE_TYPE ::google::protobuf::ProtobufOnceType #define GOOGLE_PROTOBUF_DECLARE_ONCE(NAME) \ - ::google::protobuf::ProtobufOnceType NAME = GOOGLE_PROTOBUF_ONCE_INIT + ::google::protobuf::ProtobufOnceType NAME } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h index 27849298ea..de83def0ec 100644 --- a/src/google/protobuf/stubs/port.h +++ b/src/google/protobuf/stubs/port.h @@ -93,7 +93,7 @@ #include // NOLINT(build/include) #elif defined(__APPLE__) #include -#elif defined(__GLIBC__) || defined(__CYGWIN__) +#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__) #include // IWYU pragma: export #endif @@ -209,6 +209,19 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #define GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE +#ifndef GOOGLE_ATTRIBUTE_FUNC_ALIGN +#if defined(__clang__) || \ + defined(__GNUC__) && (__GNUC__ > 4 ||(__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +// Function alignment attribute introduced in gcc 4.3 +#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) __attribute__ ((aligned(bytes))) +#else +#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) +#endif +#endif + +#define GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(bytes) \ + GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) + #ifndef GOOGLE_PREDICT_TRUE #ifdef __GNUC__ // Provided at least since GCC 3.0. @@ -227,6 +240,13 @@ static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); #endif #endif +#ifndef GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL +#ifdef __GNUC__ +#define GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL \ + __attribute__((returns_nonnull)) +#endif +#endif + // Delimits a block of code which may write to memory which is simultaneously // written by other threads, but which has been determined to be thread-safe // (e.g. because it is an idempotent write). @@ -359,7 +379,7 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) { #define bswap_32(x) OSSwapInt32(x) #define bswap_64(x) OSSwapInt64(x) -#elif !defined(__GLIBC__) && !defined(__CYGWIN__) +#elif !defined(__GLIBC__) && !defined(__BIONIC__) && !defined(__CYGWIN__) static inline uint16 bswap_16(uint16 x) { return static_cast(((x & 0xFF) << 8) | ((x & 0xFF00) >> 8)); diff --git a/src/google/protobuf/stubs/singleton.h b/src/google/protobuf/stubs/singleton.h index 9301f549b1..2e6ccbdb67 100644 --- a/src/google/protobuf/stubs/singleton.h +++ b/src/google/protobuf/stubs/singleton.h @@ -30,7 +30,6 @@ #ifndef GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ #define GOOGLE_PROTOBUF_STUBS_SINGLETON_H__ -#include #include #include diff --git a/src/google/protobuf/test_util.cc b/src/google/protobuf/test_util.cc index 4e02a85d85..795cb6ae17 100644 --- a/src/google/protobuf/test_util.cc +++ b/src/google/protobuf/test_util.cc @@ -39,3312 +39,9 @@ #endif #include -#include -#include - -#include -#include -#include -#include namespace google { namespace protobuf { -void TestUtil::SetAllFields(unittest::TestAllTypes* message) { - SetOptionalFields(message); - AddRepeatedFields1(message); - AddRepeatedFields2(message); - SetDefaultFields(message); - SetOneofFields(message); -} - -void TestUtil::SetOptionalFields(unittest::TestAllTypes* message) { - message->set_optional_int32 (101); - message->set_optional_int64 (102); - message->set_optional_uint32 (103); - message->set_optional_uint64 (104); - message->set_optional_sint32 (105); - message->set_optional_sint64 (106); - message->set_optional_fixed32 (107); - message->set_optional_fixed64 (108); - message->set_optional_sfixed32(109); - message->set_optional_sfixed64(110); - message->set_optional_float (111); - message->set_optional_double (112); - message->set_optional_bool (true); - message->set_optional_string ("115"); - message->set_optional_bytes ("116"); - - message->mutable_optionalgroup ()->set_a(117); - message->mutable_optional_nested_message ()->set_bb(118); - message->mutable_optional_foreign_message ()->set_c(119); - message->mutable_optional_import_message ()->set_d(120); - message->mutable_optional_public_import_message()->set_e(126); - message->mutable_optional_lazy_message ()->set_bb(127); - - message->set_optional_nested_enum (unittest::TestAllTypes::BAZ); - message->set_optional_foreign_enum(unittest::FOREIGN_BAZ ); - message->set_optional_import_enum (unittest_import::IMPORT_BAZ); - - // StringPiece and Cord fields are only accessible via reflection in the - // open source release; see comments in compiler/cpp/string_field.cc. -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("optional_string_piece"), - "124"); - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("optional_cord"), - "125"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::AddRepeatedFields1(unittest::TestAllTypes* message) { - message->add_repeated_int32 (201); - message->add_repeated_int64 (202); - message->add_repeated_uint32 (203); - message->add_repeated_uint64 (204); - message->add_repeated_sint32 (205); - message->add_repeated_sint64 (206); - message->add_repeated_fixed32 (207); - message->add_repeated_fixed64 (208); - message->add_repeated_sfixed32(209); - message->add_repeated_sfixed64(210); - message->add_repeated_float (211); - message->add_repeated_double (212); - message->add_repeated_bool (true); - message->add_repeated_string ("215"); - message->add_repeated_bytes ("216"); - - message->add_repeatedgroup ()->set_a(217); - message->add_repeated_nested_message ()->set_bb(218); - message->add_repeated_foreign_message()->set_c(219); - message->add_repeated_import_message ()->set_d(220); - message->add_repeated_lazy_message ()->set_bb(227); - - message->add_repeated_nested_enum (unittest::TestAllTypes::BAR); - message->add_repeated_foreign_enum(unittest::FOREIGN_BAR ); - message->add_repeated_import_enum (unittest_import::IMPORT_BAR); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - "224"); - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - "225"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -void TestUtil::AddRepeatedFields2(unittest::TestAllTypes* message) { - // Add a second one of each field. - message->add_repeated_int32 (301); - message->add_repeated_int64 (302); - message->add_repeated_uint32 (303); - message->add_repeated_uint64 (304); - message->add_repeated_sint32 (305); - message->add_repeated_sint64 (306); - message->add_repeated_fixed32 (307); - message->add_repeated_fixed64 (308); - message->add_repeated_sfixed32(309); - message->add_repeated_sfixed64(310); - message->add_repeated_float (311); - message->add_repeated_double (312); - message->add_repeated_bool (false); - message->add_repeated_string ("315"); - message->add_repeated_bytes ("316"); - - message->add_repeatedgroup ()->set_a(317); - message->add_repeated_nested_message ()->set_bb(318); - message->add_repeated_foreign_message()->set_c(319); - message->add_repeated_import_message ()->set_d(320); - message->add_repeated_lazy_message ()->set_bb(327); - - message->add_repeated_nested_enum (unittest::TestAllTypes::BAZ); - message->add_repeated_foreign_enum(unittest::FOREIGN_BAZ ); - message->add_repeated_import_enum (unittest_import::IMPORT_BAZ); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - "324"); - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - "325"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::SetDefaultFields(unittest::TestAllTypes* message) { - message->set_default_int32 (401); - message->set_default_int64 (402); - message->set_default_uint32 (403); - message->set_default_uint64 (404); - message->set_default_sint32 (405); - message->set_default_sint64 (406); - message->set_default_fixed32 (407); - message->set_default_fixed64 (408); - message->set_default_sfixed32(409); - message->set_default_sfixed64(410); - message->set_default_float (411); - message->set_default_double (412); - message->set_default_bool (false); - message->set_default_string ("415"); - message->set_default_bytes ("416"); - - message->set_default_nested_enum (unittest::TestAllTypes::FOO); - message->set_default_foreign_enum(unittest::FOREIGN_FOO ); - message->set_default_import_enum (unittest_import::IMPORT_FOO); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("default_string_piece"), - "424"); - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("default_cord"), - "425"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyRepeatedFields(unittest::TestAllTypes* message) { - message->set_repeated_int32 (1, 501); - message->set_repeated_int64 (1, 502); - message->set_repeated_uint32 (1, 503); - message->set_repeated_uint64 (1, 504); - message->set_repeated_sint32 (1, 505); - message->set_repeated_sint64 (1, 506); - message->set_repeated_fixed32 (1, 507); - message->set_repeated_fixed64 (1, 508); - message->set_repeated_sfixed32(1, 509); - message->set_repeated_sfixed64(1, 510); - message->set_repeated_float (1, 511); - message->set_repeated_double (1, 512); - message->set_repeated_bool (1, true); - message->set_repeated_string (1, "515"); - message->set_repeated_bytes (1, "516"); - - message->mutable_repeatedgroup (1)->set_a(517); - message->mutable_repeated_nested_message (1)->set_bb(518); - message->mutable_repeated_foreign_message(1)->set_c(519); - message->mutable_repeated_import_message (1)->set_d(520); - message->mutable_repeated_lazy_message (1)->set_bb(527); - - message->set_repeated_nested_enum (1, unittest::TestAllTypes::FOO); - message->set_repeated_foreign_enum(1, unittest::FOREIGN_FOO ); - message->set_repeated_import_enum (1, unittest_import::IMPORT_FOO); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetRepeatedString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - 1, "524"); - message->GetReflection()->SetRepeatedString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - 1, "525"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------ -void TestUtil::SetOneofFields(unittest::TestAllTypes* message) { - message->set_oneof_uint32(601); - message->mutable_oneof_nested_message()->set_bb(602); - message->set_oneof_string("603"); - message->set_oneof_bytes("604"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllFieldsSet(const unittest::TestAllTypes& message) { - EXPECT_TRUE(message.has_optional_int32 ()); - EXPECT_TRUE(message.has_optional_int64 ()); - EXPECT_TRUE(message.has_optional_uint32 ()); - EXPECT_TRUE(message.has_optional_uint64 ()); - EXPECT_TRUE(message.has_optional_sint32 ()); - EXPECT_TRUE(message.has_optional_sint64 ()); - EXPECT_TRUE(message.has_optional_fixed32 ()); - EXPECT_TRUE(message.has_optional_fixed64 ()); - EXPECT_TRUE(message.has_optional_sfixed32()); - EXPECT_TRUE(message.has_optional_sfixed64()); - EXPECT_TRUE(message.has_optional_float ()); - EXPECT_TRUE(message.has_optional_double ()); - EXPECT_TRUE(message.has_optional_bool ()); - EXPECT_TRUE(message.has_optional_string ()); - EXPECT_TRUE(message.has_optional_bytes ()); - - EXPECT_TRUE(message.has_optionalgroup ()); - EXPECT_TRUE(message.has_optional_nested_message ()); - EXPECT_TRUE(message.has_optional_foreign_message ()); - EXPECT_TRUE(message.has_optional_import_message ()); - EXPECT_TRUE(message.has_optional_public_import_message()); - EXPECT_TRUE(message.has_optional_lazy_message ()); - - EXPECT_TRUE(message.optionalgroup ().has_a()); - EXPECT_TRUE(message.optional_nested_message ().has_bb()); - EXPECT_TRUE(message.optional_foreign_message ().has_c()); - EXPECT_TRUE(message.optional_import_message ().has_d()); - EXPECT_TRUE(message.optional_public_import_message().has_e()); - EXPECT_TRUE(message.optional_lazy_message ().has_bb()); - - EXPECT_TRUE(message.has_optional_nested_enum ()); - EXPECT_TRUE(message.has_optional_foreign_enum()); - EXPECT_TRUE(message.has_optional_import_enum ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - EXPECT_TRUE(message.has_optional_string_piece()); - EXPECT_TRUE(message.has_optional_cord()); -#endif - - EXPECT_EQ(101 , message.optional_int32 ()); - EXPECT_EQ(102 , message.optional_int64 ()); - EXPECT_EQ(103 , message.optional_uint32 ()); - EXPECT_EQ(104 , message.optional_uint64 ()); - EXPECT_EQ(105 , message.optional_sint32 ()); - EXPECT_EQ(106 , message.optional_sint64 ()); - EXPECT_EQ(107 , message.optional_fixed32 ()); - EXPECT_EQ(108 , message.optional_fixed64 ()); - EXPECT_EQ(109 , message.optional_sfixed32()); - EXPECT_EQ(110 , message.optional_sfixed64()); - EXPECT_EQ(111 , message.optional_float ()); - EXPECT_EQ(112 , message.optional_double ()); - EXPECT_TRUE( message.optional_bool ()); - EXPECT_EQ("115", message.optional_string ()); - EXPECT_EQ("116", message.optional_bytes ()); - - EXPECT_EQ(117, message.optionalgroup ().a()); - EXPECT_EQ(118, message.optional_nested_message ().bb()); - EXPECT_EQ(119, message.optional_foreign_message ().c()); - EXPECT_EQ(120, message.optional_import_message ().d()); - EXPECT_EQ(126, message.optional_public_import_message ().e()); - EXPECT_EQ(127, message.optional_lazy_message ().bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.optional_import_enum ()); - - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_lazy_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_TRUE( message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(227, message.repeated_lazy_message (0).bb()); - - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); - - EXPECT_EQ(301 , message.repeated_int32 (1)); - EXPECT_EQ(302 , message.repeated_int64 (1)); - EXPECT_EQ(303 , message.repeated_uint32 (1)); - EXPECT_EQ(304 , message.repeated_uint64 (1)); - EXPECT_EQ(305 , message.repeated_sint32 (1)); - EXPECT_EQ(306 , message.repeated_sint64 (1)); - EXPECT_EQ(307 , message.repeated_fixed32 (1)); - EXPECT_EQ(308 , message.repeated_fixed64 (1)); - EXPECT_EQ(309 , message.repeated_sfixed32(1)); - EXPECT_EQ(310 , message.repeated_sfixed64(1)); - EXPECT_EQ(311 , message.repeated_float (1)); - EXPECT_EQ(312 , message.repeated_double (1)); - EXPECT_FALSE( message.repeated_bool (1)); - EXPECT_EQ("315", message.repeated_string (1)); - EXPECT_EQ("316", message.repeated_bytes (1)); - - EXPECT_EQ(317, message.repeatedgroup (1).a()); - EXPECT_EQ(318, message.repeated_nested_message (1).bb()); - EXPECT_EQ(319, message.repeated_foreign_message(1).c()); - EXPECT_EQ(320, message.repeated_import_message (1).d()); - EXPECT_EQ(327, message.repeated_lazy_message (1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (1)); - - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.has_default_int32 ()); - EXPECT_TRUE(message.has_default_int64 ()); - EXPECT_TRUE(message.has_default_uint32 ()); - EXPECT_TRUE(message.has_default_uint64 ()); - EXPECT_TRUE(message.has_default_sint32 ()); - EXPECT_TRUE(message.has_default_sint64 ()); - EXPECT_TRUE(message.has_default_fixed32 ()); - EXPECT_TRUE(message.has_default_fixed64 ()); - EXPECT_TRUE(message.has_default_sfixed32()); - EXPECT_TRUE(message.has_default_sfixed64()); - EXPECT_TRUE(message.has_default_float ()); - EXPECT_TRUE(message.has_default_double ()); - EXPECT_TRUE(message.has_default_bool ()); - EXPECT_TRUE(message.has_default_string ()); - EXPECT_TRUE(message.has_default_bytes ()); - - EXPECT_TRUE(message.has_default_nested_enum ()); - EXPECT_TRUE(message.has_default_foreign_enum()); - EXPECT_TRUE(message.has_default_import_enum ()); - - - EXPECT_EQ(401 , message.default_int32 ()); - EXPECT_EQ(402 , message.default_int64 ()); - EXPECT_EQ(403 , message.default_uint32 ()); - EXPECT_EQ(404 , message.default_uint64 ()); - EXPECT_EQ(405 , message.default_sint32 ()); - EXPECT_EQ(406 , message.default_sint64 ()); - EXPECT_EQ(407 , message.default_fixed32 ()); - EXPECT_EQ(408 , message.default_fixed64 ()); - EXPECT_EQ(409 , message.default_sfixed32()); - EXPECT_EQ(410 , message.default_sfixed64()); - EXPECT_EQ(411 , message.default_float ()); - EXPECT_EQ(412 , message.default_double ()); - EXPECT_FALSE( message.default_bool ()); - EXPECT_EQ("415", message.default_string ()); - EXPECT_EQ("416", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_FOO , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.default_import_enum ()); - - - EXPECT_FALSE(message.has_oneof_uint32 ()); - EXPECT_FALSE(message.has_oneof_nested_message()); - EXPECT_FALSE(message.has_oneof_string ()); - EXPECT_TRUE(message.has_oneof_bytes ()); - - EXPECT_EQ("604", message.oneof_bytes()); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectClear(const unittest::TestAllTypes& message) { - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.has_optional_int32 ()); - EXPECT_FALSE(message.has_optional_int64 ()); - EXPECT_FALSE(message.has_optional_uint32 ()); - EXPECT_FALSE(message.has_optional_uint64 ()); - EXPECT_FALSE(message.has_optional_sint32 ()); - EXPECT_FALSE(message.has_optional_sint64 ()); - EXPECT_FALSE(message.has_optional_fixed32 ()); - EXPECT_FALSE(message.has_optional_fixed64 ()); - EXPECT_FALSE(message.has_optional_sfixed32()); - EXPECT_FALSE(message.has_optional_sfixed64()); - EXPECT_FALSE(message.has_optional_float ()); - EXPECT_FALSE(message.has_optional_double ()); - EXPECT_FALSE(message.has_optional_bool ()); - EXPECT_FALSE(message.has_optional_string ()); - EXPECT_FALSE(message.has_optional_bytes ()); - - EXPECT_FALSE(message.has_optionalgroup ()); - EXPECT_FALSE(message.has_optional_nested_message ()); - EXPECT_FALSE(message.has_optional_foreign_message ()); - EXPECT_FALSE(message.has_optional_import_message ()); - EXPECT_FALSE(message.has_optional_public_import_message()); - EXPECT_FALSE(message.has_optional_lazy_message ()); - - EXPECT_FALSE(message.has_optional_nested_enum ()); - EXPECT_FALSE(message.has_optional_foreign_enum()); - EXPECT_FALSE(message.has_optional_import_enum ()); - - EXPECT_FALSE(message.has_optional_string_piece()); - EXPECT_FALSE(message.has_optional_cord()); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.optional_int32 ()); - EXPECT_EQ(0 , message.optional_int64 ()); - EXPECT_EQ(0 , message.optional_uint32 ()); - EXPECT_EQ(0 , message.optional_uint64 ()); - EXPECT_EQ(0 , message.optional_sint32 ()); - EXPECT_EQ(0 , message.optional_sint64 ()); - EXPECT_EQ(0 , message.optional_fixed32 ()); - EXPECT_EQ(0 , message.optional_fixed64 ()); - EXPECT_EQ(0 , message.optional_sfixed32()); - EXPECT_EQ(0 , message.optional_sfixed64()); - EXPECT_EQ(0 , message.optional_float ()); - EXPECT_EQ(0 , message.optional_double ()); - EXPECT_FALSE( message.optional_bool ()); - EXPECT_EQ("" , message.optional_string ()); - EXPECT_EQ("" , message.optional_bytes ()); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.optionalgroup ().has_a()); - EXPECT_FALSE(message.optional_nested_message ().has_bb()); - EXPECT_FALSE(message.optional_foreign_message ().has_c()); - EXPECT_FALSE(message.optional_import_message ().has_d()); - EXPECT_FALSE(message.optional_public_import_message().has_e()); - EXPECT_FALSE(message.optional_lazy_message ().has_bb()); - - EXPECT_EQ(0, message.optionalgroup ().a()); - EXPECT_EQ(0, message.optional_nested_message ().bb()); - EXPECT_EQ(0, message.optional_foreign_message ().c()); - EXPECT_EQ(0, message.optional_import_message ().d()); - EXPECT_EQ(0, message.optional_public_import_message().e()); - EXPECT_EQ(0, message.optional_lazy_message ().bb()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypes::FOO, message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_FOO , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.optional_import_enum ()); - - - // Repeated fields are empty. - EXPECT_EQ(0, message.repeated_int32_size ()); - EXPECT_EQ(0, message.repeated_int64_size ()); - EXPECT_EQ(0, message.repeated_uint32_size ()); - EXPECT_EQ(0, message.repeated_uint64_size ()); - EXPECT_EQ(0, message.repeated_sint32_size ()); - EXPECT_EQ(0, message.repeated_sint64_size ()); - EXPECT_EQ(0, message.repeated_fixed32_size ()); - EXPECT_EQ(0, message.repeated_fixed64_size ()); - EXPECT_EQ(0, message.repeated_sfixed32_size()); - EXPECT_EQ(0, message.repeated_sfixed64_size()); - EXPECT_EQ(0, message.repeated_float_size ()); - EXPECT_EQ(0, message.repeated_double_size ()); - EXPECT_EQ(0, message.repeated_bool_size ()); - EXPECT_EQ(0, message.repeated_string_size ()); - EXPECT_EQ(0, message.repeated_bytes_size ()); - - EXPECT_EQ(0, message.repeatedgroup_size ()); - EXPECT_EQ(0, message.repeated_nested_message_size ()); - EXPECT_EQ(0, message.repeated_foreign_message_size()); - EXPECT_EQ(0, message.repeated_import_message_size ()); - EXPECT_EQ(0, message.repeated_lazy_message_size ()); - EXPECT_EQ(0, message.repeated_nested_enum_size ()); - EXPECT_EQ(0, message.repeated_foreign_enum_size ()); - EXPECT_EQ(0, message.repeated_import_enum_size ()); - - EXPECT_EQ(0, message.repeated_string_piece_size()); - EXPECT_EQ(0, message.repeated_cord_size()); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.has_default_int32 ()); - EXPECT_FALSE(message.has_default_int64 ()); - EXPECT_FALSE(message.has_default_uint32 ()); - EXPECT_FALSE(message.has_default_uint64 ()); - EXPECT_FALSE(message.has_default_sint32 ()); - EXPECT_FALSE(message.has_default_sint64 ()); - EXPECT_FALSE(message.has_default_fixed32 ()); - EXPECT_FALSE(message.has_default_fixed64 ()); - EXPECT_FALSE(message.has_default_sfixed32()); - EXPECT_FALSE(message.has_default_sfixed64()); - EXPECT_FALSE(message.has_default_float ()); - EXPECT_FALSE(message.has_default_double ()); - EXPECT_FALSE(message.has_default_bool ()); - EXPECT_FALSE(message.has_default_string ()); - EXPECT_FALSE(message.has_default_bytes ()); - - EXPECT_FALSE(message.has_default_nested_enum ()); - EXPECT_FALSE(message.has_default_foreign_enum()); - EXPECT_FALSE(message.has_default_import_enum ()); - - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.default_int32 ()); - EXPECT_EQ( 42 , message.default_int64 ()); - EXPECT_EQ( 43 , message.default_uint32 ()); - EXPECT_EQ( 44 , message.default_uint64 ()); - EXPECT_EQ(-45 , message.default_sint32 ()); - EXPECT_EQ( 46 , message.default_sint64 ()); - EXPECT_EQ( 47 , message.default_fixed32 ()); - EXPECT_EQ( 48 , message.default_fixed64 ()); - EXPECT_EQ( 49 , message.default_sfixed32()); - EXPECT_EQ(-50 , message.default_sfixed64()); - EXPECT_EQ( 51.5 , message.default_float ()); - EXPECT_EQ( 52e3 , message.default_double ()); - EXPECT_TRUE( message.default_bool ()); - EXPECT_EQ("hello", message.default_string ()); - EXPECT_EQ("world", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_BAR , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.default_import_enum ()); - - - EXPECT_FALSE(message.has_oneof_uint32 ()); - EXPECT_FALSE(message.has_oneof_nested_message()); - EXPECT_FALSE(message.has_oneof_string ()); - EXPECT_FALSE(message.has_oneof_bytes ()); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectRepeatedFieldsModified( - const unittest::TestAllTypes& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_lazy_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_TRUE( message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(227, message.repeated_lazy_message (0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); - - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.repeated_int32 (1)); - EXPECT_EQ(502 , message.repeated_int64 (1)); - EXPECT_EQ(503 , message.repeated_uint32 (1)); - EXPECT_EQ(504 , message.repeated_uint64 (1)); - EXPECT_EQ(505 , message.repeated_sint32 (1)); - EXPECT_EQ(506 , message.repeated_sint64 (1)); - EXPECT_EQ(507 , message.repeated_fixed32 (1)); - EXPECT_EQ(508 , message.repeated_fixed64 (1)); - EXPECT_EQ(509 , message.repeated_sfixed32(1)); - EXPECT_EQ(510 , message.repeated_sfixed64(1)); - EXPECT_EQ(511 , message.repeated_float (1)); - EXPECT_EQ(512 , message.repeated_double (1)); - EXPECT_TRUE( message.repeated_bool (1)); - EXPECT_EQ("515", message.repeated_string (1)); - EXPECT_EQ("516", message.repeated_bytes (1)); - - EXPECT_EQ(517, message.repeatedgroup (1).a()); - EXPECT_EQ(518, message.repeated_nested_message (1).bb()); - EXPECT_EQ(519, message.repeated_foreign_message(1).c()); - EXPECT_EQ(520, message.repeated_import_message (1).d()); - EXPECT_EQ(527, message.repeated_lazy_message (1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_FOO , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.repeated_import_enum (1)); - -} - -// ------------------------------------------------------------------- - -void TestUtil::SetPackedFields(unittest::TestPackedTypes* message) { - message->add_packed_int32 (601); - message->add_packed_int64 (602); - message->add_packed_uint32 (603); - message->add_packed_uint64 (604); - message->add_packed_sint32 (605); - message->add_packed_sint64 (606); - message->add_packed_fixed32 (607); - message->add_packed_fixed64 (608); - message->add_packed_sfixed32(609); - message->add_packed_sfixed64(610); - message->add_packed_float (611); - message->add_packed_double (612); - message->add_packed_bool (true); - message->add_packed_enum (unittest::FOREIGN_BAR); - // add a second one of each field - message->add_packed_int32 (701); - message->add_packed_int64 (702); - message->add_packed_uint32 (703); - message->add_packed_uint64 (704); - message->add_packed_sint32 (705); - message->add_packed_sint64 (706); - message->add_packed_fixed32 (707); - message->add_packed_fixed64 (708); - message->add_packed_sfixed32(709); - message->add_packed_sfixed64(710); - message->add_packed_float (711); - message->add_packed_double (712); - message->add_packed_bool (false); - message->add_packed_enum (unittest::FOREIGN_BAZ); -} - -void TestUtil::SetUnpackedFields(unittest::TestUnpackedTypes* message) { - // The values applied here must match those of SetPackedFields. - - message->add_unpacked_int32 (601); - message->add_unpacked_int64 (602); - message->add_unpacked_uint32 (603); - message->add_unpacked_uint64 (604); - message->add_unpacked_sint32 (605); - message->add_unpacked_sint64 (606); - message->add_unpacked_fixed32 (607); - message->add_unpacked_fixed64 (608); - message->add_unpacked_sfixed32(609); - message->add_unpacked_sfixed64(610); - message->add_unpacked_float (611); - message->add_unpacked_double (612); - message->add_unpacked_bool (true); - message->add_unpacked_enum (unittest::FOREIGN_BAR); - // add a second one of each field - message->add_unpacked_int32 (701); - message->add_unpacked_int64 (702); - message->add_unpacked_uint32 (703); - message->add_unpacked_uint64 (704); - message->add_unpacked_sint32 (705); - message->add_unpacked_sint64 (706); - message->add_unpacked_fixed32 (707); - message->add_unpacked_fixed64 (708); - message->add_unpacked_sfixed32(709); - message->add_unpacked_sfixed64(710); - message->add_unpacked_float (711); - message->add_unpacked_double (712); - message->add_unpacked_bool (false); - message->add_unpacked_enum (unittest::FOREIGN_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyPackedFields(unittest::TestPackedTypes* message) { - message->set_packed_int32 (1, 801); - message->set_packed_int64 (1, 802); - message->set_packed_uint32 (1, 803); - message->set_packed_uint64 (1, 804); - message->set_packed_sint32 (1, 805); - message->set_packed_sint64 (1, 806); - message->set_packed_fixed32 (1, 807); - message->set_packed_fixed64 (1, 808); - message->set_packed_sfixed32(1, 809); - message->set_packed_sfixed64(1, 810); - message->set_packed_float (1, 811); - message->set_packed_double (1, 812); - message->set_packed_bool (1, true); - message->set_packed_enum (1, unittest::FOREIGN_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedFieldsSet(const unittest::TestPackedTypes& message) { - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_TRUE( message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0)); - - EXPECT_EQ(701 , message.packed_int32 (1)); - EXPECT_EQ(702 , message.packed_int64 (1)); - EXPECT_EQ(703 , message.packed_uint32 (1)); - EXPECT_EQ(704 , message.packed_uint64 (1)); - EXPECT_EQ(705 , message.packed_sint32 (1)); - EXPECT_EQ(706 , message.packed_sint64 (1)); - EXPECT_EQ(707 , message.packed_fixed32 (1)); - EXPECT_EQ(708 , message.packed_fixed64 (1)); - EXPECT_EQ(709 , message.packed_sfixed32(1)); - EXPECT_EQ(710 , message.packed_sfixed64(1)); - EXPECT_EQ(711 , message.packed_float (1)); - EXPECT_EQ(712 , message.packed_double (1)); - EXPECT_FALSE( message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, message.packed_enum(1)); -} - -void TestUtil::ExpectUnpackedFieldsSet( - const unittest::TestUnpackedTypes& message) { - // The values expected here must match those of ExpectPackedFieldsSet. - - ASSERT_EQ(2, message.unpacked_int32_size ()); - ASSERT_EQ(2, message.unpacked_int64_size ()); - ASSERT_EQ(2, message.unpacked_uint32_size ()); - ASSERT_EQ(2, message.unpacked_uint64_size ()); - ASSERT_EQ(2, message.unpacked_sint32_size ()); - ASSERT_EQ(2, message.unpacked_sint64_size ()); - ASSERT_EQ(2, message.unpacked_fixed32_size ()); - ASSERT_EQ(2, message.unpacked_fixed64_size ()); - ASSERT_EQ(2, message.unpacked_sfixed32_size()); - ASSERT_EQ(2, message.unpacked_sfixed64_size()); - ASSERT_EQ(2, message.unpacked_float_size ()); - ASSERT_EQ(2, message.unpacked_double_size ()); - ASSERT_EQ(2, message.unpacked_bool_size ()); - ASSERT_EQ(2, message.unpacked_enum_size ()); - - EXPECT_EQ(601 , message.unpacked_int32 (0)); - EXPECT_EQ(602 , message.unpacked_int64 (0)); - EXPECT_EQ(603 , message.unpacked_uint32 (0)); - EXPECT_EQ(604 , message.unpacked_uint64 (0)); - EXPECT_EQ(605 , message.unpacked_sint32 (0)); - EXPECT_EQ(606 , message.unpacked_sint64 (0)); - EXPECT_EQ(607 , message.unpacked_fixed32 (0)); - EXPECT_EQ(608 , message.unpacked_fixed64 (0)); - EXPECT_EQ(609 , message.unpacked_sfixed32(0)); - EXPECT_EQ(610 , message.unpacked_sfixed64(0)); - EXPECT_EQ(611 , message.unpacked_float (0)); - EXPECT_EQ(612 , message.unpacked_double (0)); - EXPECT_TRUE( message.unpacked_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.unpacked_enum(0)); - - EXPECT_EQ(701 , message.unpacked_int32 (1)); - EXPECT_EQ(702 , message.unpacked_int64 (1)); - EXPECT_EQ(703 , message.unpacked_uint32 (1)); - EXPECT_EQ(704 , message.unpacked_uint64 (1)); - EXPECT_EQ(705 , message.unpacked_sint32 (1)); - EXPECT_EQ(706 , message.unpacked_sint64 (1)); - EXPECT_EQ(707 , message.unpacked_fixed32 (1)); - EXPECT_EQ(708 , message.unpacked_fixed64 (1)); - EXPECT_EQ(709 , message.unpacked_sfixed32(1)); - EXPECT_EQ(710 , message.unpacked_sfixed64(1)); - EXPECT_EQ(711 , message.unpacked_float (1)); - EXPECT_EQ(712 , message.unpacked_double (1)); - EXPECT_FALSE( message.unpacked_bool (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, message.unpacked_enum(1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedClear( - const unittest::TestPackedTypes& message) { - // Packed repeated fields are empty. - EXPECT_EQ(0, message.packed_int32_size ()); - EXPECT_EQ(0, message.packed_int64_size ()); - EXPECT_EQ(0, message.packed_uint32_size ()); - EXPECT_EQ(0, message.packed_uint64_size ()); - EXPECT_EQ(0, message.packed_sint32_size ()); - EXPECT_EQ(0, message.packed_sint64_size ()); - EXPECT_EQ(0, message.packed_fixed32_size ()); - EXPECT_EQ(0, message.packed_fixed64_size ()); - EXPECT_EQ(0, message.packed_sfixed32_size()); - EXPECT_EQ(0, message.packed_sfixed64_size()); - EXPECT_EQ(0, message.packed_float_size ()); - EXPECT_EQ(0, message.packed_double_size ()); - EXPECT_EQ(0, message.packed_bool_size ()); - EXPECT_EQ(0, message.packed_enum_size ()); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedFieldsModified( - const unittest::TestPackedTypes& message) { - // Do the same for packed repeated fields. - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_TRUE( message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0)); - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.packed_int32 (1)); - EXPECT_EQ(802 , message.packed_int64 (1)); - EXPECT_EQ(803 , message.packed_uint32 (1)); - EXPECT_EQ(804 , message.packed_uint64 (1)); - EXPECT_EQ(805 , message.packed_sint32 (1)); - EXPECT_EQ(806 , message.packed_sint64 (1)); - EXPECT_EQ(807 , message.packed_fixed32 (1)); - EXPECT_EQ(808 , message.packed_fixed64 (1)); - EXPECT_EQ(809 , message.packed_sfixed32(1)); - EXPECT_EQ(810 , message.packed_sfixed64(1)); - EXPECT_EQ(811 , message.packed_float (1)); - EXPECT_EQ(812 , message.packed_double (1)); - EXPECT_TRUE( message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_FOO, message.packed_enum(1)); -} - -// =================================================================== -// Extensions -// -// All this code is exactly equivalent to the above code except that it's -// manipulating extension fields instead of normal ones. -// -// I gave up on the 80-char limit here. Sorry. - -void TestUtil::SetAllExtensions(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::optional_int32_extension , 101); - message->SetExtension(unittest::optional_int64_extension , 102); - message->SetExtension(unittest::optional_uint32_extension , 103); - message->SetExtension(unittest::optional_uint64_extension , 104); - message->SetExtension(unittest::optional_sint32_extension , 105); - message->SetExtension(unittest::optional_sint64_extension , 106); - message->SetExtension(unittest::optional_fixed32_extension , 107); - message->SetExtension(unittest::optional_fixed64_extension , 108); - message->SetExtension(unittest::optional_sfixed32_extension, 109); - message->SetExtension(unittest::optional_sfixed64_extension, 110); - message->SetExtension(unittest::optional_float_extension , 111); - message->SetExtension(unittest::optional_double_extension , 112); - message->SetExtension(unittest::optional_bool_extension , true); - message->SetExtension(unittest::optional_string_extension , "115"); - message->SetExtension(unittest::optional_bytes_extension , "116"); - - message->MutableExtension(unittest::optionalgroup_extension )->set_a(117); - message->MutableExtension(unittest::optional_nested_message_extension )->set_bb(118); - message->MutableExtension(unittest::optional_foreign_message_extension)->set_c(119); - message->MutableExtension(unittest::optional_import_message_extension )->set_d(120); - - message->SetExtension(unittest::optional_nested_enum_extension , unittest::TestAllTypes::BAZ); - message->SetExtension(unittest::optional_foreign_enum_extension, unittest::FOREIGN_BAZ ); - message->SetExtension(unittest::optional_import_enum_extension , unittest_import::IMPORT_BAZ); - - message->SetExtension(unittest::optional_string_piece_extension, "124"); - message->SetExtension(unittest::optional_cord_extension, "125"); - - message->MutableExtension(unittest::optional_public_import_message_extension)->set_e(126); - message->MutableExtension(unittest::optional_lazy_message_extension)->set_bb(127); - - // ----------------------------------------------------------------- - - message->AddExtension(unittest::repeated_int32_extension , 201); - message->AddExtension(unittest::repeated_int64_extension , 202); - message->AddExtension(unittest::repeated_uint32_extension , 203); - message->AddExtension(unittest::repeated_uint64_extension , 204); - message->AddExtension(unittest::repeated_sint32_extension , 205); - message->AddExtension(unittest::repeated_sint64_extension , 206); - message->AddExtension(unittest::repeated_fixed32_extension , 207); - message->AddExtension(unittest::repeated_fixed64_extension , 208); - message->AddExtension(unittest::repeated_sfixed32_extension, 209); - message->AddExtension(unittest::repeated_sfixed64_extension, 210); - message->AddExtension(unittest::repeated_float_extension , 211); - message->AddExtension(unittest::repeated_double_extension , 212); - message->AddExtension(unittest::repeated_bool_extension , true); - message->AddExtension(unittest::repeated_string_extension , "215"); - message->AddExtension(unittest::repeated_bytes_extension , "216"); - - message->AddExtension(unittest::repeatedgroup_extension )->set_a(217); - message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(218); - message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(219); - message->AddExtension(unittest::repeated_import_message_extension )->set_d(220); - message->AddExtension(unittest::repeated_lazy_message_extension )->set_bb(227); - - message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAR); - message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAR ); - message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAR); - - message->AddExtension(unittest::repeated_string_piece_extension, "224"); - message->AddExtension(unittest::repeated_cord_extension, "225"); - - // Add a second one of each field. - message->AddExtension(unittest::repeated_int32_extension , 301); - message->AddExtension(unittest::repeated_int64_extension , 302); - message->AddExtension(unittest::repeated_uint32_extension , 303); - message->AddExtension(unittest::repeated_uint64_extension , 304); - message->AddExtension(unittest::repeated_sint32_extension , 305); - message->AddExtension(unittest::repeated_sint64_extension , 306); - message->AddExtension(unittest::repeated_fixed32_extension , 307); - message->AddExtension(unittest::repeated_fixed64_extension , 308); - message->AddExtension(unittest::repeated_sfixed32_extension, 309); - message->AddExtension(unittest::repeated_sfixed64_extension, 310); - message->AddExtension(unittest::repeated_float_extension , 311); - message->AddExtension(unittest::repeated_double_extension , 312); - message->AddExtension(unittest::repeated_bool_extension , false); - message->AddExtension(unittest::repeated_string_extension , "315"); - message->AddExtension(unittest::repeated_bytes_extension , "316"); - - message->AddExtension(unittest::repeatedgroup_extension )->set_a(317); - message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(318); - message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(319); - message->AddExtension(unittest::repeated_import_message_extension )->set_d(320); - message->AddExtension(unittest::repeated_lazy_message_extension )->set_bb(327); - - message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAZ); - message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAZ ); - message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAZ); - - message->AddExtension(unittest::repeated_string_piece_extension, "324"); - message->AddExtension(unittest::repeated_cord_extension, "325"); - - // ----------------------------------------------------------------- - - message->SetExtension(unittest::default_int32_extension , 401); - message->SetExtension(unittest::default_int64_extension , 402); - message->SetExtension(unittest::default_uint32_extension , 403); - message->SetExtension(unittest::default_uint64_extension , 404); - message->SetExtension(unittest::default_sint32_extension , 405); - message->SetExtension(unittest::default_sint64_extension , 406); - message->SetExtension(unittest::default_fixed32_extension , 407); - message->SetExtension(unittest::default_fixed64_extension , 408); - message->SetExtension(unittest::default_sfixed32_extension, 409); - message->SetExtension(unittest::default_sfixed64_extension, 410); - message->SetExtension(unittest::default_float_extension , 411); - message->SetExtension(unittest::default_double_extension , 412); - message->SetExtension(unittest::default_bool_extension , false); - message->SetExtension(unittest::default_string_extension , "415"); - message->SetExtension(unittest::default_bytes_extension , "416"); - - message->SetExtension(unittest::default_nested_enum_extension , unittest::TestAllTypes::FOO); - message->SetExtension(unittest::default_foreign_enum_extension, unittest::FOREIGN_FOO ); - message->SetExtension(unittest::default_import_enum_extension , unittest_import::IMPORT_FOO); - - message->SetExtension(unittest::default_string_piece_extension, "424"); - message->SetExtension(unittest::default_cord_extension, "425"); - - SetOneofFields(message); -} - -void TestUtil::SetOneofFields(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::oneof_uint32_extension, 601); - message->MutableExtension(unittest::oneof_nested_message_extension)->set_bb(602); - message->SetExtension(unittest::oneof_string_extension, "603"); - message->SetExtension(unittest::oneof_bytes_extension, "604"); -} - -// ------------------------------------------------------------------- - -void TestUtil::SetAllFieldsAndExtensions( - unittest::TestFieldOrderings* message) { - GOOGLE_CHECK(message); - message->set_my_int(1); - message->set_my_string("foo"); - message->set_my_float(1.0); - message->SetExtension(unittest::my_extension_int, 23); - message->SetExtension(unittest::my_extension_string, "bar"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyRepeatedExtensions(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::repeated_int32_extension , 1, 501); - message->SetExtension(unittest::repeated_int64_extension , 1, 502); - message->SetExtension(unittest::repeated_uint32_extension , 1, 503); - message->SetExtension(unittest::repeated_uint64_extension , 1, 504); - message->SetExtension(unittest::repeated_sint32_extension , 1, 505); - message->SetExtension(unittest::repeated_sint64_extension , 1, 506); - message->SetExtension(unittest::repeated_fixed32_extension , 1, 507); - message->SetExtension(unittest::repeated_fixed64_extension , 1, 508); - message->SetExtension(unittest::repeated_sfixed32_extension, 1, 509); - message->SetExtension(unittest::repeated_sfixed64_extension, 1, 510); - message->SetExtension(unittest::repeated_float_extension , 1, 511); - message->SetExtension(unittest::repeated_double_extension , 1, 512); - message->SetExtension(unittest::repeated_bool_extension , 1, true); - message->SetExtension(unittest::repeated_string_extension , 1, "515"); - message->SetExtension(unittest::repeated_bytes_extension , 1, "516"); - - message->MutableExtension(unittest::repeatedgroup_extension , 1)->set_a(517); - message->MutableExtension(unittest::repeated_nested_message_extension , 1)->set_bb(518); - message->MutableExtension(unittest::repeated_foreign_message_extension, 1)->set_c(519); - message->MutableExtension(unittest::repeated_import_message_extension , 1)->set_d(520); - message->MutableExtension(unittest::repeated_lazy_message_extension , 1)->set_bb(527); - - message->SetExtension(unittest::repeated_nested_enum_extension , 1, unittest::TestAllTypes::FOO); - message->SetExtension(unittest::repeated_foreign_enum_extension, 1, unittest::FOREIGN_FOO ); - message->SetExtension(unittest::repeated_import_enum_extension , 1, unittest_import::IMPORT_FOO); - - message->SetExtension(unittest::repeated_string_piece_extension, 1, "524"); - message->SetExtension(unittest::repeated_cord_extension, 1, "525"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllExtensionsSet( - const unittest::TestAllExtensions& message) { - EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_int64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed32_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed64_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_float_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_double_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bool_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bytes_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::optionalgroup_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_message_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_message_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_message_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_public_import_message_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_lazy_message_extension )); - - EXPECT_TRUE(message.GetExtension(unittest::optionalgroup_extension ).has_a()); - EXPECT_TRUE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb()); - EXPECT_TRUE(message.GetExtension(unittest::optional_foreign_message_extension ).has_c()); - EXPECT_TRUE(message.GetExtension(unittest::optional_import_message_extension ).has_d()); - EXPECT_TRUE(message.GetExtension(unittest::optional_public_import_message_extension).has_e()); - EXPECT_TRUE(message.GetExtension(unittest::optional_lazy_message_extension ).has_bb()); - - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_enum_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_enum_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_enum_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::optional_string_piece_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_cord_extension)); - - EXPECT_EQ(101 , message.GetExtension(unittest::optional_int32_extension )); - EXPECT_EQ(102 , message.GetExtension(unittest::optional_int64_extension )); - EXPECT_EQ(103 , message.GetExtension(unittest::optional_uint32_extension )); - EXPECT_EQ(104 , message.GetExtension(unittest::optional_uint64_extension )); - EXPECT_EQ(105 , message.GetExtension(unittest::optional_sint32_extension )); - EXPECT_EQ(106 , message.GetExtension(unittest::optional_sint64_extension )); - EXPECT_EQ(107 , message.GetExtension(unittest::optional_fixed32_extension )); - EXPECT_EQ(108 , message.GetExtension(unittest::optional_fixed64_extension )); - EXPECT_EQ(109 , message.GetExtension(unittest::optional_sfixed32_extension)); - EXPECT_EQ(110 , message.GetExtension(unittest::optional_sfixed64_extension)); - EXPECT_EQ(111 , message.GetExtension(unittest::optional_float_extension )); - EXPECT_EQ(112 , message.GetExtension(unittest::optional_double_extension )); - EXPECT_TRUE( message.GetExtension(unittest::optional_bool_extension )); - EXPECT_EQ("115", message.GetExtension(unittest::optional_string_extension )); - EXPECT_EQ("116", message.GetExtension(unittest::optional_bytes_extension )); - - EXPECT_EQ(117, message.GetExtension(unittest::optionalgroup_extension ).a()); - EXPECT_EQ(118, message.GetExtension(unittest::optional_nested_message_extension ).bb()); - EXPECT_EQ(119, message.GetExtension(unittest::optional_foreign_message_extension).c()); - EXPECT_EQ(120, message.GetExtension(unittest::optional_import_message_extension ).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::optional_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::optional_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::optional_import_enum_extension )); - - EXPECT_EQ("124", message.GetExtension(unittest::optional_string_piece_extension)); - EXPECT_EQ("125", message.GetExtension(unittest::optional_cord_extension)); - EXPECT_EQ(126, message.GetExtension(unittest::optional_public_import_message_extension ).e()); - EXPECT_EQ(127, message.GetExtension(unittest::optional_lazy_message_extension).bb()); - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); - - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_FALSE( message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - EXPECT_EQ(327, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 1)); - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.HasExtension(unittest::default_int32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_int64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed32_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed64_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_float_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_double_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_bool_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_string_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_bytes_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::default_nested_enum_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_foreign_enum_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_import_enum_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::default_string_piece_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_cord_extension)); - - EXPECT_EQ(401 , message.GetExtension(unittest::default_int32_extension )); - EXPECT_EQ(402 , message.GetExtension(unittest::default_int64_extension )); - EXPECT_EQ(403 , message.GetExtension(unittest::default_uint32_extension )); - EXPECT_EQ(404 , message.GetExtension(unittest::default_uint64_extension )); - EXPECT_EQ(405 , message.GetExtension(unittest::default_sint32_extension )); - EXPECT_EQ(406 , message.GetExtension(unittest::default_sint64_extension )); - EXPECT_EQ(407 , message.GetExtension(unittest::default_fixed32_extension )); - EXPECT_EQ(408 , message.GetExtension(unittest::default_fixed64_extension )); - EXPECT_EQ(409 , message.GetExtension(unittest::default_sfixed32_extension)); - EXPECT_EQ(410 , message.GetExtension(unittest::default_sfixed64_extension)); - EXPECT_EQ(411 , message.GetExtension(unittest::default_float_extension )); - EXPECT_EQ(412 , message.GetExtension(unittest::default_double_extension )); - EXPECT_FALSE( message.GetExtension(unittest::default_bool_extension )); - EXPECT_EQ("415", message.GetExtension(unittest::default_string_extension )); - EXPECT_EQ("416", message.GetExtension(unittest::default_bytes_extension )); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::default_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::default_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::default_import_enum_extension )); - - EXPECT_EQ("424", message.GetExtension(unittest::default_string_piece_extension)); - EXPECT_EQ("425", message.GetExtension(unittest::default_cord_extension)); - - EXPECT_TRUE(message.HasExtension(unittest::oneof_uint32_extension)); - EXPECT_TRUE(message.GetExtension(unittest::oneof_nested_message_extension).has_bb()); - EXPECT_TRUE(message.HasExtension(unittest::oneof_string_extension)); - EXPECT_TRUE(message.HasExtension(unittest::oneof_bytes_extension)); - - EXPECT_EQ(601, message.GetExtension(unittest::oneof_uint32_extension)); - EXPECT_EQ(602, message.GetExtension(unittest::oneof_nested_message_extension).bb()); - EXPECT_EQ("603", message.GetExtension(unittest::oneof_string_extension)); - EXPECT_EQ("604", message.GetExtension(unittest::oneof_bytes_extension)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectExtensionsClear( - const unittest::TestAllExtensions& message) { - string serialized; - ASSERT_TRUE(message.SerializeToString(&serialized)); - EXPECT_EQ("", serialized); - EXPECT_EQ(0, message.ByteSize()); - - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.HasExtension(unittest::optional_int32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed32_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed64_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_float_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_double_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bool_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_string_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bytes_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optionalgroup_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_message_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_message_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_message_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_public_import_message_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_lazy_message_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_enum_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_enum_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_enum_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optional_string_piece_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_cord_extension)); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed32_extension)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed64_extension)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_float_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_double_extension )); - EXPECT_FALSE( message.GetExtension(unittest::optional_bool_extension )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_string_extension )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_bytes_extension )); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.GetExtension(unittest::optionalgroup_extension ).has_a()); - EXPECT_FALSE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb()); - EXPECT_FALSE(message.GetExtension(unittest::optional_foreign_message_extension ).has_c()); - EXPECT_FALSE(message.GetExtension(unittest::optional_import_message_extension ).has_d()); - EXPECT_FALSE(message.GetExtension(unittest::optional_public_import_message_extension).has_e()); - EXPECT_FALSE(message.GetExtension(unittest::optional_lazy_message_extension ).has_bb()); - - EXPECT_EQ(0, message.GetExtension(unittest::optionalgroup_extension ).a()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension ).bb()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_foreign_message_extension ).c()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_import_message_extension ).d()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_public_import_message_extension).e()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_lazy_message_extension ).bb()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::optional_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::optional_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::optional_import_enum_extension )); - - EXPECT_EQ("", message.GetExtension(unittest::optional_string_piece_extension)); - EXPECT_EQ("", message.GetExtension(unittest::optional_cord_extension)); - - // Repeated fields are empty. - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_float_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_double_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bool_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bytes_extension )); - - EXPECT_EQ(0, message.ExtensionSize(unittest::repeatedgroup_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_piece_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_cord_extension)); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.HasExtension(unittest::default_int32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_int64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed32_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed64_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_float_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_double_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_bool_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_string_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_bytes_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::default_nested_enum_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_foreign_enum_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_import_enum_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::default_string_piece_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_cord_extension)); - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.GetExtension(unittest::default_int32_extension )); - EXPECT_EQ( 42 , message.GetExtension(unittest::default_int64_extension )); - EXPECT_EQ( 43 , message.GetExtension(unittest::default_uint32_extension )); - EXPECT_EQ( 44 , message.GetExtension(unittest::default_uint64_extension )); - EXPECT_EQ(-45 , message.GetExtension(unittest::default_sint32_extension )); - EXPECT_EQ( 46 , message.GetExtension(unittest::default_sint64_extension )); - EXPECT_EQ( 47 , message.GetExtension(unittest::default_fixed32_extension )); - EXPECT_EQ( 48 , message.GetExtension(unittest::default_fixed64_extension )); - EXPECT_EQ( 49 , message.GetExtension(unittest::default_sfixed32_extension)); - EXPECT_EQ(-50 , message.GetExtension(unittest::default_sfixed64_extension)); - EXPECT_EQ( 51.5 , message.GetExtension(unittest::default_float_extension )); - EXPECT_EQ( 52e3 , message.GetExtension(unittest::default_double_extension )); - EXPECT_TRUE( message.GetExtension(unittest::default_bool_extension )); - EXPECT_EQ("hello", message.GetExtension(unittest::default_string_extension )); - EXPECT_EQ("world", message.GetExtension(unittest::default_bytes_extension )); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::default_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::default_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::default_import_enum_extension )); - - EXPECT_EQ("abc", message.GetExtension(unittest::default_string_piece_extension)); - EXPECT_EQ("123", message.GetExtension(unittest::default_cord_extension)); - - EXPECT_FALSE(message.HasExtension(unittest::oneof_uint32_extension)); - EXPECT_FALSE(message.GetExtension(unittest::oneof_nested_message_extension).has_bb()); - EXPECT_FALSE(message.HasExtension(unittest::oneof_string_extension)); - EXPECT_FALSE(message.HasExtension(unittest::oneof_bytes_extension)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensions& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(502 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(503 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(504 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(505 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(506 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(507 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(508 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(509 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(510 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(511 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(512 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("515", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("516", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(517, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(518, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(519, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(520, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - EXPECT_EQ(527, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("524", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("525", message.GetExtension(unittest::repeated_cord_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::SetPackedExtensions(unittest::TestPackedExtensions* message) { - message->AddExtension(unittest::packed_int32_extension , 601); - message->AddExtension(unittest::packed_int64_extension , 602); - message->AddExtension(unittest::packed_uint32_extension , 603); - message->AddExtension(unittest::packed_uint64_extension , 604); - message->AddExtension(unittest::packed_sint32_extension , 605); - message->AddExtension(unittest::packed_sint64_extension , 606); - message->AddExtension(unittest::packed_fixed32_extension , 607); - message->AddExtension(unittest::packed_fixed64_extension , 608); - message->AddExtension(unittest::packed_sfixed32_extension, 609); - message->AddExtension(unittest::packed_sfixed64_extension, 610); - message->AddExtension(unittest::packed_float_extension , 611); - message->AddExtension(unittest::packed_double_extension , 612); - message->AddExtension(unittest::packed_bool_extension , true); - message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAR); - // add a second one of each field - message->AddExtension(unittest::packed_int32_extension , 701); - message->AddExtension(unittest::packed_int64_extension , 702); - message->AddExtension(unittest::packed_uint32_extension , 703); - message->AddExtension(unittest::packed_uint64_extension , 704); - message->AddExtension(unittest::packed_sint32_extension , 705); - message->AddExtension(unittest::packed_sint64_extension , 706); - message->AddExtension(unittest::packed_fixed32_extension , 707); - message->AddExtension(unittest::packed_fixed64_extension , 708); - message->AddExtension(unittest::packed_sfixed32_extension, 709); - message->AddExtension(unittest::packed_sfixed64_extension, 710); - message->AddExtension(unittest::packed_float_extension , 711); - message->AddExtension(unittest::packed_double_extension , 712); - message->AddExtension(unittest::packed_bool_extension , false); - message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyPackedExtensions(unittest::TestPackedExtensions* message) { - message->SetExtension(unittest::packed_int32_extension , 1, 801); - message->SetExtension(unittest::packed_int64_extension , 1, 802); - message->SetExtension(unittest::packed_uint32_extension , 1, 803); - message->SetExtension(unittest::packed_uint64_extension , 1, 804); - message->SetExtension(unittest::packed_sint32_extension , 1, 805); - message->SetExtension(unittest::packed_sint64_extension , 1, 806); - message->SetExtension(unittest::packed_fixed32_extension , 1, 807); - message->SetExtension(unittest::packed_fixed64_extension , 1, 808); - message->SetExtension(unittest::packed_sfixed32_extension, 1, 809); - message->SetExtension(unittest::packed_sfixed64_extension, 1, 810); - message->SetExtension(unittest::packed_float_extension , 1, 811); - message->SetExtension(unittest::packed_double_extension , 1, 812); - message->SetExtension(unittest::packed_bool_extension , 1, true); - message->SetExtension(unittest::packed_enum_extension , 1, - unittest::FOREIGN_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsSet( - const unittest::TestPackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension )); - - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::packed_enum_extension, 0)); - EXPECT_EQ(701 , message.GetExtension(unittest::packed_int32_extension , 1)); - EXPECT_EQ(702 , message.GetExtension(unittest::packed_int64_extension , 1)); - EXPECT_EQ(703 , message.GetExtension(unittest::packed_uint32_extension , 1)); - EXPECT_EQ(704 , message.GetExtension(unittest::packed_uint64_extension , 1)); - EXPECT_EQ(705 , message.GetExtension(unittest::packed_sint32_extension , 1)); - EXPECT_EQ(706 , message.GetExtension(unittest::packed_sint64_extension , 1)); - EXPECT_EQ(707 , message.GetExtension(unittest::packed_fixed32_extension , 1)); - EXPECT_EQ(708 , message.GetExtension(unittest::packed_fixed64_extension , 1)); - EXPECT_EQ(709 , message.GetExtension(unittest::packed_sfixed32_extension, 1)); - EXPECT_EQ(710 , message.GetExtension(unittest::packed_sfixed64_extension, 1)); - EXPECT_EQ(711 , message.GetExtension(unittest::packed_float_extension , 1)); - EXPECT_EQ(712 , message.GetExtension(unittest::packed_double_extension , 1)); - EXPECT_FALSE( message.GetExtension(unittest::packed_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, - message.GetExtension(unittest::packed_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsClear( - const unittest::TestPackedExtensions& message) { - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed32_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed64_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_float_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_double_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_bool_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_enum_extension )); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsModified( - const unittest::TestPackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension )); - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::packed_enum_extension, 0)); - - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.GetExtension(unittest::packed_int32_extension , 1)); - EXPECT_EQ(802 , message.GetExtension(unittest::packed_int64_extension , 1)); - EXPECT_EQ(803 , message.GetExtension(unittest::packed_uint32_extension , 1)); - EXPECT_EQ(804 , message.GetExtension(unittest::packed_uint64_extension , 1)); - EXPECT_EQ(805 , message.GetExtension(unittest::packed_sint32_extension , 1)); - EXPECT_EQ(806 , message.GetExtension(unittest::packed_sint64_extension , 1)); - EXPECT_EQ(807 , message.GetExtension(unittest::packed_fixed32_extension , 1)); - EXPECT_EQ(808 , message.GetExtension(unittest::packed_fixed64_extension , 1)); - EXPECT_EQ(809 , message.GetExtension(unittest::packed_sfixed32_extension, 1)); - EXPECT_EQ(810 , message.GetExtension(unittest::packed_sfixed64_extension, 1)); - EXPECT_EQ(811 , message.GetExtension(unittest::packed_float_extension , 1)); - EXPECT_EQ(812 , message.GetExtension(unittest::packed_double_extension , 1)); - EXPECT_TRUE( message.GetExtension(unittest::packed_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_FOO, - message.GetExtension(unittest::packed_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectUnpackedExtensionsSet( - const unittest::TestUnpackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::unpacked_enum_extension )); - - EXPECT_EQ(601 , message.GetExtension(unittest::unpacked_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::unpacked_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::unpacked_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::unpacked_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::unpacked_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::unpacked_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::unpacked_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::unpacked_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::unpacked_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::unpacked_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::unpacked_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::unpacked_double_extension , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::unpacked_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::unpacked_enum_extension, 0)); - EXPECT_EQ(701 , message.GetExtension(unittest::unpacked_int32_extension , 1)); - EXPECT_EQ(702 , message.GetExtension(unittest::unpacked_int64_extension , 1)); - EXPECT_EQ(703 , message.GetExtension(unittest::unpacked_uint32_extension , 1)); - EXPECT_EQ(704 , message.GetExtension(unittest::unpacked_uint64_extension , 1)); - EXPECT_EQ(705 , message.GetExtension(unittest::unpacked_sint32_extension , 1)); - EXPECT_EQ(706 , message.GetExtension(unittest::unpacked_sint64_extension , 1)); - EXPECT_EQ(707 , message.GetExtension(unittest::unpacked_fixed32_extension , 1)); - EXPECT_EQ(708 , message.GetExtension(unittest::unpacked_fixed64_extension , 1)); - EXPECT_EQ(709 , message.GetExtension(unittest::unpacked_sfixed32_extension, 1)); - EXPECT_EQ(710 , message.GetExtension(unittest::unpacked_sfixed64_extension, 1)); - EXPECT_EQ(711 , message.GetExtension(unittest::unpacked_float_extension , 1)); - EXPECT_EQ(712 , message.GetExtension(unittest::unpacked_double_extension , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::unpacked_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, - message.GetExtension(unittest::unpacked_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllFieldsAndExtensionsInOrder(const string& serialized) { - // We set each field individually, serialize separately, and concatenate all - // the strings in canonical order to determine the expected serialization. - string expected; - unittest::TestFieldOrderings message; - message.set_my_int(1); // Field 1. - message.AppendToString(&expected); - message.Clear(); - message.SetExtension(unittest::my_extension_int, 23); // Field 5. - message.AppendToString(&expected); - message.Clear(); - message.set_my_string("foo"); // Field 11. - message.AppendToString(&expected); - message.Clear(); - message.SetExtension(unittest::my_extension_string, "bar"); // Field 50. - message.AppendToString(&expected); - message.Clear(); - message.set_my_float(1.0); // Field 101. - message.AppendToString(&expected); - message.Clear(); - - // We don't EXPECT_EQ() since we don't want to print raw bytes to stdout. - EXPECT_TRUE(serialized == expected); -} - -void TestUtil::ExpectLastRepeatedsRemoved( - const unittest::TestAllTypes& message) { - ASSERT_EQ(1, message.repeated_int32_size ()); - ASSERT_EQ(1, message.repeated_int64_size ()); - ASSERT_EQ(1, message.repeated_uint32_size ()); - ASSERT_EQ(1, message.repeated_uint64_size ()); - ASSERT_EQ(1, message.repeated_sint32_size ()); - ASSERT_EQ(1, message.repeated_sint64_size ()); - ASSERT_EQ(1, message.repeated_fixed32_size ()); - ASSERT_EQ(1, message.repeated_fixed64_size ()); - ASSERT_EQ(1, message.repeated_sfixed32_size()); - ASSERT_EQ(1, message.repeated_sfixed64_size()); - ASSERT_EQ(1, message.repeated_float_size ()); - ASSERT_EQ(1, message.repeated_double_size ()); - ASSERT_EQ(1, message.repeated_bool_size ()); - ASSERT_EQ(1, message.repeated_string_size ()); - ASSERT_EQ(1, message.repeated_bytes_size ()); - - ASSERT_EQ(1, message.repeatedgroup_size ()); - ASSERT_EQ(1, message.repeated_nested_message_size ()); - ASSERT_EQ(1, message.repeated_foreign_message_size()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - ASSERT_EQ(1, message.repeated_nested_enum_size ()); - ASSERT_EQ(1, message.repeated_foreign_enum_size ()); - ASSERT_EQ(1, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(1, message.repeated_string_piece_size()); - ASSERT_EQ(1, message.repeated_cord_size()); -#endif - - // Test that the remaining element is the correct one. - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_TRUE( message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); -} - -void TestUtil::ExpectLastRepeatedExtensionsRemoved( - const unittest::TestAllExtensions& message) { - - // Test that one element was removed. - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(1, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_cord_extension)); - - // Test that the remaining element is the correct one. - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); -} - -void TestUtil::ExpectLastRepeatedsReleased( - const unittest::TestAllTypes& message) { - ASSERT_EQ(1, message.repeatedgroup_size ()); - ASSERT_EQ(1, message.repeated_nested_message_size ()); - ASSERT_EQ(1, message.repeated_foreign_message_size()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); -} - -void TestUtil::ExpectLastRepeatedExtensionsReleased( - const unittest::TestAllExtensions& message) { - ASSERT_EQ(1, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); -} - -void TestUtil::ExpectRepeatedsSwapped( - const unittest::TestAllTypes& message) { - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - // Test that the first element and second element are flipped. - EXPECT_EQ(201 , message.repeated_int32 (1)); - EXPECT_EQ(202 , message.repeated_int64 (1)); - EXPECT_EQ(203 , message.repeated_uint32 (1)); - EXPECT_EQ(204 , message.repeated_uint64 (1)); - EXPECT_EQ(205 , message.repeated_sint32 (1)); - EXPECT_EQ(206 , message.repeated_sint64 (1)); - EXPECT_EQ(207 , message.repeated_fixed32 (1)); - EXPECT_EQ(208 , message.repeated_fixed64 (1)); - EXPECT_EQ(209 , message.repeated_sfixed32(1)); - EXPECT_EQ(210 , message.repeated_sfixed64(1)); - EXPECT_EQ(211 , message.repeated_float (1)); - EXPECT_EQ(212 , message.repeated_double (1)); - EXPECT_TRUE( message.repeated_bool (1)); - EXPECT_EQ("215", message.repeated_string (1)); - EXPECT_EQ("216", message.repeated_bytes (1)); - - EXPECT_EQ(217, message.repeatedgroup (1).a()); - EXPECT_EQ(218, message.repeated_nested_message (1).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(1).c()); - EXPECT_EQ(220, message.repeated_import_message (1).d()); - EXPECT_EQ(220, message.repeated_import_message (1).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (1)); - - EXPECT_EQ(301 , message.repeated_int32 (0)); - EXPECT_EQ(302 , message.repeated_int64 (0)); - EXPECT_EQ(303 , message.repeated_uint32 (0)); - EXPECT_EQ(304 , message.repeated_uint64 (0)); - EXPECT_EQ(305 , message.repeated_sint32 (0)); - EXPECT_EQ(306 , message.repeated_sint64 (0)); - EXPECT_EQ(307 , message.repeated_fixed32 (0)); - EXPECT_EQ(308 , message.repeated_fixed64 (0)); - EXPECT_EQ(309 , message.repeated_sfixed32(0)); - EXPECT_EQ(310 , message.repeated_sfixed64(0)); - EXPECT_EQ(311 , message.repeated_float (0)); - EXPECT_EQ(312 , message.repeated_double (0)); - EXPECT_FALSE( message.repeated_bool (0)); - EXPECT_EQ("315", message.repeated_string (0)); - EXPECT_EQ("316", message.repeated_bytes (0)); - - EXPECT_EQ(317, message.repeatedgroup (0).a()); - EXPECT_EQ(318, message.repeated_nested_message (0).bb()); - EXPECT_EQ(319, message.repeated_foreign_message(0).c()); - EXPECT_EQ(320, message.repeated_import_message (0).d()); - EXPECT_EQ(320, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (0)); -} - -void TestUtil::ExpectRepeatedExtensionsSwapped( - const unittest::TestAllExtensions& message) { - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_lazy_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_TRUE( message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - EXPECT_EQ(227, message.GetExtension(unittest::repeated_lazy_message_extension , 1).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 1)); - - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_FALSE( message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - EXPECT_EQ(327, message.GetExtension(unittest::repeated_lazy_message_extension , 0).bb()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 0)); -} - -void TestUtil::SetOneof1(unittest::TestOneof2* message) { - message->mutable_foo_lazy_message()->set_qux_int(100); - message->set_bar_string("101"); - message->set_baz_int(102); - message->set_baz_string("103"); -} - -void TestUtil::SetOneof2(unittest::TestOneof2* message) { - message->set_foo_int(200); - message->set_bar_enum(unittest::TestOneof2::BAZ); - message->set_baz_int(202); - message->set_baz_string("203"); -} - -void TestUtil::ExpectOneofSet1(const unittest::TestOneof2& message) { - ExpectAtMostOneFieldSetInOneof(message); - - EXPECT_TRUE(message.has_foo_lazy_message ()); - EXPECT_TRUE(message.foo_lazy_message().has_qux_int()); - - EXPECT_TRUE(message.has_bar_string()); - EXPECT_TRUE(message.has_baz_int ()); - EXPECT_TRUE(message.has_baz_string()); - - ASSERT_EQ(0, message.foo_lazy_message().corge_int_size()); - - EXPECT_EQ(100 , message.foo_lazy_message().qux_int()); - EXPECT_EQ("101", message.bar_string ()); - EXPECT_EQ(102 , message.baz_int ()); - EXPECT_EQ("103", message.baz_string ()); -} - -void TestUtil::ExpectOneofSet2(const unittest::TestOneof2& message) { - ExpectAtMostOneFieldSetInOneof(message); - - EXPECT_TRUE(message.has_foo_int ()); - EXPECT_TRUE(message.has_bar_enum ()); - EXPECT_TRUE(message.has_baz_int ()); - EXPECT_TRUE(message.has_baz_string()); - - EXPECT_EQ(200 , message.foo_int ()); - EXPECT_EQ(unittest::TestOneof2::BAZ, message.bar_enum ()); - EXPECT_EQ(202 , message.baz_int ()); - EXPECT_EQ("203" , message.baz_string()); -} - -void TestUtil::ExpectOneofClear(const unittest::TestOneof2& message) { - EXPECT_FALSE(message.has_foo_int()); - EXPECT_FALSE(message.has_foo_string()); - EXPECT_FALSE(message.has_foo_bytes()); - EXPECT_FALSE(message.has_foo_enum()); - EXPECT_FALSE(message.has_foo_message()); - EXPECT_FALSE(message.has_foogroup()); - EXPECT_FALSE(message.has_foo_lazy_message()); - - EXPECT_FALSE(message.has_bar_int()); - EXPECT_FALSE(message.has_bar_string()); - EXPECT_FALSE(message.has_bar_bytes()); - EXPECT_FALSE(message.has_bar_enum()); - - EXPECT_FALSE(message.has_baz_int()); - EXPECT_FALSE(message.has_baz_string()); - - EXPECT_EQ(unittest::TestOneof2::FOO_NOT_SET, message.foo_case()); - EXPECT_EQ(unittest::TestOneof2::BAR_NOT_SET, message.bar_case()); -} - -void TestUtil::ExpectAtMostOneFieldSetInOneof( - const unittest::TestOneof2& message) { - int count = 0; - if (message.has_foo_int()) count++; - if (message.has_foo_string()) count++; - if (message.has_foo_bytes()) count++; - if (message.has_foo_enum()) count++; - if (message.has_foo_message()) count++; - if (message.has_foogroup()) count++; - if (message.has_foo_lazy_message()) count++; - EXPECT_LE(count, 1); - count = 0; - if (message.has_bar_int()) count++; - if (message.has_bar_string()) count++; - if (message.has_bar_bytes()) count++; - if (message.has_bar_enum()) count++; - EXPECT_TRUE(count == 0 || count == 1); -} - -// =================================================================== - -TestUtil::ReflectionTester::ReflectionTester( - const Descriptor* base_descriptor) - : base_descriptor_(base_descriptor) { - - const DescriptorPool* pool = base_descriptor->file()->pool(); - - nested_b_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.NestedMessage.bb"); - foreign_c_ = - pool->FindFieldByName("protobuf_unittest.ForeignMessage.c"); - import_d_ = - pool->FindFieldByName("protobuf_unittest_import.ImportMessage.d"); - import_e_ = - pool->FindFieldByName("protobuf_unittest_import.PublicImportMessage.e"); - nested_foo_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.FOO"); - nested_bar_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAR"); - nested_baz_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAZ"); - foreign_foo_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_FOO"); - foreign_bar_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAR"); - foreign_baz_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAZ"); - import_foo_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_FOO"); - import_bar_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAR"); - import_baz_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAZ"); - - if (base_descriptor_->name() == "TestAllExtensions") { - group_a_ = - pool->FindFieldByName("protobuf_unittest.OptionalGroup_extension.a"); - repeated_group_a_ = - pool->FindFieldByName("protobuf_unittest.RepeatedGroup_extension.a"); - } else { - group_a_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.OptionalGroup.a"); - repeated_group_a_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.RepeatedGroup.a"); - } - - EXPECT_TRUE(group_a_ != NULL); - EXPECT_TRUE(repeated_group_a_ != NULL); - EXPECT_TRUE(nested_b_ != NULL); - EXPECT_TRUE(foreign_c_ != NULL); - EXPECT_TRUE(import_d_ != NULL); - EXPECT_TRUE(import_e_ != NULL); - EXPECT_TRUE(nested_foo_ != NULL); - EXPECT_TRUE(nested_bar_ != NULL); - EXPECT_TRUE(nested_baz_ != NULL); - EXPECT_TRUE(foreign_foo_ != NULL); - EXPECT_TRUE(foreign_bar_ != NULL); - EXPECT_TRUE(foreign_baz_ != NULL); - EXPECT_TRUE(import_foo_ != NULL); - EXPECT_TRUE(import_bar_ != NULL); - EXPECT_TRUE(import_baz_ != NULL); -} - -// Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. -const FieldDescriptor* TestUtil::ReflectionTester::F(const string& name) { - const FieldDescriptor* result = NULL; - if (base_descriptor_->name() == "TestAllExtensions" || - base_descriptor_->name() == "TestPackedExtensions") { - result = base_descriptor_->file()->FindExtensionByName(name + "_extension"); - } else { - result = base_descriptor_->FindFieldByName(name); - } - GOOGLE_CHECK(result != NULL); - return result; -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::SetAllFieldsViaReflection(Message* message) { - const Reflection* reflection = message->GetReflection(); - Message* sub_message; - - reflection->SetInt32 (message, F("optional_int32" ), 101); - reflection->SetInt64 (message, F("optional_int64" ), 102); - reflection->SetUInt32(message, F("optional_uint32" ), 103); - reflection->SetUInt64(message, F("optional_uint64" ), 104); - reflection->SetInt32 (message, F("optional_sint32" ), 105); - reflection->SetInt64 (message, F("optional_sint64" ), 106); - reflection->SetUInt32(message, F("optional_fixed32" ), 107); - reflection->SetUInt64(message, F("optional_fixed64" ), 108); - reflection->SetInt32 (message, F("optional_sfixed32"), 109); - reflection->SetInt64 (message, F("optional_sfixed64"), 110); - reflection->SetFloat (message, F("optional_float" ), 111); - reflection->SetDouble(message, F("optional_double" ), 112); - reflection->SetBool (message, F("optional_bool" ), true); - reflection->SetString(message, F("optional_string" ), "115"); - reflection->SetString(message, F("optional_bytes" ), "116"); - - sub_message = reflection->MutableMessage(message, F("optionalgroup")); - sub_message->GetReflection()->SetInt32(sub_message, group_a_, 117); - sub_message = reflection->MutableMessage(message, F("optional_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 118); - sub_message = reflection->MutableMessage(message, F("optional_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 119); - sub_message = reflection->MutableMessage(message, F("optional_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 120); - - reflection->SetEnum(message, F("optional_nested_enum" ), nested_baz_); - reflection->SetEnum(message, F("optional_foreign_enum"), foreign_baz_); - reflection->SetEnum(message, F("optional_import_enum" ), import_baz_); - - reflection->SetString(message, F("optional_string_piece"), "124"); - reflection->SetString(message, F("optional_cord"), "125"); - - sub_message = reflection->MutableMessage(message, F("optional_public_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_e_, 126); - - sub_message = reflection->MutableMessage(message, F("optional_lazy_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 127); - - // ----------------------------------------------------------------- - - reflection->AddInt32 (message, F("repeated_int32" ), 201); - reflection->AddInt64 (message, F("repeated_int64" ), 202); - reflection->AddUInt32(message, F("repeated_uint32" ), 203); - reflection->AddUInt64(message, F("repeated_uint64" ), 204); - reflection->AddInt32 (message, F("repeated_sint32" ), 205); - reflection->AddInt64 (message, F("repeated_sint64" ), 206); - reflection->AddUInt32(message, F("repeated_fixed32" ), 207); - reflection->AddUInt64(message, F("repeated_fixed64" ), 208); - reflection->AddInt32 (message, F("repeated_sfixed32"), 209); - reflection->AddInt64 (message, F("repeated_sfixed64"), 210); - reflection->AddFloat (message, F("repeated_float" ), 211); - reflection->AddDouble(message, F("repeated_double" ), 212); - reflection->AddBool (message, F("repeated_bool" ), true); - reflection->AddString(message, F("repeated_string" ), "215"); - reflection->AddString(message, F("repeated_bytes" ), "216"); - - sub_message = reflection->AddMessage(message, F("repeatedgroup")); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 217); - sub_message = reflection->AddMessage(message, F("repeated_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 218); - sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 219); - sub_message = reflection->AddMessage(message, F("repeated_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 220); - sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 227); - - reflection->AddEnum(message, F("repeated_nested_enum" ), nested_bar_); - reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_bar_); - reflection->AddEnum(message, F("repeated_import_enum" ), import_bar_); - - reflection->AddString(message, F("repeated_string_piece"), "224"); - reflection->AddString(message, F("repeated_cord"), "225"); - - // Add a second one of each field. - reflection->AddInt32 (message, F("repeated_int32" ), 301); - reflection->AddInt64 (message, F("repeated_int64" ), 302); - reflection->AddUInt32(message, F("repeated_uint32" ), 303); - reflection->AddUInt64(message, F("repeated_uint64" ), 304); - reflection->AddInt32 (message, F("repeated_sint32" ), 305); - reflection->AddInt64 (message, F("repeated_sint64" ), 306); - reflection->AddUInt32(message, F("repeated_fixed32" ), 307); - reflection->AddUInt64(message, F("repeated_fixed64" ), 308); - reflection->AddInt32 (message, F("repeated_sfixed32"), 309); - reflection->AddInt64 (message, F("repeated_sfixed64"), 310); - reflection->AddFloat (message, F("repeated_float" ), 311); - reflection->AddDouble(message, F("repeated_double" ), 312); - reflection->AddBool (message, F("repeated_bool" ), false); - reflection->AddString(message, F("repeated_string" ), "315"); - reflection->AddString(message, F("repeated_bytes" ), "316"); - - sub_message = reflection->AddMessage(message, F("repeatedgroup")); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 317); - sub_message = reflection->AddMessage(message, F("repeated_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 318); - sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 319); - sub_message = reflection->AddMessage(message, F("repeated_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 320); - sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 327); - - reflection->AddEnum(message, F("repeated_nested_enum" ), nested_baz_); - reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_baz_); - reflection->AddEnum(message, F("repeated_import_enum" ), import_baz_); - - reflection->AddString(message, F("repeated_string_piece"), "324"); - reflection->AddString(message, F("repeated_cord"), "325"); - - // ----------------------------------------------------------------- - - reflection->SetInt32 (message, F("default_int32" ), 401); - reflection->SetInt64 (message, F("default_int64" ), 402); - reflection->SetUInt32(message, F("default_uint32" ), 403); - reflection->SetUInt64(message, F("default_uint64" ), 404); - reflection->SetInt32 (message, F("default_sint32" ), 405); - reflection->SetInt64 (message, F("default_sint64" ), 406); - reflection->SetUInt32(message, F("default_fixed32" ), 407); - reflection->SetUInt64(message, F("default_fixed64" ), 408); - reflection->SetInt32 (message, F("default_sfixed32"), 409); - reflection->SetInt64 (message, F("default_sfixed64"), 410); - reflection->SetFloat (message, F("default_float" ), 411); - reflection->SetDouble(message, F("default_double" ), 412); - reflection->SetBool (message, F("default_bool" ), false); - reflection->SetString(message, F("default_string" ), "415"); - reflection->SetString(message, F("default_bytes" ), "416"); - - reflection->SetEnum(message, F("default_nested_enum" ), nested_foo_); - reflection->SetEnum(message, F("default_foreign_enum"), foreign_foo_); - reflection->SetEnum(message, F("default_import_enum" ), import_foo_); - - reflection->SetString(message, F("default_string_piece"), "424"); - reflection->SetString(message, F("default_cord"), "425"); - - reflection->SetUInt32(message, F("oneof_uint32" ), 601); - sub_message = reflection->MutableMessage(message, F("oneof_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 602); - reflection->SetString(message, F("oneof_string"), "603"); - reflection->SetString(message, F("oneof_bytes" ), "604"); -} - -void TestUtil::ReflectionTester::SetOneofViaReflection(Message* message) { - const Descriptor* descriptor = message->GetDescriptor(); - const Reflection* reflection = message->GetReflection(); - Message* sub_message = reflection->MutableMessage( - message, descriptor->FindFieldByName("foo_lazy_message")); - sub_message->GetReflection()->SetInt64( - sub_message, - descriptor->file()->pool()->FindFieldByName( - "protobuf_unittest.TestOneof2.NestedMessage.qux_int"), - 100); - - reflection->SetString(message, - descriptor->FindFieldByName("bar_cord"), - "101"); - reflection->SetInt32(message, - descriptor->FindFieldByName("baz_int"), - 102); - reflection->SetString(message, - descriptor->FindFieldByName("baz_string"), - "103"); -} - -void TestUtil::ReflectionTester::ExpectOneofSetViaReflection( - const Message& message) { - const Descriptor* descriptor = message.GetDescriptor(); - const Reflection* reflection = message.GetReflection(); - string scratch; - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("foo_lazy_message"))); - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("bar_cord"))); - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("baz_int"))); - EXPECT_TRUE(reflection->HasField( - message, descriptor->FindFieldByName("baz_string"))); - - const Message* sub_message = &reflection->GetMessage( - message, descriptor->FindFieldByName("foo_lazy_message")); - EXPECT_EQ(100, sub_message->GetReflection()->GetInt64( - *sub_message, - descriptor->file()->pool()->FindFieldByName( - "protobuf_unittest.TestOneof2.NestedMessage.qux_int"))); - - EXPECT_EQ("101", reflection->GetString( - message, descriptor->FindFieldByName("bar_cord"))); - EXPECT_EQ("101", reflection->GetStringReference( - message, descriptor->FindFieldByName("bar_cord"), &scratch)); - - EXPECT_EQ(102, reflection->GetInt32( - message, descriptor->FindFieldByName("baz_int"))); - - EXPECT_EQ("103", reflection->GetString( - message, descriptor->FindFieldByName("baz_string"))); - EXPECT_EQ("103", reflection->GetStringReference( - message, descriptor->FindFieldByName("baz_string"), &scratch)); -} - -void TestUtil::ReflectionTester::SetPackedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - reflection->AddInt32 (message, F("packed_int32" ), 601); - reflection->AddInt64 (message, F("packed_int64" ), 602); - reflection->AddUInt32(message, F("packed_uint32" ), 603); - reflection->AddUInt64(message, F("packed_uint64" ), 604); - reflection->AddInt32 (message, F("packed_sint32" ), 605); - reflection->AddInt64 (message, F("packed_sint64" ), 606); - reflection->AddUInt32(message, F("packed_fixed32" ), 607); - reflection->AddUInt64(message, F("packed_fixed64" ), 608); - reflection->AddInt32 (message, F("packed_sfixed32"), 609); - reflection->AddInt64 (message, F("packed_sfixed64"), 610); - reflection->AddFloat (message, F("packed_float" ), 611); - reflection->AddDouble(message, F("packed_double" ), 612); - reflection->AddBool (message, F("packed_bool" ), true); - reflection->AddEnum (message, F("packed_enum" ), foreign_bar_); - - reflection->AddInt32 (message, F("packed_int32" ), 701); - reflection->AddInt64 (message, F("packed_int64" ), 702); - reflection->AddUInt32(message, F("packed_uint32" ), 703); - reflection->AddUInt64(message, F("packed_uint64" ), 704); - reflection->AddInt32 (message, F("packed_sint32" ), 705); - reflection->AddInt64 (message, F("packed_sint64" ), 706); - reflection->AddUInt32(message, F("packed_fixed32" ), 707); - reflection->AddUInt64(message, F("packed_fixed64" ), 708); - reflection->AddInt32 (message, F("packed_sfixed32"), 709); - reflection->AddInt64 (message, F("packed_sfixed64"), 710); - reflection->AddFloat (message, F("packed_float" ), 711); - reflection->AddDouble(message, F("packed_double" ), 712); - reflection->AddBool (message, F("packed_bool" ), false); - reflection->AddEnum (message, F("packed_enum" ), foreign_baz_); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection( - const Message& message) { - // We have to split this into three function otherwise it creates a stack - // frame so large that it triggers a warning. - ExpectAllFieldsSetViaReflection1(message); - ExpectAllFieldsSetViaReflection2(message); - ExpectAllFieldsSetViaReflection3(message); -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - EXPECT_TRUE(reflection->HasField(message, F("optional_int32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_int64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_uint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_uint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_fixed32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_fixed64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed32"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed64"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_float" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_double" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_bool" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_string" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_bytes" ))); - - EXPECT_TRUE(reflection->HasField(message, F("optionalgroup" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_nested_message" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_message" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_import_message" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_public_import_message"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_lazy_message" ))); - - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); - sub_message = &reflection->GetMessage(message, F("optional_public_import_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); - sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - - EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_import_enum" ))); - - EXPECT_TRUE(reflection->HasField(message, F("optional_string_piece"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_cord"))); - - EXPECT_EQ(101 , reflection->GetInt32 (message, F("optional_int32" ))); - EXPECT_EQ(102 , reflection->GetInt64 (message, F("optional_int64" ))); - EXPECT_EQ(103 , reflection->GetUInt32(message, F("optional_uint32" ))); - EXPECT_EQ(104 , reflection->GetUInt64(message, F("optional_uint64" ))); - EXPECT_EQ(105 , reflection->GetInt32 (message, F("optional_sint32" ))); - EXPECT_EQ(106 , reflection->GetInt64 (message, F("optional_sint64" ))); - EXPECT_EQ(107 , reflection->GetUInt32(message, F("optional_fixed32" ))); - EXPECT_EQ(108 , reflection->GetUInt64(message, F("optional_fixed64" ))); - EXPECT_EQ(109 , reflection->GetInt32 (message, F("optional_sfixed32"))); - EXPECT_EQ(110 , reflection->GetInt64 (message, F("optional_sfixed64"))); - EXPECT_EQ(111 , reflection->GetFloat (message, F("optional_float" ))); - EXPECT_EQ(112 , reflection->GetDouble(message, F("optional_double" ))); - EXPECT_TRUE( reflection->GetBool (message, F("optional_bool" ))); - EXPECT_EQ("115", reflection->GetString(message, F("optional_string" ))); - EXPECT_EQ("116", reflection->GetString(message, F("optional_bytes" ))); - - EXPECT_EQ("115", reflection->GetStringReference(message, F("optional_string"), &scratch)); - EXPECT_EQ("116", reflection->GetStringReference(message, F("optional_bytes" ), &scratch)); - - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_EQ(117, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_EQ(118, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_EQ(119, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_EQ(120, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetMessage(message, F("optional_public_import_message")); - EXPECT_EQ(126, sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); - sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); - EXPECT_EQ(127, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - EXPECT_EQ( nested_baz_, reflection->GetEnum(message, F("optional_nested_enum" ))); - EXPECT_EQ(foreign_baz_, reflection->GetEnum(message, F("optional_foreign_enum"))); - EXPECT_EQ( import_baz_, reflection->GetEnum(message, F("optional_import_enum" ))); - - EXPECT_EQ("124", reflection->GetString(message, F("optional_string_piece"))); - EXPECT_EQ("124", reflection->GetStringReference(message, F("optional_string_piece"), &scratch)); - - EXPECT_EQ("125", reflection->GetString(message, F("optional_cord"))); - EXPECT_EQ("125", reflection->GetStringReference(message, F("optional_cord"), &scratch)); - - EXPECT_TRUE(reflection->HasField(message, F("oneof_bytes" ))); - EXPECT_EQ("604", reflection->GetString(message, F("oneof_bytes" ))); - - if (base_descriptor_->name() == "TestAllTypes") { - EXPECT_FALSE(reflection->HasField(message, F("oneof_uint32"))); - EXPECT_FALSE(reflection->HasField(message, F("oneof_string"))); - } else { - EXPECT_TRUE(reflection->HasField(message, F("oneof_uint32"))); - EXPECT_TRUE(reflection->HasField(message, F("oneof_string"))); - EXPECT_EQ(601 , reflection->GetUInt32(message, F("oneof_uint32"))); - EXPECT_EQ("603", reflection->GetString(message, F("oneof_string"))); - sub_message = &reflection->GetMessage(message, F("oneof_nested_message")); - EXPECT_EQ(602, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - } -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed32"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed64"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_float" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_double" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bool" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bytes" ))); - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeatedgroup" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_message"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_lazy_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_enum" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_enum" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_enum" ))); - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string_piece"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_cord"))); - - EXPECT_EQ(201 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 0)); - EXPECT_EQ(202 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 0)); - EXPECT_EQ(203 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 0)); - EXPECT_EQ(204 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 0)); - EXPECT_EQ(205 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 0)); - EXPECT_EQ(206 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 0)); - EXPECT_EQ(207 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 0)); - EXPECT_EQ(208 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 0)); - EXPECT_EQ(209 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 0)); - EXPECT_EQ(210 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 0)); - EXPECT_EQ(211 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 0)); - EXPECT_EQ(212 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 0)); - EXPECT_TRUE( reflection->GetRepeatedBool (message, F("repeated_bool" ), 0)); - EXPECT_EQ("215", reflection->GetRepeatedString(message, F("repeated_string" ), 0)); - EXPECT_EQ("216", reflection->GetRepeatedString(message, F("repeated_bytes" ), 0)); - - EXPECT_EQ("215", reflection->GetRepeatedStringReference(message, F("repeated_string"), 0, &scratch)); - EXPECT_EQ("216", reflection->GetRepeatedStringReference(message, F("repeated_bytes"), 0, &scratch)); - - sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 0); - EXPECT_EQ(217, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 0); - EXPECT_EQ(218, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 0); - EXPECT_EQ(219, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 0); - EXPECT_EQ(220, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 0); - EXPECT_EQ(227, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - EXPECT_EQ( nested_bar_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),0)); - EXPECT_EQ(foreign_bar_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),0)); - EXPECT_EQ( import_bar_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),0)); - - EXPECT_EQ("224", reflection->GetRepeatedString(message, F("repeated_string_piece"), 0)); - EXPECT_EQ("224", reflection->GetRepeatedStringReference( - message, F("repeated_string_piece"), 0, &scratch)); - - EXPECT_EQ("225", reflection->GetRepeatedString(message, F("repeated_cord"), 0)); - EXPECT_EQ("225", reflection->GetRepeatedStringReference( - message, F("repeated_cord"), 0, &scratch)); - - EXPECT_EQ(301 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 1)); - EXPECT_EQ(302 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 1)); - EXPECT_EQ(303 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 1)); - EXPECT_EQ(304 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 1)); - EXPECT_EQ(305 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 1)); - EXPECT_EQ(306 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 1)); - EXPECT_EQ(307 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 1)); - EXPECT_EQ(308 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 1)); - EXPECT_EQ(309 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 1)); - EXPECT_EQ(310 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 1)); - EXPECT_EQ(311 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 1)); - EXPECT_EQ(312 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 1)); - EXPECT_FALSE( reflection->GetRepeatedBool (message, F("repeated_bool" ), 1)); - EXPECT_EQ("315", reflection->GetRepeatedString(message, F("repeated_string" ), 1)); - EXPECT_EQ("316", reflection->GetRepeatedString(message, F("repeated_bytes" ), 1)); - - EXPECT_EQ("315", reflection->GetRepeatedStringReference(message, F("repeated_string"), - 1, &scratch)); - EXPECT_EQ("316", reflection->GetRepeatedStringReference(message, F("repeated_bytes"), - 1, &scratch)); - - sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 1); - EXPECT_EQ(317, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 1); - EXPECT_EQ(318, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 1); - EXPECT_EQ(319, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 1); - EXPECT_EQ(320, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 1); - EXPECT_EQ(327, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - EXPECT_EQ( nested_baz_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),1)); - EXPECT_EQ(foreign_baz_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),1)); - EXPECT_EQ( import_baz_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),1)); - - EXPECT_EQ("324", reflection->GetRepeatedString(message, F("repeated_string_piece"), 1)); - EXPECT_EQ("324", reflection->GetRepeatedStringReference( - message, F("repeated_string_piece"), 1, &scratch)); - - EXPECT_EQ("325", reflection->GetRepeatedString(message, F("repeated_cord"), 1)); - EXPECT_EQ("325", reflection->GetRepeatedStringReference( - message, F("repeated_cord"), 1, &scratch)); -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - - // ----------------------------------------------------------------- - - EXPECT_TRUE(reflection->HasField(message, F("default_int32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_int64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_uint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_uint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_fixed32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_fixed64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sfixed32"))); - EXPECT_TRUE(reflection->HasField(message, F("default_sfixed64"))); - EXPECT_TRUE(reflection->HasField(message, F("default_float" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_double" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_bool" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_string" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_bytes" ))); - - EXPECT_TRUE(reflection->HasField(message, F("default_nested_enum" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_foreign_enum"))); - EXPECT_TRUE(reflection->HasField(message, F("default_import_enum" ))); - - EXPECT_TRUE(reflection->HasField(message, F("default_string_piece"))); - EXPECT_TRUE(reflection->HasField(message, F("default_cord"))); - - EXPECT_EQ(401 , reflection->GetInt32 (message, F("default_int32" ))); - EXPECT_EQ(402 , reflection->GetInt64 (message, F("default_int64" ))); - EXPECT_EQ(403 , reflection->GetUInt32(message, F("default_uint32" ))); - EXPECT_EQ(404 , reflection->GetUInt64(message, F("default_uint64" ))); - EXPECT_EQ(405 , reflection->GetInt32 (message, F("default_sint32" ))); - EXPECT_EQ(406 , reflection->GetInt64 (message, F("default_sint64" ))); - EXPECT_EQ(407 , reflection->GetUInt32(message, F("default_fixed32" ))); - EXPECT_EQ(408 , reflection->GetUInt64(message, F("default_fixed64" ))); - EXPECT_EQ(409 , reflection->GetInt32 (message, F("default_sfixed32"))); - EXPECT_EQ(410 , reflection->GetInt64 (message, F("default_sfixed64"))); - EXPECT_EQ(411 , reflection->GetFloat (message, F("default_float" ))); - EXPECT_EQ(412 , reflection->GetDouble(message, F("default_double" ))); - EXPECT_FALSE( reflection->GetBool (message, F("default_bool" ))); - EXPECT_EQ("415", reflection->GetString(message, F("default_string" ))); - EXPECT_EQ("416", reflection->GetString(message, F("default_bytes" ))); - - EXPECT_EQ("415", reflection->GetStringReference(message, F("default_string"), &scratch)); - EXPECT_EQ("416", reflection->GetStringReference(message, F("default_bytes" ), &scratch)); - - EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("default_nested_enum" ))); - EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("default_foreign_enum"))); - EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("default_import_enum" ))); - - EXPECT_EQ("424", reflection->GetString(message, F("default_string_piece"))); - EXPECT_EQ("424", reflection->GetStringReference(message, F("default_string_piece"), - &scratch)); - - EXPECT_EQ("425", reflection->GetString(message, F("default_cord"))); - EXPECT_EQ("425", reflection->GetStringReference(message, F("default_cord"), &scratch)); -} - -void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed32"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed64"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_float" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_double" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_bool" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_enum" ))); - - EXPECT_EQ(601 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 0)); - EXPECT_EQ(602 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 0)); - EXPECT_EQ(603 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 0)); - EXPECT_EQ(604 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 0)); - EXPECT_EQ(605 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 0)); - EXPECT_EQ(606 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 0)); - EXPECT_EQ(607 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 0)); - EXPECT_EQ(608 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 0)); - EXPECT_EQ(609 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 0)); - EXPECT_EQ(610 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 0)); - EXPECT_EQ(611 , reflection->GetRepeatedFloat (message, F("packed_float" ), 0)); - EXPECT_EQ(612 , reflection->GetRepeatedDouble(message, F("packed_double" ), 0)); - EXPECT_TRUE( reflection->GetRepeatedBool (message, F("packed_bool" ), 0)); - EXPECT_EQ(foreign_bar_, - reflection->GetRepeatedEnum(message, F("packed_enum"), 0)); - - EXPECT_EQ(701 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 1)); - EXPECT_EQ(702 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 1)); - EXPECT_EQ(703 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 1)); - EXPECT_EQ(704 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 1)); - EXPECT_EQ(705 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 1)); - EXPECT_EQ(706 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 1)); - EXPECT_EQ(707 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 1)); - EXPECT_EQ(708 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 1)); - EXPECT_EQ(709 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 1)); - EXPECT_EQ(710 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 1)); - EXPECT_EQ(711 , reflection->GetRepeatedFloat (message, F("packed_float" ), 1)); - EXPECT_EQ(712 , reflection->GetRepeatedDouble(message, F("packed_double" ), 1)); - EXPECT_FALSE( reflection->GetRepeatedBool (message, F("packed_bool" ), 1)); - EXPECT_EQ(foreign_baz_, - reflection->GetRepeatedEnum(message, F("packed_enum"), 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ExpectClearViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(reflection->HasField(message, F("optional_int32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_int64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_uint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_uint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_fixed32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_fixed64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed32"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed64"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_float" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_double" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_bool" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_string" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_bytes" ))); - - EXPECT_FALSE(reflection->HasField(message, F("optionalgroup" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_nested_message" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_message"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_import_message" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_public_import_message"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_lazy_message"))); - - EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_import_enum" ))); - - EXPECT_FALSE(reflection->HasField(message, F("optional_string_piece"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_cord"))); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_int32" ))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_int64" ))); - EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_uint32" ))); - EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_uint64" ))); - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sint32" ))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sint64" ))); - EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_fixed32" ))); - EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_fixed64" ))); - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sfixed32"))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sfixed64"))); - EXPECT_EQ(0 , reflection->GetFloat (message, F("optional_float" ))); - EXPECT_EQ(0 , reflection->GetDouble(message, F("optional_double" ))); - EXPECT_FALSE( reflection->GetBool (message, F("optional_bool" ))); - EXPECT_EQ("" , reflection->GetString(message, F("optional_string" ))); - EXPECT_EQ("" , reflection->GetString(message, F("optional_bytes" ))); - - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string"), &scratch)); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_bytes" ), &scratch)); - - // Embedded messages should also be clear. - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - sub_message = &reflection->GetMessage(message, F("optional_public_import_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); - sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("optional_nested_enum" ))); - EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("optional_foreign_enum"))); - EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("optional_import_enum" ))); - - EXPECT_EQ("", reflection->GetString(message, F("optional_string_piece"))); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string_piece"), &scratch)); - - EXPECT_EQ("", reflection->GetString(message, F("optional_cord"))); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_cord"), &scratch)); - - // Repeated fields are empty. - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed32"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed64"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_float" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_double" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bool" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bytes" ))); - - EXPECT_EQ(0, reflection->FieldSize(message, F("repeatedgroup" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_message"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_lazy_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_enum" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_enum" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_enum" ))); - - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string_piece"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_cord"))); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(reflection->HasField(message, F("default_int32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_int64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_uint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_uint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_fixed32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_fixed64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sfixed32"))); - EXPECT_FALSE(reflection->HasField(message, F("default_sfixed64"))); - EXPECT_FALSE(reflection->HasField(message, F("default_float" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_double" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_bool" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_string" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_bytes" ))); - - EXPECT_FALSE(reflection->HasField(message, F("default_nested_enum" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_foreign_enum"))); - EXPECT_FALSE(reflection->HasField(message, F("default_import_enum" ))); - - EXPECT_FALSE(reflection->HasField(message, F("default_string_piece"))); - EXPECT_FALSE(reflection->HasField(message, F("default_cord"))); - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , reflection->GetInt32 (message, F("default_int32" ))); - EXPECT_EQ( 42 , reflection->GetInt64 (message, F("default_int64" ))); - EXPECT_EQ( 43 , reflection->GetUInt32(message, F("default_uint32" ))); - EXPECT_EQ( 44 , reflection->GetUInt64(message, F("default_uint64" ))); - EXPECT_EQ(-45 , reflection->GetInt32 (message, F("default_sint32" ))); - EXPECT_EQ( 46 , reflection->GetInt64 (message, F("default_sint64" ))); - EXPECT_EQ( 47 , reflection->GetUInt32(message, F("default_fixed32" ))); - EXPECT_EQ( 48 , reflection->GetUInt64(message, F("default_fixed64" ))); - EXPECT_EQ( 49 , reflection->GetInt32 (message, F("default_sfixed32"))); - EXPECT_EQ(-50 , reflection->GetInt64 (message, F("default_sfixed64"))); - EXPECT_EQ( 51.5 , reflection->GetFloat (message, F("default_float" ))); - EXPECT_EQ( 52e3 , reflection->GetDouble(message, F("default_double" ))); - EXPECT_TRUE( reflection->GetBool (message, F("default_bool" ))); - EXPECT_EQ("hello", reflection->GetString(message, F("default_string" ))); - EXPECT_EQ("world", reflection->GetString(message, F("default_bytes" ))); - - EXPECT_EQ("hello", reflection->GetStringReference(message, F("default_string"), &scratch)); - EXPECT_EQ("world", reflection->GetStringReference(message, F("default_bytes" ), &scratch)); - - EXPECT_EQ( nested_bar_, reflection->GetEnum(message, F("default_nested_enum" ))); - EXPECT_EQ(foreign_bar_, reflection->GetEnum(message, F("default_foreign_enum"))); - EXPECT_EQ( import_bar_, reflection->GetEnum(message, F("default_import_enum" ))); - - EXPECT_EQ("abc", reflection->GetString(message, F("default_string_piece"))); - EXPECT_EQ("abc", reflection->GetStringReference(message, F("default_string_piece"), &scratch)); - - EXPECT_EQ("123", reflection->GetString(message, F("default_cord"))); - EXPECT_EQ("123", reflection->GetStringReference(message, F("default_cord"), &scratch)); -} - -void TestUtil::ReflectionTester::ExpectPackedClearViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed32"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed64"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_float" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_double" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_bool" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_enum" ))); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ModifyRepeatedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - Message* sub_message; - - reflection->SetRepeatedInt32 (message, F("repeated_int32" ), 1, 501); - reflection->SetRepeatedInt64 (message, F("repeated_int64" ), 1, 502); - reflection->SetRepeatedUInt32(message, F("repeated_uint32" ), 1, 503); - reflection->SetRepeatedUInt64(message, F("repeated_uint64" ), 1, 504); - reflection->SetRepeatedInt32 (message, F("repeated_sint32" ), 1, 505); - reflection->SetRepeatedInt64 (message, F("repeated_sint64" ), 1, 506); - reflection->SetRepeatedUInt32(message, F("repeated_fixed32" ), 1, 507); - reflection->SetRepeatedUInt64(message, F("repeated_fixed64" ), 1, 508); - reflection->SetRepeatedInt32 (message, F("repeated_sfixed32"), 1, 509); - reflection->SetRepeatedInt64 (message, F("repeated_sfixed64"), 1, 510); - reflection->SetRepeatedFloat (message, F("repeated_float" ), 1, 511); - reflection->SetRepeatedDouble(message, F("repeated_double" ), 1, 512); - reflection->SetRepeatedBool (message, F("repeated_bool" ), 1, true); - reflection->SetRepeatedString(message, F("repeated_string" ), 1, "515"); - reflection->SetRepeatedString(message, F("repeated_bytes" ), 1, "516"); - - sub_message = reflection->MutableRepeatedMessage(message, F("repeatedgroup"), 1); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 517); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_nested_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 518); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_foreign_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 519); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_import_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 520); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_lazy_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 527); - - reflection->SetRepeatedEnum(message, F("repeated_nested_enum" ), 1, nested_foo_); - reflection->SetRepeatedEnum(message, F("repeated_foreign_enum"), 1, foreign_foo_); - reflection->SetRepeatedEnum(message, F("repeated_import_enum" ), 1, import_foo_); - - reflection->SetRepeatedString(message, F("repeated_string_piece"), 1, "524"); - reflection->SetRepeatedString(message, F("repeated_cord"), 1, "525"); -} - -void TestUtil::ReflectionTester::ModifyPackedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - reflection->SetRepeatedInt32 (message, F("packed_int32" ), 1, 801); - reflection->SetRepeatedInt64 (message, F("packed_int64" ), 1, 802); - reflection->SetRepeatedUInt32(message, F("packed_uint32" ), 1, 803); - reflection->SetRepeatedUInt64(message, F("packed_uint64" ), 1, 804); - reflection->SetRepeatedInt32 (message, F("packed_sint32" ), 1, 805); - reflection->SetRepeatedInt64 (message, F("packed_sint64" ), 1, 806); - reflection->SetRepeatedUInt32(message, F("packed_fixed32" ), 1, 807); - reflection->SetRepeatedUInt64(message, F("packed_fixed64" ), 1, 808); - reflection->SetRepeatedInt32 (message, F("packed_sfixed32"), 1, 809); - reflection->SetRepeatedInt64 (message, F("packed_sfixed64"), 1, 810); - reflection->SetRepeatedFloat (message, F("packed_float" ), 1, 811); - reflection->SetRepeatedDouble(message, F("packed_double" ), 1, 812); - reflection->SetRepeatedBool (message, F("packed_bool" ), 1, true); - reflection->SetRepeatedEnum (message, F("packed_enum" ), 1, foreign_foo_); -} - -void TestUtil::ReflectionTester::RemoveLastRepeatedsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - - std::vector output; - reflection->ListFields(*message, &output); - for (int i=0; iis_repeated()) continue; - - reflection->RemoveLast(message, field); - } -} - -void TestUtil::ReflectionTester::ReleaseLastRepeatedsViaReflection( - Message* message, bool expect_extensions_notnull) { - const Reflection* reflection = message->GetReflection(); - - std::vector output; - reflection->ListFields(*message, &output); - for (int i=0; iis_repeated()) continue; - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; - - Message* released = reflection->ReleaseLast(message, field); - if (!field->is_extension() || expect_extensions_notnull) { - ASSERT_TRUE(released != NULL) << "ReleaseLast returned NULL for: " - << field->name(); - } - delete released; - } -} - -void TestUtil::ReflectionTester::SwapRepeatedsViaReflection(Message* message) { - const Reflection* reflection = message->GetReflection(); - - std::vector output; - reflection->ListFields(*message, &output); - for (int i=0; iis_repeated()) continue; - - reflection->SwapElements(message, field, 0, 1); - } -} - -void TestUtil::ReflectionTester:: -SetAllocatedOptionalMessageFieldsToNullViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - - std::vector fields; - reflection->ListFields(*message, &fields); - - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - if (!field->is_optional() || - field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; - - reflection->SetAllocatedMessage(message, NULL, field); - } -} - -void TestUtil::ReflectionTester:: -SetAllocatedOptionalMessageFieldsToMessageViaReflection( - Message* from_message, - Message* to_message) { - EXPECT_EQ(from_message->GetDescriptor(), to_message->GetDescriptor()); - const Reflection* from_reflection = from_message->GetReflection(); - const Reflection* to_reflection = to_message->GetReflection(); - - std::vector fields; - from_reflection->ListFields(*from_message, &fields); - - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - if (!field->is_optional() || - field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; - - Message* sub_message = - from_reflection->ReleaseMessage(from_message, field); - to_reflection->SetAllocatedMessage(to_message, sub_message, field); - } -} - -void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection( - Message* message, - TestUtil::ReflectionTester::MessageReleaseState expected_release_state) { - const Reflection* reflection = message->GetReflection(); - - static const char* fields[] = { - "optionalgroup", - "optional_nested_message", - "optional_foreign_message", - "optional_import_message", - }; - for (int i = 0; i < GOOGLE_ARRAYSIZE(fields); i++) { - const Message& sub_message = reflection->GetMessage(*message, F(fields[i])); - Message* released = reflection->ReleaseMessage(message, F(fields[i])); - switch (expected_release_state) { - case IS_NULL: - EXPECT_TRUE(released == NULL); - break; - case NOT_NULL: - EXPECT_TRUE(released != NULL); - if (message->GetArena() == NULL) { - // released message must be same as sub_message if source message is - // not on arena. - EXPECT_EQ(&sub_message, released); - } - break; - case CAN_BE_NULL: - break; - } - delete released; - EXPECT_FALSE(reflection->HasField(*message, F(fields[i]))); - } -} - } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/test_util.h b/src/google/protobuf/test_util.h index 1c13a1a7f6..b9abb6717d 100644 --- a/src/google/protobuf/test_util.h +++ b/src/google/protobuf/test_util.h @@ -35,180 +35,1266 @@ #ifndef GOOGLE_PROTOBUF_TEST_UTIL_H__ #define GOOGLE_PROTOBUF_TEST_UTIL_H__ -#include -#include -#include #include +#define UNITTEST ::protobuf_unittest +#define UNITTEST_IMPORT ::protobuf_unittest_import +// Must be included when the preprocessor symbols above are defined. +#include +#undef UNITTEST +#undef UNITTEST_IMPORT + + namespace google { namespace protobuf { - +// This file doesn't use these declarations, but some .cc files do. namespace unittest = ::protobuf_unittest; -namespace unittest_import = protobuf_unittest_import; +namespace unittest_import = ::protobuf_unittest_import; -class TestUtil { +namespace TestUtil { + +class ReflectionTester { public: - // Set every field in the message to a unique value. - static void SetAllFields(unittest::TestAllTypes* message); - static void SetOptionalFields(unittest::TestAllTypes* message); - static void AddRepeatedFields1(unittest::TestAllTypes* message); - static void AddRepeatedFields2(unittest::TestAllTypes* message); - static void SetDefaultFields(unittest::TestAllTypes* message); - static void SetOneofFields(unittest::TestAllTypes* message); - static void SetAllExtensions(unittest::TestAllExtensions* message); - static void SetOneofFields(unittest::TestAllExtensions* message); - static void SetAllFieldsAndExtensions(unittest::TestFieldOrderings* message); - static void SetPackedFields(unittest::TestPackedTypes* message); - static void SetPackedExtensions(unittest::TestPackedExtensions* message); - static void SetUnpackedFields(unittest::TestUnpackedTypes* message); - static void SetOneof1(unittest::TestOneof2* message); - static void SetOneof2(unittest::TestOneof2* message); - - // Use the repeated versions of the set_*() accessors to modify all the - // repeated fields of the message (which should already have been - // initialized with Set*Fields()). Set*Fields() itself only tests - // the add_*() accessors. - static void ModifyRepeatedFields(unittest::TestAllTypes* message); - static void ModifyRepeatedExtensions(unittest::TestAllExtensions* message); - static void ModifyPackedFields(unittest::TestPackedTypes* message); - static void ModifyPackedExtensions(unittest::TestPackedExtensions* message); - - // Check that all fields have the values that they should have after - // Set*Fields() is called. - static void ExpectAllFieldsSet(const unittest::TestAllTypes& message); - static void ExpectAllExtensionsSet( - const unittest::TestAllExtensions& message); - static void ExpectPackedFieldsSet(const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsSet( - const unittest::TestPackedExtensions& message); - static void ExpectUnpackedFieldsSet( - const unittest::TestUnpackedTypes& message); - static void ExpectUnpackedExtensionsSet( - const unittest::TestUnpackedExtensions& message); - static void ExpectOneofSet1(const unittest::TestOneof2& message); - static void ExpectOneofSet2(const unittest::TestOneof2& message); - - // Expect that the message is modified as would be expected from - // Modify*Fields(). - static void ExpectRepeatedFieldsModified( - const unittest::TestAllTypes& message); - static void ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensions& message); - static void ExpectPackedFieldsModified( - const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsModified( - const unittest::TestPackedExtensions& message); - - // Check that all fields have their default values. - static void ExpectClear(const unittest::TestAllTypes& message); - static void ExpectExtensionsClear(const unittest::TestAllExtensions& message); - static void ExpectPackedClear(const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsClear( - const unittest::TestPackedExtensions& message); - static void ExpectOneofClear(const unittest::TestOneof2& message); - - // Check that the passed-in serialization is the canonical serialization we - // expect for a TestFieldOrderings message filled in by - // SetAllFieldsAndExtensions(). - static void ExpectAllFieldsAndExtensionsInOrder(const string& serialized); - - // Check that all repeated fields have had their last elements removed. - static void ExpectLastRepeatedsRemoved( - const unittest::TestAllTypes& message); - static void ExpectLastRepeatedExtensionsRemoved( - const unittest::TestAllExtensions& message); - static void ExpectLastRepeatedsReleased( - const unittest::TestAllTypes& message); - static void ExpectLastRepeatedExtensionsReleased( - const unittest::TestAllExtensions& message); - - // Check that all repeated fields have had their first and last elements - // swapped. - static void ExpectRepeatedsSwapped(const unittest::TestAllTypes& message); - static void ExpectRepeatedExtensionsSwapped( - const unittest::TestAllExtensions& message); - - static void ExpectAtMostOneFieldSetInOneof( - const unittest::TestOneof2 &message); - - // Like above, but use the reflection interface. - class ReflectionTester { - public: - // base_descriptor must be a descriptor for TestAllTypes or - // TestAllExtensions. In the former case, ReflectionTester fetches from - // it the FieldDescriptors needed to use the reflection interface. In - // the latter case, ReflectionTester searches for extension fields in - // its file. - explicit ReflectionTester(const Descriptor* base_descriptor); - - void SetAllFieldsViaReflection(Message* message); - void ModifyRepeatedFieldsViaReflection(Message* message); - void ExpectAllFieldsSetViaReflection(const Message& message); - void ExpectClearViaReflection(const Message& message); - - void SetPackedFieldsViaReflection(Message* message); - void ModifyPackedFieldsViaReflection(Message* message); - void ExpectPackedFieldsSetViaReflection(const Message& message); - void ExpectPackedClearViaReflection(const Message& message); - - void RemoveLastRepeatedsViaReflection(Message* message); - void ReleaseLastRepeatedsViaReflection( - Message* message, bool expect_extensions_notnull); - void SwapRepeatedsViaReflection(Message* message); - void SetAllocatedOptionalMessageFieldsToNullViaReflection( - Message* message); - static void SetAllocatedOptionalMessageFieldsToMessageViaReflection( - Message* from_message, - Message* to_message); - - enum MessageReleaseState { - IS_NULL, - CAN_BE_NULL, - NOT_NULL, - }; - void ExpectMessagesReleasedViaReflection( - Message* message, MessageReleaseState expected_release_state); - - // Set and check functions for TestOneof2 messages. No need to construct - // the ReflectionTester by TestAllTypes nor TestAllExtensions. - static void SetOneofViaReflection(Message* message); - static void ExpectOneofSetViaReflection(const Message& message); - - private: - const FieldDescriptor* F(const string& name); - - const Descriptor* base_descriptor_; - - const FieldDescriptor* group_a_; - const FieldDescriptor* repeated_group_a_; - const FieldDescriptor* nested_b_; - const FieldDescriptor* foreign_c_; - const FieldDescriptor* import_d_; - const FieldDescriptor* import_e_; - - const EnumValueDescriptor* nested_foo_; - const EnumValueDescriptor* nested_bar_; - const EnumValueDescriptor* nested_baz_; - const EnumValueDescriptor* foreign_foo_; - const EnumValueDescriptor* foreign_bar_; - const EnumValueDescriptor* foreign_baz_; - const EnumValueDescriptor* import_foo_; - const EnumValueDescriptor* import_bar_; - const EnumValueDescriptor* import_baz_; - - // We have to split this into three function otherwise it creates a stack - // frame so large that it triggers a warning. - void ExpectAllFieldsSetViaReflection1(const Message& message); - void ExpectAllFieldsSetViaReflection2(const Message& message); - void ExpectAllFieldsSetViaReflection3(const Message& message); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionTester); + // base_descriptor must be a descriptor for TestAllTypes or + // TestAllExtensions. In the former case, ReflectionTester fetches from + // it the FieldDescriptors needed to use the reflection interface. In + // the latter case, ReflectionTester searches for extension fields in + // its file. + explicit ReflectionTester(const Descriptor* base_descriptor); + + void SetAllFieldsViaReflection(Message* message); + void ModifyRepeatedFieldsViaReflection(Message* message); + void ExpectAllFieldsSetViaReflection(const Message& message); + void ExpectClearViaReflection(const Message& message); + + void SetPackedFieldsViaReflection(Message* message); + void ModifyPackedFieldsViaReflection(Message* message); + void ExpectPackedFieldsSetViaReflection(const Message& message); + void ExpectPackedClearViaReflection(const Message& message); + + void RemoveLastRepeatedsViaReflection(Message* message); + void ReleaseLastRepeatedsViaReflection(Message* message, + bool expect_extensions_notnull); + void SwapRepeatedsViaReflection(Message* message); + void SetAllocatedOptionalMessageFieldsToNullViaReflection(Message* message); + static void SetAllocatedOptionalMessageFieldsToMessageViaReflection( + Message* from_message, Message* to_message); + + enum MessageReleaseState { + IS_NULL, + CAN_BE_NULL, + NOT_NULL, }; + void ExpectMessagesReleasedViaReflection( + Message* message, MessageReleaseState expected_release_state); + + // Set and check functions for TestOneof2 messages. No need to construct + // the ReflectionTester by TestAllTypes nor TestAllExtensions. + static void SetOneofViaReflection(Message* message); + static void ExpectOneofSetViaReflection(const Message& message); private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TestUtil); + const FieldDescriptor* F(const string& name); + + const Descriptor* base_descriptor_; + + const FieldDescriptor* group_a_; + const FieldDescriptor* repeated_group_a_; + const FieldDescriptor* nested_b_; + const FieldDescriptor* foreign_c_; + const FieldDescriptor* import_d_; + const FieldDescriptor* import_e_; + + const EnumValueDescriptor* nested_foo_; + const EnumValueDescriptor* nested_bar_; + const EnumValueDescriptor* nested_baz_; + const EnumValueDescriptor* foreign_foo_; + const EnumValueDescriptor* foreign_bar_; + const EnumValueDescriptor* foreign_baz_; + const EnumValueDescriptor* import_foo_; + const EnumValueDescriptor* import_bar_; + const EnumValueDescriptor* import_baz_; + + // We have to split this into three function otherwise it creates a stack + // frame so large that it triggers a warning. + void ExpectAllFieldsSetViaReflection1(const Message& message); + void ExpectAllFieldsSetViaReflection2(const Message& message); + void ExpectAllFieldsSetViaReflection3(const Message& message); + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionTester); }; +inline TestUtil::ReflectionTester::ReflectionTester( + const Descriptor* base_descriptor) + : base_descriptor_(base_descriptor) { + const DescriptorPool* pool = base_descriptor->file()->pool(); + string package = base_descriptor->file()->package(); + const FieldDescriptor* import_descriptor = + pool->FindFieldByName(package + ".TestAllTypes.optional_import_message"); + string import_package = import_descriptor->message_type()->file()->package(); + + nested_b_ = pool->FindFieldByName(package + ".TestAllTypes.NestedMessage.bb"); + foreign_c_ = pool->FindFieldByName(package + ".ForeignMessage.c"); + import_d_ = pool->FindFieldByName(import_package + ".ImportMessage.d"); + import_e_ = pool->FindFieldByName(import_package + ".PublicImportMessage.e"); + nested_foo_ = pool->FindEnumValueByName(package + ".TestAllTypes.FOO"); + nested_bar_ = pool->FindEnumValueByName(package + ".TestAllTypes.BAR"); + nested_baz_ = pool->FindEnumValueByName(package + ".TestAllTypes.BAZ"); + foreign_foo_ = pool->FindEnumValueByName(package + ".FOREIGN_FOO"); + foreign_bar_ = pool->FindEnumValueByName(package + ".FOREIGN_BAR"); + foreign_baz_ = pool->FindEnumValueByName(package + ".FOREIGN_BAZ"); + import_foo_ = pool->FindEnumValueByName(import_package + ".IMPORT_FOO"); + import_bar_ = pool->FindEnumValueByName(import_package + ".IMPORT_BAR"); + import_baz_ = pool->FindEnumValueByName(import_package + ".IMPORT_BAZ"); + + if (base_descriptor_->name() == "TestAllExtensions") { + group_a_ = pool->FindFieldByName(package + ".OptionalGroup_extension.a"); + repeated_group_a_ = + pool->FindFieldByName(package + ".RepeatedGroup_extension.a"); + } else { + group_a_ = pool->FindFieldByName(package + ".TestAllTypes.OptionalGroup.a"); + repeated_group_a_ = + pool->FindFieldByName(package + ".TestAllTypes.RepeatedGroup.a"); + } + + EXPECT_TRUE(group_a_ != nullptr); + EXPECT_TRUE(repeated_group_a_ != nullptr); + EXPECT_TRUE(nested_b_ != nullptr); + EXPECT_TRUE(foreign_c_ != nullptr); + EXPECT_TRUE(import_d_ != nullptr); + EXPECT_TRUE(import_e_ != nullptr); + EXPECT_TRUE(nested_foo_ != nullptr); + EXPECT_TRUE(nested_bar_ != nullptr); + EXPECT_TRUE(nested_baz_ != nullptr); + EXPECT_TRUE(foreign_foo_ != nullptr); + EXPECT_TRUE(foreign_bar_ != nullptr); + EXPECT_TRUE(foreign_baz_ != nullptr); + EXPECT_TRUE(import_foo_ != nullptr); + EXPECT_TRUE(import_bar_ != nullptr); + EXPECT_TRUE(import_baz_ != nullptr); +} + +// Shorthand to get a FieldDescriptor for a field of TestAllTypes. +inline const FieldDescriptor* TestUtil::ReflectionTester::F( + const string& name) { + const FieldDescriptor* result = nullptr; + if (base_descriptor_->name() == "TestAllExtensions" || + base_descriptor_->name() == "TestPackedExtensions") { + result = base_descriptor_->file()->FindExtensionByName(name + "_extension"); + } else { + result = base_descriptor_->FindFieldByName(name); + } + GOOGLE_CHECK(result != nullptr); + return result; +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::SetAllFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + Message* sub_message; + + reflection->SetInt32(message, F("optional_int32"), 101); + reflection->SetInt64(message, F("optional_int64"), 102); + reflection->SetUInt32(message, F("optional_uint32"), 103); + reflection->SetUInt64(message, F("optional_uint64"), 104); + reflection->SetInt32(message, F("optional_sint32"), 105); + reflection->SetInt64(message, F("optional_sint64"), 106); + reflection->SetUInt32(message, F("optional_fixed32"), 107); + reflection->SetUInt64(message, F("optional_fixed64"), 108); + reflection->SetInt32(message, F("optional_sfixed32"), 109); + reflection->SetInt64(message, F("optional_sfixed64"), 110); + reflection->SetFloat(message, F("optional_float"), 111); + reflection->SetDouble(message, F("optional_double"), 112); + reflection->SetBool(message, F("optional_bool"), true); + reflection->SetString(message, F("optional_string"), "115"); + reflection->SetString(message, F("optional_bytes"), "116"); + + sub_message = reflection->MutableMessage(message, F("optionalgroup")); + sub_message->GetReflection()->SetInt32(sub_message, group_a_, 117); + sub_message = + reflection->MutableMessage(message, F("optional_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 118); + sub_message = + reflection->MutableMessage(message, F("optional_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 119); + sub_message = + reflection->MutableMessage(message, F("optional_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 120); + + reflection->SetEnum(message, F("optional_nested_enum"), nested_baz_); + reflection->SetEnum(message, F("optional_foreign_enum"), foreign_baz_); + reflection->SetEnum(message, F("optional_import_enum"), import_baz_); + + reflection->SetString(message, F("optional_string_piece"), "124"); + reflection->SetString(message, F("optional_cord"), "125"); + + sub_message = + reflection->MutableMessage(message, F("optional_public_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_e_, 126); + + sub_message = reflection->MutableMessage(message, F("optional_lazy_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 127); + + // ----------------------------------------------------------------- + + reflection->AddInt32(message, F("repeated_int32"), 201); + reflection->AddInt64(message, F("repeated_int64"), 202); + reflection->AddUInt32(message, F("repeated_uint32"), 203); + reflection->AddUInt64(message, F("repeated_uint64"), 204); + reflection->AddInt32(message, F("repeated_sint32"), 205); + reflection->AddInt64(message, F("repeated_sint64"), 206); + reflection->AddUInt32(message, F("repeated_fixed32"), 207); + reflection->AddUInt64(message, F("repeated_fixed64"), 208); + reflection->AddInt32(message, F("repeated_sfixed32"), 209); + reflection->AddInt64(message, F("repeated_sfixed64"), 210); + reflection->AddFloat(message, F("repeated_float"), 211); + reflection->AddDouble(message, F("repeated_double"), 212); + reflection->AddBool(message, F("repeated_bool"), true); + reflection->AddString(message, F("repeated_string"), "215"); + reflection->AddString(message, F("repeated_bytes"), "216"); + + sub_message = reflection->AddMessage(message, F("repeatedgroup")); + sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 217); + sub_message = reflection->AddMessage(message, F("repeated_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 218); + sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 219); + sub_message = reflection->AddMessage(message, F("repeated_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 220); + sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 227); + + reflection->AddEnum(message, F("repeated_nested_enum"), nested_bar_); + reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_bar_); + reflection->AddEnum(message, F("repeated_import_enum"), import_bar_); + + reflection->AddString(message, F("repeated_string_piece"), "224"); + reflection->AddString(message, F("repeated_cord"), "225"); + + // Add a second one of each field. + reflection->AddInt32(message, F("repeated_int32"), 301); + reflection->AddInt64(message, F("repeated_int64"), 302); + reflection->AddUInt32(message, F("repeated_uint32"), 303); + reflection->AddUInt64(message, F("repeated_uint64"), 304); + reflection->AddInt32(message, F("repeated_sint32"), 305); + reflection->AddInt64(message, F("repeated_sint64"), 306); + reflection->AddUInt32(message, F("repeated_fixed32"), 307); + reflection->AddUInt64(message, F("repeated_fixed64"), 308); + reflection->AddInt32(message, F("repeated_sfixed32"), 309); + reflection->AddInt64(message, F("repeated_sfixed64"), 310); + reflection->AddFloat(message, F("repeated_float"), 311); + reflection->AddDouble(message, F("repeated_double"), 312); + reflection->AddBool(message, F("repeated_bool"), false); + reflection->AddString(message, F("repeated_string"), "315"); + reflection->AddString(message, F("repeated_bytes"), "316"); + + sub_message = reflection->AddMessage(message, F("repeatedgroup")); + sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 317); + sub_message = reflection->AddMessage(message, F("repeated_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 318); + sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 319); + sub_message = reflection->AddMessage(message, F("repeated_import_message")); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 320); + sub_message = reflection->AddMessage(message, F("repeated_lazy_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 327); + + reflection->AddEnum(message, F("repeated_nested_enum"), nested_baz_); + reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_baz_); + reflection->AddEnum(message, F("repeated_import_enum"), import_baz_); + + reflection->AddString(message, F("repeated_string_piece"), "324"); + reflection->AddString(message, F("repeated_cord"), "325"); + + // ----------------------------------------------------------------- + + reflection->SetInt32(message, F("default_int32"), 401); + reflection->SetInt64(message, F("default_int64"), 402); + reflection->SetUInt32(message, F("default_uint32"), 403); + reflection->SetUInt64(message, F("default_uint64"), 404); + reflection->SetInt32(message, F("default_sint32"), 405); + reflection->SetInt64(message, F("default_sint64"), 406); + reflection->SetUInt32(message, F("default_fixed32"), 407); + reflection->SetUInt64(message, F("default_fixed64"), 408); + reflection->SetInt32(message, F("default_sfixed32"), 409); + reflection->SetInt64(message, F("default_sfixed64"), 410); + reflection->SetFloat(message, F("default_float"), 411); + reflection->SetDouble(message, F("default_double"), 412); + reflection->SetBool(message, F("default_bool"), false); + reflection->SetString(message, F("default_string"), "415"); + reflection->SetString(message, F("default_bytes"), "416"); + + reflection->SetEnum(message, F("default_nested_enum"), nested_foo_); + reflection->SetEnum(message, F("default_foreign_enum"), foreign_foo_); + reflection->SetEnum(message, F("default_import_enum"), import_foo_); + + reflection->SetString(message, F("default_string_piece"), "424"); + reflection->SetString(message, F("default_cord"), "425"); + + reflection->SetUInt32(message, F("oneof_uint32"), 601); + sub_message = reflection->MutableMessage(message, F("oneof_nested_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 602); + reflection->SetString(message, F("oneof_string"), "603"); + reflection->SetString(message, F("oneof_bytes"), "604"); +} + +inline void TestUtil::ReflectionTester::SetOneofViaReflection( + Message* message) { + const Descriptor* descriptor = message->GetDescriptor(); + const Reflection* reflection = message->GetReflection(); + Message* sub_message = reflection->MutableMessage( + message, descriptor->FindFieldByName("foo_lazy_message")); + sub_message->GetReflection()->SetInt64( + sub_message, sub_message->GetDescriptor()->FindFieldByName("qux_int"), + 100); + + reflection->SetString(message, descriptor->FindFieldByName("bar_cord"), + "101"); + reflection->SetInt32(message, descriptor->FindFieldByName("baz_int"), 102); + reflection->SetString(message, descriptor->FindFieldByName("baz_string"), + "103"); +} + +inline void TestUtil::ReflectionTester::ExpectOneofSetViaReflection( + const Message& message) { + const Descriptor* descriptor = message.GetDescriptor(); + const Reflection* reflection = message.GetReflection(); + string scratch; + EXPECT_TRUE(reflection->HasField( + message, descriptor->FindFieldByName("foo_lazy_message"))); + EXPECT_TRUE( + reflection->HasField(message, descriptor->FindFieldByName("bar_cord"))); + EXPECT_TRUE( + reflection->HasField(message, descriptor->FindFieldByName("baz_int"))); + EXPECT_TRUE( + reflection->HasField(message, descriptor->FindFieldByName("baz_string"))); + + const Message* sub_message = &reflection->GetMessage( + message, descriptor->FindFieldByName("foo_lazy_message")); + EXPECT_EQ(100, sub_message->GetReflection()->GetInt64( + *sub_message, + sub_message->GetDescriptor()->FindFieldByName("qux_int"))); + + EXPECT_EQ("101", reflection->GetString( + message, descriptor->FindFieldByName("bar_cord"))); + EXPECT_EQ("101", + reflection->GetStringReference( + message, descriptor->FindFieldByName("bar_cord"), &scratch)); + + EXPECT_EQ(102, reflection->GetInt32(message, + descriptor->FindFieldByName("baz_int"))); + + EXPECT_EQ("103", reflection->GetString( + message, descriptor->FindFieldByName("baz_string"))); + EXPECT_EQ("103", + reflection->GetStringReference( + message, descriptor->FindFieldByName("baz_string"), &scratch)); +} + +inline void TestUtil::ReflectionTester::SetPackedFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + reflection->AddInt32(message, F("packed_int32"), 601); + reflection->AddInt64(message, F("packed_int64"), 602); + reflection->AddUInt32(message, F("packed_uint32"), 603); + reflection->AddUInt64(message, F("packed_uint64"), 604); + reflection->AddInt32(message, F("packed_sint32"), 605); + reflection->AddInt64(message, F("packed_sint64"), 606); + reflection->AddUInt32(message, F("packed_fixed32"), 607); + reflection->AddUInt64(message, F("packed_fixed64"), 608); + reflection->AddInt32(message, F("packed_sfixed32"), 609); + reflection->AddInt64(message, F("packed_sfixed64"), 610); + reflection->AddFloat(message, F("packed_float"), 611); + reflection->AddDouble(message, F("packed_double"), 612); + reflection->AddBool(message, F("packed_bool"), true); + reflection->AddEnum(message, F("packed_enum"), foreign_bar_); + + reflection->AddInt32(message, F("packed_int32"), 701); + reflection->AddInt64(message, F("packed_int64"), 702); + reflection->AddUInt32(message, F("packed_uint32"), 703); + reflection->AddUInt64(message, F("packed_uint64"), 704); + reflection->AddInt32(message, F("packed_sint32"), 705); + reflection->AddInt64(message, F("packed_sint64"), 706); + reflection->AddUInt32(message, F("packed_fixed32"), 707); + reflection->AddUInt64(message, F("packed_fixed64"), 708); + reflection->AddInt32(message, F("packed_sfixed32"), 709); + reflection->AddInt64(message, F("packed_sfixed64"), 710); + reflection->AddFloat(message, F("packed_float"), 711); + reflection->AddDouble(message, F("packed_double"), 712); + reflection->AddBool(message, F("packed_bool"), false); + reflection->AddEnum(message, F("packed_enum"), foreign_baz_); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection( + const Message& message) { + // We have to split this into three function otherwise it creates a stack + // frame so large that it triggers a warning. + ExpectAllFieldsSetViaReflection1(message); + ExpectAllFieldsSetViaReflection2(message); + ExpectAllFieldsSetViaReflection3(message); +} + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + const Message* sub_message; + + EXPECT_TRUE(reflection->HasField(message, F("optional_int32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_int64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_uint32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_uint64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sint32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sint64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_fixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_fixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_float"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_double"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_bool"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_string"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_bytes"))); + + EXPECT_TRUE(reflection->HasField(message, F("optionalgroup"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_nested_message"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_message"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_import_message"))); + EXPECT_TRUE( + reflection->HasField(message, F("optional_public_import_message"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_lazy_message"))); + + sub_message = &reflection->GetMessage(message, F("optionalgroup")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); + sub_message = &reflection->GetMessage(message, F("optional_nested_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); + sub_message = &reflection->GetMessage(message, F("optional_import_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); + sub_message = + &reflection->GetMessage(message, F("optional_public_import_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); + sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + + EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_import_enum"))); + + EXPECT_TRUE(reflection->HasField(message, F("optional_string_piece"))); + EXPECT_TRUE(reflection->HasField(message, F("optional_cord"))); + + EXPECT_EQ(101, reflection->GetInt32(message, F("optional_int32"))); + EXPECT_EQ(102, reflection->GetInt64(message, F("optional_int64"))); + EXPECT_EQ(103, reflection->GetUInt32(message, F("optional_uint32"))); + EXPECT_EQ(104, reflection->GetUInt64(message, F("optional_uint64"))); + EXPECT_EQ(105, reflection->GetInt32(message, F("optional_sint32"))); + EXPECT_EQ(106, reflection->GetInt64(message, F("optional_sint64"))); + EXPECT_EQ(107, reflection->GetUInt32(message, F("optional_fixed32"))); + EXPECT_EQ(108, reflection->GetUInt64(message, F("optional_fixed64"))); + EXPECT_EQ(109, reflection->GetInt32(message, F("optional_sfixed32"))); + EXPECT_EQ(110, reflection->GetInt64(message, F("optional_sfixed64"))); + EXPECT_EQ(111, reflection->GetFloat(message, F("optional_float"))); + EXPECT_EQ(112, reflection->GetDouble(message, F("optional_double"))); + EXPECT_TRUE(reflection->GetBool(message, F("optional_bool"))); + EXPECT_EQ("115", reflection->GetString(message, F("optional_string"))); + EXPECT_EQ("116", reflection->GetString(message, F("optional_bytes"))); + + EXPECT_EQ("115", reflection->GetStringReference(message, F("optional_string"), + &scratch)); + EXPECT_EQ("116", reflection->GetStringReference(message, F("optional_bytes"), + &scratch)); + + sub_message = &reflection->GetMessage(message, F("optionalgroup")); + EXPECT_EQ(117, + sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); + sub_message = &reflection->GetMessage(message, F("optional_nested_message")); + EXPECT_EQ(118, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); + EXPECT_EQ(119, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = &reflection->GetMessage(message, F("optional_import_message")); + EXPECT_EQ(120, + sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetMessage(message, F("optional_public_import_message")); + EXPECT_EQ(126, + sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); + sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); + EXPECT_EQ(127, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + EXPECT_EQ(nested_baz_, + reflection->GetEnum(message, F("optional_nested_enum"))); + EXPECT_EQ(foreign_baz_, + reflection->GetEnum(message, F("optional_foreign_enum"))); + EXPECT_EQ(import_baz_, + reflection->GetEnum(message, F("optional_import_enum"))); + + EXPECT_EQ("124", reflection->GetString(message, F("optional_string_piece"))); + EXPECT_EQ("124", reflection->GetStringReference( + message, F("optional_string_piece"), &scratch)); + + EXPECT_EQ("125", reflection->GetString(message, F("optional_cord"))); + EXPECT_EQ("125", reflection->GetStringReference(message, F("optional_cord"), + &scratch)); + + EXPECT_TRUE(reflection->HasField(message, F("oneof_bytes"))); + EXPECT_EQ("604", reflection->GetString(message, F("oneof_bytes"))); + + if (base_descriptor_->name() == "TestAllTypes") { + EXPECT_FALSE(reflection->HasField(message, F("oneof_uint32"))); + EXPECT_FALSE(reflection->HasField(message, F("oneof_string"))); + } else { + EXPECT_TRUE(reflection->HasField(message, F("oneof_uint32"))); + EXPECT_TRUE(reflection->HasField(message, F("oneof_string"))); + EXPECT_EQ(601, reflection->GetUInt32(message, F("oneof_uint32"))); + EXPECT_EQ("603", reflection->GetString(message, F("oneof_string"))); + sub_message = &reflection->GetMessage(message, F("oneof_nested_message")); + EXPECT_EQ(602, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + } +} + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + const Message* sub_message; + + // ----------------------------------------------------------------- + + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_float"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_double"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bool"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bytes"))); + + ASSERT_EQ(2, reflection->FieldSize(message, F("repeatedgroup"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_lazy_message"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_enum"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_enum"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_enum"))); + + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string_piece"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_cord"))); + + EXPECT_EQ(201, reflection->GetRepeatedInt32(message, F("repeated_int32"), 0)); + EXPECT_EQ(202, reflection->GetRepeatedInt64(message, F("repeated_int64"), 0)); + EXPECT_EQ(203, + reflection->GetRepeatedUInt32(message, F("repeated_uint32"), 0)); + EXPECT_EQ(204, + reflection->GetRepeatedUInt64(message, F("repeated_uint64"), 0)); + EXPECT_EQ(205, + reflection->GetRepeatedInt32(message, F("repeated_sint32"), 0)); + EXPECT_EQ(206, + reflection->GetRepeatedInt64(message, F("repeated_sint64"), 0)); + EXPECT_EQ(207, + reflection->GetRepeatedUInt32(message, F("repeated_fixed32"), 0)); + EXPECT_EQ(208, + reflection->GetRepeatedUInt64(message, F("repeated_fixed64"), 0)); + EXPECT_EQ(209, + reflection->GetRepeatedInt32(message, F("repeated_sfixed32"), 0)); + EXPECT_EQ(210, + reflection->GetRepeatedInt64(message, F("repeated_sfixed64"), 0)); + EXPECT_EQ(211, reflection->GetRepeatedFloat(message, F("repeated_float"), 0)); + EXPECT_EQ(212, + reflection->GetRepeatedDouble(message, F("repeated_double"), 0)); + EXPECT_TRUE(reflection->GetRepeatedBool(message, F("repeated_bool"), 0)); + EXPECT_EQ("215", + reflection->GetRepeatedString(message, F("repeated_string"), 0)); + EXPECT_EQ("216", + reflection->GetRepeatedString(message, F("repeated_bytes"), 0)); + + EXPECT_EQ("215", reflection->GetRepeatedStringReference( + message, F("repeated_string"), 0, &scratch)); + EXPECT_EQ("216", reflection->GetRepeatedStringReference( + message, F("repeated_bytes"), 0, &scratch)); + + sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 0); + EXPECT_EQ(217, sub_message->GetReflection()->GetInt32(*sub_message, + repeated_group_a_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 0); + EXPECT_EQ(218, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetRepeatedMessage( + message, F("repeated_foreign_message"), 0); + EXPECT_EQ(219, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 0); + EXPECT_EQ(220, + sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 0); + EXPECT_EQ(227, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + EXPECT_EQ(nested_bar_, + reflection->GetRepeatedEnum(message, F("repeated_nested_enum"), 0)); + EXPECT_EQ(foreign_bar_, reflection->GetRepeatedEnum( + message, F("repeated_foreign_enum"), 0)); + EXPECT_EQ(import_bar_, + reflection->GetRepeatedEnum(message, F("repeated_import_enum"), 0)); + + EXPECT_EQ("224", reflection->GetRepeatedString( + message, F("repeated_string_piece"), 0)); + EXPECT_EQ("224", reflection->GetRepeatedStringReference( + message, F("repeated_string_piece"), 0, &scratch)); + + EXPECT_EQ("225", + reflection->GetRepeatedString(message, F("repeated_cord"), 0)); + EXPECT_EQ("225", reflection->GetRepeatedStringReference( + message, F("repeated_cord"), 0, &scratch)); + + EXPECT_EQ(301, reflection->GetRepeatedInt32(message, F("repeated_int32"), 1)); + EXPECT_EQ(302, reflection->GetRepeatedInt64(message, F("repeated_int64"), 1)); + EXPECT_EQ(303, + reflection->GetRepeatedUInt32(message, F("repeated_uint32"), 1)); + EXPECT_EQ(304, + reflection->GetRepeatedUInt64(message, F("repeated_uint64"), 1)); + EXPECT_EQ(305, + reflection->GetRepeatedInt32(message, F("repeated_sint32"), 1)); + EXPECT_EQ(306, + reflection->GetRepeatedInt64(message, F("repeated_sint64"), 1)); + EXPECT_EQ(307, + reflection->GetRepeatedUInt32(message, F("repeated_fixed32"), 1)); + EXPECT_EQ(308, + reflection->GetRepeatedUInt64(message, F("repeated_fixed64"), 1)); + EXPECT_EQ(309, + reflection->GetRepeatedInt32(message, F("repeated_sfixed32"), 1)); + EXPECT_EQ(310, + reflection->GetRepeatedInt64(message, F("repeated_sfixed64"), 1)); + EXPECT_EQ(311, reflection->GetRepeatedFloat(message, F("repeated_float"), 1)); + EXPECT_EQ(312, + reflection->GetRepeatedDouble(message, F("repeated_double"), 1)); + EXPECT_FALSE(reflection->GetRepeatedBool(message, F("repeated_bool"), 1)); + EXPECT_EQ("315", + reflection->GetRepeatedString(message, F("repeated_string"), 1)); + EXPECT_EQ("316", + reflection->GetRepeatedString(message, F("repeated_bytes"), 1)); + + EXPECT_EQ("315", reflection->GetRepeatedStringReference( + message, F("repeated_string"), 1, &scratch)); + EXPECT_EQ("316", reflection->GetRepeatedStringReference( + message, F("repeated_bytes"), 1, &scratch)); + + sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 1); + EXPECT_EQ(317, sub_message->GetReflection()->GetInt32(*sub_message, + repeated_group_a_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 1); + EXPECT_EQ(318, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetRepeatedMessage( + message, F("repeated_foreign_message"), 1); + EXPECT_EQ(319, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 1); + EXPECT_EQ(320, + sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetRepeatedMessage(message, F("repeated_lazy_message"), 1); + EXPECT_EQ(327, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + EXPECT_EQ(nested_baz_, + reflection->GetRepeatedEnum(message, F("repeated_nested_enum"), 1)); + EXPECT_EQ(foreign_baz_, reflection->GetRepeatedEnum( + message, F("repeated_foreign_enum"), 1)); + EXPECT_EQ(import_baz_, + reflection->GetRepeatedEnum(message, F("repeated_import_enum"), 1)); + + EXPECT_EQ("324", reflection->GetRepeatedString( + message, F("repeated_string_piece"), 1)); + EXPECT_EQ("324", reflection->GetRepeatedStringReference( + message, F("repeated_string_piece"), 1, &scratch)); + + EXPECT_EQ("325", + reflection->GetRepeatedString(message, F("repeated_cord"), 1)); + EXPECT_EQ("325", reflection->GetRepeatedStringReference( + message, F("repeated_cord"), 1, &scratch)); +} + +inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + + // ----------------------------------------------------------------- + + EXPECT_TRUE(reflection->HasField(message, F("default_int32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_int64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_uint32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_uint64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sint32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sint64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_fixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_fixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sfixed32"))); + EXPECT_TRUE(reflection->HasField(message, F("default_sfixed64"))); + EXPECT_TRUE(reflection->HasField(message, F("default_float"))); + EXPECT_TRUE(reflection->HasField(message, F("default_double"))); + EXPECT_TRUE(reflection->HasField(message, F("default_bool"))); + EXPECT_TRUE(reflection->HasField(message, F("default_string"))); + EXPECT_TRUE(reflection->HasField(message, F("default_bytes"))); + + EXPECT_TRUE(reflection->HasField(message, F("default_nested_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("default_foreign_enum"))); + EXPECT_TRUE(reflection->HasField(message, F("default_import_enum"))); + + EXPECT_TRUE(reflection->HasField(message, F("default_string_piece"))); + EXPECT_TRUE(reflection->HasField(message, F("default_cord"))); + + EXPECT_EQ(401, reflection->GetInt32(message, F("default_int32"))); + EXPECT_EQ(402, reflection->GetInt64(message, F("default_int64"))); + EXPECT_EQ(403, reflection->GetUInt32(message, F("default_uint32"))); + EXPECT_EQ(404, reflection->GetUInt64(message, F("default_uint64"))); + EXPECT_EQ(405, reflection->GetInt32(message, F("default_sint32"))); + EXPECT_EQ(406, reflection->GetInt64(message, F("default_sint64"))); + EXPECT_EQ(407, reflection->GetUInt32(message, F("default_fixed32"))); + EXPECT_EQ(408, reflection->GetUInt64(message, F("default_fixed64"))); + EXPECT_EQ(409, reflection->GetInt32(message, F("default_sfixed32"))); + EXPECT_EQ(410, reflection->GetInt64(message, F("default_sfixed64"))); + EXPECT_EQ(411, reflection->GetFloat(message, F("default_float"))); + EXPECT_EQ(412, reflection->GetDouble(message, F("default_double"))); + EXPECT_FALSE(reflection->GetBool(message, F("default_bool"))); + EXPECT_EQ("415", reflection->GetString(message, F("default_string"))); + EXPECT_EQ("416", reflection->GetString(message, F("default_bytes"))); + + EXPECT_EQ("415", reflection->GetStringReference(message, F("default_string"), + &scratch)); + EXPECT_EQ("416", reflection->GetStringReference(message, F("default_bytes"), + &scratch)); + + EXPECT_EQ(nested_foo_, + reflection->GetEnum(message, F("default_nested_enum"))); + EXPECT_EQ(foreign_foo_, + reflection->GetEnum(message, F("default_foreign_enum"))); + EXPECT_EQ(import_foo_, + reflection->GetEnum(message, F("default_import_enum"))); + + EXPECT_EQ("424", reflection->GetString(message, F("default_string_piece"))); + EXPECT_EQ("424", reflection->GetStringReference( + message, F("default_string_piece"), &scratch)); + + EXPECT_EQ("425", reflection->GetString(message, F("default_cord"))); + EXPECT_EQ("425", reflection->GetStringReference(message, F("default_cord"), + &scratch)); +} + +inline void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed32"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed64"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_float"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_double"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_bool"))); + ASSERT_EQ(2, reflection->FieldSize(message, F("packed_enum"))); + + EXPECT_EQ(601, reflection->GetRepeatedInt32(message, F("packed_int32"), 0)); + EXPECT_EQ(602, reflection->GetRepeatedInt64(message, F("packed_int64"), 0)); + EXPECT_EQ(603, reflection->GetRepeatedUInt32(message, F("packed_uint32"), 0)); + EXPECT_EQ(604, reflection->GetRepeatedUInt64(message, F("packed_uint64"), 0)); + EXPECT_EQ(605, reflection->GetRepeatedInt32(message, F("packed_sint32"), 0)); + EXPECT_EQ(606, reflection->GetRepeatedInt64(message, F("packed_sint64"), 0)); + EXPECT_EQ(607, + reflection->GetRepeatedUInt32(message, F("packed_fixed32"), 0)); + EXPECT_EQ(608, + reflection->GetRepeatedUInt64(message, F("packed_fixed64"), 0)); + EXPECT_EQ(609, + reflection->GetRepeatedInt32(message, F("packed_sfixed32"), 0)); + EXPECT_EQ(610, + reflection->GetRepeatedInt64(message, F("packed_sfixed64"), 0)); + EXPECT_EQ(611, reflection->GetRepeatedFloat(message, F("packed_float"), 0)); + EXPECT_EQ(612, reflection->GetRepeatedDouble(message, F("packed_double"), 0)); + EXPECT_TRUE(reflection->GetRepeatedBool(message, F("packed_bool"), 0)); + EXPECT_EQ(foreign_bar_, + reflection->GetRepeatedEnum(message, F("packed_enum"), 0)); + + EXPECT_EQ(701, reflection->GetRepeatedInt32(message, F("packed_int32"), 1)); + EXPECT_EQ(702, reflection->GetRepeatedInt64(message, F("packed_int64"), 1)); + EXPECT_EQ(703, reflection->GetRepeatedUInt32(message, F("packed_uint32"), 1)); + EXPECT_EQ(704, reflection->GetRepeatedUInt64(message, F("packed_uint64"), 1)); + EXPECT_EQ(705, reflection->GetRepeatedInt32(message, F("packed_sint32"), 1)); + EXPECT_EQ(706, reflection->GetRepeatedInt64(message, F("packed_sint64"), 1)); + EXPECT_EQ(707, + reflection->GetRepeatedUInt32(message, F("packed_fixed32"), 1)); + EXPECT_EQ(708, + reflection->GetRepeatedUInt64(message, F("packed_fixed64"), 1)); + EXPECT_EQ(709, + reflection->GetRepeatedInt32(message, F("packed_sfixed32"), 1)); + EXPECT_EQ(710, + reflection->GetRepeatedInt64(message, F("packed_sfixed64"), 1)); + EXPECT_EQ(711, reflection->GetRepeatedFloat(message, F("packed_float"), 1)); + EXPECT_EQ(712, reflection->GetRepeatedDouble(message, F("packed_double"), 1)); + EXPECT_FALSE(reflection->GetRepeatedBool(message, F("packed_bool"), 1)); + EXPECT_EQ(foreign_baz_, + reflection->GetRepeatedEnum(message, F("packed_enum"), 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::ExpectClearViaReflection( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + string scratch; + const Message* sub_message; + + // has_blah() should initially be false for all optional fields. + EXPECT_FALSE(reflection->HasField(message, F("optional_int32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_int64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_uint32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_uint64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sint32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sint64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_fixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_fixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_float"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_double"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_bool"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_string"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_bytes"))); + + EXPECT_FALSE(reflection->HasField(message, F("optionalgroup"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_nested_message"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_message"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_import_message"))); + EXPECT_FALSE( + reflection->HasField(message, F("optional_public_import_message"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_lazy_message"))); + + EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_import_enum"))); + + EXPECT_FALSE(reflection->HasField(message, F("optional_string_piece"))); + EXPECT_FALSE(reflection->HasField(message, F("optional_cord"))); + + // Optional fields without defaults are set to zero or something like it. + EXPECT_EQ(0, reflection->GetInt32(message, F("optional_int32"))); + EXPECT_EQ(0, reflection->GetInt64(message, F("optional_int64"))); + EXPECT_EQ(0, reflection->GetUInt32(message, F("optional_uint32"))); + EXPECT_EQ(0, reflection->GetUInt64(message, F("optional_uint64"))); + EXPECT_EQ(0, reflection->GetInt32(message, F("optional_sint32"))); + EXPECT_EQ(0, reflection->GetInt64(message, F("optional_sint64"))); + EXPECT_EQ(0, reflection->GetUInt32(message, F("optional_fixed32"))); + EXPECT_EQ(0, reflection->GetUInt64(message, F("optional_fixed64"))); + EXPECT_EQ(0, reflection->GetInt32(message, F("optional_sfixed32"))); + EXPECT_EQ(0, reflection->GetInt64(message, F("optional_sfixed64"))); + EXPECT_EQ(0, reflection->GetFloat(message, F("optional_float"))); + EXPECT_EQ(0, reflection->GetDouble(message, F("optional_double"))); + EXPECT_FALSE(reflection->GetBool(message, F("optional_bool"))); + EXPECT_EQ("", reflection->GetString(message, F("optional_string"))); + EXPECT_EQ("", reflection->GetString(message, F("optional_bytes"))); + + EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string"), + &scratch)); + EXPECT_EQ("", reflection->GetStringReference(message, F("optional_bytes"), + &scratch)); + + // Embedded messages should also be clear. + sub_message = &reflection->GetMessage(message, F("optionalgroup")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); + sub_message = &reflection->GetMessage(message, F("optional_nested_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); + EXPECT_FALSE( + sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); + EXPECT_EQ(0, + sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); + sub_message = &reflection->GetMessage(message, F("optional_import_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); + sub_message = + &reflection->GetMessage(message, F("optional_public_import_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_e_)); + sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + + // Enums without defaults are set to the first value in the enum. + EXPECT_EQ(nested_foo_, + reflection->GetEnum(message, F("optional_nested_enum"))); + EXPECT_EQ(foreign_foo_, + reflection->GetEnum(message, F("optional_foreign_enum"))); + EXPECT_EQ(import_foo_, + reflection->GetEnum(message, F("optional_import_enum"))); + + EXPECT_EQ("", reflection->GetString(message, F("optional_string_piece"))); + EXPECT_EQ("", reflection->GetStringReference( + message, F("optional_string_piece"), &scratch)); + + EXPECT_EQ("", reflection->GetString(message, F("optional_cord"))); + EXPECT_EQ("", reflection->GetStringReference(message, F("optional_cord"), + &scratch)); + + // Repeated fields are empty. + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_float"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_double"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bool"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bytes"))); + + EXPECT_EQ(0, reflection->FieldSize(message, F("repeatedgroup"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_lazy_message"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_enum"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_enum"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_enum"))); + + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string_piece"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_cord"))); + + // has_blah() should also be false for all default fields. + EXPECT_FALSE(reflection->HasField(message, F("default_int32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_int64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_uint32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_uint64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sint32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sint64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_fixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_fixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sfixed32"))); + EXPECT_FALSE(reflection->HasField(message, F("default_sfixed64"))); + EXPECT_FALSE(reflection->HasField(message, F("default_float"))); + EXPECT_FALSE(reflection->HasField(message, F("default_double"))); + EXPECT_FALSE(reflection->HasField(message, F("default_bool"))); + EXPECT_FALSE(reflection->HasField(message, F("default_string"))); + EXPECT_FALSE(reflection->HasField(message, F("default_bytes"))); + + EXPECT_FALSE(reflection->HasField(message, F("default_nested_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("default_foreign_enum"))); + EXPECT_FALSE(reflection->HasField(message, F("default_import_enum"))); + + EXPECT_FALSE(reflection->HasField(message, F("default_string_piece"))); + EXPECT_FALSE(reflection->HasField(message, F("default_cord"))); + + // Fields with defaults have their default values (duh). + EXPECT_EQ(41, reflection->GetInt32(message, F("default_int32"))); + EXPECT_EQ(42, reflection->GetInt64(message, F("default_int64"))); + EXPECT_EQ(43, reflection->GetUInt32(message, F("default_uint32"))); + EXPECT_EQ(44, reflection->GetUInt64(message, F("default_uint64"))); + EXPECT_EQ(-45, reflection->GetInt32(message, F("default_sint32"))); + EXPECT_EQ(46, reflection->GetInt64(message, F("default_sint64"))); + EXPECT_EQ(47, reflection->GetUInt32(message, F("default_fixed32"))); + EXPECT_EQ(48, reflection->GetUInt64(message, F("default_fixed64"))); + EXPECT_EQ(49, reflection->GetInt32(message, F("default_sfixed32"))); + EXPECT_EQ(-50, reflection->GetInt64(message, F("default_sfixed64"))); + EXPECT_EQ(51.5, reflection->GetFloat(message, F("default_float"))); + EXPECT_EQ(52e3, reflection->GetDouble(message, F("default_double"))); + EXPECT_TRUE(reflection->GetBool(message, F("default_bool"))); + EXPECT_EQ("hello", reflection->GetString(message, F("default_string"))); + EXPECT_EQ("world", reflection->GetString(message, F("default_bytes"))); + + EXPECT_EQ("hello", reflection->GetStringReference( + message, F("default_string"), &scratch)); + EXPECT_EQ("world", reflection->GetStringReference(message, F("default_bytes"), + &scratch)); + + EXPECT_EQ(nested_bar_, + reflection->GetEnum(message, F("default_nested_enum"))); + EXPECT_EQ(foreign_bar_, + reflection->GetEnum(message, F("default_foreign_enum"))); + EXPECT_EQ(import_bar_, + reflection->GetEnum(message, F("default_import_enum"))); + + EXPECT_EQ("abc", reflection->GetString(message, F("default_string_piece"))); + EXPECT_EQ("abc", reflection->GetStringReference( + message, F("default_string_piece"), &scratch)); + + EXPECT_EQ("123", reflection->GetString(message, F("default_cord"))); + EXPECT_EQ("123", reflection->GetStringReference(message, F("default_cord"), + &scratch)); +} + +inline void TestUtil::ReflectionTester::ExpectPackedClearViaReflection( + const Message& message) { + const Reflection* reflection = message.GetReflection(); + + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed32"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed64"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_float"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_double"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_bool"))); + EXPECT_EQ(0, reflection->FieldSize(message, F("packed_enum"))); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ReflectionTester::ModifyRepeatedFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + Message* sub_message; + + reflection->SetRepeatedInt32(message, F("repeated_int32"), 1, 501); + reflection->SetRepeatedInt64(message, F("repeated_int64"), 1, 502); + reflection->SetRepeatedUInt32(message, F("repeated_uint32"), 1, 503); + reflection->SetRepeatedUInt64(message, F("repeated_uint64"), 1, 504); + reflection->SetRepeatedInt32(message, F("repeated_sint32"), 1, 505); + reflection->SetRepeatedInt64(message, F("repeated_sint64"), 1, 506); + reflection->SetRepeatedUInt32(message, F("repeated_fixed32"), 1, 507); + reflection->SetRepeatedUInt64(message, F("repeated_fixed64"), 1, 508); + reflection->SetRepeatedInt32(message, F("repeated_sfixed32"), 1, 509); + reflection->SetRepeatedInt64(message, F("repeated_sfixed64"), 1, 510); + reflection->SetRepeatedFloat(message, F("repeated_float"), 1, 511); + reflection->SetRepeatedDouble(message, F("repeated_double"), 1, 512); + reflection->SetRepeatedBool(message, F("repeated_bool"), 1, true); + reflection->SetRepeatedString(message, F("repeated_string"), 1, "515"); + reflection->SetRepeatedString(message, F("repeated_bytes"), 1, "516"); + + sub_message = + reflection->MutableRepeatedMessage(message, F("repeatedgroup"), 1); + sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 517); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_nested_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 518); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_foreign_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 519); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_import_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, import_d_, 520); + sub_message = reflection->MutableRepeatedMessage( + message, F("repeated_lazy_message"), 1); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 527); + + reflection->SetRepeatedEnum(message, F("repeated_nested_enum"), 1, + nested_foo_); + reflection->SetRepeatedEnum(message, F("repeated_foreign_enum"), 1, + foreign_foo_); + reflection->SetRepeatedEnum(message, F("repeated_import_enum"), 1, + import_foo_); + + reflection->SetRepeatedString(message, F("repeated_string_piece"), 1, "524"); + reflection->SetRepeatedString(message, F("repeated_cord"), 1, "525"); +} + +inline void TestUtil::ReflectionTester::ModifyPackedFieldsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + reflection->SetRepeatedInt32(message, F("packed_int32"), 1, 801); + reflection->SetRepeatedInt64(message, F("packed_int64"), 1, 802); + reflection->SetRepeatedUInt32(message, F("packed_uint32"), 1, 803); + reflection->SetRepeatedUInt64(message, F("packed_uint64"), 1, 804); + reflection->SetRepeatedInt32(message, F("packed_sint32"), 1, 805); + reflection->SetRepeatedInt64(message, F("packed_sint64"), 1, 806); + reflection->SetRepeatedUInt32(message, F("packed_fixed32"), 1, 807); + reflection->SetRepeatedUInt64(message, F("packed_fixed64"), 1, 808); + reflection->SetRepeatedInt32(message, F("packed_sfixed32"), 1, 809); + reflection->SetRepeatedInt64(message, F("packed_sfixed64"), 1, 810); + reflection->SetRepeatedFloat(message, F("packed_float"), 1, 811); + reflection->SetRepeatedDouble(message, F("packed_double"), 1, 812); + reflection->SetRepeatedBool(message, F("packed_bool"), 1, true); + reflection->SetRepeatedEnum(message, F("packed_enum"), 1, foreign_foo_); +} + +inline void TestUtil::ReflectionTester::RemoveLastRepeatedsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + + std::vector output; + reflection->ListFields(*message, &output); + for (int i = 0; i < output.size(); ++i) { + const FieldDescriptor* field = output[i]; + if (!field->is_repeated()) continue; + + reflection->RemoveLast(message, field); + } +} + +inline void TestUtil::ReflectionTester::ReleaseLastRepeatedsViaReflection( + Message* message, bool expect_extensions_notnull) { + const Reflection* reflection = message->GetReflection(); + + std::vector output; + reflection->ListFields(*message, &output); + for (int i = 0; i < output.size(); ++i) { + const FieldDescriptor* field = output[i]; + if (!field->is_repeated()) continue; + if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; + + Message* released = reflection->ReleaseLast(message, field); + if (!field->is_extension() || expect_extensions_notnull) { + ASSERT_TRUE(released != nullptr) + << "ReleaseLast returned nullptr for: " << field->name(); + } + delete released; + } +} + +inline void TestUtil::ReflectionTester::SwapRepeatedsViaReflection( + Message* message) { + const Reflection* reflection = message->GetReflection(); + + std::vector output; + reflection->ListFields(*message, &output); + for (int i = 0; i < output.size(); ++i) { + const FieldDescriptor* field = output[i]; + if (!field->is_repeated()) continue; + + reflection->SwapElements(message, field, 0, 1); + } +} + +inline void TestUtil::ReflectionTester:: + SetAllocatedOptionalMessageFieldsToNullViaReflection(Message* message) { + const Reflection* reflection = message->GetReflection(); + + std::vector fields; + reflection->ListFields(*message, &fields); + + for (int i = 0; i < fields.size(); ++i) { + const FieldDescriptor* field = fields[i]; + if (!field->is_optional() || + field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) + continue; + + reflection->SetAllocatedMessage(message, nullptr, field); + } +} + +inline void TestUtil::ReflectionTester:: + SetAllocatedOptionalMessageFieldsToMessageViaReflection( + Message* from_message, Message* to_message) { + EXPECT_EQ(from_message->GetDescriptor(), to_message->GetDescriptor()); + const Reflection* from_reflection = from_message->GetReflection(); + const Reflection* to_reflection = to_message->GetReflection(); + + std::vector fields; + from_reflection->ListFields(*from_message, &fields); + + for (int i = 0; i < fields.size(); ++i) { + const FieldDescriptor* field = fields[i]; + if (!field->is_optional() || + field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) + continue; + + Message* sub_message = from_reflection->ReleaseMessage(from_message, field); + to_reflection->SetAllocatedMessage(to_message, sub_message, field); + } +} + +inline void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection( + Message* message, + TestUtil::ReflectionTester::MessageReleaseState expected_release_state) { + const Reflection* reflection = message->GetReflection(); + + static const char* fields[] = { + "optionalgroup", + "optional_nested_message", + "optional_foreign_message", + "optional_import_message", + }; + for (int i = 0; i < GOOGLE_ARRAYSIZE(fields); i++) { + const Message& sub_message = reflection->GetMessage(*message, F(fields[i])); + Message* released = reflection->ReleaseMessage(message, F(fields[i])); + switch (expected_release_state) { + case IS_NULL: + EXPECT_TRUE(released == nullptr); + break; + case NOT_NULL: + EXPECT_TRUE(released != nullptr); + if (message->GetArena() == nullptr) { + // released message must be same as sub_message if source message is + // not on arena. + EXPECT_EQ(&sub_message, released); + } + break; + case CAN_BE_NULL: + break; + } + delete released; + EXPECT_FALSE(reflection->HasField(*message, F(fields[i]))); + } +} + +// Check that the passed-in serialization is the canonical serialization we +// expect for a TestFieldOrderings message filled in by +// SetAllFieldsAndExtensions(). +inline void ExpectAllFieldsAndExtensionsInOrder( + const string& serialized) { + // We set each field individually, serialize separately, and concatenate all + // the strings in canonical order to determine the expected serialization. + string expected; + unittest::TestFieldOrderings message; + message.set_my_int(1); // Field 1. + message.AppendToString(&expected); + message.Clear(); + message.SetExtension(unittest::my_extension_int, 23); // Field 5. + message.AppendToString(&expected); + message.Clear(); + message.set_my_string("foo"); // Field 11. + message.AppendToString(&expected); + message.Clear(); + message.SetExtension(unittest::my_extension_string, "bar"); // Field 50. + message.AppendToString(&expected); + message.Clear(); + message.set_my_float(1.0); // Field 101. + message.AppendToString(&expected); + message.Clear(); + + // We don't EXPECT_EQ() since we don't want to print raw bytes to stdout. + EXPECT_TRUE(serialized == expected); +} + +} // namespace TestUtil } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/test_util.inc b/src/google/protobuf/test_util.inc new file mode 100644 index 0000000000..185f68d901 --- /dev/null +++ b/src/google/protobuf/test_util.inc @@ -0,0 +1,2600 @@ +// 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) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// This file needs to be included as .inc as it depends on the namespaces +// (unittest and unittest_import) being set up properly. It is also included +// within an enclosing namespace and requires header files to be included +// out of this file. + +#include +#include +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace TestUtil { + +// Set every field in the message to a unique value. +inline void SetAllFields(UNITTEST::TestAllTypes* message); +inline void SetOptionalFields(UNITTEST::TestAllTypes* message); +inline void AddRepeatedFields1(UNITTEST::TestAllTypes* message); +inline void AddRepeatedFields2(UNITTEST::TestAllTypes* message); +inline void SetDefaultFields(UNITTEST::TestAllTypes* message); +inline void SetOneofFields(UNITTEST::TestAllTypes* message); +inline void SetAllExtensions(UNITTEST::TestAllExtensions* message); +inline void SetOneofFields(UNITTEST::TestAllExtensions* message); +inline void SetAllFieldsAndExtensions(UNITTEST::TestFieldOrderings* message); +inline void SetPackedFields(UNITTEST::TestPackedTypes* message); +inline void SetPackedExtensions(UNITTEST::TestPackedExtensions* message); +inline void SetUnpackedFields(UNITTEST::TestUnpackedTypes* message); +inline void SetOneof1(UNITTEST::TestOneof2* message); +inline void SetOneof2(UNITTEST::TestOneof2* message); + +// Use the repeated versions of the set_*() accessors to modify all the +// repeated fields of the message (which should already have been +// initialized with Set*Fields()). Set*Fields() itself only tests +// the add_*() accessors. +inline void ModifyRepeatedFields(UNITTEST::TestAllTypes* message); +inline void ModifyRepeatedExtensions(UNITTEST::TestAllExtensions* message); +inline void ModifyPackedFields(UNITTEST::TestPackedTypes* message); +inline void ModifyPackedExtensions(UNITTEST::TestPackedExtensions* message); + +// Check that all fields have the values that they should have after +// Set*Fields() is called. +inline void ExpectAllFieldsSet(const UNITTEST::TestAllTypes& message); +inline void ExpectAllExtensionsSet(const UNITTEST::TestAllExtensions& message); +inline void ExpectPackedFieldsSet(const UNITTEST::TestPackedTypes& message); +inline void ExpectPackedExtensionsSet( + const UNITTEST::TestPackedExtensions& message); +inline void ExpectUnpackedFieldsSet(const UNITTEST::TestUnpackedTypes& message); +inline void ExpectUnpackedExtensionsSet( + const UNITTEST::TestUnpackedExtensions& message); +inline void ExpectOneofSet1(const UNITTEST::TestOneof2& message); +inline void ExpectOneofSet2(const UNITTEST::TestOneof2& message); + +// Expect that the message is modified as would be expected from +// Modify*Fields(). +inline void ExpectRepeatedFieldsModified(const UNITTEST::TestAllTypes& message); +inline void ExpectRepeatedExtensionsModified( + const UNITTEST::TestAllExtensions& message); +inline void ExpectPackedFieldsModified( + const UNITTEST::TestPackedTypes& message); +inline void ExpectPackedExtensionsModified( + const UNITTEST::TestPackedExtensions& message); + +// Check that all fields have their default values. +inline void ExpectClear(const UNITTEST::TestAllTypes& message); +inline void ExpectExtensionsClear(const UNITTEST::TestAllExtensions& message); +inline void ExpectPackedClear(const UNITTEST::TestPackedTypes& message); +inline void ExpectPackedExtensionsClear( + const UNITTEST::TestPackedExtensions& message); +inline void ExpectOneofClear(const UNITTEST::TestOneof2& message); + +// Check that all repeated fields have had their last elements removed. +inline void ExpectLastRepeatedsRemoved(const UNITTEST::TestAllTypes& message); +inline void ExpectLastRepeatedExtensionsRemoved( + const UNITTEST::TestAllExtensions& message); +inline void ExpectLastRepeatedsReleased(const UNITTEST::TestAllTypes& message); +inline void ExpectLastRepeatedExtensionsReleased( + const UNITTEST::TestAllExtensions& message); + +// Check that all repeated fields have had their first and last elements +// swapped. +inline void ExpectRepeatedsSwapped(const UNITTEST::TestAllTypes& message); +inline void ExpectRepeatedExtensionsSwapped( + const UNITTEST::TestAllExtensions& message); + +inline void ExpectAtMostOneFieldSetInOneof(const UNITTEST::TestOneof2& message); + +} // namespace TestUtil + +inline void TestUtil::SetAllFields(UNITTEST::TestAllTypes* message) { + SetOptionalFields(message); + AddRepeatedFields1(message); + AddRepeatedFields2(message); + SetDefaultFields(message); + SetOneofFields(message); +} + +inline void TestUtil::SetOptionalFields(UNITTEST::TestAllTypes* message) { + message->set_optional_int32(101); + message->set_optional_int64(102); + message->set_optional_uint32(103); + message->set_optional_uint64(104); + message->set_optional_sint32(105); + message->set_optional_sint64(106); + message->set_optional_fixed32(107); + message->set_optional_fixed64(108); + message->set_optional_sfixed32(109); + message->set_optional_sfixed64(110); + message->set_optional_float(111); + message->set_optional_double(112); + message->set_optional_bool(true); + message->set_optional_string("115"); + message->set_optional_bytes("116"); + + message->mutable_optionalgroup()->set_a(117); + message->mutable_optional_nested_message()->set_bb(118); + message->mutable_optional_foreign_message()->set_c(119); + message->mutable_optional_import_message()->set_d(120); + message->mutable_optional_public_import_message()->set_e(126); + message->mutable_optional_lazy_message()->set_bb(127); + + message->set_optional_nested_enum(UNITTEST::TestAllTypes::BAZ); + message->set_optional_foreign_enum(UNITTEST::FOREIGN_BAZ); + message->set_optional_import_enum(UNITTEST_IMPORT::IMPORT_BAZ); + + // StringPiece and Cord fields are only accessible via reflection in the + // open source release; see comments in compiler/cpp/string_field.cc. +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->SetString( + message, + message->GetDescriptor()->FindFieldByName("optional_string_piece"), + "124"); + message->GetReflection()->SetString( + message, message->GetDescriptor()->FindFieldByName("optional_cord"), + "125"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------- + +inline void TestUtil::AddRepeatedFields1(UNITTEST::TestAllTypes* message) { + message->add_repeated_int32(201); + message->add_repeated_int64(202); + message->add_repeated_uint32(203); + message->add_repeated_uint64(204); + message->add_repeated_sint32(205); + message->add_repeated_sint64(206); + message->add_repeated_fixed32(207); + message->add_repeated_fixed64(208); + message->add_repeated_sfixed32(209); + message->add_repeated_sfixed64(210); + message->add_repeated_float(211); + message->add_repeated_double(212); + message->add_repeated_bool(true); + message->add_repeated_string("215"); + message->add_repeated_bytes("216"); + + message->add_repeatedgroup()->set_a(217); + message->add_repeated_nested_message()->set_bb(218); + message->add_repeated_foreign_message()->set_c(219); + message->add_repeated_import_message()->set_d(220); + message->add_repeated_lazy_message()->set_bb(227); + + message->add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR); + message->add_repeated_foreign_enum(UNITTEST::FOREIGN_BAR); + message->add_repeated_import_enum(UNITTEST_IMPORT::IMPORT_BAR); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->AddString( + message, + message->GetDescriptor()->FindFieldByName("repeated_string_piece"), + "224"); + message->GetReflection()->AddString( + message, message->GetDescriptor()->FindFieldByName("repeated_cord"), + "225"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +inline void TestUtil::AddRepeatedFields2(UNITTEST::TestAllTypes* message) { + // Add a second one of each field. + message->add_repeated_int32(301); + message->add_repeated_int64(302); + message->add_repeated_uint32(303); + message->add_repeated_uint64(304); + message->add_repeated_sint32(305); + message->add_repeated_sint64(306); + message->add_repeated_fixed32(307); + message->add_repeated_fixed64(308); + message->add_repeated_sfixed32(309); + message->add_repeated_sfixed64(310); + message->add_repeated_float(311); + message->add_repeated_double(312); + message->add_repeated_bool(false); + message->add_repeated_string("315"); + message->add_repeated_bytes("316"); + + message->add_repeatedgroup()->set_a(317); + message->add_repeated_nested_message()->set_bb(318); + message->add_repeated_foreign_message()->set_c(319); + message->add_repeated_import_message()->set_d(320); + message->add_repeated_lazy_message()->set_bb(327); + + message->add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ); + message->add_repeated_foreign_enum(UNITTEST::FOREIGN_BAZ); + message->add_repeated_import_enum(UNITTEST_IMPORT::IMPORT_BAZ); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->AddString( + message, + message->GetDescriptor()->FindFieldByName("repeated_string_piece"), + "324"); + message->GetReflection()->AddString( + message, message->GetDescriptor()->FindFieldByName("repeated_cord"), + "325"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetDefaultFields(UNITTEST::TestAllTypes* message) { + message->set_default_int32(401); + message->set_default_int64(402); + message->set_default_uint32(403); + message->set_default_uint64(404); + message->set_default_sint32(405); + message->set_default_sint64(406); + message->set_default_fixed32(407); + message->set_default_fixed64(408); + message->set_default_sfixed32(409); + message->set_default_sfixed64(410); + message->set_default_float(411); + message->set_default_double(412); + message->set_default_bool(false); + message->set_default_string("415"); + message->set_default_bytes("416"); + + message->set_default_nested_enum(UNITTEST::TestAllTypes::FOO); + message->set_default_foreign_enum(UNITTEST::FOREIGN_FOO); + message->set_default_import_enum(UNITTEST_IMPORT::IMPORT_FOO); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->SetString( + message, + message->GetDescriptor()->FindFieldByName("default_string_piece"), "424"); + message->GetReflection()->SetString( + message, message->GetDescriptor()->FindFieldByName("default_cord"), + "425"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyRepeatedFields(UNITTEST::TestAllTypes* message) { + message->set_repeated_int32(1, 501); + message->set_repeated_int64(1, 502); + message->set_repeated_uint32(1, 503); + message->set_repeated_uint64(1, 504); + message->set_repeated_sint32(1, 505); + message->set_repeated_sint64(1, 506); + message->set_repeated_fixed32(1, 507); + message->set_repeated_fixed64(1, 508); + message->set_repeated_sfixed32(1, 509); + message->set_repeated_sfixed64(1, 510); + message->set_repeated_float(1, 511); + message->set_repeated_double(1, 512); + message->set_repeated_bool(1, true); + message->set_repeated_string(1, "515"); + message->set_repeated_bytes(1, "516"); + + message->mutable_repeatedgroup(1)->set_a(517); + message->mutable_repeated_nested_message(1)->set_bb(518); + message->mutable_repeated_foreign_message(1)->set_c(519); + message->mutable_repeated_import_message(1)->set_d(520); + message->mutable_repeated_lazy_message(1)->set_bb(527); + + message->set_repeated_nested_enum(1, UNITTEST::TestAllTypes::FOO); + message->set_repeated_foreign_enum(1, UNITTEST::FOREIGN_FOO); + message->set_repeated_import_enum(1, UNITTEST_IMPORT::IMPORT_FOO); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + message->GetReflection()->SetRepeatedString( + message, + message->GetDescriptor()->FindFieldByName("repeated_string_piece"), 1, + "524"); + message->GetReflection()->SetRepeatedString( + message, message->GetDescriptor()->FindFieldByName("repeated_cord"), 1, + "525"); +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS +} + +// ------------------------------------------------------------------ +inline void TestUtil::SetOneofFields(UNITTEST::TestAllTypes* message) { + message->set_oneof_uint32(601); + message->mutable_oneof_nested_message()->set_bb(602); + message->set_oneof_string("603"); + message->set_oneof_bytes("604"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectAllFieldsSet( + const UNITTEST::TestAllTypes& message) { + EXPECT_TRUE(message.has_optional_int32()); + EXPECT_TRUE(message.has_optional_int64()); + EXPECT_TRUE(message.has_optional_uint32()); + EXPECT_TRUE(message.has_optional_uint64()); + EXPECT_TRUE(message.has_optional_sint32()); + EXPECT_TRUE(message.has_optional_sint64()); + EXPECT_TRUE(message.has_optional_fixed32()); + EXPECT_TRUE(message.has_optional_fixed64()); + EXPECT_TRUE(message.has_optional_sfixed32()); + EXPECT_TRUE(message.has_optional_sfixed64()); + EXPECT_TRUE(message.has_optional_float()); + EXPECT_TRUE(message.has_optional_double()); + EXPECT_TRUE(message.has_optional_bool()); + EXPECT_TRUE(message.has_optional_string()); + EXPECT_TRUE(message.has_optional_bytes()); + + EXPECT_TRUE(message.has_optionalgroup()); + EXPECT_TRUE(message.has_optional_nested_message()); + EXPECT_TRUE(message.has_optional_foreign_message()); + EXPECT_TRUE(message.has_optional_import_message()); + EXPECT_TRUE(message.has_optional_public_import_message()); + EXPECT_TRUE(message.has_optional_lazy_message()); + + EXPECT_TRUE(message.optionalgroup().has_a()); + EXPECT_TRUE(message.optional_nested_message().has_bb()); + EXPECT_TRUE(message.optional_foreign_message().has_c()); + EXPECT_TRUE(message.optional_import_message().has_d()); + EXPECT_TRUE(message.optional_public_import_message().has_e()); + EXPECT_TRUE(message.optional_lazy_message().has_bb()); + + EXPECT_TRUE(message.has_optional_nested_enum()); + EXPECT_TRUE(message.has_optional_foreign_enum()); + EXPECT_TRUE(message.has_optional_import_enum()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + EXPECT_TRUE(message.has_optional_string_piece()); + EXPECT_TRUE(message.has_optional_cord()); +#endif + + EXPECT_EQ(101, message.optional_int32()); + EXPECT_EQ(102, message.optional_int64()); + EXPECT_EQ(103, message.optional_uint32()); + EXPECT_EQ(104, message.optional_uint64()); + EXPECT_EQ(105, message.optional_sint32()); + EXPECT_EQ(106, message.optional_sint64()); + EXPECT_EQ(107, message.optional_fixed32()); + EXPECT_EQ(108, message.optional_fixed64()); + EXPECT_EQ(109, message.optional_sfixed32()); + EXPECT_EQ(110, message.optional_sfixed64()); + EXPECT_EQ(111, message.optional_float()); + EXPECT_EQ(112, message.optional_double()); + EXPECT_TRUE(message.optional_bool()); + EXPECT_EQ("115", message.optional_string()); + EXPECT_EQ("116", message.optional_bytes()); + + EXPECT_EQ(117, message.optionalgroup().a()); + EXPECT_EQ(118, message.optional_nested_message().bb()); + EXPECT_EQ(119, message.optional_foreign_message().c()); + EXPECT_EQ(120, message.optional_import_message().d()); + EXPECT_EQ(126, message.optional_public_import_message().e()); + EXPECT_EQ(127, message.optional_lazy_message().bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.optional_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.optional_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.optional_import_enum()); + + + // ----------------------------------------------------------------- + + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); + ASSERT_EQ(2, message.repeated_sfixed32_size()); + ASSERT_EQ(2, message.repeated_sfixed64_size()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); + + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); + ASSERT_EQ(2, message.repeated_foreign_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_lazy_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(2, message.repeated_string_piece_size()); + ASSERT_EQ(2, message.repeated_cord_size()); +#endif + + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_TRUE(message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(227, message.repeated_lazy_message(0).bb()); + + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0)); + + EXPECT_EQ(301, message.repeated_int32(1)); + EXPECT_EQ(302, message.repeated_int64(1)); + EXPECT_EQ(303, message.repeated_uint32(1)); + EXPECT_EQ(304, message.repeated_uint64(1)); + EXPECT_EQ(305, message.repeated_sint32(1)); + EXPECT_EQ(306, message.repeated_sint64(1)); + EXPECT_EQ(307, message.repeated_fixed32(1)); + EXPECT_EQ(308, message.repeated_fixed64(1)); + EXPECT_EQ(309, message.repeated_sfixed32(1)); + EXPECT_EQ(310, message.repeated_sfixed64(1)); + EXPECT_EQ(311, message.repeated_float(1)); + EXPECT_EQ(312, message.repeated_double(1)); + EXPECT_FALSE(message.repeated_bool(1)); + EXPECT_EQ("315", message.repeated_string(1)); + EXPECT_EQ("316", message.repeated_bytes(1)); + + EXPECT_EQ(317, message.repeatedgroup(1).a()); + EXPECT_EQ(318, message.repeated_nested_message(1).bb()); + EXPECT_EQ(319, message.repeated_foreign_message(1).c()); + EXPECT_EQ(320, message.repeated_import_message(1).d()); + EXPECT_EQ(327, message.repeated_lazy_message(1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.repeated_nested_enum(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.repeated_foreign_enum(1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.repeated_import_enum(1)); + + + // ----------------------------------------------------------------- + + EXPECT_TRUE(message.has_default_int32()); + EXPECT_TRUE(message.has_default_int64()); + EXPECT_TRUE(message.has_default_uint32()); + EXPECT_TRUE(message.has_default_uint64()); + EXPECT_TRUE(message.has_default_sint32()); + EXPECT_TRUE(message.has_default_sint64()); + EXPECT_TRUE(message.has_default_fixed32()); + EXPECT_TRUE(message.has_default_fixed64()); + EXPECT_TRUE(message.has_default_sfixed32()); + EXPECT_TRUE(message.has_default_sfixed64()); + EXPECT_TRUE(message.has_default_float()); + EXPECT_TRUE(message.has_default_double()); + EXPECT_TRUE(message.has_default_bool()); + EXPECT_TRUE(message.has_default_string()); + EXPECT_TRUE(message.has_default_bytes()); + + EXPECT_TRUE(message.has_default_nested_enum()); + EXPECT_TRUE(message.has_default_foreign_enum()); + EXPECT_TRUE(message.has_default_import_enum()); + + + EXPECT_EQ(401, message.default_int32()); + EXPECT_EQ(402, message.default_int64()); + EXPECT_EQ(403, message.default_uint32()); + EXPECT_EQ(404, message.default_uint64()); + EXPECT_EQ(405, message.default_sint32()); + EXPECT_EQ(406, message.default_sint64()); + EXPECT_EQ(407, message.default_fixed32()); + EXPECT_EQ(408, message.default_fixed64()); + EXPECT_EQ(409, message.default_sfixed32()); + EXPECT_EQ(410, message.default_sfixed64()); + EXPECT_EQ(411, message.default_float()); + EXPECT_EQ(412, message.default_double()); + EXPECT_FALSE(message.default_bool()); + EXPECT_EQ("415", message.default_string()); + EXPECT_EQ("416", message.default_bytes()); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.default_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.default_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.default_import_enum()); + + + EXPECT_FALSE(message.has_oneof_uint32()); + EXPECT_FALSE(message.has_oneof_nested_message()); + EXPECT_FALSE(message.has_oneof_string()); + EXPECT_TRUE(message.has_oneof_bytes()); + + EXPECT_EQ("604", message.oneof_bytes()); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectClear(const UNITTEST::TestAllTypes& message) { + // has_blah() should initially be false for all optional fields. + EXPECT_FALSE(message.has_optional_int32()); + EXPECT_FALSE(message.has_optional_int64()); + EXPECT_FALSE(message.has_optional_uint32()); + EXPECT_FALSE(message.has_optional_uint64()); + EXPECT_FALSE(message.has_optional_sint32()); + EXPECT_FALSE(message.has_optional_sint64()); + EXPECT_FALSE(message.has_optional_fixed32()); + EXPECT_FALSE(message.has_optional_fixed64()); + EXPECT_FALSE(message.has_optional_sfixed32()); + EXPECT_FALSE(message.has_optional_sfixed64()); + EXPECT_FALSE(message.has_optional_float()); + EXPECT_FALSE(message.has_optional_double()); + EXPECT_FALSE(message.has_optional_bool()); + EXPECT_FALSE(message.has_optional_string()); + EXPECT_FALSE(message.has_optional_bytes()); + + EXPECT_FALSE(message.has_optionalgroup()); + EXPECT_FALSE(message.has_optional_nested_message()); + EXPECT_FALSE(message.has_optional_foreign_message()); + EXPECT_FALSE(message.has_optional_import_message()); + EXPECT_FALSE(message.has_optional_public_import_message()); + EXPECT_FALSE(message.has_optional_lazy_message()); + + EXPECT_FALSE(message.has_optional_nested_enum()); + EXPECT_FALSE(message.has_optional_foreign_enum()); + EXPECT_FALSE(message.has_optional_import_enum()); + + EXPECT_FALSE(message.has_optional_string_piece()); + EXPECT_FALSE(message.has_optional_cord()); + + // Optional fields without defaults are set to zero or something like it. + EXPECT_EQ(0, message.optional_int32()); + EXPECT_EQ(0, message.optional_int64()); + EXPECT_EQ(0, message.optional_uint32()); + EXPECT_EQ(0, message.optional_uint64()); + EXPECT_EQ(0, message.optional_sint32()); + EXPECT_EQ(0, message.optional_sint64()); + EXPECT_EQ(0, message.optional_fixed32()); + EXPECT_EQ(0, message.optional_fixed64()); + EXPECT_EQ(0, message.optional_sfixed32()); + EXPECT_EQ(0, message.optional_sfixed64()); + EXPECT_EQ(0, message.optional_float()); + EXPECT_EQ(0, message.optional_double()); + EXPECT_FALSE(message.optional_bool()); + EXPECT_EQ("", message.optional_string()); + EXPECT_EQ("", message.optional_bytes()); + + // Embedded messages should also be clear. + EXPECT_FALSE(message.optionalgroup().has_a()); + EXPECT_FALSE(message.optional_nested_message().has_bb()); + EXPECT_FALSE(message.optional_foreign_message().has_c()); + EXPECT_FALSE(message.optional_import_message().has_d()); + EXPECT_FALSE(message.optional_public_import_message().has_e()); + EXPECT_FALSE(message.optional_lazy_message().has_bb()); + + EXPECT_EQ(0, message.optionalgroup().a()); + EXPECT_EQ(0, message.optional_nested_message().bb()); + EXPECT_EQ(0, message.optional_foreign_message().c()); + EXPECT_EQ(0, message.optional_import_message().d()); + EXPECT_EQ(0, message.optional_public_import_message().e()); + EXPECT_EQ(0, message.optional_lazy_message().bb()); + + // Enums without defaults are set to the first value in the enum. + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.optional_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.optional_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.optional_import_enum()); + + + // Repeated fields are empty. + EXPECT_EQ(0, message.repeated_int32_size()); + EXPECT_EQ(0, message.repeated_int64_size()); + EXPECT_EQ(0, message.repeated_uint32_size()); + EXPECT_EQ(0, message.repeated_uint64_size()); + EXPECT_EQ(0, message.repeated_sint32_size()); + EXPECT_EQ(0, message.repeated_sint64_size()); + EXPECT_EQ(0, message.repeated_fixed32_size()); + EXPECT_EQ(0, message.repeated_fixed64_size()); + EXPECT_EQ(0, message.repeated_sfixed32_size()); + EXPECT_EQ(0, message.repeated_sfixed64_size()); + EXPECT_EQ(0, message.repeated_float_size()); + EXPECT_EQ(0, message.repeated_double_size()); + EXPECT_EQ(0, message.repeated_bool_size()); + EXPECT_EQ(0, message.repeated_string_size()); + EXPECT_EQ(0, message.repeated_bytes_size()); + + EXPECT_EQ(0, message.repeatedgroup_size()); + EXPECT_EQ(0, message.repeated_nested_message_size()); + EXPECT_EQ(0, message.repeated_foreign_message_size()); + EXPECT_EQ(0, message.repeated_import_message_size()); + EXPECT_EQ(0, message.repeated_lazy_message_size()); + EXPECT_EQ(0, message.repeated_nested_enum_size()); + EXPECT_EQ(0, message.repeated_foreign_enum_size()); + EXPECT_EQ(0, message.repeated_import_enum_size()); + + EXPECT_EQ(0, message.repeated_string_piece_size()); + EXPECT_EQ(0, message.repeated_cord_size()); + + // has_blah() should also be false for all default fields. + EXPECT_FALSE(message.has_default_int32()); + EXPECT_FALSE(message.has_default_int64()); + EXPECT_FALSE(message.has_default_uint32()); + EXPECT_FALSE(message.has_default_uint64()); + EXPECT_FALSE(message.has_default_sint32()); + EXPECT_FALSE(message.has_default_sint64()); + EXPECT_FALSE(message.has_default_fixed32()); + EXPECT_FALSE(message.has_default_fixed64()); + EXPECT_FALSE(message.has_default_sfixed32()); + EXPECT_FALSE(message.has_default_sfixed64()); + EXPECT_FALSE(message.has_default_float()); + EXPECT_FALSE(message.has_default_double()); + EXPECT_FALSE(message.has_default_bool()); + EXPECT_FALSE(message.has_default_string()); + EXPECT_FALSE(message.has_default_bytes()); + + EXPECT_FALSE(message.has_default_nested_enum()); + EXPECT_FALSE(message.has_default_foreign_enum()); + EXPECT_FALSE(message.has_default_import_enum()); + + + // Fields with defaults have their default values (duh). + EXPECT_EQ(41, message.default_int32()); + EXPECT_EQ(42, message.default_int64()); + EXPECT_EQ(43, message.default_uint32()); + EXPECT_EQ(44, message.default_uint64()); + EXPECT_EQ(-45, message.default_sint32()); + EXPECT_EQ(46, message.default_sint64()); + EXPECT_EQ(47, message.default_fixed32()); + EXPECT_EQ(48, message.default_fixed64()); + EXPECT_EQ(49, message.default_sfixed32()); + EXPECT_EQ(-50, message.default_sfixed64()); + EXPECT_EQ(51.5, message.default_float()); + EXPECT_EQ(52e3, message.default_double()); + EXPECT_TRUE(message.default_bool()); + EXPECT_EQ("hello", message.default_string()); + EXPECT_EQ("world", message.default_bytes()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.default_nested_enum()); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.default_foreign_enum()); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.default_import_enum()); + + + EXPECT_FALSE(message.has_oneof_uint32()); + EXPECT_FALSE(message.has_oneof_nested_message()); + EXPECT_FALSE(message.has_oneof_string()); + EXPECT_FALSE(message.has_oneof_bytes()); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectRepeatedFieldsModified( + const UNITTEST::TestAllTypes& message) { + // ModifyRepeatedFields only sets the second repeated element of each + // field. In addition to verifying this, we also verify that the first + // element and size were *not* modified. + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); + ASSERT_EQ(2, message.repeated_sfixed32_size()); + ASSERT_EQ(2, message.repeated_sfixed64_size()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); + + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); + ASSERT_EQ(2, message.repeated_foreign_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_lazy_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(2, message.repeated_string_piece_size()); + ASSERT_EQ(2, message.repeated_cord_size()); +#endif + + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_TRUE(message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(227, message.repeated_lazy_message(0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0)); + + + // Actually verify the second (modified) elements now. + EXPECT_EQ(501, message.repeated_int32(1)); + EXPECT_EQ(502, message.repeated_int64(1)); + EXPECT_EQ(503, message.repeated_uint32(1)); + EXPECT_EQ(504, message.repeated_uint64(1)); + EXPECT_EQ(505, message.repeated_sint32(1)); + EXPECT_EQ(506, message.repeated_sint64(1)); + EXPECT_EQ(507, message.repeated_fixed32(1)); + EXPECT_EQ(508, message.repeated_fixed64(1)); + EXPECT_EQ(509, message.repeated_sfixed32(1)); + EXPECT_EQ(510, message.repeated_sfixed64(1)); + EXPECT_EQ(511, message.repeated_float(1)); + EXPECT_EQ(512, message.repeated_double(1)); + EXPECT_TRUE(message.repeated_bool(1)); + EXPECT_EQ("515", message.repeated_string(1)); + EXPECT_EQ("516", message.repeated_bytes(1)); + + EXPECT_EQ(517, message.repeatedgroup(1).a()); + EXPECT_EQ(518, message.repeated_nested_message(1).bb()); + EXPECT_EQ(519, message.repeated_foreign_message(1).c()); + EXPECT_EQ(520, message.repeated_import_message(1).d()); + EXPECT_EQ(527, message.repeated_lazy_message(1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.repeated_nested_enum(1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.repeated_foreign_enum(1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, message.repeated_import_enum(1)); + +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetPackedFields(UNITTEST::TestPackedTypes* message) { + message->add_packed_int32(601); + message->add_packed_int64(602); + message->add_packed_uint32(603); + message->add_packed_uint64(604); + message->add_packed_sint32(605); + message->add_packed_sint64(606); + message->add_packed_fixed32(607); + message->add_packed_fixed64(608); + message->add_packed_sfixed32(609); + message->add_packed_sfixed64(610); + message->add_packed_float(611); + message->add_packed_double(612); + message->add_packed_bool(true); + message->add_packed_enum(UNITTEST::FOREIGN_BAR); + // add a second one of each field + message->add_packed_int32(701); + message->add_packed_int64(702); + message->add_packed_uint32(703); + message->add_packed_uint64(704); + message->add_packed_sint32(705); + message->add_packed_sint64(706); + message->add_packed_fixed32(707); + message->add_packed_fixed64(708); + message->add_packed_sfixed32(709); + message->add_packed_sfixed64(710); + message->add_packed_float(711); + message->add_packed_double(712); + message->add_packed_bool(false); + message->add_packed_enum(UNITTEST::FOREIGN_BAZ); +} + +inline void TestUtil::SetUnpackedFields(UNITTEST::TestUnpackedTypes* message) { + // The values applied here must match those of SetPackedFields. + + message->add_unpacked_int32(601); + message->add_unpacked_int64(602); + message->add_unpacked_uint32(603); + message->add_unpacked_uint64(604); + message->add_unpacked_sint32(605); + message->add_unpacked_sint64(606); + message->add_unpacked_fixed32(607); + message->add_unpacked_fixed64(608); + message->add_unpacked_sfixed32(609); + message->add_unpacked_sfixed64(610); + message->add_unpacked_float(611); + message->add_unpacked_double(612); + message->add_unpacked_bool(true); + message->add_unpacked_enum(UNITTEST::FOREIGN_BAR); + // add a second one of each field + message->add_unpacked_int32(701); + message->add_unpacked_int64(702); + message->add_unpacked_uint32(703); + message->add_unpacked_uint64(704); + message->add_unpacked_sint32(705); + message->add_unpacked_sint64(706); + message->add_unpacked_fixed32(707); + message->add_unpacked_fixed64(708); + message->add_unpacked_sfixed32(709); + message->add_unpacked_sfixed64(710); + message->add_unpacked_float(711); + message->add_unpacked_double(712); + message->add_unpacked_bool(false); + message->add_unpacked_enum(UNITTEST::FOREIGN_BAZ); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyPackedFields(UNITTEST::TestPackedTypes* message) { + message->set_packed_int32(1, 801); + message->set_packed_int64(1, 802); + message->set_packed_uint32(1, 803); + message->set_packed_uint64(1, 804); + message->set_packed_sint32(1, 805); + message->set_packed_sint64(1, 806); + message->set_packed_fixed32(1, 807); + message->set_packed_fixed64(1, 808); + message->set_packed_sfixed32(1, 809); + message->set_packed_sfixed64(1, 810); + message->set_packed_float(1, 811); + message->set_packed_double(1, 812); + message->set_packed_bool(1, true); + message->set_packed_enum(1, UNITTEST::FOREIGN_FOO); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedFieldsSet( + const UNITTEST::TestPackedTypes& message) { + ASSERT_EQ(2, message.packed_int32_size()); + ASSERT_EQ(2, message.packed_int64_size()); + ASSERT_EQ(2, message.packed_uint32_size()); + ASSERT_EQ(2, message.packed_uint64_size()); + ASSERT_EQ(2, message.packed_sint32_size()); + ASSERT_EQ(2, message.packed_sint64_size()); + ASSERT_EQ(2, message.packed_fixed32_size()); + ASSERT_EQ(2, message.packed_fixed64_size()); + ASSERT_EQ(2, message.packed_sfixed32_size()); + ASSERT_EQ(2, message.packed_sfixed64_size()); + ASSERT_EQ(2, message.packed_float_size()); + ASSERT_EQ(2, message.packed_double_size()); + ASSERT_EQ(2, message.packed_bool_size()); + ASSERT_EQ(2, message.packed_enum_size()); + + EXPECT_EQ(601, message.packed_int32(0)); + EXPECT_EQ(602, message.packed_int64(0)); + EXPECT_EQ(603, message.packed_uint32(0)); + EXPECT_EQ(604, message.packed_uint64(0)); + EXPECT_EQ(605, message.packed_sint32(0)); + EXPECT_EQ(606, message.packed_sint64(0)); + EXPECT_EQ(607, message.packed_fixed32(0)); + EXPECT_EQ(608, message.packed_fixed64(0)); + EXPECT_EQ(609, message.packed_sfixed32(0)); + EXPECT_EQ(610, message.packed_sfixed64(0)); + EXPECT_EQ(611, message.packed_float(0)); + EXPECT_EQ(612, message.packed_double(0)); + EXPECT_TRUE(message.packed_bool(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.packed_enum(0)); + + EXPECT_EQ(701, message.packed_int32(1)); + EXPECT_EQ(702, message.packed_int64(1)); + EXPECT_EQ(703, message.packed_uint32(1)); + EXPECT_EQ(704, message.packed_uint64(1)); + EXPECT_EQ(705, message.packed_sint32(1)); + EXPECT_EQ(706, message.packed_sint64(1)); + EXPECT_EQ(707, message.packed_fixed32(1)); + EXPECT_EQ(708, message.packed_fixed64(1)); + EXPECT_EQ(709, message.packed_sfixed32(1)); + EXPECT_EQ(710, message.packed_sfixed64(1)); + EXPECT_EQ(711, message.packed_float(1)); + EXPECT_EQ(712, message.packed_double(1)); + EXPECT_FALSE(message.packed_bool(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.packed_enum(1)); +} + +inline void TestUtil::ExpectUnpackedFieldsSet( + const UNITTEST::TestUnpackedTypes& message) { + // The values expected here must match those of ExpectPackedFieldsSet. + + ASSERT_EQ(2, message.unpacked_int32_size()); + ASSERT_EQ(2, message.unpacked_int64_size()); + ASSERT_EQ(2, message.unpacked_uint32_size()); + ASSERT_EQ(2, message.unpacked_uint64_size()); + ASSERT_EQ(2, message.unpacked_sint32_size()); + ASSERT_EQ(2, message.unpacked_sint64_size()); + ASSERT_EQ(2, message.unpacked_fixed32_size()); + ASSERT_EQ(2, message.unpacked_fixed64_size()); + ASSERT_EQ(2, message.unpacked_sfixed32_size()); + ASSERT_EQ(2, message.unpacked_sfixed64_size()); + ASSERT_EQ(2, message.unpacked_float_size()); + ASSERT_EQ(2, message.unpacked_double_size()); + ASSERT_EQ(2, message.unpacked_bool_size()); + ASSERT_EQ(2, message.unpacked_enum_size()); + + EXPECT_EQ(601, message.unpacked_int32(0)); + EXPECT_EQ(602, message.unpacked_int64(0)); + EXPECT_EQ(603, message.unpacked_uint32(0)); + EXPECT_EQ(604, message.unpacked_uint64(0)); + EXPECT_EQ(605, message.unpacked_sint32(0)); + EXPECT_EQ(606, message.unpacked_sint64(0)); + EXPECT_EQ(607, message.unpacked_fixed32(0)); + EXPECT_EQ(608, message.unpacked_fixed64(0)); + EXPECT_EQ(609, message.unpacked_sfixed32(0)); + EXPECT_EQ(610, message.unpacked_sfixed64(0)); + EXPECT_EQ(611, message.unpacked_float(0)); + EXPECT_EQ(612, message.unpacked_double(0)); + EXPECT_TRUE(message.unpacked_bool(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.unpacked_enum(0)); + + EXPECT_EQ(701, message.unpacked_int32(1)); + EXPECT_EQ(702, message.unpacked_int64(1)); + EXPECT_EQ(703, message.unpacked_uint32(1)); + EXPECT_EQ(704, message.unpacked_uint64(1)); + EXPECT_EQ(705, message.unpacked_sint32(1)); + EXPECT_EQ(706, message.unpacked_sint64(1)); + EXPECT_EQ(707, message.unpacked_fixed32(1)); + EXPECT_EQ(708, message.unpacked_fixed64(1)); + EXPECT_EQ(709, message.unpacked_sfixed32(1)); + EXPECT_EQ(710, message.unpacked_sfixed64(1)); + EXPECT_EQ(711, message.unpacked_float(1)); + EXPECT_EQ(712, message.unpacked_double(1)); + EXPECT_FALSE(message.unpacked_bool(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.unpacked_enum(1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedClear( + const UNITTEST::TestPackedTypes& message) { + // Packed repeated fields are empty. + EXPECT_EQ(0, message.packed_int32_size()); + EXPECT_EQ(0, message.packed_int64_size()); + EXPECT_EQ(0, message.packed_uint32_size()); + EXPECT_EQ(0, message.packed_uint64_size()); + EXPECT_EQ(0, message.packed_sint32_size()); + EXPECT_EQ(0, message.packed_sint64_size()); + EXPECT_EQ(0, message.packed_fixed32_size()); + EXPECT_EQ(0, message.packed_fixed64_size()); + EXPECT_EQ(0, message.packed_sfixed32_size()); + EXPECT_EQ(0, message.packed_sfixed64_size()); + EXPECT_EQ(0, message.packed_float_size()); + EXPECT_EQ(0, message.packed_double_size()); + EXPECT_EQ(0, message.packed_bool_size()); + EXPECT_EQ(0, message.packed_enum_size()); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedFieldsModified( + const UNITTEST::TestPackedTypes& message) { + // Do the same for packed repeated fields. + ASSERT_EQ(2, message.packed_int32_size()); + ASSERT_EQ(2, message.packed_int64_size()); + ASSERT_EQ(2, message.packed_uint32_size()); + ASSERT_EQ(2, message.packed_uint64_size()); + ASSERT_EQ(2, message.packed_sint32_size()); + ASSERT_EQ(2, message.packed_sint64_size()); + ASSERT_EQ(2, message.packed_fixed32_size()); + ASSERT_EQ(2, message.packed_fixed64_size()); + ASSERT_EQ(2, message.packed_sfixed32_size()); + ASSERT_EQ(2, message.packed_sfixed64_size()); + ASSERT_EQ(2, message.packed_float_size()); + ASSERT_EQ(2, message.packed_double_size()); + ASSERT_EQ(2, message.packed_bool_size()); + ASSERT_EQ(2, message.packed_enum_size()); + + EXPECT_EQ(601, message.packed_int32(0)); + EXPECT_EQ(602, message.packed_int64(0)); + EXPECT_EQ(603, message.packed_uint32(0)); + EXPECT_EQ(604, message.packed_uint64(0)); + EXPECT_EQ(605, message.packed_sint32(0)); + EXPECT_EQ(606, message.packed_sint64(0)); + EXPECT_EQ(607, message.packed_fixed32(0)); + EXPECT_EQ(608, message.packed_fixed64(0)); + EXPECT_EQ(609, message.packed_sfixed32(0)); + EXPECT_EQ(610, message.packed_sfixed64(0)); + EXPECT_EQ(611, message.packed_float(0)); + EXPECT_EQ(612, message.packed_double(0)); + EXPECT_TRUE(message.packed_bool(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.packed_enum(0)); + // Actually verify the second (modified) elements now. + EXPECT_EQ(801, message.packed_int32(1)); + EXPECT_EQ(802, message.packed_int64(1)); + EXPECT_EQ(803, message.packed_uint32(1)); + EXPECT_EQ(804, message.packed_uint64(1)); + EXPECT_EQ(805, message.packed_sint32(1)); + EXPECT_EQ(806, message.packed_sint64(1)); + EXPECT_EQ(807, message.packed_fixed32(1)); + EXPECT_EQ(808, message.packed_fixed64(1)); + EXPECT_EQ(809, message.packed_sfixed32(1)); + EXPECT_EQ(810, message.packed_sfixed64(1)); + EXPECT_EQ(811, message.packed_float(1)); + EXPECT_EQ(812, message.packed_double(1)); + EXPECT_TRUE(message.packed_bool(1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.packed_enum(1)); +} + +// =================================================================== +// Extensions +// +// All this code is exactly equivalent to the above code except that it's +// manipulating extension fields instead of normal ones. + +inline void TestUtil::SetAllExtensions(UNITTEST::TestAllExtensions* message) { + message->SetExtension(UNITTEST::optional_int32_extension, 101); + message->SetExtension(UNITTEST::optional_int64_extension, 102); + message->SetExtension(UNITTEST::optional_uint32_extension, 103); + message->SetExtension(UNITTEST::optional_uint64_extension, 104); + message->SetExtension(UNITTEST::optional_sint32_extension, 105); + message->SetExtension(UNITTEST::optional_sint64_extension, 106); + message->SetExtension(UNITTEST::optional_fixed32_extension, 107); + message->SetExtension(UNITTEST::optional_fixed64_extension, 108); + message->SetExtension(UNITTEST::optional_sfixed32_extension, 109); + message->SetExtension(UNITTEST::optional_sfixed64_extension, 110); + message->SetExtension(UNITTEST::optional_float_extension, 111); + message->SetExtension(UNITTEST::optional_double_extension, 112); + message->SetExtension(UNITTEST::optional_bool_extension, true); + message->SetExtension(UNITTEST::optional_string_extension, "115"); + message->SetExtension(UNITTEST::optional_bytes_extension, "116"); + + message->MutableExtension(UNITTEST::optionalgroup_extension)->set_a(117); + message->MutableExtension(UNITTEST::optional_nested_message_extension) + ->set_bb(118); + message->MutableExtension(UNITTEST::optional_foreign_message_extension) + ->set_c(119); + message->MutableExtension(UNITTEST::optional_import_message_extension) + ->set_d(120); + + message->SetExtension(UNITTEST::optional_nested_enum_extension, + UNITTEST::TestAllTypes::BAZ); + message->SetExtension(UNITTEST::optional_foreign_enum_extension, + UNITTEST::FOREIGN_BAZ); + message->SetExtension(UNITTEST::optional_import_enum_extension, + UNITTEST_IMPORT::IMPORT_BAZ); + + message->SetExtension(UNITTEST::optional_string_piece_extension, "124"); + message->SetExtension(UNITTEST::optional_cord_extension, "125"); + + message->MutableExtension(UNITTEST::optional_public_import_message_extension) + ->set_e(126); + message->MutableExtension(UNITTEST::optional_lazy_message_extension) + ->set_bb(127); + + // ----------------------------------------------------------------- + + message->AddExtension(UNITTEST::repeated_int32_extension, 201); + message->AddExtension(UNITTEST::repeated_int64_extension, 202); + message->AddExtension(UNITTEST::repeated_uint32_extension, 203); + message->AddExtension(UNITTEST::repeated_uint64_extension, 204); + message->AddExtension(UNITTEST::repeated_sint32_extension, 205); + message->AddExtension(UNITTEST::repeated_sint64_extension, 206); + message->AddExtension(UNITTEST::repeated_fixed32_extension, 207); + message->AddExtension(UNITTEST::repeated_fixed64_extension, 208); + message->AddExtension(UNITTEST::repeated_sfixed32_extension, 209); + message->AddExtension(UNITTEST::repeated_sfixed64_extension, 210); + message->AddExtension(UNITTEST::repeated_float_extension, 211); + message->AddExtension(UNITTEST::repeated_double_extension, 212); + message->AddExtension(UNITTEST::repeated_bool_extension, true); + message->AddExtension(UNITTEST::repeated_string_extension, "215"); + message->AddExtension(UNITTEST::repeated_bytes_extension, "216"); + + message->AddExtension(UNITTEST::repeatedgroup_extension)->set_a(217); + message->AddExtension(UNITTEST::repeated_nested_message_extension) + ->set_bb(218); + message->AddExtension(UNITTEST::repeated_foreign_message_extension) + ->set_c(219); + message->AddExtension(UNITTEST::repeated_import_message_extension) + ->set_d(220); + message->AddExtension(UNITTEST::repeated_lazy_message_extension)->set_bb(227); + + message->AddExtension(UNITTEST::repeated_nested_enum_extension, + UNITTEST::TestAllTypes::BAR); + message->AddExtension(UNITTEST::repeated_foreign_enum_extension, + UNITTEST::FOREIGN_BAR); + message->AddExtension(UNITTEST::repeated_import_enum_extension, + UNITTEST_IMPORT::IMPORT_BAR); + + message->AddExtension(UNITTEST::repeated_string_piece_extension, "224"); + message->AddExtension(UNITTEST::repeated_cord_extension, "225"); + + // Add a second one of each field. + message->AddExtension(UNITTEST::repeated_int32_extension, 301); + message->AddExtension(UNITTEST::repeated_int64_extension, 302); + message->AddExtension(UNITTEST::repeated_uint32_extension, 303); + message->AddExtension(UNITTEST::repeated_uint64_extension, 304); + message->AddExtension(UNITTEST::repeated_sint32_extension, 305); + message->AddExtension(UNITTEST::repeated_sint64_extension, 306); + message->AddExtension(UNITTEST::repeated_fixed32_extension, 307); + message->AddExtension(UNITTEST::repeated_fixed64_extension, 308); + message->AddExtension(UNITTEST::repeated_sfixed32_extension, 309); + message->AddExtension(UNITTEST::repeated_sfixed64_extension, 310); + message->AddExtension(UNITTEST::repeated_float_extension, 311); + message->AddExtension(UNITTEST::repeated_double_extension, 312); + message->AddExtension(UNITTEST::repeated_bool_extension, false); + message->AddExtension(UNITTEST::repeated_string_extension, "315"); + message->AddExtension(UNITTEST::repeated_bytes_extension, "316"); + + message->AddExtension(UNITTEST::repeatedgroup_extension)->set_a(317); + message->AddExtension(UNITTEST::repeated_nested_message_extension) + ->set_bb(318); + message->AddExtension(UNITTEST::repeated_foreign_message_extension) + ->set_c(319); + message->AddExtension(UNITTEST::repeated_import_message_extension) + ->set_d(320); + message->AddExtension(UNITTEST::repeated_lazy_message_extension)->set_bb(327); + + message->AddExtension(UNITTEST::repeated_nested_enum_extension, + UNITTEST::TestAllTypes::BAZ); + message->AddExtension(UNITTEST::repeated_foreign_enum_extension, + UNITTEST::FOREIGN_BAZ); + message->AddExtension(UNITTEST::repeated_import_enum_extension, + UNITTEST_IMPORT::IMPORT_BAZ); + + message->AddExtension(UNITTEST::repeated_string_piece_extension, "324"); + message->AddExtension(UNITTEST::repeated_cord_extension, "325"); + + // ----------------------------------------------------------------- + + message->SetExtension(UNITTEST::default_int32_extension, 401); + message->SetExtension(UNITTEST::default_int64_extension, 402); + message->SetExtension(UNITTEST::default_uint32_extension, 403); + message->SetExtension(UNITTEST::default_uint64_extension, 404); + message->SetExtension(UNITTEST::default_sint32_extension, 405); + message->SetExtension(UNITTEST::default_sint64_extension, 406); + message->SetExtension(UNITTEST::default_fixed32_extension, 407); + message->SetExtension(UNITTEST::default_fixed64_extension, 408); + message->SetExtension(UNITTEST::default_sfixed32_extension, 409); + message->SetExtension(UNITTEST::default_sfixed64_extension, 410); + message->SetExtension(UNITTEST::default_float_extension, 411); + message->SetExtension(UNITTEST::default_double_extension, 412); + message->SetExtension(UNITTEST::default_bool_extension, false); + message->SetExtension(UNITTEST::default_string_extension, "415"); + message->SetExtension(UNITTEST::default_bytes_extension, "416"); + + message->SetExtension(UNITTEST::default_nested_enum_extension, + UNITTEST::TestAllTypes::FOO); + message->SetExtension(UNITTEST::default_foreign_enum_extension, + UNITTEST::FOREIGN_FOO); + message->SetExtension(UNITTEST::default_import_enum_extension, + UNITTEST_IMPORT::IMPORT_FOO); + + message->SetExtension(UNITTEST::default_string_piece_extension, "424"); + message->SetExtension(UNITTEST::default_cord_extension, "425"); + + SetOneofFields(message); +} + +inline void TestUtil::SetOneofFields(UNITTEST::TestAllExtensions* message) { + message->SetExtension(UNITTEST::oneof_uint32_extension, 601); + message->MutableExtension(UNITTEST::oneof_nested_message_extension) + ->set_bb(602); + message->SetExtension(UNITTEST::oneof_string_extension, "603"); + message->SetExtension(UNITTEST::oneof_bytes_extension, "604"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetAllFieldsAndExtensions( + UNITTEST::TestFieldOrderings* message) { + GOOGLE_CHECK(message); + message->set_my_int(1); + message->set_my_string("foo"); + message->set_my_float(1.0); + message->SetExtension(UNITTEST::my_extension_int, 23); + message->SetExtension(UNITTEST::my_extension_string, "bar"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyRepeatedExtensions( + UNITTEST::TestAllExtensions* message) { + message->SetExtension(UNITTEST::repeated_int32_extension, 1, 501); + message->SetExtension(UNITTEST::repeated_int64_extension, 1, 502); + message->SetExtension(UNITTEST::repeated_uint32_extension, 1, 503); + message->SetExtension(UNITTEST::repeated_uint64_extension, 1, 504); + message->SetExtension(UNITTEST::repeated_sint32_extension, 1, 505); + message->SetExtension(UNITTEST::repeated_sint64_extension, 1, 506); + message->SetExtension(UNITTEST::repeated_fixed32_extension, 1, 507); + message->SetExtension(UNITTEST::repeated_fixed64_extension, 1, 508); + message->SetExtension(UNITTEST::repeated_sfixed32_extension, 1, 509); + message->SetExtension(UNITTEST::repeated_sfixed64_extension, 1, 510); + message->SetExtension(UNITTEST::repeated_float_extension, 1, 511); + message->SetExtension(UNITTEST::repeated_double_extension, 1, 512); + message->SetExtension(UNITTEST::repeated_bool_extension, 1, true); + message->SetExtension(UNITTEST::repeated_string_extension, 1, "515"); + message->SetExtension(UNITTEST::repeated_bytes_extension, 1, "516"); + + message->MutableExtension(UNITTEST::repeatedgroup_extension, 1)->set_a(517); + message->MutableExtension(UNITTEST::repeated_nested_message_extension, 1) + ->set_bb(518); + message->MutableExtension(UNITTEST::repeated_foreign_message_extension, 1) + ->set_c(519); + message->MutableExtension(UNITTEST::repeated_import_message_extension, 1) + ->set_d(520); + message->MutableExtension(UNITTEST::repeated_lazy_message_extension, 1) + ->set_bb(527); + + message->SetExtension(UNITTEST::repeated_nested_enum_extension, 1, + UNITTEST::TestAllTypes::FOO); + message->SetExtension(UNITTEST::repeated_foreign_enum_extension, 1, + UNITTEST::FOREIGN_FOO); + message->SetExtension(UNITTEST::repeated_import_enum_extension, 1, + UNITTEST_IMPORT::IMPORT_FOO); + + message->SetExtension(UNITTEST::repeated_string_piece_extension, 1, "524"); + message->SetExtension(UNITTEST::repeated_cord_extension, 1, "525"); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectAllExtensionsSet( + const UNITTEST::TestAllExtensions& message) { + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_int32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_int64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_uint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_uint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_float_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_double_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_bool_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_string_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_bytes_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::optionalgroup_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_nested_message_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_foreign_message_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_import_message_extension)); + EXPECT_TRUE( + message.HasExtension(UNITTEST::optional_public_import_message_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_lazy_message_extension)); + + EXPECT_TRUE(message.GetExtension(UNITTEST::optionalgroup_extension).has_a()); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_nested_message_extension) + .has_bb()); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_foreign_message_extension) + .has_c()); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_import_message_extension) + .has_d()); + EXPECT_TRUE( + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .has_e()); + EXPECT_TRUE( + message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb()); + + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::optional_cord_extension)); + + EXPECT_EQ(101, message.GetExtension(UNITTEST::optional_int32_extension)); + EXPECT_EQ(102, message.GetExtension(UNITTEST::optional_int64_extension)); + EXPECT_EQ(103, message.GetExtension(UNITTEST::optional_uint32_extension)); + EXPECT_EQ(104, message.GetExtension(UNITTEST::optional_uint64_extension)); + EXPECT_EQ(105, message.GetExtension(UNITTEST::optional_sint32_extension)); + EXPECT_EQ(106, message.GetExtension(UNITTEST::optional_sint64_extension)); + EXPECT_EQ(107, message.GetExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_EQ(108, message.GetExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_EQ(109, message.GetExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_EQ(110, message.GetExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_EQ(111, message.GetExtension(UNITTEST::optional_float_extension)); + EXPECT_EQ(112, message.GetExtension(UNITTEST::optional_double_extension)); + EXPECT_TRUE(message.GetExtension(UNITTEST::optional_bool_extension)); + EXPECT_EQ("115", message.GetExtension(UNITTEST::optional_string_extension)); + EXPECT_EQ("116", message.GetExtension(UNITTEST::optional_bytes_extension)); + + EXPECT_EQ(117, message.GetExtension(UNITTEST::optionalgroup_extension).a()); + EXPECT_EQ( + 118, + message.GetExtension(UNITTEST::optional_nested_message_extension).bb()); + EXPECT_EQ( + 119, + message.GetExtension(UNITTEST::optional_foreign_message_extension).c()); + EXPECT_EQ( + 120, + message.GetExtension(UNITTEST::optional_import_message_extension).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + message.GetExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, + message.GetExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_EQ("124", + message.GetExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_EQ("125", message.GetExtension(UNITTEST::optional_cord_extension)); + EXPECT_EQ( + 126, + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .e()); + EXPECT_EQ( + 127, + message.GetExtension(UNITTEST::optional_lazy_message_extension).bb()); + + // ----------------------------------------------------------------- + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); + + EXPECT_EQ(301, message.GetExtension(UNITTEST::repeated_int32_extension, 1)); + EXPECT_EQ(302, message.GetExtension(UNITTEST::repeated_int64_extension, 1)); + EXPECT_EQ(303, message.GetExtension(UNITTEST::repeated_uint32_extension, 1)); + EXPECT_EQ(304, message.GetExtension(UNITTEST::repeated_uint64_extension, 1)); + EXPECT_EQ(305, message.GetExtension(UNITTEST::repeated_sint32_extension, 1)); + EXPECT_EQ(306, message.GetExtension(UNITTEST::repeated_sint64_extension, 1)); + EXPECT_EQ(307, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1)); + EXPECT_EQ(308, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1)); + EXPECT_EQ(309, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1)); + EXPECT_EQ(310, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1)); + EXPECT_EQ(311, message.GetExtension(UNITTEST::repeated_float_extension, 1)); + EXPECT_EQ(312, message.GetExtension(UNITTEST::repeated_double_extension, 1)); + EXPECT_FALSE(message.GetExtension(UNITTEST::repeated_bool_extension, 1)); + EXPECT_EQ("315", + message.GetExtension(UNITTEST::repeated_string_extension, 1)); + EXPECT_EQ("316", message.GetExtension(UNITTEST::repeated_bytes_extension, 1)); + + EXPECT_EQ(317, + message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a()); + EXPECT_EQ(318, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 1) + .bb()); + EXPECT_EQ( + 319, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1) + .c()); + EXPECT_EQ( + 320, + message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d()); + EXPECT_EQ( + 327, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 1)); + + EXPECT_EQ("324", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 1)); + EXPECT_EQ("325", message.GetExtension(UNITTEST::repeated_cord_extension, 1)); + + // ----------------------------------------------------------------- + + EXPECT_TRUE(message.HasExtension(UNITTEST::default_int32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_int64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_uint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_uint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sint32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sint64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_fixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_fixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_float_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_double_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_bool_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_string_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_bytes_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::default_string_piece_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::default_cord_extension)); + + EXPECT_EQ(401, message.GetExtension(UNITTEST::default_int32_extension)); + EXPECT_EQ(402, message.GetExtension(UNITTEST::default_int64_extension)); + EXPECT_EQ(403, message.GetExtension(UNITTEST::default_uint32_extension)); + EXPECT_EQ(404, message.GetExtension(UNITTEST::default_uint64_extension)); + EXPECT_EQ(405, message.GetExtension(UNITTEST::default_sint32_extension)); + EXPECT_EQ(406, message.GetExtension(UNITTEST::default_sint64_extension)); + EXPECT_EQ(407, message.GetExtension(UNITTEST::default_fixed32_extension)); + EXPECT_EQ(408, message.GetExtension(UNITTEST::default_fixed64_extension)); + EXPECT_EQ(409, message.GetExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_EQ(410, message.GetExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_EQ(411, message.GetExtension(UNITTEST::default_float_extension)); + EXPECT_EQ(412, message.GetExtension(UNITTEST::default_double_extension)); + EXPECT_FALSE(message.GetExtension(UNITTEST::default_bool_extension)); + EXPECT_EQ("415", message.GetExtension(UNITTEST::default_string_extension)); + EXPECT_EQ("416", message.GetExtension(UNITTEST::default_bytes_extension)); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, + message.GetExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, + message.GetExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_EQ("424", + message.GetExtension(UNITTEST::default_string_piece_extension)); + EXPECT_EQ("425", message.GetExtension(UNITTEST::default_cord_extension)); + + EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_uint32_extension)); + EXPECT_TRUE( + message.GetExtension(UNITTEST::oneof_nested_message_extension).has_bb()); + EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_string_extension)); + EXPECT_TRUE(message.HasExtension(UNITTEST::oneof_bytes_extension)); + + EXPECT_EQ(601, message.GetExtension(UNITTEST::oneof_uint32_extension)); + EXPECT_EQ( + 602, message.GetExtension(UNITTEST::oneof_nested_message_extension).bb()); + EXPECT_EQ("603", message.GetExtension(UNITTEST::oneof_string_extension)); + EXPECT_EQ("604", message.GetExtension(UNITTEST::oneof_bytes_extension)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectExtensionsClear( + const UNITTEST::TestAllExtensions& message) { + string serialized; + ASSERT_TRUE(message.SerializeToString(&serialized)); + EXPECT_EQ("", serialized); + EXPECT_EQ(0, message.ByteSizeLong()); + + // has_blah() should initially be false for all optional fields. + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_int32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_int64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_uint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_uint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_float_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_double_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_bool_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_string_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_bytes_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::optionalgroup_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_nested_message_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_foreign_message_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_import_message_extension)); + EXPECT_FALSE( + message.HasExtension(UNITTEST::optional_public_import_message_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_lazy_message_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::optional_cord_extension)); + + // Optional fields without defaults are set to zero or something like it. + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_int32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_int64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_uint32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_uint64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sint32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sint64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_fixed32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_fixed64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sfixed32_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_sfixed64_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_float_extension)); + EXPECT_EQ(0, message.GetExtension(UNITTEST::optional_double_extension)); + EXPECT_FALSE(message.GetExtension(UNITTEST::optional_bool_extension)); + EXPECT_EQ("", message.GetExtension(UNITTEST::optional_string_extension)); + EXPECT_EQ("", message.GetExtension(UNITTEST::optional_bytes_extension)); + + // Embedded messages should also be clear. + EXPECT_FALSE(message.GetExtension(UNITTEST::optionalgroup_extension).has_a()); + EXPECT_FALSE(message.GetExtension(UNITTEST::optional_nested_message_extension) + .has_bb()); + EXPECT_FALSE( + message.GetExtension(UNITTEST::optional_foreign_message_extension) + .has_c()); + EXPECT_FALSE(message.GetExtension(UNITTEST::optional_import_message_extension) + .has_d()); + EXPECT_FALSE( + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .has_e()); + EXPECT_FALSE( + message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb()); + + EXPECT_EQ(0, message.GetExtension(UNITTEST::optionalgroup_extension).a()); + EXPECT_EQ( + 0, + message.GetExtension(UNITTEST::optional_nested_message_extension).bb()); + EXPECT_EQ( + 0, + message.GetExtension(UNITTEST::optional_foreign_message_extension).c()); + EXPECT_EQ( + 0, message.GetExtension(UNITTEST::optional_import_message_extension).d()); + EXPECT_EQ( + 0, + message.GetExtension(UNITTEST::optional_public_import_message_extension) + .e()); + EXPECT_EQ( + 0, message.GetExtension(UNITTEST::optional_lazy_message_extension).bb()); + + // Enums without defaults are set to the first value in the enum. + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, + message.GetExtension(UNITTEST::optional_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::optional_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, + message.GetExtension(UNITTEST::optional_import_enum_extension)); + + EXPECT_EQ("", + message.GetExtension(UNITTEST::optional_string_piece_extension)); + EXPECT_EQ("", message.GetExtension(UNITTEST::optional_cord_extension)); + + // Repeated fields are empty. + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_float_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_double_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_string_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + EXPECT_EQ( + 0, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + EXPECT_EQ(0, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + // has_blah() should also be false for all default fields. + EXPECT_FALSE(message.HasExtension(UNITTEST::default_int32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_int64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_uint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_uint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sint32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sint64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_fixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_fixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_float_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_double_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_bool_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_string_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_bytes_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::default_string_piece_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::default_cord_extension)); + + // Fields with defaults have their default values (duh). + EXPECT_EQ(41, message.GetExtension(UNITTEST::default_int32_extension)); + EXPECT_EQ(42, message.GetExtension(UNITTEST::default_int64_extension)); + EXPECT_EQ(43, message.GetExtension(UNITTEST::default_uint32_extension)); + EXPECT_EQ(44, message.GetExtension(UNITTEST::default_uint64_extension)); + EXPECT_EQ(-45, message.GetExtension(UNITTEST::default_sint32_extension)); + EXPECT_EQ(46, message.GetExtension(UNITTEST::default_sint64_extension)); + EXPECT_EQ(47, message.GetExtension(UNITTEST::default_fixed32_extension)); + EXPECT_EQ(48, message.GetExtension(UNITTEST::default_fixed64_extension)); + EXPECT_EQ(49, message.GetExtension(UNITTEST::default_sfixed32_extension)); + EXPECT_EQ(-50, message.GetExtension(UNITTEST::default_sfixed64_extension)); + EXPECT_EQ(51.5, message.GetExtension(UNITTEST::default_float_extension)); + EXPECT_EQ(52e3, message.GetExtension(UNITTEST::default_double_extension)); + EXPECT_TRUE(message.GetExtension(UNITTEST::default_bool_extension)); + EXPECT_EQ("hello", message.GetExtension(UNITTEST::default_string_extension)); + EXPECT_EQ("world", message.GetExtension(UNITTEST::default_bytes_extension)); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::default_nested_enum_extension)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::default_foreign_enum_extension)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::default_import_enum_extension)); + + EXPECT_EQ("abc", + message.GetExtension(UNITTEST::default_string_piece_extension)); + EXPECT_EQ("123", message.GetExtension(UNITTEST::default_cord_extension)); + + EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_uint32_extension)); + EXPECT_FALSE( + message.GetExtension(UNITTEST::oneof_nested_message_extension).has_bb()); + EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_string_extension)); + EXPECT_FALSE(message.HasExtension(UNITTEST::oneof_bytes_extension)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectRepeatedExtensionsModified( + const UNITTEST::TestAllExtensions& message) { + // ModifyRepeatedFields only sets the second repeated element of each + // field. In addition to verifying this, we also verify that the first + // element and size were *not* modified. + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); + + // Actually verify the second (modified) elements now. + EXPECT_EQ(501, message.GetExtension(UNITTEST::repeated_int32_extension, 1)); + EXPECT_EQ(502, message.GetExtension(UNITTEST::repeated_int64_extension, 1)); + EXPECT_EQ(503, message.GetExtension(UNITTEST::repeated_uint32_extension, 1)); + EXPECT_EQ(504, message.GetExtension(UNITTEST::repeated_uint64_extension, 1)); + EXPECT_EQ(505, message.GetExtension(UNITTEST::repeated_sint32_extension, 1)); + EXPECT_EQ(506, message.GetExtension(UNITTEST::repeated_sint64_extension, 1)); + EXPECT_EQ(507, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1)); + EXPECT_EQ(508, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1)); + EXPECT_EQ(509, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1)); + EXPECT_EQ(510, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1)); + EXPECT_EQ(511, message.GetExtension(UNITTEST::repeated_float_extension, 1)); + EXPECT_EQ(512, message.GetExtension(UNITTEST::repeated_double_extension, 1)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 1)); + EXPECT_EQ("515", + message.GetExtension(UNITTEST::repeated_string_extension, 1)); + EXPECT_EQ("516", message.GetExtension(UNITTEST::repeated_bytes_extension, 1)); + + EXPECT_EQ(517, + message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a()); + EXPECT_EQ(518, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 1) + .bb()); + EXPECT_EQ( + 519, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1) + .c()); + EXPECT_EQ( + 520, + message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d()); + EXPECT_EQ( + 527, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::FOO, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_FOO, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 1)); + + EXPECT_EQ("524", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 1)); + EXPECT_EQ("525", message.GetExtension(UNITTEST::repeated_cord_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::SetPackedExtensions( + UNITTEST::TestPackedExtensions* message) { + message->AddExtension(UNITTEST::packed_int32_extension, 601); + message->AddExtension(UNITTEST::packed_int64_extension, 602); + message->AddExtension(UNITTEST::packed_uint32_extension, 603); + message->AddExtension(UNITTEST::packed_uint64_extension, 604); + message->AddExtension(UNITTEST::packed_sint32_extension, 605); + message->AddExtension(UNITTEST::packed_sint64_extension, 606); + message->AddExtension(UNITTEST::packed_fixed32_extension, 607); + message->AddExtension(UNITTEST::packed_fixed64_extension, 608); + message->AddExtension(UNITTEST::packed_sfixed32_extension, 609); + message->AddExtension(UNITTEST::packed_sfixed64_extension, 610); + message->AddExtension(UNITTEST::packed_float_extension, 611); + message->AddExtension(UNITTEST::packed_double_extension, 612); + message->AddExtension(UNITTEST::packed_bool_extension, true); + message->AddExtension(UNITTEST::packed_enum_extension, UNITTEST::FOREIGN_BAR); + // add a second one of each field + message->AddExtension(UNITTEST::packed_int32_extension, 701); + message->AddExtension(UNITTEST::packed_int64_extension, 702); + message->AddExtension(UNITTEST::packed_uint32_extension, 703); + message->AddExtension(UNITTEST::packed_uint64_extension, 704); + message->AddExtension(UNITTEST::packed_sint32_extension, 705); + message->AddExtension(UNITTEST::packed_sint64_extension, 706); + message->AddExtension(UNITTEST::packed_fixed32_extension, 707); + message->AddExtension(UNITTEST::packed_fixed64_extension, 708); + message->AddExtension(UNITTEST::packed_sfixed32_extension, 709); + message->AddExtension(UNITTEST::packed_sfixed64_extension, 710); + message->AddExtension(UNITTEST::packed_float_extension, 711); + message->AddExtension(UNITTEST::packed_double_extension, 712); + message->AddExtension(UNITTEST::packed_bool_extension, false); + message->AddExtension(UNITTEST::packed_enum_extension, UNITTEST::FOREIGN_BAZ); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ModifyPackedExtensions( + UNITTEST::TestPackedExtensions* message) { + message->SetExtension(UNITTEST::packed_int32_extension, 1, 801); + message->SetExtension(UNITTEST::packed_int64_extension, 1, 802); + message->SetExtension(UNITTEST::packed_uint32_extension, 1, 803); + message->SetExtension(UNITTEST::packed_uint64_extension, 1, 804); + message->SetExtension(UNITTEST::packed_sint32_extension, 1, 805); + message->SetExtension(UNITTEST::packed_sint64_extension, 1, 806); + message->SetExtension(UNITTEST::packed_fixed32_extension, 1, 807); + message->SetExtension(UNITTEST::packed_fixed64_extension, 1, 808); + message->SetExtension(UNITTEST::packed_sfixed32_extension, 1, 809); + message->SetExtension(UNITTEST::packed_sfixed64_extension, 1, 810); + message->SetExtension(UNITTEST::packed_float_extension, 1, 811); + message->SetExtension(UNITTEST::packed_double_extension, 1, 812); + message->SetExtension(UNITTEST::packed_bool_extension, 1, true); + message->SetExtension(UNITTEST::packed_enum_extension, 1, + UNITTEST::FOREIGN_FOO); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedExtensionsSet( + const UNITTEST::TestPackedExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_enum_extension)); + + EXPECT_EQ(601, message.GetExtension(UNITTEST::packed_int32_extension, 0)); + EXPECT_EQ(602, message.GetExtension(UNITTEST::packed_int64_extension, 0)); + EXPECT_EQ(603, message.GetExtension(UNITTEST::packed_uint32_extension, 0)); + EXPECT_EQ(604, message.GetExtension(UNITTEST::packed_uint64_extension, 0)); + EXPECT_EQ(605, message.GetExtension(UNITTEST::packed_sint32_extension, 0)); + EXPECT_EQ(606, message.GetExtension(UNITTEST::packed_sint64_extension, 0)); + EXPECT_EQ(607, message.GetExtension(UNITTEST::packed_fixed32_extension, 0)); + EXPECT_EQ(608, message.GetExtension(UNITTEST::packed_fixed64_extension, 0)); + EXPECT_EQ(609, message.GetExtension(UNITTEST::packed_sfixed32_extension, 0)); + EXPECT_EQ(610, message.GetExtension(UNITTEST::packed_sfixed64_extension, 0)); + EXPECT_EQ(611, message.GetExtension(UNITTEST::packed_float_extension, 0)); + EXPECT_EQ(612, message.GetExtension(UNITTEST::packed_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::packed_enum_extension, 0)); + EXPECT_EQ(701, message.GetExtension(UNITTEST::packed_int32_extension, 1)); + EXPECT_EQ(702, message.GetExtension(UNITTEST::packed_int64_extension, 1)); + EXPECT_EQ(703, message.GetExtension(UNITTEST::packed_uint32_extension, 1)); + EXPECT_EQ(704, message.GetExtension(UNITTEST::packed_uint64_extension, 1)); + EXPECT_EQ(705, message.GetExtension(UNITTEST::packed_sint32_extension, 1)); + EXPECT_EQ(706, message.GetExtension(UNITTEST::packed_sint64_extension, 1)); + EXPECT_EQ(707, message.GetExtension(UNITTEST::packed_fixed32_extension, 1)); + EXPECT_EQ(708, message.GetExtension(UNITTEST::packed_fixed64_extension, 1)); + EXPECT_EQ(709, message.GetExtension(UNITTEST::packed_sfixed32_extension, 1)); + EXPECT_EQ(710, message.GetExtension(UNITTEST::packed_sfixed64_extension, 1)); + EXPECT_EQ(711, message.GetExtension(UNITTEST::packed_float_extension, 1)); + EXPECT_EQ(712, message.GetExtension(UNITTEST::packed_double_extension, 1)); + EXPECT_FALSE(message.GetExtension(UNITTEST::packed_bool_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::packed_enum_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedExtensionsClear( + const UNITTEST::TestPackedExtensions& message) { + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_int32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_int64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_uint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_uint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sint32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sint64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_fixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_fixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sfixed32_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_sfixed64_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_float_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_double_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_bool_extension)); + EXPECT_EQ(0, message.ExtensionSize(UNITTEST::packed_enum_extension)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectPackedExtensionsModified( + const UNITTEST::TestPackedExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::packed_enum_extension)); + EXPECT_EQ(601, message.GetExtension(UNITTEST::packed_int32_extension, 0)); + EXPECT_EQ(602, message.GetExtension(UNITTEST::packed_int64_extension, 0)); + EXPECT_EQ(603, message.GetExtension(UNITTEST::packed_uint32_extension, 0)); + EXPECT_EQ(604, message.GetExtension(UNITTEST::packed_uint64_extension, 0)); + EXPECT_EQ(605, message.GetExtension(UNITTEST::packed_sint32_extension, 0)); + EXPECT_EQ(606, message.GetExtension(UNITTEST::packed_sint64_extension, 0)); + EXPECT_EQ(607, message.GetExtension(UNITTEST::packed_fixed32_extension, 0)); + EXPECT_EQ(608, message.GetExtension(UNITTEST::packed_fixed64_extension, 0)); + EXPECT_EQ(609, message.GetExtension(UNITTEST::packed_sfixed32_extension, 0)); + EXPECT_EQ(610, message.GetExtension(UNITTEST::packed_sfixed64_extension, 0)); + EXPECT_EQ(611, message.GetExtension(UNITTEST::packed_float_extension, 0)); + EXPECT_EQ(612, message.GetExtension(UNITTEST::packed_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::packed_enum_extension, 0)); + + // Actually verify the second (modified) elements now. + EXPECT_EQ(801, message.GetExtension(UNITTEST::packed_int32_extension, 1)); + EXPECT_EQ(802, message.GetExtension(UNITTEST::packed_int64_extension, 1)); + EXPECT_EQ(803, message.GetExtension(UNITTEST::packed_uint32_extension, 1)); + EXPECT_EQ(804, message.GetExtension(UNITTEST::packed_uint64_extension, 1)); + EXPECT_EQ(805, message.GetExtension(UNITTEST::packed_sint32_extension, 1)); + EXPECT_EQ(806, message.GetExtension(UNITTEST::packed_sint64_extension, 1)); + EXPECT_EQ(807, message.GetExtension(UNITTEST::packed_fixed32_extension, 1)); + EXPECT_EQ(808, message.GetExtension(UNITTEST::packed_fixed64_extension, 1)); + EXPECT_EQ(809, message.GetExtension(UNITTEST::packed_sfixed32_extension, 1)); + EXPECT_EQ(810, message.GetExtension(UNITTEST::packed_sfixed64_extension, 1)); + EXPECT_EQ(811, message.GetExtension(UNITTEST::packed_float_extension, 1)); + EXPECT_EQ(812, message.GetExtension(UNITTEST::packed_double_extension, 1)); + EXPECT_TRUE(message.GetExtension(UNITTEST::packed_bool_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_FOO, + message.GetExtension(UNITTEST::packed_enum_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectUnpackedExtensionsSet( + const UNITTEST::TestUnpackedExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::unpacked_enum_extension)); + + EXPECT_EQ(601, message.GetExtension(UNITTEST::unpacked_int32_extension, 0)); + EXPECT_EQ(602, message.GetExtension(UNITTEST::unpacked_int64_extension, 0)); + EXPECT_EQ(603, message.GetExtension(UNITTEST::unpacked_uint32_extension, 0)); + EXPECT_EQ(604, message.GetExtension(UNITTEST::unpacked_uint64_extension, 0)); + EXPECT_EQ(605, message.GetExtension(UNITTEST::unpacked_sint32_extension, 0)); + EXPECT_EQ(606, message.GetExtension(UNITTEST::unpacked_sint64_extension, 0)); + EXPECT_EQ(607, message.GetExtension(UNITTEST::unpacked_fixed32_extension, 0)); + EXPECT_EQ(608, message.GetExtension(UNITTEST::unpacked_fixed64_extension, 0)); + EXPECT_EQ(609, + message.GetExtension(UNITTEST::unpacked_sfixed32_extension, 0)); + EXPECT_EQ(610, + message.GetExtension(UNITTEST::unpacked_sfixed64_extension, 0)); + EXPECT_EQ(611, message.GetExtension(UNITTEST::unpacked_float_extension, 0)); + EXPECT_EQ(612, message.GetExtension(UNITTEST::unpacked_double_extension, 0)); + EXPECT_EQ(true, message.GetExtension(UNITTEST::unpacked_bool_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::unpacked_enum_extension, 0)); + EXPECT_EQ(701, message.GetExtension(UNITTEST::unpacked_int32_extension, 1)); + EXPECT_EQ(702, message.GetExtension(UNITTEST::unpacked_int64_extension, 1)); + EXPECT_EQ(703, message.GetExtension(UNITTEST::unpacked_uint32_extension, 1)); + EXPECT_EQ(704, message.GetExtension(UNITTEST::unpacked_uint64_extension, 1)); + EXPECT_EQ(705, message.GetExtension(UNITTEST::unpacked_sint32_extension, 1)); + EXPECT_EQ(706, message.GetExtension(UNITTEST::unpacked_sint64_extension, 1)); + EXPECT_EQ(707, message.GetExtension(UNITTEST::unpacked_fixed32_extension, 1)); + EXPECT_EQ(708, message.GetExtension(UNITTEST::unpacked_fixed64_extension, 1)); + EXPECT_EQ(709, + message.GetExtension(UNITTEST::unpacked_sfixed32_extension, 1)); + EXPECT_EQ(710, + message.GetExtension(UNITTEST::unpacked_sfixed64_extension, 1)); + EXPECT_EQ(711, message.GetExtension(UNITTEST::unpacked_float_extension, 1)); + EXPECT_EQ(712, message.GetExtension(UNITTEST::unpacked_double_extension, 1)); + EXPECT_EQ(false, message.GetExtension(UNITTEST::unpacked_bool_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::unpacked_enum_extension, 1)); +} + +// ------------------------------------------------------------------- + +inline void TestUtil::ExpectLastRepeatedsRemoved( + const UNITTEST::TestAllTypes& message) { + ASSERT_EQ(1, message.repeated_int32_size()); + ASSERT_EQ(1, message.repeated_int64_size()); + ASSERT_EQ(1, message.repeated_uint32_size()); + ASSERT_EQ(1, message.repeated_uint64_size()); + ASSERT_EQ(1, message.repeated_sint32_size()); + ASSERT_EQ(1, message.repeated_sint64_size()); + ASSERT_EQ(1, message.repeated_fixed32_size()); + ASSERT_EQ(1, message.repeated_fixed64_size()); + ASSERT_EQ(1, message.repeated_sfixed32_size()); + ASSERT_EQ(1, message.repeated_sfixed64_size()); + ASSERT_EQ(1, message.repeated_float_size()); + ASSERT_EQ(1, message.repeated_double_size()); + ASSERT_EQ(1, message.repeated_bool_size()); + ASSERT_EQ(1, message.repeated_string_size()); + ASSERT_EQ(1, message.repeated_bytes_size()); + + ASSERT_EQ(1, message.repeatedgroup_size()); + ASSERT_EQ(1, message.repeated_nested_message_size()); + ASSERT_EQ(1, message.repeated_foreign_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + ASSERT_EQ(1, message.repeated_nested_enum_size()); + ASSERT_EQ(1, message.repeated_foreign_enum_size()); + ASSERT_EQ(1, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(1, message.repeated_string_piece_size()); + ASSERT_EQ(1, message.repeated_cord_size()); +#endif + + // Test that the remaining element is the correct one. + EXPECT_EQ(201, message.repeated_int32(0)); + EXPECT_EQ(202, message.repeated_int64(0)); + EXPECT_EQ(203, message.repeated_uint32(0)); + EXPECT_EQ(204, message.repeated_uint64(0)); + EXPECT_EQ(205, message.repeated_sint32(0)); + EXPECT_EQ(206, message.repeated_sint64(0)); + EXPECT_EQ(207, message.repeated_fixed32(0)); + EXPECT_EQ(208, message.repeated_fixed64(0)); + EXPECT_EQ(209, message.repeated_sfixed32(0)); + EXPECT_EQ(210, message.repeated_sfixed64(0)); + EXPECT_EQ(211, message.repeated_float(0)); + EXPECT_EQ(212, message.repeated_double(0)); + EXPECT_TRUE(message.repeated_bool(0)); + EXPECT_EQ("215", message.repeated_string(0)); + EXPECT_EQ("216", message.repeated_bytes(0)); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(0)); +} + +inline void TestUtil::ExpectLastRepeatedExtensionsRemoved( + const UNITTEST::TestAllExtensions& message) { + // Test that one element was removed. + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 1, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + // Test that the remaining element is the correct one. + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); +} + +inline void TestUtil::ExpectLastRepeatedsReleased( + const UNITTEST::TestAllTypes& message) { + ASSERT_EQ(1, message.repeatedgroup_size()); + ASSERT_EQ(1, message.repeated_nested_message_size()); + ASSERT_EQ(1, message.repeated_foreign_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + ASSERT_EQ(1, message.repeated_import_message_size()); + + EXPECT_EQ(217, message.repeatedgroup(0).a()); + EXPECT_EQ(218, message.repeated_nested_message(0).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(0).c()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); + EXPECT_EQ(220, message.repeated_import_message(0).d()); +} + +inline void TestUtil::ExpectLastRepeatedExtensionsReleased( + const UNITTEST::TestAllExtensions& message) { + ASSERT_EQ(1, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 1, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(1, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); +} + +inline void TestUtil::ExpectRepeatedsSwapped( + const UNITTEST::TestAllTypes& message) { + ASSERT_EQ(2, message.repeated_int32_size()); + ASSERT_EQ(2, message.repeated_int64_size()); + ASSERT_EQ(2, message.repeated_uint32_size()); + ASSERT_EQ(2, message.repeated_uint64_size()); + ASSERT_EQ(2, message.repeated_sint32_size()); + ASSERT_EQ(2, message.repeated_sint64_size()); + ASSERT_EQ(2, message.repeated_fixed32_size()); + ASSERT_EQ(2, message.repeated_fixed64_size()); + ASSERT_EQ(2, message.repeated_sfixed32_size()); + ASSERT_EQ(2, message.repeated_sfixed64_size()); + ASSERT_EQ(2, message.repeated_float_size()); + ASSERT_EQ(2, message.repeated_double_size()); + ASSERT_EQ(2, message.repeated_bool_size()); + ASSERT_EQ(2, message.repeated_string_size()); + ASSERT_EQ(2, message.repeated_bytes_size()); + + ASSERT_EQ(2, message.repeatedgroup_size()); + ASSERT_EQ(2, message.repeated_nested_message_size()); + ASSERT_EQ(2, message.repeated_foreign_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_import_message_size()); + ASSERT_EQ(2, message.repeated_nested_enum_size()); + ASSERT_EQ(2, message.repeated_foreign_enum_size()); + ASSERT_EQ(2, message.repeated_import_enum_size()); + +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS + ASSERT_EQ(2, message.repeated_string_piece_size()); + ASSERT_EQ(2, message.repeated_cord_size()); +#endif + + // Test that the first element and second element are flipped. + EXPECT_EQ(201, message.repeated_int32(1)); + EXPECT_EQ(202, message.repeated_int64(1)); + EXPECT_EQ(203, message.repeated_uint32(1)); + EXPECT_EQ(204, message.repeated_uint64(1)); + EXPECT_EQ(205, message.repeated_sint32(1)); + EXPECT_EQ(206, message.repeated_sint64(1)); + EXPECT_EQ(207, message.repeated_fixed32(1)); + EXPECT_EQ(208, message.repeated_fixed64(1)); + EXPECT_EQ(209, message.repeated_sfixed32(1)); + EXPECT_EQ(210, message.repeated_sfixed64(1)); + EXPECT_EQ(211, message.repeated_float(1)); + EXPECT_EQ(212, message.repeated_double(1)); + EXPECT_TRUE(message.repeated_bool(1)); + EXPECT_EQ("215", message.repeated_string(1)); + EXPECT_EQ("216", message.repeated_bytes(1)); + + EXPECT_EQ(217, message.repeatedgroup(1).a()); + EXPECT_EQ(218, message.repeated_nested_message(1).bb()); + EXPECT_EQ(219, message.repeated_foreign_message(1).c()); + EXPECT_EQ(220, message.repeated_import_message(1).d()); + EXPECT_EQ(220, message.repeated_import_message(1).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message.repeated_nested_enum(1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeated_foreign_enum(1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, message.repeated_import_enum(1)); + + EXPECT_EQ(301, message.repeated_int32(0)); + EXPECT_EQ(302, message.repeated_int64(0)); + EXPECT_EQ(303, message.repeated_uint32(0)); + EXPECT_EQ(304, message.repeated_uint64(0)); + EXPECT_EQ(305, message.repeated_sint32(0)); + EXPECT_EQ(306, message.repeated_sint64(0)); + EXPECT_EQ(307, message.repeated_fixed32(0)); + EXPECT_EQ(308, message.repeated_fixed64(0)); + EXPECT_EQ(309, message.repeated_sfixed32(0)); + EXPECT_EQ(310, message.repeated_sfixed64(0)); + EXPECT_EQ(311, message.repeated_float(0)); + EXPECT_EQ(312, message.repeated_double(0)); + EXPECT_FALSE(message.repeated_bool(0)); + EXPECT_EQ("315", message.repeated_string(0)); + EXPECT_EQ("316", message.repeated_bytes(0)); + + EXPECT_EQ(317, message.repeatedgroup(0).a()); + EXPECT_EQ(318, message.repeated_nested_message(0).bb()); + EXPECT_EQ(319, message.repeated_foreign_message(0).c()); + EXPECT_EQ(320, message.repeated_import_message(0).d()); + EXPECT_EQ(320, message.repeated_import_message(0).d()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.repeated_nested_enum(0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.repeated_foreign_enum(0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, message.repeated_import_enum(0)); +} + +inline void TestUtil::ExpectRepeatedExtensionsSwapped( + const UNITTEST::TestAllExtensions& message) { + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_int64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_uint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sint64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_fixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed32_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_sfixed64_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_float_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_double_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bool_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_string_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_bytes_extension)); + + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeatedgroup_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_nested_message_extension)); + ASSERT_EQ( + 2, message.ExtensionSize(UNITTEST::repeated_foreign_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_import_message_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_lazy_message_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_nested_enum_extension)); + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_foreign_enum_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_import_enum_extension)); + + ASSERT_EQ(2, + message.ExtensionSize(UNITTEST::repeated_string_piece_extension)); + ASSERT_EQ(2, message.ExtensionSize(UNITTEST::repeated_cord_extension)); + + EXPECT_EQ(201, message.GetExtension(UNITTEST::repeated_int32_extension, 1)); + EXPECT_EQ(202, message.GetExtension(UNITTEST::repeated_int64_extension, 1)); + EXPECT_EQ(203, message.GetExtension(UNITTEST::repeated_uint32_extension, 1)); + EXPECT_EQ(204, message.GetExtension(UNITTEST::repeated_uint64_extension, 1)); + EXPECT_EQ(205, message.GetExtension(UNITTEST::repeated_sint32_extension, 1)); + EXPECT_EQ(206, message.GetExtension(UNITTEST::repeated_sint64_extension, 1)); + EXPECT_EQ(207, message.GetExtension(UNITTEST::repeated_fixed32_extension, 1)); + EXPECT_EQ(208, message.GetExtension(UNITTEST::repeated_fixed64_extension, 1)); + EXPECT_EQ(209, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 1)); + EXPECT_EQ(210, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 1)); + EXPECT_EQ(211, message.GetExtension(UNITTEST::repeated_float_extension, 1)); + EXPECT_EQ(212, message.GetExtension(UNITTEST::repeated_double_extension, 1)); + EXPECT_TRUE(message.GetExtension(UNITTEST::repeated_bool_extension, 1)); + EXPECT_EQ("215", + message.GetExtension(UNITTEST::repeated_string_extension, 1)); + EXPECT_EQ("216", message.GetExtension(UNITTEST::repeated_bytes_extension, 1)); + + EXPECT_EQ(217, + message.GetExtension(UNITTEST::repeatedgroup_extension, 1).a()); + EXPECT_EQ(218, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 1) + .bb()); + EXPECT_EQ( + 219, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 1) + .c()); + EXPECT_EQ( + 220, + message.GetExtension(UNITTEST::repeated_import_message_extension, 1).d()); + EXPECT_EQ( + 227, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 1).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAR, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 1)); + EXPECT_EQ(UNITTEST::FOREIGN_BAR, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 1)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAR, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 1)); + + EXPECT_EQ("224", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 1)); + EXPECT_EQ("225", message.GetExtension(UNITTEST::repeated_cord_extension, 1)); + + EXPECT_EQ(301, message.GetExtension(UNITTEST::repeated_int32_extension, 0)); + EXPECT_EQ(302, message.GetExtension(UNITTEST::repeated_int64_extension, 0)); + EXPECT_EQ(303, message.GetExtension(UNITTEST::repeated_uint32_extension, 0)); + EXPECT_EQ(304, message.GetExtension(UNITTEST::repeated_uint64_extension, 0)); + EXPECT_EQ(305, message.GetExtension(UNITTEST::repeated_sint32_extension, 0)); + EXPECT_EQ(306, message.GetExtension(UNITTEST::repeated_sint64_extension, 0)); + EXPECT_EQ(307, message.GetExtension(UNITTEST::repeated_fixed32_extension, 0)); + EXPECT_EQ(308, message.GetExtension(UNITTEST::repeated_fixed64_extension, 0)); + EXPECT_EQ(309, + message.GetExtension(UNITTEST::repeated_sfixed32_extension, 0)); + EXPECT_EQ(310, + message.GetExtension(UNITTEST::repeated_sfixed64_extension, 0)); + EXPECT_EQ(311, message.GetExtension(UNITTEST::repeated_float_extension, 0)); + EXPECT_EQ(312, message.GetExtension(UNITTEST::repeated_double_extension, 0)); + EXPECT_FALSE(message.GetExtension(UNITTEST::repeated_bool_extension, 0)); + EXPECT_EQ("315", + message.GetExtension(UNITTEST::repeated_string_extension, 0)); + EXPECT_EQ("316", message.GetExtension(UNITTEST::repeated_bytes_extension, 0)); + + EXPECT_EQ(317, + message.GetExtension(UNITTEST::repeatedgroup_extension, 0).a()); + EXPECT_EQ(318, + message.GetExtension(UNITTEST::repeated_nested_message_extension, 0) + .bb()); + EXPECT_EQ( + 319, message.GetExtension(UNITTEST::repeated_foreign_message_extension, 0) + .c()); + EXPECT_EQ( + 320, + message.GetExtension(UNITTEST::repeated_import_message_extension, 0).d()); + EXPECT_EQ( + 327, + message.GetExtension(UNITTEST::repeated_lazy_message_extension, 0).bb()); + + EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, + message.GetExtension(UNITTEST::repeated_nested_enum_extension, 0)); + EXPECT_EQ(UNITTEST::FOREIGN_BAZ, + message.GetExtension(UNITTEST::repeated_foreign_enum_extension, 0)); + EXPECT_EQ(UNITTEST_IMPORT::IMPORT_BAZ, + message.GetExtension(UNITTEST::repeated_import_enum_extension, 0)); + + EXPECT_EQ("324", + message.GetExtension(UNITTEST::repeated_string_piece_extension, 0)); + EXPECT_EQ("325", message.GetExtension(UNITTEST::repeated_cord_extension, 0)); +} + +inline void TestUtil::SetOneof1(UNITTEST::TestOneof2* message) { + message->mutable_foo_lazy_message()->set_qux_int(100); + message->set_bar_string("101"); + message->set_baz_int(102); + message->set_baz_string("103"); +} + +inline void TestUtil::SetOneof2(UNITTEST::TestOneof2* message) { + message->set_foo_int(200); + message->set_bar_enum(UNITTEST::TestOneof2::BAZ); + message->set_baz_int(202); + message->set_baz_string("203"); +} + +inline void TestUtil::ExpectOneofSet1(const UNITTEST::TestOneof2& message) { + ExpectAtMostOneFieldSetInOneof(message); + + EXPECT_TRUE(message.has_foo_lazy_message()); + EXPECT_TRUE(message.foo_lazy_message().has_qux_int()); + + EXPECT_TRUE(message.has_bar_string()); + EXPECT_TRUE(message.has_baz_int()); + EXPECT_TRUE(message.has_baz_string()); + + ASSERT_EQ(0, message.foo_lazy_message().corge_int_size()); + + EXPECT_EQ(100, message.foo_lazy_message().qux_int()); + EXPECT_EQ("101", message.bar_string()); + EXPECT_EQ(102, message.baz_int()); + EXPECT_EQ("103", message.baz_string()); +} + +inline void TestUtil::ExpectOneofSet2(const UNITTEST::TestOneof2& message) { + ExpectAtMostOneFieldSetInOneof(message); + + EXPECT_TRUE(message.has_foo_int()); + EXPECT_TRUE(message.has_bar_enum()); + EXPECT_TRUE(message.has_baz_int()); + EXPECT_TRUE(message.has_baz_string()); + + EXPECT_EQ(200, message.foo_int()); + EXPECT_EQ(UNITTEST::TestOneof2::BAZ, message.bar_enum()); + EXPECT_EQ(202, message.baz_int()); + EXPECT_EQ("203", message.baz_string()); +} + +inline void TestUtil::ExpectOneofClear(const UNITTEST::TestOneof2& message) { + EXPECT_FALSE(message.has_foo_int()); + EXPECT_FALSE(message.has_foo_string()); + EXPECT_FALSE(message.has_foo_bytes()); + EXPECT_FALSE(message.has_foo_enum()); + EXPECT_FALSE(message.has_foo_message()); + EXPECT_FALSE(message.has_foogroup()); + EXPECT_FALSE(message.has_foo_lazy_message()); + + EXPECT_FALSE(message.has_bar_int()); + EXPECT_FALSE(message.has_bar_string()); + EXPECT_FALSE(message.has_bar_bytes()); + EXPECT_FALSE(message.has_bar_enum()); + + EXPECT_FALSE(message.has_baz_int()); + EXPECT_FALSE(message.has_baz_string()); + + EXPECT_EQ(UNITTEST::TestOneof2::FOO_NOT_SET, message.foo_case()); + EXPECT_EQ(UNITTEST::TestOneof2::BAR_NOT_SET, message.bar_case()); +} + +inline void TestUtil::ExpectAtMostOneFieldSetInOneof( + const UNITTEST::TestOneof2& message) { + int count = 0; + if (message.has_foo_int()) count++; + if (message.has_foo_string()) count++; + if (message.has_foo_bytes()) count++; + if (message.has_foo_enum()) count++; + if (message.has_foo_message()) count++; + if (message.has_foogroup()) count++; + if (message.has_foo_lazy_message()) count++; + EXPECT_LE(count, 1); + count = 0; + if (message.has_bar_int()) count++; + if (message.has_bar_string()) count++; + if (message.has_bar_bytes()) count++; + if (message.has_bar_enum()) count++; + EXPECT_TRUE(count == 0 || count == 1); +} + +// =================================================================== + +} // namespace protobuf +} // namespace google diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc index eed2a768c0..0965fd7af9 100644 --- a/src/google/protobuf/text_format.cc +++ b/src/google/protobuf/text_format.cc @@ -57,6 +57,7 @@ #include #include + #include #include @@ -189,6 +190,24 @@ TextFormat::ParseInfoTree* TextFormat::ParseInfoTree::GetTreeForNested( return (*trees)[index]; } +namespace { +// These functions implement the behavior of the "default" TextFormat::Finder, +// they are defined as standalone to be called when finder_ is NULL. +const FieldDescriptor* DefaultFinderFindExtension(Message* message, + const string& name) { + return message->GetReflection()->FindKnownExtensionByName(name); +} + +const Descriptor* DefaultFinderFindAnyType(const Message& message, + const string& prefix, + const string& name) { + if (prefix != internal::kTypeGoogleApisComPrefix && + prefix != internal::kTypeGoogleProdComPrefix) { + return NULL; + } + return message.GetDescriptor()->file()->pool()->FindMessageTypeByName(name); +} +} // namespace // =========================================================================== // Internal class for parsing an ASCII representation of a Protocol Message. @@ -217,7 +236,7 @@ class TextFormat::Parser::ParserImpl { ParserImpl(const Descriptor* root_message_type, io::ZeroCopyInputStream* input_stream, io::ErrorCollector* error_collector, - TextFormat::Finder* finder, + const TextFormat::Finder* finder, ParseInfoTree* parse_info_tree, SingularOverwritePolicy singular_overwrite_policy, bool allow_case_insensitive_field, @@ -380,9 +399,15 @@ class TextFormat::Parser::ParserImpl { DO(Consume("]")); TryConsume(":"); // ':' is optional between message labels and values. string serialized_value; - DO(ConsumeAnyValue(full_type_name, - message->GetDescriptor()->file()->pool(), - &serialized_value)); + const Descriptor* value_descriptor = + finder_ ? finder_->FindAnyType(*message, prefix, full_type_name) + : DefaultFinderFindAnyType(*message, prefix, full_type_name); + if (value_descriptor == NULL) { + ReportError("Could not find type \"" + prefix + full_type_name + + "\" stored in google.protobuf.Any."); + return false; + } + DO(ConsumeAnyValue(value_descriptor, &serialized_value)); if (singular_overwrite_policy_ == FORBID_SINGULAR_OVERWRITES) { // Fail if any_type_url_field has already been specified. if ((!any_type_url_field->is_repeated() && @@ -404,9 +429,8 @@ class TextFormat::Parser::ParserImpl { DO(ConsumeFullTypeName(&field_name)); DO(Consume("]")); - field = (finder_ != NULL - ? finder_->FindExtension(message, field_name) - : reflection->FindKnownExtensionByName(field_name)); + field = finder_ ? finder_->FindExtension(message, field_name) + : DefaultFinderFindExtension(message, field_name); if (field == NULL) { if (!allow_unknown_field_) { @@ -572,12 +596,12 @@ label_skip_parsing: // Skips the next field including the field's name and value. bool SkipField() { - string field_name; if (TryConsume("[")) { - // Extension name. - DO(ConsumeFullTypeName(&field_name)); + // Extension name or type URL. + DO(ConsumeTypeUrlOrFullTypeName()); DO(Consume("]")); } else { + string field_name; DO(ConsumeIdentifier(&field_name)); } @@ -881,6 +905,15 @@ label_skip_parsing: return true; } + bool ConsumeTypeUrlOrFullTypeName() { + string discarded; + DO(ConsumeIdentifier(&discarded)); + while (TryConsume(".") || TryConsume("/")) { + DO(ConsumeIdentifier(&discarded)); + } + return true; + } + // Consumes a string and saves its value in the text parameter. // Returns false if the token is not of type STRING. bool ConsumeString(string* text) { @@ -1029,44 +1062,29 @@ label_skip_parsing: bool ConsumeAnyTypeUrl(string* full_type_name, string* prefix) { // TODO(saito) Extend Consume() to consume multiple tokens at once, so that // this code can be written as just DO(Consume(kGoogleApisTypePrefix)). - string url1, url2, url3; - DO(ConsumeIdentifier(&url1)); // type - DO(Consume(".")); - DO(ConsumeIdentifier(&url2)); // googleapis - DO(Consume(".")); - DO(ConsumeIdentifier(&url3)); // com + DO(ConsumeIdentifier(prefix)); + while (TryConsume(".")) { + string url; + DO(ConsumeIdentifier(&url)); + *prefix += "." + url; + } DO(Consume("/")); + *prefix += "/"; DO(ConsumeFullTypeName(full_type_name)); - *prefix = url1 + "." + url2 + "." + url3 + "/"; - if (*prefix != internal::kTypeGoogleApisComPrefix && - *prefix != internal::kTypeGoogleProdComPrefix) { - ReportError("TextFormat::Parser for Any supports only " - "type.googleapis.com and type.googleprod.com, " - "but found \"" + *prefix + "\""); - return false; - } return true; } // A helper function for reconstructing Any::value. Consumes a text of - // full_type_name, then serializes it into serialized_value. "pool" is used to - // look up and create a temporary object with full_type_name. - bool ConsumeAnyValue(const string& full_type_name, const DescriptorPool* pool, + // full_type_name, then serializes it into serialized_value. + bool ConsumeAnyValue(const Descriptor* value_descriptor, string* serialized_value) { - const Descriptor* value_descriptor = - pool->FindMessageTypeByName(full_type_name); - if (value_descriptor == NULL) { - ReportError("Could not find type \"" + full_type_name + - "\" stored in google.protobuf.Any."); - return false; - } DynamicMessageFactory factory; const Message* value_prototype = factory.GetPrototype(value_descriptor); if (value_prototype == NULL) { return false; } - google::protobuf::scoped_ptr value(value_prototype->New()); + std::unique_ptr value(value_prototype->New()); string sub_delimiter; DO(ConsumeMessageDelimiter(&sub_delimiter)); DO(ConsumeMessage(value.get(), sub_delimiter)); @@ -1076,7 +1094,7 @@ label_skip_parsing: } else { if (!value->IsInitialized()) { ReportError( - "Value of type \"" + full_type_name + + "Value of type \"" + value_descriptor->full_name() + "\" stored in google.protobuf.Any has missing required fields"); return false; } @@ -1136,7 +1154,7 @@ label_skip_parsing: }; io::ErrorCollector* error_collector_; - TextFormat::Finder* finder_; + const TextFormat::Finder* finder_; ParseInfoTree* parse_info_tree_; ParserErrorCollector tokenizer_error_collector_; io::Tokenizer tokenizer_; @@ -1180,13 +1198,11 @@ class TextFormat::Printer::TextGenerator // Indent text by two spaces. After calling Indent(), two spaces will be // inserted at the beginning of each line of text. Indent() may be called // multiple times to produce deeper indents. - void Indent() { - ++indent_level_; - } + void Indent() override { ++indent_level_; } // Reduces the current indent level by two spaces, or crashes if the indent // level is zero. - void Outdent() { + void Outdent() override { if (indent_level_ == 0 || indent_level_ < initial_indent_level_) { GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent()."; @@ -1197,7 +1213,7 @@ class TextFormat::Printer::TextGenerator } // Print text to the output stream. - void Print(const char* text, size_t size) { + void Print(const char* text, size_t size) override { if (indent_level_ > 0) { size_t pos = 0; // The number of bytes we've written so far. for (size_t i = 0; i < size; i++) { @@ -1294,10 +1310,23 @@ class TextFormat::Printer::TextGenerator }; // =========================================================================== - +// Implementation of the default Finder for extensions. TextFormat::Finder::~Finder() { } +const FieldDescriptor* TextFormat::Finder::FindExtension( + Message* message, const string& name) const { + return DefaultFinderFindExtension(message, name); +} + +const Descriptor* TextFormat::Finder::FindAnyType(const Message& message, + const string& prefix, + const string& name) const { + return DefaultFinderFindAnyType(message, prefix, name); +} + +// =========================================================================== + TextFormat::Parser::Parser() : error_collector_(NULL), finder_(NULL), @@ -1363,8 +1392,9 @@ bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* /* input */, if (!allow_partial_ && !output->IsInitialized()) { std::vector missing_fields; output->FindInitializationErrors(&missing_fields); - parser_impl->ReportError(-1, 0, "Message missing required fields: " + - Join(missing_fields, ", ")); + parser_impl->ReportError(-1, 0, + "Message missing required fields: " + + Join(missing_fields, ", ")); return false; } return true; @@ -1552,6 +1582,12 @@ void TextFormat::FastFieldValuePrinter::PrintBytes( const string& val, BaseTextGenerator* generator) const { PrintString(val, generator); } +void TextFormat::FastFieldValuePrinter::PrintFieldName( + const Message& message, int field_index, int field_count, + const Reflection* reflection, const FieldDescriptor* field, + BaseTextGenerator* generator) const { + PrintFieldName(message, reflection, field, generator); +} void TextFormat::FastFieldValuePrinter::PrintFieldName( const Message& message, const Reflection* reflection, const FieldDescriptor* field, BaseTextGenerator* generator) const { @@ -1639,6 +1675,13 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter { TextFormat::BaseTextGenerator* generator) const { generator->PrintString(delegate_->PrintEnum(val, name)); } + void PrintFieldName(const Message& message, int field_index, int field_count, + const Reflection* reflection, + const FieldDescriptor* field, + TextFormat::BaseTextGenerator* generator) const { + generator->PrintString(delegate_->PrintFieldName( + message, reflection, field)); + } void PrintFieldName(const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextFormat::BaseTextGenerator* generator) const { @@ -1659,7 +1702,7 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter { } private: - google::protobuf::scoped_ptr delegate_; + std::unique_ptr delegate_; }; // Our own specialization: for UTF8 escaped strings. @@ -1688,12 +1731,14 @@ TextFormat::Printer::Printer() hide_unknown_fields_(false), print_message_fields_in_index_order_(false), expand_any_(false), - truncate_string_field_longer_than_(0LL) { + truncate_string_field_longer_than_(0LL), + finder_(NULL) { SetUseUtf8StringEscaping(false); } TextFormat::Printer::~Printer() { STLDeleteValues(&custom_printers_); + STLDeleteValues(&custom_message_printers_); } void TextFormat::Printer::SetUseUtf8StringEscaping(bool as_utf8) { @@ -1718,7 +1763,7 @@ bool TextFormat::Printer::RegisterFieldValuePrinter( return false; } FieldValuePrinterWrapper* const wrapper = - new FieldValuePrinterWrapper(NULL); + new FieldValuePrinterWrapper(nullptr); if (custom_printers_.insert(std::make_pair(field, wrapper)).second) { wrapper->SetDelegate(printer); return true; @@ -1734,6 +1779,13 @@ bool TextFormat::Printer::RegisterFieldValuePrinter( custom_printers_.insert(std::make_pair(field, printer)).second; } +bool TextFormat::Printer::RegisterMessagePrinter( + const Descriptor* descriptor, const MessagePrinter* printer) { + return descriptor != nullptr && printer != nullptr && + custom_message_printers_.insert(std::make_pair(descriptor, printer)) + .second; +} + bool TextFormat::Printer::PrintToString(const Message& message, string* output) const { GOOGLE_DCHECK(output) << "output specified is NULL"; @@ -1777,10 +1829,19 @@ bool TextFormat::Printer::PrintUnknownFields( namespace { // Comparison functor for sorting FieldDescriptors by field index. +// Normal fields have higher precedence than extensions. struct FieldIndexSorter { bool operator()(const FieldDescriptor* left, const FieldDescriptor* right) const { - return left->index() < right->index(); + if (left->is_extension() && right->is_extension()) { + return left->number() < right->number(); + } else if (left->is_extension()) { + return false; + } else if (right->is_extension()) { + return true; + } else { + return left->index() < right->index(); + } } }; @@ -1799,21 +1860,22 @@ bool TextFormat::Printer::PrintAny(const Message& message, // Extract the full type name from the type_url field. const string& type_url = reflection->GetString(message, type_url_field); + string url_prefix; string full_type_name; - if (!internal::ParseAnyTypeUrl(type_url, &full_type_name)) { + if (!internal::ParseAnyTypeUrl(type_url, &url_prefix, &full_type_name)) { return false; } // Print the "value" in text. const google::protobuf::Descriptor* value_descriptor = - message.GetDescriptor()->file()->pool()->FindMessageTypeByName( - full_type_name); + finder_ ? finder_->FindAnyType(message, url_prefix, full_type_name) + : DefaultFinderFindAnyType(message, url_prefix, full_type_name); if (value_descriptor == NULL) { GOOGLE_LOG(WARNING) << "Proto type " << type_url << " not found"; return false; } DynamicMessageFactory factory; - google::protobuf::scoped_ptr value_message( + std::unique_ptr value_message( factory.GetPrototype(value_descriptor)->New()); string serialized_value = reflection->GetString(message, value_field); if (!value_message->ParseFromString(serialized_value)) { @@ -1836,6 +1898,11 @@ bool TextFormat::Printer::PrintAny(const Message& message, void TextFormat::Printer::Print(const Message& message, TextGenerator* generator) const { const Descriptor* descriptor = message.GetDescriptor(); + auto itr = custom_message_printers_.find(descriptor); + if (itr != custom_message_printers_.end()) { + itr->second->Print(message, single_line_mode_, generator); + return; + } const Reflection* reflection = message.GetReflection(); if (descriptor->full_name() == internal::kAnyFullTypeName && expand_any_ && PrintAny(message, generator)) { @@ -1859,7 +1926,6 @@ void TextFormat::Printer::PrintFieldValueToString( const FieldDescriptor* field, int index, string* output) const { - GOOGLE_DCHECK(output) << "output specified is NULL"; output->clear(); @@ -1898,7 +1964,7 @@ void TextFormat::Printer::PrintField(const Message& message, for (int j = 0; j < count; ++j) { const int field_index = field->is_repeated() ? j : -1; - PrintFieldName(message, reflection, field, generator); + PrintFieldName(message, field_index, count, reflection, field, generator); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { const FastFieldValuePrinter* printer = FindWithDefault( @@ -1932,9 +1998,9 @@ void TextFormat::Printer::PrintShortRepeatedField( const Message& message, const Reflection* reflection, const FieldDescriptor* field, TextGenerator* generator) const { // Print primitive repeated field in short form. - PrintFieldName(message, reflection, field, generator); - int size = reflection->FieldSize(message, field); + PrintFieldName(message, /*field_index=*/-1, /*field_count=*/size, reflection, + field, generator); generator->PrintLiteral(": ["); for (int i = 0; i < size; i++) { if (i > 0) generator->PrintLiteral(", "); @@ -1948,6 +2014,7 @@ void TextFormat::Printer::PrintShortRepeatedField( } void TextFormat::Printer::PrintFieldName(const Message& message, + int field_index, int field_count, const Reflection* reflection, const FieldDescriptor* field, TextGenerator* generator) const { @@ -1960,7 +2027,8 @@ void TextFormat::Printer::PrintFieldName(const Message& message, const FastFieldValuePrinter* printer = FindWithDefault( custom_printers_, field, default_field_value_printer_.get()); - printer->PrintFieldName(message, reflection, field, generator); + printer->PrintFieldName(message, field_index, field_count, reflection, field, + generator); } void TextFormat::Printer::PrintFieldValue(const Message& message, diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h index a2670d6bb4..d6f3e16bfd 100644 --- a/src/google/protobuf/text_format.h +++ b/src/google/protobuf/text_format.h @@ -40,9 +40,6 @@ #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -97,6 +94,10 @@ class LIBPROTOBUF_EXPORT TextFormat { class LIBPROTOBUF_EXPORT BaseTextGenerator { public: virtual ~BaseTextGenerator(); + + virtual void Indent() {} + virtual void Outdent() {} + // Print text to the output stream. virtual void Print(const char* text, size_t size) = 0; @@ -129,6 +130,10 @@ class LIBPROTOBUF_EXPORT TextFormat { BaseTextGenerator* generator) const; virtual void PrintEnum(int32 val, const string& name, BaseTextGenerator* generator) const; + virtual void PrintFieldName(const Message& message, int field_index, + int field_count, const Reflection* reflection, + const FieldDescriptor* field, + BaseTextGenerator* generator) const; virtual void PrintFieldName(const Message& message, const Reflection* reflection, const FieldDescriptor* field, @@ -176,6 +181,40 @@ class LIBPROTOBUF_EXPORT TextFormat { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldValuePrinter); }; + class LIBPROTOBUF_EXPORT MessagePrinter { + public: + MessagePrinter() {} + virtual ~MessagePrinter() {} + virtual void Print(const Message& message, bool single_line_mode, + BaseTextGenerator* generator) const = 0; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessagePrinter); + }; + + // Interface that Printers or Parsers can use to find extensions, or types + // referenced in Any messages. + class LIBPROTOBUF_EXPORT Finder { + public: + virtual ~Finder(); + + // Try to find an extension of *message by fully-qualified field + // name. Returns NULL if no extension is known for this name or number. + // The base implementation uses the extensions already known by the message. + virtual const FieldDescriptor* FindExtension( + Message* message, + const string& name) const; + + // Find the message type for an Any proto. + // Returns NULL if no message is known for this name. + // The base implementation only accepts prefixes of type.googleprod.com/ or + // type.googleapis.com/, and searches the DescriptorPool of the parent + // message. + virtual const Descriptor* FindAnyType(const Message& message, + const string& prefix, + const string& name) const; + }; + // Class for those users which require more fine-grained control over how // a protobuffer message is printed out. class LIBPROTOBUF_EXPORT Printer { @@ -251,9 +290,11 @@ class LIBPROTOBUF_EXPORT TextFormat { hide_unknown_fields_ = hide; } - // If print_message_fields_in_index_order is true, print fields of a proto - // message using the order defined in source code instead of the field - // number. By default, use the field number order. + // If print_message_fields_in_index_order is true, fields of a proto message + // will be printed using the order defined in source code instead of the + // field number, extensions will be printed at the end of the message + // and their relative order is determined by the extension number. + // By default, use the field number order. void SetPrintMessageFieldsInIndexOrder( bool print_message_fields_in_index_order) { print_message_fields_in_index_order_ = @@ -271,6 +312,11 @@ class LIBPROTOBUF_EXPORT TextFormat { expand_any_ = expand; } + // Set how parser finds message for Any payloads. + void SetFinder(Finder* finder) { + finder_ = finder; + } + // If non-zero, we truncate all string fields that are longer than this // threshold. This is useful when the proto message has very long strings, // e.g., dump of encoded image file. @@ -293,6 +339,13 @@ class LIBPROTOBUF_EXPORT TextFormat { bool RegisterFieldValuePrinter(const FieldDescriptor* field, const FastFieldValuePrinter* printer); + // Register a custom message-specific MessagePrinter for messages with a + // particular Descriptor. + // Returns "true" if the registration succeeded, or "false" if there is + // already a printer for that Descriptor. + bool RegisterMessagePrinter(const Descriptor* descriptor, + const MessagePrinter* printer); + private: // Forward declaration of an internal class used to print the text // output to the OutputStream (see text_format.cc for implementation). @@ -315,7 +368,8 @@ class LIBPROTOBUF_EXPORT TextFormat { // Print the name of a field -- i.e. everything that comes before the // ':' for a single name/value pair. - void PrintFieldName(const Message& message, const Reflection* reflection, + void PrintFieldName(const Message& message, int field_index, + int field_count, const Reflection* reflection, const FieldDescriptor* field, TextGenerator* generator) const; @@ -349,10 +403,16 @@ class LIBPROTOBUF_EXPORT TextFormat { int64 truncate_string_field_longer_than_; - google::protobuf::scoped_ptr default_field_value_printer_; + std::unique_ptr default_field_value_printer_; typedef std::map CustomPrinterMap; CustomPrinterMap custom_printers_; + + typedef std::map + CustomMessagePrinterMap; + CustomMessagePrinterMap custom_message_printers_; + + const Finder* finder_; }; // Parses a text-format protocol message from the given input stream to @@ -387,20 +447,6 @@ class LIBPROTOBUF_EXPORT TextFormat { const FieldDescriptor* field, Message* message); - // Interface that TextFormat::Parser can use to find extensions. - // This class may be extended in the future to find more information - // like fields, etc. - class LIBPROTOBUF_EXPORT Finder { - public: - virtual ~Finder(); - - // Try to find an extension of *message by fully-qualified field - // name. Returns NULL if no extension is known for this name or number. - virtual const FieldDescriptor* FindExtension( - Message* message, - const string& name) const = 0; - }; - // A location in the parsed text. struct ParseLocation { int line; @@ -524,7 +570,7 @@ class LIBPROTOBUF_EXPORT TextFormat { ParserImpl* parser_impl); io::ErrorCollector* error_collector_; - Finder* finder_; + const Finder* finder_; ParseInfoTree* parse_info_tree_; bool allow_partial_; bool allow_case_insensitive_field_; diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc index f823bcb2cc..544c37e258 100644 --- a/src/google/protobuf/text_format_unittest.cc +++ b/src/google/protobuf/text_format_unittest.cc @@ -38,9 +38,6 @@ #include #include #include -#ifndef _SHARED_PTR_H -#include -#endif #include #include @@ -474,14 +471,14 @@ TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) { // NULL printer. EXPECT_FALSE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), - static_cast(NULL))); + static_cast(nullptr))); EXPECT_FALSE(printer.RegisterFieldValuePrinter( message.GetDescriptor()->FindFieldByName("optional_int32"), - static_cast(NULL))); + static_cast(nullptr))); // Because registration fails, the ownership of this printer is never taken. TextFormat::FieldValuePrinter my_field_printer; // NULL field - EXPECT_FALSE(printer.RegisterFieldValuePrinter(NULL, &my_field_printer)); + EXPECT_FALSE(printer.RegisterFieldValuePrinter(nullptr, &my_field_printer)); } class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter { @@ -564,6 +561,143 @@ TEST_F(TextFormatTest, CustomPrinterForMultilineComments) { text); } +// Achieve effects similar to SetUseShortRepeatedPrimitives for messages, using +// RegisterFieldValuePrinter. Use this to test the version of PrintFieldName +// that accepts repeated field index and count. +class CompactRepeatedFieldPrinter : public TextFormat::FastFieldValuePrinter { + public: + void PrintFieldName(const Message& message, int field_index, int field_count, + const Reflection* reflection, + const FieldDescriptor* field, + TextFormat::BaseTextGenerator* generator) const override { + if (field_index == 0 || field_index == -1) { + generator->PrintString(field->name()); + } + } + void PrintMessageStart( + const Message& message, int field_index, int field_count, + bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { + if (field_index == 0 || field_index == -1) { + if (single_line_mode) { + generator->PrintLiteral(" { "); + } else { + generator->PrintLiteral(" {\n"); + } + } + } + void PrintMessageEnd( + const Message& message, int field_index, int field_count, + bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { + if (field_index == field_count - 1 || field_index == -1) { + if (single_line_mode) { + generator->PrintLiteral("} "); + } else { + generator->PrintLiteral("}\n"); + } + } + } +}; + +TEST_F(TextFormatTest, CompactRepeatedFieldPrinter) { + TextFormat::Printer printer; + ASSERT_TRUE(printer.RegisterFieldValuePrinter( + unittest::TestAllTypes::default_instance() + .descriptor() + ->FindFieldByNumber( + unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber), + new CompactRepeatedFieldPrinter)); + + protobuf_unittest::TestAllTypes message; + message.add_repeated_nested_message()->set_bb(1); + message.add_repeated_nested_message()->set_bb(2); + message.add_repeated_nested_message()->set_bb(3); + + string text; + ASSERT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ( + "repeated_nested_message {\n" + " bb: 1\n" + " bb: 2\n" + " bb: 3\n" + "}\n", + text); +} + +// Print strings into multiple line, with indention. Use this to test +// BaseTextGenerator::Indent and BaseTextGenerator::Outdent. +class MultilineStringPrinter : public TextFormat::FastFieldValuePrinter { + public: + void PrintString(const string& val, + TextFormat::BaseTextGenerator* generator) const override { + generator->Indent(); + int last_pos = 0; + int newline_pos = val.find('\n'); + while (newline_pos != string::npos) { + generator->PrintLiteral("\n"); + TextFormat::FastFieldValuePrinter::PrintString( + val.substr(last_pos, newline_pos + 1 - last_pos), generator); + last_pos = newline_pos + 1; + newline_pos = val.find('\n', last_pos); + } + if (last_pos < val.size()) { + generator->PrintLiteral("\n"); + TextFormat::FastFieldValuePrinter::PrintString(val.substr(last_pos), + generator); + } + generator->Outdent(); + } +}; + +TEST_F(TextFormatTest, MultilineStringPrinter) { + TextFormat::Printer printer; + ASSERT_TRUE(printer.RegisterFieldValuePrinter( + unittest::TestAllTypes::default_instance() + .descriptor() + ->FindFieldByNumber( + unittest::TestAllTypes::kOptionalStringFieldNumber), + new MultilineStringPrinter)); + + protobuf_unittest::TestAllTypes message; + message.set_optional_string("first line\nsecond line\nthird line"); + + string text; + ASSERT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ( + "optional_string: \n" + " \"first line\\n\"\n" + " \"second line\\n\"\n" + " \"third line\"\n", + text); +} + +class CustomNestedMessagePrinter : public TextFormat::MessagePrinter { + public: + CustomNestedMessagePrinter() {} + ~CustomNestedMessagePrinter() override {} + void Print(const Message& message, bool single_line_mode, + TextFormat::BaseTextGenerator* generator) const override { + generator->PrintLiteral("custom"); + } +}; + +TEST_F(TextFormatTest, CustomMessagePrinter) { + TextFormat::Printer printer; + printer.RegisterMessagePrinter( + unittest::TestAllTypes::NestedMessage::default_instance().descriptor(), + new CustomNestedMessagePrinter); + + unittest::TestAllTypes message; + string text; + EXPECT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ("", text); + + message.mutable_optional_nested_message()->set_bb(1); + EXPECT_TRUE(printer.PrintToString(message, &text)); + EXPECT_EQ("optional_nested_message {\n custom}\n", text); +} + TEST_F(TextFormatTest, ParseBasic) { io::ArrayInputStream input_stream(proto_debug_string_.data(), proto_debug_string_.size()); @@ -1031,29 +1165,93 @@ TEST_F(TextFormatTest, ParseExotic) { TEST_F(TextFormatTest, PrintFieldsInIndexOrder) { protobuf_unittest::TestFieldOrderings message; // Fields are listed in index order instead of field number. - message.set_my_string("Test String"); // Field number 11 + message.set_my_string("str"); // Field number 11 message.set_my_int(12345); // Field number 1 message.set_my_float(0.999); // Field number 101 + // Extensions are listed based on the order of extension number. + // Extension number 12. + message + .MutableExtension( + protobuf_unittest::TestExtensionOrderings2::test_ext_orderings2) + ->set_my_string("ext_str2"); + // Extension number 13. + message + .MutableExtension( + protobuf_unittest::TestExtensionOrderings1::test_ext_orderings1) + ->set_my_string("ext_str1"); + // Extension number 14. + message + .MutableExtension(protobuf_unittest::TestExtensionOrderings2:: + TestExtensionOrderings3::test_ext_orderings3) + ->set_my_string("ext_str3"); + // Extension number 50. + *message.MutableExtension(protobuf_unittest::my_extension_string) = "ext_str0"; + TextFormat::Printer printer; string text; // By default, print in field number order. + // my_int: 12345 + // my_string: "str" + // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] { + // my_string: "ext_str2" + // } + // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] { + // my_string: "ext_str1" + // } + // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3] + // { + // my_string: "ext_str3" + // } + // [protobuf_unittest.my_extension_string]: "ext_str0" + // my_float: 0.999 printer.PrintToString(message, &text); - EXPECT_EQ("my_int: 12345\nmy_string: \"Test String\"\nmy_float: 0.999\n", - text); + EXPECT_EQ( + "my_int: 12345\nmy_string: " + "\"str\"\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] " + "{\n my_string: " + "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_" + "orderings1] {\n my_string: " + "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2." + "TestExtensionOrderings3.test_ext_orderings3] {\n my_string: " + "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: " + "\"ext_str0\"\nmy_float: 0.999\n", + text); // Print in index order. + // my_string: "str" + // my_int: 12345 + // my_float: 0.999 + // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] { + // my_string: "ext_str2" + // } + // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] { + // my_string: "ext_str1" + // } + // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3] + // { + // my_string: "ext_str3" + // } + // [protobuf_unittest.my_extension_string]: "ext_str0" printer.SetPrintMessageFieldsInIndexOrder(true); printer.PrintToString(message, &text); - EXPECT_EQ("my_string: \"Test String\"\nmy_int: 12345\nmy_float: 0.999\n", - text); + EXPECT_EQ( + "my_string: \"str\"\nmy_int: 12345\nmy_float: " + "0.999\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] " + "{\n my_string: " + "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_" + "orderings1] {\n my_string: " + "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2." + "TestExtensionOrderings3.test_ext_orderings3] {\n my_string: " + "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: \"ext_str0\"\n", + text); } class TextFormatParserTest : public testing::Test { protected: void ExpectFailure(const string& input, const string& message, int line, int col) { - google::protobuf::scoped_ptr proto(new unittest::TestAllTypes); + std::unique_ptr proto(new unittest::TestAllTypes); ExpectFailure(input, message, line, col, proto.get()); } @@ -1114,7 +1312,7 @@ class TextFormatParserTest : public testing::Test { }; TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { - google::protobuf::scoped_ptr message(new unittest::TestAllTypes); + std::unique_ptr message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); string stringData = @@ -1179,7 +1377,7 @@ TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) { } TEST_F(TextFormatParserTest, ParseFieldValueFromString) { - google::protobuf::scoped_ptr message(new unittest::TestAllTypes); + std::unique_ptr message(new unittest::TestAllTypes); const Descriptor* d = message->GetDescriptor(); #define EXPECT_FIELD(name, value, valuestring) \ diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc index f57d4d6699..8e6b5f23f8 100644 --- a/src/google/protobuf/timestamp.pb.cc +++ b/src/google/protobuf/timestamp.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,7 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + namespace google { namespace protobuf { class TimestampDefaultTypeInternal { @@ -29,14 +29,9 @@ class TimestampDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto { -void InitDefaultsTimestampImpl() { +static void InitDefaultsTimestamp() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS { void* ptr = &::google::protobuf::_Timestamp_default_instance_; new (ptr) ::google::protobuf::Timestamp(); @@ -45,9 +40,11 @@ void InitDefaultsTimestampImpl() { ::google::protobuf::Timestamp::InitAsDefaultInstance(); } -void InitDefaultsTimestamp() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTimestampImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTimestamp}, {}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Timestamp.base); } ::google::protobuf::Metadata file_level_metadata[1]; @@ -71,15 +68,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -105,8 +101,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -129,24 +125,22 @@ const int Timestamp::kNanosFieldNumber; Timestamp::Timestamp() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Timestamp) } Timestamp::Timestamp(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp) } Timestamp::Timestamp(const Timestamp& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&seconds_, &from.seconds_, static_cast(reinterpret_cast(&nanos_) - @@ -158,7 +152,6 @@ void Timestamp::SharedCtor() { ::memset(&seconds_, 0, static_cast( reinterpret_cast(&nanos_) - reinterpret_cast(&seconds_)) + sizeof(nanos_)); - _cached_size_ = 0; } Timestamp::~Timestamp() { @@ -177,9 +170,7 @@ void Timestamp::ArenaDtor(void* object) { void Timestamp::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Timestamp::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Timestamp::descriptor() { ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce(); @@ -187,7 +178,7 @@ const ::google::protobuf::Descriptor* Timestamp::descriptor() { } const Timestamp& Timestamp::default_instance() { - ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestamp(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base); return *internal_default_instance(); } @@ -210,7 +201,7 @@ bool Timestamp::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Timestamp) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -334,9 +325,7 @@ size_t Timestamp::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -412,7 +401,6 @@ void Timestamp::InternalSwap(Timestamp* other) { swap(seconds_, other->seconds_); swap(nanos_, other->nanos_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Timestamp::GetMetadata() const { @@ -426,7 +414,7 @@ void Timestamp::InternalSwap(Timestamp* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMessage< ::google::protobuf::Timestamp >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMaybeMessage< ::google::protobuf::Timestamp >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Timestamp >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h index a0f9605ca7..f73e75b3ee 100644 --- a/src/google/protobuf/timestamp.pb.h +++ b/src/google/protobuf/timestamp.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto -#ifndef PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto #include @@ -24,12 +24,14 @@ #include #include #include +#include #include #include #include // IWYU pragma: export #include // IWYU pragma: export #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftimestamp_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto { // Internal implementation detail -- do not use these members. @@ -42,11 +44,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsTimestampImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsTimestamp(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsTimestamp(); -} } // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto namespace google { namespace protobuf { @@ -57,7 +54,7 @@ LIBPROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instan } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMessage< ::google::protobuf::Timestamp>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMaybeMessage<::google::protobuf::Timestamp>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -91,10 +88,10 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -105,7 +102,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro return reinterpret_cast( &_Timestamp_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Timestamp* other); @@ -116,32 +113,33 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline Timestamp* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Timestamp* New() const final { + return CreateMaybeMessage(NULL); } - Timestamp* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Timestamp* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Timestamp& from); void MergeFrom(const Timestamp& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Timestamp* other); protected: explicit Timestamp(::google::protobuf::Arena* arena); @@ -157,7 +155,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -184,9 +182,8 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro typedef void DestructorSkippable_; ::google::protobuf::int64 seconds_; ::google::protobuf::int32 nanos_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::InitDefaultsTimestampImpl(); }; // =================================================================== @@ -238,4 +235,4 @@ inline void Timestamp::set_nanos(::google::protobuf::int32 value) { // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_google_2fprotobuf_2ftimestamp_2eproto_INCLUDED +#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc index a2edabb69d..130af52a30 100644 --- a/src/google/protobuf/type.pb.cc +++ b/src/google/protobuf/type.pb.cc @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,18 @@ #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) + +namespace protobuf_google_2fprotobuf_2fany_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Any; +} // namespace protobuf_google_2fprotobuf_2fany_2eproto +namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext; +} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto +namespace protobuf_google_2fprotobuf_2ftype_2eproto { +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Field; +extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option; +} // namespace protobuf_google_2fprotobuf_2ftype_2eproto namespace google { namespace protobuf { class TypeDefaultTypeInternal { @@ -49,17 +60,9 @@ class OptionDefaultTypeInternal { } // namespace protobuf } // namespace google namespace protobuf_google_2fprotobuf_2ftype_2eproto { -void InitDefaultsTypeImpl() { +static void InitDefaultsType() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); { void* ptr = &::google::protobuf::_Type_default_instance_; new (ptr) ::google::protobuf::Type(); @@ -68,20 +71,15 @@ void InitDefaultsTypeImpl() { ::google::protobuf::Type::InitAsDefaultInstance(); } -void InitDefaultsType() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsTypeImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Type = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsType}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base, + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base,}}; -void InitDefaultsFieldImpl() { +static void InitDefaultsField() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); { void* ptr = &::google::protobuf::_Field_default_instance_; new (ptr) ::google::protobuf::Field(); @@ -90,22 +88,13 @@ void InitDefaultsFieldImpl() { ::google::protobuf::Field::InitAsDefaultInstance(); } -void InitDefaultsField() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFieldImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Field = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsField}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; -void InitDefaultsEnumImpl() { +static void InitDefaultsEnum() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext(); { void* ptr = &::google::protobuf::_Enum_default_instance_; new (ptr) ::google::protobuf::Enum(); @@ -114,20 +103,15 @@ void InitDefaultsEnumImpl() { ::google::protobuf::Enum::InitAsDefaultInstance(); } -void InitDefaultsEnum() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Enum = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnum}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base, + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, + &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base,}}; -void InitDefaultsEnumValueImpl() { +static void InitDefaultsEnumValue() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); { void* ptr = &::google::protobuf::_EnumValue_default_instance_; new (ptr) ::google::protobuf::EnumValue(); @@ -136,20 +120,13 @@ void InitDefaultsEnumValueImpl() { ::google::protobuf::EnumValue::InitAsDefaultInstance(); } -void InitDefaultsEnumValue() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsEnumValueImpl); -} +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValue}, { + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; -void InitDefaultsOptionImpl() { +static void InitDefaultsOption() { GOOGLE_PROTOBUF_VERIFY_VERSION; -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - ::google::protobuf::internal::InitProtobufDefaultsForceUnique(); -#else - ::google::protobuf::internal::InitProtobufDefaults(); -#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny(); { void* ptr = &::google::protobuf::_Option_default_instance_; new (ptr) ::google::protobuf::Option(); @@ -158,9 +135,16 @@ void InitDefaultsOptionImpl() { ::google::protobuf::Option::InitAsDefaultInstance(); } -void InitDefaultsOption() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &InitDefaultsOptionImpl); +LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Option = + {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOption}, { + &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base,}}; + +void InitDefaults() { + ::google::protobuf::internal::InitSCC(&scc_info_Type.base); + ::google::protobuf::internal::InitSCC(&scc_info_Field.base); + ::google::protobuf::internal::InitSCC(&scc_info_Enum.base); + ::google::protobuf::internal::InitSCC(&scc_info_EnumValue.base); + ::google::protobuf::internal::InitSCC(&scc_info_Option.base); } ::google::protobuf::Metadata file_level_metadata[5]; @@ -237,15 +221,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = { void protobuf_AssignDescriptors() { AddDescriptors(); - ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( - "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets, factory, + "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; @@ -307,8 +290,8 @@ void AddDescriptorsImpl() { } void AddDescriptors() { - static GOOGLE_PROTOBUF_DECLARE_ONCE(once); - ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); + static ::google::protobuf::internal::once_flag once; + ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { @@ -450,9 +433,8 @@ const int Type::kSyntaxFieldNumber; Type::Type() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Type) } @@ -462,7 +444,7 @@ Type::Type(::google::protobuf::Arena* arena) fields_(arena), oneofs_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Type) @@ -472,8 +454,7 @@ Type::Type(const Type& from) _internal_metadata_(NULL), fields_(from.fields_), oneofs_(from.oneofs_), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -494,7 +475,6 @@ void Type::SharedCtor() { ::memset(&source_context_, 0, static_cast( reinterpret_cast(&syntax_) - reinterpret_cast(&source_context_)) + sizeof(syntax_)); - _cached_size_ = 0; } Type::~Type() { @@ -515,9 +495,7 @@ void Type::ArenaDtor(void* object) { void Type::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Type::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Type::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -525,7 +503,7 @@ const ::google::protobuf::Descriptor* Type::descriptor() { } const Type& Type::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsType(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base); return *internal_default_instance(); } @@ -554,7 +532,7 @@ bool Type::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Type) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -709,7 +687,7 @@ void Type::SerializeWithCachedSizes( // .google.protobuf.SourceContext source_context = 5; if (this->has_source_context()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *source_context_, output); + 5, this->_internal_source_context(), output); } // .google.protobuf.Syntax syntax = 6; @@ -773,7 +751,7 @@ void Type::SerializeWithCachedSizes( if (this->has_source_context()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 5, *source_context_, deterministic, target); + 5, this->_internal_source_context(), deterministic, target); } // .google.protobuf.Syntax syntax = 6; @@ -850,9 +828,7 @@ size_t Type::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -934,11 +910,11 @@ void Type::InternalSwap(Type* other) { CastToBase(&fields_)->InternalSwap(CastToBase(&other->fields_)); oneofs_.InternalSwap(CastToBase(&other->oneofs_)); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(source_context_, other->source_context_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Type::GetMetadata() const { @@ -966,9 +942,8 @@ const int Field::kDefaultValueFieldNumber; Field::Field() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Field) } @@ -976,7 +951,7 @@ Field::Field(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Field) @@ -984,8 +959,7 @@ Field::Field(::google::protobuf::Arena* arena) Field::Field(const Field& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -1021,7 +995,6 @@ void Field::SharedCtor() { ::memset(&kind_, 0, static_cast( reinterpret_cast(&packed_) - reinterpret_cast(&kind_)) + sizeof(packed_)); - _cached_size_ = 0; } Field::~Field() { @@ -1044,9 +1017,7 @@ void Field::ArenaDtor(void* object) { void Field::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Field::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Field::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1054,7 +1025,7 @@ const ::google::protobuf::Descriptor* Field::descriptor() { } const Field& Field::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsField(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base); return *internal_default_instance(); } @@ -1082,7 +1053,7 @@ bool Field::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Field) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1517,9 +1488,7 @@ size_t Field::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -1615,17 +1584,20 @@ void Field::UnsafeArenaSwap(Field* other) { void Field::InternalSwap(Field* other) { using std::swap; CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); - type_url_.Swap(&other->type_url_); - json_name_.Swap(&other->json_name_); - default_value_.Swap(&other->default_value_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + json_name_.Swap(&other->json_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); + default_value_.Swap(&other->default_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(kind_, other->kind_); swap(cardinality_, other->cardinality_); swap(number_, other->number_); swap(oneof_index_, other->oneof_index_); swap(packed_, other->packed_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Field::GetMetadata() const { @@ -1669,9 +1641,8 @@ const int Enum::kSyntaxFieldNumber; Enum::Enum() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Enum) } @@ -1680,7 +1651,7 @@ Enum::Enum(::google::protobuf::Arena* arena) _internal_metadata_(arena), enumvalue_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Enum) @@ -1689,8 +1660,7 @@ Enum::Enum(const Enum& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), enumvalue_(from.enumvalue_), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -1711,7 +1681,6 @@ void Enum::SharedCtor() { ::memset(&source_context_, 0, static_cast( reinterpret_cast(&syntax_) - reinterpret_cast(&source_context_)) + sizeof(syntax_)); - _cached_size_ = 0; } Enum::~Enum() { @@ -1732,9 +1701,7 @@ void Enum::ArenaDtor(void* object) { void Enum::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Enum::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Enum::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -1742,7 +1709,7 @@ const ::google::protobuf::Descriptor* Enum::descriptor() { } const Enum& Enum::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnum(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base); return *internal_default_instance(); } @@ -1770,7 +1737,7 @@ bool Enum::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Enum) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -1898,7 +1865,7 @@ void Enum::SerializeWithCachedSizes( // .google.protobuf.SourceContext source_context = 4; if (this->has_source_context()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, *source_context_, output); + 4, this->_internal_source_context(), output); } // .google.protobuf.Syntax syntax = 5; @@ -1952,7 +1919,7 @@ void Enum::SerializeWithCachedSizes( if (this->has_source_context()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 4, *source_context_, deterministic, target); + 4, this->_internal_source_context(), deterministic, target); } // .google.protobuf.Syntax syntax = 5; @@ -2021,9 +1988,7 @@ size_t Enum::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2103,11 +2068,11 @@ void Enum::InternalSwap(Enum* other) { using std::swap; CastToBase(&enumvalue_)->InternalSwap(CastToBase(&other->enumvalue_)); CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(source_context_, other->source_context_); swap(syntax_, other->syntax_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Enum::GetMetadata() const { @@ -2128,9 +2093,8 @@ const int EnumValue::kOptionsFieldNumber; EnumValue::EnumValue() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.EnumValue) } @@ -2138,7 +2102,7 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), options_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValue) @@ -2146,8 +2110,7 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena) EnumValue::EnumValue(const EnumValue& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), - options_(from.options_), - _cached_size_(0) { + options_(from.options_) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -2161,7 +2124,6 @@ EnumValue::EnumValue(const EnumValue& from) void EnumValue::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); number_ = 0; - _cached_size_ = 0; } EnumValue::~EnumValue() { @@ -2181,9 +2143,7 @@ void EnumValue::ArenaDtor(void* object) { void EnumValue::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void EnumValue::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* EnumValue::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2191,7 +2151,7 @@ const ::google::protobuf::Descriptor* EnumValue::descriptor() { } const EnumValue& EnumValue::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValue(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base); return *internal_default_instance(); } @@ -2214,7 +2174,7 @@ bool EnumValue::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.EnumValue) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2391,9 +2351,7 @@ size_t EnumValue::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2468,10 +2426,10 @@ void EnumValue::UnsafeArenaSwap(EnumValue* other) { void EnumValue::InternalSwap(EnumValue* other) { using std::swap; CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(number_, other->number_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata EnumValue::GetMetadata() const { @@ -2512,24 +2470,22 @@ const int Option::kValueFieldNumber; Option::Option() : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); - } + ::google::protobuf::internal::InitSCC( + &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base); SharedCtor(); // @@protoc_insertion_point(constructor:google.protobuf.Option) } Option::Option(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:google.protobuf.Option) } Option::Option(const Option& from) : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _cached_size_(0) { + _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { @@ -2547,7 +2503,6 @@ Option::Option(const Option& from) void Option::SharedCtor() { name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_ = NULL; - _cached_size_ = 0; } Option::~Option() { @@ -2568,9 +2523,7 @@ void Option::ArenaDtor(void* object) { void Option::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Option::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Option::descriptor() { ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce(); @@ -2578,7 +2531,7 @@ const ::google::protobuf::Descriptor* Option::descriptor() { } const Option& Option::default_instance() { - ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption(); + ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base); return *internal_default_instance(); } @@ -2603,7 +2556,7 @@ bool Option::MergePartialFromCodedStream( ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.protobuf.Option) for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); + ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { @@ -2674,7 +2627,7 @@ void Option::SerializeWithCachedSizes( // .google.protobuf.Any value = 2; if (this->has_value()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, *value_, output); + 2, this->_internal_value(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -2706,7 +2659,7 @@ void Option::SerializeWithCachedSizes( if (this->has_value()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( - 2, *value_, deterministic, target); + 2, this->_internal_value(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { @@ -2741,9 +2694,7 @@ size_t Option::ByteSizeLong() const { } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); + SetCachedSize(cached_size); return total_size; } @@ -2816,10 +2767,10 @@ void Option::UnsafeArenaSwap(Option* other) { } void Option::InternalSwap(Option* other) { using std::swap; - name_.Swap(&other->name_); + name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), + GetArenaNoVirtual()); swap(value_, other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); - swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Option::GetMetadata() const { @@ -2833,19 +2784,19 @@ void Option::InternalSwap(Option* other) { } // namespace google namespace google { namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Type* Arena::CreateMessage< ::google::protobuf::Type >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Type* Arena::CreateMaybeMessage< ::google::protobuf::Type >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Type >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Field* Arena::CreateMessage< ::google::protobuf::Field >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Field* Arena::CreateMaybeMessage< ::google::protobuf::Field >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Field >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Enum* Arena::CreateMessage< ::google::protobuf::Enum >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Enum* Arena::CreateMaybeMessage< ::google::protobuf::Enum >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Enum >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValue* Arena::CreateMessage< ::google::protobuf::EnumValue >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValue* Arena::CreateMaybeMessage< ::google::protobuf::EnumValue >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::EnumValue >(arena); } -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Option* Arena::CreateMessage< ::google::protobuf::Option >(Arena* arena) { +template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Option* Arena::CreateMaybeMessage< ::google::protobuf::Option >(Arena* arena) { return Arena::CreateMessageInternal< ::google::protobuf::Option >(arena); } } // namespace protobuf diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h index 49bed8eed6..69af6c2e91 100644 --- a/src/google/protobuf/type.pb.h +++ b/src/google/protobuf/type.pb.h @@ -1,8 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto -#ifndef PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED -#define PROTOBUF_google_2fprotobuf_2ftype_2eproto_INCLUDED +#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto +#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto #include @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: export @@ -33,6 +34,7 @@ #include #include // @@protoc_insertion_point(includes) +#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto LIBPROTOBUF_EXPORT namespace protobuf_google_2fprotobuf_2ftype_2eproto { // Internal implementation detail -- do not use these members. @@ -45,23 +47,6 @@ struct LIBPROTOBUF_EXPORT TableStruct { static const ::google::protobuf::uint32 offsets[]; }; void LIBPROTOBUF_EXPORT AddDescriptors(); -void LIBPROTOBUF_EXPORT InitDefaultsTypeImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsType(); -void LIBPROTOBUF_EXPORT InitDefaultsFieldImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsField(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnum(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValueImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsEnumValue(); -void LIBPROTOBUF_EXPORT InitDefaultsOptionImpl(); -void LIBPROTOBUF_EXPORT InitDefaultsOption(); -inline void LIBPROTOBUF_EXPORT InitDefaults() { - InitDefaultsType(); - InitDefaultsField(); - InitDefaultsEnum(); - InitDefaultsEnumValue(); - InitDefaultsOption(); -} } // namespace protobuf_google_2fprotobuf_2ftype_2eproto namespace google { namespace protobuf { @@ -84,11 +69,11 @@ LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_; } // namespace google namespace google { namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMessage< ::google::protobuf::Enum>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMessage< ::google::protobuf::EnumValue>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMessage< ::google::protobuf::Field>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMessage< ::google::protobuf::Option>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMessage< ::google::protobuf::Type>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMaybeMessage<::google::protobuf::Enum>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMaybeMessage<::google::protobuf::EnumValue>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMaybeMessage<::google::protobuf::Field>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMaybeMessage<::google::protobuf::Option>(Arena*); +template<> LIBPROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMaybeMessage<::google::protobuf::Type>(Arena*); } // namespace protobuf } // namespace google namespace google { @@ -204,10 +189,10 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -218,7 +203,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i return reinterpret_cast( &_Type_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 0; void UnsafeArenaSwap(Type* other); @@ -229,32 +214,33 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i // implements Message ---------------------------------------------- - inline Type* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Type* New() const final { + return CreateMaybeMessage(NULL); } - Type* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Type* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Type& from); void MergeFrom(const Type& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Type* other); protected: explicit Type(::google::protobuf::Arena* arena); @@ -270,7 +256,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -349,6 +335,9 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i bool has_source_context() const; void clear_source_context(); static const int kSourceContextFieldNumber = 5; + private: + const ::google::protobuf::SourceContext& _internal_source_context() const; + public: const ::google::protobuf::SourceContext& source_context() const; ::google::protobuf::SourceContext* release_source_context(); ::google::protobuf::SourceContext* mutable_source_context(); @@ -376,9 +365,8 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::SourceContext* source_context_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsTypeImpl(); }; // ------------------------------------------------------------------- @@ -408,10 +396,10 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -422,7 +410,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ return reinterpret_cast( &_Field_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 1; void UnsafeArenaSwap(Field* other); @@ -433,32 +421,33 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ // implements Message ---------------------------------------------- - inline Field* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Field* New() const final { + return CreateMaybeMessage(NULL); } - Field* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Field* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Field& from); void MergeFrom(const Field& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Field* other); protected: explicit Field(::google::protobuf::Arena* arena); @@ -474,7 +463,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -721,9 +710,8 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_ ::google::protobuf::int32 number_; ::google::protobuf::int32 oneof_index_; bool packed_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsFieldImpl(); }; // ------------------------------------------------------------------- @@ -753,10 +741,10 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -767,7 +755,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i return reinterpret_cast( &_Enum_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 2; void UnsafeArenaSwap(Enum* other); @@ -778,32 +766,33 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i // implements Message ---------------------------------------------- - inline Enum* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline Enum* New() const final { + return CreateMaybeMessage(NULL); } - Enum* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + Enum* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const Enum& from); void MergeFrom(const Enum& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(Enum* other); protected: explicit Enum(::google::protobuf::Arena* arena); @@ -819,7 +808,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -876,6 +865,9 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i bool has_source_context() const; void clear_source_context(); static const int kSourceContextFieldNumber = 4; + private: + const ::google::protobuf::SourceContext& _internal_source_context() const; + public: const ::google::protobuf::SourceContext& source_context() const; ::google::protobuf::SourceContext* release_source_context(); ::google::protobuf::SourceContext* mutable_source_context(); @@ -902,9 +894,8 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::SourceContext* source_context_; int syntax_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumImpl(); }; // ------------------------------------------------------------------- @@ -934,10 +925,10 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -948,7 +939,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro return reinterpret_cast( &_EnumValue_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 3; void UnsafeArenaSwap(EnumValue* other); @@ -959,32 +950,33 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro // implements Message ---------------------------------------------- - inline EnumValue* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(NULL); + inline EnumValue* New() const final { + return CreateMaybeMessage(NULL); } - EnumValue* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage(arena); + EnumValue* New(::google::protobuf::Arena* arena) const final { + return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; - void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; + void CopyFrom(const ::google::protobuf::Message& from) final; + void MergeFrom(const ::google::protobuf::Message& from) final; void CopyFrom(const EnumValue& from); void MergeFrom(const EnumValue& from); - void Clear() PROTOBUF_FINAL; - bool IsInitialized() const PROTOBUF_FINAL; + void Clear() final; + bool IsInitialized() const final; - size_t ByteSizeLong() const PROTOBUF_FINAL; + size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; + ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; + ::google::protobuf::io::CodedOutputStream* output) const final; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; - int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } + bool deterministic, ::google::protobuf::uint8* target) const final; + int GetCachedSize() const final { return _cached_size_.Get(); } + private: void SharedCtor(); void SharedDtor(); - void SetCachedSize(int size) const PROTOBUF_FINAL; + void SetCachedSize(int size) const final; void InternalSwap(EnumValue* other); protected: explicit EnumValue(::google::protobuf::Arena* arena); @@ -1000,7 +992,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro } public: - ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; + ::google::protobuf::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- @@ -1057,9 +1049,8 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_; ::google::protobuf::internal::ArenaStringPtr name_; ::google::protobuf::int32 number_; - mutable int _cached_size_; + mutable ::google::protobuf::internal::CachedSize _cached_size_; friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct; - friend void ::protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsEnumValueImpl(); }; // ------------------------------------------------------------------- @@ -1089,10 +1080,10 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc return *this; } #endif - inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL { + inline ::google::protobuf::Arena* GetArena() const final { return GetArenaNoVirtual(); } - inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL { + inline void* GetMaybeArenaPointer() const final { return MaybeArenaPtr(); } static const ::google::protobuf::Descriptor* descriptor(); @@ -1103,7 +1094,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc return reinterpret_cast( &_Option_default_instance_); } - static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = + static constexpr int kIndexInFileMessages = 4; void UnsafeArenaSwap(Option* other); @@ -1114,32 +1105,33 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc // implements Message ---------------------------------------------- - inline Option* New() const PROTOBUF_FINAL { - return ::google::protobuf::Arena::CreateMessage